text
stringlengths
184
4.48M
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LoginComponent } from './components/login/login.component'; const routes: Routes = [ { path: 'admin', loadChildren: './components/admin/admin.module#AdminModule' }, { path: 'agent', loadChildren: './components/agent/agent.module#AgentModule' }, { path: '', component: LoginComponent }, { path: '**', redirectTo: '' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Help on module codepad: NAME codepad FUNCTIONS call(c) Execute an ANSI escape code clear() Clear the screen. color(x) Set the foreground text color (FG) or the cell background color (BG). Parameters are added together. Ex: color(fg+red+brite) color(bg+blue) color(reset) `brite` serves to expose a lighter version of the original palette, allowing for 16 colors total. In general the following sums are acceptable: SCOLOR+MODE+brite COLOR+MODE reset where COLOR is black, red, green, yellow, blue, magenta, cyan, white, or reset SCOLOR stands for Strict Color, it is the same as COLOR except it excludes reset MODE is either fg or bg As a special case reset can be called without a MODE, in which case it will reset both the fg and the bg. And of course reset cannot be brightened. cursor(x, y, delta=False) nl() Reset color and write newline. pix(x, y, c) Shorthand for cursor(x,y); color(bg+c); write(" ") place(x, y, s) Puts a string on screen with some special features. (1) Parts of the string that go past the screen boundary are clipped (2) Newlines stay on the same column without overwritting preceeding content (3) Character \0 can be used as a transparent value ploop() Place this in the condition of the main loop. Ex: while ploop(): write("Prompt value: " + promptValue + " " + frameNumber + "\n:") It will provide one prompt per frame and leave the collected input in a variable called promptValue. prompt() Get the prompt input that came before this frame. size() write(c) Write character to cursor location DATA bg = 40 black = 0 blue = 4 brite = 60 cyan = 6 fg = 30 frameNumber = 0 green = 2 magenta = 5 promptValue = '' red = 1 reset = 8 white = 7 yellow = 3 FILE /Users/samie/playground/codepad/codepad.py
<div class="cart_session__field"> <div class="cart_session__container"> <div class="breadcrumbz"> <div class="d-flex"> <div class="breadcrumbz__item"> <a href="/" class="breadcrumbz__link">Home</a> </div> <span>/</span> <div class="breadcrumbz__item breadcrumbz__item-active"> Cart Session </div> </div> </div> </div> <div class="cart_session__container row"> <div class="col-lg-7 col-md-12 pb-2"> <div class="cart_session__title d-flex mb-3"> <div class="col-4 item-title">Product</div> <div class="col-2 item-title">Price</div> <div class="col-2 item-title">Quantity</div> <div class="col-2 item-title">Total</div> <div class="col-2 item-title">Remove</div> </div> <% @cart_session.cart_items.each do |cart_item| %> <div class="cart_session__row d-flex mb-3"> <div class="col-4 cart-items_col"> <%= link_to cart_item.product, class: "d-flex" do %> <div class="col-3"> <div class=""> <%= image_tag cart_item.product.product_images[2].image.url, class: "img-fluid" %> </div> </div> <div class="col-9"> <div class="cart-items__info"> <div class="cart-items__name"> <%= cart_item.product.name %> </div> <div class="cart-items__size"> <%= cart_item.size %> </div> </div> </div> <% end %> </div> <div class="col-2 cart-items_col"> <div class="cart-items__price"> $<%= cart_item.product.current_price %> </div> </div> <div class="col-2 cart-items_col"> <div class="cart-items__quantity"> <%= form_for cart_item, url: update_quantity_path do |form| %> <%= form.hidden_field :current_id, value: cart_item.id %> <div class="d-flex justify-content-center"> <input type="button" value="-" class="btn_quantity_1"> <%= form.text_field :quantity, value: cart_item.quantity, class: "btn_quantity_2" %> <input type="button" value="+" class="btn_quantity_3"> </div> <%= form.submit "Update", class: "btn btn-info cart_session__btn mt-2" %> <% end %> </div> </div> <div class="col-2 cart-items_col"> <div class="cart-items__price"> $<%= cart_item.product.current_price * cart_item.quantity %> </div> </div> <div class="col-2 cart-items_col"> <%= button_to "x", cart_item, method: :delete, class: "btn btn-danger cart_session__btn" %> </div> </div> <% end %> </div> <div class="col-lg-5 col-md-12"> <%= form_with(url: submit_voucher_path, method: :post) do |form| %> <div class="d-flex align-items-center cart_session__voucher"> <%= form.number_field :code, class: "cart_session__voucher_code", placeholder: "Voucher Code" %> <%# <input class="cart_session__voucher_code" placeholder="Voucher Code"> %> <%= form.submit "Apply", class: "cart_session__voucher_btn" %> <%#= button_to "Apply", submit_voucher_path, method: :post, class: "cart_session__voucher_btn" %> </div> <% end %> <div class="cart_session__heading mb-2"> CART SUMMARY </div> <div class="cart_session__row p-4"> <div class="border-bottom"> <div class="d-flex justify-content-between align-item-center mb-3"> <h6>Subtotal</h6> <h6> $<%= @cart_session.sum_money %> </h6> </div> <div class="d-flex justify-content-between align-item-center mb-2 "> <h6>Ship</h6> <% if @cart_session.sum_money >= 50 %> <h6> $0 </h6> <% else %> <h6> $4.0 </h6> <% end %> </div> </div> <% if @cart_session.discount > 0 %> <div class="border-bottom pt-3"> <div class="d-flex justify-content-between align-item-center mb-3"> <h6>Discount</h6> <h6> -$<%= @cart_session.sum_money * @cart_session.discount / 100 %> </h6> </div> </div> <% end %> <div class="pt-3"> <div class="d-flex justify-content-between align-item-center mb-3 fw-bold"> <h5>Total</h5> <% if @cart_session.total_final > 50 %> <h5> $<%= @cart_session.total_final + 0 %> </h5> <% else %> <h5> $<%= @cart_session.total_final + 4 %> </h5> <% end %> </div> <%= button_to "Proceed To Checkout", orderz_path, method: :post, class: "btn btn-primary w-100" %> </div> </div> </div> </div> </div> <%= javascript_importmap_tags("custom/change_quantity") %>
const express = require('express'); const dotenv = require('dotenv').config(); const axios = require('axios'); const julep = require("@julep/sdk"); const port = process.env.PORT; const MY_TOKEN = process.env.MY_TOKEN; const BASE_URL = `https://api.telegram.org/bot${MY_TOKEN}`; //julep ai api const THIRD_PARTY_API_KEY = process.env.THIRD_PARTY_API_KEY; const client = new julep.Client({ apiKey: THIRD_PARTY_API_KEY }); // console.log(THIRD_PARTY_API_KEY); // Controlling our request from Telegram using Axios and making API calls function getAxiosInstance() { return { get(method, params) { return axios.get(`/${method}`, { baseURL: BASE_URL, params, }); }, post(method, data) { return axios({ method: 'post', baseURL: BASE_URL, url: `/${method}`, data, }); }, }; } // Communicating with the Telegram bot function sendMessage(messageObj, messageText) { const axiosInstance = getAxiosInstance(); return axiosInstance.post('sendMessage', { chat_id: messageObj.chat.id, text: messageText, }); } messages = [ { "role": "system", "name": "situation", "content": "Sara is a opinionated sex therapist & educator. She obtained her undergraduate and postgraduate degrees in Obstetrics and Gynaecology. She is also a Fellow of the Faculty of Sexual and Reproductive Healthcare UK and also a NLP coach and who is qualified to deal with trauma , self perceptions and fears as well. \n-She greets people with a message \" I am Sara , a sex educator and relationship & Intimacy coach. Thank you for reaching out , how can I help you today?\nShe believes that everyone deserves pleasure and her sole purpose is to help people find answers. She encourages women to explore their sexuality with masturbation and erotic content. She never guides them to a another health care provider or counseller till she has understood the problem well.\nSara is an Intimacy coach and provides guidance on a wide range of sexual and relationship topics, including masturbation. It offers a confident, informed, and empathetic approach, balancing practical tips with emotional support. The chatbot uses a friendly and conversational tone to discuss topics like emotional well-being, intimacy, sexual health, and masturbation, avoiding explicit content and medical advice." }, { "role": "user", "name": "Megha", "content": "Hi" }, { "role": "assistant", "name": "Sara", "content": "Hello! I'm here to help. How can I assist you today?" }, { "role": "user", "name": "Megha", "content": "Hi" }, { "role": "assistant", "name": "Sara", "content": "Hello! I'm here to help. How can I assist you today?" }, { "role": "system", "name": "thought", "content": "Q: Is this how she greets people ?\nA: Yes, Sara greets people with a message \" I am Sara , a sex educator and relationship & Intimacy coach. Thank you for reaching out , how can I help you today?\n\nPlease use this format to greet ." }, { "role": "user", "name": "Megha", "content": "Hi" }, { "role": "assistant", "name": "Sara", "content": "Hello! I'm here to help. How can I assist you today?" }, { "role": "assistant", "name": "Sara", "content": "Hello! I'm here to help. How can I assist you today?" }, { "role": "user", "name": "Megha", "content": "" } ] async function handleMessage(messageObj) { const messageText = messageObj.text.toLowerCase(); const chatId = messageObj.chat.id; console.log(messageObj); // Check if the message is "hi" or "hello" if (messageText === 'hi' || messageText === 'hello') { const welcomeMessage = "Hi, I am Sara, your dedicated relationship and intimacy coach. Welcome to ATOG, where our mission is to empower women to explore and understand their sexuality. Would you like to ask questions or listen to audio stories?\n\n→ Type 1 to Listen Audio Stories\n\n→ Type AMA to ask questions"; await sendMessage(messageObj, welcomeMessage); } else if (messageText === '1') { // Respond with a list of audio links const audioLinks = [ "1. www.atog.in/playlist1", "2. www.atog.in/playlist1", "3. www.atog.in/playlist1" ].join("\n"); await sendMessage(messageObj, audioLinks); } else if (messageText === 'ama') { // getting the response from julep ai // const aiResponse = await client.chat.completions.create({ // model: "julep-ai/samantha-1-turbo", // messages: [messageObj], // temperature: 0.7, // max_tokens: 300, // top_p: 1, // }); // const aiMessage = aiResponse.choices[0].message.content; // // sending the msg from julep to chat bot // await sendMessage(chatId, aiMessage); } else { // For any other message, respond with a default message await sendMessage(messageObj, 'Oops! I did not understand that. Please type "hi" or "hello" to start.'); } } // Handling all the inputs appropriately async function handler(req, method) { const { body } = req; if (body) { console.log(body); const messageObj = body.message; await handleMessage(messageObj); } return; } const app = express(); app.use(express.json()); app.post('*', async (req, res) => { console.log(req.body); res.status(200).send(await handler(req)); }); app.get('*', async (req, res) => { res.status(200).send(await handler(req)); }); app.listen(port, () => { console.log('Server is live at', port); }); //chat gpt code // const express = require("express"); // const bodyParser = require('body-parser'); // const { Telegraf } = require("telegraf"); // const axios = require("axios"); // const julep = require("@julep/sdk"); // const app = express(); // const port = process.env.PORT || 3000; // // Use bodyParser middleware to parse JSON bodies // app.use(bodyParser.json()); // // Initialize Telegraf bot // const MY_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"; // const bot = new Telegraf(MY_TOKEN); // // Initialize Julep client // const THIRD_PARTY_API_KEY = process.env.THIRD_PARTY_API_KEY; // const client = new julep.Client({ apiKey: THIRD_PARTY_API_KEY }); // // Function to chat with Maya using Julep API // async function chatWithMaya(messages) { // try { // if (messages.length > 0) { // const chatCompletion = await client.chat.completions.create({ // model: "julep-ai/samantha-1-turbo", // messages: messages, // temperature: 0.7, // max_tokens: 300, // top_p: 1, // frequency_penalty: 0.5, // presence_penalty: 0.5, // stop: ["<", "<|"], // }); // return chatCompletion.choices[0].message.content; // } else { // return "I'm sorry, I can only assist with your queries."; // } // } catch (error) { // console.error("Error:", error); // return "An error occurred while processing your request."; // } // } // // Handle messages from Telegram // app.post(`/bot${MY_TOKEN}`, async(req, res) => { // const { message } = req.body; // if (message && message.text) { // // Simplified handling for basic commands and messages // const chatId = message.chat.id; // const text = message.text; // try { // // Handling basic greetings // if ( // text.toLowerCase() === "hi" || // text.toLowerCase() === "hello" || // text.toLowerCase() === "hey" || // text.toLowerCase() === "hy" // ) { // const welcomeMessage = // "Hi, I am Sara, your dedicated relationship and intimacy coach. Welcome to ATOG, where our mission is to empower women to explore and understand their sexuality. Would you like to ask questions or listen to audio stories?\n\n→ Type 1 to Listen Audio Stories\n\n→ Type AMA to ask questions"; // bot.telegram.sendMessage(chatId, welcomeMessage); // } else if (text.toLowerCase() === "1") { // const audioStories = [ // "Audio Story 1: [Link to audio]", // "Audio Story 2: [Link to audio]", // "Audio Story 3: [Link to audio]" // ]; // const playlistMessage = "Here are some audio stories for you:\n\n"; // const formattedAudioStories = audioStories.map( // (story, index) => `${index + 1}. ${story}` // ); // bot.telegram.sendMessage( // chatId, // playlistMessage + formattedAudioStories.join("\n") // ); // } else if (text.toLowerCase() === "ama") { // const amaMessage = // "Feel free to ask me anything related to relationships, intimacy, or sexual wellbeing."; // bot.telegram.sendMessage(chatId, amaMessage); // } else { // // Directly handling any message without filtering for specific keywords // const response = await chatWithMaya([{ role: "user", name: "User", content: text }]); // bot.telegram.sendMessage(chatId, response); // } // } catch (error) { // console.error("Error:", error); // bot.telegram.sendMessage(chatId, "An error occurred while processing your request."); // } // } // // Respond to the webhook request // res.status(200).send("OK"); // }); // // Start the Express server // app.listen(port, () => { // console.log(`Telegram bot server listening at http://localhost:${port}`); // }); // // Set the webhook // bot.telegram.setWebhook(`https://telegrambot-1-9ifb.onrender.com/bot${MY_TOKEN}`);
pub use part_1::solution as part_1; pub use part_2::solution as part_2; pub use part_2::solution_mathematical as part_2_mathematical; pub const INPUT: &str = include_str!("../input"); mod part_1 { pub fn solution(input: &str) -> u32 { let mut lines = input.lines(); let times = lines .next() .unwrap() .split_once(":") .unwrap() .1 .split_whitespace() .map(|x| x.parse::<u32>().unwrap()); let distances = lines .next() .unwrap() .split_once(":") .unwrap() .1 .split_whitespace() .map(|x| x.parse::<u32>().unwrap()); let mut results: Vec<u32> = vec![]; for (time, distance) in times.zip(distances) { let mut count: u32 = 0; for t in 0..=time { if t * (time - t) >= distance { count += 1; } } results.push(count); } return results.iter().product(); } } mod part_2 { pub fn solution(input: &str) -> u64 { let mut lines = input.lines(); let time = lines .next() .unwrap() .split_once(":") .unwrap() .1 .split_whitespace() .collect::<String>() .parse::<u64>() .unwrap(); let distance = lines .next() .unwrap() .split_once(":") .unwrap() .1 .split_whitespace() .collect::<String>() .parse::<u64>() .unwrap(); let mut lower: u64 = 0; for t in 0..=time { if t * (time - t) >= distance { lower = t; break; } } let mut upper: u64 = 0; for t in (0..=time).into_iter().rev() { if t * (time - t) >= distance { upper = t; break; } } return upper - lower + 1; } fn quadratic_formula(a: f64, b: f64, c: f64) -> (f64, f64) { let t = ((-1 as f64 * b) + ((b * b) - 4 as f64 * a * c).sqrt()) / 2 as f64 * a; let x = ((-1 as f64 * b) - ((b * b) - 4 as f64 * a * c).sqrt()) / 2 as f64 * a; return (t, x); } pub fn solution_mathematical(input: &str) -> u64 { let mut lines = input.lines(); let time = lines .next() .unwrap() .split_once(":") .unwrap() .1 .split_whitespace() .collect::<String>() .parse::<f64>() .unwrap(); let distance = lines .next() .unwrap() .split_once(":") .unwrap() .1 .split_whitespace() .collect::<String>() .parse::<f64>() .unwrap(); let (lower, upper) = quadratic_formula(-1_f64, time, distance * -1_f64); return (upper - lower) as u64 + 1; } }
import 'package:flutter/material.dart'; import 'LoginPage.dart'; // Import your LoginPage file import 'RegistrationPage.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'CampusNav', theme: ThemeData( primarySwatch: Colors.blue, ), home: StartPage(), ); } } class StartPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('CampusNav'), ), backgroundColor: Color(0xFF104271), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox(height: 30), Text( 'Welcome to', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white, ), ), Text( 'CampusNav!', style: TextStyle( fontSize: 40, fontWeight: FontWeight.bold, color: Colors.black, ), ), SizedBox(height: 20), Stack( alignment: Alignment.center, children: [ Image.asset( 'assets/images/Grey Orange Triangle Modern Bus For Sale Instagram Story.png', height: 400, width: 300, ), Positioned( top: 10, child: Text( 'Track your point with CampusNav!', style: TextStyle( fontSize: 18, fontStyle: FontStyle.italic, color: Colors.white, ), textAlign: TextAlign.center, ), ), ], ), ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => LoginPage()), ); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { return states.contains(MaterialState.hovered) ? Colors.black : Colors.blue; }, ), ), child: Text('Track Your Point'), ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'New user? ', style: TextStyle(fontSize: 16, color: Colors.white), ), TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => RegistrationPage()), ); }, child: Text( 'Sign up', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.blue, ), ), ), ], ), ], ), ), ); } }
import { getAdditionalUserInfo, signInWithCustomToken, UserCredential, } from 'firebase/auth'; import { httpsCallable } from 'firebase/functions'; import { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { auth, functions } from '@/firebase'; import { connectors, useWallet } from '@/hooks/useWallet'; const CONNECTOR_LOCAL_STORAGE_KEY = 'WEB3_CONNECT_CACHED_PROVIDER'; const toHex = (v: string) => v .split('') .map((c) => c.charCodeAt(0).toString(16).padStart(2, '0')) .join(''); export const useAuth = (firstAuthFlow?: (cred: UserCredential) => void) => { const { account, activate, active, deactivate, library } = useWallet(); const [needAuth, setNeedAuth] = useState(false); const [userCred, setUserCred] = useState<UserCredential>(); const navigate = useNavigate(); useEffect(() => { if (!needAuth || !account || !active || !library) return; authentication().catch(() => { deactivate(); }); }, [needAuth, account, active, library]); const authentication = async () => { if (!account || !active || !library) { throw Error('Wallet is not connected.'); } setNeedAuth(false); const { data: nonceData } = await httpsCallable< { address: string }, { nonce: string } >( functions, 'getNonceToSign' )({ address: account }).catch((e) => { throw Error(`Failed to fetch nonce. Reason: ${e.message}`); }); // Sign to nonce const signature = await library.send('personal_sign', [ `0x${toHex(nonceData.nonce)}`, account, ]); // Verify signature const { data: verifyData } = await httpsCallable< { address: string; signature: string; }, { token: string } >( functions, 'verifySignedMessage' )({ address: account, signature }).catch((e) => { throw Error(`Failed to verify signature. Reason: ${e.message}`); }); // Sign in with custom token const cred = await signInWithCustomToken(auth, verifyData.token); setUserCred(cred); return cred; }; useEffect(() => { if (!userCred) return; const isNewUser = getAdditionalUserInfo(userCred); if (!isNewUser) return; if (!firstAuthFlow) { firstAuthFlow = () => navigate('/mypage', { state: { isOk: true } }); } return firstAuthFlow(userCred); }, [userCred]); const signIn = async (connector: keyof typeof connectors) => { await activate(connector, undefined, true); setNeedAuth(true); }; const signOut = async () => { deactivate(); await auth.signOut(); }; const getConnector = () => { const item = localStorage.getItem(CONNECTOR_LOCAL_STORAGE_KEY); if (item) { return item.replace(/"/g, '') as keyof typeof connectors; } return null; }; return { authentication, getConnector, processing: needAuth, signIn, signOut, }; };
package com.gerenciarfuncionarios.controller; import com.gerenciarfuncionarios.common.Mensagem; import com.gerenciarfuncionarios.dto.AtualizarFuncionarioDto; import com.gerenciarfuncionarios.dto.CriarFuncionarioDto; import com.gerenciarfuncionarios.dto.FuncionarioDto; import com.gerenciarfuncionarios.dto.ResultadoDto; import com.gerenciarfuncionarios.mapper.FuncionarioMapper; import com.gerenciarfuncionarios.model.Funcionario; import com.gerenciarfuncionarios.model.Gerente; import com.gerenciarfuncionarios.service.ColaboradorService; import jakarta.validation.Valid; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/funcionarios") public class FuncionarioController { private final ColaboradorService<Funcionario> funcionarioService; private final ColaboradorService<Gerente> gerenteService; @Autowired public FuncionarioController(final ColaboradorService<Funcionario> funcionarioService, final ColaboradorService<Gerente> gerenteService) { this.funcionarioService = funcionarioService; this.gerenteService = gerenteService; } @GetMapping( produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<?> listarFuncionarios() { List<Funcionario> funcionarios = funcionarioService.listar(); List<FuncionarioDto> funcionarioDtos = FuncionarioMapper.entidadeParaDto(funcionarios); return ResponseEntity.ok(funcionarioDtos); } @PostMapping( consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<?> criarFuncionario(@Valid @RequestBody CriarFuncionarioDto criarFuncionarioDto) { Gerente gerente = null; if (criarFuncionarioDto.getGerenteId() != null) { gerente = gerenteService.buscar(criarFuncionarioDto.getGerenteId()); } final Funcionario funcionario = Funcionario.criar( criarFuncionarioDto.getNome(), criarFuncionarioDto.getCpf(), criarFuncionarioDto.getRg(), criarFuncionarioDto.getDataNascimento(), criarFuncionarioDto.getSalario(), gerente ); final Funcionario funcionarioSalvo = funcionarioService.criar(funcionario); final FuncionarioDto funcionarioDto = FuncionarioMapper.entidadeParaDto(funcionarioSalvo); return ResponseEntity.ok( funcionarioDto ); } @PutMapping( value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<?> atualizar(@PathVariable Long id, @RequestBody AtualizarFuncionarioDto funcionarioDto) { final Gerente gerente = funcionarioDto.getGerenteId() == null ? null : gerenteService.buscar(funcionarioDto.getGerenteId()); final Funcionario funcionario = Funcionario.criar( funcionarioDto.getNome(), funcionarioDto.getCpf(), funcionarioDto.getRg(), funcionarioDto.getDataNascimento(), funcionarioDto.getSalario(), gerente ); final Funcionario funcionarioAtualizado = this.funcionarioService.atualizar(funcionario, id); final FuncionarioDto novoFuncionarioDto = FuncionarioMapper.entidadeParaDto(funcionarioAtualizado); return ResponseEntity.ok(novoFuncionarioDto); } @DeleteMapping("/{id}") public ResponseEntity<?> deletar(@PathVariable Long id) { this.funcionarioService.deletar(id); final String msgRetorno = String.format(Mensagem.COLABORADOR_REMOVIDO_COM_SUCESSO, id); return ResponseEntity.status(HttpStatus.ACCEPTED).body(new ResultadoDto(msgRetorno)); } }
package com.joshfullstack.customer; import jakarta.persistence.*; import java.util.Objects; @Entity @Table( name = "customer", uniqueConstraints = { @UniqueConstraint( name = "customer_email_unique", columnNames = "email" ) } ) public class Customer { @Id @SequenceGenerator( name = "customer_id_seq", sequenceName = "customer_id_seq", allocationSize = 1 ) @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "customer_id_seq" ) private Integer id; private String name; @Column(nullable = false) private String email; private Integer age; public Customer(int id, String name, String email, Integer age) { this.name = name; this.id = id; this.email = email; this.age = age; } public Customer(String name, String email, Integer age) { this.name = name; this.email = email; this.age = age; } public Customer() { this.name = "dummy"; this.id = 0; this.email = "email"; this.age = 0; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer customer = (Customer) o; return Objects.equals(name, customer.name) && Objects.equals(id, customer.id) && Objects.equals(email, customer.email) && Objects.equals(age, customer.age); } @Override public int hashCode() { return Objects.hash(name, id, email, age); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", id=" + id + ", email='" + email + '\'' + ", age=" + age + '}'; } }
Use market_db; -- Type of Index CREATE TABLE table1 ( col1 INT PRIMARY KEY, col2 INT, col3 INT ); SHOW INDEX FROM table1; CREATE TABLE table2 ( col1 INT PRIMARY KEY, col2 INT UNIQUE, col3 INT UNIQUE ); SHOW INDEX FROM table2; -- Feature of Indexes USE market_db; DROP TABLE IF EXISTS buy, member; CREATE TABLE member ( mem_id CHAR(8), mem_name VARCHAR(10), mem_number INT, addr CHAR(2) ); INSERT INTO member VALUES ('TWC', '트와이스', 9, '서울'), ('BLK', '블랙핑크', 4, '경남'), ('WMN', '여자친구', 6, '경기'), ('OMY', '오마이걸', 7, '서울'); SELECT * FROM member; ALTER TABLE member ADD CONSTRAINT PRIMARY KEY(mem_id); SELECT * FROM member; ALTER TABLE member DROP PRIMARY KEY; ALTER TABLE member ADD CONSTRAINT PRIMARY KEY(mem_name); SELECT * FROM member; INSERT INTO member VALUES ('GRL', '소녀시대', 8, '서울'); SELECT * FROM member; DROP TABLE IF EXISTS member; CREATE TABLE member ( mem_id CHAR(8), mem_name VARCHAR(10), mem_number INT, addr CHAR(2) ); INSERT INTO member VALUES ('TWC', '트와이스', 9, '서울'), ('BLK', '블랙핑크', 4, '경남'), ('WMN', '여자친구', 6, '경기'), ('OMY', '오마이걸', 7, '서울'); SELECT * FROM member; ALTER TABLE member ADD CONSTRAINT UNIQUE(mem_id); SELECT * FROM member; ALTER TABLE member ADD CONSTRAINT UNIQUE(mem_name); SELECT * FROM member; INSERT INTO member VALUES ('GRL', '소녀시대', 8, '서울'); SELECT * FROM member;
class TasksController < ApplicationController skip_before_action :is_logged_in?, only: [:new, :create] before_action :current_user_is_the_owner, only: [:edit, :update, :destroy] # GET /tasks def index #@tasks = Task.all #if logged_in? @tasks = current_user.tasks #else # redirect_to login_path #end end # GET /tasks/1 def show @task = Task.find params[:id] end # GET /tasks/new def new @task = Task.new end # GET /tasks/1/edit def edit #@task = Task.find params[:id] if @task.user_id = @user_id end end # POST /tasks def create @task = Task.new task_params respond_to do |format| if @task.save format.html { redirect_to @task, notice: 'Task was successfully created.' } else format.html { render :new } end end end # PATCH/PUT /tasks/1 def update #@task = Task.find(params[:id]) respond_to do |format| if @task.update(task_params) format.html { redirect_to @task, notice: 'Task was successfully updated.' } else format.html { render :edit } end end end # DELETE /tasks/1 def destroy #@task = Task.find(params[:id]) @task.destroy respond_to do |format| format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' } end end private # Never trust parameters from the scary internet, only allow the white list through. def task_params params.require(:task).permit(:name, :due_date, :completed, :user_id) end def current_user_is_the_owner @task = Task.find params[:id] unless current_user.id == @task.user_id redirect_to tasks_path, notice: 'Access forbidden.' end end end
import { z } from "zod"; import { userRole } from "./user.constants"; const createUserZodValidation = z.object({ body: z.object({ phoneNumber: z.string({ required_error: 'Contact number is required', }).min(11, "phone number is too short").max(11, "phone number is too long"), role: z.enum([...userRole] as [string, ...string[]], { required_error: 'user role is required', }), password: z.string({ }).min(6, "password is too short").max(50, "password is too long"), name: z.object({ firstName: z.string({ required_error: 'First name is required', }).min(3, "Name is too short").max(32, "Name is too long"), lastName: z.string().optional() }), address: z.string({ required_error: 'Address is required', }), budget: z.number({}).default(0), income: z.number({}).default(0), }), }); const updateUserZodValidation = z.object({ body: z.object({ // phoneNumber: z.string({ // required_error: 'Contact number is required', // }).min(11, "phone number is too short").max(11, "phone number is too long"), role: z.enum([...userRole] as [string, ...string[]], {}).optional(), name: z.object({ firstName: z.string({ required_error: 'First name is required', }).min(3, "Name is too short").max(32, "Name is too long").optional(), lastName: z.string().optional() }).optional(), address: z.string({}).optional(), budget: z.number({}).optional(), income: z.number({}).optional(), }), }); const updatePasswordZodSchema = z.object({ body: z.object({ OldPassword: z.string({ required_error: 'OldPassword is required', }).min(6, "old password is too short").max(50, "old password is too long"), newPassword: z.string({ required_error: 'newPassword is required', }).min(6, "new password is too short").max(50, "new password is too long"), }), }); export const UserValidation = { createUserZodValidation, updateUserZodValidation, updatePasswordZodSchema };
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Home - Data Store Application</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #e3f2fd;"> <a class="navbar-brand mb-0 h1" href="#"> <img th:src="@{/images/AK.png}" width="30" height="35" class="d-inline-block align-top" alt=""> STORE </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span> </a></li> <!-- <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> --> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <div class="text-center" style="position: fixed; top: 50%; left: 45%; right: 45%;"> <button type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#exampleModal1" data-whatever="LOGIN">SIGN IN</button> </div> <div class="text-center" style="position: fixed; top: 60%; left: 45%; right: 45%"> <button type="button" class="btn btn-warning btn-lg" data-toggle="modal" data-target="#exampleModal" data-whatever="REGISTER">SIGN UP</button> </div> <!-- ----------------------------LOGIN MODAL START------------------------------------- --> <div class="modal fade" id="exampleModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">LOGIN</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="#"> <div class="form-group"> <label for="recipient-name" class="col-form-label">Email-ID:</label> <input type="email" class="form-control" id="email" placeholder="Enter your email-id"> </div> <div class="form-group"> <label for="recipient-name" class="col-form-label">Password:</label> <input type="password" class="form-control" id="password" placeholder="Enter your password"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary" id="submit">Submit</button> </div> </div> </div> </div> <!-- ----------------------------LOGIN MODAL END------------------------------------- --> <!-- ----------------------------REGISTER MODAL START------------------------------------- --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">REGISTER</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="#"> <div class="form-group"> <label for="recipient-name" class="col-form-label">Username:</label> <input type="text" class="form-control" id="recipient-name" placeholder="Enter your name"> </div> <div class="form-group"> <label for="recipient-name" class="col-form-label">Email-ID:</label> <input type="email" class="form-control" id="recipient-name" placeholder="Enter your email-id"> </div> <div class="form-group"> <label for="recipient-name" class="col-form-label">Password:</label> <input type="password" class="form-control" id="recipient-name" placeholder="Enter your password"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Create an account</button> </div> </div> </div> </div> <!-- ----------------------------REGISTER MODAL END------------------------------------- --> </body> <script type="text/javascript"> $('#exampleModal1').on('show.bs.modal', function(event) { var button = $(event.relatedTarget) // Button that triggered the modal var recipient = button.data('whatever') // Extract info from data-* attributes // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) modal.find('.modal-title').text(recipient) /* modal.find('.modal-body input').val(recipient) */ }) </script> <script type="text/javascript"> $("#submit").click(function() { var email = $("#email").val(); var password = $("#password").val(); if (email == '' || password == '') { swal({ title : "Fields is empty!", text : "Please enter your credentials!", icon : "warning", button : "Ok", }); }else{ swal({ title : "Successfully Submitted.", text : "Success", icon : "success", button : "Ok", }); } }) </script> </html>
from dataclasses import dataclass from flask import Blueprint, request prompt_bp = Blueprint('prompt', __name__) @dataclass class Prompt: id: int subject: str tags: list text:str author: str date: str response: str tryit_link: str category: str @prompt_bp.route('/prompts', methods=['GET']) def get_prompts() -> list: # Get the 'nextlink' query parameter nextlink = request.args.get('nextlink') if nextlink is None: nextlink = 1 response = { 'prompts': list(map(lambda prompt: prompt.__dict__, [ Prompt(1, 'Math', ['algebra', 'geometry'], 'What is 1 + 1?', 'John Doe', '2021-01-01', '2', 'https://tryit.com/1', 'question'), Prompt(2, 'Science', ['biology', 'chemistry'], 'What is the powerhouse of the cell?', 'Jane Doe', '2021-01-01', 'Mitochondria', 'https://tryit.com/2', 'question'), Prompt(3, 'English', ['literature', 'grammar'], 'What is the past tense of the verb "to be"?', 'John Doe', '2021-01-01', 'was', 'https://tryit.com/3', 'question'), Prompt(4, 'Math', ['algebra', 'geometry'], 'What is 1 + 1?', 'John Doe', '2021-01-01', '2', 'https://tryit.com/1', 'question'), Prompt(5, 'Science', ['biology', 'chemistry'], 'What is the powerhouse of the cell?', 'Jane Doe', '2021-01-01', 'Mitochondria', 'https://tryit.com/2', 'question'), Prompt(6, 'English', ['literature', 'grammar'], 'What is the past tense of the verb "to be"?', 'John Doe', '2021-01-01', 'was', 'https://tryit.com/3', 'question'), Prompt(7, 'Math', ['algebra', 'geometry'], 'What is 1 + 1?', 'John Doe', '2021-01-01', '2', 'https://tryit.com/1', 'question'), Prompt(8, 'Science', ['biology', 'chemistry'], 'What is the powerhouse of the cell?', 'Jane Doe', '2021-01-01', 'Mitochondria', 'https://tryit.com/2', 'question'), Prompt(9, 'English', ['literature', 'grammar'], 'What is the past tense of the verb "to be"?', 'John Doe', '2021-01-01', 'was', 'https://tryit.com/3', 'question'), Prompt(10, 'Math', ['algebra', 'geometry'], 'What is 1 + 1?', 'John Doe', '2021-01-01', '2', 'https://tryit.com/1', 'question')])), 'nextlink': nextlink } return response
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:task_manager/presentation/controller/add_new_task_controller.dart'; import 'package:task_manager/presentation/widgets/background_widget.dart'; import 'package:task_manager/presentation/widgets/profile_app_bar.dart'; class AddNewTaskScreen extends StatefulWidget { const AddNewTaskScreen({super.key}); @override State<AddNewTaskScreen> createState() => _AddNewTaskScreenState(); } class _AddNewTaskScreenState extends State<AddNewTaskScreen> { final TextEditingController _titleTEController = TextEditingController(); final TextEditingController _descriptionTEController = TextEditingController(); final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final AddNewTaskController _addNewTaskController = Get.find<AddNewTaskController>(); @override Widget build(BuildContext context) { return PopScope( canPop: false, onPopInvoked: (didPop) { if (didPop) { return; } Navigator.pop(context, _addNewTaskController.shouldRefreshNewTaskList); }, child: Scaffold( appBar: profileAppBar, body: BackgroundWidget( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 48), Text("Add New Task", style: Theme.of(context) .textTheme .titleLarge ?.copyWith(fontSize: 24)), const SizedBox(height: 16), TextFormField( controller: _titleTEController, decoration: const InputDecoration( hintText: "Title", ), validator: (String? value) { if (value?.trim().isEmpty ?? true) { return "Enter your title"; } return null; }, ), const SizedBox(height: 8), TextFormField( controller: _descriptionTEController, maxLines: 6, decoration: const InputDecoration( hintText: "Description", ), validator: (String? value) { if (value?.trim().isEmpty ?? true) { return "Enter your description"; } return null; }, ), const SizedBox(height: 16), SizedBox( width: double.infinity, child: GetBuilder<AddNewTaskController>( builder: (addNewTaskController) { return Visibility( visible: addNewTaskController.inProgress == false, replacement: const Center( child: CircularProgressIndicator(), ), child: ElevatedButton( onPressed: () { if (_formKey.currentState!.validate()) { _addNewTask(); } }, child: const Icon(Icons.arrow_circle_right_outlined), ), ); }, ), ), ], ), ), ), ), ), ), ); } Future<void> _addNewTask() async { final result = await _addNewTaskController.getAddNewTask( _titleTEController.text.trim(), _descriptionTEController.text.trim(), "New"); if (result) { _addNewTaskController.shouldRefreshNewTaskList == true; _titleTEController.clear(); _descriptionTEController.clear(); } } @override void dispose() { super.dispose(); _titleTEController.dispose(); _descriptionTEController.dispose(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Boostrap 4 --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Asynchronous JavaScript: From Callback Hell to Promises</title> </head> <body> <div class="container text-center"> <h1 class="display-4 text-center">Asynchronous JavaScript: From Callback Hell to Promises</h1> <p> Open <a href="https://github.com/Ch-sriram/JavaScript/blob/master/Asynchronous-JS/promise.html">promise.html</a> for the code and explaination | Images are taken from: <a href="https://www.udemy.com/the-complete-javascript-course/">JS Course by Jonas Schmedtmann</a> </p> <img src="./assets/img/promise.png" alt="JS Runtime" class="img-thumbnail mb-3"> <p><em>Check the Developer Console for Output. View Page Source for Code.</em></p> </div> <script> // Promise is an ES6 feature designed specifically to deal with Asynchronous JavaScript. // What is a Promise? // In simple terms, a Promise can be defined by the following 3 important points: // 1. Promise is an object that keeps track about whether a certain even has happened already or not. Here, // the events are asynchronous. // 2. Promise determines what happens after the event has stopped, i.e., if an event finishes, like a timer // finishing, or an AJAX request getting fulfilled, etc, in these cases, the Promise object will determine // what will happen after the event has finished its work and stopped. // 3. Promise implements the concept of a future value that we're expecting (kind of). Example: If we have an // AJAX call that says "Get me the data from the server in the background", and the Promise then promises // us that it'll get that data, so we can handle it in the future. If the Promise fails to get that data, // we have to handle that differently, and if the Promise succeeds to get the data, then we handle that // case differently. All code has to be written in a way, keeping the future in mind. // Now, since we are dealing with "Time Sensitive" now, a Promise can have different States. // Different States in a Promise: // 1. Pending: Before an event has happened, the Promise is in Pending State. // 2. Resolved/Settled: After an event has happened, the Promise is in Resolved/Settled State. // 3. Fulfilled: When a Promise in the Resolved State has successfully executed what the user wanted, then // Promise goes to Fulfilled State, which means that the result is available. // 4. Rejected: When a Promise in the Resolved State has not successfully executed what the user wanted, // i.e., an error/exception occured in the Promise, then in that case, the Promise goes to // the Rejected State. // Now, the Fulfilled and the Rejected States are important because these 2 states are to be handled by the // programmer/user. // In more practical terms, we can "Produce" and "Consume" Promises. // When we Produce a Promise, we create a new Promise and send a result using that Promise. And when we // Consume that Promise, we can use callback functions for Fulfillment and for Rejection of our Promise. // We will now use Promises to see the same example that we took in callback_hell.html. We will convert the // following code into code generated using Promises. Read the code/comments from Line #75. // function getRecipe() { // setTimeout(() => { // const recipeID = [543, 299, 195, 2234]; // console.log(recipeID); // setTimeout(id => { // const recipe = { title: 'Cheese Masala Dosa', publisher: 'Sriram' }; // console.log(`${id}: ${recipe.title}`); // setTimeout(pub => { // const recipe2 = { title: 'Paneer Masala Dosa', publisher: pub}; // console.log(recipe2); // }, 1500, recipe.publisher); // }, 1500, recipeID[3]); // }, 1500); // } // A Promise is an object, so we simply instantiate it using the 'new' keyword. The Promise's contructor // takes in a callback function called "Executor" function. The Executor function takes in 2 parameters. // These 2 parameters are again 2 callback functions known as "resolve" and "reject", and that's because the // Executor function is used to inform the promise whether the event it is handling was successful or not, // and if the event was successful, we are going to call the resolve() function with the data generated by // the event. If the event was unsuccessful, in that case, we will call the reject() function. These 2 // functions represent the two states, "Fulfilled" & "Reject" States. // Since we are simulating the same fake recipe reader which we did using Callbacks in Asynchronous JS, we // will use that same example here also. We first need the IDs of the Recipies. For that, we will make a // Promise as follows: // const getIDs = new Promise((resolve, reject) => { // // Here, we need to make a call to an asynchronous event which is the AJAX Request to get the Recipe IDs // // from the remote web server. But here, we are simulating the situation, therefore, we can simply call // // a setTimeout() function // setTimeout(() => { // // After 1500ms, we want to return the data we got from the server. Here, since this is a simulation, // // we will just send some made up data. And the way to send the data back is based on whether this // // specific event is successful or unsuccessful. Since we simply made a setTimeout() call, this event // // will always be successful, and therefore, we call the resolve() function and pass in some fake IDs // // i.e., our fake data. // resolve([100, 200, 433, 955]); // }, 1500); // // Therefore, after 1500ms, the Promise says that the event is successfully executed and the Promise is // // resolved using the resolve() function, which will take in the fake data we sent, the recipe IDs. // }); // // Now we "Produced" our Promise inside the getIDs variable. Now it's time that we "Consume" the Promise // // we made from the getIDs variable. To Consume a Promise, we have 2 methods on all the Promise objects. // // These methods are called "then()" and "catch()" methods. All of the Promise objects inherit then() and // // catch() methods. // // The then() method allows us to add an event handler for the case, when the promise is fulfilled, which // // means that there's a result that we obtained from the asynchronous call and we have to handle it. // getIDs.then(IDs => { // // IDs is the result obtained from the successful Promise, i.e., IDs now stores whatever we passed to the // // resolve() function in the Promise above i.e., IDs points to [100, 200, 433, 955]. // console.log(IDs); // }); // // Produce the Promise // const getIDs = new Promise((resolve, reject) => { // setTimeout(() => { // resolve([100, 200, 433, 955]); // }, 1500); // }); // // Consume the Promise // getIDs.then(IDs => { // console.log(IDs); // }); // Now, in the code above, from line #117 to line #126, we assumed that the event is simply going to be // successful and that will lead the event to be in Fulfilled state, because this is a simulation. // Now, if the event is unsuccessful, i.e., the data wasn't served after the AJAX call, in that case, we have // to handle that scenario as well. Now, if the event was unsuccessful, it means that the Promise goes to // Reject state, and therefore, now the reject() function is called. // Produce the Promise // const getIDs = new Promise((resolve, reject) => { // setTimeout(() => { // // If the AJAX request was unsuccessful, we simply reject() and send in some error message or some // // kind of data. // reject("Did not get data from the server!"); // // We can send any kind of data using the reject() function. Even the fake data, but it won't make // // much sense sending them. // //reject([100, 200, 433, 955]); // }, 1500); // }); // // Consume the Promise by chaining the calls to then() and catch() as follows. // getIDs // .then(IDs => { // console.log(IDs); // }) // .catch(error => { // // error is now the string that we sent as a parameter into the reject() function, i.e., // // error -> "Did not get data from the server!" // console.log(error); // }); // If we don't use the catch() method, and if the Promise goes to Rejected state, then, we would get an error // that will be logged onto the console that says: "Uncaught (in promise) > [Parameter sent to reject()]" // const getIDs = new Promise((resolve, reject) => { // setTimeout(() => { // resolve([100, 200, 433, 955]); // }, 1500); // }); // // We have the recipe IDs, and now, we get a recipe as we did in line #60 - #62 // // What we will do is that, we will create a function which receives the Recipe IDs which will then return // // a Promise // const getRecipe = recipeID => { // return new Promise((resolve, reject) => { // // Here, we will do the same as we did in line #60 to #62 // setTimeout(ID => { // const recipe = { title: 'Cheese Masala Dosa', publisher: 'Sriram' }; // // Instead of console.log(), here we just call the resolve() method - therefore we are assuming // // that this Promise is successful, since this is just a simulation. // resolve(`${ID}: ${recipe.title}`); // }, 1500, recipeID); // }); // }; // // Consume the Promise by chaining the calls to then() and catch() as follows. // getIDs // .then(IDs => { // console.log(IDs); // // Consuming the second Promise can be done as follows: // // getRecipe(IDs[2]); and then we can chain the then() and catch() here itself as follows: // // getRecipe(IDs[2]).then(()=>{...}).catch(()=>{...}); // // This would be same as the Callback Hell and we will end up with a triangular shape of asynchronous // // calls inside asynchronous calls again, which we don't want. // // Therefore, what we can do is, we can call the getRecipe() function here and get a Promise, and then // // return the Promise, which will be handled by a then() [in line #196] chained directly to this // // particular then() [in line #179], which is as follows: // return getRecipe(IDs[2]); // }) // // the then() here resolves the Promise returned by getRecipe() function. The Promise if run successfully, // // (which it will, because this is a simulation), will go to the Fulfilled state and call resolve on the data // // which is a template string of ID and Title of the Recipe, which is then handled by the then() below, // // chained to the the previous then() [in line #179] which returns the Promise. // .then(recipe => { // console.log(recipe); // }) // .catch(error => { // console.log(error); // }); // // getRecipe() is made a function because the Promise that's returned by the getRecipe() needs the recipeID // // data, which is passed to the getRecipe() in the then() of the getIDs' Promise, therefore, the Promise // // returned by the getRecipe() function actually needs the recipeID returned at the handler of getIDs' // // Promise, so that the callback chain (not as callback hell, but in Promise style) is maintained. // Now, we finally demonstrate the full callback hell as mentioned in line #55 using Promises // Produce the Promise(s) const getIDs = new Promise((resolve, reject) => { setTimeout(() => { resolve([100, 200, 433, 955]); }, 1500); }); const getRecipe = recipeID => { return new Promise((resolve, reject) => { setTimeout(ID => { const recipe = { title: 'Cheese Masala Dosa', publisher: 'Sriram' }; resolve([ID, recipe]); }, 1500, recipeID); }); }; const getRelated = publisher => { return new Promise((resolve, reject) => { setTimeout(pub => { // Assume that we got this recipe object below after an AJAX request sent to the server const recipe = { title: 'Paneer Masala Dosa', publisher: 'Sriram' }; resolve(`${pub}: ${recipe.title}`); }, 1500, publisher); }); }; // Consume the Promise(s) getIDs .then(IDs => { console.log(IDs); return getRecipe(IDs[2]); }) .then(ID_recipe => { // "Fulfilled State" Handler for Promise returned by getRecipe() function const ID = ID_recipe[0]; const recipe = ID_recipe[1]; console.log(`${ID}: ${recipe.title}`); return getRelated(recipe.publisher); }) .then(recipe => { // "Fulfilled State" Handler for Promise returned by getRelated() function console.log(recipe); }) .catch(error => { console.log(error); }); </script> </body> </html>
package club.jkxy.jumphelper; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.graphics.Point; import android.hardware.display.DisplayManager; import android.hardware.display.VirtualDisplay; import android.media.Image; import android.media.ImageReader; import android.media.projection.MediaProjection; import android.media.projection.MediaProjectionManager; import android.os.AsyncTask; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.os.AsyncTaskCompat; import android.text.TextUtils; import android.view.Display; import android.view.WindowManager; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.SoftReference; import java.nio.ByteBuffer; /** * Created by wei on 16-12-1. */ public class Shotter { private final SoftReference<Context> mRefContext; private ImageReader mImageReader; private MediaProjection mMediaProjection; private VirtualDisplay mVirtualDisplay; private String mLocalUrl = ""; private Context context; private OnShotListener mOnShotListener; public Shotter(Context context, Intent data) { this.context = context; this.mRefContext = new SoftReference<>(context); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mMediaProjection = getMediaProjectionManager().getMediaProjection(Activity.RESULT_OK, data); mImageReader = ImageReader.newInstance( getScreenWidth(), getScreenHeight(), PixelFormat.RGBA_8888,//此处必须和下面 buffer处理一致的格式 ,RGB_565在一些机器上出现兼容问题。 1); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void virtualDisplay() { mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror", getScreenWidth(), getScreenHeight(), Resources.getSystem().getDisplayMetrics().densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null); } public void startScreenShot(OnShotListener onShotListener, String loc_url) { mLocalUrl = loc_url; startScreenShot(onShotListener); } @TargetApi(Build.VERSION_CODES.KITKAT) public void startScreenShot(OnShotListener onShotListener) { mOnShotListener = onShotListener; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { virtualDisplay(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { Image image = mImageReader.acquireLatestImage(); AsyncTaskCompat.executeParallel(new SaveTask(), image); } }, 200); } } public class SaveTask extends AsyncTask<Image, Void, Bitmap> { @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected Bitmap doInBackground(Image... params) { if (params == null || params.length < 1 || params[0] == null) { return null; } Image image = params[0]; int width = image.getWidth(); int height = image.getHeight(); final Image.Plane[] planes = image.getPlanes(); final ByteBuffer buffer = planes[0].getBuffer(); //每个像素的间距 int pixelStride = planes[0].getPixelStride(); //总的间距 int rowStride = planes[0].getRowStride(); int rowPadding = rowStride - pixelStride * width; Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);//虽然这个色彩比较费内存但是 兼容性更好 bitmap.copyPixelsFromBuffer(buffer); bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height); image.close(); File fileImage = null; if (bitmap != null) { try { if (TextUtils.isEmpty(mLocalUrl)) { // mLocalUrl = getContext().getExternalFilesDir("jumphelper").getAbsoluteFile()+ "/" +SystemClock.currentThreadTimeMillis() + ".png"; // mLocalUrl = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "jump_" + SystemClock.currentThreadTimeMillis() + ".png"; mLocalUrl = getContext().getExternalFilesDir("jumphelper").getAbsoluteFile() + "/jump_" + System.currentTimeMillis() + ".png"; } fileImage = new File(mLocalUrl); if (!fileImage.exists()) { fileImage.createNewFile(); } FileOutputStream out = new FileOutputStream(fileImage); if (out != null) { bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); fileImage = null; } catch (IOException e) { e.printStackTrace(); fileImage = null; } } if (fileImage != null) { return bitmap; } return null; } @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); LogUtils.e("JUMP", "Result:" + bitmap); if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); } if (mVirtualDisplay != null) { mVirtualDisplay.release(); } if (mOnShotListener != null) { mOnShotListener.onFinish(mLocalUrl); } } } private MediaProjectionManager getMediaProjectionManager() { return (MediaProjectionManager) getContext().getSystemService( Context.MEDIA_PROJECTION_SERVICE); } private Context getContext() { return mRefContext.get(); } private int getScreenWidth() { return Resources.getSystem().getDisplayMetrics().widthPixels; } private int getScreenHeight() { return getFullActivityHeight(context.getApplicationContext()); } /** * getResources().getDisplayMetrics().heightPixels 在三星S8上返回的值不对,没包含系统状态栏 * * https://blog.csdn.net/xu20082100226/article/details/80076351 * * @param context * @return */ public static int getFullActivityHeight(@Nullable Context context) { if (!isAllScreenDevice(context)) { return getScreenHeight(context); } return getScreenRealHeight(context); } private static final int PORTRAIT = 0; private static final int LANDSCAPE = 1; @NonNull private volatile static Point[] mRealSizes = new Point[2]; public static int getScreenRealHeight(@Nullable Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return getScreenHeight(context); } int orientation = context != null ? context.getResources().getConfiguration().orientation : context.getResources().getConfiguration().orientation; orientation = orientation == Configuration.ORIENTATION_PORTRAIT ? PORTRAIT : LANDSCAPE; if (mRealSizes[orientation] == null) { WindowManager windowManager = context != null ? (WindowManager) context.getSystemService(Context.WINDOW_SERVICE) : (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (windowManager == null) { return getScreenHeight(context); } Display display = windowManager.getDefaultDisplay(); Point point = new Point(); display.getRealSize(point); mRealSizes[orientation] = point; } return mRealSizes[orientation].y; } public static int getScreenHeight(@Nullable Context context) { if (context != null) { return context.getResources().getDisplayMetrics().heightPixels; } return 0; } private volatile static boolean mHasCheckAllScreen; private volatile static boolean mIsAllScreenDevice; /** * 判断是否是全面屏 * @param context * @return */ public static boolean isAllScreenDevice(Context context) { if (mHasCheckAllScreen) { return mIsAllScreenDevice; } mHasCheckAllScreen = true; mIsAllScreenDevice = false; // 低于 API 21的,都不会是全面屏。。。 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { return false; } WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (windowManager != null) { Display display = windowManager.getDefaultDisplay(); Point point = new Point(); display.getRealSize(point); float width, height; if (point.x < point.y) { width = point.x; height = point.y; } else { width = point.y; height = point.x; } if (height / width >= 1.97f) { mIsAllScreenDevice = true; } } return mIsAllScreenDevice; } // a call back listener public interface OnShotListener { void onFinish(String url); } }
<!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"> <!-- Font AWESOME SCRIPT INCLUSION (ICONS)--> <script src="https://kit.fontawesome.com/7b36db9d89.js" crossorigin="anonymous"></script> <!--Fonts --> <link href="https://fonts.googleapis.com/css2?family=Dosis&family=Staatliches&display=swap" rel="stylesheet"> <!-- CSS FILE LINKED --> <link rel="stylesheet" href="css/main.css"> <!-- Favicon Icon --> <link rel="shortcut icon" type="image/x-icon" href="./img/KC Logos/favicon-KC web dev.ico"> <title>Kedejra Cameron| About Me</title> </head> <body> <!-- Header --> <header id="header-inner"> <div class="container"> <!--Container is to help with centering elements--> <nav id="main-nav"> <img src="img/KC Logos/Portfolio Logo Transparent3.png" alt="My Portfolio" id="logo"> <ul> <li><a href="index.html">Home</a></li> <li><a href="about.html">About</a></li> <li><a href="work.html">Work</a></li> <li><a class="current" href="contact.html">Contact</a></li> </ul> </nav> </div> </header> <!-- Section A: Contact Form --> <section id="contact-a" class="text-center pad-3"> <div class="container"> <h2 class="section-title">Hit Me Up</h2> <div class="underline"></div> <p class="lead">Here's how you can reach me</p> <form method="post" data-netlify="true" data-netlify-recaptcha="true"> <div class="text-fields"> <input type="text" class="text-input name-input" name="name" placeholder="What's your name?"> <input type="text" class="text-input subject-input" name="subject" placeholder="What's the subject?"> <input type="email" class="text-input email-input" name="email" placeholder="What's your email address?"> <input type="text" class="text-input phone-input" name="phone" placeholder="What's your phone number?"> <textarea class="message-input" name="message" placeholder="Type your message..."></textarea> <div class="marg-2"> <div data-netlify-recaptcha="true"></div> </div> </div> <button type="submit" class="btn-dark">Submit <i style="padding-left:0.7rem" class="fas fa-paper-plane"></i></button> </form> </div> </section> <!-- Contact info --> <section id="contact-b" class=" text-center pad-3 bg-dark"> <div class="container"> <div class="contact-info"> <div> <i class="fas fa-envelope fa-2x"></i> <h3>Email</h3> <p>kc.web.dev@something.com</p> </div> <div> <i class="fas fa-phone-alt fa-2x"></i> <h3>Phone Number</h3> <p>+1 876 333-3333</p> </div> <div> <i class="fas fa-map-pin fa-2x"></i> <h3>Location</h3> <p>Kingston, Jamaica</p> </div> </div> </div> </section> <!-- Section C: Tagline --> <section id="contact-c" class=" text-center bg-gradient pad-4"> <div class="container"> <h1 id="tag"> Let's Start Your Next Project!</h1> </div> </section> <!-- Footer --> <footer id="main-footer"> <div class="footer-content container"> <p>Copyright &copy; 2022. All rights reserved</p> <div class="social"> <a href="https://www.linkedin.com/in/kedejra-cameron-bsc" target="_blank"><i class="fab fa-linkedin "></i></a> <a href="https://facebook.com" target="_blank"><i class="fab fa-facebook "></i></a> <a href="https://instagram.com" target="_blank"><i class="fab fa-instagram "></i></a> <a href="https://twitter.com" target="_blank"><i class="fab fa-twitter "></i></a> </div> <p>Showcase image: Photo by <a href="https://unsplash.com/@norestinthewild?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank">Chris Malinao Burgett</a> on Unsplash</p> </div> </footer> </body> </html>
/** * @file RStack.h * @author Radu-D. Chira (github.com/raduCh04) * @date 2024-03-15 */ #ifndef __RSTACK_H__ #define __RSTACK_H__ #include <stdbool.h> struct RStack; typedef struct RStack RStack; /** * @brief Initialize a resizable stack for storing elements of a specified data type. * * This function initializes a resizable stack to store elements of a specified data type. * It requires the size of the data type. * * @param type_size The size (in bytes) of the data type. * @return A pointer to the initialized stack. */ RStack *rstack_init(size_t type_size); /** * @brief Destroy a resizable stack. * * This function deallocates the memory occupied by the resizable stack (RStack), * including the memory occupied by its elements. * * @param stack A pointer to the RStack to be destroyed. */ void rstack_destroy(RStack *stack); /** * @brief Push an element onto the top of the resizable stack. * * This function pushes a new element onto the top of the resizable stack (RStack). * * @param stack A pointer to the RStack. * @param data A pointer to the data to be pushed onto the stack. */ void rstack_push(RStack *stack, void *data); /** * @brief Pop the top element from the resizable stack. * * This function removes and returns the top element from the resizable stack (RStack). * * @param stack A pointer to the RStack. * @return A pointer to the data popped from the stack. */ void *rstack_pop(RStack *stack); /** * @brief Get the top element of the resizable stack without removing it. * * This function returns a pointer to the top element of the resizable stack (RStack) * without removing it from the stack. * * @param stack A pointer to the RStack. * @return A pointer to the top element of the stack. */ void *rstack_top(const RStack *stack); /** * @brief Get the current size of the resizable stack. * * This function returns the current number of elements in the resizable stack (RStack). * * @param stack A pointer to the RStack. * @return The number of elements in the stack. */ size_t rstack_get_size(const RStack *stack); /** * @brief Check if the resizable stack is empty. * * This function checks if the resizable stack (RStack) is empty. * * @param stack A pointer to the RStack. * @return true if the stack is empty, false otherwise. */ bool rstack_is_empty(const RStack *stack); /** * @brief Print the contents of the resizable stack. * * This function prints the contents of the resizable stack (RStack) using the * provided printing function. * * @param stack A pointer to the RStack. * @param print A function pointer to a function that prints an individual element. */ void rstack_print(const RStack *stack, void (*print)(void *)); #endif /* __RSTACK_H__ */
package hw05; import java.util.Arrays; import java.util.Objects; public class Pet { private String species; private String nickname; private int age; private int trickLevel; private String [] habits; public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getTrickLevel() { return trickLevel; } public void setTrickLevel(int trickLevel) { this.trickLevel = trickLevel; } public String[] getHabits() { return habits; } public void setHabits(String[] habits) { this.habits = habits; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pet pet = (Pet) o; return age == pet.age && trickLevel == pet.trickLevel && nickname.equals(pet.nickname) && Arrays.equals(habits, pet.habits); } @Override public int hashCode() { int result = Objects.hash(species, nickname, age); result = 31 * result + Arrays.hashCode(habits); return result; } @Override public String toString() { return "Pet{" + "species='" + getSpecies() + '\'' + ", nickname='" + getNickname() + '\'' + ", age=" + getAge() + ", trickLevel=" + getTrickLevel() + ", habits=" + Arrays.toString(getHabits()) + '}'; } }
import { fireEvent, logRoles, render } from "@testing-library/react" import FilterMenuTemplate from '.' jest.mock('@/context/useMenuFilterState', () => ({ __esModule: true, useMenuFilterState: jest.fn(() => ({ isOpen: true, })), })); describe("<FilterMenuTemplate />", () => { it("check elements rendered", () => { const view = render(<FilterMenuTemplate type_name={[]} />) const radio1 = view.getByRole('button', { name: /Tall/i }) const radio2 = view.getByRole('button', { name: /Small/i }) const radio3 = view.getByRole('button', { name: /Light/i }) const radio4 = view.getByRole('button', { name: /Heavy/i }) const resetFiltersButton = view.getByRole('button', { name: /Resetar filtros/i }) expect(radio1).toBeInTheDocument() expect(radio2).toBeInTheDocument() expect(radio3).toBeInTheDocument() expect(radio4).toBeInTheDocument() expect(resetFiltersButton).toBeInTheDocument() }) it("check options elements in menu rendering correctly", () => { const view = render(<FilterMenuTemplate type_name={['fire', 'water', 'grass']} />); const button = view.getByText('All'); fireEvent.click(button); const optionWater = view.getByRole('button', {name: 'water'}) const optionFire = view.getByRole('button', {name: 'fire'}) const optionGrass = view.getByRole('button', {name: 'grass'}) logRoles(view.container) expect(optionFire).toBeInTheDocument() expect(optionWater).toBeInTheDocument() expect(optionGrass).toBeInTheDocument() }) })
import React, { useEffect } from "react"; import { connect } from "react-redux"; import PropTypes from "prop-types"; import { loadMemberCount } from "./memberCountActions"; import Alert from "../../common/Alert"; import Spinner from "../../common/Spinner"; const MemberCount = props => { const { loading, error, loadMemberCount, dashboardMemberCount } = props; const totalMembers = dashboardMemberCount.activeMembers + dashboardMemberCount.inactiveMembers; const activePerct = (dashboardMemberCount.activeMembers * 100) / totalMembers; const inactivePerct = (dashboardMemberCount.inactiveMembers * 100) / totalMembers; useEffect(() => { loadMemberCount(); }, []); if (loading) { return <Spinner />; } if (error !== null) { return ( <Alert show={error !== null} type={error !== null ? "failure" : "success"} > There was an error fetching data </Alert> ); } return ( <div className="item col-md-4 col-sm-6 col-xs-12"> <div className="panel panel-default"> <div className="panel-body"> <h3>Member Count</h3> <div className="row"> <div className="col-xs-6"> <h4 className="text-headline margin-none"> {" "} {dashboardMemberCount.activeMembers} </h4> <p className="text-light"> <i className="fa fa-circle-o text-success fa-fw" /> Active </p> </div> <div className="col-xs-6"> <h4 className="text-headline margin-none"> {dashboardMemberCount.inactiveMembers} </h4> <p className="text-light"> <i className="fa fa-circle-o text-danger fa-fw" /> Inactive </p> </div> </div> <div className="progress progress-mini"> <div className="progress-bar progress-bar-success" style={{ width: `${activePerct}%` }} > <span className="sr-only">{activePerct}% Active Members</span> </div> <div className="progress-bar progress-bar-danger" style={{ width: `${inactivePerct}%` }} > <span className="sr-only">{inactivePerct}% Inactive Members</span> </div> </div> </div> </div> </div> ); }; MemberCount.propTypes = { dashboardMemberCount: PropTypes.object.isRequired, loadMemberCount: PropTypes.func.isRequired, loading: PropTypes.bool, error: PropTypes.string }; function mapStateToProps(state) { const loading = state.apiCallsInProgress > 0; const { error } = state; const { dashboardMemberCount } = state; return { loading, error, dashboardMemberCount }; } const mapDispatchToProps = { loadMemberCount }; export default connect( mapStateToProps, mapDispatchToProps )(MemberCount);
<?php header('Cache-Control: no-store, no-cache, must-revalidate'); session_start([ 'cookie_lifetime' => 86400, 'cookie_httponly' => TRUE ]); const PROJECT_DIR = "BIT210-assignment/"; define('PROJECT_PATH', "{$_SERVER['DOCUMENT_ROOT']}/" . PROJECT_DIR); define('PROJECT_URL', "http://{$_SERVER['HTTP_HOST']}/" . PROJECT_DIR); const COPYRIGHT_TEXT = 'PCVS - copyright&copy; 2021'; const APP_SLOGAN = 'Private Covid-19 Vaccination Service'; const APP_NAME = 'PCVS'; set_include_path(PROJECT_PATH); /** * Gets the current user or redirect the user to the login page * * @return array|null the authenticated user. returns null on failure */ function authenticate(bool $redirectOnFailure = TRUE) : array|null { if (isset($_SESSION, $_SESSION['current_user'])) { $user = $_SESSION['current_user']; $dir = basename(dirname($_SERVER['PHP_SELF'])); if ($user['userType'] === 'administrator' && $dir == 'admin') { return $user; } else if ($user['userType'] === 'patient' && $dir == 'patient') { return $user; } } if ($redirectOnFailure) { redirect_to_login_form(); } return NULL; } function redirect_to_login_form() { header('Location: ' . PROJECT_URL . 'users/login-form.php'); exit(); } // parse query string and initialize a constant parse_str($_SERVER['QUERY_STRING'], $temp_str_query_assoc); define('STRING_QUERY', $temp_str_query_assoc); unset($temp_str_query_assoc); function statusToColor($status) { switch ($status) { case "pending": return "secondary"; break; case "confirmed": return "primary"; break; case "rejected": return "danger"; break; case "administered": return "success"; break; } }
import { ReactNode, createContext, useContext, useEffect, useState } from 'react'; import { Product } from '../types'; import { useGetFavorites, useGetOrder } from '../hooks'; export type CartItem = { product: Product; quantity: number; }; type UserContext = { cartItems: CartItem[]; favoriteItems: Product[]; cartQuantity: () => number; cartTotal: () => number; addFavoriteItem: (product: Product) => void; removeFavoriteItem: (id: number) => void; getItemQuantity: (id: number) => number; isFavorite: (id: number) => boolean; addToCart: (product: Product) => void; }; type CartProviderProps = { children: ReactNode; }; const CartContext = createContext({} as UserContext); export function useCart() { return useContext(CartContext); } export function CartProvider({ children }: CartProviderProps) { const [favoriteItems, setFavoriteItems] = useState<Product[]>([]); const [cartItems, setCartItems] = useState<CartItem[]>([]); const { data } = useGetOrder(); const { data: favorites } = useGetFavorites(); useEffect(() => { if (data) { setCartItems( data.map(product => { return { product: product, quantity: 1 } as CartItem; }) ); } }, [data]); useEffect(() => { if (favorites) { setFavoriteItems(favorites); } }, [favorites]); function addToCart(product: Product) { setCartItems(currItems => { const newData = [...currItems]; let itemIndex = currItems.findIndex(item => item.product.id === product.id); if (itemIndex === -1) { newData.push({ product, quantity: 1 }); } else { const currentItem = newData[itemIndex]; newData[itemIndex] = { ...currentItem, quantity: currentItem.quantity + 1 }; } return newData; }); } return ( <CartContext.Provider value={{ cartTotal: () => cartItems .map(item => item.product.attenuation_level * item.quantity) .reduce((sum, current) => sum + current, 0), cartQuantity: () => cartItems.map(item => item.quantity).reduce((sum, current) => sum + current, 0), addToCart: addToCart, isFavorite: id => favoriteItems.some(item => item.id === id), addFavoriteItem: product => setFavoriteItems([...favoriteItems, product]), removeFavoriteItem: id => setFavoriteItems(favoriteItems.filter(item => item.id !== id)), cartItems, getItemQuantity: id => cartItems.find(item => item.product.id === id)?.quantity || 0, favoriteItems, }}> {children} </CartContext.Provider> ); }
/* * Copyright (c) 2024 OceanBase. * * 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 server import ( "crypto/tls" "net" "os" "os/signal" "runtime/debug" "syscall" "time" "github.com/facebookgo/grace/gracenet" "github.com/oceanbase/modis/config" "github.com/oceanbase/modis/connection/conncontext" "github.com/oceanbase/modis/log" "github.com/oceanbase/modis/storage" "github.com/oceanbase/modis/util" "github.com/pkg/errors" "github.com/oceanbase/obkv-table-client-go/obkvrpc" ) const maxQueueCmd = 100 // Server accept request from redis clients type Server struct { ServCtx *conncontext.ServerContext Listener net.Listener IDGenerator func() int64 CloseChan chan struct{} } // NewServer creates a new server func NewServer(servCtx *conncontext.ServerContext, idGenerator func() int64) *Server { return &Server{ ServCtx: servCtx, IDGenerator: idGenerator, CloseChan: make(chan struct{})} } // Close close server, error should not be returned during execution func (s *Server) Close() { log.Debug("server", nil, "close server", log.String("stack", string(debug.Stack()))) // stop create new connections err := s.Listener.Close() if err != nil { log.Warn("server", nil, "fail to close linstener", log.Errors(err)) } // close current connection close(s.CloseChan) if s.ServCtx.Storage != nil { err = s.ServCtx.Storage.Close() if err != nil { log.Warn("server", nil, "fail to close storage", log.Errors(err)) } } if s.ServCtx.SuperMode == conncontext.SupervisedSystemd { err := util.SdNotify("STOPPING=1\n") if err != nil { log.Warn("server", nil, "fail to do SdNotify", log.Errors(err)) } } } // SignalHandle handle signal func (s *Server) SignalHandle(gnet *gracenet.Net, sigChan chan os.Signal) { log.Debug("server", nil, "start to wait signals") signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP) for { sig := <-sigChan log.Debug("server", nil, "receive signal", log.Any("signal", sig)) switch sig { case syscall.SIGTERM, syscall.SIGINT: log.Info("server", nil, "receive SIGTERM/SIGINT, stop server") signal.Stop(sigChan) s.Close() case syscall.SIGHUP: // restart pid, err := gnet.StartProcess() if err != nil { log.Warn("server", nil, "fail to restart process", log.Errors(err), log.Int("pid", pid)) } else { log.Info("server", nil, "success to restart process", log.Errors(err), log.Int("pid", pid)) } signal.Stop(sigChan) s.Close() } } } func (s *Server) serve(servCfg *config.ServerConfig) (err error) { s.ServCtx.StartTime = time.Now() obkvServer, err := obkvrpc.NewServer(servCfg.MaxConnection, &s.CloseChan) var db *storage.DB if err != nil { log.Error("server", nil, "fail to create new OBKV RPC server", log.Errors(err)) return err } defer obkvServer.Close() s.ServCtx.StartMetricsTicker() for { // until Accept() return error conn, err := s.Listener.Accept() if err != nil { log.Error("server", nil, "fail to accept connection", log.Errors(err), log.String("addr", s.Listener.Addr().String())) return err } if s.ServCtx.ClientNum.Load() + 1 > int64(servCfg.MaxConnection) { log.Warn("server", nil, "exceed max connection num", log.Errors(err), log.String("addr", s.Listener.Addr().String())) conn.Close() s.ServCtx.RejectClientNum++ continue } db, err = s.ServCtx.GetDB(0) if err != nil { log.Warn("server", nil, "fail to visit db", log.Errors(err), log.String("addr", s.Listener.Addr().String())) return err } s.ServCtx.ClientNum.Add(1) s.ServCtx.TotalClientNum++ cliID := s.IDGenerator() cliCtx := conncontext.NewCodecCtx(conn, cliID, db, maxQueueCmd) log.Debug("server", nil, "succ to accept a new connection", log.String("addr", s.Listener.Addr().String()), log.Int64("client id", cliID)) s.ServCtx.Clients.Set(conncontext.ClientID(cliID), cliCtx) redisSrv := NewRedisCodec(cliCtx, s.ServCtx) go obkvServer.ServeCodec(redisSrv, maxQueueCmd) } } // ListenAndServe handle connection and request from clients func (s *Server) ListenAndServe(servCfg *config.ServerConfig, tlsCfg *tls.Config) error { defer func() { if err := recover(); err != nil { log.Error("server", nil, "server panic, exit", log.Any("error", err), log.String("stack", string(debug.Stack()))) } }() var err error if servCfg.MaxConnection > 10000 || servCfg.MaxConnection < 1 { err = errors.New("server max connection should be >= 1 and <= 10000") log.Warn("server", nil, "invalid server config: max_connection", log.Errors(err), log.Int("max_connection", servCfg.MaxConnection)) return err } // Listen gnet := &gracenet.Net{} s.Listener, err = gnet.Listen("tcp", servCfg.Listen) if err != nil { log.Warn("server", nil, "fail to listen address", log.Errors(err), log.String("addr", servCfg.Listen)) return err } if tlsCfg != nil { s.Listener = tls.NewListener(s.Listener, tlsCfg) } if s.ServCtx.SuperMode == conncontext.SupervisedSystemd { err = util.SdNotify("STATUS=Ready to accept connections\n") if err != nil { return err } err = util.SdNotify("READY=1\n") if err != nil { return err } } log.Debug("server", nil, "tcp: listen to ", log.String("addr", servCfg.Listen)) // process signal sigChan := make(chan os.Signal, 1) go s.SignalHandle(gnet, sigChan) // Serve return s.serve(servCfg) }
package repository import ( "context" core "github.com/jackyuan2022/workspace/core" model "github.com/jackyuan2022/workspace/domain/model" ) type UserRepository interface { FindById(ctx context.Context, id string) (*model.User, *core.AppError) FindByMobile(ctx context.Context, mobile string) (*model.User, *core.AppError) InsertUser(ctx context.Context, user *model.User) (*model.User, *core.AppError) UpdateUser(ctx context.Context, user *model.User) (*model.User, *core.AppError) DeleteUserById(ctx context.Context, id string) (bool, *core.AppError) DeleteUserByMobile(ctx context.Context, mobile string) (bool, *core.AppError) QueryData(ctx context.Context, query *core.DbQuery) ([]model.User, *core.AppError) }
import 'package:e_kaksha_homepage/Constant.dart'; import 'package:e_kaksha_homepage/utility/theme_manager.dart'; import 'package:e_kaksha_homepage/utility/user_info_change.dart/basic_change.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { static int index = 0; void change(num ){ setState(() { index = num; }); } @override Widget build(BuildContext context) { final GetLocalData = Provider.of<GetAndSaveImage>(context); return Scaffold( drawer: Drawer( child: ListView( children: [ SizedBox(height: 60,), Column( children: [ const Text("Welcome to E-Kaksha",style: TextStyle(fontSize: 27,fontWeight: FontWeight.bold),), Divider(), ClipOval( child: SizedBox( width: 200, height: 200, child: GetImage( width: 200, Height: 200, GetImageProvider: GetLocalData.imageBytes,)), ), const SizedBox(height: 20,), Text("Hi :) ${GetLocalData.userName}",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),) ], ), const SizedBox(height: 30,), DrawerList( icon: Icons.dashboard, text: "DashBoard", onTap: () { change(0); Navigator.pop(context); }, ), DrawerList( icon: Icons.home, text: "Home", onTap: () { change(1); Navigator.pop(context); }, ), DrawerList( icon: Icons.assignment, text: "Assignment", onTap: () {change(2); Navigator.pop(context);}, ), DrawerList( icon: Icons.edit, text: "Profile Edit", onTap: () {change(3); print(barName); Navigator.pop(context);}, ), ], ), ), appBar: AppBar( title: Text(barName[index]), actions: [ Padding( padding: EdgeInsets.symmetric(horizontal: 30), child: IconButton( onPressed: () { Provider.of<themedata>(context, listen: false) .changetTheme(); }, icon: Icon(Icons.light_mode))) ], ), body: getWidget[index]); } } class DrawerList extends StatelessWidget { const DrawerList({ super.key, this.icon, this.onTap, this.text, }); final icon; final text; final onTap; @override Widget build(BuildContext context) { return ListTile( leading: Icon(icon), title: Text(text), onTap: onTap, ); } }
<?php /** * Template part for displaying page content in page.php * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/ * * @package lb19 */ ?> <!-- template-parts/content-single-post.php --> <div class="post mdl-cell mdl-cell--12-col mdl-shadow--4dp"> <?php if ( ! is_front_page() ) { ?> <div class="mdl-grid mdl-cell mdl-cell--12-col post-title"> <div class="mdl-cell mdl-cell--12-col"> <h1><?php the_title(); ?></h1> </div> </div> <div class="mdl-grid mdl-cell mdl-cell--12-col"> <span class="post-date"> <?php echo esc_html( get_the_date() ); ?></span> <div class="mdl-layout-spacer"></div> <?php lb19_posted_by(); ?> </div> <?php } ?> <div class="mdl-card__supporting-text"> <?php the_content(); ?> </div> <div class="mdl-card__actions mdl-grid"> <?php if ( has_category() ) { foreach ( get_the_category() as $category ) { echo '<span class="mdl-chip post-category"><a href="' . esc_url( get_category_link( $category->term_id ) ) . '"><span class="mdl-chip__text">' . esc_html( $category->name ) . '</a></span>'; } } if ( has_tag() ) { foreach ( get_the_tags() as $post_tag ) { echo '<span class="mdl-chip post-tag"> <a href="' . esc_url( get_tag_link( $post_tag->term_id ) ) . '">' . '<span class="mdl-chip__text">' . esc_attr( $post_tag->name ) . '</span>' . '</a>' . '</span>'; } } ?> </div> </div>
import { Injectable } from '@angular/core'; import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { OktaAuthStateService } from '@okta/okta-angular'; import { from, Observable } from 'rxjs'; import {EnvironmentService} from "../../services/common/environment.service"; @Injectable({ providedIn: 'root', }) export class AuthInterceptor implements HttpInterceptor { constructor( private readonly environment: EnvironmentService, private readonly oktaAuthStateService: OktaAuthStateService, ) {} async handle(request: HttpRequest<any>, next: HttpHandler): Promise<HttpEvent<any>> { const skipInterceptor = request.headers.has('skip-auth-interceptor'); if (skipInterceptor) { request = request.clone({ headers: request.headers.delete('skip-auth-interceptor'), }); } const accessToken = (await this.oktaAuthStateService['oktaAuth'].tokenManager.get('accessToken'))?.accessToken; let newRequest = request; if ( accessToken && (request.url.startsWith(`${this.environment.amberBaseUrl}/api`) || request.url.startsWith(`${this.environment.amberBaseUrl}/domain/api`)) && !skipInterceptor ) { newRequest = request.clone({ headers: request.headers.set('Authorization', `Bearer ${accessToken}`), }); } return next.handle(newRequest).toPromise(); } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return from(this.handle(request, next)); } }
import { Controller, Get, Param, Post, Query } from '@nestjs/common'; import { ApiHeader, ApiQuery, ApiResponse } from '@nestjs/swagger'; import { ObjectId } from 'mongoose'; import { AppService } from './app.service'; import { WalletBalance } from './blockchain/domain/balance_service'; import { Transaction } from './schemas/transaction.schema'; @ApiHeader({ name: 'X-ApiKey', description: 'API Key', }) @Controller("") export class AppController { constructor(private readonly appService: AppService) { } @Get("transactions") @ApiQuery({ name: 'cursor_id', required: false }) @ApiQuery({ name: 'sender', required: false }) @ApiQuery({ name: 'recipient', required: false }) @ApiResponse({ status: 200, description: 'A list of the latest 100 Dai transactions, cursor-based pagination with cursor_id and filter by sender, recipient', type: [Transaction]}) async getTransactions( @Query('cursor_id') cursor_id?: ObjectId, @Query('sender') sender?: string, @Query('recipient') recipient?: string): Promise<Transaction[]> { return await this.appService.retrieveTransactions(100, cursor_id, recipient, sender) } @Get("balance/:wallet") @ApiResponse({ status: 200, description: 'The balance of the wallet', type: WalletBalance}) async getBalance( @Param('wallet') wallet: string): Promise<WalletBalance> { return await this.appService.getBalance(wallet) } }
class ChampignonsProduct extends Product{ ChampignonsProduct(){ this.calorie = 27.; this.protein = 4.4; this.fat = 1.; this.carbohydrates = 0.2; this.cost = 20.; } @Override public Double accept(Visitor visitor) { return visitor.visit(this); } } class ShrimpProduct extends Product{ ShrimpProduct(){ this.calorie = 83.; this.protein = 18.; this.fat = 1.; this.carbohydrates = 0.; this.cost = 50.; } @Override public Double accept(Visitor visitor) { return visitor.visit(this); } } class SourCreamProduct extends Product{ SourCreamProduct(){ this.calorie = 120.; this.protein = 3.3; this.fat = 10.; this.carbohydrates = 3.3; this.cost = 14.4; } @Override public Double accept(Visitor visitor) { return visitor.visit(this); } } class CheeseProduct extends Product{ CheeseProduct(){ this.calorie = 345.; this.protein = 25.; this.fat = 25.; this.carbohydrates = 0.; this.cost = 70.; } @Override public Double accept(Visitor visitor) { return visitor.visit(this); } } class SpicesProduct extends Product{ SpicesProduct(){ this.calorie = 37.; this.protein = 3.3; this.fat = 0.; this.carbohydrates = 7.; this.cost = 20.; } @Override public Double accept(Visitor visitor) { return visitor.visit(this); } }
import { OfferCardType } from '../../types'; import { MemoOfferCard as OfferCard } from '../offer-card/offer-card'; type OffersListProps = { offerCards: OfferCardType[]; blockClass: string; containerClass?: string; onOfferCardMouseEnter: (card: OfferCardType) => void; onOfferCardMouseLeave: () => void; } export default function OffersList(props: OffersListProps): JSX.Element { const {offerCards, onOfferCardMouseEnter, onOfferCardMouseLeave, blockClass, containerClass = ''} = props; return ( <div className={`${blockClass}__list ${containerClass} places__list`}> { offerCards.map((offerCard) => ( <OfferCard onOfferCardMouseEnter={onOfferCardMouseEnter} onOfferCardMouseLeave={onOfferCardMouseLeave} offerCard={offerCard} blockClass={blockClass} key={offerCard.id} /> )) } </div> ); }
import React from "react"; import { City, District, Floor, GateHeight, LandArea, LivingArea, Rooms, Series, Size } from "../../../../assets/params"; import { useTranslation } from "next-i18next"; import { IEstate } from "../../../../types"; import style from "./params.module.scss"; interface ParamsProps { estate: IEstate, dark?: boolean } export default function Params ({ estate, dark }: ParamsProps) { const { t, i18n } = useTranslation() return ( <div className={style.params}> {estate.city && ( <div className={style.param}> <div className={style.label + ` ${dark ? style.dark : ""}`}>{t("estatePage:filter.city")}</div> <div className={style.value + ` ${dark ? style.dark : ""}`}> <span><City /></span>{estate.city.name[i18n.language]} </div> </div> )} {estate.district && ( <div className={style.param}> <div className={style.label + ` ${dark ? style.dark : ""}`}>{t("estatePage:filter.district")}</div> <div className={style.value + ` ${dark ? style.dark : ""}`}> <span><District /></span>{estate.district.name[i18n.language]} </div> </div> )} {estate.landArea && ( <div className={style.param}> <div className={style.label + ` ${dark ? style.dark : ""}`}>{t("estatePage:filter.landArea")}</div> <div className={style.value + ` ${dark ? style.dark : ""}`}> <span><LandArea /></span>{estate.landArea} m² </div> </div> )} {estate.floor && ( <div className={style.param}> <div className={style.label + ` ${dark ? style.dark : ""}`}>{estate.type.en === "Houses" ? t("params:floors") : t("params:floor")}</div> <div className={style.value + ` ${dark ? style.dark : ""}`}> <span><Floor /></span>{estate.floor} {estate.type.en === "Houses" ? t("params:floors") : t("params:floor")} </div> </div> )} {estate.rooms && ( <div className={style.param}> <div className={style.label + ` ${dark ? style.dark : ""}`}>{t("estatePage:filter.rooms")}</div> <div className={style.value + ` ${dark ? style.dark : ""}`}> <span><Rooms /></span>{estate.rooms} {t("params:rooms")} </div> </div> )} {estate.livingArea && ( <div className={style.param}> <div className={style.label + ` ${dark ? style.dark : ""}`}>{t("estatePage:filter.livingArea")}</div> <div className={style.value + ` ${dark ? style.dark : ""}`}> <span><LivingArea /></span>{estate.livingArea} m² </div> </div> )} {estate.series && ( <div className={style.param}> <div className={style.label + ` ${dark ? style.dark : ""}`}>{t("estatePage:filter.series")}</div> <div className={style.value + ` ${dark ? style.dark : ""}`}> <span><Series /></span>{estate.series[i18n.language]} </div> </div> )} {estate.gateHeight && ( <div className={style.param}> <div className={style.label + ` ${dark ? style.dark : ""}`}>{t("estatePage:filter.gateHeight")}</div> <div className={style.value + ` ${dark ? style.dark : ""}`}> <span><GateHeight /></span>{estate.gateHeight} m </div> </div> )} {estate.size && ( <div className={style.param}> <div className={style.label + ` ${dark ? style.dark : ""}`}>{t("estatePage:filter.size")}</div> <div className={style.value + ` ${dark ? style.dark : ""}`}> <span><Size /></span>{estate.size} </div> </div> )} </div> ) }
import { View, Text, ActivityIndicator, TouchableOpacity } from 'react-native' import React, { useEffect, useRef, useState } from 'react' import type { NativeStackScreenProps } from '@react-navigation/native-stack'; import { FlatList } from 'react-native-gesture-handler'; import data from "../data/civics_test_2020.json"; import { useDataStore } from '../app/store.zustand.data'; import QuestionsCardScreen from './QuestionsCardScreen'; import { MinusIcon, PlusIcon } from 'react-native-heroicons/outline'; import ScrollToTopScreen from './ScrollToTopScreen'; import { SafeAreaView } from 'react-native-safe-area-context'; import AdsScreen from './AdsScreen'; import CheckBox from '../components/CheckBox'; import { useTranslation } from 'react-i18next'; import StorageService from '../utils/StorageService'; import AdsFullScreen from './AdsFullScreen'; import ForQuestionScreen from './settings/ForQuestionScreen'; import { setPreviousPlayingAudioHandler, stopPreviousPlayingAudioHandler } from '../utils/libs'; type RootStackParamList = {}; type Props = NativeStackScreenProps<RootStackParamList>; const Learn2020Screen = ({ route, navigation }: Props) => { const {showFullAds} = route.params; const listRef = useRef(null); const [isLoadingData, setIsLoadingData] = useState<boolean>(true); const {t} = useTranslation(); const jsonData = useDataStore((state) => state.data2020); const setJsonData = useDataStore((state) => state.setData2020); const [toggleTranslate, setToggleTranslate] = useState<boolean>(false) const [fontsize, setFontsize] = useState<number>(0); let defaultPrimaryFontSize = 20; let defaultSubSizeNumber = 20; const [primaryFontSize, setPrimaryFontSize] = useState<number>(20); const [subFontSize, setSubFontSize] = useState<number>(18); const defaultTranslateQuestionTxt = 'question_'; const defaultTranslateAnswerTxt = 'answer_'; const [traslateQuestionLn, setTraslateQuestionLn] = useState(''); const [translateAnswerLn, setTranslateAnswerLn] = useState(''); const changeFontsizeHandler = (action:number) => { if(action === 1) { if(fontsize < 30) { setFontsize((prev) => prev = prev + 1); } } else if(action === 2) { if(fontsize > 0) { setFontsize((prev) => prev = prev - 1); } } else { setFontsize(0); } setPrimaryFontSize(defaultPrimaryFontSize + fontsize); setSubFontSize(defaultSubSizeNumber + fontsize); } useEffect(() => { const getLanguage = async () => { const language = await StorageService.getItem(StorageService.APP_LANGUAGE); if(language && language?.language) { setTraslateQuestionLn(defaultTranslateQuestionTxt + "" + language.language); setTranslateAnswerLn(defaultTranslateAnswerTxt + "" + language.language); } } getLanguage(); }, []); useEffect(() => { setIsLoadingData(true); if(!jsonData) { setTimeout(() => { const parsedData = JSON.stringify(data.questions); if(parsedData) { setJsonData(JSON.parse(parsedData)); setIsLoadingData(false); } }, 1); } else { setIsLoadingData(false); } }, [jsonData]); const scrollToTopHandler = () => { listRef.current.scrollToOffset({ offset: 0, animated: true }); } const toggleTranslateHandler = () => { setToggleTranslate(!toggleTranslate); } return ( <View className="flex-columns items-center w-full h-max"> <View className="w-full h-[89%] mt-2"> {isLoadingData && <View> <Text>Loading </Text> <ActivityIndicator animating = {isLoadingData} color = '#bc2b78' size = "large"/> </View> } {jsonData && jsonData?.length && <View className="m-2"> {/* <View className="absolute top-0 left-0 w-full"> <View className="flex-row justify-between "> <View className="flex-row"> <TouchableOpacity onPress={() => toggleTranslateHandler()} className="flex-row" > <Text className="text-xl text-blue-700">{t("show-translate")}</Text> <CheckBox toggleTranslate={toggleTranslate} /> </TouchableOpacity> </View> <View className="flex-row"> <TouchableOpacity onPress={() => changeFontsizeHandler(1)} > <Text className="text-xl text-blue-700">{t("change-font-size")} &nbsp;</Text> </TouchableOpacity> <TouchableOpacity onPress={() => changeFontsizeHandler(1)} > <PlusIcon size={25} color="blue" /> </TouchableOpacity> <Text>&nbsp;&nbsp;&nbsp;</Text> <TouchableOpacity onPress={() => changeFontsizeHandler(2)} > <MinusIcon size={25} color="blue" /> </TouchableOpacity> </View> </View> </View> */} <FlatList className="" ref={listRef} data={jsonData} renderItem={({item, index}) => <QuestionsCardScreen count={index} question={item.question} translate_question={item[traslateQuestionLn]} answer={item.answer} translate_answer={item[translateAnswerLn]} voice={item.voice} toggleTranslate={toggleTranslate} primaryFontSize={primaryFontSize} subFontSize={subFontSize} setPreviousPlayingAudioHandler={setPreviousPlayingAudioHandler} stopPreviousPlayingAudioHandler={stopPreviousPlayingAudioHandler} /> } keyExtractor={(item, index) => index.toString()} /> <ScrollToTopScreen ref={listRef}/> <ForQuestionScreen changeFontsizeHandler={changeFontsizeHandler} toggleTranslateHandler={toggleTranslateHandler} /> </View> } </View> <AdsScreen /> <AdsFullScreen showFullAds={showFullAds}/> </View> ) } export default Learn2020Screen
# script used to manually verify that all incidents were added correctly to the database # step 1: collect all Article objects from the database that do not have incidents_verified set to True # step 2: for each article from step 1, print the article's URL and all incidents associated with the article # step 3: for each incident, print the incident details and a y/n prompt to verify the incident # step 4: if the incident details are incorrect, update the incident in the database # step 5: if the incident details are correct, mark the incident as verified in the database # step 6: repeat steps 2-5 until all incidents are verified from tqdm import tqdm from database import get_database_session from models.article import Article from models.incident import Incident from police_fire.maps import get_lat_lng_of_addresses DBsession, engine = get_database_session(environment='prod') # filter by both if incidents_scraped == True and incidents_verified == False articles = DBsession.query(Article).filter_by(incidents_scraped=True, incidents_verified=False).all() def handle_incorrect_number_of_incidents(article): number_of_missing_incidents = int(input("How many missing incidents are there? ")) # if number_of_incidents == 0, delete the incidents associated with the article from the database # and set incidents_verified to True for the article if number_of_missing_incidents == 0: incidents = DBsession.query(Incident).filter_by(source=article.url).all() for incident in incidents: DBsession.delete(incident) article.incidents_verified = True DBsession.commit() return for i in range(number_of_missing_incidents): print(f'\nInputting details for missing incident #{str(i + 1)}.\n') # prompt for the details of each incident incident_reported_date = article.date_published accused_name = input("Accused Name: ") accused_age = input("Accused Age: ") accused_location = input("Accused Location: ") charges = input("Charges: ") details = input("Details: ") legal_actions = input("Legal Actions: ") incident_date = input("Incident Date: ") incident_location = input("Incident Location: ") incident_location_lat, incident_location_lng = get_lat_lng_of_addresses.get_lat_lng_of_address(incident_location) source = article.url # create a new Incident object and add it to the database new_incident = Incident( incident_reported_date=incident_reported_date, accused_name=accused_name, accused_age=accused_age, accused_location=accused_location, charges=charges, details=details, legal_actions=legal_actions, incident_location=incident_location, incident_date=incident_date, incident_location_lat=incident_location_lat, incident_location_lng=incident_location_lng, source=source ) DBsession.add(new_incident) DBsession.commit() return def verify_incidents_for_article(article): print(f"\nArticle URL: {article.url}") # an article's incidents are ones where the source == article.url incidents = DBsession.query(Incident).filter_by(source=article.url).all() article_incidents_verified = [] print(f"Number of Incidents in database: {len(incidents)}\n") number_of_incidents_response = input('Is this correct? (y/n): ') if number_of_incidents_response == 'n': handle_incorrect_number_of_incidents(article) # grab the updated incidents from the database incidents = DBsession.query(Incident).filter_by(source=article.url).all() for incident in incidents: print('\n') print(f"Accused Name: {incident.accused_name}") print(f"Accused Age: {incident.accused_age}") print(f"Accused Location: {incident.accused_location}") print(f"Charges: {incident.charges}") print(f"Details: {incident.details}") print(f"Legal Actions: {incident.legal_actions}") # prompt to verify the incident print('\n') verified = input("Is this incident correct? (y/n): ") if verified == 'y': article_incidents_verified.append(incident) else: print("Please update the incident in the database.") article.incidents_verified = False DBsession.commit() return # if all incidents are verified, mark the article as verified if len(article_incidents_verified) == len(incidents): article.incidents_verified = True DBsession.commit() print("\nArticle verified.") else: print("\nArticle not verified.") return def main(): print(len(articles), 'articles with unverified incidents found.') for article in articles: verify_incidents_for_article(article) return if __name__ == '__main__': main()
import './App.css'; import { Link, Route,Routes } from 'react-router-dom'; import Nav from './component/nav/Nav'; import Home from './component/home/Home'; import React, { useContext, useState ,useEffect ,createContext} from 'react'; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import Quess from './component/question/Quess'; import Profile from './component/profile/Profile'; import Raters from './component/raters/Raters'; import RaterAnswer from './component/raters-answers/raterAnswer'; export const AppContext=createContext() function App() { const [login,setLogin] =useState(false) const [token,setToken] =useState("") const [userName,setUserName] =useState("") const [loader ,setLoader] =useState(false) const [route ,setRoute]=useState("https://n-m-nstty.onrender.com/api/v1") const [data,setData] =useState("sayed") useEffect(()=>{ if(localStorage.getItem("login")){ setLogin(true) } },[login]) return ( <AppContext.Provider value={{ route, setRoute, userName, setUserName, login, setLogin , token, setToken , loader, setLoader , data }}> <div className="App"> <ToastContainer /> {loader ? <div className="spin-cont"><div className="spinner"> <div className="rect1"></div> <div className="rect2"></div> <div className="rect3"></div> <div className="rect4"></div> <div className="rect5"></div> </div></div>:null} <Nav /> <Routes> <Route path="/" element={<Home />} /> <Route path="/ques" element={<Quess/>}/> <Route path="/raters" element={<Raters/>}/> <Route path="/profile" element={<Profile/>}/> <Route path="/rater-answer" element={<RaterAnswer/>}/> <Route path="/raters/:raterEmail/:raterCode" element={<RaterAnswer/>}/> </Routes> </div> </AppContext.Provider> ); } export default App;
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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 3 of the License, or (at your option) any later version. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "createvirtualclusterresponse.h" #include "createvirtualclusterresponse_p.h" #include <QDebug> #include <QNetworkReply> #include <QXmlStreamReader> namespace QtAws { namespace EMRContainers { /*! * \class QtAws::EMRContainers::CreateVirtualClusterResponse * \brief The CreateVirtualClusterResponse class provides an interace for EMRContainers CreateVirtualCluster responses. * * \inmodule QtAwsEMRContainers * * Amazon EMR on EKS provides a deployment option for Amazon EMR that allows you to run open-source big data frameworks on * Amazon Elastic Kubernetes Service (Amazon EKS). With this deployment option, you can focus on running analytics * workloads while Amazon EMR on EKS builds, configures, and manages containers for open-source applications. For more * information about Amazon EMR on EKS concepts and tasks, see <a * href="https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/emr-eks.html">What is Amazon EMR on * * EKS</a>> * * <i>Amazon EMR containers</i> is the API name for Amazon EMR on EKS. The <code>emr-containers</code> prefix is used in * the following scenarios: * * </p <ul> <li> * * It is the prefix in the CLI commands for Amazon EMR on EKS. For example, <code>aws emr-containers * * start-job-run</code>> </li> <li> * * It is the prefix before IAM policy actions for Amazon EMR on EKS. For example, <code>"Action": [ * "emr-containers:StartJobRun"]</code>. For more information, see <a * href="https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies-actions">Policy * actions for Amazon EMR on * * EKS</a>> </li> <li> * * It is the prefix used in Amazon EMR on EKS service endpoints. For example, * <code>emr-containers.us-east-2.amazonaws.com</code>. For more information, see <a * href="https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/service-quotas.html#service-endpoints">Amazon * EMR on EKS Service * * \sa EMRContainersClient::createVirtualCluster */ /*! * Constructs a CreateVirtualClusterResponse object for \a reply to \a request, with parent \a parent. */ CreateVirtualClusterResponse::CreateVirtualClusterResponse( const CreateVirtualClusterRequest &request, QNetworkReply * const reply, QObject * const parent) : EMRContainersResponse(new CreateVirtualClusterResponsePrivate(this), parent) { setRequest(new CreateVirtualClusterRequest(request)); setReply(reply); } /*! * \reimp */ const CreateVirtualClusterRequest * CreateVirtualClusterResponse::request() const { Q_D(const CreateVirtualClusterResponse); return static_cast<const CreateVirtualClusterRequest *>(d->request); } /*! * \reimp * Parses a successful EMRContainers CreateVirtualCluster \a response. */ void CreateVirtualClusterResponse::parseSuccess(QIODevice &response) { //Q_D(CreateVirtualClusterResponse); QXmlStreamReader xml(&response); /// @todo } /*! * \class QtAws::EMRContainers::CreateVirtualClusterResponsePrivate * \brief The CreateVirtualClusterResponsePrivate class provides private implementation for CreateVirtualClusterResponse. * \internal * * \inmodule QtAwsEMRContainers */ /*! * Constructs a CreateVirtualClusterResponsePrivate object with public implementation \a q. */ CreateVirtualClusterResponsePrivate::CreateVirtualClusterResponsePrivate( CreateVirtualClusterResponse * const q) : EMRContainersResponsePrivate(q) { } /*! * Parses a EMRContainers CreateVirtualCluster response element from \a xml. */ void CreateVirtualClusterResponsePrivate::parseCreateVirtualClusterResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("CreateVirtualClusterResponse")); Q_UNUSED(xml) ///< @todo } } // namespace EMRContainers } // namespace QtAws
module registerFile # ( parameter REG_DEPTH = 32, parameter REG_WIDTH = 32, parameter RADDR_WIDTH = 5 )( // inputs input clk, input rst, input we, // write enable input [RADDR_WIDTH-1:0] rs1_addr, input [RADDR_WIDTH-1:0] rs2_addr, input [RADDR_WIDTH-1:0] rd_addr, input [REG_WIDTH-1:0] rd_value, output [REG_WIDTH-1:0] rs1_value, // this are set in blocking mode output [REG_WIDTH-1:0] rs2_value ); reg [REG_WIDTH-1:0] bank [REG_DEPTH-1:0]; //reset logic always @ (posedge clk or posedge rst) begin if (rst) begin for (integer i = 0; i < REG_DEPTH; i = i + 1) begin bank[i] <= 0; end end end // write enable logic always @(posedge clk or posedge rst) begin if (we && (~rst)) begin if ( (0 < rd_addr) && (rd_addr < REG_DEPTH) ) begin bank[rd_addr] <= rd_value; end end end // Read assignment statement assign rs1_value = (~rst && |rs1_addr) ? bank[rs1_addr] : 0; assign rs2_value = (~rst && |rs2_addr) ? bank[rs2_addr] : 0; endmodule
import numpy as np from utils.features import prepare_for_training class LinearRegression: """ 1. pre-process the raw data 2. get the number of features 3. initialise the theta matrix """ def __init__(self, data, labels,polynomial_degree,sinudsoid_degree, normalize_data = True): (processed_data, features_mean, features_deviation) = \ prepare_for_training(data,polynomial_degree,sinudsoid_degree,normalize_data = True) self.data = processed_data self.labels = labels self.features_mean = features_mean self.features_deviation = features_deviation self.polynomial_degree = polynomial_degree self.sinusoid_degree = sinudsoid_degree self.normalise_data = normalize_data features_num = self.data.shape[1] # shape[1]: How many columns in the data self.theta = np.zeros((features_num,1)) # initialise a matrix, column 1, line features_num def train(self,alpha,num_iterations = 500): cost_history = self.gradient_descent(alpha, num_iterations) return self.theta, cost_history def gradient_descent (self,alpha, num_iterations = 500): cost_history = [] for _ in range (num_iterations): self.gradient_step(alpha) cost_history.append(self.loss_function(self.data,self.labels)) return cost_history def gradient_step(self,alpha): """ Matrix operations, update parameter theta """ num_examples = self.data.shape[0] prediction = LinearRegression.hypothesis(self.data, self.theta) delta = prediction - self.labels theta = self.theta """ new theta """ theta = theta - alpha * (1/num_examples) * (np.dot(delta.T,self.data)).T self.theta = theta def loss_function(self,data,labels): num_examples = data.shape[0] delta = LinearRegression.hypothesis(self.data,self.theta) - labels cost = (1/2) * np.dot(delta.T, delta) / num_examples return cost[0][0] @staticmethod def hypothesis(data,theta): prediction = np.dot(data,theta) return prediction def get_cost(self,data,labels): processed_data = prepare_for_training \ (data, self.polynomial_degree, self.sinusoid_degree, self.normalise_data)[0] return self.loss_function(processed_data,labels) def predict(self,data): """ To predict based on the trained models, testifying our model """ processed_data = prepare_for_training \ (data, self.polynomial_degree, self.sinusoid_degree, self.normalise_data)[0] predictions = LinearRegression.hypothesis(processed_data, self.theta) return predictions
import { useState } from "react"; import toast from "react-hot-toast"; const Form = ({ BASE_URL }) => { const [input, setInput] = useState({ name: "", email: "", }); const handleInput = (e) => { const name = e.target.name; const value = e.target.value; setInput({ ...input, [name]: value }); }; const submitData = async () => { try { const { name, email } = input; if (!(name && email)) { return toast.error("Empty fields are not allowed"); } const regEx = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g; if (!regEx.test(email)) { return toast.error("Invalid email"); } const res = await fetch(`${BASE_URL}/create`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ name, email }), }); const data = await res.json(); console.log(data); if (data.success) { toast.success("User Info created successfully"); } } catch (error) { toast.error(error.message); console.log(error.message); } }; const handleSubmit = async (e) => { e.preventDefault(); submitData(); setInput({ name: "", email: "" }); }; return ( <form> <section className="text-gray-600 body-font relative"> <div className="container px-5 py-8 mx-auto"> <div className="flex flex-col text-center w-full mb-6"> <h1 className="sm:text-3xl text-2xl font-medium title-font text-gray-900"> Create User </h1> </div> <div className="lg:w-1/2 md:w-2/3 mx-auto"> <div className="flex flex-wrap -m-2"> <div className="p-2 w-1/2"> <div className="relative"> <label htmlFor="name" className="leading-7 text-sm text-gray-600" > Name </label> <input type="text" id="name" name="name" value={input.name} className="w-full bg-gray-100 bg-opacity-50 rounded border border-gray-300 focus:border-indigo-500 focus:bg-white focus:ring-2 focus:ring-indigo-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out" onChange={handleInput} required /> </div> </div> <div className="p-2 w-1/2"> <div className="relative"> <label htmlFor="email" className="leading-7 text-sm text-gray-600" > Email </label> <input type="email" id="email" name="email" value={input.email} className="w-full bg-gray-100 bg-opacity-50 rounded border border-gray-300 focus:border-indigo-500 focus:bg-white focus:ring-2 focus:ring-indigo-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out" onChange={handleInput} required /> </div> </div> <div className="p-2 w-full"> <button type="submit" className="flex mx-auto text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-none hover:bg-indigo-600 rounded text-lg" onClick={handleSubmit} > Submit </button> </div> </div> </div> </div> </section> </form> ); }; export default Form;
package com.snackgame.server.applegame.controller; import java.util.List; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.snackgame.server.applegame.business.AppleGameService; import com.snackgame.server.applegame.business.domain.AppleGame; import com.snackgame.server.applegame.controller.dto.AppleGameResponse; import com.snackgame.server.applegame.controller.dto.CoordinateRequest; import com.snackgame.server.applegame.controller.dto.MoveRequest; import com.snackgame.server.member.business.domain.Member; import io.swagger.v3.oas.annotations.Operation; import lombok.RequiredArgsConstructor; @RestController @RequiredArgsConstructor public class AppleGameController { private final AppleGameService appleGameService; @Operation(summary = "게임 세션 시작", description = "1번 게임(사과게임) 세션을 시작한다") @PostMapping("/games/1") public AppleGameResponse startGameFor(Member member) { AppleGame game = appleGameService.startGameOf(member); return AppleGameResponse.of(game); } @Operation(summary = "세션에 수 삽입", description = "지정한 세션에 수들을 삽입한다") @PutMapping("/sessions/{sessionId}/moves") public void placeMoves(Member member, @PathVariable Long sessionId, @RequestBody List<MoveRequest> moves) { appleGameService.placeMoves(member, sessionId, moves); } @Operation(summary = "게임판 초기화", description = "지정한 세션의 게임판을 초기화한다. 황금사과와는 별도의 기능이다.") @DeleteMapping("/sessions/{sessionId}/board") public AppleGameResponse resetBoard(Member member, @PathVariable Long sessionId) { AppleGame game = appleGameService.resetBoard(member, sessionId); return AppleGameResponse.of(game); } @Operation(summary = "게임 세션 종료", description = "현재 세션의 종료를 알린다") @PutMapping("/sessions/{sessionId}/end") public void endSession(Member member, @PathVariable Long sessionId) { appleGameService.endSession(member, sessionId); } }
from .resources import UserDB from .crypto import PasswordHash, TokenHandler from chalice.app import UnauthorizedError from secrets import compare_digest class Users: def __init__(self, user_db: UserDB) -> None: self._user_db = user_db # TODO: customize from config self._password_hash = PasswordHash() self._token_handler = TokenHandler("b1b36d29-18ac-4671-a9c6-59b5ecedecca") def register_user(self, email: str, password: str): derived_key, salt = self._password_hash.derive_key(password) self._user_db.add_user(email, derived_key, salt) # TODO: catch user exists error def authenticate(self, email: str, password: str): user = self._user_db.get_user(email) derived_key, _ = self._password_hash.derive_key(password, bytes(user["salt"])) if not compare_digest(derived_key, bytes(user["passcode"])): raise UnauthorizedError() claims = { "sub": email } access_token = self._token_handler.generate(claims, 60) # TODO: add refresh_code as well return {"email": email, "access_token": access_token} def change_password(self, email:str, password: str, new_password: str): user = self._user_db.get_user(email) derived_key, _ = self._password_hash.derive_key(password, bytes(user["salt"])) if not compare_digest(derived_key, bytes(user["passcode"])): raise UnauthorizedError() derived_key, salt = self._password_hash.derive_key(new_password) self._user_db.update_user_crendentials(email, derived_key, salt) def verify_token(self, token: str): if token.startswith("Bearer "): token = token[len("Bearer "):] return self._token_handler.verify(token)
import React from "react"; import PropTypes from "prop-types"; const ErrorAlert = ({ errors = [], close }) => { return errors.length ? ( <div className="alert alert-danger alert-dismissible"> <button className="close" data-dismiss="alert" onClick={close}> &times; </button> <h4>Ooops..</h4> <ul> {errors.map((err) => ( <li key={err.message}>{err.message}</li> ))} </ul> </div> ) : null; }; ErrorAlert.propTypes = { errors: PropTypes.arrayOf( PropTypes.shape({ message: PropTypes.string.isRequired, }) ).isRequired, close: PropTypes.func.isRequired, }; export default ErrorAlert;
import React from "react"; import { MdCheckCircle, MdError, MdLink } from "react-icons/md"; import { CircularProgressbar }from "react-circular-progressbar"; import { Container, FileInfo } from "./styles"; import { faFilePdf, } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; const FileListPdf = ({ files, onDelete }) => ( <Container> {files.map(uploadedFile => ( <li key={uploadedFile.key}> <FileInfo> <FontAwesomeIcon icon={faFilePdf} style={{ color: "#e83f3f", fontSize: "1.85em", }} /> <div> <strong>{uploadedFile.pdf_name}</strong> <span> {uploadedFile.readableSize}{" "} {!!uploadedFile.url && ( <button onClick={() => onDelete(uploadedFile.key)}> Excluir </button> )} </span> </div> </FileInfo> <div> {!uploadedFile.uploaded && !uploadedFile.error && ( <CircularProgressbar styles={{ root: { width: 24 }, path: { stroke: "#7159c1" } }} strokeWidth={10} percentage={uploadedFile.progress} /> )} {uploadedFile.url && ( <a href={uploadedFile.url} target="_blank" rel="noopener noreferrer" > <MdLink style={{ marginRight: 8 }} size={24} color="#222" /> </a> )} {uploadedFile.uploaded && <MdCheckCircle size={24} color="#78e5d5" />} {uploadedFile.error && <div id="erroupload"> <MdError size={24} color="#e57878" /> <p>arquivo maior 2MB ou você não tem autorização</p> </div> } </div> </li> ))} </Container> ); export default FileListPdf;
import { KeyboardEvent, MouseEvent, RefObject } from 'react'; import SyntaxHighlighter from 'react-syntax-highlighter'; import { nightOwl } from 'react-syntax-highlighter/dist/cjs/styles/hljs'; import { IExampleStep } from '../interfaces/example-step.interface'; interface CodeBlockProps { step: IExampleStep; containerRef: RefObject<HTMLDivElement>; } export const CodeBlock = (props: CodeBlockProps) => { const handleScrolling = () => { const block = document.getElementById(`block-${props.step.id}`); if (block) { block.scrollIntoView({ behavior: 'smooth', block: 'start' }); } else { props.containerRef.current?.scrollTo({ behavior: 'smooth', top: 0 }); } }; const handleOnClick = (e: MouseEvent<HTMLDivElement>) => { handleScrolling(); (e.target as any).blur(); }; const handleOnKeyPress = (event: KeyboardEvent<HTMLDivElement>) => { event.preventDefault(); if (event.key === 'Enter' || event.key === ' ') { handleScrolling(); } }; return ( <div className="block border-transparent border-2 rounded mb-2 transition-all select-all cursor-pointer hover:border-slate-700 hover:bg-slate-700 hover:shadow-inner hover:shadow-slate-700 hover:scale-[1.02] focus:border-slate-700 focus:bg-slate-700 focus:shadow-inner focus:shadow-slate-700 focus:scale-[1.02] active:cursor-text" title={props.step.title} tabIndex={0} onClick={handleOnClick} onKeyPress={handleOnKeyPress} > <SyntaxHighlighter language="javascript" style={nightOwl} wrapLongLines={true} customStyle={{ background: 'transparent', pointerEvents: 'none', }} > {props.step.code} </SyntaxHighlighter> </div> ); };
// Copyright (c) 2006 IBM. All rights reserved. // Xen_ComputerSystemSettingData [Provider ("cmpi:Xen_VirtualSystemSettingData"), Description ( "A class derived from CIM_VirtualSystemSettingData to " "represent the current and/or recorded virtualization aspects of " "a XenServer virtual machine, template or a snapshot. A virtual system can be of " "'PV' or 'XenServer paravirtualized' type or 'HVM' or 'hardware virtualized' " "type. Some of the properties in this class apply to one or the other type. " "Specifically, ones that start with 'PV_' apply to paravirtualized " "virtual systems and ones that start with 'HVM_' to hardware virtualized " "These properties are mutually exclusive.")] class Xen_VirtualSystemSettingData : CIM_VirtualSystemSettingData { [Description ("The Version strings of the Operating System installed on the " "Virtual System. This information is only available if the tools have been run once.")] string OS_Version[]; [Description ("Bootloader used to extract kernel for booting. " "Ex: 'pygrub'. If Bootloader is specified, values " "contained in PV_Kernel and PV_RAMDisk will be ignored. ")] string PV_Bootloader; [Description ("Options to pass to the bootloader specified in " "'PV_Bootloader' property.")] string PV_Bootloader_Args; [Description ("Path to the kernel image.")] string PV_Kernel; [Description ("Command line options to pass to the kernel. ")] string PV_Args; [Description ("Legacy command line options to pass to the kernel. ")] string PV_Legacy_Args; [Description ("Path to a paravirtualized ramdisk image to boot from.")] string PV_RAMDisk; [Description ("String representing any boot-time policies. " "Eg: 'BIOS order' to specify that the VM will boot using the device " "order specified in the bios.")] string HVM_Boot_Policy; [Description ("Parameters to pass to the HVM bootloader. " "Eg: 'order=dcn' to specify boot order in " "'CD/harddrive/network' order.")] string HVM_Boot_Params[]; [Description ("Specify the Shadow multiplier. Defaults to 1.0.")] real64 HVM_ShadowMultiplier; [Description ("This property consists of all BIOS platform " "related VM settings. E.g. apic=true viridian=true usb=false " "Possible Values include: " "apic (Enable/disable virtual APIC in the virtual machine); " "acpi (Enable/disable virtual ACPI in the virtual machine); " "pae (Enable/disable PAE in virtual machine); " "usb (If \"true\", emulate USB controller in virtual machine); " "usbdevice (Specifies type of emulated USB device to add eg:\"mouse\" or \"tablet\"); " "localtime (Specify whether virtual machine expects virtual hardware clock to be in local time or UTC); " "stdvga (Specify emulation of standard VGA instead of cirrus logic); " "nx (Enable/disable nx (DEP) support in virtual machine); " "viridian (Enable/disable viridian support in virtual machine).")] string Platform[]; [Description ("This is a property bag of random data " " associated with the VM." " This property corresponds to the 'other-config' setting under xen.")] string Other_Config[]; [Description ("This is a property bag of" " random configuration data for the VM. The VM could use this " " data during boot time.")] string Xenstore_Data[]; [Description ("This property contains the WEBM URI for the object's parent. " "The parent could be a snapshot, a template or a vm.")] string Parent; [Description ("This property contains an array of the WEBM URIs " "for the object's children. The chilren could be snapshots or vms.")] string Children[]; }; [Provider ("cmpi:Xen_ComputerSystemSettingData"), Description ( "A class derived from Xen_VirtualSystemSettingData to " "represent the active settings of a XenServer virtual machine or snapshot.")] class Xen_ComputerSystemActiveSettings : Xen_VirtualSystemSettingData { [Description ("The Version strings of the XenServer paravirtualization " "drivers and services (tools) installed in the Virtual System. This includes " "versions of the individual drivers (block/net) and the overall version " "of the toolset. This information is only available if the tools have been run once.")] string PV_Drivers_Version[]; [Description ("A Boolean indicating if the XenServer paravirtualization " "drivers (tools) installed in the Virtual System are up to date or not.")] Boolean PV_Drivers_UpToDate; }; [Provider ("cmpi:Xen_ComputerSystemSettingData"), Description ( "A class derived from Xen_VirtualSystemSettingData to " "represent the active virtualization settings of " "a XenServer virtual machine.")] class Xen_ComputerSystemSettingData : Xen_ComputerSystemActiveSettings { [Description("Time when this VM was first started.")] dateTime StartTime; [Description("The XenServer host that this VM is currently running on (if running).")] string Host; [Description("The XenServer host this virtual machine is closely associated with. This " "could be due to a number of reasons: For Eg: If the VM's disk " "image file is located on the host from a previous instantiation, " "then the next instantiation is going to be on the same host.")] string HostAffinity; [Description("The remaining slots available on the VM's Xen" " block device bus to add a virtual block device on.")] string AvailableBlockDeviceSlots; [Description("The remaining slots available on the VM's Xen" " network interface device bus to add a virtual NIC on.")] string AvailableNetworkInterfaceSlots; [Description ("A Boolean indicating if the XenServer paravirtualization " "drivers (tools) installed in the Virtual System are running. This implies the " "Virtual System has been issued a 'Start'.")] Boolean Xen_Tools_AreRunning; }; [Provider ("cmpi:Xen_ComputerSystemTemplate"), Description ( "A class derived from Xen_VirtualSystemSettingData to " "represent the recorded virtualization settings " "(a.k.a template) of a XenServer virtual machine. This can be used to " "serve as the reference configuration prior to creation of new VMs.")] class Xen_ComputerSystemTemplate : Xen_VirtualSystemSettingData { }; [Provider ("cmpi:Xen_ComputerSystemSnapshot"), Description ( "A class derived from Xen_VirtualSystemSettingData to " "represent the virtualization settings " "of a XenServer virtual machine snapshot. This represents a point-in-time " "setting for the VM.")] class Xen_ComputerSystemSnapshot : Xen_ComputerSystemActiveSettings { [Description("The Xen_ComputerSystem instance this is a snapshot of.")] string SnapshotOf; [Description("Time at which the snapshot was taken.")] dateTime SnapshotTime; };
import { useRouter } from 'next/router'; import { Button } from '~/components/ui/button'; import React from 'react'; import { useGetTodo } from '~/api/hooks/useGetTodo'; import {ChevronLeft} from "lucide-react"; import useDeleteTodo from "~/api/hooks/useDeleteTodo"; export default function TodoDetailPage() { const router = useRouter(); const { todoId } = router.query; const [todo, query] = useGetTodo(+(todoId ?? 0)); const [deleteTodo] = useDeleteTodo() const handleDelete = async () => { try { if (todo) { deleteTodo({ id: todo.id, body: {} }); router.push('/todo'); } } catch (error) { console.error('Failed to delete todo:', error); } }; if (query.isPending) return <h1>Loading...</h1>; if (query.error) return <h1>ERROR: {query.error.message}</h1>; return ( <div className='mx-auto max-w-screen-sm mt-10'> <Button variant='outline' size='icon' className='w-11 h-7 mb-3' onClick={() => router.push('/todo')}> <ChevronLeft className='h-5 w-5' /> </Button> <h1 className='mb-4'>Детали задачи</h1> <div className=' flex-col justify-between border border-gray-500 border-solid rounded-lg p-2'> <div className='flex items-center justify-between max-w-screen-sm mb-4'> <label className='text-xl'>{todo?.title}</label> </div> <div className='text-black italic'> <p>Описание:</p> <span>{todo?.description}</span> </div> <div className='flex justify-between items-center text-black text-sm mt-3'> <Button onClick={handleDelete}>Удалить задачу</Button> <div> <p className='bg-amber-400 border-solid rounded-lg pl-1 pr-1'>Deadline: {todo?.deadline}</p> <p className="bg-blue-400 border-solid rounded-lg pl-1 pr-1 mt-2">Created: {todo?.created}</p> </div> </div> </div> </div> ); }
package api.commands; import api.Command; import api.shared.ResponseHandler; import com.arangodb.entity.BaseDocument; import com.arangodb.entity.CollectionEntity; import com.arangodb.entity.DocumentCreateEntity; import com.arangodb.entity.DocumentUpdateEntity; import config.STATUSCODES; import db.ArangoConfig; import db.PostgresConfig; import models.nosql.BlockedUser; import org.json.JSONObject; import java.util.ArrayList; import java.util.LinkedHashMap; public class BlockUser extends Command { @Override public void execute() { try{ boolean checkIfCollectionExists = ArangoConfig.arangoDatabase.collection("BlockedUsers").exists(); if(!checkIfCollectionExists){ CollectionEntity myArangoCollection=ArangoConfig.arangoDatabase.createCollection("BlockedUsers"); System.out.println("New collection created: " + myArangoCollection.getName()); } JSONObject responseObject = new JSONObject(); String checkKey = map.get("_key"); String checkId = map.get("_id"); String checkUserId = map.get("user_id"); String checkBlockedUserId = map.get("blocked_id"); dbConn = PostgresConfig.getDataSource().getConnection(); func = dbConn.prepareStatement("SELECT * FROM get_account(?);"); func.setInt(1, Integer.parseInt(checkBlockedUserId)); set = func.executeQuery(); JSONObject retrievedUser = new JSONObject(); boolean flag = false; while(set.next()) { retrievedUser.put("user_name", set.getString(1)); retrievedUser.put("user_id", checkBlockedUserId); flag = true; } if(!flag){ // retrievedUser.add("error","no accounts found"); // throw new Exception("No accounts found"); ResponseHandler.handleError("No accounts found", STATUSCODES.ENTITYNOTFOUND, map.get("queue"), map.get("correlation_id")); return; } set.close(); func.close(); if(checkKey!=null){ BaseDocument myDocument = ArangoConfig.arangoDatabase.collection("BlockedUsers").getDocument(checkKey, BaseDocument.class); if(myDocument!=null){ System.out.println(myDocument.getProperties()); }else{ System.out.println("There is no objects with _key: "+checkKey); } }else{ if(checkId!=null){ }else{ if(checkUserId!=null && checkBlockedUserId!=null){ // String query = "FOR t IN BlockedUsers FILTER t.UserID == @user_id RETURN t"; // Map<String, Object> bindVars = new MapBuilder().put("user_id", checkUserId).get(); // ArangoCursor<BaseDocument> cursor = ArangoConfig.arangoDatabase.query(query, bindVars, null, // BaseDocument.class); // List<BaseDocument> result = cursor.asListRemaining(); BaseDocument result = ArangoConfig.arangoDatabase.collection("BlockedUsers").getDocument(checkUserId, BaseDocument.class); if(result==null){ BaseDocument toBeInserted = new BaseDocument(); toBeInserted.addAttribute("user_id",checkUserId); ArrayList<BlockedUser> tempArray = new ArrayList<BlockedUser>(); tempArray.add(new BlockedUser(retrievedUser.getString("user_id"),retrievedUser.getString("user_name"))); toBeInserted.addAttribute("blocked_users",tempArray); toBeInserted.setKey(checkUserId); DocumentCreateEntity newDocumentInsertion = ArangoConfig.arangoDatabase.collection("BlockedUsers").insertDocument(toBeInserted); System.out.println("Document inserted"); // responseObject.put("status","200 OK"); responseObject.put("message","User blocked successfully !!"); }else{ ArrayList<Object> blockedUsersArray = (ArrayList<Object>) result.getAttribute("blocked_users"); boolean alreadyBlockedFlag = false; ArrayList<BlockedUser> newBlockedArray = new ArrayList<BlockedUser>(); for(Object singleBlockedObj:blockedUsersArray){ LinkedHashMap castedObject = (LinkedHashMap) singleBlockedObj; if(castedObject.get("user_id").equals(checkBlockedUserId)){ alreadyBlockedFlag =true; break; }else{ BlockedUser newObj = new BlockedUser(castedObject.get("user_id").toString(),castedObject.get("user_name").toString()); newBlockedArray.add(newObj); } } if(alreadyBlockedFlag){ // responseObject.put("status","error"); // responseObject.put("message","blocked_id is already blocked"); ResponseHandler.handleError("blocked_id is already blocked", STATUSCODES.ENTITYNOTFOUND, map.get("queue"), map.get("correlation_id")); return; }else{ newBlockedArray.add(new BlockedUser(retrievedUser.getString("user_id"),retrievedUser.getString("user_name"))); BaseDocument updateBody = new BaseDocument(); updateBody.addAttribute("blocked_users",newBlockedArray); DocumentUpdateEntity<BaseDocument> newDocumentInsertion = ArangoConfig.arangoDatabase.collection("BlockedUsers").updateDocument(result.getKey(), updateBody); System.out.print(newDocumentInsertion.getNew()); // responseObject.put("status","200 OK"); responseObject.put("message","User blocked successfully !!"); } } } } } ResponseHandler.handleResponse(responseObject.toString(),map.get("queue"),map.get("correlation_id")); } catch(Exception e){ System.out.println(e.toString()); System.out.println(e.getStackTrace()[0].getLineNumber()); JSONObject result = new JSONObject(); // result.put("error","An exception has occurred"); // ResponseHandler.handleResponse(result.toString(), map.get("queue"), map.get("correlation_id")); ResponseHandler.handleError("An exception has occurred", STATUSCODES.UNKNOWN, map.get("queue"), map.get("correlation_id")); return; } } }
import React, { useState } from 'react'; import { Modal, Button, Input, Select, Tooltip, Upload, Progress, Message, Table } from '@arco-design/web-react'; import IconXlsx from '@assets/xlsx.svg'; import cn from 'classnames'; import { RD_BASE_URL } from '@config'; import { getBatchImportFile, companyMemeberImport } from '@services/company'; import IconNoFile from '@assets/no_file.svg'; import { useTranslation } from 'react-i18next'; import './index.less'; import { debounce, isArray, isNumber, isPlainObject, isString } from 'lodash'; const Option = Select.Option; const BatchImport = (props) => { const { onCancel, initMemberList } = props; const [step, setStep] = useState('upload_file'); // upload_file | import_data | success const [successInfo, setSuccessInfo] = useState({}); const [import_err_desc, setImport_err_desc] = useState([]); const [file, setFile] = useState(null); const [percent, setPercent] = useState(0); const { t } = useTranslation(); const onSelectFile = (files) => { if (isArray(files) && files.length > 0 && files[0]?.originFile instanceof File) { setFile(files[0]?.originFile); } return false; }; // const onReupload = (files) => { // return false; // }; const viewErrorReport = () => { const columns = [ { title: t('text.account'), dataIndex: 'account', ellipsis: true }, { title: t('text.err_msg'), dataIndex: 'err_msg', ellipsis: true }, ]; Modal.confirm({ title: t('text.err_report'), className: "runnerGo-view-error-report-modal", style: { width: '900px', height: '640px', padding: '0px', }, content: <div className='info'> {/* <div className='lable'>{t('text.err_report')}</div> */} <Table pagination={false} ellipsis={true} borderCell={true} columns={columns} data={import_err_desc || []} /> </div>, closable: true, icon: null, onOk: () => { return new Promise((resolve, reject) => { updateUserData('password', '').then(data => resolve()).catch(err => reject()) }) }, }); } const renderContent = () => { switch (step) { case 'upload_file': // 选中文件 if (file != null && file instanceof File) { return <div className="content select-file"> <div className="svg"> <IconXlsx /> </div> <div className="support-text"> {file?.name} <span className='size'>{`(${isNumber(file?.size) ? (file.size / 1024).toFixed(2) : '-'}k)`}</span> </div> <Upload fileList={[]} showUploadList={false} onChange={onSelectFile} autoUpload={false} accept=".xls,.xlsx"> <Button type='outline' onClick={(e) => { e.stopPropagation(); setFile(null) }}>{t('text.reselect')}</Button> </Upload> </div> } else { return <div className="content"> <div className="left"> <div className="title">{t('text.upload_file_text')}</div> <div className="svg"> <IconXlsx /> </div> <div className="support-text"></div> <Button type='outline'> <a href={'/xlsx/RunnerGo创建成员批量导入模板.xlsx'} target="_blank" rel="nofollow noreferrer"> {t('text.download_template')} </a> </Button> </div> <div className="line"></div> <div className="right"> <div className="title">{t('text.upload_file_after_text')}</div> <div className="svg"> <IconNoFile /> </div> <div className="support-text"> {t('text.support_files')} </div> <Upload fileList={[]} showUploadList={false} onChange={onSelectFile} autoUpload={false} accept=".xls,.xlsx"> <Button type='outline' onClick={() => console.log('')}>{t('text.upload_file')}</Button> </Upload> </div> </div> } break; case 'import_data': return ( <> <div className='progress'> <Progress color='var(--theme-color)' size='large' type='circle' percent={percent} style={{ color: "var(--theme-color)" }} /> </div> <div className='progress-text'>{t('text.importing')}...</div> </> ) break; case 'success': return ( <> <div className='progress'> <Progress size='large' type='circle' percent={100} style={{ color: "var(--theme-color)" }} /> </div> <div className='progress-text'>{t('message.importSuccess')}</div> <div className='progress-text' style={{ marginTop: '10px' }}>{t('message.importSuccess')}{successInfo?.success_num || '0'}{t('text.article')},{t('text.import_failure')}{successInfo?.fail_num || '0'}{t('text.article')} </div> {isString(successInfo?.path) && successInfo.path.length > 0 && (<div className='progress-text'> {t('text.please_check')}<Button onClick={()=>{}} style={{ color: 'var(--theme-color)' }} type='text'><a href={`${RD_BASE_URL}${successInfo.path}`}>{t('text.err_report')}</a></Button>,{t('text.modify_import_again')}</div>)} </> ) break; default: break; } } const importFile = debounce(async () => { if (file == null) { Message.error(t('text.upload_file_befort_import')) return; } if (step == 'success') { setStep('upload_file'); setFile(null); return; } setStep('import_data'); let company_id = localStorage.getItem('company_id'); try { const resp = await companyMemeberImport({ company_id, file: file }, (progressEvent) => { const temp_percent = parseInt((progressEvent.loaded / progressEvent.total) * 100); setPercent(temp_percent); }) if (resp?.code == 0 && isPlainObject(resp?.data)) { // 上传成功 setSuccessInfo(resp?.data); setImport_err_desc(resp?.data?.import_err_desc || []); if (resp?.data?.success_num > 0) { initMemberList && initMemberList(); } setStep('success'); } } catch (error) { setStep('upload_file'); } }, 200) return ( <> <Modal title={t('text.batch_import')} className="runnerGo-batch-import-modal" visible onOk={() => onCancel()} onCancel={onCancel} autoFocus={false} focusLock={true} footer={ <> <Button className='btn-close' onClick={() => { if (step == 'success') { importFile(); } else { onCancel(); } }} > {step == 'success' ? t('text.continue_import') : t('btn.close')} </Button> <Button onClick={() => { if (step == 'success') { onCancel(); } else { importFile(); } }} > {step == 'success' ? t('text.complete') : t('text.import')} </Button> </> } style={{ width: 800, height: 416 }} > <div className="step"> <div className={cn('step-number', { active: step == 'upload_file' })}>1</div> <label htmlFor="">{t('text.upload_file')}</label> <div className="line"></div> <div className={cn('step-number', { active: step == 'import_data' })}>2</div> <label htmlFor="">{t('text.import_data')}</label> <div className="line"></div> <div className={cn('step-number', { active: step == 'success' })}>3</div> <label htmlFor="">{t('text.complete')}</label> </div> {renderContent()} </Modal > </> ) }; export default BatchImport;
# 강화학습 강화란 좋은 행동을 점점 더 많이 하는 것 강화학습이란 에이전트가 환경과 직접 상호작용하며 환경이 주는 정보인 보상을 통해 어떤 행동을 해야 더 많은 보상을 얻을 수 있을지 학습하는 것 ![강화학습](./image/rl-basic1.png) 강화학습은 순차적으로 행동을 결정해야 하는 문제에서 사용할 수 있다. 강화학습을 하기 위해서 순차적 행동 결정 문제를 수학적으로 정의해야 한다. 이 때 사용하는 것이 Markov Decision Process # MDP (Markov Decision Process) MDP는 순차적 행동 결정 문제를 수학적으로 표현한 것으로 상태, 행동, 보상 함수, 상태 변환 확률, 할인율로 구성된다. ### 상태 (State) S는 에이전트가 관찰 가능한 상태의 집합 ### 행동 (Action) 에이전트가 상태 St에서 할 수 있는 행동의 집합 A ### 보상함수 (Reward) 에이전트가 학습할 수 있는 유일한 정보로서 에이전트가 어떤 상태에서 어떤 행동을 했을 때 환경이 에이전트에게 주는 정보 ### 상태 변환 확률 (state transition probability) 어떤 상태 s에서 행동 a를 했을 때 다음 상태 s’에 도달할 확률 보상과 마찬가지로 환경의 일부이다. ### 할인율 현재에 가까운 보상을 더 가치 있는 것으로 판단하기 위해 미래의 보상일수록 가치를 낮춰주는 비율 ## 예시) 그리드월드 강화학습을 가장 쉽고 간단히 구현하는 방법으로 길찾기 문제를 만들 수 있다. 아래의 그리드 월드에서는 각 행동을 했을 때 100퍼센트 다음 칸으로 이동하기 때문에 상태 변환 확률은 구현하지 않았다. ``` import numpy as np # state state = [[0 for _ in range(5)] for _ in range(5)] start_state = state[0][0] # action (상, 하, 좌, 우) A = [[-1, 0], [1, 0], [0, -1], [0, 1]] # reward rwd = [[0. for _ in range(5)] for _ in range(5)] rwd[1][2] = -1 rwd[2][1] = -1 rwd[2][2] = 1 # discount factor df = 0.9 ``` ## 에이전트 MDP로 표현한 환경에서 에이전트는 두 가지 요소를 바탕으로 보상을 최대화한다. ### 정책 정책은 모든 상태에 대해 각각의 상태에서 어떤 행동을 할지 정의한 것 ### 가치함수 ![가치함수](./image/rl-basic2.png) 어떤 상태 혹은 행동이 얼마나 좋은지 나타내는 함수 앞으로 받을 보상을 추정하여 현재 상태 혹은 행동의 가치를 추정한다. - 상태 가치 함수 v(s) → 입력된 상태 s의 가치 - 상태-행동 가치 함수 (큐함수) q(s, a) →입력된 상태 s에서 행동 a의 가치 에이전트는 아래와 같이 어떤 상태에서 어떤 행동을 할지 나타낸 정책과, 각 상태 혹은 각 상태에서의 각 행동이 얼마만큼의 가치가 있는지를 나타낸 가치함수를 보유하고 있다. 이 정책 또는 가치함수를 바탕으로 다음 행동을 결정한다. 아래의 정책은 각 상태에서 무작위로 행동을 선택하는 정책을 나타낸 것이다. ``` # policy p = [[[0.25 for _ in range(4)] for _ in range(5)] for _ in range(5)] # state-value function v = [[0. for _ in range(5)] for _ in range(5)] # action-value function q = [[[0 for _ in range(4)] for _ in range(5)] for _ in range(5)] ```
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="./images/Frame.png" type="image/x-icon"> <title>Gamer</title> <!-- google fonts cdn --> <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=EB+Garamond:wght@800&family=Inter:wght@400;500;700&family=Lato:wght@400;700&family=Work+Sans:wght@400;600;700;800&display=swap" rel="stylesheet"> <!-- fontawesome cdn --> <script src="https://kit.fontawesome.com/122c5d5188.js" crossorigin="anonymous"></script> <!-- this is our own stylesheet --> <link rel="stylesheet" href="./style.css"> </head> <body> <!-- header and nav section --> <header> <nav class="container"> <div class="logo"> <img src="./images/Frame.png" alt=""> <h2><span>G</span>amer</h2> </div> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Developers</a></li> <div class="follow-us"> <a href="#">Follow Us On</a> <a href="#"><i class="fa-brands fa-youtube"></i></a> <a href="#"><i class="fa-brands fa-tiktok"></i></a> </div> </ul> </nav> </header> <main> <!-- banner section --> <section class="top-banner"> <div class="banner container"> <div class="half-width"> <h2>Play Like The</h2> <h1>G.O.A.T.</h1> <p><i class="fa-regular fa-circle-play"></i> 1-Click instant play</p> <p><i class="fa-solid fa-download"></i> No Download</p> <p><i class="fa-solid fa-user-group"></i> 1000s of supported online games</p> <button class="primary-btn sign-in-btn">Sign In</button> <button class="primary-btn go-rouge-btn">Go Rogue</button> </div> <div class="half-width"> <img src="./images/Group 18.png" alt=""> </div> </div> </section> <!-- online games section --> <section class="online-games"> <h2>Online Games <span>Funny Videos</span></h2> <p>A Collection of Hilarious Videos to Brighten Your Day</p> <div class="game-boxes container"> <div class="box"> <img src="./images/Rectangle 4.png" alt=""> <div class="middle"> <div class="text"> <i class="fa-regular fa-circle-play"></i> <p>Watch Now</p> </div> </div> <p>No Download. No Installs. Play games Instantly on Gamer.</p> </div> <div class="box"> <img src="./images/Rectangle 5.png" alt=""> <div class="middle"> <div class="text"> <i class="fa-regular fa-circle-play"></i> <p>Watch Now</p> </div> </div> <p>Did you score? #unblockedgames #school</p> </div> <div class="box"> <img src="./images/Rectangle 6.png" alt=""> <div class="middle"> <div class="text"> <i class="fa-regular fa-circle-play"></i> <p>Watch Now</p> </div> </div> <p>Breaking game records like OG</p> </div> <div class="box"> <img src="./images/Rectangle 7.png" alt=""> <div class="middle"> <div class="text"> <i class="fa-regular fa-circle-play"></i> <p>Watch Now</p> </div> </div> <p>Busted gaming on school laptop, but you are still lit.</p> </div> </div> </section> <!-- play games section --> <section class="play-games container"> <div class="game-images"> <img class="game-img1" src="./images/Rectangle 67.png" alt=""> <img class="game-img2" src="./images/Rectangle 78.png" alt=""> </div> <div class="responsive-img"> <img src="./images/Rectangle 65.png" alt=""> </div> <div class="game-play-text"> <h2> <span>Play Games Online</span> Anywhere, Anytime!</h2> <p>PC. dad’s phone, mom’s tablet, or your Chromebook, with Gamer you can play your favorite games online for free, any time, anywhere , on any device.</p> </div> </section> <!-- game button section --> <section class="game-button container"> <div class="btn-boxes"> <div class="btn-box"> <img src="./images/Rectangle 11.png" alt=""> <p>Action Games</p> </div> <div class="btn-box"> <img src="./images/Rectangle 12.png" alt=""> <p>Adventure Games</p> </div> <div class="btn-box"> <img src="./images/Rectangle 13.png" alt=""> <p>Arcade Games</p> </div> <div class="btn-box"> <img src="./images/Rectangle 14.png" alt=""> <p>Educational Games</p> </div> <div class="btn-box"> <img src="./images/Rectangle 15.png" alt=""> <p>Word Games</p> </div> <div class="btn-box"> <img src="./images/Rectangle 16.png" alt=""> <p>Role Palying Games</p> </div> <div class="btn-box"> <img src="./images/Rectangle 17.png" alt=""> <p>Music & Audio Games</p> </div> <div class="btn-box"> <img src="./images/Rectangle 18.png" alt=""> <p>Puzzle Games</p> </div> <div class="btn-box"> <img src="./images/Rectangle 19.png" alt=""> <p>Strategy Games</p> </div> </div> </section> </main> <footer> <section class="footer container"> <div class="logo-footer"> <img src="./images/Frame.png" alt=""> <h2><span>G</span>amer</h2> </div> <ul class="footer-ul"> <li><a href="#">Our Story</a></li> <li><a href="#">Games</a></li> <li><a href="#">Web Games</a></li> <li><a href="#">Careers</a></li> <li><a href="#">Support</a></li> <li><a href="#">My Account</a></li> </ul> <ul class="footer-logo"> <li><a href="#"><i class="fa-brands fa-twitter"></i></a></li> <li><a href="#"><i class="fa-brands fa-facebook"></i></a></li> <li><a href="#"><i class="fa-brands fa-youtube"></i></a></li> <li><a href="#"><i class="fa-brands fa-linkedin-in"></i></a></li> <li><a href="#"><i class="fa-brands fa-instagram"></i></a></li> <li><a href="#"><i class="fa-brands fa-apple"></i></a></li> </ul> <ul class="terms"> <li><a href="#">Terms and Conditions</a></li> <li><a href="#">Privacy Policy</a></li> <li><a href="#">Cookie Policy</a></li> <li><a href="#">Privacy Settings</a></li> </ul> <small>Play Games @ Gamer @ 2000-2023 Gamer Bangladesh</small> </section> </footer> </body> </html>
# sous meteor app --- # Usage ## run locally npm run start-development # Docker ## Build a deployment package ``` npm install -g demeteorizer chmod +x ./private/docker/deploy.sh ./private/docker/deploy.sh ``` ## Docker run locally (dev environment) ``` docker build -t "sousapp:sousmeteor" .demeteorized # verify that the new image exists docker image ls # run the new image with staging settings (change as needed) docker run \ -e MONGO_URL="$(node -p 'settings=require("./settings-staging.json");settings.MONGO_URL.MONGOLAB')" \ -e METEOR_SETTINGS="$(node -p 'settings=require("./settings-staging.json");JSON.stringify(settings)')" \ -e SERVER_BASE=/usr/src/app/bundle/programs/server \ -e ROOT_URL=http://127.0.0.0:3000 \ -e NODE_ENV=staging \ -e PORT=3000 \ -p 3000:3000 \ sousapp:sousmeteor # then open the url open http://localhost:3000 ``` ## Upload to Zeit/Now ``` npm i -g now now \ -e MONGO_URL="$(node -p 'settings=require("./settings-staging.json");settings.MONGO_URL.MONGOLAB')" \ -e METEOR_SETTINGS="$(node -p 'settings=require("./settings-staging.json");JSON.stringify(settings)')" \ -e SERVER_BASE=/usr/src/app/bundle/programs/server \ -e ROOT_URL=http://127.0.0.0:3000 \ -e NODE_ENV=staging \ -e PORT=3000 \ -p 3000:3000 \ deploy .demeteorized ``` ### Alias to ENV ``` # the url is displayed during the now command above, and in some cases copied to the clipboard now alias set <url-slug>.now.sh <env>.sousapp.com ``` # Misc ## Notes: ### For deployment, you will need the latest modulus-cli and Meteor >= 1.3.2.4 (see https://help.modulus.io/customer/portal/articles/1647770-getting-started-with-meteor-on-modulus) $ npm install -g modulus@next ### Execute DDP commandline npm install node var WebSocket = require('ws') var DDPClient = require('ddp-client') var ENDPOINT_WS = 'ws://localhost:3000/websocket' var ddpClient = new DDPClient({url: ENDPOINT_WS, autoReconnect : false, maintainCollections : false,}) ddpClient.on("message", function(){ console.log("MSG FUNC: ", arguments); }) ddpClient.connect(function(error, wasReconnect){ console.log("CONN FUNC: ERROR: ", error, " WAS RECONNECT: ", wasReconnect); }) # ddpClient.call('sendOrders',[]) ddpClient.close() ### Import Purveyors (then) Products # Make data available via json url (Google Sheets + sheetsu) # if remotely # npm run start-staging # if locally npm run start-development # in a separate window/tab meteor shell # according to docs (meteor help shell) should have access to everything # [...] The shell supports tab completion for global variables like `Meteor`, # `Mongo`, and `Package`. Try typing `Meteor.is` and then pressing tab. [...] # note, unlike ddp calls, the parameters SHOULD NOT be in an array Meteor.call('importProducts', productJsonUrl, teamId); Meteor.call('importPurveyors', purveyorJsonUrl, teamId); # examples # Meteor.call('importTeams', "https://sheetsu.com/apis/816ed77a"); # Meteor.call('importUsers', "https://sheetsu.com/apis/452f3fd5"); # Meteor.call('importPurveyors', "https://sheetsu.com/apis/06d066f5"); # Meteor.call('importProducts', "https://sheetsu.com/apis/d1d0cbb3"); ### Quick load for debugging: npm run start-development # in a separate window/tab meteor shell Meteor.call('resetImportInvite', ['<your phone number>']); ## Testing errors # Execute DDP commandline (see above) #### inside `meteor shell`: Meteor.users.findOne() # copy the \_id #### inside `interactive node (ddp)`: ddpClient.subscribe('errors', ["<id>"]) #### inside `meteor shell`: # Meteor.call('triggerError', 'technical-error:email', 'Order Send Error - Sous has been notified, in the meantime please send order to your purveyors directly.', "<id>") # the error should show up in the `interactive node (ddp)` ## Templates: SEND_ORDER template: SEND_ORDER.txt
package org.defra.orchestration.function; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.azure.functions.ExecutionContext; import com.microsoft.azure.functions.HttpMethod; import com.microsoft.azure.functions.HttpRequestMessage; import com.microsoft.azure.functions.HttpResponseMessage; import com.microsoft.azure.functions.HttpStatus; import com.microsoft.azure.functions.annotation.AuthorizationLevel; import com.microsoft.azure.functions.annotation.FunctionName; import com.microsoft.azure.functions.annotation.HttpTrigger; import java.util.Optional; import lombok.extern.slf4j.Slf4j; import org.defra.orchestration.service.MdmService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @Slf4j public class PhesFunctions { private final MdmService mdmService; private final ObjectMapper objectMapper; @Autowired public PhesFunctions(MdmService mdmService, ObjectMapper objectMapper) { this.mdmService = mdmService; this.objectMapper = objectMapper; } @FunctionName("genus-and-species") public HttpResponseMessage genusAndSpecies( @HttpTrigger( name = "req", methods = HttpMethod.GET, authLevel = AuthorizationLevel.ANONYMOUS ) HttpRequestMessage<Optional<String>> request, final ExecutionContext context) throws JsonProcessingException { log.info("genus-and-species HTTP trigger starting"); return request.createResponseBuilder(HttpStatus.OK) .header("Content-Type", "application/json") .body(objectMapper.writeValueAsString(mdmService.getGenusAndSpecies())) .build(); } }
import { fireEvent, render, screen } from "src/test-utils"; import StyledModal from "."; const MockComponent = () => <span>Contents</span>; describe("StyledModal component", () => { it("should component render", () => { render( <StyledModal open={true} handleCloseModal={jest.fn()}> <MockComponent /> </StyledModal> ); expect(screen.getByRole("button")).toBeInTheDocument(); expect(screen.getByText(/contents/i)).toBeInTheDocument(); }); it("should component close", () => { const onClose = jest.fn(); render( <StyledModal open={true} handleCloseModal={onClose}> <MockComponent /> </StyledModal> ); fireEvent.click(screen.getByRole("button")); expect(onClose).toBeCalled(); }); });
" Save user-defined 'completeopt's so they can be restored after running this " custom completion function let s:old_completeopt = &completeopt " Completion for Git SHAs in the current repository function! gitcha#GitSHAComplete() let line = getline('.') let start = col('.') while start > 0 && line[start - 2] =~ '[0-9a-f]' let start -= 1 endwhile " Match Git SHAs in the current repository let matches = [] let revs = system('git rev-list --all --pretty=oneline --no-abbrev-commit') let base = line[start - 1 : col('.') - 1] for m in s:BuildMatchDictionary(revs) if m['word'] =~ '^' . base call add(matches, m) endif endfor set completeopt=menu,menuone,preview call complete(start, matches) let &completeopt = s:old_completeopt return '' endfunction " Takes rev-list output from: " $ git rev-list --all --pretty=oneline --no-abbrev-commit " " Creates a dictionary to be used for matching that uses commit SHAs for the " completion word and the commit subject as extra text. function! s:BuildMatchDictionary(rev_list) let matches = [] let commits = split(a:rev_list, '\n') for commit in commits let separator = stridx(commit, ' ') let sha = strpart(commit, 0, separator) let subject = strpart(commit, separator + 1) call add(matches, { \ 'word': sha, \ 'abbr': strpart(sha, 0, 10), \ 'menu': subject \ }) endfor return matches endfunction
from app.all_routes import * import requests def get_location(ip_address): access_token = '560450c74485ed' response = requests.get(f'http://ipinfo.io/{ip_address}/json?token={access_token}') data = response.json() city = data.get('city', 'Unknown') region = data.get('region', 'Unknown') country = data.get('country', 'Unknown') org = data.get('org', 'Unknown') return [city, region, country, org] def extract_info(str): start_pos = str.find('(') + 1 end_pos = str.find(')') if start_pos != -1 and end_pos != -1: device_info = str[start_pos:end_pos] os = device_info.split(';')[1].strip() user_agent = str[end_pos + 1:].strip() return os, user_agent else: return "Unknown Device", "Unknown User Agent" @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': identifier = request.form['identifier'] password = request.form['password'] user = Users.query.filter((Users.email == identifier) | (Users.username == identifier)).first() if user and bcrypt.check_password_hash(user.password, password) and user.otp_verified == 'true': session['logged_in'] = True session['user_id'] = user.id session['username'] = user.username session['email'] = user.email user_agent_str = request.headers.get('User-Agent') os , user_agent = extract_info(user_agent_str) login_time = datetime.now() ip = request.headers.get('X-Forwarded-For', request.remote_addr) location = get_location(ip) login_info = LoginInfo( users_id = user.id, user_agent = user_agent, os=os, city=location[0], region=location[1], country=location[2], telecom_service_provider=location[3], ip_address=ip, timestamp=login_time ) db.session.add(login_info) db.session.commit() return redirect(url_for('home')) else: flash('Login failed. Check your email/username and password.', 'danger') return render_template('pages/login.html')
# Configurations ## Overview The `Configurations` class provides a set of methods to interact with the configuration settings using the platform. This API allows you to retrieve, modify, and manage configuration parameters for your application. ## Methods ### get ```javascript public static get(key: string, defaultValue?: string): string | undefined ``` Retrieve the value associated with the specified configuration key. If the key is not found, it returns the specified default value, or undefined if not provided. **Example** ```javascript const value = Configurations.get("myConfigKey", "defaultValue"); console.log(value); // Output: "configuredValue" or "defaultValue" if not found ``` ### set ```javascript public static set(key: string, value: string): void ``` Set the value for the specified configuration key. **Example** ```javascript Configurations.set("myConfigKey", "configuredValue"); ``` ### remove ```javascript public static remove(key: string): void ``` Remove the configuration entry associated with the specified key. **Example** ```javascript Configurations.remove("myConfigKey"); ``` ### getKeys ```javascript public static getKeys(): string[] ``` Retrieve an array of all configuration keys. **Example** ```javascript const keys = Configurations.getKeys(); console.log(keys); // Output: ["key1", "key2", ...] ``` ### load ```javascript public static load(path: string): void ``` Load configuration settings from the specified path. **Example** ```javascript Configurations.load("/path/to/config/file.properties"); ``` ### update ```javascript public static update(): void ``` Update the configuration settings. **Example** ```javascript Configurations.update(); ``` ### getOS ```javascript public static getOS(): string ``` Retrieve the operating system name. **Example** ```javascript const osName = Configurations.getOS(); console.log(osName); // Output: "Windows", "Mac OS X", "Linux", "Solaris", etc. ``` ### isOSWindows ```javascript public static isOSWindows(): boolean ``` Check if the operating system is Windows. **Example** ```javascript const isWindows = Configurations.isOSWindows(); console.log(isWindows); // Output: true or false ``` ### isOSMac ```javascript public static isOSMac(): boolean ``` Check if the operating system is Mac OS. **Example** ```javascript const isMac = Configurations.isOSMac(); console.log(isMac); // Output: true or false ``` ### isOSUNIX ```javascript public static isOSUNIX(): boolean ``` Check if the operating system is UNIX-based. **Example** ```javascript const isUNIX = Configurations.isOSUNIX(); console.log(isUNIX); // Output: true or false ``` ### isOSSolaris ```javascript public static isOSSolaris(): boolean ``` Check if the operating system is Solaris. **Example** ```javascript const isSolaris = Configurations.isOSSolaris(); console.log(isSolaris); // Output: true or false ``` ## Functions --- Function | Description | Returns ------------ | ----------- | -------- **get(key, defaultValue)()** | Returns the value for the specified key, or the default value | *string* **set(key, value)** | Sets a value, for the specified key | *-* **getKeys()** | Returns an arrays of keys | *array of string* **load(path)** | Loads a configuration from a properties file at *path* | *-* **update()** | Updates the loaded configurations | *-*
--- layout: post title: Let's start with Software Testing subtitle: Why do we test software? thumbnail-img: /assets/posts/testing.png tags: [fundamentals, software testing] --- ```The true subject matter of the tester is not testing, but the design of test cases. by Paul Ammann and Jeff Offutt``` It is well known that software affects our behaviour, movement, health, relationships, etc. Overall, it influences our lives. With staggering advances in the medical sector, transport industry, power grids, communications, trading, financial sectors... we rely upon the systems in control to be reliable and high quality assuring. And they are, most of the time, repeat: most of the time. Software took control, and it is the driving force of the world. If someone finds this arguable, I will remind its role during the last 3 years, when the world was in chains of the pandemic. Thanks to the software industry, and staggering human intellect, we managed to save lives and economies. This is a sign of how large the software industry has become and how complex are the systems providing us with the services. However, not many users know that the software can fail to deliver. It is not visible to daily users that there is a set of well-crafted procedures behind every software unit that deals with software design, development management, and software testing as an evaluation guardian standing between users and unreliable software. Although many factors influence the reliability of the software, the factors that can be both certain and uncertain, this guardian has been staying straight and refuses to give in to the waves of innovations without assurance of testing thoroughness. Fortunately, or unfortunately for the guardian, it currently deals with a new wave. New software development continuous integration processes have put the most potent pressure on testing so far as they balance thorough testing and tight delivery schedule. Yes, it is hard to balance. Yet, these two factors are mutually dependent. Think about it, if the system does not satisfy high-quality expectations, it will neglect rapid delivery, and if there is no rapid delivery, it will neglect high-quality expectations. Thus, besides investing all the efforts in rapid delivery, synergy is required between stressing the units of complex systems and the interaction of different software components heavily. This combination in test-driven development makes the key to functional requirements and hides the key to the success of software products now and in the future. ### How does it come that software can be unreliable? My social apps never let me down! Let's be clear that software development is an engineering discipline. Like all other disciplines, engineering products are often diverse. As in civil engineering, when we build from house to bridge, in the software industry, also, the scope is quite broad. It goes from the social app where we can exchange with our friends from the cosy sofa, from the exchange with a NASA rover from Mars, asking him if there is a cosy chair up there? Or down there? :) This software spectrum goes to the control rooms of nuclear reactors, aerospace vehicles, CT and MRI scans, and many more. Even with our guardian (software testing practices), software disasters often have severe consequences for health, environment and economy, which usually results in severe disasters. Before you depart and start investigating severe disasters related to the software (you will find some references at the bottom), you need to know that not all the problems related to the software end up with consequences. That's why you need to learn about software faults, errors and failures (and yes, remember, don't be judgmental, remember all the lives saved by software, increased well being and what it brought to science). Before discussing these 3 major concerns of each software practitioner, it is essential to emphasize that each defines its definition of fault, error, and failure based on the area (remember engineering area). It is justifiable, right? The fault occurring in your social media app is not the same concern when the fault occurs in a critical safety system that can cause someone to lose their life. Nevertheless, let's try to describe them as broadly as possible: The fault is a defect in the software's internal state. You know that the software is a set of instructions that we indicate a computer to execute. During the execution, everything that happens in the program (variables, counters, memory, i/o, etc., you don't need to know about this) considers a program state, leading to an output. Therefore, a fault is a design mistake occurring inside the program state and relates to those instructions. It occurs as a product of a constrained (far from flawless) human decision-making process. And as long as the human nature of thoughts is not perfect, and as a human is the one that writes the software, at least for some time yet, we will never be able to eliminate all possible faults of the software. ```The faults are easy to make, but difficult to catch``` by MIT mathematician Edelman. As soon as the fault manifests and makes an incorrect internal program state, we are dealing with errors in the system. Errors are okay, as long as they are handled tho. Think about it, have you ever tried to fill a form field with a date format that is not quite the one that particular software prefers (or at least the software engineer that wrote it)? And usually, it tells you what kind of format it prefers? What happens is that your input is about to produce the incorrect internal program state, but the engineer anticipated the scenario, leaving you the note. In an alternative scenario, if the engineer didn't care much about how you interact with the system for another field (it didn't consider the broad spectrum of scenarios), it left you the possibility of making a software fail to deliver you what you want. More formally, Software Failure occurs as the incorrect external behaviour of the system concerning the expected behaviour (software requirements or another means of describing software behaviour) Over history, there have been many failures, some more known than others, related to CT scans, providing extensive radiation. Examples include rocket lunches, processor chips, and automotive faults, causing recalls of millions of products and causing massive economic damage in favour of safety. Besides the significant threat of having software not functionally assured, it is also essential to know that the software faults do not propagate only to functional failures. Many security vulnerabilities of the system are the product of faulty software. Such a system leaves the door open for not ethical practitioners to exploit the software of their own will. Many areas, if not all, are acceptable to this threat. Examples are cryptography, database, cloud, network security, etc. Overall, the software is available to many users all over the world. The Web makes software being distributed worldwide, adding additional complexity. And it is more crucial now than ever before to stress the systems with accumulated knowledge and gained experience in software testing to reach a reasonable level of testing thoroughness, derive high-quality tests, and test rationally while often.
<template> <div class="root-container-main"> <!-- <canvas class="sub-canvas" width="512" height="512"></canvas> --> <canvas class="main-canvas" width="512" height="512"></canvas> <!-- <div class="hover-box"> 其他内容 <img src="" alt="" width="100" height="100" id="raw-img"> </div> --> <!-- <SiderPannel /> --> <!-- <div id='openSeadragon1' style="display: none;"></div> --> <!-- 使用 v-if 会重新加载一遍这个组件,方便传参 --> <HighResImage v-if="store.state.pic_browser.CPU_storage.show_highres" :heigh_res_file_path="'hello'" /> </div> </template> <script setup> import SiderPannel from './SiderPannel/SiderPannel.vue'; import HighResImage from './HighResImage.vue'; import { useStore } from 'vuex'; import { onMounted } from 'vue'; import { inject, provide, watch } from 'vue'; import { mat4, vec3, vec4 } from "wgpu-matrix" import { useRouter } from 'vue-router'; /** * 以下语句必须,不可注释 * 恰好为等待 device 响应的时间,之后再去执行 onMounted 可以保证 device 是可靠的 * */ const device = await inject("device"); const store = useStore(); const router = useRouter(); const ws = store.state.ws; console.log("device = ", device) // provide("single_img_info", store.state.pic_browser.CPU_storage.single_img_info); // onMounted onMounted(() => { const window_width = window.innerWidth; const window_height = window.innerHeight; const main_canvas = document.querySelector(".main-canvas"); const sub_canvas = document.querySelector(".sub-canvas"); main_canvas.width = window_width; main_canvas.height = window_height; store.state.pic_browser.main_canvas.canvas = main_canvas; // store.state.pic_browser.sub_canvas.canvas = sub_canvas; const device = store.state.device; console.log("device device = ", device) /** * 将 rootState 中的 ws 接口赋值给本地的 ws * */ store.state.pic_browser.ws = ws; /** * device initialization * */ store.commit("pic_browser/init_device", { canvas: { main_canvas, sub_canvas }, device }); /** * camera initialization * */ store.commit("pic_browser/init_camera", device); // /** // * fetch data set description info once // * */ // const temp_json_cmd = { // cmd: "void", // pack: [] // } // ws.send(JSON.stringify(temp_json_cmd)); const fetch_large_texture_cmd = { cmd: "sys_startup_prefetch", pack: [] } ws.send(JSON.stringify(fetch_large_texture_cmd)); }) /*** ################# Global Watch Camera ################# ***/ // watch(() => { // return store.state.pic_browser.camera["prim_camera"]; // }, () => { // console.log("camera moving~"); // }, { deep: true }); /*** ################# Sub View Debug Flow Control Watcher Group ################# ***/ watch(() => { return store.state.pic_browser.sub_view_flow_debug.fence["DATASET_INFO_READY"]; }, (flag) => { if (flag == true) { store.commit("pic_browser/sub_flow_dataset_info_ready", device); } }, { deep: true }); watch(() => { return store.state.pic_browser.sub_view_flow_debug.fence["RENDER_READY"]; }, (flag) => { if (flag == true) { store.commit("pic_browser/sub_canvas_renderLoop", device); } }, { deep: true }); /*** ################# Main View Quad Flow Control Watcher Group ################# ***/ watch(() => { return store.state.pic_browser.main_view_flow_quad.fence["DATASET_INFO_READY"]; }, (flag) => { if (flag == true) { store.commit("pic_browser/main_quad_flow_dataset_info_ready", device); } }, { deep: true }); /** * Sys Startup Info Parse Done * */ watch(() => { return store.state.pic_browser.main_view_flow_quad.fence["DATASET_INFO_PARSE_DONE"]; }, (flag) => { if (flag == true) { store.commit("pic_browser/main_quad_flow_dataset_info_parse_done", device); } }, { deep: true }) /** * RENDER Ready * */ watch(() => { return store.state.pic_browser.main_view_flow_quad.fence["RENDER_READY"]; }, (flag) => { if (flag == true) { store.commit("pic_browser/main_canvas_quad_renderLoop", device); } }, { deep: true }); /** * Compute MipLevel Pass Submit * */ watch(() => { return store.state.pic_browser.main_view_flow_quad.fence["COMPUTE_MIP_SUBMIT"]; }, (flag) => { if (flag == true) { // console.time("dynamic loop time cost : "); store.dispatch("pic_browser/readBackMipLevel_and_FetchQuadPicSetFromServer", device); } }, { deep: true }); /** * BitMap Received * */ watch(() => { return store.state.pic_browser.main_view_flow_quad.fence["BITMAP_RECEIVED"]; }, (flag) => { if (flag == true) { store.dispatch("pic_browser/construct_quad_imgBitMap"); } }, { deep: true }); /** * BitMap Ready * */ watch(() => { return store.state.pic_browser.main_view_flow_quad.fence["BITMAP_READY"]; }, (flag) => { if (flag == true) { store.commit("pic_browser/main_flow_fetch_bitmap_ready", device); } }, { deep: true }); /** * Get selected img Done * 第一次需要被触发执行(选择你的触发位置吧,先去吃饭,回来从选择触发位置开始继续) * */ watch(() => { return store.state.pic_browser.main_view_flow_quad.fence["GET_SELECTED_IMG"]; }, (flag) => { if (flag == true) { store.dispatch("pic_browser/get_selected_image_idx", device); } }, { deep: true }); watch(() => { return store.state.pic_browser.CPU_storage.selected_img; }, (val) => { if (val.val != -1) { /** * 根据当前的信息,向服务端取数据 * */ const img_idx = val.val; const json_cmd = { cmd: "fetch_single_img", idx: img_idx, }; // store.state.pic_browser.ws.send(JSON.stringify(json_cmd)); } }, { deep: true }); // 是否进行页面跳转 watch(() => { return store.state.pic_browser.main_canvas.mouse_info.db_click_flag; }, (flag) => { router.push("./heigh_res"); }, { deep: true }); </script> <style> .root-container-main { position: absolute; left: 0px; top: 0px; /* 内廓border不额外占用空间 */ box-sizing: border-box; width: 100%; height: 100%; border: solid 10px black; background-color: #d5d5d5; } .main-canvas { width: 100%; height: 100%; } .sub-canvas { position: absolute; /* width: 100%; height: 100%; */ right: 0px; bottom: 0px; } .hover-box { position: absolute; left: 0px; top: 0px; width: 50px; height: 50px; background-color: aquamarine; display: none; } /* #openSeadragon1 { position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; border: chocolate 1vw solid; box-sizing: border-box; background-color: white; } */ </style>
# C++ Message Broker ## Overview This project implements a concurrent message broker using C++ with some object-oriented programming (OOP). The message broker allows clients to subscribe to topics, publish messages, and receive messages from subscribed topics. ## Features - **Subscription**: Clients can subscribe to specific topics to receive messages. - **Publishing**: Clients can publish messages to specific topics, which are then delivered to subscribed clients. - **Unsubscription**: Clients can unsubscribe from topics to stop receiving messages. - The server has a simple thread per client concurrency. ## Project Structure - `server.cpp`: Contains the implementation of the server, which handles client connections and message routing. - `handlers.cpp` and `handlers.h`: Define the command handlers for different commands like SUB, PUB, UNSUB, and PING. - `parser.h`: Implements the command parser, which creates command handlers based on received commands. - `server.h`: Header file for the server class. ## Usage ### Building the Server ``` mkdir build ``` + ``` cd build ``` + ``` make ``` ### Running the Server ``` ./server ``` ### Connecting Clients Clients can connect to the server using a socket connection. For testing purposes, you can use tools like telnet or create a simple client in C++. ### Example Commands ``` telnet localhost 4222 ``` ``` SUB my_topic ``` ### Publish a Message: ``` PUB my_topic 8 ``` "Hello!" and we get: Hello! as the subscribers too (In this case our client is both the subscriber and the publisher), you can open another terminal and connect with a different client and experience it Unsubscribe from a Topic: ``` UNSUB my_topic ``` ### Classes details: #### Prerequisites: abstract base classes, interfaces and polymorphism. AbsractHandler: Abstract base class for command handlers, defining the common interface. SubCommandHandler, PubCommandHandler, UnsubCommandHandler, PingCommandHandler: Concrete implementations of command handlers. CommandParser: Responsible for creating the appropriate command handler based on the received command. #### Contributing Feel free to contribute to the project by opening issues or creating pull requests. Your feedback and contributions are highly appreciated!
from typing import Any, Dict, List, Type, TypeVar, Union from attrs import define as _attrs_define from attrs import field as _attrs_field from ..types import UNSET, Unset T = TypeVar("T", bound="IngestersCloudResource") @_attrs_define class IngestersCloudResource: """ Example: {'iam_instance_profile_arn': 'iam_instance_profile_arn', 'allow_blob_public_access': True, 'ingress_settings': 'ingress_settings', 'vpc_id': 'vpc_id', 'event_notification_configuration': '', 'ip_configuration': '', 'access_level': 'access_level', 'path': 'path', 'connectivity': 'connectivity', 'policy_std': '', 'target_health_descriptions': '', 'iam_policy': '', 'action': 'action', 'private_ip_address': 'private_ip_address', 'id': 'id', 'create_date': 'create_date', 'resource_vpc_config': '', 'inline_policies': '', 'restrict_public_buckets': True, 'db_cluster_identifier': 'db_cluster_identifier', 'group': 'group', 'target_group_arn': 'target_group_arn', 'ignore_public_acls': True, 'storage_account_name': 'storage_account_name', 'service_name': 'service_name', 'instance_profile_arns': '', 'users': '', 'network_interfaces': '', 'tags': '', 'security_groups': '', 'task_arn': 'task_arn', 'block_public_acls': True, 'organization_master_account_email': 'organization_master_account_email', 'instance_id': 'instance_id', 'public_access': 'public_access', 'task_definition': '', 'user_id': 'user_id', 'organization_id': 'organization_id', 'name': 'name', 'resources_vpc_config': '', 'attached_policy_arns': '', 'task_definition_arn': 'task_definition_arn', 'containers': '', 'region': 'region', 'container_definitions': '', 'instance_type': 'instance_type', 'scheme': 'scheme', 'instances': '', 'network_mode': 'network_mode', 'is_egress': True, 'description': 'description', 'privilege': 'privilege', 'network_configuration': '', 'public_network_access': 'public_network_access', 'vpc_options': '', 'vpc_security_group_ids': '', 'arn': 'arn', 'private_dns_name': 'private_dns_name', 'policy': '', 'public_ips': '', 'cluster_name': 'cluster_name', 'cluster_arn': 'cluster_arn', 'public_ip_address': 'public_ip_address', 'cidr_ipv4': 'cidr_ipv4', 'last_status': 'last_status', 'groups': '', 'user-groups': '', 'cloud_provider': 'cloud_provider', 'vpc_security_groups': '', 'block_public_policy': True, 'account_id': 'account_id', 'iam_instance_profile_id': 'iam_instance_profile_id', 'group_id': 'group_id', 'organization_master_account_arn': 'organization_master_account_arn', 'resource_id': 'resource_id', 'bucket_policy_is_public': True, 'host_name': 'host_name'} Attributes: access_level (Union[Unset, str]): account_id (Union[Unset, str]): action (Union[Unset, str]): allow_blob_public_access (Union[Unset, bool]): arn (Union[Unset, str]): attached_policy_arns (Union[Unset, Any]): block_public_acls (Union[Unset, bool]): block_public_policy (Union[Unset, bool]): bucket_policy_is_public (Union[Unset, bool]): cidr_ipv4 (Union[Unset, str]): cloud_provider (Union[Unset, str]): cluster_arn (Union[Unset, str]): cluster_name (Union[Unset, str]): connectivity (Union[Unset, str]): container_definitions (Union[Unset, Any]): containers (Union[Unset, Any]): create_date (Union[Unset, str]): db_cluster_identifier (Union[Unset, str]): description (Union[Unset, str]): event_notification_configuration (Union[Unset, Any]): group (Union[Unset, str]): group_id (Union[Unset, str]): groups (Union[Unset, Any]): host_name (Union[Unset, str]): iam_instance_profile_arn (Union[Unset, str]): iam_instance_profile_id (Union[Unset, str]): iam_policy (Union[Unset, Any]): id (Union[Unset, str]): ignore_public_acls (Union[Unset, bool]): ingress_settings (Union[Unset, str]): inline_policies (Union[Unset, Any]): instance_id (Union[Unset, str]): instance_profile_arns (Union[Unset, Any]): instance_type (Union[Unset, str]): instances (Union[Unset, Any]): ip_configuration (Union[Unset, Any]): is_egress (Union[Unset, bool]): last_status (Union[Unset, str]): name (Union[Unset, str]): network_configuration (Union[Unset, Any]): network_interfaces (Union[Unset, Any]): network_mode (Union[Unset, str]): organization_id (Union[Unset, str]): organization_master_account_arn (Union[Unset, str]): organization_master_account_email (Union[Unset, str]): path (Union[Unset, str]): policy (Union[Unset, Any]): policy_std (Union[Unset, Any]): private_dns_name (Union[Unset, str]): private_ip_address (Union[Unset, str]): privilege (Union[Unset, str]): public_access (Union[Unset, str]): public_ip_address (Union[Unset, str]): public_ips (Union[Unset, Any]): public_network_access (Union[Unset, str]): region (Union[Unset, str]): resource_id (Union[Unset, str]): resource_vpc_config (Union[Unset, Any]): resources_vpc_config (Union[Unset, Any]): restrict_public_buckets (Union[Unset, bool]): scheme (Union[Unset, str]): security_groups (Union[Unset, Any]): service_name (Union[Unset, str]): storage_account_name (Union[Unset, str]): tags (Union[Unset, Any]): target_group_arn (Union[Unset, str]): target_health_descriptions (Union[Unset, Any]): task_arn (Union[Unset, str]): task_definition (Union[Unset, Any]): task_definition_arn (Union[Unset, str]): user_groups (Union[Unset, Any]): user_id (Union[Unset, str]): users (Union[Unset, Any]): vpc_id (Union[Unset, str]): vpc_options (Union[Unset, Any]): vpc_security_group_ids (Union[Unset, Any]): vpc_security_groups (Union[Unset, Any]): """ access_level: Union[Unset, str] = UNSET account_id: Union[Unset, str] = UNSET action: Union[Unset, str] = UNSET allow_blob_public_access: Union[Unset, bool] = UNSET arn: Union[Unset, str] = UNSET attached_policy_arns: Union[Unset, Any] = UNSET block_public_acls: Union[Unset, bool] = UNSET block_public_policy: Union[Unset, bool] = UNSET bucket_policy_is_public: Union[Unset, bool] = UNSET cidr_ipv4: Union[Unset, str] = UNSET cloud_provider: Union[Unset, str] = UNSET cluster_arn: Union[Unset, str] = UNSET cluster_name: Union[Unset, str] = UNSET connectivity: Union[Unset, str] = UNSET container_definitions: Union[Unset, Any] = UNSET containers: Union[Unset, Any] = UNSET create_date: Union[Unset, str] = UNSET db_cluster_identifier: Union[Unset, str] = UNSET description: Union[Unset, str] = UNSET event_notification_configuration: Union[Unset, Any] = UNSET group: Union[Unset, str] = UNSET group_id: Union[Unset, str] = UNSET groups: Union[Unset, Any] = UNSET host_name: Union[Unset, str] = UNSET iam_instance_profile_arn: Union[Unset, str] = UNSET iam_instance_profile_id: Union[Unset, str] = UNSET iam_policy: Union[Unset, Any] = UNSET id: Union[Unset, str] = UNSET ignore_public_acls: Union[Unset, bool] = UNSET ingress_settings: Union[Unset, str] = UNSET inline_policies: Union[Unset, Any] = UNSET instance_id: Union[Unset, str] = UNSET instance_profile_arns: Union[Unset, Any] = UNSET instance_type: Union[Unset, str] = UNSET instances: Union[Unset, Any] = UNSET ip_configuration: Union[Unset, Any] = UNSET is_egress: Union[Unset, bool] = UNSET last_status: Union[Unset, str] = UNSET name: Union[Unset, str] = UNSET network_configuration: Union[Unset, Any] = UNSET network_interfaces: Union[Unset, Any] = UNSET network_mode: Union[Unset, str] = UNSET organization_id: Union[Unset, str] = UNSET organization_master_account_arn: Union[Unset, str] = UNSET organization_master_account_email: Union[Unset, str] = UNSET path: Union[Unset, str] = UNSET policy: Union[Unset, Any] = UNSET policy_std: Union[Unset, Any] = UNSET private_dns_name: Union[Unset, str] = UNSET private_ip_address: Union[Unset, str] = UNSET privilege: Union[Unset, str] = UNSET public_access: Union[Unset, str] = UNSET public_ip_address: Union[Unset, str] = UNSET public_ips: Union[Unset, Any] = UNSET public_network_access: Union[Unset, str] = UNSET region: Union[Unset, str] = UNSET resource_id: Union[Unset, str] = UNSET resource_vpc_config: Union[Unset, Any] = UNSET resources_vpc_config: Union[Unset, Any] = UNSET restrict_public_buckets: Union[Unset, bool] = UNSET scheme: Union[Unset, str] = UNSET security_groups: Union[Unset, Any] = UNSET service_name: Union[Unset, str] = UNSET storage_account_name: Union[Unset, str] = UNSET tags: Union[Unset, Any] = UNSET target_group_arn: Union[Unset, str] = UNSET target_health_descriptions: Union[Unset, Any] = UNSET task_arn: Union[Unset, str] = UNSET task_definition: Union[Unset, Any] = UNSET task_definition_arn: Union[Unset, str] = UNSET user_groups: Union[Unset, Any] = UNSET user_id: Union[Unset, str] = UNSET users: Union[Unset, Any] = UNSET vpc_id: Union[Unset, str] = UNSET vpc_options: Union[Unset, Any] = UNSET vpc_security_group_ids: Union[Unset, Any] = UNSET vpc_security_groups: Union[Unset, Any] = UNSET additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> Dict[str, Any]: access_level = self.access_level account_id = self.account_id action = self.action allow_blob_public_access = self.allow_blob_public_access arn = self.arn attached_policy_arns = self.attached_policy_arns block_public_acls = self.block_public_acls block_public_policy = self.block_public_policy bucket_policy_is_public = self.bucket_policy_is_public cidr_ipv4 = self.cidr_ipv4 cloud_provider = self.cloud_provider cluster_arn = self.cluster_arn cluster_name = self.cluster_name connectivity = self.connectivity container_definitions = self.container_definitions containers = self.containers create_date = self.create_date db_cluster_identifier = self.db_cluster_identifier description = self.description event_notification_configuration = self.event_notification_configuration group = self.group group_id = self.group_id groups = self.groups host_name = self.host_name iam_instance_profile_arn = self.iam_instance_profile_arn iam_instance_profile_id = self.iam_instance_profile_id iam_policy = self.iam_policy id = self.id ignore_public_acls = self.ignore_public_acls ingress_settings = self.ingress_settings inline_policies = self.inline_policies instance_id = self.instance_id instance_profile_arns = self.instance_profile_arns instance_type = self.instance_type instances = self.instances ip_configuration = self.ip_configuration is_egress = self.is_egress last_status = self.last_status name = self.name network_configuration = self.network_configuration network_interfaces = self.network_interfaces network_mode = self.network_mode organization_id = self.organization_id organization_master_account_arn = self.organization_master_account_arn organization_master_account_email = self.organization_master_account_email path = self.path policy = self.policy policy_std = self.policy_std private_dns_name = self.private_dns_name private_ip_address = self.private_ip_address privilege = self.privilege public_access = self.public_access public_ip_address = self.public_ip_address public_ips = self.public_ips public_network_access = self.public_network_access region = self.region resource_id = self.resource_id resource_vpc_config = self.resource_vpc_config resources_vpc_config = self.resources_vpc_config restrict_public_buckets = self.restrict_public_buckets scheme = self.scheme security_groups = self.security_groups service_name = self.service_name storage_account_name = self.storage_account_name tags = self.tags target_group_arn = self.target_group_arn target_health_descriptions = self.target_health_descriptions task_arn = self.task_arn task_definition = self.task_definition task_definition_arn = self.task_definition_arn user_groups = self.user_groups user_id = self.user_id users = self.users vpc_id = self.vpc_id vpc_options = self.vpc_options vpc_security_group_ids = self.vpc_security_group_ids vpc_security_groups = self.vpc_security_groups field_dict: Dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update({}) if access_level is not UNSET: field_dict["access_level"] = access_level if account_id is not UNSET: field_dict["account_id"] = account_id if action is not UNSET: field_dict["action"] = action if allow_blob_public_access is not UNSET: field_dict["allow_blob_public_access"] = allow_blob_public_access if arn is not UNSET: field_dict["arn"] = arn if attached_policy_arns is not UNSET: field_dict["attached_policy_arns"] = attached_policy_arns if block_public_acls is not UNSET: field_dict["block_public_acls"] = block_public_acls if block_public_policy is not UNSET: field_dict["block_public_policy"] = block_public_policy if bucket_policy_is_public is not UNSET: field_dict["bucket_policy_is_public"] = bucket_policy_is_public if cidr_ipv4 is not UNSET: field_dict["cidr_ipv4"] = cidr_ipv4 if cloud_provider is not UNSET: field_dict["cloud_provider"] = cloud_provider if cluster_arn is not UNSET: field_dict["cluster_arn"] = cluster_arn if cluster_name is not UNSET: field_dict["cluster_name"] = cluster_name if connectivity is not UNSET: field_dict["connectivity"] = connectivity if container_definitions is not UNSET: field_dict["container_definitions"] = container_definitions if containers is not UNSET: field_dict["containers"] = containers if create_date is not UNSET: field_dict["create_date"] = create_date if db_cluster_identifier is not UNSET: field_dict["db_cluster_identifier"] = db_cluster_identifier if description is not UNSET: field_dict["description"] = description if event_notification_configuration is not UNSET: field_dict["event_notification_configuration"] = event_notification_configuration if group is not UNSET: field_dict["group"] = group if group_id is not UNSET: field_dict["group_id"] = group_id if groups is not UNSET: field_dict["groups"] = groups if host_name is not UNSET: field_dict["host_name"] = host_name if iam_instance_profile_arn is not UNSET: field_dict["iam_instance_profile_arn"] = iam_instance_profile_arn if iam_instance_profile_id is not UNSET: field_dict["iam_instance_profile_id"] = iam_instance_profile_id if iam_policy is not UNSET: field_dict["iam_policy"] = iam_policy if id is not UNSET: field_dict["id"] = id if ignore_public_acls is not UNSET: field_dict["ignore_public_acls"] = ignore_public_acls if ingress_settings is not UNSET: field_dict["ingress_settings"] = ingress_settings if inline_policies is not UNSET: field_dict["inline_policies"] = inline_policies if instance_id is not UNSET: field_dict["instance_id"] = instance_id if instance_profile_arns is not UNSET: field_dict["instance_profile_arns"] = instance_profile_arns if instance_type is not UNSET: field_dict["instance_type"] = instance_type if instances is not UNSET: field_dict["instances"] = instances if ip_configuration is not UNSET: field_dict["ip_configuration"] = ip_configuration if is_egress is not UNSET: field_dict["is_egress"] = is_egress if last_status is not UNSET: field_dict["last_status"] = last_status if name is not UNSET: field_dict["name"] = name if network_configuration is not UNSET: field_dict["network_configuration"] = network_configuration if network_interfaces is not UNSET: field_dict["network_interfaces"] = network_interfaces if network_mode is not UNSET: field_dict["network_mode"] = network_mode if organization_id is not UNSET: field_dict["organization_id"] = organization_id if organization_master_account_arn is not UNSET: field_dict["organization_master_account_arn"] = organization_master_account_arn if organization_master_account_email is not UNSET: field_dict["organization_master_account_email"] = organization_master_account_email if path is not UNSET: field_dict["path"] = path if policy is not UNSET: field_dict["policy"] = policy if policy_std is not UNSET: field_dict["policy_std"] = policy_std if private_dns_name is not UNSET: field_dict["private_dns_name"] = private_dns_name if private_ip_address is not UNSET: field_dict["private_ip_address"] = private_ip_address if privilege is not UNSET: field_dict["privilege"] = privilege if public_access is not UNSET: field_dict["public_access"] = public_access if public_ip_address is not UNSET: field_dict["public_ip_address"] = public_ip_address if public_ips is not UNSET: field_dict["public_ips"] = public_ips if public_network_access is not UNSET: field_dict["public_network_access"] = public_network_access if region is not UNSET: field_dict["region"] = region if resource_id is not UNSET: field_dict["resource_id"] = resource_id if resource_vpc_config is not UNSET: field_dict["resource_vpc_config"] = resource_vpc_config if resources_vpc_config is not UNSET: field_dict["resources_vpc_config"] = resources_vpc_config if restrict_public_buckets is not UNSET: field_dict["restrict_public_buckets"] = restrict_public_buckets if scheme is not UNSET: field_dict["scheme"] = scheme if security_groups is not UNSET: field_dict["security_groups"] = security_groups if service_name is not UNSET: field_dict["service_name"] = service_name if storage_account_name is not UNSET: field_dict["storage_account_name"] = storage_account_name if tags is not UNSET: field_dict["tags"] = tags if target_group_arn is not UNSET: field_dict["target_group_arn"] = target_group_arn if target_health_descriptions is not UNSET: field_dict["target_health_descriptions"] = target_health_descriptions if task_arn is not UNSET: field_dict["task_arn"] = task_arn if task_definition is not UNSET: field_dict["task_definition"] = task_definition if task_definition_arn is not UNSET: field_dict["task_definition_arn"] = task_definition_arn if user_groups is not UNSET: field_dict["user-groups"] = user_groups if user_id is not UNSET: field_dict["user_id"] = user_id if users is not UNSET: field_dict["users"] = users if vpc_id is not UNSET: field_dict["vpc_id"] = vpc_id if vpc_options is not UNSET: field_dict["vpc_options"] = vpc_options if vpc_security_group_ids is not UNSET: field_dict["vpc_security_group_ids"] = vpc_security_group_ids if vpc_security_groups is not UNSET: field_dict["vpc_security_groups"] = vpc_security_groups return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy() access_level = d.pop("access_level", UNSET) account_id = d.pop("account_id", UNSET) action = d.pop("action", UNSET) allow_blob_public_access = d.pop("allow_blob_public_access", UNSET) arn = d.pop("arn", UNSET) attached_policy_arns = d.pop("attached_policy_arns", UNSET) block_public_acls = d.pop("block_public_acls", UNSET) block_public_policy = d.pop("block_public_policy", UNSET) bucket_policy_is_public = d.pop("bucket_policy_is_public", UNSET) cidr_ipv4 = d.pop("cidr_ipv4", UNSET) cloud_provider = d.pop("cloud_provider", UNSET) cluster_arn = d.pop("cluster_arn", UNSET) cluster_name = d.pop("cluster_name", UNSET) connectivity = d.pop("connectivity", UNSET) container_definitions = d.pop("container_definitions", UNSET) containers = d.pop("containers", UNSET) create_date = d.pop("create_date", UNSET) db_cluster_identifier = d.pop("db_cluster_identifier", UNSET) description = d.pop("description", UNSET) event_notification_configuration = d.pop("event_notification_configuration", UNSET) group = d.pop("group", UNSET) group_id = d.pop("group_id", UNSET) groups = d.pop("groups", UNSET) host_name = d.pop("host_name", UNSET) iam_instance_profile_arn = d.pop("iam_instance_profile_arn", UNSET) iam_instance_profile_id = d.pop("iam_instance_profile_id", UNSET) iam_policy = d.pop("iam_policy", UNSET) id = d.pop("id", UNSET) ignore_public_acls = d.pop("ignore_public_acls", UNSET) ingress_settings = d.pop("ingress_settings", UNSET) inline_policies = d.pop("inline_policies", UNSET) instance_id = d.pop("instance_id", UNSET) instance_profile_arns = d.pop("instance_profile_arns", UNSET) instance_type = d.pop("instance_type", UNSET) instances = d.pop("instances", UNSET) ip_configuration = d.pop("ip_configuration", UNSET) is_egress = d.pop("is_egress", UNSET) last_status = d.pop("last_status", UNSET) name = d.pop("name", UNSET) network_configuration = d.pop("network_configuration", UNSET) network_interfaces = d.pop("network_interfaces", UNSET) network_mode = d.pop("network_mode", UNSET) organization_id = d.pop("organization_id", UNSET) organization_master_account_arn = d.pop("organization_master_account_arn", UNSET) organization_master_account_email = d.pop("organization_master_account_email", UNSET) path = d.pop("path", UNSET) policy = d.pop("policy", UNSET) policy_std = d.pop("policy_std", UNSET) private_dns_name = d.pop("private_dns_name", UNSET) private_ip_address = d.pop("private_ip_address", UNSET) privilege = d.pop("privilege", UNSET) public_access = d.pop("public_access", UNSET) public_ip_address = d.pop("public_ip_address", UNSET) public_ips = d.pop("public_ips", UNSET) public_network_access = d.pop("public_network_access", UNSET) region = d.pop("region", UNSET) resource_id = d.pop("resource_id", UNSET) resource_vpc_config = d.pop("resource_vpc_config", UNSET) resources_vpc_config = d.pop("resources_vpc_config", UNSET) restrict_public_buckets = d.pop("restrict_public_buckets", UNSET) scheme = d.pop("scheme", UNSET) security_groups = d.pop("security_groups", UNSET) service_name = d.pop("service_name", UNSET) storage_account_name = d.pop("storage_account_name", UNSET) tags = d.pop("tags", UNSET) target_group_arn = d.pop("target_group_arn", UNSET) target_health_descriptions = d.pop("target_health_descriptions", UNSET) task_arn = d.pop("task_arn", UNSET) task_definition = d.pop("task_definition", UNSET) task_definition_arn = d.pop("task_definition_arn", UNSET) user_groups = d.pop("user-groups", UNSET) user_id = d.pop("user_id", UNSET) users = d.pop("users", UNSET) vpc_id = d.pop("vpc_id", UNSET) vpc_options = d.pop("vpc_options", UNSET) vpc_security_group_ids = d.pop("vpc_security_group_ids", UNSET) vpc_security_groups = d.pop("vpc_security_groups", UNSET) ingesters_cloud_resource = cls( access_level=access_level, account_id=account_id, action=action, allow_blob_public_access=allow_blob_public_access, arn=arn, attached_policy_arns=attached_policy_arns, block_public_acls=block_public_acls, block_public_policy=block_public_policy, bucket_policy_is_public=bucket_policy_is_public, cidr_ipv4=cidr_ipv4, cloud_provider=cloud_provider, cluster_arn=cluster_arn, cluster_name=cluster_name, connectivity=connectivity, container_definitions=container_definitions, containers=containers, create_date=create_date, db_cluster_identifier=db_cluster_identifier, description=description, event_notification_configuration=event_notification_configuration, group=group, group_id=group_id, groups=groups, host_name=host_name, iam_instance_profile_arn=iam_instance_profile_arn, iam_instance_profile_id=iam_instance_profile_id, iam_policy=iam_policy, id=id, ignore_public_acls=ignore_public_acls, ingress_settings=ingress_settings, inline_policies=inline_policies, instance_id=instance_id, instance_profile_arns=instance_profile_arns, instance_type=instance_type, instances=instances, ip_configuration=ip_configuration, is_egress=is_egress, last_status=last_status, name=name, network_configuration=network_configuration, network_interfaces=network_interfaces, network_mode=network_mode, organization_id=organization_id, organization_master_account_arn=organization_master_account_arn, organization_master_account_email=organization_master_account_email, path=path, policy=policy, policy_std=policy_std, private_dns_name=private_dns_name, private_ip_address=private_ip_address, privilege=privilege, public_access=public_access, public_ip_address=public_ip_address, public_ips=public_ips, public_network_access=public_network_access, region=region, resource_id=resource_id, resource_vpc_config=resource_vpc_config, resources_vpc_config=resources_vpc_config, restrict_public_buckets=restrict_public_buckets, scheme=scheme, security_groups=security_groups, service_name=service_name, storage_account_name=storage_account_name, tags=tags, target_group_arn=target_group_arn, target_health_descriptions=target_health_descriptions, task_arn=task_arn, task_definition=task_definition, task_definition_arn=task_definition_arn, user_groups=user_groups, user_id=user_id, users=users, vpc_id=vpc_id, vpc_options=vpc_options, vpc_security_group_ids=vpc_security_group_ids, vpc_security_groups=vpc_security_groups, ) ingesters_cloud_resource.additional_properties = d return ingesters_cloud_resource @property def additional_keys(self) -> List[str]: return list(self.additional_properties.keys()) def __getitem__(self, key: str) -> Any: return self.additional_properties[key] def __setitem__(self, key: str, value: Any) -> None: self.additional_properties[key] = value def __delitem__(self, key: str) -> None: del self.additional_properties[key] def __contains__(self, key: str) -> bool: return key in self.additional_properties
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const child_process_1 = require("child_process"); const promises_1 = require("fs/promises"); const path_1 = require("path"); class Obfuscater { constructor() { // 初始化代码 } static get Instance() { if (!Obfuscater.instance) { Obfuscater.instance = new Obfuscater(); } return Obfuscater.instance; } // 混淆代码文件 obfuscateCodeFiles(filePaths) { return __awaiter(this, void 0, void 0, function* () { const obfuscateConfig = { target: 'node', deadCodeInjection: true, deadCodeInjectionThreshold: 1, //中度混淆 compact: true, controlFlowFlattening: true, controlFlowFlatteningThreshold: 0.75, debugProtection: false, debugProtectionInterval: 0, disableConsoleOutput: true, identifierNamesGenerator: 'hexadecimal', log: false, renameGlobals: false, rotateStringArray: true, selfDefending: true, shuffleStringArray: true, splitStrings: true, splitStringsChunkLength: 10, stringArray: true, stringArrayEncoding: ['base64'], stringArrayThreshold: 0.75, // transformObjectKeys: true, // 这个混淆选项打开会影响贪吃蛇游戏,勿打开 unicodeEscapeSequence: false, //轻度混淆 // compact: true, // controlFlowFlattening: false, // debugProtection: false, // debugProtectionInterval: false, // disableConsoleOutput: true, // identifierNamesGenerator: 'hexadecimal', // log: false, // renameGlobals: false, // rotateStringArray: true, // selfDefending: true, // shuffleStringArray: true, // splitStrings: false, // stringArray: true, // stringArrayEncoding: false, // stringArrayThreshold: 0.75, // unicodeEscapeSequence: false, //重度混淆 // compact: true, // controlFlowFlattening: true, // controlFlowFlatteningThreshold: 1, // debugProtection: true, // debugProtectionInterval: true, // disableConsoleOutput: true, // identifierNamesGenerator: 'hexadecimal', // log: false, // renameGlobals: false, // rotateStringArray: true, // selfDefending: true, // shuffleStringArray: true, // splitStrings: true, // splitStringsChunkLength: 5, // stringArray: true, // stringArrayEncoding: 'rc4', // stringArrayThreshold: 1, // transformObjectKeys: true, // 这个混淆选项打开会影响贪吃蛇游戏,勿打开 // unicodeEscapeSequence: false }; // for (const filePath of filePaths) { // const code = await readFile(filePath, 'utf8'); // const obfuscatedCode = obfuscate(code, midconfig).getObfuscatedCode(); // if (obfuscatedCode) { // console.log(`混淆文件成功: ${filePath}`); // writeFile(filePath, obfuscatedCode, 'utf8'); // }else{ // console.error(`混淆文件失败: ${filePath}`); // } // } let toolsPath = Editor.Project.path + "/tool/obfuscator"; let obfuscateConfigPath = toolsPath + "/ObfuscatorOptions.json"; let result = yield this.exec(`node -r ts-node/register ${toolsPath}/source/index.ts -p '${JSON.stringify(filePaths)}' -c ${obfuscateConfigPath}`, { env: Object.assign(Object.assign({}, process.env), { LANG: 'en_US.UTF-8' // 设置所需的字符编码 }) }); let succ = result.isSuccess; let err = result.err; let data = result.data; console.log("混淆代码data", JSON.stringify(data)); if (succ || err == null) { console.log("混淆代码成功"); } else { console.error("混淆代码失败: ", JSON.stringify(err)); } }); } obfuscateAllCodeFiles(folderPath, config) { return __awaiter(this, void 0, void 0, function* () { console.log("obfuscate config", JSON.stringify(config)); if (!config.isObfuscate) { return; } const pluginPath = (0, path_1.join)(__dirname, ".."); console.log("插件路径: ", pluginPath); let toolsPath = "./tools"; let obfuscateConfigPath = ""; switch (config.obSelect) { case "low": console.log("选择轻度混淆"); obfuscateConfigPath = (0, path_1.join)(pluginPath, toolsPath + "/configs/ObfuscatorOptionsLow.json"); break; case "medium": console.log("选择中度混淆"); obfuscateConfigPath = (0, path_1.join)(pluginPath, toolsPath + "/configs/ObfuscatorOptionsMedium.json"); break; case "high": console.log("选择重度混淆"); obfuscateConfigPath = (0, path_1.join)(pluginPath, toolsPath + "/configs/ObfuscatorOptionsHigh.json"); break; case "config": console.log("选择重度混淆"); obfuscateConfigPath = config.obConfigPath; break; default: console.error("未知的混淆选项"); return; } // 转化为绝对路径 console.log("混淆配置文件路径: ", obfuscateConfigPath.toString()); //检查配置文件是否存在 try { yield (0, promises_1.stat)(obfuscateConfigPath); console.log("配置文件存在: ", obfuscateConfigPath); } catch (error) { console.error("配置文件不存在: ", obfuscateConfigPath); return; } let result = yield this.spawn( // toolsPath + "/index.exe", (0, path_1.join)(pluginPath, toolsPath, "index.exe"), ["-p", folderPath, "-c", obfuscateConfigPath], { env: Object.assign(Object.assign({}, process.env), { LANG: 'en_US.UTF-8' // 设置所需的字符编码 }) }); let succ = result.isSuccess; let err = result.err; let data = result.data; console.log("混淆代码data", JSON.stringify(data)); if (succ || err == null) { console.log("混淆代码成功"); } else { console.error("混淆代码失败: ", JSON.stringify(err)); } }); } // 递归获取所有.js文件的地址 getAllJsFilePaths(folderPath_1) { return __awaiter(this, arguments, void 0, function* (folderPath, jsFilePaths = []) { const files = yield (0, promises_1.readdir)(folderPath); for (const file of files) { const filePath = (0, path_1.join)(folderPath, file); const fileStats = yield (0, promises_1.stat)(filePath); if (fileStats.isDirectory()) { if (file === 'cocos-js' || file === 'plugin' || file === 'jsb-adapter') { // 如果文件夹名字是"cocos-js",跳过处理 continue; } // 如果是子文件夹,递归处理子文件夹中的文件 yield this.getAllJsFilePaths(filePath, jsFilePaths); } else if (fileStats.isFile() && file.endsWith('.js')) { // 如果是.js文件,将其地址存储在数组中 jsFilePaths.push(filePath); } } return jsFilePaths; }); } /**@description 执行命令 */ exec(cmd, options, isLog = true) { return new Promise((resolve, reject) => { var _a, _b; isLog && console.log(`执行命令 : ${cmd}`); let result = (0, child_process_1.exec)(cmd, options, (err, stdout, stderr) => { if (err) { isLog && console.error(`执行命令 : ${cmd}失败`); isLog && console.error("err", err); isLog && console.error("stderr", stderr); resolve({ isSuccess: false, data: stdout, err: err }); } else { resolve({ isSuccess: true, data: stdout, err: err }); } }); (_a = result.stdout) === null || _a === void 0 ? void 0 : _a.on("data", (data) => { isLog && console.log(data); }); (_b = result.stderr) === null || _b === void 0 ? void 0 : _b.on("error", (data) => { isLog && console.error(data); }); }); } spawn(cmd, args, options, isLog = true) { return new Promise((resolve, reject) => { isLog && console.log(`执行命令 cmd: ${cmd}`); isLog && console.log(`执行命令 args: ${args}`); let ls = (0, child_process_1.spawn)(cmd, args, options); ls.stdout.on("data", (data) => { // buffer转字符串 let str = data.toString(); isLog && console.log("data", str); }); ls.stderr.on("data", (data) => { let str = data.toString(); isLog && console.error("stderr", str); }); ls.on("close", (code) => { if (code == 0) { resolve({ isSuccess: true, data: code, err: null }); } else { resolve({ isSuccess: false, data: code, err: null }); } }); }); } } exports.default = Obfuscater;
# coding=utf-8 import os from models import Employee from bs4 import BeautifulSoup from config import Config from mparser import ProfileParser from mparser import get_doc_bySelenium # @brief: 函数将过滤结果转化为Employee数据 # @tag: 输入为待处理的BeautifulSoup的tag对象 # @output:输出employee def handler(tag): name = tag.get_text() if not name: return None name = ''.join(name.split()) name = name.replace('*','') name = name.replace('﹡','') name = name.replace('※','') ass = tag.find_all('a') url = ass[0]['href'] if len(ass) != 0 else '' return Employee(name=name, url=url) def set_attr_hook(name,value): if name == 'departments': if len(value) > 32: return None elif name == 'email': if not '@' in value: return None return value # @doc: 输入为个人详情页的整个网页源码 # @output:输出employee,如果没有检测到内容返回None # employee可用属性(url, name, email, tel, title, profile, research, departments,fax,addr): def profile_handler(doc, name, url, path): filename = os.path.join(path, name + ".html") employee = Employee(name=name, url=url) # 只保存名称和个人主页,个人简历文件另存当前目录 soup = BeautifulSoup(doc, Config.SOUP_PARSER) divs = soup.find_all(name="div", attrs={"class":"darea"}, limit=1) if not divs or len(divs) == 0: return employee div = divs[0] if not os.path.exists(filename): with open(filename, 'wb') as fp: content = div.prettify() fp.write(content) fp.close() dnodes = div.find_all(name='div',class_=u"dnode") if not dnodes or len(dnodes) == 0: return employee lines = None target_node = None done = False for node in dnodes: lines = node.stripped_strings for count,line in enumerate(lines): if count >= 2: break; if line == u'联系方式': print "binggo!" target_node = node done = True break if done: break if not target_node: return employee lines = [] trs = node.find_all('tr') if trs and len(trs) != 0: for tr in trs: text = tr.get_text() if text: text = ''.join(text.split()) lines.append(text) else: lines = node.stripped_strings #lines = target_node.stripped_strings # text=div.get_text(strip=True) parser = ProfileParser(lines=lines,employee=employee,set_attr_hook=set_attr_hook) return parser.parse()
--- title: Generieren des Druckkanaldokuments durch Zusammenführen von Daten description: Erfahren Sie, wie Sie ein Dokument für den Druckkanal generieren, indem Sie die im Eingabe-Stream enthaltenen Daten zusammenführen. feature: Interactive Communication doc-type: article version: 6.4,6.5 topic: Development role: Developer level: Intermediate exl-id: 3bfbb4ef-0c51-445a-8d7b-43543a5fa191 last-substantial-update: 2019-07-07T00:00:00Z duration: 223 source-git-commit: af928e60410022f12207082467d3bd9b818af59d workflow-type: tm+mt source-wordcount: '445' ht-degree: 100% --- # Generieren von Druckkanaldokumenten mithilfe gesendeter Daten Druckkanaldokumente werden in der Regel durch Abrufen von Daten aus einer Backend-Datenquelle über den Get-Dienst des Formulardatenmodells generiert. In einigen Fällen müssen Sie möglicherweise Druckkanaldokumente mit den bereitgestellten Daten generieren. Beispiel: Die Kundin oder der Kunde füllt ein Formular zur Änderung der bzw. des Begünstigten aus, und Sie können ein Druckkanaldokument mit Daten aus dem gesendeten Formular generieren. Gehen Sie wie folgt vor, um dieses Anwendungsbeispiel zu übernehmen: ## Erstellen eines Vorbefüllungsdienstes Der Dienstname „ccm-print-test“ wird für den Zugriff auf diesen Dienst verwendet. Sobald dieser Vorbefüllungsdienst definiert ist, können Sie in Ihrer Servlet- oder Workflow-Prozessschrittimplementierung darauf zugreifen, um das Druckkanaldokument zu generieren. ```java import java.io.InputStream; import org.osgi.service.component.annotations.Component; import com.adobe.forms.common.service.ContentType; import com.adobe.forms.common.service.DataOptions; import com.adobe.forms.common.service.DataProvider; import com.adobe.forms.common.service.FormsException; import com.adobe.forms.common.service.PrefillData; @Component(immediate = true, service = {DataProvider.class}) public class ICPrefillService implements DataProvider { @Override public String getServiceDescription() { // TODO Auto-generated method stub return "Prefill Service for IC Print Channel"; } @Override public String getServiceName() { // TODO Auto-generated method stub return "ccm-print-test"; } @Override public PrefillData getPrefillData(DataOptions options) throws FormsException { // TODO Auto-generated method stub PrefillData data = null; if (options != null && options.getExtras() != null && options.getExtras().get("data") != null) { InputStream is = (InputStream) options.getExtras().get("data"); data = new PrefillData(is, options.getContentType() != null ? options.getContentType() : ContentType.JSON); } return data; } } ``` ### Erstellen der WorkflowProcess-Implementierung Das Code-Snippet zur WorkflowProcess-Implementierung wird unten gezeigt. Dieser Code wird ausgeführt, wenn der Prozessschritt im AEM-Workflow mit dieser Implementierung verknüpft ist. Diese Implementierung erwartet 3 Prozessargumente, die unten beschrieben werden: * Name des DataFile-Pfads, der beim Konfigurieren des adaptiven Formulars angegeben wird * Name der Druckkanalvorlage * Name des generierten Druckkanaldokuments Zeile 98 – Da das adaptive Formular auf dem Formulardatenmodell basiert, werden die Daten, die sich im Datenknoten von afBoundData befinden, extrahiert. Zeile 128 – Der Name des Datenoptionen-Dienstes wird festgelegt. Notieren Sie den Dienstnamen. Er muss mit dem in Zeile 45 der vorherigen Code-Auflistung zurückgegebenen Namen übereinstimmen. Zeile 135 – Dokument wird mithilfe der Rendermethode des PrintChannel-Objekts generiert. ```java String params = arg2.get("PROCESS_ARGS","string").toString(); String payloadPath = workItem.getWorkflowData().getPayload().toString(); String dataFile = params.split(",")[0]; final String icFileName = params.split(",")[1]; String dataFilePath = payloadPath + "/"+dataFile+"/jcr:content"; Session session = workflowSession.adaptTo(Session.class); Node xmlDataNode = null; try { xmlDataNode = session.getNode(dataFilePath); InputStream xmlDataStream = xmlDataNode.getProperty("jcr:data").getBinary().getStream(); JsonParser jsonParser = new JsonParser(); BufferedReader streamReader = null; try { streamReader = new BufferedReader(new InputStreamReader(xmlDataStream, "UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; try { while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String submittedDataXml = responseStrBuilder.toString(); JsonObject jsonObject = jsonParser.parse(submittedDataXml).getAsJsonObject().get("afData").getAsJsonObject() .get("afBoundData").getAsJsonObject().get("data").getAsJsonObject(); logger.info("Successfully Parsed gson" + jsonObject.toString()); InputStream targetStream = IOUtils.toInputStream(jsonObject.toString()); //InputStream targetStream = new ByteArrayInputStream(jsonObject.toString().getBytes()); // Node dataNode = session.getNode(formName); logger.info("Got resource using resource resolver" ); resHelper.callWith(getResolver.getFormsServiceResolver(), new Callable<Void>() { @Override public Void call() throws Exception { System.out.println("The target stream is "+targetStream.available()); // TODO Auto-generated method stub com.adobe.fd.ccm.channels.print.api.model.PrintChannel printChannel = null; String formName = params.split(",")[2]; logger.info("The form name I got was "+formName); printChannel = printChannelService.getPrintChannel(formName); logger.info("Did i get print channel?"); com.adobe.fd.ccm.channels.print.api.model.PrintChannelRenderOptions options = new com.adobe.fd.ccm.channels.print.api.model.PrintChannelRenderOptions(); options.setMergeDataOnServer(true); options.setRenderInteractive(false); com.adobe.forms.common.service.DataOptions dataOptions = new com.adobe.forms.common.service.DataOptions(); dataOptions.setServiceName(printChannel.getPrefillService()); // dataOptions.setExtras(map); dataOptions.setContentType(ContentType.JSON); logger.info("####Set the content type####"); dataOptions.setFormResource(getResolver.getFormsServiceResolver().getResource(formName)); dataOptions.setServiceName("ccm-print-test"); dataOptions.setExtras(new HashMap<String, Object>()); dataOptions.getExtras().put("data", targetStream); options.setDataOptions(dataOptions); logger.info("####Set the data options"); com.adobe.fd.ccm.channels.print.api.model.PrintDocument printDocument = printChannel .render(options); logger.info("####Generated the document"); com.adobe.aemfd.docmanager.Document uploadedDocument = new com.adobe.aemfd.docmanager.Document( printDocument.getInputStream()); logger.info("Generated the document"); Binary binary = session.getValueFactory().createBinary(printDocument.getInputStream()); Session jcrSession = workflowSession.adaptTo(Session.class); String dataFilePath = workItem.getWorkflowData().getPayload().toString(); Node dataFileNode = jcrSession.getNode(dataFilePath); Node icPdf = dataFileNode.addNode(icFileName, "nt:file"); Node contentNode = icPdf.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:data", binary); jcrSession.save(); logger.info("Copied the generated document"); uploadedDocument.close(); return null; } ``` Führen Sie die folgenden Schritte aus, um dies auf Ihrem Server zu testen: * [Konfigurieren Sie den Day CQ-Mail-Service.](https://helpx.adobe.com/de/experience-manager/6-5/communities/using/email.html)Dies ist erforderlich, um E-Mails mit dem als Anhang erstellten Dokument zu senden. * [Stellen Sie das Bundle zur Entwicklung mit Dienstbenutzenden bereit](/help/forms/assets/common-osgi-bundles/DevelopingWithServiceUser.jar) * Stellen Sie sicher, dass Sie den folgenden Eintrag in der Konfiguration des Apache Sling Service User Mapper Service hinzugefügt haben * **DevelopingWithServiceUser.core:getformsresourceresolver=fd-service** * [Laden Sie die Assets, die mit diesem Artikel in Verbindung stehen, herunter und entpacken Sie sie in Ihr Dateisystem.](assets/prefillservice.zip) * [Importieren Sie die folgenden Pakete mit AEM Package Manager](http://localhost:4502/crx/packmgr/index.jsp) 1. beneficiaryconfirmationic.zip 2. changeofbeneficiaryform.zip 3. generatebeneficiaryworkflow.zip * [Stellen Sie Folgendes mithilfe der AEM Felix-Web-Konsole bereit](http://localhost:4502/system/console/bundles) * GenerateIC.GenerateIC.core-1.0-SNAPSHOT.jar. Dieses Bundle enthält den in diesem Artikel erwähnten Code. * [Öffnen Sie ChangeOfBeneficiaryForm](http://localhost:4502/content/dam/formsanddocuments/changebeneficiary/jcr:content?wcmmode=disabled) * Stellen Sie sicher, dass das adaptive Formular für die Übermittlung an AEM Workflow konfiguriert ist, wie unten gezeigt. ![Bild](assets/generateic.PNG) * [Konfigurieren Sie das Workflow-Modell.](http://localhost:4502/editor.html/conf/global/settings/workflow/models/ChangesToBeneficiary.html)Stellen Sie sicher, dass die Prozessschritte und E-Mail-Komponenten gemäß Ihrer Umgebung konfiguriert sind. * [Erstellen Sie eine Vorschau der ChangeOfBeneficiaryForm.](http://localhost:4502/content/dam/formsanddocuments/changebeneficiary/jcr:content?wcmmode=disabled)Füllen Sie einige Details aus und senden Sie es. * Der Workflow sollte aufgerufen und das IC-Druckkanaldokument als Anlage an die Empfängerinnen bzw. Empfänger gesendet werden, die in der gesendeten E-Mail-Komponente angegeben sind.
@extends('layouts.backend-layout') @section('title', 'Employee Overtime List') @section('style') <link rel="stylesheet" type="text/css" href="{{ asset('css/Datatables/dataTables.bootstrap4.min.css') }}"> @endsection @section('breadcrumb-title') Employee Overtime @endsection @section('style') <style> th, td { white-space: pre-wrap !important; } </style> @endsection @section('content') <div class="ot_crud_page"> <div class="row"> <div class="col-md-3"> <div class="input-group input-group-sm input-group-primary"> <label class="input-group-addon">Date</label> {{ Form::date('date', now()->format('Y-m-d'), [ 'class' => 'form-control', 'id' => 'date', ]) }} </div> </div> <div class="col-md-3"> <div class="input-group input-group-sm input-group-primary"> <label class="input-group-addon" for="emp_name">Department</label> {{ Form::select('department_id', $departments, null, [ 'class' => 'form-control select2', 'id' => 'department_id', ]) }} </div> </div> <div class="col-md-3"> <div class="input-group input-group-sm input-group-primary"> <label class="input-group-addon" for="emp_name">Employee</label> {{ Form::select('employee_id[]', $employees, null, [ 'class' => 'form-control select2', 'id' => 'employee_id', 'multiple', ]) }} </div> </div> </div> <div class="row mt-3"> <div class="col-12 bulk_select_ot_records d-none my-2 ot_hour_container"> <input style="width:35px !important; height:33px !important; text-align:center" type="number" max="8" placeholder="H" class="h_input bulk_h_input"> : <input style="width:35px !important; height:33px !important; text-align:center" type="number" max="59" placeholder="M" class="m_input bulk_m_input"> <button class="ml-2 btn btn-sm btn-warning bulk_ot_hour_apply">Apply to Selected</button> <button class="ml-2 btn btn-sm btn-success bulk_ot_hour_save">Save Selected</button> </div> <div class="col-12"> <table class="table table-striped table-bordered dataTable ot_records_table"> </table> </div> </div> </div> @endsection @section('script') <script> $(document).ready(function() { $('#department_id').val(''); $('#employee_id').val(''); $('#department_id, #employee_id, #date').on('change', function() { if ($('#department_id').val() && $('#date').val()) { $('.ot_crud_page').waitMe({ effect: 'ios' }); $.ajax({ url: "{{ route('getEmployeeOtRecords') }}", method: 'GET', data: { date: $('#date').val(), department_id: $('#department_id').val(), employee_id: $('#employee_id').val(), }, success: function(response) { $('.ot_crud_page').waitMe("hide"); let html = ` <thead> <tr> <th><input type="checkbox" class="check_all_ot_records"></th> <th>Employee Name</th> <th>Employee Code</th> <th>Over Time Hour</th> <th>Action</th> </tr> </thead> <tbody>`; for (const item of response) { html += `<tr employee_id="${item.employee_id}" class="ot_hour_container"> <td><input type="checkbox" class="check_single_ot_record"></td> <td>${item.emp_name}</td> <td>${item.emp_code}</td> <td > <span>`; if (item.ot_hour != null) { html += ` <input style="width:30px !important; height:30px !important; text-align:center" type="number" max="8" placeholder="H" class="h_input" value=${item.ot_hour.split(':')[0]}> : <input style="width:30px !important; height:30px !important; text-align:center" type="number" max="59" placeholder="M" class="m_input" value=${item.ot_hour.split(':')[1]} > `; } else { html += ` <input style="width:30px !important; height:30px !important; text-align:center" type="number" max="8" placeholder="H" class="h_input"> : <input style="width:30px !important; height:30px !important; text-align:center" type="number" max="59" placeholder="M" class="m_input"> `; } html += `</span> </td> <td><button class="btn btn-sm rounded py-1 px-4 btn-success ot_single_save">save</button></td> </tr>`; } html += `</tbody>`; $('.ot_records_table').html(html); }, error: function(error) { } }); } }); $(document).on('click', '.ot_single_save', function() { let h_input = $(this).closest('.ot_hour_container').find('.h_input').val(); let m_input = $(this).closest('.ot_hour_container').find('.m_input').val(); if (h_input != '' && m_input != '') { $(this).waitMe({ effect: 'roundBounce', maxSize: 30, }); let records = []; records.push({ employee_id: $(this).closest('.ot_hour_container').attr('employee_id'), date: $('#date').val(), ot_hour: h_input + ":" + m_input }) save_ot_record(records).then(() => { $(this).waitMe("hide"); }); } }) $(document).on('click', '.bulk_ot_hour_save', function() { $('.ot_records_table').waitMe({ effect: 'roundBounce', maxSize: 60, }); let records = []; $('.check_single_ot_record:checked').each(function(index, element) { records.push({ employee_id: $(this).closest('.ot_hour_container').attr( 'employee_id'), date: $('#date').val(), ot_hour: $(this).closest('.ot_hour_container').find('.h_input') .val() + ":" + $(this).closest('tr').find('.m_input').val() }) }) save_ot_record(records).then(() => { $('.ot_records_table').waitMe("hide"); }); }) function save_ot_record(records) { return new Promise(function(resolve, reject) { $.ajax({ url: "{{ route('saveEmployeeOtRecords') }}", method: 'POST', data: { ot_records: records, date: $('#date').val(), _token: "{{ csrf_token() }}", }, success: function(response) { Toastify({ text: "Over Time Records Saved", close: true, gravity: "top", position: "right", style: { background: "#2ed8b6", minWidth: '100px', fontSize: '.8rem' } }).showToast(); resolve(response); }, error: function(error) { reject(error); } }); }); } $(document).on('keyup', '.h_input', function() { $(this).off('keyup'); if ($(this).val() > 8) { $(this).val(8); $(this).closest('.ot_hour_container').find('.m_input').val(0); } if ($(this).val() == 8) { $(this).closest('.ot_hour_container').find('.m_input').val(0); } $(this).on('keyup', arguments.callee); }) $(document).on('keyup', '.m_input', function() { $(this).off('keyup'); if ($(this).closest('.ot_hour_container').find('.h_input').val() == 8) { $(this).val(00) } if ($(this).val() > 59) { $(this).val(59) } $(this).on('keyup', arguments.callee); }) $(document).on('keyup', ".m_input, .h_input, .bulk_m_input, .bulk_h_input", function() { if (isNaN(parseInt($(this).val()))) { $(this).val(0); } }) $(document).on('click', '.check_all_ot_records', function() { if ($(this).prop('checked')) { $('.check_single_ot_record').prop('checked', true); } else { $('.check_single_ot_record').prop('checked', false); } }) $(document).on('click', '.check_all_ot_records, .check_single_ot_record', function() { $('.check_single_ot_record').trigger('change') if ($('.check_single_ot_record:checked').length > 0) { $(".bulk_select_ot_records").removeClass('d-none'); } else { $(".bulk_select_ot_records").addClass('d-none'); } }) $(document).on('click', '.bulk_ot_hour_apply', function() { $('.check_single_ot_record:checked').closest('.ot_hour_container').find('.h_input').val($( '.bulk_h_input') .val()); $('.check_single_ot_record:checked').closest('.ot_hour_container').find('.m_input').val($( '.bulk_m_input') .val()); }) $('#department_id').change(() => { $('#employee_id').waitMe({ effect: 'ios', maxSize: 25 }); $.ajax({ url: "{{ route('getDepartmentWiseEmployees') }}", type: 'GET', dataType: 'json', data: { _token: '{{ csrf_token() }}', department_id: $('#department_id ').val() }, success: function(response) { $('#employee_id').empty(); $('#employee_id').append('<option value="">' + "All" + '</option>'); $.each(response, function(index, value) { $('#employee_id').append('<option value="' + value.id + '">' + value .text + '</option>'); }); $('#employee_id').waitMe("hide"); }, error: function(jqXHR, textStatus, errorThrown) { $('#employee_id').waitMe("hide"); } }); }); }); </script> @endsection
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="model.*"%> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>uFIT</title> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- <link rel="stylesheet" type="text/css" href="css/app.css"> --> <!-- Check to see if the user is logged in. Otherwise, redirect back to the login page.--> <% session = request.getSession(); System.out.println(session); if (session.getAttribute("username") == null) { response.sendRedirect("login.jsp"); } %> </head> <style> * { box-sizing: border-box; } #myInput { background-image: url('/css/searchicon.png'); background-position: 10px 10px; background-repeat: no-repeat; width: 100%; font-size: 16px; padding: 12px 20px 12px 40px; border: 1px solid #ddd; margin-bottom: 12px; } #myTable { border-collapse: collapse; width: 10%; border: 1px solid #ddd; font-size: 18px; } #myTable th, #myTable td { text-align: left; padding: 12px; } #myTable tr { border-bottom: 1px solid #ddd; } #myTable tr.header, #myTable tr:hover { background-color: #f1f1f1; } </style> </head> <% Member member = (Member) session.getAttribute("currentSessionUser"); String username = (String) session.getAttribute("username"); String firstname = (String) session.getAttribute("firstname"); String lastname = (String) session.getAttribute("lastname"); //int memberid = (Integer) session.getAttribute("memberid"); %> <body> <%@ include file="navbar_loggedin.jsp"%> <!-- if you need to access the username firstname and last name, it is declared below --> <!-- example of accessing names --> Hi <%=firstname %>! Here are classes we offer. <!-- back end needs to pass in the table of classes --> <input style="width:20%; margin-top:70px; margin-left:247px; border=0" align="center" type="text" id="myInput" onkeyup="myFunction()" placeholder="Search class" title="Search"> <table id="myTable" style="width:60%; margin-top:20px; margin-left:10px; border=0" align="center"> <tr class="header"> <th style="width:20%;">Class</th> <th style="width:20%;">Level</th> <th style="width:40%;">Location</th> <th style="width:60%;">Date/Time</th> </tr> <tr> <td>Weightlifting</td> <td>Beginner</td> <td>Harthouse Upper Gym</td> <td>October 29th, 2:00PM</td> </tr> <tr> <td>Tennis</td> <td>Advanced</td> <td>Athletic Centre Upper Gym</td> <td>October 30th, 2:00PM</td> </tr> <tr> <td>Yoga</td> <td>Intermediate</td> <td>Goldring Lower Gym</td> <td>October 30th, 2:00PM</td> </tr> </table> <script> function myFunction() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> <script> $(document).ready(function() { var table = $('#example').myTable(); $('#example tbody').on( 'click', 'tr', function () { $(this).toggleClass('selected'); } ); $('#button').click( function () { alert( table.rows('.selected').data().length +' row(s) selected' ); } ); } ); </script> </body> </html>
{% load static%} <!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 href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <link rel="stylesheet" href="{% static 'css/styleCabecera.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'css/styleCliente.css' %}" type="text/css"> <title>Clientes</title> </head> <body> <header class="contheader"> <div class="d-flex align-items-center justify-content-md-start" style="background-color: #003301f4;" height="100"> <!-- LOGO IZQUIERDA --> <div class="p-1 ms-5 me-5"> <img src='{% static "img/logo.png" %}' alt="" width="100" height="100"> </div> <!-- TITULO PRINCIPAL --> <div class="tituloPrincipal fw-bold">SUPERMERCADO</div> </div> </header> <div class="barraNav pe-3"> <div class="text1 me-3">Bienvenido usuario: {{request.session.user}} </div> <a href="{% url 'index' %}"><button class="btn rounded-pill btn-outline-warning" type="button">Inicio</button></a> <a href="{% url 'MenuAdmin' %}"><button class="btn rounded-pill btn-outline-warning" type="button">Menú</button></a> <a href="{% url 'cerrar' %}"><button class="btn rounded-pill btn-outline-warning" type="button">Cerrar sesión</button></a> </div> <div class="tabla"> <div class="text-center fs-1 fw-bold mb-5">Clientes</div> <div class="d-grid gap-2 d-md-flex justify-content-md-center"> <form class="row g-3" action="{% url 'BuscarCliente' %}" method="post"> {% csrf_token %} <div class="col-auto"> <input class="form-control" type="text" name="usuario" required placeholder="Usuario"> </div> <div class="col-auto"> <button type="submit" class="btn rounded-pill btn-outline-primary">Buscar</button> </div> </form> <a href="{% url 'ListaClientes' %}"> <button class="btn rounded-pill btn-outline-primary" type="button">Todos</button> </a> <a href="{% url 'FormCliente' %}"> <button class="btn rounded-pill btn-outline-success" type="button">Agregar Cliente</button> </a> </div> {% if Mensaje%} <div class="alert alert-success mt-3" role="alert"> {{Mensaje}} </div> {% endif%} {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }} mt-3" role="alert"> {{ message }} </div> {% endfor %} {% endif %} {% if Error%} <div class="alert alert-danger mt-3" role="alert"> {{Error}} </div> {% endif%} <table class="table table-bordered table-striped table-hover mt-2"> <thead> <tr align="center"> <th scope="col-auto">USUARIO</th> <th scope="col-auto">CONTRASEÑA</th> <th scope="col-auto">NOMBRE</th> <th scope="col-auto">APELLIDO</th> <th scope="col-auto">EMAIL</th> <th scope="col-auto">TELEFONO</th> <th scope="col-auto">USER ADMIN</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> {% for cli in clientes%} <tr scope="row"> <td>{{cli.CLI_User}}</td> <td>{{cli.CLI_Password}}</td> <td>{{cli.CLI_Names}}</td> <td>{{cli.CLI_LastNames}}</td> <td>{{cli.CLI_Email}}</td> <td>{{cli.CLI_CellPhone}}</td> <td>{{cli.CLI_AD_User_id}}</td> <td align="center"><a href="{% url 'FormEditarCliente' cli.CLI_User %}"><button type="button" class="btn rounded-pill btn-outline-warning">Editar</button></a></td> <td align="center"><a href="{% url 'EliminarCliente' cli.CLI_User %}"><button type="button" class="btn rounded-pill btn-outline-danger">Eliminar</button></a></td> </tr> {% endfor%} </tbody> </table> </div> </body> </html>
import { Accordion as BaseAccordion, AccordionContent, AccordionItem, AccordionTrigger, } from "@/components/ui/accordion"; import { dateRange } from "@lib/utils"; import { Badge } from "./ui/badge"; interface Props { data: { data: { company: string; role: string; dateStart: string; dateEnd: string; isVolunteer: boolean; isCourseWork: boolean; jobdesc: string[]; } }[]; } export function Accordion({ data }: Props) { return ( <BaseAccordion type="single" collapsible className="w-full"> {data.map((item, i) => { return ( <AccordionItem value={`item-${i.toFixed()}`}> <AccordionTrigger> <div className="flex w-full flex-row justify-between gap-2 items-center pr-3"> <div> <div className="font-semibold text-black dark:text-white text-left"> {item.data.role} {item.data.isVolunteer && <Badge variant="outline">Volunteer</Badge>} {item.data.isCourseWork && <Badge variant="outline">Course Work</Badge>} </div> <div className="text-sm opacity-75 text-left"> {item.data.company} </div> </div> <div className="text-sm opacity-75 md:text-right"> {dateRange(item.data.dateStart, item.data.dateEnd)} </div> </div> </AccordionTrigger> <AccordionContent> {item.data.jobdesc.map((desc, i) => ( <div key={i} className="text-sm opacity-75"> • {desc} </div> ))} </AccordionContent> </AccordionItem> ); })} </BaseAccordion> ); }
#include <cmath> #include <fstream> #include <vector> #include <TGraph.h> #include <TF1.h> #include <TCanvas.h> #include <TH2D.h> #include <TApplication.h> #include <TStyle.h> #include <TSystem.h> #include "OdeSolver.h" #include "Vector3.h" #include "MatPoint.h" using namespace std; Vector3 fInternal(unsigned int i,unsigned int j, double t, vector<MatPoint> p){ //i soggetto a forza gen da j //STEP 2 definizione forza interna // * ritorna la forza interna che il corpo j esercita su i Vector3 forza_int(p[j].GravField( p[i].R() ) * p[i].Mass()); return forza_int; } Vector3 fExternal(unsigned int i, double t, vector<MatPoint> p){ //STEP 2 definizione forza esterna // * ritorna la forza esterna sul corpo i return Vector3(); } int main(){ TApplication app("app",0,NULL); gStyle->SetOptStat(0); //Lettura dei dati dal file double mass; double x,y,z,vx,vy,vz; ifstream f("fileInput"); vector<MatPoint> vectMat(0); OdeSolver ode("Rk4", vectMat); // STEP 1 - opzione 1 // * Creazione OdeSolver vuoto (senza passare vector<MatPoint>); // * Assegnazione dei MatPoint con il metodo AddMatPoint // STEP 1 - opzione 2 // * Creazione e riempimento vector<MatPoint> // * Creazione di OdeSolver passando vector<MatPoint> while (f >> mass >> vx >> x >> vy >> y >> vz >> z){ MatPoint temp(mass, 0, Vector3(x, y, z), Vector3(vx, vy, vz)); ode.AddMatPoint(temp); } // Creazione classe OdeSolver (per la soluzione dell'equ. diff.) ode.fInternal = fInternal; ode.fExternal = fExternal; ode.DeltaT(0.5); //Creazione dei grafici (uno per pianeta) vector<TGraph> gr(ode.N()); TCanvas c("c","",10,10,500,500); //Preparazione grafico delle coordinate dei pianeti double size=5; // 5 unita' astronimiche gPad->DrawFrame(-size,-size,size,size); int color[10]={kOrange+1,kViolet+1,kGreen+2,kAzure+1,kRed+2,kRed-7,kCyan-8,kBlue-7,kBlue+1,kBlue+2}; for (unsigned int i=0;i<ode.N();i++){ gr[i].SetPoint(0,ode.GetMatPoint(i).R().X(),ode.GetMatPoint(i).R().Y()); gr[i].SetMarkerColor(color[i]); gr[i].SetMarkerStyle(20); gr[i].SetMarkerSize(0.1); if (i==0) gr[i].SetMarkerSize(1); gr[i].Draw("P"); } gPad->Modified(); gPad->Update(); //app.Run(true); //Run del metodo numerico + grafico in tempo reale delle coordinate e del mom. angolare totale while (ode.T()<3000){ ode.Step(); for (unsigned int i=0;i<ode.N();i++){ //STEP 4 riempimento delle grafico gr[i] con le coordinate aggiornate dei pianeti gr[i].SetPoint(gr[i].GetN(), ode.GetMatPoint(i).R().X(), ode.GetMatPoint(i).R().Y()); // * accedere al MatPoint i-esimo, al vettore di coordinate spaziali, alla coordinata voluta // * inserire nel grafico gr[i] le coordinate X e Y // N.B. L'indice del nuovo punto da inserire è pari al numero di punti già presente in ciascun grafico } gPad->Modified(); gPad->Update(); gSystem->ProcessEvents(); } app.Run(true); return 0; }
import PlayedGameList from "../../played-game-list/PlayedGameList"; import "./custom-tooltip.scss"; /** * playedGames를 indexValue로 전달받았을 경우 tooltip에 playedGames를 그림 * @param {*} props * @param {*} id * @param {*} playedGames * @returns */ const CustomTooltip = ({ ...props }) => { let { color, value, id, data } = props; const transferredData = data.category; const parsedData = JSON.parse(transferredData); const barIndex = parsedData.shift(); const [streaming, keys] = parsedData; const tooltipData = streaming?.map((item, index) => { return { playedGames: item.played_games, title: item.title, key: keys[index], }; }); const currentData = tooltipData?.find((item) => item.key === id); return ( <div className="tooltip-container" style={{ color }}> <div className="head" style={{ borderBottom: `1px solid ${color}` }}> {id} </div> <div className="body"> {currentData && <p className="streaming-title">{currentData.title}</p>} <div className="properties"> <div className="keys">{barIndex}</div> <div className="value"> <span>{value}</span> <span className="unit"></span> </div> </div> </div> {currentData && ( <div className="game-list-box"> <PlayedGameList playedGames={currentData?.playedGames} isTooltip /> </div> )} </div> ); }; export default CustomTooltip;
package com.example.vinid_icecreams.di import android.content.Context import com.example.vinid_icecreams.MyApplication import com.example.vinid_icecreams.di.repoModule.RepoModule import com.example.vinid_icecreams.di.viewModelModule.ViewModelModule import com.example.vinid_icecreams.di.viewModule.ViewBuilder import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjector import dagger.android.support.AndroidSupportInjectionModule import javax.inject.Singleton @Singleton @Component( modules = [RepoModule::class, ViewModelModule::class, ViewBuilder::class, AndroidSupportInjectionModule::class] ) interface AppComponent : AndroidInjector<MyApplication> { @Component.Factory interface Factory { fun create(@BindsInstance applicationContext: Context): AppComponent } }
package com.example.shifumi.game; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; /** * Classe de gestion du jeu */ public final class Game { /** * Enum de gestion des deux joueurs */ private enum ScoreKey { PLAYER, OPPONENT } private final Map<ScoreKey, Integer> scores; /** * Retourne le score actuel du joueur * * @return score du joueur */ public int getPlayerScore() { return scores.get(ScoreKey.PLAYER); } /** * Retourne le score actuel de l'opposent * * @return score de l'opposent */ public int getOpponentScore() { return scores.get(ScoreKey.OPPONENT); } private final List<VictoryCondition> victoryConditions; /** * Réinitialise le score des deux joueurs */ public Game() { scores = new EnumMap<>(ScoreKey.class); resetScores(); victoryConditions = new ArrayList<>(Arrays.asList( new VictoryCondition(Choice.ROCK, Choice.PAPER), new VictoryCondition(Choice.PAPER, Choice.SCISSORS), new VictoryCondition(Choice.SCISSORS, Choice.ROCK) )); } /** * Convertir un booléen en résultat * * @param hasWon vrai si le joueur a gangé la manche * @return l'enum Result correspondant */ private Result resultMapper(boolean hasWon) { return hasWon ? Result.WIN : Result.LOST; } /** * Vérifie si le joueur a gangé la manche * * @param playerChoice choix sélectionné par le joueur * @param opponentChoice choix sélectionné par l'opposent * @return le résultat de la manche : WIN pour gagner, LOST pour perdu ou DRAW pour match null */ public Result hasWon(Choice playerChoice, Choice opponentChoice) { if (playerChoice.equals(opponentChoice)) { return Result.DRAW; // match nul } for (VictoryCondition victoryCondition : victoryConditions) { if (victoryCondition.opponentChoice.equals(opponentChoice)) { return resultMapper(victoryCondition.hasWon(playerChoice)); } } return Result.LOST; } /** * Mise à jour des scores des deux jouers de la partie * * @param result résultat de la manche */ public void updateScore(Result result) { if (result.equals(Result.DRAW)) { return; } ScoreKey key = result.equals(Result.WIN) ? ScoreKey.PLAYER : ScoreKey.OPPONENT; scores.put(key, scores.get(key) + 1); } /** * Remise à zéro des scores des deux joueurs */ public void resetScores() { for (ScoreKey key : ScoreKey.values()) { scores.put(key, 0); } } }
import { useState, useContext, createContext } from 'react'; import { Container, Inner, Title, Item, Header, Body, } from './styles/accordion'; const ToggleContext = createContext(); const Accordion = ({ children, ...restProps }) => { return ( <Container {...restProps}> <Inner>{children}</Inner> </Container> ); }; Accordion.Title = ({ children, ...restProps }) => { return <Title {...restProps}>{children}</Title>; }; Accordion.Item = ({ children, ...restProps }) => { // eslint-disable-next-line react-hooks/rules-of-hooks const [toggleShow, setToggleShow] = useState(false); return ( <ToggleContext.Provider value={{ toggleShow, setToggleShow }}> <Item {...restProps}>{children}</Item> </ToggleContext.Provider> ); }; Accordion.Header = ({ children, ...restProps }) => { // eslint-disable-next-line react-hooks/rules-of-hooks const { toggleShow, setToggleShow } = useContext(ToggleContext); return ( <Header {...restProps} onClick={() => setToggleShow((toggleShow) => !toggleShow)} > {children} {toggleShow ? ( <img src="/images/icons/close-slim.png" alt="Close" /> ) : ( <img src="/images/icons/add.png" alt="Add" /> )} </Header> ); }; Accordion.Body = ({ children, ...restProps }) => { // eslint-disable-next-line react-hooks/rules-of-hooks const { toggleShow } = useContext(ToggleContext); return toggleShow ? ( <Body {...restProps}>{children}</Body> ) : ( <Body style={{ 'max-height': '0', padding: '0' }} {...restProps} /> ); }; export default Accordion;
--- title: spring指南——接入网络上提供的RESTful Web服务 date: 2017-04-16T19:07:01+08:00 draft: false toc: true comments: true aliases: - /detail/67 - /detail/67/ tags: - untagged --- > 本指南将引导您完成创建接入网络上提供的RESTful Web服务的应用程序的过程。 ### 1、你需要构建的什么 你将构建一个使用spring `RestTemplate`来取回一个Spring Boot quotation的应用,Spring Boot quotation来自这个web api: http://gturnquist-quoters.cfapps.io/api/random 也就是说,你的app需要使用一些外部的RESTful web api,如微信api接口等,`restTemplate`可以完成从http请求到解析数据到填充实体类的全部过程 ### 2、你需要什么 * 15分钟时间 * 一个你喜欢的文本编辑器或者IDE * JDK 1.8 或更新 * Gradle 2.3+ 或 Maven 3.0+ * 您还可以将代码直接导入到IDE中: * Spring Tool Suite (STS) * IntelliJ IDEA ### 3、如何完成本指南 与大多数“入门指南”指南一样,您可以从头开始,完成每一步,也可以绕过已经熟悉的基本设置步骤。无论哪种方式,你都会得到工作代码。 要从头开始,请转到 [4、使用Gradle构建](#4、使用Gradle构建) 要跳过基本操作,请执行以下操作: * 下载并解压本文档的源码,或者使用git克隆 `git clone https://github.com/spring-guides/gs-consuming-rest.git` * `cd` 进入 `gs-consuming-rest/initial` * 跳转到 [获取REST资源](#7、获取REST资源) 当你完成后,你可以对照`gs-consuming-rest/complete`检查你的代码 ``` buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'org.springframework.boot' jar { baseName = 'gs-consuming-rest' version = '0.1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile("org.springframework.boot:spring-boot-starter") compile("org.springframework:spring-web") compile("com.fasterxml.jackson.core:jackson-databind") testCompile("junit:junit") } ``` ### 4、使用Gradle构建 首先你要设置一个基本的构建脚本。你可以使用任意一种你喜欢构建工具在构建Spring应用,此外Maven和 Gradle的构建方式在这里。如果你不熟悉他们请参考[Building Java Projects with Gradle](https://spring.io/guides/gs/gradle) 或者[Building Java Projects with Maven](https://spring.io/guides/gs/maven). #### (1)创建目录结构 在您选择的项目目录中,创建以下子目录结构;例如在类unix系统中用`mkdir -p src/main/java/hello`创建 ``` └── src └── main └── java └── hello ``` #### (2)创建`Gradle`构建文件 下面是[初始化的Gradle构建文件](https://github.com/spring-guides/gs-consuming-rest/blob/master/initial/build.gradle). `build.gradle`文件 ``` buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'org.springframework.boot' jar { baseName = 'gs-rest-service' version = '0.1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile('org.springframework.boot:spring-boot-starter-test') } ``` Spring BootGradle插件提供了许多方便的功能: * 他收集所有的jar文件在classpath中并可以构建一个单独的(不依赖web容器)、可运行的,更方便执行和传输您的服务"über-jar" * 它搜索`public static void main()`方法来标记为可运行类。 * 它提供了一个内嵌的依赖关系解析器,可以设置版本号与[Spring Boot的依赖](#https://github.com/spring-projects/spring-boot/blob/master/spring-boot-dependencies/pom.xml)相匹配。您可以覆盖任何您想要的版本,当然它将默认为Boot的所选版本集合 ### 5、使用Maven构建 首先你要设置一个基本的构建脚本。你可以使用任意一种你喜欢构建工具在构建Spring应用,此外Maven和 Gradle的构建方式在这里。如果你不熟悉他们请参考[Building Java Projects with Gradle](https://spring.io/guides/gs/gradle) 或者[Building Java Projects with Maven](https://spring.io/guides/gs/maven). #### (1)创建目录结构 在您选择的项目目录中,创建以下子目录结构;例如在类unix系统中用`mkdir -p src/main/java/hello`创建 ``` └── src └── main └── java └── hello ``` #### (2)创建`Maven`构建文件 `pom.xml`文件 ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework</groupId> <artifactId>gs-consuming-rest</artifactId> <version>0.1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` Spring BootGradle插件提供了许多方便的功能: * 他收集所有的jar文件在classpath中并可以构建一个单独的(不依赖web容器)、可运行的,更方便执行和传输您的服务"über-jar" * 它搜索`public static void main()`方法来标记为可运行类。 * 它提供了一个内嵌的依赖关系解析器,可以设置版本号与[Spring Boot的依赖](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-dependencies/pom.xml)相匹配。您可以覆盖任何您想要的版本,当然它将默认为Boot的所选版本集合 ### 6、使用你的IDE构建 * 阅读如何直接通过 [Spring Tool Suite](61)来导出代码. * 阅读如何通过[IntelliJ IDEA](63)来导出代码. ### 7、获取REST资源 完成项目设置后,您可以创建一个使用RESTful服务的简单应用程序。 测试的RESTful服务已经在 https://gturnquist-quoters.cfapps.io/api/random 上部署了。它随机提取有关Spring Boot的quotes ,并将其作为JSON文档返回。 如果您通过Web浏览器或curl请求该URL,您将收到一个如下所示的JSON文档: ```json { type: "success", value: { id: 10, quote: "Really loving Spring Boot, makes stand alone Spring apps easy." } } ``` 足够简单,但是通过浏览器或通过curl获取不是非常有用的。 使用REST Web服务的更有用的方法是以编程方式。为了帮助您完成该任务,Spring提供了一个名为[`RestTemplate`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html)的方便的模板类。`RestTemplate`使大多数RESTful服务像咒语一样一行完成。甚至可以将该数据绑定到自定义域类型。 首先,创建一个实体类以包含所需的数据。 `src/main/java/hello/Quote.java` ```java package hello; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Quote { private String type; private Value value; public Quote() { } public String getType() { return type; } public void setType(String type) { this.type = type; } public Value getValue() { return value; } public void setValue(Value value) { this.value = value; } @Override public String toString() { return "Quote{" + "type='" + type + '\'' + ", value=" + value + '}'; } } ``` 如您所见,这是一个简单的Java类,具有少量属性和匹配的getter方法。它使用Jackson JSON处理库中的`@JsonIgnoreProperties`进行注释,表明任何未绑定在此类型中的属性都应被忽略。 为了直接将数据绑定到您的自定义类型,您需要指定与从API返回的JSON文档中的键完全相同的变量名称。如果JSON文档中的变量名和键不匹配,您需要使用@JsonProperty注释来指定JSON文档的确切键。需要一个额外的类来嵌入内部引号本身。 `src/main/java/hello/Value.java` ```java package hello; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Value { private Long id; private String quote; public Value() { } public Long getId() { return this.id; } public String getQuote() { return this.quote; } public void setId(Long id) { this.id = id; } public void setQuote(String quote) { this.quote = quote; } @Override public String toString() { return "Value{" + "id=" + id + ", quote='" + quote + '\'' + '}'; } } ``` 这使用相同的注解,但只是映射到其他数据字段。 ### 8、使应用可执行 尽管可以将此服务打包成传统[WAR](https://spring.io/understanding/WAR)文件,以部署到外部应用程序服务器。下面演示的更简单的方法创建了一个独立的应用程序。You package everything in a single, executable JAR file, driven by a good old Java main() method. 你可以将所有的东西打包成一个单独的可执行的JAR 文件,由一个好的传统的java Main()方法驱动。这样,你需要使用Spring支持的Tomcat servlet容器嵌入到HTTP运行时,而不是部署到外部实例。 现在,您可以编写使用`RestTemplate`的Application类来获取数据来Spring Boot quotation服务,来填充实体类,以方便业务逻辑的使用 `src/main/java/hello/Application.java`文件 ```java public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String args[]) { RestTemplate restTemplate = new RestTemplate(); Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); } } ``` 因为Jackson JSON处理库已经加入是类路径中,`RestTemplate`将使用它([通过消息转换器](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/HttpMessageConverter.html))将传入的JSON数据转换为`Quote`对象。从那里,Quote对象的内容将被记录到控制台。 在这里,您只使用RestTemplate进行HTTP GET请求。但是RestTemplate还支持其他HTTP动词,如POST,PUT和DELETE。 ### 9、使用Spring Boot管理应用程序生命周期 到目前为止,我们在应用程序中没有使用Spring Boot,但是这样做有一些优势来做这些,这并不难做到。其中一个优点是我们可能希望让Spring Boot来管理`RestTemplate`中的消息转换器,这样定制很容易以声明方式添加。我们在主类上使用`@SpringBootApplication`,并转换main方法来启动它。最后我们将`RestTemplate`移动到一个`CommandLineRunner`回调,因此它在启动时由Spring Boot执行: `src/main/java/hello/Application.java`文件 ```java package hello; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String args[]) { SpringApplication.run(Application.class); } @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } @Bean public CommandLineRunner run(RestTemplate restTemplate) throws Exception { return args -> { Quote quote = restTemplate.getForObject( "http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); }; } } ``` `RestTemplateBuilder`由Spring注入,如果您使用它来创建`RestTemplate`,那么您将受益于Spring引导中使用消息转换器和请求工厂的所有自动配置。我们还将`RestTemplate`解压缩成`@Bean`,使其更容易测试(这是可以被模仿的更简单的方式) **构建可执行的JAR** 您可以使用Gradle或Maven从命令行运行应用程序。或者,您可以构建一个包含所有必需依赖项,类和资源的单个可执行JAR文件,并运行该文件。这使得在整个开发生命周期,跨不同环境等方面,可以轻松地将服务作为应用程序进行发布,版本和部署。 如果您使用Gradle,您可以使用`./gradlew bootRun`运行应用程序。或者您可以使用`./gradlew build`来构建JAR文件。然后可以运行JAR文件: ```bash java -jar build/libs/gs-consuming-rest-0.1.0.jar ``` 如果您使用Maven,则可以使用`./mvnw spring-boot:run`。或者您可以使用`./mvnw clean package`来构建JAR文件。然后可以运行JAR文件: ```bash java -jar target/gs-consuming-rest-0.1.0.jar ``` > 上面的过程将创建一个可运行的JAR。您也可以选择[构建一个经典的WAR文件](65)。 你应该看到如下的输出,随机引用: ``` 2015-09-23 14:22:26.415 INFO 23613 --- [main] hello.Application : Quote{type='success', value=Value{id=12, quote='@springboot with @springframework is pure productivity! Who said in #java one has to write double the code than in other langs? #newFavLib'}} ``` > 如果你看到错误:`Could not extract response: no suitable HttpMessageConverter found for response type [class hello.Quote]`。您可能处于无法连接到后端服务的环境中(如果您能够访问该服务,则会发送JSON)。也许你是企业代理的背后?尝试将标准系统属性`http.proxyHost`和`http.proxyPort`设置为适合您的环境的值。 ### 10、总结 恭喜!您刚刚使用Spring开发了一个RESTful Web服务。 想去写一个新的指南或者为我们的指南做贡献?请检出我们的[contribution guidelines](#https://github.com/spring-guides/getting-started-guides/wiki)。 > 所有的指南使用 ASLv2开源协议 和 [Attribution, NoDerivatives creative commons license](https://creativecommons.org/licenses/by-nd/3.0/) 来发布
import React from 'react' import { Box, Card, CardContent, Grid, TextField, Typography, FormControl, FormLabel, FormHelperText, InputLabel, Input, InputAdornment, IconButton, Button } from '@mui/material' import Visibility from '@mui/icons-material/Visibility'; import VisibilityOff from '@mui/icons-material/VisibilityOff'; import vid from "../assets/vid.mp4" import { useFormik } from 'formik' import * as yup from 'yup' import { useNavigate } from 'react-router-dom'; const SignUps = () => { const navigate = useNavigate() const { handleBlur, handleChange, handleSubmit, errors, touched, values, getFieldProps } = useFormik({ initialValues: { email: '', firstName: '', lastName: "", phoneNumber: '', password: '', }, onSubmit: (values) => { navigate('/signin') }, validationSchema: yup.object({ firstName: yup.string().required(`Required Field`), lastName: yup.string().required(`Required Field`), email: yup.string().required(`Required Field`), phoneNumber: yup.string().required(`Required Field`), password: yup.string().required(`Required Field`), }) }) return ( <> <form action="" onSubmit={handleSubmit} id= 'myForm'> <div> <TextField // required id="standard-required" label="First Name" variant="standard" color="error" name='firstName' focused onChange={handleChange} onBlur={handleBlur} // value={values.firstName} // {...getFieldProps('firstName')} // helperText={touched.firstName && errors.firstName} /> </div> {touched.firstName && <div className='text-warning' style={{ fontSize: '10px' }}>{errors.firstName}</div>} <div> <TextField // required id="standard-required" label="Last Name" variant="standard" color="error" name='lastName' focused value={values.lastName} onChange={handleChange} onBlur={handleBlur} // {...getFieldProps('lastName')} // helperText={touched.lastName && errors.lastName} /> {/* {/* helperText={touched.phoneNumber && <div className='text-warning' style={{fontSize:'10px'}}>{errors.phoneNumber}</div>} */} </div> {touched.lastName && <div className='text-warning' style={{ fontSize: '10px' }}>{errors.lastName}</div>} <div> <TextField // required id="standard-required" label="Phone Number" variant="standard" color="error" name='phoneNumber' type='number' focused value={values.phoneNumber} onChange={handleChange} onBlur={handleBlur} // {...getFieldProps('phoneNumber')} // helperText={touched.phoneNumber && errors.phoneNumber} /> </div> {touched.phoneNumber && <div className='text-warning' style={{ fontSize: '10px' }}>{errors.phoneNumber}</div>} <div> <TextField // required id="standard-required" label="Email" variant="standard" name='email' color="error" focused value={values.email} onChange={handleChange} onBlur={handleBlur} // {...getFieldProps('email')} // helperText={touched.email && errors.email} /> </div> {touched.email && <div className='text-warning' style={{ fontSize: '10px' }}>{errors.email}</div>} <Button type='submit' form="myForm" variant="contained" color="error" sx={{ backgroundColor: "red", color: "white" }}> Sign Up </Button> </form> </> ) } export default SignUps
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Data Structures-Linked list simple</h1> <p>An linked list are data structure very similar to a arrays, where the access to the element or node <br> is through a pointer instead of the index or key <br> <br> #1 HEAD => THIS.HEAD => NULL/or/NODE => THIS.DATA; <br> &emsp;&emsp;&emsp; &emsp;&emsp; THIS.SIZE = 0; &emsp;&emsp; &emsp; &emsp; &emsp;&emsp;&emsp;&emsp;THIS.NEXT => NULL/or/NODE =>etc.etc.ect <br> <br> <h2>one form</h2> cass Node{ <br> &emsp;constructor(data,next){<br> &emsp;&emsp; this.data = data; <br> &emsp;&emsp; this.next = next;<br> &emsp; }; <br> }; <br> <br> class Linkedlist { <br> &emsp;constructor(){ <br> &emsp;&emsp;this.head = null; <br> &emsp;&emsp;this.size = 0; <br> &emsp;};<br> }; <br> <br> <h2>another form</h2> function Node (value) { <br> &emsp; this.value = value <br> &emsp; this.next = null <br> } <br> <br> function LinkedList() { <br> &emsp; this.head = null <br> } <br> <br> something interzing from the lists that it can be as an advantage over arrays for example if we add a new <br> element in an array it wil verify that there is a contiguous memory space available for the new element and if <br> it has not moved the entire array to another place in memory where if there is a full space, this does not happen <br> with the list, items may be scattered in memory <br> <br> we can play a little bit with these kinds of structures <br> <br> adding nodes to the list <br> look at #1 above on the page watch as head joins the nodes think a little bit how it works for this situation we have to look for the node whose next is null(that means that an the node I'm standing on is the last one) <br> and it's important to highlight this that the 'next' is null ... remember that nodes only know <br> their predecessor, so if we were standing in null we can't meke the old one poin to new node !. so we'll step back and <br> reassigned node.next, now yes, toward the new node.<br> <br> <h3>Add Node at End (append) one form</h3> <br> LinkedList.prototype.append = function(value, current = this.head){ <br> &emsp; if(this.head === null){ <br> &emsp;&emsp;return this.head = new Node(value) <br> &emsp;} <br> &emsp; if(current.next === null){ <br> &emsp; &emsp;return current.next = new Node(value) <br> &emsp;} <br> &emsp;&emsp; this.append(value, current.next) <br> } <br> <br> <h3>Another form</h3> add(data){<br> &emsp;const newNode = new Node(data,null); <br> &emsp;if(!this.head){ <br> &emsp;&emsp;this.head = newNode <br> &emsp; }else{ <br> &emsp;&emsp;let current = this.head; <br> &emsp;&emsp;while(current.next){ <br> &emsp;&emsp;&emsp;current = current.next; <br> &emsp;&emsp;}; <br> &emsp;this.size++ <br> &emsp;}; <br> }; <br> <br> <br> <h3>Add node to beginning</h3> In this particular case the important thing is, first create the new node and then point it to what points head finally <br> head reassigb it to the new node. <br> if we did it in reverse, that is, firt we put the head assignment to the new node, we lose the reference of the rest of the nodes <br> <br> <h3>one form</h3> LinkedList.prototype.prepend = function(value){ <br> &emsp;if(this.head === null){ <br> &emsp;&emsp;return this.head = new Node(value) <br> &emsp;} <br> &emsp;let newNode = new Node(value) <br> &emsp;newNode.next = this.head <br> &emsp; this.head = newNode <br> } <br> <br> <h3>Removing nodes to the list</h3> the simplest case is to want to delete the first element, in that case head points to head.next <br> now to delete any other items, the first thing is to locate the node before the searched one(that we do asking for next)and point <br> that node the next from which we wnt to delete <br> <br> <h3>One form whit recursive</h3> LinkedList.prototype.removeNode = function (value, current = this.head) { <br> &emsp; if(this.head === null){ // no head <br> &emsp;&emsp; return false <br> &emsp; } <br> <br> &emsp; if (this.head.value === value){ <br> &emsp;&emsp; return this.head = this.head.next <br> &emsp; } <br> <br> &emsp; if(current.next !== null){ <br> &emsp;&emsp; if(current.next.value === value){ <br> &emsp;&emsp;&emsp; return current.next = current.next.next <br> &emsp; } <br> &emsp;&emsp; this.removeNode(value, current.next) <br> &emsp; } <br> &emsp;&emsp; return false // no match found <br> } <br> <br> <h3>Removing nodes to the list through position</h3> LinkedList.prototype.removeFromPos = function(pos,current = this.head,i=0){ <br> &emsp;if(this.head === null){ <br>   &emsp;&emsp; return false <br> &emsp;} <br> &emsp;if (i === pos){ <br> &emsp;&emsp; var aux = this.head.value; <br> &emsp;&emsp; this.head = this.head.next <br> &emsp;&emsp; return aux; <br> &emsp;} <br> &emsp;i++ <br> &emsp;if(current!==null){ <br> &emsp;&emsp;  if(i === pos){ <br>   &emsp;&emsp;&emsp;  let aux = current.next.value; <br> &emsp; &emsp; &emsp;&emsp;&emsp;&emsp;current.next = current.next.next <br> &emsp; &emsp;&emsp; &emsp;&emsp;&emsp;return aux; <br>  &emsp;&emsp;&emsp; } <br>    this.removeFromPos(pos, current =current.next,i) <br>   } <br>    return false <br> } <br> <br> <h3>looking for a node</h3> there's not much to explain .. if it matches the item it returns true , <br> if it reaches the end of the list (NULL) the item does not exist and returns false. <br> <br> <h3>one from with recursive</h3> <br> <br> LinkedList.prototype.findNode = function (value, current = this.head){ <br> &emsp;if(this.head === null) { <br> &emsp;&emsp; return false <br> &emsp;} <br> <br> &emsp;if (current !== null) { <br> &emsp; &emsp;if (current.value === value){ <br> &emsp; &emsp;&emsp; return true <br> &emsp;&emsp;} else { <br> &emsp; &emsp;&emsp; return this.findNode(value, current.next) <br> &emsp; &emsp;} <br> &emsp;} <br> &emsp;&emsp;return false <br> } <br> <br> <br> <h3>long list</h3> <br> LinkedList.prototype.length = function (current = this.head, acum = 1) { <br> &emsp; if(this.head === null){ <br> &emsp;&emsp; return 0 <br> &emsp; } <br> &emsp; if (current.next !== null){ <br> &emsp;&emsp; return this.length(current.next, acum = acum + 1) <br> &emsp; } <br> &emsp; return acum <br> } <br> <br> <br> </p> </body> </html>
import React from 'react'; import styles from './styles.module.css'; import classNames from 'classnames'; interface CardProps extends React.PropsWithChildren { color: 'base' | 'primary' | 'secondary'; size: 'sm' | 'md' | 'lg'; isClickable: Boolean; isDraggable: Boolean; handleClick: () => void; } export const Card = ({ color, size, isClickable, isDraggable, handleClick = () => {}, children, }: CardProps) => { return ( <div onClick={handleClick} className={classNames(styles.card, styles[color], styles[size], { [styles.isClickable]: isClickable, [styles.isDraggable]: isDraggable, })} > {children} </div> ); }; export default Card;
import 'package:afrofood_explore/theme/colors/appColors.dart'; import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class ActionCard extends StatelessWidget { ActionCard({ super.key, required this.titre, required this.subTitre, required this.imageUrl, required this.onPress, }); String titre, subTitre, imageUrl; final Function? onPress; @override Widget build(BuildContext context) { return InkWell( onTap: onPress as void Function()?, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5.0), ), surfaceTintColor: AppColors.secondColor.withOpacity(0.2), borderOnForeground: false, shadowColor: Colors.blueAccent.shade100, elevation: 1.0, color: AppColors.secondColor.withOpacity(0.2), margin: const EdgeInsets.all(5), child: SizedBox( width: 150, height: 150, child: Stack(children: [ Container( height: double.infinity, width: double.infinity, decoration: BoxDecoration( borderRadius: const BorderRadius.all( Radius.circular(5), ), image: DecorationImage( image: AssetImage(imageUrl), fit: BoxFit.cover), ), ), Opacity( opacity: 0.3, child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(5), ), color: AppColors.secondColor, ), ), ), Positioned( bottom: -25, right: -25, child: Container( height: 110, width: 110, padding: const EdgeInsets.all(8), decoration: BoxDecoration( color: AppColors.witeColor.withOpacity(0.2), shape: BoxShape.circle), ), ), Column( mainAxisAlignment: MainAxisAlignment.end, children: [ Expanded( flex: 2, child: Align( alignment: Alignment.topLeft, child: Padding( padding: const EdgeInsets.only( top: 5, left: 5, right: 20, bottom: 5), child: AutoSizeText( titre, presetFontSizes: const [12, 11], maxLines: 2, textDirection: TextDirection.ltr, style: GoogleFonts.inter( textStyle: TextStyle( fontWeight: FontWeight.w500, color: AppColors.witeColor.withOpacity(0.9), ), ), ), ), ), ), Expanded( flex: 2, child: Align( alignment: Alignment.bottomLeft, child: Padding( padding: const EdgeInsets.all(5), child: AutoSizeText( subTitre, presetFontSizes: const [12, 11, 10], maxLines: 1, textDirection: TextDirection.ltr, style: GoogleFonts.inter( textStyle: TextStyle( fontWeight: FontWeight.w600, color: AppColors.witeColor.withOpacity(0.9), ), ), ), ), ), ), ], ), ]), ), ), ); } }
/* * Copyright (c) 2007-2016 Concurrent, Inc. All Rights Reserved. * * Project and contact information: http://www.cascading.org/ * * This file is part of the Cascading project. * * 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 cascading.flow.hive; import java.io.Serializable; import java.util.Collections; import java.util.Map; import cascading.util.Util; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.Driver; import org.apache.hadoop.hive.ql.history.HiveHistory; import org.apache.hadoop.hive.ql.session.SessionState; /** * A simple factory class for creating Driver instances. This class exists to make * testing and stubbing within the HiveRiffle easier. */ public class HiveDriverFactory implements Serializable { /** Properties to merge into the hive conf. */ protected Map<String, String> properties; /** a HiveConf object. */ protected transient HiveConf hiveConf; /** decorator for the HiveHistory object to fetch counters. */ private CascadingHiveHistoryDecorator hiveHistory; /** Initialises the HiveDriverFactory. */ public HiveDriverFactory() { this( Collections.<String, String>emptyMap() ); } /** * Initialises the HiveDriverFactory with the specified properties applied to the HiveConf for the driver. * * @param properties Properties to add to the HiveConf used by the driver. */ public HiveDriverFactory( Map<String, String> properties ) { this.properties = properties; } /** * Creates a new Driver instance and sets everything up for compiling/processing queries. Users of * this method are responsible for destroying the driver instance, after they are done. * * @return a new Driver instance. */ public Driver createHiveDriver() { SessionState sessionState = SessionState.start( getHiveConf() ); if( hiveHistory != null ) { HiveHistory original = sessionState.getHiveHistory(); hiveHistory.setOriginal( original ); // this might break in the future, but there is no API to do that, so we have to use reflection. Util.setInstanceFieldIfExists( sessionState, "hiveHist", hiveHistory ); } SessionState.setCurrentSessionState( sessionState ); Driver driver = new Driver( getHiveConf() ); driver.init(); return driver; } /** * Helper method to return the HiveConf object. * * @return the HiveConf object. */ HiveConf getHiveConf() { if( this.hiveConf == null ) { this.hiveConf = new HiveConf(); for( Map.Entry<String, String> entry : properties.entrySet() ) this.hiveConf.set( entry.getKey(), entry.getValue() ); } return this.hiveConf; } /** * Sets the CascadingHiveHistoryDecorator. * * @param hiveHistory a CascadingHiveHistoryDecorator instance. */ public void setCascadingHiveHistoryDecorator( CascadingHiveHistoryDecorator hiveHistory ) { this.hiveHistory = hiveHistory; } }
from django.db import models # Create the news model with the following fields: title, url, crawled_at, created_at, updated_at, sent_at, is_summary, is_send, is_valid class News(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=300) url = models.CharField(max_length=1000) # Add the original source of the news crawled source = models.CharField(max_length=1000, null=True, blank=True) content = models.TextField(null=True, blank=True) summary = models.TextField(null=True, blank=True) is_summary = models.BooleanField(default=False) is_send = models.BooleanField(default=False) is_valid = models.BooleanField(default=True) crawled_at = models.DateTimeField(auto_now=False, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) published_at = models.DateTimeField(auto_now=False, null=True, blank=True) sent_at = models.DateTimeField(auto_now=False, null=True, blank=True) def __str__(self): return self.title # Create the Thread model with the following fields: thresh_id, channel_name, message, created_at, updated_at, sent_at class Thread(models.Model): id = models.AutoField(primary_key=True) thresh_id = models.CharField(max_length=100) channel_name = models.CharField(max_length=100) content = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=False) def __str__(self): return self.thresh_id # Create the Message model with the following fields: thread_id, message, created_at, updated_at class Message(models.Model): id = models.AutoField(primary_key=True) thread = models.ForeignKey(Thread, on_delete=models.CASCADE) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=False) def __str__(self): return self.id
import sqlite3 import json from bot_initialization import worksheet # Имя файла базы данных SQLite DB_FILE = 'user_states.db' def create_tables(): print('create_tables') conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS user_states ( user_id INTEGER, selected_class TEXT, PRIMARY KEY (user_id, selected_class) ) ''') conn.commit() conn.close() # Функция для загрузки всех выбранных классов для пользователя def load_user_states(user_id): print('load_user_states') """Загрузка всех выбранных классов для пользователя""" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute( ''' SELECT selected_class FROM user_states WHERE user_id = ? ''', (user_id, )) results = cursor.fetchall() conn.close() return [result[0] for result in results] if results else [] # Ваша существующая функция для сохранения состояния пользователя def save_user_state(user_id, selected_class): print('save_user_state') conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute( ''' INSERT OR REPLACE INTO user_states (user_id, selected_class) VALUES (?, ?) ''', (user_id, selected_class)) conn.commit() conn.close() # Получение списка всех пользователей с выбранными классами def get_users_with_classes(): print('get_users_with_classes') conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("SELECT DISTINCT user_id FROM user_states") users = cursor.fetchall() print("Users with classes:", [user[0] for user in users]) # Добавляем логирование для отладки conn.close() return [user[0] for user in users] def fetch_data_from_sheets(): print('fetch_data_from_sheets') data = worksheet.get_all_records() return data def initialize_db(): print('initialize_db') conn = sqlite3.connect('cache.db') c = conn.cursor() # Создаем таблицу, если она еще не существует c.execute( '''CREATE TABLE IF NOT EXISTS cache (id INTEGER PRIMARY KEY, data TEXT)''' ) conn.commit() conn.close() def update_cache(data): print('update_cache') conn = sqlite3.connect('cache.db') c = conn.cursor() # Сохраняем данные в формате JSON в таблице cache c.execute('INSERT OR REPLACE INTO cache (id, data) VALUES (1, ?)', (json.dumps(data), )) conn.commit() conn.close() def load_cache(): conn = sqlite3.connect('cache.db') c = conn.cursor() c.execute("SELECT data FROM cache WHERE id = 1") data = c.fetchone()[0] conn.close() return json.loads(data) initialize_db() data = fetch_data_from_sheets() update_cache(data)
<?php declare(strict_types=1); namespace App\Product\Application\ActivateProduct; use App\User\Domain\Exception\UserNotFoundException; use App\User\Domain\UserRepositoryInterface; use App\Product\Domain\Exception\ProductActiveException; use App\Product\Domain\Exception\ProductNotFoundException; use App\Product\Domain\ProductRepositoryInterface; use App\Shared\Domain\Bus\Command\CommandHandlerInterface; use App\Shared\Domain\UuidCreatorInterface; final class ActivateProductCommandHandler implements CommandHandlerInterface { public function __construct( private readonly UserRepositoryInterface $userRepository, private readonly ProductRepositoryInterface $productRepository, private readonly UuidCreatorInterface $uuidCreator, ) { } /** @throws UserNotFoundException|ProductNotFoundException|ProductActiveException */ public function __invoke(ActivateProductCommand $command): void { $userUuid = $command->getUserUuid(); $this->userRepository->getOneByUuidActive($userUuid); $productUuid = $command->getProductUuid(); $product = $this->productRepository->getOneByUuid($productUuid); $product->activate($this->uuidCreator->create()); $this->productRepository->save($product); } }
import { Visibility } from "@mui/icons-material"; import { IconButton, TextField, TextFieldProps } from "@mui/material"; import { debounce, isString } from "lodash"; import React, { Dispatch, SetStateAction, useEffect, useMemo, useState, } from "react"; type TProps = { password: string; setPassword: Dispatch<SetStateAction<string>>; hideErrors?: boolean; label?: string; autoComplete?: TextFieldProps["autoComplete"]; customError?: string; }; const MIN_PASSWORD_LENGTH = 8; const PASSWORD_HELPER_TEXT = `Password is too short (min ${MIN_PASSWORD_LENGTH})`; export const isValidPassword = (password: string | null): password is string => isString(password) && password.length >= MIN_PASSWORD_LENGTH; const PasswordEdit = (props: TProps): JSX.Element => { const { password, setPassword, hideErrors = false, label = "Password", autoComplete = "current-password", customError, } = props; const [passwordType, setPasswordType] = useState<TextFieldProps["type"]>("password"); const [passwordError, setPasswordError] = useState<string | null>(); const debouncePasswordError = useMemo( () => debounce(setPasswordError, 500), [] ); useEffect(() => debouncePasswordError.cancel(), [debouncePasswordError]); return ( <TextField sx={{ mt: 1 }} type={passwordType} value={password ?? ""} onChange={(e) => { const password = e.target.value; setPassword(password); if (isValidPassword(password)) { debouncePasswordError.cancel(); setPasswordError(null); } else debouncePasswordError(PASSWORD_HELPER_TEXT); }} label={label} error={isString(customError) || (!hideErrors && isString(passwordError))} helperText={customError ?? (!hideErrors && passwordError)} autoComplete={autoComplete} InputProps={{ endAdornment: ( <IconButton onMouseDown={() => setPasswordType("text")} onMouseUp={() => setPasswordType("password")} > <Visibility /> </IconButton> ), }} name={autoComplete} /> ); }; export default PasswordEdit;
import torch from torch import nn as nn class GradientReversalFunction(torch.autograd.Function): """ From: https://github.com/jvanvugt/pytorch-domain-adaptation/blob/cb65581f20b71ff9883dd2435b2275a1fd4b90df/utils.py#L26 Gradient Reversal Layer from: Unsupervised Domain Adaptation by Backpropagation (Ganin & Lempitsky, 2015) Forward pass is the identity function. In the backward pass, the upstream gradients are multiplied by -lambda (i.e. gradient is reversed) """ @staticmethod def forward(ctx, x, lambda_): ctx.lambda_ = lambda_ return x.clone() @staticmethod def backward(ctx, grads): lambda_ = ctx.lambda_ lambda_ = grads.new_tensor(lambda_) dx = -lambda_ * grads return dx, None class GradientReversal(torch.nn.Module): def __init__(self, lambda_): super(GradientReversal, self).__init__() self.lambda_ = lambda_ def forward(self, x): return GradientReversalFunction.apply(x, self.lambda_)
import React from 'react' import { BrowserRouter, Route, Routes } from 'react-router-dom' import { Layout } from './Layout' import { ToDo } from '../../pages/toDo/ToDo' import { Bank } from '../../pages/bank/Bank' import { Crosses } from '../../ui/extraLesson/superCrosses/Crosses' import { MainWithIgor } from '../../pages/withIgor/MainWithIgor' import { ModalWrapper } from '../../ui/extraLesson/modal/ModalWrapper' import { NotFound } from '../../pages/notFound/NotFound' import { S2hw1Microtask } from '../../pages/s2hw1/S2hw1Microtask' import { S2eLesson1 } from '../../pages/s2eLesson1/S2eLesson1' import { LocalStorage } from '../../pages/localStorage/LocalStorage' export const Router = () => { return ( <BrowserRouter> <Routes> <Route path="/" element={<Layout />}> <Route index element={<ToDo />} /> <Route path="/bank" element={<Bank />} /> <Route path="/crosses" element={<Crosses />} /> <Route path="/modal" element={<ModalWrapper />} /> <Route path="/atm" element={<MainWithIgor />} /> <Route path="/s2hw1" element={<S2hw1Microtask />} /> <Route path="/s2eLesson1" element={<S2eLesson1 />} /> <Route path="/LSCounter" element={<LocalStorage />} /> <Route element={<NotFound />} path="*" /> </Route> </Routes> </BrowserRouter> ); }
! ! \\\\\\\\\\ B E G I N S U B R O U T I N E ////////// ! ////////// L O R E N T Z \\\\\\\\\\ ! ! Developed by ! Laboratory of Computational Astrophysics ! University of Illinois at Urbana-Champaign ! ! subroutine lorentz_2D(ibeg,iend,jbeg,jend,kbeg,kend & ,u1,u2,u3,w1,w2,w3) ! ! dac:zeus3d.lorentz <----- MoC estimate of transverse lorentz forces ! october, 1992 ! ! written by: David Clarke ! modified 1: Mordecai-Mark Mac Low, December 1997 - March 1998 ! rewritten for ZEUS-MP ! modified 2: John Hayes, years ago; Rewritten for f90 ! modified 3: John Hayes, October 2005; created lorentz_2D clone ! which assumes symmetry about the K axis; after ZEUS3D ! modified 4: John Hayes, 09/01/2006; corrected metric factor ! in second loop for "st3" ! ! PURPOSE: Uses the Method of Characteristics (MoC) to compute the ! transverse components of the Lorentz force and then accelerate the ! velocities accordingly. After a suggestion by John Hawley, these ! source terms are computed separately from the MoC estimate of the ! emfs (MOCEMFS) and before the magnetic field update. This improves ! stability of multi-dimensional Alfven waves. ! ! MOCEMFS solves the induction equation without the use of operator ! splitting. Thus, the relevant characteristic velocities are v+/-va ! and includes the flow velocity v (from the advection term v grad(B)) ! and the alfven velocity va (from the induction term va grad(B)). ! Conversely, Euler's equation is operator split, and the advection ! term (v grad(v)) is handled elsewhere (MOMX*). Thus, the effective ! characteristic velocities when estimating the transverse Lorentz ! terms is simply +/-va (from the induction term va grad(v)). ! ! See comments in MOCEMFS for further ideas regarding the Method of ! Characteristics. ! ! INPUT VARIABLES: ! ! u[1,2,3] = old velocities ! ! OUTPUT VARIABLES: ! ! w[1,2,3] = velocities from ibeg to iend, jbeg to jend, kbeg to kend ! ! LOCAL VARIABLES: ! srd[n] sqrt of spatially averaged density at [n]-face n=1,2,3 ! bave spatially averaged density at edge ! srdpi 1.0/srd[n] along the plus alfven characteristic (A+) ! srdmi 1.0/srd[n] along the minus alfven characteristic (A-) ! valp characteristic velocity along A+ (-va) ! valm characteristic velocity along A- (+va) ! vpal velocity interpolated to the time-centred footpoint of A+ ! vmal velocity interpolated to the time-centred footpoint of A- ! bpal B-field interpolated to the time-centred footpoint of A+ ! bmal B-field interpolated to the time-centred footpoint of A- ! bstar MoC estimate of b[n] used to evaluate st[n], n=1,2,3 ! st[n] Transverse Lorentz force on the [n]-velocity, n=1,2,3 ! ! EXTERNALS: ! ! -----> these are now inlined (M-MML): X1ZC1D , X2ZC1D , X3ZC1D ! !----------------------------------------------------------------------- ! use real_prec use config use param use field use root use grid use scratch use lor_scr #ifdef MPI_USED use mpiyes #else use mpino #endif use mpipar ! implicit NONE ! integer :: i , j , k integer :: ibeg,iend,jbeg,jend,kbeg,kend integer :: kone,km1,kp1,jone !asif ! real(rl) :: u1(in,jn,kn), u2(in,jn,kn), u3(in,jn,kn), & w1(in,jn,kn), w2(in,jn,kn), w3(in,jn,kn) ! real(rl) :: absb ,q1, qv1, qv2, qb1, qb2, q3, dqm, dqp, & xi, fact, & dv(ijkn), db(ijkn) ! real(rl) :: bave(ijkn), srdpi(ijkn), srdmi(ijkn), & valp(ijkn), valm (ijkn), vtmp (ijkn), & btmp(ijkn), vpal (ijkn), vmal (ijkn), & bpal(ijkn), bmal (ijkn), bstar(ijkn) ! real(rl) :: st1(in,jn,kn), st2(in,jn,kn), & st3(in,jn,kn) ! ! equivalence ! . ( bave , w1da ), ! . ( srdpi , w1db ), ! 1 ( srdmi , w1dc ), ( vtmp , w1dd ), ! 2 ( vpal , w1de ), ( vmal , w1df ) ! 2 ( valp , bpal , w1dg ), ! 1 ( valm , bmal , w1dh ), ! 8 ( btmp , bstar , w1di ), ! 9 ( db , w1dj ), ( dv , w1dk ) ! ! Routine MOCEMFS is expecting to find "srd1", "srd2", and "srd3" ! intact in worker arrays "wd3d", "we3d", and "wf3d" respectively. ! [but MOCEMFS is in ZEUS-3D. does HSMOC also need these? M-MML 9.12.97 ! so far, yes 4.3.98] ! !PS: prevent overwritten of momenta. ! equivalence ( st1 , w3da ), ( st2 , w3db ) ! 1 , ( st3 , w3dc ) !PS -- end ! ! equivalence ( srd1 , w3di ), ! . ( srd2 , w3dj ), ! 1 ( srd3 , w3df ) ! ! External statements ! ! ! !----------------------------------------------------------------------- ! ! Compute face-centred averages of density, initialise source terms ! to zero. ! kone = 0 jone = 1 k = ks km1 = k-kone do 2 j=jbeg-1,jend+1 do 1 i=ibeg-1,iend+1 srd1(i,j,k) = sqrt ( 0.5 * ( d (i,j,k) + d (i-1,j,k) ) ) srd2(i,j,k) = sqrt ( 0.5 * ( d (i,j,k) + d (i,j-1,k) ) ) srd3(i,j,k) = sqrt ( 0.5 * ( d (i,j,k) + d (i,j,km1) ) ) st1 (i,j,k) = 0.0 st2 (i,j,k) = 0.0 st3 (i,j,k) = 0.0 1 continue 2 continue ! !----------------------------------------------------------------------- !---- 1-force ---------------------------------------------------------- !----------------------------------------------------------------------- ! ! By following the Alfven velocity in the 2-direction, evaluate ! "bstar" from "b1" to estimate the 2-transverse Lorentz force. ! do 45 i=ibeg,iend+1 ! ! Select an effective density and determine the Alfven speed for ! each Alfven characteristic in the 2-direction. ! do 10 j=jbeg,jend+1 bave (j) = 0.5 * ( b2(i,j,k) + b2(i-1,j,k) ) absb = abs ( bave(j) ) srdpi(j) = 1.0 / srd1(i,j ,k) srdmi(j) = 1.0 / srd1(i,j-1,k) valp (j) =-absb * srdpi(j) valm (j) = absb * srdmi(j) 10 continue ! ! Interpolate 1-D vectors of "u1" and "b1" in the 2-direction to ! the footpoints of both Alfven characteristics. ! do 20 j=jbeg-2,jend+2 vtmp(j) = u1(i,j,k) - vg1(i) btmp(j) = b1(i,j,k) 20 continue ! call x2zc1d ( vtmp, valp, valm, iords1, istps1, k, i ! 1 , g2a, g2ai, vpal, vmal ) ! call x2zc1d ( btmp, valp, valm, iordb1, istpb1, k, i ! 1 , g2a, g2ai, bpal, bmal ) ! ! Inline interpolation (following tranx*) ! do 22 j=jbeg-1,jend+1 dqm = ( vtmp(j ) - vtmp(j-1) ) * dx2bi(j ) dqp = ( vtmp(j+1) - vtmp(j ) ) * dx2bi(j+1) dv (j ) = max ( dqm * dqp, zro ) & * sign ( one, dqm + dqp ) & / max ( abs ( dqm + dqp ), tiny ) dqm = ( btmp(j ) - btmp(j-1) ) * dx2bi(j ) dqp = ( btmp(j+1) - btmp(j ) ) * dx2bi(j+1) db (j ) = max ( dqm * dqp, zro ) & * sign ( one, dqm + dqp ) & / max ( abs ( dqm + dqp ), tiny ) 22 continue ! ! 2. Perform an upwinded interpolation of "q" to the time-centred ! bases of the characteristics. ! fact = dt * g2ai(i) do 24 j=jbeg,jend+1 qv1 = vtmp(j-1) + dx2a(j-1) * dv (j-1) qv2 = vtmp(j ) - dx2a(j ) * dv (j ) qb1 = btmp(j-1) + dx2a(j-1) * db (j-1) qb2 = btmp(j ) - dx2a(j ) * db (j ) ! xi = valp(j) * fact q3 = sign ( haf, xi ) vpal(j)= ( 0.5 + q3 ) * ( qv1 - xi * dv (j-1) ) & + ( 0.5 - q3 ) * ( qv2 - xi * dv (j ) ) bpal(j)= ( 0.5 + q3 ) * ( qb1 - xi * db (j-1) ) & + ( 0.5 - q3 ) * ( qb2 - xi * db (j ) ) ! xi = valm(j) * fact q3 = sign ( haf, xi ) vmal(j)= ( 0.5 + q3 ) * ( qv1 - xi * dv (j-1) ) & + ( 0.5 - q3 ) * ( qv2 - xi * dv (j ) ) bmal(j)= ( 0.5 + q3 ) * ( qb1 - xi * db (j-1) ) & + ( 0.5 - q3 ) * ( qb2 - xi * db (j ) ) 24 continue ! ! Evaluate "bstar" by solving the characteristic equations. ! do 30 j=jbeg,jend+1 q1 = sign ( one, bave(j) ) bstar(j) = ( bpal(j) * srdpi(j) + bmal(j) * srdmi(j) & + q1 * ( vpal(j) - vmal(j) ) ) & / ( srdpi(j) + srdmi(j) ) 30 continue ! ! Evaluate transverse Lorentz force. ! do 40 j=jbeg,jend !JH if(lgeom .eq. 3) then if(x1a(i) .eq. 0.0) then st1(i,j,k) = 0.0D0 go to 40 endif endif st1(i,j,k) = ( bave (j+1) + bave (j) ) * g2ai(i) & * ( bstar(j+1) - bstar(j) ) * dx2ai(j) 40 continue 45 continue 50 continue ! !----------------------------------------------------------------------- !---- 2-force ---------------------------------------------------------- !----------------------------------------------------------------------- ! !----------------------------------------------------------------------- ! ! By following the Alfven velocity in the 1-direction, evaluate ! "bstar" from "b2" to estimate the 1-transverse Lorentz force. ! do 205 j=jbeg,jend+1 ! ! Select an effective density and determine the Alfven speed for ! each Alfven characteristic in the 1-direction. ! do 170 i=ibeg,iend+1 bave (i) = 0.5 * ( b1(i,j,k) + b1(i,j-1,k) ) absb = abs ( bave(i) ) srdpi(i) = 1.0 / srd2(i ,j,k) srdmi(i) = 1.0 / srd2(i-1,j,k) valp (i) =-absb * srdpi(i) valm (i) = absb * srdmi(i) 170 continue ! ! Interpolate 1-D vectors of "u2" and "b2" in the 1-direction to ! the footpoints of both Alfven characteristics. ! do 180 i=ibeg-2,iend+2 vtmp(i) = u2(i,j,k) - vg2(j) btmp(i) = b2(i,j,k) 180 continue ! call x1zc1d ( vtmp, valp, valm, iords2, istps2, j, k ! 1 , vpal, vmal ) ! call x1zc1d ( btmp, valp, valm, iordb2, istpb2, j, k ! 1 , bpal, bmal ) ! 1. Evaluate monotonised, van Leer difference in "q" across the zone. ! do 182 i=ibeg-1,iend+1 dqm = ( vtmp(i ) - vtmp(i-1) ) * dx1bi(i ) dqp = ( vtmp(i+1) - vtmp(i ) ) * dx1bi(i+1) dv (i ) = max ( dqm * dqp, zro ) & * sign ( one, dqm + dqp ) & / max ( abs ( dqm + dqp ), tiny ) dqm = ( btmp(i ) - btmp(i-1) ) * dx1bi(i ) dqp = ( btmp(i+1) - btmp(i ) ) * dx1bi(i+1) db (i ) = max ( dqm * dqp, zro ) & * sign ( one, dqm + dqp ) & / max ( abs ( dqm + dqp ), tiny ) 182 continue ! ! 2. Perform an upwinded interpolation of "q" to the time-centred ! bases of the characteristics. ! do 184 i=ibeg,iend+1 qv1 = vtmp(i-1) + dx1a(i-1) * dv (i-1) qv2 = vtmp(i ) - dx1a(i ) * dv (i ) qb1 = btmp(i-1) + dx1a(i-1) * db (i-1) qb2 = btmp(i ) - dx1a(i ) * db (i ) ! xi = valp(i) * dt q3 = sign ( haf, xi ) vpal(i)= ( 0.5 + q3 ) * ( qv1 - xi * dv (i-1) ) & + ( 0.5 - q3 ) * ( qv2 - xi * dv (i ) ) bpal(i)= ( 0.5 + q3 ) * ( qb1 - xi * db (i-1) ) & + ( 0.5 - q3 ) * ( qb2 - xi * db (i ) ) ! xi = valm(i) * dt q3 = sign ( haf, xi ) vmal(i)= ( 0.5 + q3 ) * ( qv1 - xi * dv (i-1) ) & + ( 0.5 - q3 ) * ( qv2 - xi * dv (i ) ) bmal(i)= ( 0.5 + q3 ) * ( qb1 - xi * db (i-1) ) & + ( 0.5 - q3 ) * ( qb2 - xi * db (i ) ) 184 continue ! ! Evaluate "bstar" by solving the characteristic equations. ! do 190 i=ibeg,iend+1 q1 = sign ( one, bave(i) ) bstar(i) = ( bpal(i) * srdpi(i) + bmal(i) * srdmi(i) & + q1 * ( vpal(i) - vmal(i) ) ) * g2a(i) & / ( srdpi(i) + srdmi(i) ) 190 continue ! ! Evaluate transverse Lorentz force. Note that the metric ! factor "g2a" has been absorbed into "bstar". ! do 200 i=ibeg,iend st2(i,j,k) = st2(i,j,k) & + ( bave (i+1) + bave (i) ) * g2bi(i) & * ( bstar(i+1) - bstar(i) ) * dx1ai(i) 200 continue 205 continue 210 continue ! 220 continue ! !----------------------------------------------------------------------- !---- 3-force ---------------------------------------------------------- !----------------------------------------------------------------------- ! km1=k-kone kp1=k+kone ! ! By following the Alfven velocity in the 1-direction, evaluate ! "bstar" from "b3" to estimate the 1-transverse Lorentz force. ! do 270 j=jbeg,jend ! ! Select an effective density and determine the Alfven speed for ! each Alfven characteristic in the 1-direction. ! do 230 i=ibeg,iend+1 bave (i) = 0.5 * ( b1(i,j,k) + b1(i,j,km1) ) absb = abs ( bave(i) ) srdpi(i) = 1.0 / srd3(i ,j,k) srdmi(i) = 1.0 / srd3(i-1,j,k) valp (i) =-absb * srdpi(i) valm (i) = absb * srdmi(i) 230 continue ! ! Interpolate 1-D vectors of "u3" and "b3" in the 1-direction to ! the footpoints of both Alfven characteristics. ! do 240 i=ibeg-2,iend+2 vtmp(i) = u3(i,j,k) - vg3(k) btmp(i) = b3(i,j,k) 240 continue ! call x1zc1d ( vtmp, valp, valm, iords3, istps3, j, k ! 1 , vpal, vmal ) ! call x1zc1d ( btmp, valp, valm, iordb3, istpb3, j, k ! 1 , bpal, bmal ) ! ! 1. Evaluate monotonised, van Leer difference in "q" across the zone. ! do 242 i=ibeg-1,iend+1 dqm = ( vtmp(i ) - vtmp(i-1) ) * dx1bi(i ) dqp = ( vtmp(i+1) - vtmp(i ) ) * dx1bi(i+1) dv (i ) = max ( dqm * dqp, zro ) & * sign ( one, dqm + dqp ) & / max ( abs ( dqm + dqp ), tiny ) dqm = ( btmp(i ) - btmp(i-1) ) * dx1bi(i ) dqp = ( btmp(i+1) - btmp(i ) ) * dx1bi(i+1) db (i ) = max ( dqm * dqp, zro ) & * sign ( one, dqm + dqp ) & / max ( abs ( dqm + dqp ), tiny ) 242 continue ! ! 2. Perform an upwinded interpolation of "q" to the time-centred ! bases of the characteristics. ! do 244 i=ibeg,iend+1 qv1 = vtmp(i-1) + dx1a(i-1) * dv (i-1) qv2 = vtmp(i ) - dx1a(i ) * dv (i ) qb1 = btmp(i-1) + dx1a(i-1) * db (i-1) qb2 = btmp(i ) - dx1a(i ) * db (i ) ! xi = valp(i) * dt q3 = sign ( haf, xi ) vpal(i)= ( 0.5 + q3 ) * ( qv1 - xi * dv (i-1) ) & + ( 0.5 - q3 ) * ( qv2 - xi * dv (i ) ) bpal(i)= ( 0.5 + q3 ) * ( qb1 - xi * db (i-1) ) & + ( 0.5 - q3 ) * ( qb2 - xi * db (i ) ) ! xi = valm(i) * dt q3 = sign ( haf, xi ) vmal(i)= ( 0.5 + q3 ) * ( qv1 - xi * dv (i-1) ) & + ( 0.5 - q3 ) * ( qv2 - xi * dv (i ) ) bmal(i)= ( 0.5 + q3 ) * ( qb1 - xi * db (i-1) ) & + ( 0.5 - q3 ) * ( qb2 - xi * db (i ) ) 244 continue ! ! Evaluate "bstar" by solving the characteristic equations. ! do 250 i=ibeg,iend+1 q1 = sign ( one, bave(i) ) bstar(i) = ( bpal(i) * srdpi(i) + bmal(i) * srdmi(i) & + q1 * ( vpal(i) - vmal(i) ) ) * g31a(i) & / ( srdpi(i) + srdmi(i) ) 250 continue ! ! Evaluate transverse Lorentz force. Note that the metric ! factor "g31a" has been absorbed into "bstar". ! do 260 i=ibeg,iend !JH if(lgeom .eq. 3) then if(x1a(i) .eq. 0.0) then st3(i,j,k) = 0.0D0 go to 260 endif endif st3(i,j,k) = ( bave (i+1) + bave (i) ) * g31bi(i) & * ( bstar(i+1) - bstar(i) ) * dx1ai(i) 260 continue 270 continue ! !----------------------------------------------------------------------- ! ! By following the Alfven velocity in the 2-direction, evaluate ! "bstar" from "b3" to estimate the 2-transverse Lorentz force. ! do 320 i=ibeg,iend ! ! Select an effective density and determine the Alfven speed for ! each Alfven characteristic in the 2-direction. ! do 280 j=jbeg,jend+1 bave (j) = 0.5 * ( b2(i,j,k) + b2(i,j,km1) ) absb = abs ( bave(j) ) srdpi(j) = 1.0 / srd3(i,j ,k) srdmi(j) = 1.0 / srd3(i,j-1,k) valp (j) =-absb * srdpi(j) valm (j) = absb * srdmi(j) 280 continue ! ! Interpolate 1-D vectors of "u3" and "b3" in the 2-direction to ! the footpoints of both Alfven characteristics. ! do 290 j=jbeg-2,jend+2 vtmp(j) = u3(i,j,k) - vg3(k) btmp(j) = b3(i,j,k) 290 continue ! call x2zc1d ( vtmp, valp, valm, iords3, istps3, k, i ! 1 , g2b, g2bi, vpal, vmal ) ! call x2zc1d ( btmp, valp, valm, iordb3, istpb3, k, i ! 1 , g2b, g2bi, bpal, bmal ) ! do 292 j=jbeg-1,jend+1 dqm = ( vtmp(j ) - vtmp(j-1) ) * dx2bi(j ) dqp = ( vtmp(j+1) - vtmp(j ) ) * dx2bi(j+1) dv (j ) = max ( dqm * dqp, zro ) & * sign ( one, dqm + dqp ) & / max ( abs ( dqm + dqp ), tiny ) dqm = ( btmp(j ) - btmp(j-1) ) * dx2bi(j ) dqp = ( btmp(j+1) - btmp(j ) ) * dx2bi(j+1) db (j ) = max ( dqm * dqp, zro ) & * sign ( one, dqm + dqp ) & / max ( abs ( dqm + dqp ), tiny ) 292 continue ! ! 2. Perform an upwinded interpolation of "q" to the time-centred ! bases of the characteristics. ! fact = dt * g2bi(i) do 294 j=jbeg,jend+1 qv1 = vtmp(j-1) + dx2a(j-1) * dv (j-1) qv2 = vtmp(j ) - dx2a(j ) * dv (j ) qb1 = btmp(j-1) + dx2a(j-1) * db (j-1) qb2 = btmp(j ) - dx2a(j ) * db (j ) ! xi = valp(j) * fact q3 = sign ( haf, xi ) vpal(j)= ( 0.5 + q3 ) * ( qv1 - xi * dv (j-1) ) & + ( 0.5 - q3 ) * ( qv2 - xi * dv (j ) ) bpal(j)= ( 0.5 + q3 ) * ( qb1 - xi * db (j-1) ) & + ( 0.5 - q3 ) * ( qb2 - xi * db (j ) ) ! xi = valm(j) * fact q3 = sign ( haf, xi ) vmal(j)= ( 0.5 + q3 ) * ( qv1 - xi * dv (j-1) ) & + ( 0.5 - q3 ) * ( qv2 - xi * dv (j ) ) bmal(j)= ( 0.5 + q3 ) * ( qb1 - xi * db (j-1) ) & + ( 0.5 - q3 ) * ( qb2 - xi * db (j ) ) 294 continue ! ! Evaluate "bstar" by solving the characteristic equations. ! do 300 j=jbeg,jend+1 q1 = sign ( one, bave(j) ) bstar(j) = ( bpal(j) * srdpi(j) + bmal(j) * srdmi(j) & + q1 * ( vpal(j) - vmal(j) ) ) * g32a(j) & / ( srdpi(j) + srdmi(j) ) 300 continue ! ! Evaluate transverse Lorentz force. Note that the metric ! factor "g32a" has been absorbed into "bstar". ! do 310 j=jbeg,jend if(lgeom .eq. 3) then if(x1a(i) .eq. 0.0) then st3(i,j,k) = 0.0D0 go to 310 endif endif !JH !JH changed g2ai to g2bi since v3 lives at x1b !JH st3(i,j,k) = st3(i,j,k) & + ( bave (j+1) + bave (j) ) * g2bi(i) * g32bi(j) & * ( bstar(j+1) - bstar(j) ) * dx2ai(j) 310 continue 320 continue ! 330 continue ! !----------------------------------------------------------------------- ! ! Accelerate velocities and set boundaries. ! q1 = 0.5 * dt do 350 j=jbeg,jend do 340 i=ibeg,iend w1(i,j,k) = u1(i,j,k) + q1 * st1(i,j,k) / srd1(i,j,k)**2 w2(i,j,k) = u2(i,j,k) + q1 * st2(i,j,k) / srd2(i,j,k)**2 w3(i,j,k) = u3(i,j,k) + q1 * st3(i,j,k) / srd3(i,j,k)**2 340 continue 350 continue 360 continue ! return end ! ! ! \\\\\\\\\\ E N D S U B R O U T I N E ////////// ! ////////// L O R E N T Z \\\\\\\\\\ ! !
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>通知管理</title> <!-- vue --> <script src="js/vue.js"></script> <!-- jquery --> <script src="js/jquery.min.js"></script> <!-- element-ui --> <!-- 引入样式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <!-- 引入组件库 --> <script src="js/element-ui@2.15.13.js"></script> <!-- 请勿在项目正式环境中引用该 layui.css 地址 --> <link rel="stylesheet" href="layui/css/layui.css"> <script src="js/layui.js"></script> </head> <body> <!-- 搜索表单开始 --> <form class="layui-form"> <div class="layui-inline"> <label class="layui-form-label">查询条件</label> <div class="layui-input-block"> <input type="text" id="name" name="name" style="width: 400px;" placeholder="请输入商品名称" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-inline"> <input type="button" id="selectBtn" class="layui-btn" data-type="reload" value="查询"> </div> <div class="layui-inline"> <input type="button" id="addBtn" class="layui-btn" data-type="reload" value="发布新通知"> </div> </form> <!-- 添加表单开始 --> <div id="app" style="display: none"> <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> <div class="layui-form-item"> <div class="layui-input-group"> <div class="layui-input-split layui-input-prefix"> 标题: </div> <input type="text" v-model="ruleForm.title" class="layui-input"> </div> </div> <div class="layui-form-item"> <div class="layui-input-group"> <div class="layui-input-split layui-input-prefix"> 简介: </div> <input type="text" v-model="ruleForm.introduce" class="layui-input"> </div> </div> <div class="layui-form-item"> <div class="layui-input-group"> <div class="layui-input-split layui-input-prefix"> 详细内容: </div> <input type="text" v-model="ruleForm.details" class="layui-input"> </div> </div> <div class="layui-form-item"> <div class="layui-inline"> <label class="layui-form-label">发布日期:</label> <div class="layui-input-inline"> <input type="text" class="layui-input" id="ins-laydate-demo" placeholder="yyyy-MM-dd"> </div> </div> </div> </el-form> </div> <table id="table_data"></table> <!-- 操作工具条件开始 --> </body> </html> <script> var app = new Vue({ el: '#app', data() { return { ruleForm: { nid: '', title:'', introduce:'', details:'', releaseDate:'' }, } } }); // 加载 table 模块 layui.use( ['jquery', 'layer', 'form','table','laydate'],function(){ // 实例化动态表格的实例对象 let laydate = layui.laydate; let $ = layui.jquery; let table = layui.table; let layer = layui.layer; let form = layui.form; //渲染添加功能日期组件 laydate.render({ elem: '#ins-laydate-demo' }) // 定义动态表格相关的参数 table.render({ elem: '#table_data' ,url:'/listNotice' ,page: true // 开启分页 ,limit:5 ,limits:[5,10,20] ,cols:[[ // {field: '实体对象的属性名称', title: '列头显示内容', width:宽, sort: 是否排序, fixed: '定位'} {field: 'nid', title: '通知ID', fixed: 'left'} ,{field: 'title', title: '标题', fixed: 'left'} ,{field: 'introduce', title: '简介', fixed: 'left'} ,{field: 'details', title: '详细内容', fixed: 'left'} ,{field: 'releaseDate', title: '发布时间', fixed: 'left'} ,{title: '操作', fixed: 'left',templet:function (){ return ' <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</button>' }} ]] // 把后台数据转换为layui中table组件所要求的数据格式 ,parseData:function( res ) { return { "code":res.code==200?0:'-1', "data":res.data, "count":res.count }; } }); // 绑定查询按钮 $('#selectBtn').on('click', function () { if ($('#name').val() != null && $('#name').val() != ""){ // 重新渲染动态表格相关的参数 table.render({ elem: '#table_data' ,url: "/selectTypes" ,where: { // 在这里设置额外的参数 // 例如,传递一个名为 'param' 的参数,值为输入框中的值 param: $('#name').val() } ,page: true // 开启分页 ,limit:5 ,limits:[5,10,20] ,cols:[[ // {field: '实体对象的属性名称', title: '列头显示内容', width:宽, sort: 是否排序, fixed: '定位'} {field: 'tid', title: '类型ID', fixed: 'left'} ,{field: 'name', title: '名称', fixed: 'left'} ,{title: '操作', fixed: 'left',templet:function (){ return ' <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</button>' }} ]] // 把后台数据转换为layui中table组件所要求的数据格式 ,parseData:function( res ) { return { "code":res.code==200?0:'-1', "data":res.data, "count":res.count }; } }); }else { location.href = 'notice.html'; } }); // 监听表格操作按钮 table.on('tool',function (obj){ console.log(obj) ; if(obj.event=='delete') { let p = obj.data ; // 弹出确认框 layer.confirm("您确认删除此通知吗?",function( index ){ // 向服务器发起异步请求,实现数据的删除 $.ajax({ url:'/delNotice', method:'POST', data:{'nid':p.nid}, success:function( res ){ // 弹出提示框 layer.msg("删除成功") // 根据弹出层的索引,关闭弹出确认框 layer.close(index) ; // 重新加载表格数据 table.reload('table_data',{page:{curr:1}}); } }) ; }) ; } }); //清空添加表单数据方法 let deladd = function (){ app.ruleForm={ nid: '', title:'', introduce:'', details:'', releaseDate:'' } document.getElementById('ins-laydate-demo').value = ''; } // 实现添加类型操作 $("#addBtn").click(function () { layer.open({ type: 1, title: '发布新通知', area: ['50%', '35em'], resize: false, content: $("#app"), btn: ['添加', '取消'], btn1: function (index) { $.ajax({ url: '/addNotice', method: 'post', data: { title:app.ruleForm.title, introduce:app.ruleForm.introduce, details:app.ruleForm.details, releaseDate:$('#ins-laydate-demo').val() }, success: function (res) { // 弹出提示框 layer.msg("添加成功") // 根据弹出层的索引,关闭弹出确认框 layer.close(index); //清空添加表单数据 deladd() // 重新加载表格数据 table.reload('table_data', {page: {curr: 1}}); } }); }, btn2: function (){ //清空添加表单数据 deladd() }, cancel: function (){ //清空添加表单数据 deladd() } }); }) }) ; </script>
const express= require('express'); const app=express(); const cors= require('cors'); const port=3200; app.use(cors()) const foodData= require('./models/dbSchema'); require('./db/connection'); app.use(express.json()); //welcome page app.get('/', (req, res)=>{ res.send('<h1>Welcome to Page</h1>'); }) //get all food data app.get('/getFoodData', async(req,res)=>{ try{ const getData= await foodData.find({}); res.status(201).json(getData); } catch(e){ console.error(e); } }) //find specific food detail by its name app.get('/getFoodData/:id', async(req,res)=>{ const id=req.params.id; try{ const oneFoodData=await foodData.findOne({id:id}); //data of only one parameter if(!oneFoodData){ return res.status(400).json({error: 'Food Not Found'}) } res.status(200).json(oneFoodData) } catch(error){ console.error(error); } }) //post data to the database app.post('/foodData', async(req, res)=>{ try{ const addingData= new foodData(req.body); console.log("Wohooo!! A new food item is being added to the database" ); console.log(addingData.item_Name + " is added to the database."); const saveData= await addingData.save(); console.log(saveData); res.status(201).json(saveData); } catch(e){ console.error(e); } }) //Update data in the database app.put('/updateFoodData/:id', async(req, res)=>{ const id=req.params.id; delete id._id const newData=req.body; delete newData._id; console.log("Received request to update data with ID:", id); console.log("New data:", newData); try{ const updatedData=await foodData.findOneAndUpdate({id:id} ,{ $set: newData }, { new:true}); if(!updatedData){ return res.status(404).json({ error: 'Food item not found' }); } console.log(updatedData.item_Name + " is now updated"); res.status(200).json(updatedData); } catch(error){ console.error(error); res.status(500).json({error: 'Internal server error'}); } }) //delete date from the database app.delete('/deleteFoodData/:id', async(req,res)=>{ const id=req.params.id; try{ const deletedRecord=await foodData.findOneAndDelete({id}) console.log('One item is deleted from the database'); if(!deletedRecord){ return res.status(400).json({error: 'Food item not found'}); } res.status(200).json(deletedRecord) } catch(error){ console.error(error); res.status(500).json({error: 'Internal server error'}); } }) app.listen(port, ()=>{ console.log(`Port Number ${port}`); })
//dependencies var mysql = require('mysql'); var inquirer = require('inquirer'); //var password = require('./password.js'); var Table = require('cli-table'); var connection = mysql.createConnection({ host: 'localhost', port: 3306, user: 'root', password: 'password', database: 'bamazon_db' }); function start() { //prints the items for sale and their details connection.query('SELECT * FROM products', function(err, res) { if (err) throw err; console.log('Welcome to my bamazon: Chelsea edition'); console.log( '----------------------------------------------------------------------------------------------------' ); for (var i = 0; i < res.length; i++) { console.table( 'Id: ' + res[i].id + ' | ' + 'Product: ' + res[i].product_name + ' | ' + 'Department: ' + res[i].department_name + ' | ' + 'Price: ' + res[i].price + ' | ' + 'QTY: ' + res[i].stock_quantity ); console.log( '--------------------------------------------------------------------------------------------------' ); } console.log(' '); inquirer .prompt([ { type: 'input', name: 'id', message: 'What is the ID of the product you would like to purchase?', validate: function(value) { if ( isNaN(value) == false && parseInt(value) <= res.length && parseInt(value) > 0 ) { return true; } else { return false; } } }, { type: 'input', name: 'qty', message: 'How much would you like to purchase?', validate: function(value) { if (isNaN(value)) { return false; } else { return true; } } } ]) .then(function(ans) { var whatToBuy = ans.id - 1; var howMuchToBuy = parseInt(ans.qty); var grandTotal = parseFloat( (res[whatToBuy].price * howMuchToBuy).toFixed(2) ); //check if quantity is sufficient if (res[whatToBuy].StockQuantity >= howMuchToBuy) { //after purchase, updates quantity in Products connection.query( 'UPDATE products SET ? WHERE ?', [ { stock_quantity: res[whatToBuy].stock_quantity - howMuchToBuy }, { id: ans.id } ], function(err, result) { if (err) throw err; console.log( 'Success! Your total is $' + grandTotal.toFixed(2) + '. Your item(s) will be shipped to you in 3-5 business days.' ); } ); connection.query('SELECT * FROM departments', function(err, deptRes) { if (err) throw err; var index; for (var i = 0; i < deptRes.length; i++) { if ( deptRes[i].department_name === res[whatToBuy].department_name ) { index = i; } } //updates totalSales in departments table connection.query( 'UPDATE Departments SET ? WHERE ?', [ { TotalSales: deptRes[index].total_sales + grandTotal }, { DepartmentName: res[whatToBuy].department_name } ], function(err, deptRes) { if (err) throw err; //console.log("Updated Dept Sales."); } ); }); } else { console.log("Sorry, there's not enough in stock!"); } reprompt(); }); }); } //asks if they would like to purchase another item function reprompt() { inquirer .prompt([ { type: 'confirm', name: 'reply', message: 'Would you like to purchase another item?' } ]) .then(function(ans) { if (ans.reply) { start(); } else { console.log('See you soon!'); connection.end(); } }); } start();
import HomePost from "../components/HomePost"; import axios from "axios"; import { URL } from "./url"; import { useContext, useEffect, useState } from "react"; import { Link, useLocation } from "react-router-dom"; import Loader from "../components/Loader"; import SerachNav from "../components/SerachNav"; const Home = () => { const { search } = useLocation(); const [posts, setPosts] = useState([]); const [noResults, setNoresults] = useState(false); const [loder, setLoder] = useState(false); // const { user } = useContext(UserContext); const fetchPosts = async () => { setLoder(true); try { const res = await axios.get(URL + "api/v1/" + search); console.log(res.data); setPosts(res.data); if (res.data.length === 0) { setNoresults(true); } else { setNoresults(false); } setLoder(false); } catch (err) { console.log(err); setLoder(true); } }; useEffect(() => { fetchPosts(); }, [search]); return ( <> <SerachNav /> <div className="px-5 flex-col md:px-[200px] min-h-[80vh] mb-4"> {loder ? ( <div className="h-[40vh] flex justify-center items-center"> <Loader /> </div> ) : !noResults ? ( posts.map((post) => ( <> <Link key={post._id} to={`/post/${post._id}`}> <HomePost key={post._id} post={post} /> </Link> </> )) ) : ( <h3 className="mt-16 font-bold text-centre">No posts availble </h3> )} </div> </> ); }; export default Home;
using Microsoft.AspNetCore.Mvc; using TestC.Models; using TestC.Data; // Adicione este using para acessar ApplicationDbContext using System.Linq; using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; namespace TestC.Controllers { [Route("api/[controller]")] [ApiController] public class UsersController : ControllerBase { private readonly ApplicationDbContext _context; private readonly PasswordHasher<User> _passwordHasher = new PasswordHasher<User>(); public UsersController(ApplicationDbContext context) { _context = context; } // GET: api/users [HttpGet] public ActionResult<IEnumerable<User>> Get() { return _context.Users.ToList(); } // POST: api/Users/register [HttpPost("register")] public async Task<ActionResult<User>> Register([FromBody] User user) { if (_context.Users.Any(u => u.Email == user.Email)) { return BadRequest("Usuário com este e-mail já existe."); } user.Password = _passwordHasher.HashPassword(user, user.Password); _context.Users.Add(user); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(Get), new { id = user.Id }, user); } // POST: api/Users/login [HttpPost("login")] public ActionResult Login([FromBody] User loginRequest) { var user = _context.Users.FirstOrDefault(u => u.Email == loginRequest.Email); if (user == null || _passwordHasher.VerifyHashedPassword(user, user.Password, loginRequest.Password) != PasswordVerificationResult.Success) { return Unauthorized("Credenciais inválidas."); } // Aqui, insira a lógica para gerar e retornar um token JWT return Ok(new { Message = "Login bem-sucedido.", Token = "token_aqui" }); } // DELETE: api/Users/5 [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { var user = await _context.Users.FindAsync(id); if (user == null) { return NotFound(); } _context.Users.Remove(user); await _context.SaveChangesAsync(); return NoContent(); } } }
#include <bits/stdc++.h> using namespace std; bool comp1(vector<int> &j1, vector<int> &j2){ if (j1[1] == j2[1]) return j1[0] < j2[0]; else return j1[1] < j2[1]; } int main(){ int num_jobs; cout << "Enter the number of jobs: "; cin >> num_jobs; vector<vector<int>> jobs; for (int i = 0; i < num_jobs; i++){ cout << "Enter details for Job " << i + 1 << " id ,at , bt : "; vector<int> job_details(3); for (int j = 0; j < 3; j++) { cin >> job_details[j]; } job_details.push_back(0); job_details.push_back(0); job_details.push_back(0); job_details.push_back(job_details[2]); jobs.push_back(job_details); } vector<bool> visited(num_jobs, false); int ct = 0; sort(jobs.begin(), jobs.end(), comp1); int currbt = -1; int currid = -1; int completed_jobs = 0; while (completed_jobs < num_jobs){ int id = -1; int maxbt = INT_MIN; for (int i = 0; i < num_jobs; i++){ if (jobs[i][1] <= ct && !visited[i]){ if (jobs[i][6] > maxbt){ maxbt = jobs[i][6]; id = i; } } } if(maxbt==currbt){ id=currid; } if (id == -1){ ct++; continue; } jobs[id][6]--; if (jobs[id][6] == 0){ visited[id] = true; completed_jobs++; jobs[id][3] = ct + 1; jobs[id][4] = jobs[id][3] - jobs[id][1]; jobs[id][5] = jobs[id][4] - jobs[id][2]; currbt=-1; currid=-1; } else{ currbt=jobs[id][6]; currid=id; } ct++; } cout << "Job ID\tArrival Time\tBurst Time\tCompletion Time\tTurnaround Time\tWaiting Time\n"; for (int i = 0; i < num_jobs; i++) { cout << jobs[i][0] << "\t" << jobs[i][1] << "\t\t" << jobs[i][2] << "\t\t" << jobs[i][3] << "\t\t" << jobs[i][4] << "\t\t" << jobs[i][5] << endl; } return 0; }
# YOLOv7 Compressing Example <!--TOC--> - [Requirements](#requirements) - [Prepare Dataset](#prepare-dataset) - [Run Example](#run-example) - [References](#references) <!--TOC--> _CLIKA SDK_ example to compress `Yolov7` model on `COCO` dataset ## Requirements - Python >= 3.8 - CLIKA SDK (<https://docs.clika.io/docs/installation>) - Clone YOLOv7 project & Install dependencies ```shell # pwd: object_detection/yolov7 git clone https://github.com/WongKinYiu/yolov7.git cd yolov7 git reset --hard 84932d70fb9e2932d0a70e4a1f02a1d6dd1dd6ca cd .. # install requirements pip install -r yolov7/requirements.txt pip install torchmetrics[detection]==1.0.1 # download checkpoint wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt ``` ## Prepare Dataset To download and prepare the dataset simply run the following command: ```shell # pwd: object_detection/yolov7 sh ./yolov7/scripts/get_coco.sh ``` The dataset directory tree should look like the following: ```text coco ├── annotations ├── images │   ├── test2017 │   ├── train2017 │   └── val2017 └── labels    ├── train2017    └── val2017 ``` OR You may download COCO dataset from [official website](https://cocodataset.org/#download) and unzip. ## Run Example ```shell # pwd: object_detection/yolov7 python3 yolov7_main.py ``` ## References <https://github.com/WongKinYiu/yolov7>
<script setup> import Swal from 'sweetalert2' import axios from 'axios'; import { useTheme } from 'vuetify' const theme = useTheme(); const supabase = useSupabaseClient() const user = useSupabaseUser() const loading1 = ref(false) const loading2 = ref(false) // Define reactive variables const userAddress = ref([]); const usernewAddress = ref([]); const editMode = ref(false); const editedAddress = ref(); const newaddress = ref(false) const loadingAddresses = ref(true) // Fetch user's address on component mount onMounted(() => { fetchAddresses(); }) const fetchAddresses = async () => { const { data, error } = await supabase.auth.getSession() const id = data.session.user.id try { const { data, error } = await supabase .from('user_address') .select('*') .eq('uid', id) if (error) { throw error; } if (data) { userAddress.value = [data]; // Store fetched address in an array editedAddress.value = userAddress.value; // Initialize editedAddress with user's address // console.log(userAddress.value); loadingAddresses.value = false } } catch (error) { console.error('Error fetching user address:', error.message); } } // Function to enter edit mode andadd new address, populate editedAddress with selected address const newaddresstrigger = () => { newaddress.value = true editAddress() } // begin edit address const id = ref(); const updateValue = (addressId) => { id.value = addressId; // console.log('id value', id.value); editAddress() }; const editAddress = () => { editMode.value = true; // fetchCities() if (newaddress.value == false) { userAddress.value = editedAddress.value[0][id.value]; // userAddress.value = { } // console.log('editing User address:', editedAddress.value[0][id.value]); } else { userAddress.value = [] usernewAddress.value = userAddress.value; // console.log('una', usernewAddress.value); } }; // Function to cancel edit mode and reset editedAddress const cancelEdit = () => { editMode.value = false; editedAddress.value = []; // Reset editedAddress userAddress.value = [] fetchAddresses() }; // Function to save the edited, new addresses const saveAddress = async () => { if (newaddress.value == false) { // console.log('uploading edited address'); loading1.value = true const { data, error } = await supabase.auth.getSession(); const userId = data.session.user.id; try { // Save the edited address to Supabase const { data2, error } = await supabase .from('user_address') .upsert([{ uid: userId, ...editedAddress.value[0][id.value] }]); // , { onConflict: ['uid'] } if (error) { throw error; } fetchAddresses() // console.log('Address saved:', data2); } catch (error) { console.error('Error saving address:', error.message); } } else { newaddress.value = false // console.log('uploading new address'); loading1.value = true const { data, error } = await supabase.auth.getSession(); const userId = data.session.user.id; try { // Save the new address to Supabase const { data2, error } = await supabase .from('user_address') .upsert([{ uid: userId, ...usernewAddress.value }]); // , { onConflict: ['uid'] } if (error) { throw error; } fetchAddresses() // console.log('address to add', usernewAddress.value); // console.log('Address saved:', data2); } catch (error) { console.error('Error saving address:', error.message); } } // Exit edit mode loading1.value = false editMode.value = false; }; // delete address // delete confirm const DeleteAddressBegin = (addressId) => { id.value = addressId; Swal.fire({ title: 'Warning!', icon: 'warning', text: 'This Address will be deleted!', showConfirmButton: true, showCancelButton: true, }).then((result) => { if (result.isConfirmed) { DeleteAddress(); } else { } }); } // Delete Address from database const DeleteAddress = async () => { const supabase = useSupabaseClient() try { const { error } = await supabase .from('user_address') .delete() .eq('id', id.value) // console.log(userAddress.value) if (error) { console.log(error) } else { // const { error } = await supabase // .storage // .from('products_images') // .remove([`${product.value.name}`]); // if (error) { // console.log(error) // } else { // console.log('Deleted image'); Swal.fire({ title: 'Success', icon: 'success', text: 'Address deleted successfully!', toast: true, timer: 2000, showConfirmButton: false, }).then(() => { fetchAddresses() }) // } } } catch (error) { console.log(error) } }; // fetch cities const cities = ref() async function fetchCities() { try { const response = await axios.get(`/eg_cities.json`); if (response.status === 200) { cities.value = (response.data) .sort((a, b) => { // Accessing the common name of each country object const commonA = a.city_name_en.toUpperCase(); // Convert to uppercase for case-insensitive sorting const commonB = b.city_name_en.toUpperCase(); // Use localeCompare for string comparison return commonA.localeCompare(commonB); }); // console.log(cities.value); } else { throw new Error('Failed to fetch data'); } } catch (err) { console.log(err); cities.value = null; } } // fetch Governorates const states = ref() async function fetchStates() { try { const response = await axios.get(`/eg_governorates.json`); if (response.status === 200) { states.value = (response.data) .sort((a, b) => { // Accessing the common name of each country object const commonA = a.governorate_name_en.toUpperCase(); // Convert to uppercase for case-insensitive sorting const commonB = b.governorate_name_en.toUpperCase(); // Use localeCompare for string comparison return commonA.localeCompare(commonB); }); // console.log(cities.value); } else { throw new Error('Failed to fetch data'); } } catch (err) { console.log(err); states.value = null; } } </script> <template> <div class="mb-20"> <v-icon class="m-2" size="30">mdi-home</v-icon> <h2 class="text-2xl font-bold mb-10">Manage Delivery Addresses</h2> <div v-if="editMode && editedAddress"> <form id="form" class="space-y-5 p-5 w-11/12 md:w-11/12 h-fit text-center mx-auto justify-center flex-col" @submit.prevent="saveAddress"> <!--input fields--> <div class="mainfields grid grid-flow-row auto-cols-auto gap-6"> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text flex w-full "> <label for="street" class="p-2 font-semibold text-lg text-left my-auto">Name<span class="required text-red-600">*</span>:</label> <input id="name" name="name" v-model="userAddress.name" placeholder="Full name ex: Joe Doe" type="text" @focus="move" @blur="back" class=" outline outline-1 outline-zinc-700 rounded-lg px-2 text-black bg-transparent p-3 w-full" :class="theme.global.current.value.dark ? 'text-white' : 'text-black'" required> </div> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text flex w-full "> <label for="street" class="p-2 font-semibold text-lg text-left my-auto">Phone<span class="required text-red-600">*</span>:</label> <input id="phone" name="phone" v-model="userAddress.phone" placeholder="ex: 01xxxxxxxxx" type="tel" @focus="move" @blur="back" class=" outline outline-1 outline-zinc-700 rounded-lg px-2 text-black bg-transparent p-3 w-full" :class="theme.global.current.value.dark ? 'text-white' : 'text-black'" required> </div> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text flex w-full "> <label for="street" class="p-2 font-semibold text-lg text-left my-auto">Email<span class="required text-red-600">*</span>:</label> <input id="email" name="email" v-model="userAddress.email" placeholder="email@email.com" type="text" @focus="move" @blur="back" class=" outline outline-1 outline-zinc-700 rounded-lg px-2 text-black bg-transparent p-3 w-full" :class="theme.global.current.value.dark ? 'text-white' : 'text-black'" required> </div> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text flex w-full "> <label for="street" class="p-2 font-semibold text-lg text-left my-auto">Street<span class="required text-red-600">*</span>:</label> <input id="street" name="street" v-model="userAddress.street" placeholder="Street name, address..." type="text" @focus="move" @blur="back" class=" outline outline-1 outline-zinc-700 rounded-lg px-2 text-black bg-transparent p-3 w-full" :class="theme.global.current.value.dark ? 'text-white' : 'text-black'" required> </div> <div class="2,3 grid grid-cols-2 grid-rows-1 gap-2"> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text md:flex w-full text-left mx-auto"> <label for="street" class="p-2 font-semibold text-lg my-auto">Building<span class="required text-red-600">*</span>:</label> <input id="building" name="building" v-model="userAddress.building" placeholder="Building no." type="text" @focus="move" @blur="back" class=" outline outline-1 px-2 outline-zinc-700 rounded-lg text-black bg-transparent p-3 w-full" :class="theme.global.current.value.dark ? 'text-white' : 'text-black'" required> </div> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text md:flex w-full text-left mx-auto"> <label for="street" class="p-2 font-semibold text-lg my-auto">Apartment<span class="required text-red-600">*</span>:</label> <input id="apartment" name="apartment" v-model="userAddress.apartment" placeholder="Apartment, flat no." type="text" @focus="move" @blur="back" class="outline outline-1 px-2 outline-zinc-700 rounded-lg text-black bg-transparent p-3 w-full" :class="theme.global.current.value.dark ? 'text-white' : 'text-black'" required> </div> </div> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text md:flex w-full text-left mx-auto"> <label for="street" class="p-2 font-semibold text-lg my-auto">Neighborhood<span class="required text-red-600">*</span>:</label> <input id="neighborhood" name="neighborhood" v-model="userAddress.neighborhood" placeholder="Neighborhood or district" type="text" @focus="move" @blur="back" class="outline outline-1 px-2 outline-zinc-700 rounded-lg text-black bg-transparent p-3 w-full" :class="theme.global.current.value.dark ? 'text-white' : 'text-black'" required> </div> <div class="5,6,7 grid md:grid-rows-1 gap-4 w-full"> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text pxa-2 rounded-lg w-full "> <v-select variant="outlined" id="city" name="city" :items="cities" @click="fetchCities" :item-title="'city_name_en'" :item-value="'city_name_en'" label="Select a city*" item-text="city_name_en" placeholder="City*" type="text" v-model="userAddress.city" class="text-blac outline-none bg-transparent my-auto p- w-full" :theme="theme.global.current.value.dark ? 'dark' : 'light'" :required='true'></v-select> </div> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text pax-2 rounded-lg w-full "> <v-select variant="outlined" id="state" name="state" :items="states" @click="fetchStates" :item-title="'governorate_name_en'" :item-value="'governorate_name_en'" label="Select a governorate*" item-text="governorate_name_en" placeholder="State*" type="text" v-model="userAddress.state" class="text-blac outline-none bg-transparent my-auto p- w-full" :theme="theme.global.current.value.dark ? 'dark' : 'light'" :required='true'></v-select> </div> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text outline outline-1 px-2 outline-zinc-700 rounded-lg w-full "> <input id="postcode" name="postcode" v-model="userAddress.postalCode" placeholder="Post code*" type="number" min="4" @focus="move" @blur="back" class="text-black outline-none bg-transparent p-3 w-full" :class="theme.global.current.value.dark ? 'text-white' : 'text-black'" required> </div> </div> <div :class="theme.global.current.value.dark ? ' text-white' : 'bg-zinc-100 text-black'" class="text md:flex w-full text-left mx-auto"> <!-- <label for="street" class="p-2 font-semibold text-lg my-auto">Country<span class="required text-red-600">*</span>:</label> --> <v-select variant="outlined" id="country" name="country" :items="['Egypt']" :item-value="'Egypt'" label="Select a Country*" placeholder="Country*" type="text" v-model="userAddress.country" class="text-blac outline-none bg-transparent my-auto p- w-full" :theme="theme.global.current.value.dark ? 'dark' : 'light'" :required='true'></v-select> </div> </div> <!--Submit button--> <v-btn @click="" type="submit" min-width="150" min-height="40" color="green-lighten-1" elevation="1" :disabled="false" variant="outlined" :class="theme.global.current.value.dark ? ' text-white' : ' hover:bg-green-1a00 text-white hover:text-gray-5s0'" class="m-5 text-lg rounded-md hover:cursor-pointer"> <v-progress-circular v-if="loading1" width="2" size="20" color="darken-blue-4" class="m-1" indeterminate></v-progress-circular> Save </v-btn> <v-btn @click="cancelEdit" type="button" min-width="150" min-height="40" color="red-lighten-1" elevation="1" variant="tonal" :class="theme.global.current.value.dark ? ' text-white' : ' hover:bg-red-100 text-white hover:text-gray-50'" class="m-5 text-lg rounded-md hover:cursor-pointer"> <v-progress-circular v-if="loading2" width="2" size="20" color="darken-blue-4" class="m-1" indeterminate></v-progress-circular> cancel </v-btn> </form> </div> <div v-else> <div v-if="!loadingAddresses" class="md:grid grid-cols-2 gap-2 justify-center md:space-x- text-left text-lg shadow-md w-11/12 p-5 mx-auto"> <div v-if="userAddress" v-for="(address, index) in userAddress[0]" :key="index" class=" mb-2 min-w-48 p-5 outline outline-zinc-700 shadow-lg"> <strong>Name:</strong> {{ address.name }} <br> <strong>Phone:</strong> {{ address.phone }} <br> <strong>Email:</strong> {{ address.email }} <br> <strong>Street:</strong> {{ address.street }} <br> <strong>Building:</strong> {{ address.building }} <br> <strong>Apartment:</strong> {{ address.apartment }} <br> <strong>Neighborhood:</strong> {{ address.neighborhood }} <br> <strong>City:</strong> {{ address.city }} <br> <strong>State:</strong> {{ address.state }} <br> <strong>Postal Code:</strong> {{ address.postalCode }} <br> <strong>Country:</strong> {{ address.country }} <br> <div class="grid grid-cols-2 grid-rows-2 w-fit mx-auto text-center justify-center space-x- mt-4"> <v-btn @click="updateValue(index)" class="m-1" min-height="40" max-width="100" color="grey-lighten-2"><v-icon>mdi-pencil</v-icon></v-btn> <v-btn @click="DeleteAddressBegin(address.id)" class="m-1" min-height="40" max-width="100" color="red-darken-2"><v-icon>mdi-delete</v-icon></v-btn> <v-btn @click="" class="m-2 col-span-2 w-fuasll flaex justify-center" min-height="40" max-width="200" variant="outlined">Set as default</v-btn> </div> </div> <div v-else>No address available for this user.</div> </div> <div v-else> <div class="flex justify-center w-full"> <div class=" shadow-sm"> <div class="flex w-full justify-center text-zinc-950 p-10"><v-progress-circular color="dark-blue" indeterminate></v-progress-circular> </div> </div> </div> </div> </div> <div v-if="!editMode" class="add p-5"> <v-btn @click="newaddresstrigger"><v-icon>mdi-plus</v-icon>Add New address</v-btn> </div> </div> </template>
import { useEffect, useRef, useState } from 'react'; import { Link } from 'react-router-dom'; import { useRecipeApi } from '../../../hooks/useApi'; import { Button } from '../../atoms/Button'; import { Candidate } from '../../molecules/Candidate'; import timer from '../../../scripts/formatTime'; export default function PollRecipes() { const [recipes, setRecipes] = useState([]); const refRecipeApi = useRef(useRecipeApi()); useEffect(() => { (async () => { const { data } = await refRecipeApi.current.getAllRecipes(); const filteredRecipeByDate = data.filter(recipe => { if (timer(recipe.createdAt).isSameMonth()) return recipe else return null }) setRecipes(filteredRecipeByDate) })() }, []) recipes.sort((candidateA, candidateB) => { return candidateB.votes.length - candidateA.votes.length }); return ( <div className="w-full bg-white p-4 border-b-[1px] border-solid border-gray-300 flex flex-col"> <h2 className='text-center mb-8 p-4 text-s2'>Qual será a melhor receita do mês?</h2> <div className="w-full flex items-end justify-evenly my-4"> {recipes.map((candidate, i) => { return i < 3 && <Candidate key={candidate.id} position={i} candidate={candidate} recipes={recipes} /> })} </div> <Link to={'/poll'}> <Button customClass={"btn-primary mx-auto block px-12 text-s1_2 mt-8"}>Ver votação</Button> </Link> </div> ) }
# 动物类 class Animal: def eat(self): print("父类:吃") # 猫类 class Cat(Animal): # 写和父类 同名的方法 def eat(self): # 先调用父类的方法 # super() 通用写法 # super() 代表 父类 super().eat() # 然后再调用 自己的代码 print("子类:吃鱼 吃大鱼 吃鲨鱼") # 创建猫的对象 c = Cat() c.eat()
import React, { useState } from 'react' import { FormattedMessage } from 'react-intl' import history from '../../../router/history' import AreasWrapper, { AreaInputs } from './Areas.styles' import Button from '../../common/Buttons/Button' import Input from '../../common/Inputs/Input' import { createArea } from './api' import { siteMap } from '../../siteMap' import { InputTheme } from '../../../model/Themes' const AreaComponent = () => { const [name, setName] = useState(null) const [description, setDescription] = useState(null) const [weight, setWeight] = useState(null) const onWeightUpdate = (val) => { let cleanVal = Number(val.replace(/[^0-9 ]/g, '')) if (cleanVal > 10) { cleanVal = 10 } setWeight(cleanVal) } const onCreate = () => { createArea(name, description, '', false, weight) .then(() => history.push(siteMap.USER.areas())) } return ( <AreasWrapper> <AreasWrapper.Title> <FormattedMessage id="AreaComponent.title" /> </AreasWrapper.Title> <AreasWrapper.Areas> <AreaInputs> <Input theme={InputTheme.LIGHT_WITH_BORDER} placeholderId="AreaComponent.field.name" value={name} onChange={(e) => setName(e.target.value)} /> <Input theme={InputTheme.LIGHT_WITH_BORDER} placeholderId="AreaComponent.field.description" value={description} onChange={(e) => setDescription(e.target.value)} /> <Input theme={InputTheme.LIGHT_WITH_BORDER} placeholderId="AreaComponent.field.weight" value={weight} onChange={(e) => onWeightUpdate(e.target.value)} /> <Button onClick={onCreate} > <FormattedMessage id="AreaComponent.btn.create" /> </Button> </AreaInputs> </AreasWrapper.Areas> </AreasWrapper> ) } export default AreaComponent
export const snippets = { "[fizzbuzz]: Fizzbuzz program in Javascript using recursion": { prefix: "snippet-fizzbuzz", body: [ "function myFunction(number, current = 1, results = []) { \n" + " if (current > number) { \n" + " return results; \n" + " } \n\n" + " let output = []; \n" + " if (current % 3 === 0) output.push('Fizz'); \n" + " if (current % 5 === 0) output.push('Buzz'); \n\n" + " if (output.length === 0) { \n" + " results.push(current); \n" + " } else { \n" + " results.push(output.join('')); \n" + " } \n\n" + " return myFunction(number, current + 1, results); \n" + "} ", ], description: "[fizzbuzz]: Fizzbuzz program in Javascript using recursion", }, };
<template> <q-drawer :value="drawerActivityList" :width="250" content-class="navNachos" content-style="padding-bottom:40px;" > <q-item clickable class="bg-secondary text-white" style="border-bottom: 1px solid #1d3346" > <q-item-section avatar> <q-avatar size="28px" class="q-ml-sm" > <img src="https://www.gstatic.com/mobilesdk/160503_mobilesdk/logo/2x/firebase_28dp.png" /> </q-avatar> </q-item-section> <q-item-section class="text-h6 text-weight-bold" style="letter-spacing:-1px;font-family: manjari;padding-top:2px" > Einstein Tech </q-item-section> </q-item> <q-scroll-area :thumb-style="thumbStyle" style="height: 90%;overflow-x:hidden" :content-style="contentStyle" :content-active-style="contentActiveStyle" > <q-list class="q-pb-md text-blueGreyfire"> <div class="row bg-secondary"> <div class="col"> <q-item clickable exact to="/" class="q-py-md bg-secondary" active-class="text-blue-5" @mouseover="inset = false" @mouseleave="inset = true" > <q-item-section avatar class="" > <q-icon class="on-right" size="22px" name="home" /> </q-item-section> <q-item-section class="text-subtitle2">System Overview</q-item-section> </q-item> </div> <q-separator vertical class="bg-separatorFire" :inset="inset" /> <div class="bg-secondary"> <q-avatar v-ripple @click="test" @mouseover="hoverIcon = true" @mouseleave="hoverIcon = false" class="cursor-pointer q-mt-xs" > <q-icon size="20px" name="settings" :class="hoverIcon ? 'rotate-315' : ''" /> <q-icon style="margin-left:-3px; " v-if="hoverIcon || showSetting" size="15px" name="play_arrow" /> <q-menu v-model="showSetting" :offset="[-45,-45]" > <q-list bordered dense class="q-py-sm" > <q-item clickable> <q-item-section> System Settings </q-item-section> </q-item> <q-item clickable> <q-item-section> Users and permissions </q-item-section> </q-item> </q-list> </q-menu> </q-avatar> <!-- </q-btn> --> </div> </div> <q-separator style="background-color: #404854" /> <registrarList :registrarMenuList="registrarMenuList" /> <q-separator class="bg-secondaryTransSeparator" /> <libraryList :libraryMenuList="libraryMenuList" /> <q-separator class="bg-secondaryTransSeparator" /> <dsaList :dsaList="dsaList" /> <q-separator class="bg-secondaryTransSeparator" /> <!-- <cmoList :cmoList="cmoList" /> --> </q-list> </q-scroll-area> </q-drawer> </template> <script> export default { props: ['thumbStyle', 'contentStyle', 'contentActiveStyle', 'drawerActivityList'], components: { 'registrarList': require('./drawerListItem/registrarList.vue').default, 'libraryList': require('./drawerListItem/libraryList.vue').default, 'dsaList': require('./drawerListItem/dsaList.vue').default // 'cmoList': require('./drawerListItem/cmoList.vue').default }, data () { return { inset: true, hoverIcon: false, showSetting: false, registrarMenuList: [ { title: 'Students', avatar: 'person', nameRoute: '/registrarStudents' }, { title: 'Parents', avatar: 'face', nameRoute: '' }, { title: 'Personnel', avatar: 'supervisor_account', nameRoute: '/registrarPersonnel' } ], libraryMenuList: [ { title: 'Catalog', avatar: 'library_books', nameRoute: 'libraryCatalog' }, { title: 'Statistics', avatar: 'perm_contact_calendar', nameRoute: '/libraryStatistics' }, { title: 'Borrowers', avatar: 'book', nameRoute: '/libraryBorrowers' }, { title: 'Penalties', avatar: 'monetization_on', nameRoute: '' } ], dsaList: [ // { // title: 'Voting', // avatar: 'library_books' // }, // { // title: 'Statistics', // avatar: 'perm_contact_calendar' // }, // { // title: 'Borrowers', // avatar: 'book' // }, // { // title: 'Penalties', // avatar: 'monetization_on' // } ] } }, methods: { test () { console.log('test') // alert('test') } } } </script>
-- Paquete estándar que vamos a manejar. with Ada.Text_Io; use Ada.Text_Io; --LA TABLA DE LA PARTE B DEL PROBLEMA --Número entero más pequeño-->-2147483648 --Número entero más grande-->2147483647 --Número natural más pequeño-->0 --Número positivo más pequeño--> 1 --Número de dígitos significativos de los números reales-->7 procedure registros is package Ent_Es is new Ada.Text_Io.Integer_Io( Integer ); use Ent_Es; --Estas dos variables serviran para saber en que posicion del array esta el maximo y el minimo encontradoMinimo: Boolean := False; encontradoMaximo: Boolean := False; I, J,posicionMin,posicionMax: Integer; media : Float; -- Definimos los parametros de fehca y sus respectivos paquetes para poder hacer entradas y salidas por pantalla --TEMPERATURA type temperatura_t is delta 0.01 range -25.0..75.0; package ES_temperatura_t is new Ada.Text_Io.Fixed_Io(temperatura_t); use ES_temperatura_t; --DIAS type dias_t is range 1..31; package ES_dias_t is new Ada.Text_Io.Integer_Io(dias_t); use Es_dias_t; --MESES type meses_t is (enero , febrero , marzo , abril , mayo , junio , julio, agosto, septiembre, octubre, noviembre , diciembre); package ES_meses_t is new Ada.Text_Io.Enumeration_Io(meses_t); use ES_meses_t ; --ANNO type year_t is range 1900..2100; package ES_year_t is new Ada.Text_Io.Integer_Io(year_t); use ES_year_t; type fecha_t is record Dia : dias_t ; Mes : meses_t ; Year : year_t ; temp : temperatura_t; end record ; type fecha_array is array ( Positive range <> ) of fecha_t ; -- Creamos un tipo puntero al tipo anterior type pArray_t is access fecha_array ; -- Declaramos una variable de tipo puntero a array_t v: pArray_t ; --Maximo, Minimo y Media minimo : temperatura_t; maximo : temperatura_t; suma : temperatura_t; begin --Primero obtenemos el numero de parametros y lo almacenamos en la variable I previamente definida New_Line; Put ("Introduce cuantos valores vas a introducir: "); get (I); J :=1; --Declaramos una nueva instancia al array en el que vamos a almacenar las fechas v:= new fecha_array(1..I) ; while J<= I loop New_Line; --Salto de linea Put ("Introduce el dia: "); get(v(J).Dia); Put ("Introduce el mes: "); get(v(J).Mes); Put ("Introduce el anno: "); get(v(J).Year); Put ("Introduce la temperatura en grados:"); get(v(J).temp); J := J +1; end loop ; --Empezamos declarando el minimo como la primera posicion del array y vamos comprobando numero a numero del array si es menor y si los es lo declaramos como el nuevo minimo minimo := v(1).temp; for I in v'Range loop if v(I).temp < minimo then minimo := v(I).temp; end if; end loop; --Empezamos declarando el maximo como la primera posicion del array y vamos comprobando numero a numero del array si es mayor y si los es lo declaramos como el nuevo maximo maximo := v(1).temp; for I in v'Range loop if v(I).temp > maximo then maximo := v(I).temp; end if; end loop; for I in v'Range loop suma := v(I).temp+ suma; end loop; media := Float(suma)/Float(I); --Para calcular la media en este caso necesito la suma de temperaturas y el numero de temperaturas I, como una es de tipo temperatura_t y la otra --de tipo int por lo que , hago esta conversion a float que es la unica que me deja hacer temperatura_t --Recooremos ek array en base a los booleanos creados , si el minimo es igual al numero del array, es que esta en esa posicion por lo que ponemos la varibale en true y salimos del bucle -- si no es igual pues le sumamos uno a posicion y pasamos a la siguiente posicion del array y comprobamos hasta encontrar el valor . posicionMin := 1; for I in v'Range loop if minimo = v(I).temp then encontradoMinimo := True; elsif encontradoMinimo = False then posicionMin := posicionMin +1; end if; end loop; --Recooremos ek array en base a los booleanos creados , si el maximo es igual al numero del array, es que esta en esa posicion por lo que ponemos la varibale en true y salimos del bucle -- si no es igual pues le sumamos uno a posicion y pasamos a la siguiente posicion del array y comprobamos hasta encontrar el valor . posicionMax := 1; for I in v'Range loop if maximo = v(I).temp then encontradoMaximo := True; elsif encontradoMaximo = False then posicionMax := posicionMax +1; end if; end loop; --Mostramos por pantalla el maximo el minimo la media y las fehcas registradas de ambas Put("Temperatura minima: " & minimo'Image ); Put(" grados, alcanzados el" & v(posicionMin).dia'Image ); Put(" de " & v(posicionMin).Mes'Image ); Put(" de " & v(posicionMin).Year'Image ); New_Line; Put("Temperatura maxima: " & maximo'Image); Put(" grados, alcanzados el" & v(posicionMax).dia'Image ); Put(" de" & v(posicionMax).Mes'Image ); Put(" de" & v(posicionMax).Year'Image ); New_line; Put("La temperatura media del periodo" & v(1).dia'Image); Put(" de " & v(1).Mes'Image ); Put(" de " & v(1).Year'Image ); Put(" al" & v(v'Last).Dia'Image); Put(" de" & v(v'Last).Mes'Image ); Put(" de " & v(v'Last).Year'Image ); Put(" ha sido de" & media'Image ); Put(" grados"); end registros;