text
stringlengths 184
4.48M
|
---|
<template>
<div class="container page">
<main>
<div class="sushi-select not-started">
<div class="not-started__title">管理者に招待されています</div>
<div class="not-started__textbox">
<div class="not-started__textbox--title">{{ room.title }}</div>
<div>
{{ room.description }}
</div>
{{ room.state === "ongoing" ? "ルーム開催中" : "ルーム開始前" }}
</div>
<div class="not-started__button">
<button @click="regiaterAdmin">招待を受ける</button>
</div>
</div>
<InviteSuccess />
</main>
</div>
</template>
<script lang="ts">
import Vue from "vue"
import VModal from "vue-js-modal"
import { RoomModel } from "~/../shared/dist"
import InviteSuccess from "@/components/Home/InviteSuccess.vue"
// Data型
type DataType = {
// ルーム情報
room: RoomModel
roomId: string
adminInviteKey: string
}
Vue.use(VModal)
export default Vue.extend({
name: "Invited",
components: {
InviteSuccess,
},
async asyncData({ app, query }) {
if (
query.roomId == null ||
query.roomId === "" ||
query.adminInviteKey == null ||
query.adminInviteKey === ""
) {
throw new Error(
"エラーが発生しました。URLが間違っている可能性があります。",
)
}
const res = await app.$apiClient
.get({
pathname: "/room/:id",
params: { id: query.roomId as string },
})
.catch(() => {
throw new Error(
"エラーが発生しました。URLが間違っている可能性があります。",
)
})
if (res.result === "error") {
throw res.error
}
return { room: res.data }
},
data(): DataType {
return { room: {} as RoomModel, roomId: "", adminInviteKey: "" }
},
mounted() {
// roomId取得
this.roomId = this.$route.query.roomId as string
// adminInviteKey取得
this.adminInviteKey = this.$route.query.admin_invite_key as string
if (this.roomId == null || this.roomId === "") {
this.$router.push("/")
}
},
methods: {
async regiaterAdmin() {
const res = await this.$apiClient.post(
{
pathname: `/room/:id/invited`,
params: { id: this.roomId },
},
{},
{
admin_invite_key: this.adminInviteKey,
},
)
if (res.result === "error") {
window.alert("処理に失敗しました")
throw new Error("管理者招待失敗")
}
this.$modal.show("home-invite-success-modal", {
title: this.room.title,
id: this.room.id,
adminInviteKey: this.room.adminInviteKey,
})
},
},
})
</script> |
import java.util.*;
/**
* Classe concreta e immutabile utile a rappresentare un equazione chimica,
* un equazione chimica descrive una reazione (o trasformazione) chimica e consiste di una lista di reagenti (le molecole di partenza)
* e di una lista di prodotti (le molecole di arrivo)
*/
public class EquazioneChimica {
private final String equazione; //equazione
private final Map<Molecola,Integer> reagenti = new HashMap<>(); //i reagenti con la loro numerosità
private final Map<Molecola,Integer> prodotti = new HashMap<>(); //i prodotti con la loro numerosità
/**
* RI: Reagenti e prodotti non devono essere null, ogni molecola non deve essere null, ogni molecola deve avere numerosità almeno 1
*/
/**
* Costruisce una nuova formula chimica a partire da un equazione e la tavola periodica
* @param equazione l'equazione
* @param tv la tavola periodica
* @throws NullPointerException se l'equazione è nul
*/
public EquazioneChimica(final String equazione, TavolaPeriodica tv) {
if (Objects.requireNonNull(equazione,"L'equazione non può essere null").isEmpty()){
throw new IllegalArgumentException("l'equazione non può essere null");
}
if (!equazione.contains("->")) throw new IllegalArgumentException("L'equazione non ha reagenti o prodotti");
this.equazione = equazione;
var componentiEq = equazione.split("->");
var parseReagenti = Helpers.parseSommaStechiometrica(componentiEq[0]);
for (int i = 1; i < parseReagenti.length; i+=2) {
Molecola m;
if (Molecola.isSemplice(parseReagenti[i])){
m = new MolecolaSemplice(parseReagenti[i],tv);
}else {
m = new MolecolaComposta(parseReagenti[i],tv);
}
reagenti.put(m,Integer.parseInt(parseReagenti[i-1]));
}
var parseProdotti = Helpers.parseSommaStechiometrica(componentiEq[1]);
for (int i = 1; i < parseProdotti.length; i+=2) {
Molecola m;
if (Molecola.isSemplice(parseProdotti[i])){
m = new MolecolaSemplice(parseProdotti[i],tv);
}else {
m = new MolecolaComposta(parseProdotti[i],tv);
}
prodotti.put(m,Integer.parseInt(parseProdotti[i-1]));
}
}
/**
* Verifica se un equazione è bilanciata ovvero se e solo se ciascun tipo di elementi è presente nello stesso numero sia nei reagenti che nei prodotti.
* @return true se l'equazione è bilanciata, false altrimenti
*/
public boolean isBilanciata(){
Map<ElementoChimico,Integer> numeroElementiReagenti = new HashMap<>();
Map<ElementoChimico,Integer> numeroElementiProdotti = new HashMap<>();
for (var el : reagenti.entrySet()){
for (ElementoChimico atomo : el.getKey()){
if (numeroElementiReagenti.containsKey(atomo)) {
numeroElementiReagenti.put(atomo, numeroElementiReagenti.get(atomo) + el.getValue() * el.getKey().numerositàAtomo(atomo));
}else {
numeroElementiReagenti.put(atomo, el.getValue() * el.getKey().numerositàAtomo(atomo));
}
}
}
for (var el : prodotti.entrySet()){
for (ElementoChimico atomo : el.getKey()){
if (numeroElementiProdotti.containsKey(atomo)){
numeroElementiProdotti.put(atomo , numeroElementiProdotti.get(atomo) + el.getValue() * el.getKey().numerositàAtomo(atomo));
}else{
numeroElementiProdotti.put(atomo , el.getValue() * el.getKey().numerositàAtomo(atomo));
}
}
}
return numeroElementiProdotti.equals(numeroElementiReagenti);
}
/**
* Restituisce una lista contenente i reagenti coinvolti nell'equazione
* @return i reagenti
*/
public List<Molecola> getReagenti(){
return new ArrayList<Molecola>(reagenti.keySet());
}
/**
* Restituisce una lista contenente i prodotti coinvolti nell'equazione
* @return i prodotti
*/
public List<Molecola> getProdotti(){
return new ArrayList<Molecola>(prodotti.keySet());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
String spazi = " ";
sb.append("Equazione: \n");
sb.append(spazi);
sb.append(equazione + ", "+ (isBilanciata() ? "bilanciata" : "non bilanciata")+"\n");
sb.append("Reagenti: \n");
for (var reagente : getReagenti()){
sb.append(spazi + reagente+"\n");
}
sb.append("Prodotto: \n");
for (var reagente : getProdotti()){
sb.append(spazi + reagente+"\n");
}
return sb.toString();
}
} |
using AutoMapper;
using ClothesShop.DatabaseAccess.Entities.ItemsEntity;
using ClothesShop.DatabaseAccess.Interfaces.ItemsRepository;
using ClothesShop.Services.Interfaces;
using ClothesShop.Services.Models.ItemsModels;
using ClothesShopServices.WebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClothesShop.Services.Services
{
public class ItemsService : IItemsService
{
private IReadItemsRepository _readItemsRepository;
private IWriteItemsRepository _writeItemsRepository;
private IMapper _mapper;
public ItemsService(IReadItemsRepository readItemsRepository, IWriteItemsRepository writeItemsRepository, IMapper mapper)
{
_readItemsRepository = readItemsRepository;
_writeItemsRepository = writeItemsRepository;
_mapper = mapper;
}
private ResponceData NullValidation<T>(T inputElement, string successfulMessage, string failureMessage)
{
var result = new ResponceData();
if (inputElement != null)
{
result.Result = true;
result.Message = successfulMessage;
}
else
{
result.Result = false;
result.Message = failureMessage;
}
return result;
}
public async Task<ItemsDetailedData> GetItemById(int itemId)
{
var findedItem = await _readItemsRepository.GetItemById(itemId);
var result = _mapper.Map<ItemsDetailedData>(findedItem);
return result;
}
public async Task<IEnumerable<ItemsDetailedData>> GetItemsByPage(int page, int pageSize)
{
var listOfItems = await _readItemsRepository.GetItemsByPage(page, pageSize);
var result = _mapper.Map<IEnumerable<ItemsDetailedData>>(listOfItems);
return result.ToList();
}
public async Task<ResponceData> AddNewItem(ItemsDetailedData newItemPostData)
{
var mappedItem = _mapper.Map<Items>(newItemPostData);
var createdItem = await _writeItemsRepository.AddNewItem(mappedItem);
return NullValidation(createdItem, "Item was added successfuly", "An error occured while adding new item");
}
public async Task<ResponceData> UpdateItem(ItemsDetailedData newItemPostData, int itemId)
{
var findedItem = await _readItemsRepository.GetItemById(itemId);
var mappedItem = _mapper.Map(newItemPostData, findedItem);
var updatedItem = await _writeItemsRepository.UpdateItem(mappedItem, itemId);
return NullValidation(updatedItem, "Item was updated successfully", "An error occured while updating new item");
}
public async Task<ResponceData> AddCartItem(int itemId, string userId)
{
var addedToCartItem = await _writeItemsRepository.AddCartItem(itemId, userId);
return NullValidation(addedToCartItem, "Item was added to cart successfully", "An error occured while adding item to cart");
}
public async Task<ResponceData> DeactivateItem(int itemId)
{
var deactivatedItem = await _writeItemsRepository.DeactivateItem(itemId);
return NullValidation(deactivatedItem, "Item was deactivated successfully", "An error occured while deactivating cart");
}
public async Task<ResponceData> DeleteCartItem(int itemId)
{
var deletedCartItem = await _writeItemsRepository.DeleteCartItem(itemId);
return NullValidation(deletedCartItem, "Cart item was deleted successfully", "An error occured whiledeleting cart item");
}
}
} |
package ru.skillbranch.skillarticles.markdown.spans
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.text.Layout
import android.text.style.LeadingMarginSpan
import android.util.Log
import androidx.annotation.ColorInt
import androidx.annotation.Px
import androidx.annotation.VisibleForTesting
class OrderedListSpan(
@Px
private val gapWidth: Float,
private val order: String,
@ColorInt
private val orderColor: Int
) : LeadingMarginSpan {
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
override fun getLeadingMargin(first: Boolean): Int {
return (order.length.inc() * gapWidth).toInt()
}
override fun drawLeadingMargin(
canvas: Canvas, paint: Paint, currentMarginLocation: Int, paragraphDirection: Int,
lineTop: Int, lineBaseline: Int, lineBottom: Int, text: CharSequence?, lineStart: Int,
lineEnd: Int, isFirstLine: Boolean, layout: Layout?
) {
if (isFirstLine) {
val oldColor = paint.color
paint.withCustomColor {
canvas.drawText(
order,
currentMarginLocation + gapWidth,
lineBaseline.toFloat(),
paint
)
// canvas.drawText(
// gapWidth + currentMarginLocation + paint.measureText(order).toInt(),
// lineTop.toFloat()
// bulletRadius,
// paint
// )
}
paint.color = oldColor
}
}
private inline fun Paint.withCustomColor(block: () -> Unit) {
val oldColor = color
color = orderColor
block()
color = oldColor
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3 Page Template</title>
<script type="text/javascript" src="./d3.js"></script>
<style type="text/css">
div.tooltip {
position: absolute;
text-align: center;
width: 250px;
height: 280px;
padding: 2px;
font: 12px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
div.legend {
position: absolute;
text-align: center;
width: 450px;
height: 100px;
padding: 2px;
font: 12px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
</style>
</head>
<body>
<script type="text/javascript">
//Width and height
var w = 1000;
var h = 1000;
//Define default path generator
//var path = d3.geo.path();
var projection = d3.geo.mercator()
.scale(8700)
.translate([-1550,980])
.precision(.1);
var path = d3.geo.path()
.projection(projection);
var div2=d3.select("body").append("div")
.attr("class","legend")
.style("opacity",1)
.style("left", "420px")
.style("top","60px")
.html('<br><em><strong>How to read this map:</strong></em><br><ul><li>States highlighted in purple are those for which DMF data exists</li><li>Hovering over the state will open a popup with the DMF data</li><li>Clicking the state will open the state DMF page</li></ul>')
var div=d3.select("body").append("div")
.attr("class","tooltip")
.style("opacity",0)
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var format = d3.time.format("%Y/%m/%d")
var fmt2= d3.time.format("%d-%b-%Y")
//Load in GeoJSON data
d3.json("./dmftest-simple.geojson", function(json) {
//Bind data and create one path per GeoJSON feature
svg.selectAll("path")
.data(json.features)
.enter()
.append("a")
.attr("xlink:href", function(d){return d.properties.LNK})
.attr("target","_blank")
.append("path")
.attr("d", path)
.style("stroke","black")
.attr("fill", function(d)
{
if (d.properties['DT_DMF_RUL']==null && d.properties['DT_DMF_NOT']==null ){
return "#666666"
}
else{
return "#8E5CB4"
}
})
.on("mouseover", function(d)
{
if (d.properties['DT_DMF_RUL']!==null || d.properties['DT_DMF_NOT']!==null) {
var dmfnotdate="NA"
var dmfruledate="NA"
if (d.properties['DT_DMF_NOT']!=null){
dmfnotdate=fmt2(format.parse(d.properties['DT_DMF_NOT']))
}
if (d.properties['DT_DMF_RUL']!=null){
dmfruledate=fmt2(format.parse(d.properties['DT_DMF_RUL']))
}
d3.select(this).attr("fill","#1E732D")
//Get this bar's x/y values, then augment for the tooltip
var xPosition = d3.mouse(this)[0];
var yPosition = d3.mouse(this)[1];
var xDiv=xPosition +50
var yDiv=yPosition+50
//Create the tooltip label
div.transition()
.duration(200)
.style("opacity", .9);
div.html("<center><h1>"+d.properties['ST_NM'] +"</h1></center><left>"
+"<br/><i>Date of DMF Notification: </i>"+dmfnotdate
+"<br/><i>Date of DMF Rules: </i>"+ dmfruledate
+"<br/><i>Total Districts: </i>"+d.properties['TOT_DISTS']
+"<br/><i>DMF Districts: </i>"+d.properties['NUM_DISTS']
+"<br/><i>Expected Royalty from Coal (INR) : </i>"+d.properties['RYLT_C']+" Cr"
+"<br/><i>Expected Royalty from Other Minerals (INR): </i>"+d.properties['RYLT_NC']+" Cr"
+"<br/><i>Actual Collection by DMF (INR): </i>"+d.properties['COLL_DMF'] +" Cr")
.style("left", + xDiv+ "px")
.style("top", yDiv +"px");
svg.append("line")
.attr("id","pointer")
.attr("x1", xDiv)
.attr("y1", yDiv)
.attr("x2", xPosition)
.attr("y2", yPosition)
.style("stroke", "black")
}
})
.on("mouseout", function() {
d3.select(this).attr("fill", function(d)
{
if (d.properties.DT_DMF_RUL===null && d.properties['DT_DMF_NOT']==null){
return "#666666"
}
else{
return "#8E5CB4"
}
})
//Remove the tooltip
d3.select("#tooltip").remove();
d3.select("#pointer").remove();
div.transition()
.duration(1500)
.style("opacity", 0);
});
});
</script>
</body>
</html> |
def is_pangram(s):
s = set(s.lower())
alphabet = [chr(i) for i in range(ord("a"), ord("z")+1)]
sentence = [i for i in s if i.isalpha()]
return len(alphabet) == len(sentence)
# Examples:
'''
"The quick, brown fox jumps over the lazy dog!"
=>
True
"1bcdefghijklmnopqrstuvwxyz"
=>
False
'''
# A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant).
# Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation. |
const btn = document.querySelector('.custom-button'); // btn is our "fake" button
let active = false;
btn.addEventListener('mouseover', () => {
// Add a class of "hover" to the button when the mouse is over it
btn.classList.add('hover');
if (active) {
// If the user's mouse comes back over the button while the mouse is **still** pressed down, add the "active" class
btn.classList.add('active');
}
});
btn.addEventListener('mouseout', () => {
btn.classList.remove('hover');
if (active) {
// If the user's mouse leaves the button while the mouse is pressed down, remove the "active" class
btn.classList.remove('active');
}
});
btn.addEventListener('mousedown', () => {
// Add a class of "active" to the button when the user presses the mouse down on it
btn.classList.add('active');
active = true;
});
window.addEventListener('mouseup', (event) => {
// If the user's mouse is released while it is over the button, "flash" the button by calling flashClicked(btn)
if (event.target === btn) { //event.target is where the event happened.
flashClicked(btn);
}
btn.classList.remove('active');
active = false;
})
/**
* Call this function when you want to "flash" the button --- when it is clicked
*
* @param {*} element The element that we want to "flash"
*/
function flashClicked(element) {
element.classList.add('clicked');
setTimeout(() => {
element.classList.remove('clicked');
}, 300);
}
// Give the "real" button a flash effect
const realButton = document.querySelector('button');
realButton.addEventListener('click', () => {
flashClicked(realButton);
}); |
import React, { useEffect, useRef, useState } from "react"
import { CopyToClipboard } from "react-copy-to-clipboard"
import Peer from "simple-peer" //WebRTC api
import io from "socket.io-client"
import {Button, Col, Container, FloatingLabel, Row,Form} from "react-bootstrap";
const socket = io.connect('http://localhost:5001')
const MeetComponent=()=>{
const [ me, setMe ] = useState("")
const [ stream, setStream ] = useState()
const [ receivingCall, setReceivingCall ] = useState(false)
const [ caller, setCaller ] = useState("")
const [ callerSignal, setCallerSignal ] = useState()
const [ callAccepted, setCallAccepted ] = useState(false)
const [ idToCall, setIdToCall ] = useState("")
const [ callEnded, setCallEnded] = useState(false)
const [ name, setName ] = useState("")
const myVideo = useRef()
const userVideo = useRef()
const connectionRef= useRef()
useEffect(() => {
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((stream) => {
setStream(stream)
myVideo.current.srcObject = stream
})
socket.on("me", (id) => {
setMe(id)
})
socket.on("callUser", (data) => {
setReceivingCall(true)
setCaller(data.from)
setName(data.name)
setCallerSignal(data.signal)
})
}, [])
const callUser = (id) => {
const peer = new Peer({
initiator: true,
trickle: false,
stream: stream
})
peer.on("signal", (data) => {
socket.emit("callUser", {
userToCall: id,
signalData: data,
from: me,
name: name
})
})
peer.on("stream", (stream) => {
userVideo.current.srcObject = stream
})
socket.on("callAccepted", (signal) => {
setCallAccepted(true)
peer.signal(signal)
})
connectionRef.current = peer
}
const answerCall =() => {
setCallAccepted(true)
const peer = new Peer({
initiator: false,
trickle: false,
stream: stream
})
peer.on("signal", (data) => {
socket.emit("answerCall", { signal: data, to: caller })
})
peer.on("stream", (stream) => {
userVideo.current.srcObject = stream
})
peer.signal(callerSignal)
connectionRef.current = peer
}
const leaveCall = () => {
setCallEnded(true)
connectionRef.current.destroy()
}
return(<>
<Container>
<Row>
<Col>
<div className="video">
{stream && <video playsInline muted ref={myVideo} autoPlay />}
</div>
</Col>
<Col>
<div className="video">
{callAccepted && !callEnded ?
<video playsInline ref={userVideo} autoPlay />:
null}
</div>
</Col>
</Row>
<Row className="d-inline text-center">
<Col>
<FloatingLabel controlId="floatingPassword" label="Enter Name">
<Form.Control type="text" value={name}
onChange={(e) => setName(e.target.value)} />
</FloatingLabel>
</Col>
<Col>
<CopyToClipboard text={me}>
<Button variant="dark" >
Copy ID
</Button>
</CopyToClipboard>
</Col>
<Col>
<FloatingLabel controlId="floatingPassword" label="Enter id to call">
<Form.Control type="text" value={idToCall}
onChange={(e) => setIdToCall(e.target.value)} />
</FloatingLabel>
</Col>
<Col>
{callAccepted && !callEnded ? (
<Button variant="dark" color="secondary" onClick={leaveCall}>
End Call
</Button>
) : (
<Button variant="dark" onClick={() => callUser(idToCall)}>
Dial
</Button>
)}
{idToCall}
{receivingCall && !callAccepted ? (
<div className="caller">
<h1 >{name} is calling...</h1>
<Button variant="dark" onClick={answerCall}>
Answer
</Button>
</div>
) : null}
</Col>
</Row>
</Container>
</>)
}
export default MeetComponent; |
package com.example.board20231.question;
import com.example.board20231.DataNotFoundException;
import com.example.board20231.answer.Answer;
import com.example.board20231.user.SiteUser;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@RequiredArgsConstructor
@Service
public class QuestionService {
private final QuestionRepository questionRepository;
private Specification<Question> search(String kw) {
return new Specification<>() {
private static final long serialVersionUID = 1L;
@Override
public Predicate toPredicate(Root<Question> q, CriteriaQuery<?> query, CriteriaBuilder cb) { //q : 질문제목,내용 검색하기위해
query.distinct(true); // 중복을 제거
Join<Question, SiteUser> u1 = q.join("author", JoinType.LEFT); //Question,SiteUser은 author로 연결되어있기 때문에 조인 -질문작성자 검색
Join<Question, Answer> a = q.join("answerList", JoinType.LEFT);
Join<Answer, SiteUser> u2 = a.join("author", JoinType.LEFT);
return cb.or(cb.like(q.get("subject"), "%" + kw + "%"), // 제목
cb.like(q.get("content"), "%" + kw + "%"), // 내용
cb.like(u1.get("username"), "%" + kw + "%"), // 질문 작성자
cb.like(a.get("content"), "%" + kw + "%"), // 답변 내용
cb.like(u2.get("username"), "%" + kw + "%")); // 답변 작성자
}
};
}
public List<Question> getList() {
return this.questionRepository.findAll();
}
public Question getQuestion(Integer id) {
Optional<Question> question = this.questionRepository.findById(id);
if (question.isPresent()) {
return question.get();
} else {
throw new DataNotFoundException("question not found");
}
}
public void create(String subject, String content, Question.Category category, SiteUser user){
Question q = new Question();
q.setSubject(subject);
q.setContent(content);
q.setCreateDate(LocalDateTime.now());
q.setCategory(category);
q.setAuthor(user);
this.questionRepository.save(q);
}
/*
Pageable 객체를 생성할때 사용한 pageRequest.of(page,10) 에서 page : 조회할 페이지의 번호, 10 : 한페이지에 보여줄 게시물의 갯수
*/
public Page<Question> getList(int page,String kw){
List<Sort.Order> sorts = new ArrayList<>();
sorts.add(Sort.Order.desc("createDate"));
Pageable pageable = PageRequest.of(page,10,Sort.by(sorts));
Specification<Question> spec = search(kw);
return this.questionRepository.findAll(spec, pageable);
}
public void modify(Question question, String subject, String content) {
question.setSubject(subject);
question.setContent(content);
question.setModifyData(LocalDateTime.now());
this.questionRepository.save(question);
}
public void delete(Question question){
this.questionRepository.delete(question);
}
public void vote(Question question, SiteUser siteUser) {
question.getVoter().add(siteUser);
this.questionRepository.save(question);
}
} |
const express = require("express");
const fs = require("fs");
const path = require("path");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
const PORT = 3000;
// Root route
app.get("/", (req, res) => {
// Read the content of the HTML file
const filePath = path.join(__dirname, "index.html");
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
console.error("Error reading HTML file:", err);
res.status(500).send("Internal Server Error");
} else {
res.status(200).send(data);
}
});
});
const employeeData = {
101: {
baseSalary: 6000,
},
102: {
baseSalary: 60000,
},
103: {
baseSalary: 5000,
},
104: {
baseSalary: 10000,
},
105: {
baseSalary: 50000,
},
106: {
baseSalary: 60000,
},
107: {
baseSalary: 40000,
},
108: {
baseSalary: 10000,
},
};
// Endpoint to get employee salary by ID
app.get("/getSalary/:employeeId", (req, res) => {
const employeeId = req.params.employeeId;
const employee = employeeData[employeeId];
if (employee) {
res.json({ baseSalary: employee.baseSalary });
} else {
res.status(404).json({ error: "Employee not found" });
}
});
app.use(express.static("public"));
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}/`);
}); |
import {Directive, ElementRef, Input} from '@angular/core';
import {Task, TaskStatus} from "../model/Task";
@Directive({
selector: '[appColorByStatus]'
})
export class ColorByStatusDirective {
@Input() appColorByStatus: TaskStatus = TaskStatus.DONE;
constructor(private el: ElementRef) {
}
ngOnInit() {
this.changeColor(this.appColorByStatus)
}
private changeColor(appColorChangeByState: TaskStatus) {
if (appColorChangeByState === TaskStatus.TODO) {
this.el.nativeElement.style.color = 'red'
} else if (appColorChangeByState === TaskStatus.IN_PROGRESS) {
this.el.nativeElement.style.color = 'yellow'
} else {
this.el.nativeElement.style.color = 'green'
}
}
} |
import * as React from "react";
import { styled } from "@mui/material/styles";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import StarRating from "../ProductDetails/StarRating";
const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: theme.palette.common.black,
color: theme.palette.common.white,
},
[`&.${tableCellClasses.body}`]: {
fontSize: 14,
},
}));
const StyledTableRow = styled(TableRow)(({ theme }) => ({
"&:nth-of-type(odd)": {
backgroundColor: theme.palette.action.hover,
},
// hide last border
"&:last-child td, &:last-child th": {
border: 0,
},
}));
export const Customers = (props) => {
console.log(props);
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 700 }} aria-label="customized table">
<TableHead>
<TableRow>
<StyledTableCell>Customer ID</StyledTableCell>
<StyledTableCell align="left">User Name</StyledTableCell>
<StyledTableCell align="left">Email</StyledTableCell>
{/* <StyledTableCell align="left">Action</StyledTableCell> */}
</TableRow>
</TableHead>
<TableBody>
{props.customers.users?.map((customer, key) => (
<StyledTableRow key={key}>
<StyledTableCell>{customer._id}</StyledTableCell>
<StyledTableCell align="left">{customer.name}</StyledTableCell>
<StyledTableCell align="left">{customer.email}</StyledTableCell>
{/* <StyledTableCell align="left">Delete</StyledTableCell> */}
{/* <StyledTableCell align="left"></StyledTableCell> */}
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}; |
import express from "express"
import { genPassword, createUser, getUserByName } from "../helper.js"
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken"
const router = express.Router()//express router
router.post('/register', async (req, res) => {
const { username, password } = req.body
console.log(username, password)
const isUserExist = await getUserByName(username)
console.log(isUserExist)
//username already exists
if (isUserExist) {
res.status(400).send({ message: "Username already exists" })
return;
}
if (!/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@!#$%_&]).{8,}$/g.test(password)) {
res.status(400).send({ message: "Password pattern does not match" })
return;
}
const hashedPassword = await genPassword(password)
const result = await createUser(username, hashedPassword)
res.send(result)
})
router.post('/login', async (req, res) => {
const { username, password } = req.body
console.log(username, password)
//validate username
const userFromDb = await getUserByName(username)
console.log(userFromDb)
// username already exists
if (!userFromDb) {
res.status(400).send({ message: "Invalid Credentials" })
return;
}
//password validate
const storedDbPassword = userFromDb.password;
const isPasswordMatch = await bcrypt.compare(password, storedDbPassword)
if (!isPasswordMatch) {
res.status(400).send({ message: "Invalid Credentials" })
return;
}
const token = jwt.sign({ id: userFromDb._id }, process.env.SECRET_KEY)
res.send({ message: "Successful Login", token: token })
})
export const usersRoute = router |
<!DOCTYPE html>
<html>
<head>
<title>Purtova A</title>
<meta charset="utf-8">
<meta name="description" content="Agency"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS Files -->
<link rel="stylesheet" href="css/style.css">
<!-- Media Queries -->
<link rel="stylesheet" href="css/media-queries.css">
<!-- Animation CSS -->
<link rel="stylesheet" type="text/css" href="css/animate.css">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans|Philosopher" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<header>
<nav>
<ul class="nav__list">
<li class="nav__item"><a href="#about">about me</a></li>
<li class="nav__item"><a href="#portfolio">portfolio</a></li>
<li class="nav__item"><a href="#contact">contacts</a></li>
</ul>
</nav>
<!-- header content -->
<div class='header__text animated wow fadeInDown'>
<h1>Frontend & Web Development</h1>
<p class='line'>HTML · CSS · JavaScript</p>
<ul class="header__list">
<li class="header__item"><a href="https://github.com/Corwira" target='blank'><i class="fa fa-github fa-2x" aria-hidden="true"></i></a></li>
<li class="header__item"><a href="http://codepen.io/corwira/#" target='blank'><i class="fa fa-codepen fa-2x" aria-hidden="true"></i></a></li>
<li class="header__item"><a href="https://vk.com/ambercreative" target='blank'><i class="fa fa-vk fa-2x" aria-hidden="true"></i></a></li>
</ul>
</div>
</header>
<!-- portfolio section -->
<main id='portfolio'>
<h2 class='portfolio__heading'>Works</h2>
<p class='d-line'><i class="fa fa-star-o" aria-hidden="true"></i>
</p>
<p class='portfolio__text'>Projects done in the curriculum of the FreeCodeCamp (JS, jQuery), and frontend website projects</p>
<div id="portfolio" class="portfolio__container">
<div class="portfolio__item animated wow fadeInLeft">
<div class="item__box">
<img src='img/agency-show.png'>
<div class='box__caption'>
<div class='box__content'>
<a href='https://corwira.github.io/Agency/' target='blank'>open project</a>
</div>
</div>
</div>
<h5>Agency</h5>
<h3>BEM, Flexbox, mobile responsive</h3>
</div>
<div class="portfolio__item animated wow fadeInUp">
<div class="item__box">
<img src='img/axit-show.png'>
<div class='box__caption'>
<div class='box__content'>
<a href='https://corwira.github.io/axit/' target='blank'>open project</a>
</div>
</div>
</div>
<h5>Axit</h5>
<h3>BEM, mobile responsive</h3>
</div>
<div class="portfolio__item animated wow fadeInRight">
<div class="item__box">
<img src='img/bandi-show.png'>
<div class='box__caption'>
<div class='box__content'>
<a href='https://corwira.github.io/bandi/' target='blank'>open project</a>
</div>
</div>
</div>
<h5>Bandi</h5>
<h3>Bootstrap3, mobile responsive</h3>
</div>
<div class="portfolio__item animated wow fadeInLeft">
<div class="item__box">
<img src='img/quote-show.png'>
<div class='box__caption'>
<div class='box__content'>
<a href='http://codepen.io/corwira/full/QEvvNj/' target='blank'>open project</a>
</div>
</div>
</div>
<h5>Random Quote Machine</h5>
<h3>jQuery</h3>
</div>
<div class="portfolio__item animated wow fadeInUp">
<div class="item__box">
<img src='img/twitch-show.png'>
<div class='box__caption'>
<div class='box__content'>
<a href='http://codepen.io/corwira/full/XKQomm/' target='blank'>open project</a>
</div>
</div>
</div>
<h5>Twitch.tv JSON API</h5>
<h3>Jade, jQuery, Twitch.tv API</h3>
</div>
<div class="portfolio__item animated wow fadeInRight">
<div class="item__box">
<img src='img/calculator-show.png'>
<div class='box__caption'>
<div class='box__content'>
<a href='http://codepen.io/corwira/full/NAOVdO/' target='blank'>open project</a>
</div>
</div>
</div>
<h5>JS Calculator</h5>
<h3>Vanilla JS</h3>
</div>
<div class="portfolio__item animated wow fadeInLeft">
<div class="item__box">
<img src='img/wikir-show.png'>
<div class='box__caption'>
<div class='box__content'>
<a href='http://codepen.io/corwira/full/kXQKrr/' target='blank'>open project</a>
</div>
</div>
</div>
<h5>Wikipedia Viewer</h5>
<h3>Wiki API, jQuery</h3>
</div>
<div class="portfolio__item animated wow fadeInUp">
<div class="item__box">
<img src='img/weather-show.png'>
<div class='box__caption'>
<div class='box__content'>
<a href='http://codepen.io/corwira/full/XKGrEZ/' target='blank'>open project</a>
</div>
</div>
</div>
<h5>Show the Local Weather</h5>
<h3>OpenWeather API, Jade, jQuery</h3>
</div>
<div class="portfolio__item animated wow fadeInRight">
<div class="item__box">
<img src='img/pomodoro-show.png'>
<div class='box__caption'>
<div class='box__content'>
<a href='http://codepen.io/corwira/full/yJWXxQ/' target='blank'>open project</a>
</div>
</div>
</div>
<h5>Pomodoro Clock</h5>
<h3>Jade, Sass, jQuery</h3>
</div>
</div>
</main>
<footer class="animated wow fadeInUp">
<div id='about' class='about'>
<div class="about__content">
<div class='about__photo'>
<img src='img/my_icon.jpg'>
</div>
<div class='about__text'>
<p>
Hi! My name is Purtova Anastasia and i'm frontend developer. I like frontend and development, curious about new technologies and interested in acquiring more skills.
</p>
<ul class='about__list'>
<li class="about__item"><i class="fa fa-envelope" aria-hidden="true"></i> annika-purtova@yandex.ru</li>
<li class="about__item"><i class="fa fa-skype" aria-hidden="true"></i> opaphirr</li>
</ul>
</div>
</div>
</div>
<div id="contact" class="contact">
<div class='contact__content'>
<ul class="contact__list">
<li class="list__item"><a href="https://github.com/Corwira" target='blank'><i class="fa fa-github fa-3x" aria-hidden="true"></i></a></li>
<li class="list__item"><a href="http://codepen.io/corwira/#" target='blank'><i class="fa fa-codepen fa-3x" aria-hidden="true"></i></a></li>
<li class="list__item"><a href="https://vk.com/ambercreative" target='blank'><i class="fa fa-vk fa-3x" aria-hidden="true"></i></a></li>
</ul>
<div class='contact__copyright'>
<p>© 2016 Purtova A. All Rights Reserved</p>
</div>
</div>
</div>
</footer>
<!---- scripts ---->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Animate JS -->
<script src=js/wow.js></script>
<!-- Plugin JavaScript -->
<script src="js/jquery.easing.min.js"></script>
<!-- Wow init -->
<script src="js/script.js"></script>
<!-- Font Awesome -->
<script src="https://use.fontawesome.com/0233c2734a.js"></script>
</body>
</html> |
// Copyright 2023 RISC Zero, Inc.
//
// 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.
use anyhow::{self, bail, ensure, Context, Ok};
use serde::{Deserialize, Serialize};
use zeth_primitives::{
b256, transactions::ethereum::EthereumTxEssence, Address, Bloom, BloomInput, B256, U256,
};
use super::batcher_db::BlockInput;
/// Signature of the deposit transaction event, i.e.
/// keccak-256 hash of "ConfigUpdate(uint256,uint8,bytes)"
const CONFIG_UPDATE_SIGNATURE: B256 =
b256!("1d2b0bda21d56b8bd12d4f94ebacffdfb35f5e226f84b461103bb8beab6353be");
/// Version of the deposit transaction event.
const CONFIG_UPDATE_VERSION: B256 = B256::ZERO;
/// Optimism system config contract values
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemConfig {
/// Batch sender address
pub batch_sender: Address,
/// L2 gas limit
pub gas_limit: U256,
/// Fee overhead
pub l1_fee_overhead: U256,
/// Fee scalar
pub l1_fee_scalar: U256,
/// Sequencer's signer for unsafe blocks
pub unsafe_block_signer: Address,
}
impl SystemConfig {
/// Updates the system config based on the given input. Returns whether the config was
/// updated.
pub fn update(
&mut self,
system_config_contract: &Address,
input: &BlockInput<EthereumTxEssence>,
) -> anyhow::Result<bool> {
let mut updated = false;
// if the bloom filter does not contain the corresponding topics, we have the guarantee
// that there are no config updates in the block
if !can_contain(system_config_contract, &input.block_header.logs_bloom) {
return Ok(updated);
}
#[cfg(not(target_os = "zkvm"))]
log::info!("Process config");
let receipts = input.receipts.as_ref().context("receipts missing")?;
for receipt in receipts {
let receipt = &receipt.payload;
// skip failed transactions
if !receipt.success {
continue;
}
for log in &receipt.logs {
// the log event contract address must match the system config contract
// the first log event topic must match the ConfigUpdate signature
if &log.address == system_config_contract
&& log.topics[0] == CONFIG_UPDATE_SIGNATURE
{
updated = true;
// the second topic determines the version
ensure!(log.topics[1] == CONFIG_UPDATE_VERSION, "invalid version");
// the third topic determines the type of update
let update_type: u64 = U256::from_be_bytes(log.topics[2].0)
.try_into()
.expect("invalid update type");
// TODO: use proper ABI decoding of the data
match update_type {
// type 0: batcherHash overwrite, as bytes32 payload
0 => {
let addr_bytes = log
.data
.get(76..96)
.context("invalid batch sender address")?;
self.batch_sender = Address::from_slice(addr_bytes);
}
// type 1: overhead and scalar overwrite, as two packed uint256 entries
1 => {
let fee_overhead = log.data.get(64..96).context("invalid data")?;
let fee_scalar = log.data.get(96..128).context("invalid data")?;
self.l1_fee_overhead = U256::try_from_be_slice(fee_overhead)
.context("invalid overhead")?;
self.l1_fee_scalar =
U256::try_from_be_slice(fee_scalar).context("invalid scalar")?;
}
// type 2: gasLimit overwrite, as uint64 payload
2 => {
let gas_limit = log.data.get(64..96).context("invalid data")?;
self.gas_limit =
U256::try_from_be_slice(gas_limit).context("invalid gas limit")?;
}
// type 3: unsafeBlockSigner overwrite, as address payload
3 => {
let addr_bytes = log
.data
.get(76..96)
.context("invalid unsafe block signer address")?;
self.unsafe_block_signer = Address::from_slice(addr_bytes);
}
_ => {
bail!("invalid update type");
}
}
}
}
}
Ok(updated)
}
}
/// Returns whether the given Bloom filter can contain a config update log.
pub fn can_contain(address: &Address, bloom: &Bloom) -> bool {
let input = BloomInput::Raw(address.as_slice());
if !bloom.contains_input(input) {
return false;
}
let input = BloomInput::Raw(CONFIG_UPDATE_SIGNATURE.as_slice());
if !bloom.contains_input(input) {
return false;
}
true
} |
---
share: true
---
## Find number of objects created
```java
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor
// instance block is preferred to make this program generic.
{
noOfObjects += 1;
}
// various types of constructors
// that can create objects
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("GFG");
// We can also write t1.noOfObjects or
// t2.noOfObjects or t3.noOfObjects
System.out.println(Test.noOfObjects);
}
}
```
## Real life applications
1. **Vehicles and Transportation:** The concept of inheritance is seen in vehicle classes. For instance, the hierarchy of vehicles might include a base class "Vehicle," subclasses like "Car," "Motorcycle," and "Truck," which inherit common properties and behaviors from the base class.
2. **Online Shopping:** In e-commerce platforms, items like "Product," "Electronics," "Clothing," etc., can be represented as classes. The concept of encapsulation is applied by hiding the internal details of these classes and exposing only the necessary methods like "getPrice()" and "addToCart()".
3. **Banking System:** In a banking application, customers can be represented as objects of a "Customer" class. Each customer object may have attributes like name, account balance, and methods like "deposit" and "withdraw".
4. **Social Media:** Social media platforms use classes like "User" to represent individuals. These user objects have attributes such as name, age, and methods to interact with the platform, like "postStatus" or "addFriend".
5. **Video Games:** In game development, OOP is used extensively. For instance, a game might have classes for "Player," "Enemy," and "Weapon." These classes encapsulate properties and behaviors specific to their roles.
6. **Cooking:** In cooking, you can think of a "Recipe" class that contains attributes like ingredients and methods like "prepare" and "cook". Inheritance can be applied when you have different types of recipes, like "Dessert" or "Main Course."
7. **Smartphones:** The design of smartphone applications heavily involves OOP concepts. Apps can be modeled as classes, with attributes like "name" and "version," and methods to perform actions like "open" or "update."
8. **Home Automation:** Home automation systems can be modeled using OOP concepts. Each device, like "Light," "Thermostat," or "Smart Plug," can be represented as classes with their unique attributes and methods.
9. **Medical Records:** In healthcare, OOP can be used to model patient records. The "Patient" class can have attributes like name, age, medical history, and methods to schedule appointments or request prescriptions.
10. **Education Systems:** Education platforms can use OOP to represent courses, students, and instructors. The "Course" class can have attributes like name, duration, and methods to enroll students and assign instructors.
## Inheritance Example
```java
class Vehicle {
private String make;
private String model;
private int year;
public Vehicle(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public void displayInfo() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
class Car extends Vehicle {
private int seatingCapacity;
public Car(String make, String model, int year, int seatingCapacity) {
super(make, model, year);
this.seatingCapacity = seatingCapacity;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Seating Capacity: " + seatingCapacity);
}
}
class Motorcycle extends Vehicle {
private boolean hasSideCar;
public Motorcycle(String make, String model, int year, boolean hasSideCar) {
super(make, model, year);
this.hasSideCar = hasSideCar;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Has Side Car: " + hasSideCar);
}
}
class Truck extends Vehicle {
private double loadCapacity;
public Truck(String make, String model, int year, double loadCapacity) {
super(make, model, year);
this.loadCapacity = loadCapacity;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Load Capacity: " + loadCapacity);
}
}
public class TransportationDemo {
public static void main(String[] args) {
Car car = new Car("Toyota", "Camry", 2022, 5);
Motorcycle motorcycle = new Motorcycle("Harley-Davidson", "Street Glide", 2021, false);
Truck truck = new Truck("Ford", "F-150", 2020, 1500.0);
System.out.println("Car Information:");
car.displayInfo();
System.out.println();
System.out.println("Motorcycle Information:");
motorcycle.displayInfo();
System.out.println();
System.out.println("Truck Information:");
truck.displayInfo();
System.out.println();
}
}
```
---
**Composition in Java:**
Composition is a design principle in object-oriented programming where a class is composed of one or more objects of other classes. It represents a "has-a" relationship, where a class contains instances of other classes as its members. Composition allows for building complex objects by combining smaller, reusable components.
In composition, the components are often created and managed by the containing class. This provides better encapsulation, as the contained objects are not directly accessible from outside the class, and changes to the implementation of the contained objects do not affect the interface of the containing class.
Here's an example of composition in Java:
```java
class Engine {
void start() {
System.out.println("Engine started");
}
}
class Car {
private Engine engine;
public Car() {
engine = new Engine();
}
void startCar() {
engine.start();
System.out.println("Car started");
}
}
public class CompositionExample {
public static void main(String[] args) {
Car car = new Car();
car.startCar();
}
}
```
In this example, the `Car` class is composed of an `Engine` object. The `Car` class uses composition to encapsulate the functionality of the `Engine` class, allowing the car to start by using its engine.
**Composition vs Inheritance:**
Composition and inheritance are two different ways to achieve code reuse and build relationships between classes:
1. **Composition:**
- Composition represents a "has-a" relationship.
- Allows you to create complex objects by combining smaller components.
- Provides better encapsulation and flexibility, as changes to the components don't affect the containing class's interface.
- Tends to result in more loosely coupled and maintainable code.
- Useful when there is no clear hierarchical relationship between classes.
2. **Inheritance:**
- Inheritance represents an "is-a" relationship.
- Involves creating a new class (subclass) by inheriting properties and behaviors from an existing class (superclass).
- Can lead to tight coupling and issues with maintenance, as changes to the superclass can affect all subclasses.
- Often used when there's a clear hierarchical relationship and shared behaviors between classes.
In general, composition is preferred over inheritance due to its better encapsulation and flexibility. However, the choice between composition and inheritance depends on the specific design requirements and relationships between classes.
---
## Stack Implementation
```java
class Stack {
private int maxSize;
private int[] stackArray;
private int top;
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (top < maxSize - 1) {
stackArray[++top] = value;
System.out.println("Pushed: " + value);
} else {
System.out.println("Stack is full. Cannot push: " + value);
}
}
public int pop() {
if (top >= 0) {
int poppedValue = stackArray[top--];
System.out.println("Popped: " + poppedValue);
return poppedValue;
} else {
System.out.println("Stack is empty. Cannot pop.");
return -1; // Return a sentinel value
}
}
public int peek() {
if (top >= 0) {
System.out.println("Peeked: " + stackArray[top]);
return stackArray[top];
} else {
System.out.println("Stack is empty. Cannot peek.");
return -1; // Return a sentinel value
}
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
}
public class StackExample {
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.push(30);
stack.pop();
stack.peek();
System.out.println("Is stack empty? " + stack.isEmpty());
System.out.println("Is stack full? " + stack.isFull());
}
}
```
---
## Implement Queue
```java
class Queue {
private int maxSize;
private int[] queueArray;
private int front;
private int rear;
private int currentSize;
public Queue(int size) {
maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1;
currentSize = 0;
}
public void enqueue(int value) {
if (currentSize < maxSize) {
rear = (rear + 1) % maxSize;
queueArray[rear] = value;
currentSize++;
System.out.println("Enqueued: " + value);
} else {
System.out.println("Queue is full. Cannot enqueue: " + value);
}
}
public int dequeue() {
if (currentSize > 0) {
int dequeuedValue = queueArray[front];
front = (front + 1) % maxSize;
currentSize--;
System.out.println("Dequeued: " + dequeuedValue);
return dequeuedValue;
} else {
System.out.println("Queue is empty. Cannot dequeue.");
return -1; // Return a sentinel value
}
}
public int peek() {
if (currentSize > 0) {
System.out.println("Front value: " + queueArray[front]);
return queueArray[front];
} else {
System.out.println("Queue is empty. Cannot peek.");
return -1; // Return a sentinel value
}
}
public boolean isEmpty() {
return currentSize == 0;
}
public boolean isFull() {
return currentSize == maxSize;
}
}
public class QueueExample {
public static void main(String[] args) {
Queue queue = new Queue(5);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.dequeue();
queue.peek();
System.out.println("Is queue empty? " + queue.isEmpty());
System.out.println("Is queue full? " + queue.isFull());
}
}
``` |
"""website URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path
from .views import DeleteBlogView, HomeView, BlogDetailView, AddBlogView, UpdateBlogView, LikeView, AddCommentView
urlpatterns = [
path('', HomeView.as_view(), name="home"),
path('blog/<int:pk>', BlogDetailView.as_view(), name="blog-details"),
path('add_post/', AddBlogView.as_view(), name="add_post"),
path('post/<int:pk>/comment ', AddCommentView.as_view(), name="add_comment"),
path('post/edit/<int:pk>', UpdateBlogView.as_view(), name="update_post"),
path('post/delete/<int:pk>', DeleteBlogView.as_view(), name="delete_post"),
path('like/<int:pk>', LikeView, name='like_post'),
] |
import 'dart:convert';
import 'package:http/http.dart' as http;
class GdgApi {
// api call to check backend status
static Future<Map<String, dynamic>> checkBackendStatus() async {
final url = Uri.parse('https://gdgapp.swoyam.engineer/');
final response = await http.get(url);
if (response.statusCode == 200) {
//parse response into map
Map<String, dynamic> result = jsonDecode(response.body);
return result;
} else {
return {'status': false};
}
}
// api call to get all sites
static Future<Map<String, dynamic>> getAllSites() async {
final url = Uri.parse('https://gdgapp.swoyam.engineer/sites/list/');
final response = await http.get(url);
if (response.statusCode == 200) {
//parse response into map
Map<String, dynamic> result = jsonDecode(response.body);
return result;
} else {
return {'status': false};
}
}
// api call to get all sites
static Future<Map<String, dynamic>> getAllNotifications() async {
final url = Uri.parse('https://gdgapp.swoyam.engineer/notification/list');
final response = await http.get(url);
if (response.statusCode == 200) {
//parse response into map
Map<String, dynamic> result = jsonDecode(response.body);
return result;
} else {
return {'status': false};
}
}
} |
import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
export default function Navbar(props) {
return (
<nav className={`navbar navbar-expand-lg navbar-${props.mode} bg-${props.mode}`}>
<div className="container-fluid">
<Link className="navbar-brand" to="/">{props.title}</Link>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav">
<li className="nav-item">
<Link className="nav-link active" aria-current="page" href="/">{props.Home}</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/about">{props.About}</Link>
</li>
</ul>
</div>
</div>
<div className="d-flex">
<div className="bg-primary rounded mx-2" onClick={()=>{props.toggleMode('primary')}} style={{height:'30px', width:'30px', cursor: 'pointer'}}></div>
<div className="bg-danger rounded mx-2" onClick={()=>{props.toggleMode('danger')}} style={{height:'30px', width:'30px', cursor: 'pointer'}}></div>
<div className="bg-success rounded mx-2" onClick={()=>{props.toggleMode('success')}} style={{height:'30px', width:'30px', cursor: 'pointer'}}></div>
<div className="bg-light rounded mx-2" onClick={()=>{props.toggleMode('light')}} style={{height:'30px', width:'30px', cursor: 'pointer'}}></div>
<div className="bg-dark rounded mx-2" onClick={()=>{props.toggleMode('dark')}} style={{height:'30px', width:'30px', cursor: 'pointer'}}></div>
</div>
<form className="d-flex" role="search">
<input className="form-control me-2" type="search" placeholder="Search" aria-label="Search"/>
<button className="btn btn-outline-success" type="submit">Search</button>
</form>
</nav>
)
}
Navbar.propTypes={
title:PropTypes.string,
About:PropTypes.string,
} |
import express from 'express';
import cors from 'cors';
import {
createPost,
deletePost,
getPosts,
updatePost,
} from './controllers/posts.js';
import {
changePwd,
loginUser,
registerUser,
resetPassword,
setPwd,
} from './controllers/users.js';
import { authValidator } from './validations/authVerify.js';
import {
userLoginValidation,
userRegistrationValidation,
} from './validations/userValidators.js';
import handleValidatorErrors from './validations/handleValidatorErrors.js';
import { postCreateValidation } from './validations/postValidators.js';
const app = express();
const PORT = 8080;
//Middleware для автоматического разбора JSON в запросах
app.use(express.json());
app.use(
cors({
origin: '*',
})
);
app.post(
'/register',
userRegistrationValidation,
handleValidatorErrors,
registerUser
);
app.post('/login', userLoginValidation, handleValidatorErrors, loginUser);
//Reset password
app.post('/reset-pwd', resetPassword);
app.patch('/set-pwd/:token', setPwd);
//Change password
app.patch('/change-pwd', authValidator, changePwd);
//Маршрут для получения ВСЕХ постов (GET)
app.get('/posts', getPosts);
//Маршрут для создания нового поста (POST)
app.post(
'/posts',
authValidator,
postCreateValidation,
handleValidatorErrors,
createPost
);
//Маршрут для обновления сеществующего поста (PATCH)
app.patch('/posts/:postId', updatePost);
//Марщрут для удаления поста
app.delete('/posts/:postId', authValidator, deletePost);
app.listen(PORT, () => {
console.log(`Сервер запущен на порту ${PORT}`);
}); |
import { List as DefaultList, Widget, ListItem as DefaultListItem } from "rayous";
import { Controller, mergeOptions, options } from "rayous/extra";
import { createClass } from "../utils/class";
import { mergeClassnameWithOptions } from "../utils/cssClass";
export interface ListItemOptions extends options {
media?: Widget;
inner?: Widget;
title?: Widget | string;
after?: Widget | string;
header?: Widget | string;
subtitle?: Widget | string;
content?: Widget | string;
url?: string;
titleRow?: boolean;
link?: boolean
}
type items = Controller<any[]> | any[]
export interface ListOptions extends options {
itemsStateName?: string,
template?: (item?: any, index?: number, array?: any[]) => Widget,
items?: items | Promise<items>,
empty?: boolean,
inset?: boolean,
strong?: boolean,
outline?: boolean,
dividers?: boolean,
}
class ListItemItem extends Widget {}
export const ListItemContainer = createClass('item-content', ListItemItem);
export const ListItemContainerLink = createClass('item-link item-content', ListItemItem, 'a');
export const ListItemMedia = createClass('item-media', ListItemItem);
export const ListItemInner = createClass('item-inner', ListItemItem);
export const ListItemInnerTitle = createClass('item-title', ListItemItem);
export const ListItemInnerTitleHeader = createClass('item-header', ListItemItem);
export const ListItemInnerAfter = createClass('item-after', ListItemItem);
export const ListItemAfter = createClass('item-after', ListItemItem);
export const ListItemSubtitle = createClass('item-subtitle', ListItemItem);
export const ListItemText = createClass('item-text', ListItemItem);
export const ListItemTitleRow = createClass('item-title-row', ListItemItem);
export class ListItem extends Widget<ListItemOptions> {
constructor(options: ListItemOptions){
super(mergeOptions({
element: { name: 'li' },
init: options,
_setters: ['init', 'url', 'inner', 'media', 'title', 'header', 'after', 'subtitle', 'content', 'titleRow']
}, options));
}
find(q: string, subchild?: string): Widget {
if(q == '.item-content' && this.options.selfContain){
return this;
} else {
return super.find(q, subchild);
}
}
set init(options: ListItemOptions){
let container = new ListItemContainer as Widget;
if(options.link) container = new ListItemContainerLink as Widget;
if(options.selfContain == true){
super.addClass('item-content');
} else {
super.add(container);
}
}
set url(url: string){
if(this.options.link == true){
this.find('a')?.attr({ href: url });
}
}
set media(media: Widget){
if(!super.find('.item-media')) this.find('.item-content').addBefore(new ListItemMedia as Widget);
super.find('.item-media').add(media);
}
/**
* Do not use unless making custom list items!
*/
set inner(inner: Widget){
if(!super.find('.item-inner')) this.find('.item-content').add(new ListItemInner as Widget);
super.find('.item-inner').add(inner);
}
set title(title: string | Widget){
if(!super.find('.item-inner')) this.find('.item-content').add(new ListItemInner as Widget);
if(!super.find('.item-title')) this.find('.item-content')
.find('.item-inner').add(new ListItemInnerTitle as Widget);
if(typeof title == "string"){
super.find('.item-title').text(title);
} else {
super.find('.item-title').add(title);
}
}
set header(title: string | Widget){
if(!super.find('.item-inner')) this.find('.item-content').add(new ListItemInner({
children: [ new ListItemInnerTitle ]
}) as Widget);
if(!super.find('.item-header')) super.find('.item-inner').find('.item-title').add(new ListItemInnerTitleHeader as Widget);
if(typeof title == "string"){
super.find('.item-header').text(title);
} else {
super.find('.item-header').add(title);
}
}
set after(title: string | Widget){
if(!super.find('.item-inner')) this.find('.item-content').add(new ListItemInner({
children: [ new ListItemInnerTitle ]
}) as Widget);
if(!super.find('.item-after')) this.find('.item-content').find('.item-inner').add(new ListItemInnerAfter as Widget);
if(typeof title == "string"){
super.find('.item-after').text(title);
} else {
super.find('.item-after').add(title);
}
}
set subtitle(title: string | Widget){
if(!super.find('.item-inner')) this.find('.item-content').add(new ListItemInner({
children: [ new ListItemInnerTitle ]
}) as Widget);
if(!super.find('.item-subtitle')) super.find('.item-inner').add(new ListItemSubtitle as Widget);
if(typeof title == "string"){
super.find('.item-subtitle').text(title);
} else {
super.find('.item-subtitle').add(title);
}
}
set content(title: string | Widget){
if(!super.find('.item-inner')) this.find('.item-content').add(new ListItemInner({
children: [ new ListItemInnerTitle ]
}) as Widget);
if(!super.find('.item-text')) super.find('.item-inner').add(new ListItemText as Widget);
if(typeof title == "string"){
super.find('.item-text').text(title);
} else {
super.find('.item-text').add(title);
}
}
set titleRow(rowEnabled: boolean){
if(rowEnabled){
let row = new ListItemTitleRow as Widget;
if(!super.find('.item-title-row')) this.find('.item-inner').addBefore(row);
row.add(super.find('.item-title'));
if(super.find('.item-after')) row.add(super.find('.item-after'));
}
}
}
export class List extends Widget {
constructor(options: ListOptions){
super(mergeOptions({
class: mergeClassnameWithOptions('list', options,
[
['inset', 'inset'],
['outline', 'list-outline'],
['strong', 'list-strong'],
['dividers', 'list-dividers']
]),
children: [
new DefaultList({
items: options.items || [],
itemsStateName: options.itemsStateName || '$items_list',
template: options.template || ((item: any) => new ListItem(item)),
empty: 'empty' in options ? options.empty : true
})
]
}, options));
}
appendItem(item: any, index: number){
this.find('ul').add((this.find('ul') as DefaultList)._fromTemplate(item, index))
return this;
}
onItems(event: string, handler: CallableFunction): this {
(this.find('ul') as DefaultList).onItems(event, handler)
return this;
}
empty(){
this.find('ul').raw().empty();
return this;
}
updateList(newOptions: ListOptions){
let list = this.find('ul') as DefaultList;
list.updateList(newOptions);
}
addItem(item: any){
(this.find('ul') as DefaultList).addItem(item);
return this;
}
removeItems(...items: any[]){
(this.find('ul') as DefaultList).removeItems(...items);
return this;
}
} |
import React from "react";
import { Button } from "../../../shared/styled/button";
import { FlexContainerCol } from "../../../shared/styled/FlexContainerCol";
import { H1, H3, H6 } from "../../../shared/styled/Headers";
import { Img } from "../../../shared/styled/Img";
function APODDisplay({
explanation,
link,
title,
isFavorite,
removeFavorite,
date,
addFavorite,
id,
}) {
return (
<div key={id}>
<H1>Astronomy Picture of the Day</H1>
<H3>{title}</H3>
<FlexContainerCol>
<Img src={link} />
<p>{explanation}</p>
{isFavorite && (
<Button onClick={() => removeFavorite(title)}>
Remove from favorites
</Button>
)}
{!isFavorite && (
<Button
onClick={() => addFavorite({ explanation, title, link, date, id })}
>
Add to favorites
</Button>
)}
</FlexContainerCol>
</div>
);
}
export default APODDisplay; |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p1 = l1, *p2 = l2, *ans = nullptr, *cur = ans;
int carry = 0;
ListNode *temp1 = new ListNode((carry + p1->val + p2->val) % 10);
carry = (carry + p1->val + p2->val) / 10;
p1 = p1->next;
p2 = p2->next;
ans = temp1;
cur = ans;
while (p1 || p2) {
ListNode *temp;
if (p1 && !p2) {
temp = new ListNode((carry + p1->val) % 10);
carry = (carry + p1->val) / 10;
p1 = p1->next;
cur->next = temp;
cur = cur->next;
cur->next = nullptr;
}
else if (!p1 && p2) {
temp = new ListNode((carry + p2->val) % 10);
carry = (carry + p2->val) / 10;
p2 = p2->next;
cur->next = temp;
cur = cur->next;
cur->next = nullptr;
}
else {
temp = new ListNode((carry + p1->val + p2->val) % 10);
carry = (carry + p1->val + p2->val) / 10;
p1 = p1->next;
p2 = p2->next;
cur->next = temp;
cur = cur->next;
cur->next = nullptr;
}
}
if (carry) {
temp1 = new ListNode(1);
cur->next = temp1;
cur->next->next = nullptr;
}
return ans;
}
};
小技巧:对于链表问题,返回结果为头结点时,通常需要先初始化一个预先指针 pre,该指针的下一个节点指向真正的头结点 head。使用预先指针的目的在于链表初始化时无可用节点值,而且链表构造过程需要指针移动,进而会导致头指针丢失,无法返回结果。
作者:画手大鹏
链接:https://leetcode.cn/problems/add-two-numbers/solutions/7348/hua-jie-suan-fa-2-liang-shu-xiang-jia-by-guanpengc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(0);
ListNode *cur = dummy;
ListNode *p1 = l1, *p2 = l2;
int carry = 0;
while (p1 || p2) {
int x = p1 ? p1->val : 0;
int y = p2 ? p2->val : 0;
int sum = x + y + carry;
int result = sum % 10;
carry = sum / 10;
ListNode *temp = new ListNode(result);
cur->next = temp;
cur = cur->next;
cur->next = nullptr;
if (p1) {
p1 = p1->next;
}
if (p2) {
p2 = p2->next;
}
}
if (carry) {
ListNode *temp = new ListNode(1);
cur->next = temp;
cur->next->next = nullptr;
}
return dummy->next;
}
}; |
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Pool } from 'pg';
import * as schema from './schema';
import { drizzle, NodePgDatabase } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { companies, insertItemSchema, items, users } from './schema';
import * as bcrypt from 'bcrypt';
import { generateCompany, generateItem } from './generator';
import { z } from 'nestjs-zod/z';
export type DrizzleType = NodePgDatabase<typeof schema>;
export const PG_CONNECTION = Symbol('PG_CONNECTION');
@Module({
providers: [
{
provide: PG_CONNECTION,
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
const connectionString = configService.get<string>('DATABASE_URL');
const pool = new Pool({
connectionString,
ssl: false,
});
const db: DrizzleType = drizzle(pool, { schema });
await migrate(db, { migrationsFolder: 'migrations' });
// flag for unseeded database
const firstUser = await db.query.users.findFirst();
if (!firstUser) {
await db.insert(users).values({
name: 'Akbar Maulana Ridho',
username: 'admin',
password: await bcrypt.hash('password', 10),
});
const companiesSeed = await db
.insert(companies)
.values([generateCompany(), generateCompany(), generateCompany()])
.returning();
for (const companySeed of companiesSeed) {
const seededitems: z.infer<typeof insertItemSchema>[] = [];
for (let i = 0; i < 10; i++) {
seededitems.push(generateItem(companySeed.id));
}
await db.insert(items).values(seededitems);
}
}
return db;
},
},
],
exports: [PG_CONNECTION],
})
export class DrizzleModule {} |
# Object
모든 클래스의 최상위(root) 클래스 모든 클래스는 object 클래스를 상속 받는다.
왜 object 클래스를 상속 받을까?
가장 큰 이유는 Object 클래스에 있는 메소드를 통해서 클래스의 기본적인 행동을 정의할 수 있기 때문이다. 클래스라면 이정도의 메소드는 정의되어 있어야 하고, 처리해 주어야 한다는 것. 그 기본이 Object 이기 때문에 Object를 상속받는다.
이건 무엇을 의미하는가? 모든 클래스는 Object 참조변수로 생성할 수 있다는 뜻!
[Java Development Kit Version 20 API Specification](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Object.html)
Object의 equals 메소드를 내맘대로 재정의 해보자
아래의 Object 클래스에 선언되어있는 equals 메소드이다. 두 객체가 서로 같은 주소를 가리키는지 판단하여 boolean 값을 반환한다.
```java
public boolean equals(Object obj) {
return (this == obj);
}
```
두 객체가 가리키는 주소는 다르지만 임의의 기준 값이 같다면 논리적으로 같은 객체다 라고 반환해주는 메소드를 선언하고 싶다.
번호와 이름을 멤버로 가지는 Student 객체가 있다.
```java
class Student {
private int number;
private String name;
Student(int number, String name) {
this.number = number;
this.name = name;
}
}
```
세 개의 Student 객체는 모두 다른 인스턴스의 주소를 가리킨다.
```java
public static void main(String[] args) {
Student student1 = new Student(1, "아이언맨");
Student student2 = new Student(1, "아이언맨");
Student student3 = new Student(2, "스파이더맨");
System.out.println(student1.equals(student2)); // false
System.out.println(student1.equals(student3)); // false
}
```
하지만 나는 number 가 같다면 논리적으로 같은 학생이다 라고 정의해주고 싶다. equals 함수를 재정의 해보자. 파라미터로 넘어온 객체가 Student 객체에 속하고 학생 번호가 같다면 true를 반환 하도록 재정의 했다.
```java
@Override
public boolean equals(Object obj) {
return (obj instanceof Student)
&& (Objects.equals(this.number, ((Student)obj).number));
}
```
```java
public static void main(String[] args) {
Student student1 = new Student(1, "아이언맨");
Student student2 = new Student(1, "아이언맨");
Student student3 = new Student(2, "스파이더맨");
System.out.println(student1.equals(student2)); // true
System.out.println(student1.equals(student3)); // false
}
```
이제 equal 메소드는 내가 원하는 대로 동작하게 되었다.
## equals() 메서드
- 두 인스턴스의 주소 값을 비교하여 true/false를 반환
- 재정의 하여 두 인스턴스가 논리적으로 동일함의 여부를 구현함
- 인스턴스가 다르더라도 논리적으로 동일한 경우 true를 반환하도록 재정의 할 수 있음
(같은 학번, 같은 사번, 같은 아이디의 회원...)
## hashCode() 메서드
- hashCode()는 인스턴스의 저장 주소를 반환함
- 힙메모리에 인스턴스가 저장되는 방식이 hash 방식
- hash : 정보를 저장, 검색하는 자료구조
- 자료의 특정 값(키 값)에 대한 저장 위치를 반환해주는 해시 함수를 사용
- 두 인스턴스가 같다는 것은?
두 인스턴스에 대한 equals()의 반환 값이 true
동일한 hashCode() 값을 반환
- 논리적으로 동일함을 위해 equals() 메서드를 재정의 하였다면 hashCode()메서드도 재정의 하여 동일한 hashCode 값이 반환되도록 한다
## clone() 메서드
- 객체의 원본을 복제하는데 사용하는 메서드
- 생성과정의 복잡한 과정을 반복하지 않고 복제 할 수 있음
- clone()메서드를 사용하면 객체의 정보(멤버 변수 값등...)가 동일한 또 다른 인스턴스가 생성되는 것이므로, 객체 지향 프로그램에서의 정보 은닉, 객체 보호의 관점에서 위배될 수 있음
- 해당 클래스의 clone() 메서드의 사용을 허용한다는 의미로 cloneable 인터페이스를 명시해 줌 |
// Copyright (c) Corporation for National Research Initiatives
// These are just like normal instances, except that their classes included
// a definition for __del__(), i.e. Python's finalizer. These two instance
// types have to be separated due to Java performance issues.
package org.python.core;
/**
* A python class instance with __del__ defined.
* <p>
* This is a special class due to performance. Defining
* finalize() on a class, makes the class a lot slower.
*/
public class PyFinalizableInstance extends PyInstance {
public PyFinalizableInstance(PyClass iclass) {
super(iclass);
}
// __del__ method is invoked upon object finalization.
@Override
protected void finalize() {
try {
instclass.__del__.__call__(this);
} catch (PyException exc) {
// Try to get the right method description.
PyObject method = instclass.__del__;
try {
method = __findattr__("__del__");
} catch (PyException e) {
// nothing we can do
}
Py.writeUnraisable(exc, method);
}
}
} |
<!-- The following are the few refferece websites from where the help was taken to buit the Milestone2_Navigations
1) https://www.youtube.com/channel/UC7pVho4O31FyfQsZdXWejEw
2) https://www.w3schools.com/howto/howto_js_topnav.asp
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Milestone2_Navigations</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>
<link href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600" rel="stylesheet">
</head>
<body>
<nav>
<div>
<i class="fa fa-bars"></i>
</div>
<ul>
<li><a href="#">About Us<i class="fa fa-sort-desc"></i></a>
<ul>
<a href="#">Missions & Visions Statement</a>
<a href="#">Structure</a>
<a href="#">Current Vacant Positions</a>
<a href="#">History</a>
<a href="#">Founding Members</a>
</ul>
</li>
<li><a href="#">Contact Us <i class="fa fa-sort-desc"></i></a>
</li>
<li><a href="#">Employment <i class="fa fa-sort-desc"></i></a>
<ul>
<a href="#">Donations</a>
<a href="#">Funding</a>
<a href="#">Working for Tangentyere</a>
<a href="#">How to Apply</a>
<a href="#">Selection Process </a>
</ul>
</li>
<li><a href="#">Publications<i class="fa fa-sort-desc"></i></a>
<ul>
<a href="#">Office of Director</a>
</ul>
</li>
<li><a href="#">Enterprises<i class="fa fa-sort-desc"></i></a>
<ul>
<a href="#">Governance</a>
<a href="#">Tangentyere Design</a>
<a href="#">Tangentyere Artists</a>
<a href="#">Tangentyere Constitution</a>
</ul>
</li>
<li><a href="#">Services<i class="fa fa-sort-desc"></i></a>
<ul>
<a href="#">Tangentyere Employment Services</a>
<a href="#">Family & youth Services</a>
<a href="#">Housing Services</a>
</ul>
</li>
<li><a href="#">Links<i class="fa fa-sort-desc"></i></a>
</li>
</nav>
<script type="text/javascript">
$("nav div").click(function() {
$("ul").slideToggle();
$("ul ul").css("display", "none");
});
$("ul li").click(function() {
$("ul ul").slideUp();
$(this).find('ul').slideToggle();
});
$(window).resize(function() {
if($(window).width() > 768) {
$("ul").removeAttr('style');
}
});
</script>
</body>
</html> |
import { match } from 'ts-pattern';
import { describe, expect, it, vi } from 'vitest';
import { VoiceClient } from './client';
import { defaultConfig } from './create-socket-config';
import { flushPromises } from '@/test-utils/flushPromises';
vi.mock('./message', () => {
return {
parseMessageType: vi.fn().mockResolvedValue({ success: false }),
};
});
describe('client', () => {
it('to start closed', () => {
const client = VoiceClient.create({
auth: {
type: 'apiKey',
value: 'test',
},
...defaultConfig,
});
client.on('message', (message) => {
match(message.type)
.with('audio', () => {
console.log('audio message');
})
.with('audio_output', () => {
console.log('audio json message');
})
.with('assistant_message', () => {
console.log('voice message');
})
.with('user_message', () => {
console.log('user message');
})
.with('assistant_end', () => {
console.log('voice end');
})
.with('user_interruption', () => {
console.log('user interruption');
})
.with('error', () => {
console.log('error');
})
.with('tool_call', () => {
console.log('tool call');
})
.with('tool_response', () => {
console.log('tool response');
})
.with('tool_error', () => {
console.log('tool error');
})
.exhaustive();
});
expect(client.readyState).toBe(3);
});
it('should not call the message event handler if parseMessageType returns a failure', async () => {
const client = VoiceClient.create({
...defaultConfig,
auth: {
type: 'apiKey',
value: 'test',
},
});
const messageHandler = vi.fn();
client.on('message', messageHandler);
const testEvent = new MessageEvent('message', {
data: JSON.stringify({ type: 'test_message', payload: 'test' }),
});
client.handleMessage(testEvent);
await flushPromises();
expect(messageHandler).not.toHaveBeenCalled();
});
}); |
from turtle import Turtle
class Score(Turtle):
def __init__(self):
super().__init__()
self.score = 0
self.color('red')
self.penup()
self.goto(0, 265)
self.hideturtle()
self.update_score()
def increment_score(self):
self.score += 1
self.update_score()
def update_score(self):
self.clear()
self.write(f"Score: {self.score}", align="center", font=("Arial", 20, "bold"))
def game_over(self):
self.goto(0, 0)
self.write("GAME OVER!", align="center", font=("Arial", 20, "bold")) |
# SOLUTION
# Version Control in Software Development
## Definition
Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later. It allows multiple developers to collaborate on a project, tracking changes made to the codebase, and provides a mechanism for resolving conflicts when different developers make changes to the same code simultaneously.
## Importance
### 1. **Collaboration:**
- `Multiple Contributors:` In software development, projects often involve multiple developers working on different aspects simultaneously. Version control systems facilitate collaboration by allowing developers to work on their own copies of the code and later merge their changes seamlessly.
- `Conflict Resolution:` When two developers make changes to the same part of the code, conflicts may arise. Version control tools provide mechanisms to detect and resolve these conflicts, ensuring that changes are integrated smoothly.
### 2. **History Tracking:**
- `Traceability:` Version control maintains a detailed history of changes made to the codebase. This historical record includes information about who made the changes, when they were made, and the nature of the changes. This traceability is invaluable for understanding the evolution of the code and for identifying when and why specific changes were introduced
### 3. **Parallel Development:**
- `Branching and Merging:` Version control systems support branching, enabling developers to work on isolated features or bug fixes without affecting the main codebase. Once the changes are tested and verified, they can be merged back into the main branch. This parallel development approach enhances efficiency and flexibility.
### 4. **Risk Mitigation:**
- `Rollback Capabilities:` Mistakes and bugs are inevitable in software development. Version control systems allow developers to roll back to previous, stable states of the codebase, reducing the risk associated with errors. This capability is crucial for maintaining a reliable and functional application.
### 5. **Continuous Integration and Deployment (CI/CD):**
- Integrates seamlessly with CI/CD pipelines, automating the testing and deployment processes.
- Ensures that only stable and tested code is deployed to production environments.
### 6. **Distribution and Remote Collaboration:**
- `Distributed Version Control:` In distributed version control systems like Git, each developer has a complete copy of the repository. This enables developers to work offline, collaborate remotely, and share changes with others easily.
### 8. **Traceability for Auditing:**
- `Compliance and Auditing:` In certain industries, compliance standards and audits require a detailed record of code changes. Version control systems provide the necessary traceability and documentation to meet these requirements.
### 7. **Efficient Release Management:**
- `Release Tagging:` Version control systems allow for the creation of release tags, which mark specific points in the code history corresponding to releases. This simplifies the process of managing and deploying software releases.
### 8. **Documentation:**
- `Commit Messages:` Developers are encouraged to provide meaningful commit messages when making changes. These messages serve as documentation for why specific changes were made, making it easier for others (and the future self) to understand the rationale behind each modification.
## Conclusion
version control is an integral part of modern software development practices, providing the infrastructure for efficient collaboration, risk management, and the maintenance of a reliable and traceable codebase. The use of version control systems contributes to the overall agility, reliability, and maintainability of software projects. |
<!--
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
-->
<Page
x:Class="FocusVisualsSample.CustomFocusVisuals"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:FocusVisualsSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<Style x:Key="CustomFocusVisualCheckBoxStyle" TargetType="CheckBox">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
<Setter Property="Padding" Value="8,5,0,0"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Top"/>
<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
<Setter Property="MinWidth" Value="120"/>
<Setter Property="MinHeight" Value="32"/>
<!--To use custom focus visuals, set this to False -->
<Setter Property="UseSystemFocusVisuals" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="CheckBox">
<Grid BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="26"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CombinedStates">
<VisualState x:Name="UncheckedNormal"/>
<VisualState x:Name="UncheckedPointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="UncheckedPressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseMediumBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="{ThemeResource CheckBoxCheckedStrokeThickness}" Storyboard.TargetProperty="StrokeThickness" Storyboard.TargetName="NormalRectangle"/>
</Storyboard>
</VisualState>
<VisualState x:Name="UncheckedDisabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="CheckedNormal">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="{ThemeResource CheckBoxCheckedStrokeThickness}" Storyboard.TargetProperty="StrokeThickness" Storyboard.TargetName="NormalRectangle"/>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundTransparentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
</Storyboard>
</VisualState>
<VisualState x:Name="CheckedPointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
</Storyboard>
</VisualState>
<VisualState x:Name="CheckedPressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseMediumBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="{ThemeResource CheckBoxCheckedStrokeThickness}" Storyboard.TargetProperty="StrokeThickness" Storyboard.TargetName="NormalRectangle"/>
<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
</Storyboard>
</VisualState>
<VisualState x:Name="CheckedDisabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="CheckGlyph">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
</Storyboard>
</VisualState>
<VisualState x:Name="IndeterminateNormal">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundAccentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="CheckGlyph">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundBaseMediumHighBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Glyph" Storyboard.TargetName="CheckGlyph">
<DiscreteObjectKeyFrame KeyTime="0" Value=""/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
</Storyboard>
</VisualState>
<VisualState x:Name="IndeterminatePointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="CheckGlyph">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Glyph" Storyboard.TargetName="CheckGlyph">
<DiscreteObjectKeyFrame KeyTime="0" Value=""/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
</Storyboard>
</VisualState>
<VisualState x:Name="IndeterminatePressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseMediumBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="CheckGlyph">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundBaseMediumBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Glyph" Storyboard.TargetName="CheckGlyph">
<DiscreteObjectKeyFrame KeyTime="0" Value=""/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
</Storyboard>
</VisualState>
<VisualState x:Name="IndeterminateDisabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="CheckGlyph">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Glyph" Storyboard.TargetName="CheckGlyph">
<DiscreteObjectKeyFrame KeyTime="0" Value=""/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
<!--Add back the FocusStates VisualStateGroup to handle your custom visuals -->
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="FocusVisual"
Storyboard.TargetProperty="Opacity"
To="1"
Duration="0" />
</Storyboard>
</VisualState>
<VisualState x:Name="Unfocused" />
<VisualState x:Name="PointerFocused" />
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid Height="38" VerticalAlignment="Top">
<!-- Here we're adding a red focus visual with 2px border to make it stand out -->
<Rectangle x:Name="FocusVisual" Stroke="Red" StrokeThickness="2" Opacity="0" Height="26" />
<Rectangle x:Name="NormalRectangle" Fill="Transparent" Height="20" Stroke="{ThemeResource SystemControlForegroundBaseMediumHighBrush}" StrokeThickness="{ThemeResource CheckBoxBorderThemeThickness}" UseLayoutRounding="False" Width="20" Margin="2"/>
<FontIcon x:Name="CheckGlyph" Foreground="{ThemeResource SystemControlForegroundChromeWhiteBrush}" FontSize="20" FontFamily="{ThemeResource SymbolThemeFontFamily}" Glyph="" Opacity="0" Margin="2"/>
</Grid>
<ContentPresenter x:Name="ContentPresenter" AutomationProperties.AccessibilityView="Raw" ContentTemplate="{TemplateBinding ContentTemplate}" ContentTransitions="{TemplateBinding ContentTransitions}" Content="{TemplateBinding Content}" Grid.Column="1" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" TextWrapping="Wrap" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<ScrollViewer Grid.Row="1" VerticalScrollMode="Auto" VerticalScrollBarVisibility="Auto">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Margin="0,0,0,12">
<TextBlock Text="Using custom focus visuals" Style="{StaticResource SampleHeaderTextStyle}" />
<RichTextBlock Style="{StaticResource BodyRichTextBlockStyle}">
<Paragraph>With Windows 10, the system now draws the focus visuals for all of the inbox controls, and can be used for custom controls as well.</Paragraph>
<Paragraph>In this example, we will show you how to customize the focus visuals, if the 1px black and white border does not suit your needs.</Paragraph>
<Paragraph>Look in the Page.Resources of CustomFocusViusals.xaml to see the source for this sample.</Paragraph>
<Paragraph>The 3 steps you need to define your own focus visuals for any inbox control are:</Paragraph>
<Paragraph TextIndent="20">1) Re-template the control and add in your desired visual (here we've added a red rectangle)</Paragraph>
<Paragraph TextIndent="20">2) Add back the FocusStates VisualStateGroup (see the control template code for the proper state names)</Paragraph>
<Paragraph TextIndent="20">3) Set Control.UseSystemFocusVisuals to False</Paragraph>
</RichTextBlock>
</StackPanel>
<CheckBox Content="Focus me" Style="{StaticResource CustomFocusVisualCheckBoxStyle}" Grid.Row="1" VerticalAlignment="Top" />
</Grid>
</ScrollViewer>
</Page> |
package com.zerobase.storeReservation.member.domain.Form;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SignUpForm {
@NotBlank(message = "필수 입력")
@Email(message = "이메일 형식에 맞게 입력해 주세요.")
private String email;
@NotBlank(message = "필수 입력")
private String name;
@NotBlank(message = "필수 입력")
@Pattern(regexp = "(?=.*[0-9])(?=.*[a-zA-Z])(?=.*\\W)(?=\\S+$).{8,16}",
message = "비밀번호는 8~16자 영문 대 소문자, 숫자, 특수문자를 사용하세요. 특수문자는 반드시 포함 해주세요.")
private String password;
@NotBlank(message = "필수 입력")
@Pattern(regexp = "^010\\d{8,9}$",
message = "'-' 빼고 010으로 시작하는 10~11자리 숫자로 작성 해주세요.")
private String phone;
} |
import React from 'react'
import styles from './Header.module.css'
import { Link, useLocation } from 'react-router-dom'
function Header() {
const [mobile, setMobile] = React.useState(false)
const [title, setTitle] = React.useState(null)
const location = useLocation();
React.useEffect(()=>{
function menuMobile(){
setMobile(false)
}
window.addEventListener('resize',menuMobile);
return ()=> window.removeEventListener('resize', menuMobile)
},[])
React.useEffect(()=>{
const {pathname} = location;
switch(pathname){
case '/services':
setTitle('services');
break;
case '/adopt':
setTitle('adopt');
break;
case '/about-us':
setTitle('about');
break;
case '/contact':
setTitle('contact');
break;
case '/turn-partner':
setTitle('partner');
break;
default:
setTitle('home')
}
},[location])
const [show, setShow] = React.useState(true);
const [lastScrollY, setLastScrollY] = React.useState(0);
const controlNavbar = () => {
if (window.scrollY > lastScrollY) {
setShow(false);
setMobile(false)
} else {
setShow(true);
}
setLastScrollY(window.scrollY);
};
React.useEffect(() => {
window.addEventListener('scroll', controlNavbar);
return () => {
window.removeEventListener('scroll', controlNavbar);
};
}, [lastScrollY]);
return (
<header className={`${styles.header} ${!show ? styles.hide : ""}`}>
<div style={{display: mobile ? 'block' : 'none'}} className={styles.overLay} onClick={()=>{setMobile(!mobile)}}></div>
<div className='container'>
<div className={styles.navbar}>
<div className={styles.mobileNav}>
<div className={styles.menuButtonWrapper}>
<button className={styles.menuButton} onClick={()=>{setMobile(!mobile)}}><i className="fa-solid fa-bars"></i></button>
</div>
<div className={styles.logoWrapper}>
<Link to="/" className={`${styles.logo}`}>
<img src="https://firebasestorage.googleapis.com/v0/b/abea-project.appspot.com/o/logo%26icons%2Fimage%20(2).png?alt=media&token=134393c8-fbdf-4732-8bbe-aba8b2926051" alt="" loading='lazy'/>
</Link>
</div>
</div>
<div style={{left: mobile ? '0px' : '-300px'}} className={styles.navigation} >
<ul>
<li><Link to="/" className={ title === "home" ? "pagina" : ""}>Home</Link></li>
<li><Link to="/services" className={ title === "services" ? "pagina" : ""}>Serviços & Eventos</Link></li>
<li><Link to="/adopt" className={ title === "adopt" ? "pagina" : ""}>Adote um Amigo</Link></li>
<li><Link to="/about-us" className={ title === "about" ? "pagina" : ""}>Sobre nós</Link></li>
<li><Link to="/contact" className={ title === "contact" ? "pagina" : ""}>Contato</Link></li>
<li className={styles.mobilePartner}><Link to="/turn-partner" className={title === "partner" ? "pagina" : "" }>Seja um apoiador</Link></li>
</ul>
<div className={styles.closeButton}>
<button onClick={()=>{setMobile(false)}}><i className='fa-solid fa-xmark'></i></button>
</div>
</div>
<div className={styles.buttonPartner}>
<Link to="/turn-partner">Seja um Apoiador</Link>
</div>
</div>
</div>
</header>
)
}
export default Header |
import Guest from "Components/Layouts/Guest";
import Image from "next/image";
import crocodileNFT from "images/crocodile-nft.png";
import styles from "styles/Pages/Mint.module.scss";
import { ISocialItem } from "types";
import { ChangeEvent, useState } from "react";
import ConnectWalletButton from "Components/Guest/Global/ConnectWalletButton";
import MintButton from "Components/Guest/Global/MintButton";
export default function Mint({ socials }: { socials: Array<ISocialItem> }) {
const [editions, setEditions] = useState<number>(2);
const MAX = 20;
const MIN = 1;
const increaseEditions = () => {
if (editions <= 2){
setEditions(editions => Math.min(MAX, editions + 1));
}
}
const decreaseEditions = () => {
setEditions(editions => Math.max(MIN, editions - 1));
}
const editionValueChange = (e: ChangeEvent<HTMLInputElement>) => {
const el = e.target as HTMLInputElement;
let value = Number(el.value);
if (isNaN(value)) return;
if (value > MAX)
value = MAX;
if (value < MIN)
value = MIN;
setEditions(value);
}
return (
<Guest socials={socials} title="Mint">
<div className={styles.Mint}>
<div className="row">
<div className={["col-md-6", styles.ImageContainer].join(" ")}>
<Image src={crocodileNFT} alt="Crocodile's NFT" />
</div>
<div className={["col-md-6", styles.FormContainer].join(" ")}>
<div className={styles.ConnectWalletContainer}>
<ConnectWalletButton />
<div className={styles.Editions}>
<div className={styles.LabelContainer}>
<label>Select Number of Editions</label>
</div>
<div className={styles.InputContainer}>
<button className={styles.MinusButton} onClick={decreaseEditions} disabled={editions === MIN}><i className="fa fa-minus" /></button>
<input type="text" className={styles.EditionCounter} value={editions} onChange={e => editionValueChange(e)} />
<button className={styles.PlusButton} onClick={increaseEditions} disabled={editions === MAX}><i className="fa fa-plus" /></button>
</div>
</div>
</div>
<div >
<MintButton editions={editions}/>
</div>
</div>
</div>
</div>
</Guest>
)
}
export async function getStaticProps() {
return {
props: {
title: "Mint"
}
}
} |
package mirecxp.aoc23.day02
import java.io.File
//https://adventofcode.com/2023/day/2
class Day02(inputPath: String) {
private val gameInputs: List<String> =
File(inputPath).readLines()
data class Game(
val id: Long,
val draws: List<Draw>
) {
fun getMinimumDraw() = Draw(
draws.maxOf { it.red },
draws.maxOf { it.green },
draws.maxOf { it.blue }
)
}
data class Draw(val red: Long, val green: Long, val blue: Long) {
fun getPower() = red * green * blue
fun isPossible(minDraw: Draw) =
red <= minDraw.red && green <= minDraw.green && blue <= minDraw.blue
}
fun solve() {
println("Solving day 2 for ${gameInputs.size} games")
var sum = 0L
var sumPowers = 0L
val games = mutableListOf<Game>()
gameInputs.forEach { gameInput ->
gameInput.split(":").apply {
val id = get(0).split(" ")[1].toLong()
val draws = mutableListOf<Draw>()
var possibleGame = true
get(1).split(";").forEach { singleGame ->
var red = 0L
var blue = 0L
var green = 0L
singleGame.split(",").forEach { gems ->
gems.trim().split(" ").apply {
val num = get(0).toLong()
when (val color = get(1)) {
"red" -> red = num
"green" -> green = num
"blue" -> blue = num
}
}
val draw = Draw(red, green, blue)
draws.add(draw)
if (!draw.isPossible(minDraw = Draw(red = 12, green = 13, blue = 14))) {
possibleGame = false
}
}
}
if (possibleGame) {
sum += id
}
val game = Game(id, draws)
games.add(game)
sumPowers += game.getMinimumDraw().getPower()
}
}
println("Sum of possible game IDs: $sum")
println("Sum of all powers: $sumPowers")
}
}
fun main(args: Array<String>) {
// val problem = Day02("/Users/miro/projects/AoC23/input/day02t.txt")
val problem = Day02("/Users/miro/projects/AoC23/input/day02a.txt")
problem.solve()
} |
const nql = require('@tryghost/nql');
const {BadRequestError} = require('@tryghost/errors');
const tpl = require('@tryghost/tpl');
const messages = {
invalidVisibilityFilter: 'Invalid visibility filter.',
invalidEmailSegment: 'The email segment parameter doesn\'t contain a valid filter'
};
class PostsService {
constructor({mega, urlUtils, models, isSet}) {
this.mega = mega;
this.urlUtils = urlUtils;
this.models = models;
this.isSet = isSet;
}
async editPost(frame) {
// Make sure the newsletter is matching an active newsletter
// Note that this option is simply ignored if the post isn't published or scheduled
if (frame.options.newsletter && frame.options.email_segment) {
if (frame.options.email_segment !== 'all') {
// check filter is valid
try {
await this.models.Member.findPage({filter: frame.options.email_segment, limit: 1});
} catch (err) {
return Promise.reject(new BadRequestError({
message: tpl(messages.invalidEmailSegment),
context: err.message
}));
}
}
}
const model = await this.models.Post.edit(frame.data.posts[0], frame.options);
/**Handle newsletter email */
if (model.get('newsletter_id')) {
const sendEmail = model.wasChanged() && this.shouldSendEmail(model.get('status'), model.previous('status'));
if (sendEmail) {
let postEmail = model.relations.email;
if (!postEmail) {
const email = await this.mega.addEmail(model, frame.options);
model.set('email', email);
} else if (postEmail && postEmail.get('status') === 'failed') {
const email = await this.mega.retryFailedEmail(postEmail);
model.set('email', email);
}
}
}
return model;
}
async getProductsFromVisibilityFilter(visibilityFilter) {
try {
const allProducts = await this.models.Product.findAll();
const visibilityFilterJson = nql(visibilityFilter).toJSON();
const productsData = (visibilityFilterJson.product ? [visibilityFilterJson] : visibilityFilterJson.$or) || [];
const tiers = productsData
.map((data) => {
return allProducts.find((p) => {
return p.get('slug') === data.product;
});
}).filter(p => !!p).map((d) => {
return d.toJSON();
});
return tiers;
} catch (err) {
return Promise.reject(new BadRequestError({
message: tpl(messages.invalidVisibilityFilter),
context: err.message
}));
}
}
/**
* Calculates if the email should be tried to be sent out
* @private
* @param {String} currentStatus current status from the post model
* @param {String} previousStatus previous status from the post model
* @returns {Boolean}
*/
shouldSendEmail(currentStatus, previousStatus) {
return (['published', 'sent'].includes(currentStatus))
&& (!['published', 'sent'].includes(previousStatus));
}
handleCacheInvalidation(model) {
let cacheInvalidate;
if (
model.get('status') === 'published' && model.wasChanged() ||
model.get('status') === 'draft' && model.previous('status') === 'published'
) {
cacheInvalidate = true;
} else if (
model.get('status') === 'draft' && model.previous('status') !== 'published' ||
model.get('status') === 'scheduled' && model.wasChanged()
) {
cacheInvalidate = {
value: this.urlUtils.urlFor({
relativeUrl: this.urlUtils.urlJoin('/p', model.get('uuid'), '/')
})
};
} else {
cacheInvalidate = false;
}
return cacheInvalidate;
}
}
/**
* @returns {PostsService} instance of the PostsService
*/
const getPostServiceInstance = () => {
const urlUtils = require('../../../shared/url-utils');
const {mega} = require('../mega');
const labs = require('../../../shared/labs');
const models = require('../../models');
return new PostsService({
mega: mega,
urlUtils: urlUtils,
models: models,
isSet: labs.isSet.bind(labs)
});
};
module.exports = getPostServiceInstance;
// exposed for testing purposes only
module.exports.PostsService = PostsService; |
import React, { FunctionComponent, ReactElement } from "react";
import { Flex, Text, TextInput, ActionIcon } from "@mantine/core";
import { IconSettings, IconSearch } from "@tabler/icons-react";
import { useNavigate } from "react-router-dom";
const Navbar: FunctionComponent = (): ReactElement => {
const navigate = useNavigate();
return (
<Flex
justify="space-between"
align="center"
px="xl"
py="md"
sx={(theme) => ({
backgroundColor: theme.colors.dark[8],
color: theme.colors.gray[2],
height: 80,
border: `1px solid ${theme.colors.dark[4]}`,
})}
>
<Text
fz="2rem"
lh="20"
weight={700}
onClick={() => navigate("/")}
sx={{ cursor: "pointer" }}
>
Books
</Text>
<TextInput
placeholder="Search books..."
variant="filled"
size="md"
icon={<IconSearch size="1.25rem" />}
sx={(theme) => ({
width: "50%",
outline: `2px solid ${theme.colors.dark[4]}`,
})}
/>
<ActionIcon
size="lg"
radius="md"
variant="subtle"
sx={(theme) => ({
color: theme.colors.gray[1],
"&:hover": {
backgroundColor: theme.colors.dark[5],
},
})}
onClick={() => navigate("/settings")}
>
<IconSettings size="2rem" />
</ActionIcon>
</Flex>
);
};
export default Navbar; |
import type { NewPosEvent, Point } from './types';
type UserOptions = NewPosEvent & {
isLocalUser?: boolean;
};
type Shape = {
points: Array<Point>;
isClosed: boolean;
color: string;
};
const CHUNK_POINTS_THRESHOLD = 3;
export class User {
id: string;
isLocalUser = false;
name: string;
trackerColor: string = '';
x: number;
y: number;
points: Array<Point>;
pointsQueue: Array<Point> = [];
shapes: Array<Shape> = [];
isDrawing = false;
constructor(options: UserOptions) {
this.id = options.id;
this.name = options.name;
this.x = options.points?.[0]?.x;
this.y = options.points?.[0]?.y;
this.points = options.points;
this.trackerColor = options.trackerColor;
this.isLocalUser = options.isLocalUser || false;
}
handleMousemove(event: MouseEvent, mouseIsDown: boolean, color: string) {
const point = {
x: Math.round(event.clientX),
y: Math.round(event.clientY),
mouseIsDown,
color
};
this.pointsQueue.push(point);
this.points.push(point);
}
getNextPoints() {
if (!this.points.length) {
return [];
}
if (this.isLocalUser) {
return [this.points[this.points.length - 1]];
}
if (this.points.length > CHUNK_POINTS_THRESHOLD) {
const safeChunkLastIdx = this.points
.slice(0, CHUNK_POINTS_THRESHOLD)
.findIndex(
(item, _idx, arr) => item.mouseIsDown !== arr[0].mouseIsDown
);
return this.points.slice(
0,
safeChunkLastIdx === -1 ? CHUNK_POINTS_THRESHOLD : safeChunkLastIdx
);
}
return [this.points[0]];
}
clearPoints(count: number) {
if (this.points.length === 1) {
return;
}
this.points.splice(0, count);
}
updateTrackerPosition(point: Point) {
if (point) {
this.x = point.x;
this.y = point.y;
}
}
addPointToShape(points: Point[]) {
if (!points.length) {
return [];
}
if (!points[0].mouseIsDown) {
this.isDrawing = false;
return;
}
const startNewShape = !this.isDrawing;
if (startNewShape) {
this.shapes.push({
points: points,
isClosed: false,
color: points[0].color
});
this.isDrawing = true;
} else {
this.shapes[this.shapes.length - 1].points.push(...points);
}
}
handleFrame() {
const points = this.getNextPoints();
this.updateTrackerPosition(points[0]);
this.addPointToShape(points);
this.clearPoints(points.length);
}
undoShape() {
this.shapes.splice(this.shapes.length - 1, 1);
}
} |
//
// RoomListView.swift
// AgoraEntScenarios
//
// Created by FanPengpeng on 2022/11/3.
//
import UIKit
class ShowRoomListView: UIView {
var roomList = [ShowRoomListModel]() {
didSet {
collectionView.reloadData()
emptyView.isHidden = roomList.count > 0
}
}
var clickCreateButtonAction: (()->())?
var joinRoomAction: ((_ room: ShowRoomListModel)->())?
var refreshValueChanged: (()->())?
var collectionView: UICollectionView!
private lazy var refreshControl: UIRefreshControl = {
let ctrl = UIRefreshControl()
ctrl.addTarget(self, action: #selector(refreshControlValueChanged), for: .valueChanged)
return ctrl
}()
private var emptyView: ShowEmptyView!
override init(frame: CGRect) {
super.init(frame: frame)
createSubviews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func createSubviews(){
// 列表
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
let itemWidth = (Screen.width - 15 - 20 * 2) * 0.5
layout.itemSize = CGSize(width: itemWidth, height: 234.0 / 160.0 * itemWidth)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = .clear
collectionView.register(ShowRoomListCell.self, forCellWithReuseIdentifier: NSStringFromClass(ShowRoomListCell.self))
collectionView.delegate = self
collectionView.dataSource = self
collectionView.refreshControl = self.refreshControl
addSubview(collectionView)
collectionView.snp.makeConstraints { make in
make.edges.equalTo(UIEdgeInsets(top: Screen.safeAreaTopHeight() + 54, left: 0, bottom: 0, right: 0))
}
// 空列表
emptyView = ShowEmptyView()
emptyView.isHidden = true
collectionView.addSubview(emptyView)
emptyView.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.top.equalTo(156)
}
// 创建房间按钮
let btnHeight: CGFloat = 48
let createButton = UIButton(type: .custom)
createButton.setTitleColor(.white, for: .normal)
createButton.setTitle("room_list_create_room".show_localized, for: .normal)
createButton.setImage(UIImage.show_sceneImage(name: "show_create_add"), for: .normal)
createButton.imageEdgeInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5))
createButton.titleEdgeInsets(UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0))
createButton.backgroundColor = .show_btn_bg
createButton.titleLabel?.font = .show_btn_title
createButton.layer.cornerRadius = btnHeight * 0.5
createButton.layer.masksToBounds = true
createButton.addTarget(self, action: #selector(didClickCreateButton), for: .touchUpInside)
addSubview(createButton)
createButton.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.bottom.equalToSuperview().offset(-max(Screen.safeAreaBottomHeight(), 10))
make.height.equalTo(btnHeight)
make.width.equalTo(195)
}
}
// 点击创建按钮
@objc private func didClickCreateButton(){
clickCreateButtonAction?()
}
@objc private func refreshControlValueChanged() {
refreshValueChanged?()
}
func beginRefreshing(){
refreshControl.beginRefreshing()
}
func endRefrshing(){
refreshControl.endRefreshing()
}
}
extension ShowRoomListView: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return roomList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: ShowRoomListCell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(ShowRoomListCell.self), for: indexPath) as! ShowRoomListCell
let room = roomList[indexPath.item]
cell.setBgImge((room.thumbnailId?.isEmpty ?? true) ? "0" : room.thumbnailId ?? "0",
name: room.roomName,
id: room.roomId,
count: room.roomUserCount)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let room = roomList[indexPath.item]
joinRoomAction?(room)
}
} |
import 'package:flutter/material.dart';
import '../../../../models/laporan_keuangan_models.dart';
import '../../../text_paragraf.dart';
import '../../isi-saldo-page/isi-saldo/isi_saldo.dart';
class DetailRiwayatDenda extends StatefulWidget {
const DetailRiwayatDenda({Key? key, required this.riwayatDendaUser})
: super(key: key);
final RiwayatDendaUser riwayatDendaUser;
@override
State<DetailRiwayatDenda> createState() => _DetailRiwayatDendaState();
}
class _DetailRiwayatDendaState extends State<DetailRiwayatDenda> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
'Detail Riwayat',
style: TextStyle(
fontSize: 20,
color: Color(0xff4B556B),
fontFamily: 'Poppins',
fontWeight: FontWeight.w800,
letterSpacing: 1,
),
),
elevation: 0,
backgroundColor: Colors.white,
iconTheme: const IconThemeData(
color: Color(0xff4B556B),
),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 50,
child: Image.asset('assets/icons/denda2.png'),
),
const SizedBox(
width: 20,
),
const Text(
"Bayar Denda",
style: TextStyle(
fontSize: 14,
color: Color(0xff4B556B),
fontFamily: 'Poppins',
fontWeight: FontWeight.w600,
letterSpacing: 1,
),
),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Text(
widget.riwayatDendaUser.fineTransactionCode,
style: const TextStyle(
fontSize: 12,
color: Color(0xff4B556B),
fontFamily: 'Poppins',
fontWeight: FontWeight.w400,
letterSpacing: 1,
),
),
),
const SizedBox(
height: 30,
),
TextParagraf(
title: 'Tanggal',
value: widget.riwayatDendaUser.createdAt.day.toString() +
'-' +
widget.riwayatDendaUser.createdAt.month.toString() +
'-' +
widget.riwayatDendaUser.createdAt.year.toString(),
),
TextParagraf(
title: 'Waktu',
value: widget.riwayatDendaUser.waktu,
),
TextParagraf(
title: 'Nominal Pembayaran',
value: FormatCurrency.convertToIdr(
widget.riwayatDendaUser.fineTransaction, 0),
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
SizedBox(
width: 130,
child: Text(
'Status',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
fontFamily: 'Poppins',
color: Color(0xff4B556B),
),
),
),
SizedBox(
width: 10,
child: Text(
": ",
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
fontFamily: 'Poppins',
color: Color(0xff4B556B),
),
),
),
Expanded(
child: Text(
'Berhasil',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
fontFamily: 'Poppins',
color: Color(0xff83BC10),
),
),
),
],
),
],
),
),
);
}
} |
/*
* Copyright (C) 2004-2006 Autodesk, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of version 2.1 of the GNU Lesser
* General Public License as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#pragma once
class FdoReadOnlyPropertyDefinitionCollection;
BEGIN_NAMESPACE_OSGEO_FDO_SCHEMA
ref class PropertyDefinition;
ref class PropertyDefinitionCollection;
/// \ingroup (OSGeoFDOSchema)
/// \brief
/// The ReadOnlyPropertyDefinitionCollection class represents a collection of PropertyDefinition objects.
[System::Reflection::DefaultMemberAttribute("Item")]
public ref class ReadOnlyPropertyDefinitionCollection sealed : public NAMESPACE_OSGEO_COMMON::CollectionReadOnlyBase
{
/// \cond DOXYGEN-IGNORE
internal:
FdoReadOnlyPropertyDefinitionCollection* GetImpObj();
public:
virtual IntPtr GetDisposableObject() override;
private:
virtual property System::Object^ IndexInternal[System::Int32]
{
private: System::Object^ get(System::Int32 index) sealed = NAMESPACE_OSGEO_COMMON::IListReadOnly::default::get;
}
/// \endcond
public:
/// \brief
/// Constructs a ReadOnlyPropertyDefinitionCollection object
///
/// \param parent
/// Input A Pointer to the parent schema object of the collection
///
ReadOnlyPropertyDefinitionCollection(NAMESPACE_OSGEO_FDO_SCHEMA::PropertyDefinitionCollection^ parent);
/// \brief
/// Constructs a ReadOnlyPropertyDefinitionCollection object based on an unmanaged instance of the object
///
/// \param unmanaged
/// Input A Pointer to the unmanaged object.
///
/// \param autoDelete
/// Input Indicates if the constructed object should be automatically deleted
/// once it no longer referenced.
///
ReadOnlyPropertyDefinitionCollection(System::IntPtr unmanaged, System::Boolean autoDelete) : NAMESPACE_OSGEO_COMMON::CollectionReadOnlyBase(unmanaged, autoDelete)
{
}
/// \brief
/// Gets the count of items in collection.
///
/// \return
/// Returns the number of items in the collection.
///
property System::Int32 Count
{
virtual System::Int32 get() override;
}
/// \brief
/// Determines the index of a specific PropertyDefinition object.
///
/// \param value
/// Input the PropertyDefinition object to locate in the collection.
///
/// \return
/// The index of value if found in the collection; otherwise, -1.
///
System::Int32 IndexOf(NAMESPACE_OSGEO_FDO_SCHEMA::PropertyDefinition^ value);
/// \brief
/// Determines whether the collection contains a specific PropertyDefinition object.
///
/// \param value
/// Input The PropertyDefinition object to search in the collection.
///
/// \return
/// Returns true if the value is found in the collection; otherwise, false.
///
System::Boolean Contains(NAMESPACE_OSGEO_FDO_SCHEMA::PropertyDefinition^ value);
/// \brief
/// Copies the elements of the collection to an array.
///
/// \param array
/// Output the one-dimensional Array that is the destination of the elements copied from this collection.
/// \param startAt
/// Input an integer that represents the index in array at which copying begins.
///
System::Void CopyTo(array<NAMESPACE_OSGEO_FDO_SCHEMA::PropertyDefinition^>^ pArray, System::Int32 index);
/// \brief
/// Gets the item in the collection at the specified index.
///
/// \param index
/// The index of the item in the collection. The index is 0 based.
///
/// \return
/// Returns an instance of a the collected item.
/// Throws an instance of Exception if the index is out of range or an error occurs.
///
property NAMESPACE_OSGEO_FDO_SCHEMA::PropertyDefinition^ Item[System::Int32]
{
NAMESPACE_OSGEO_FDO_SCHEMA::PropertyDefinition^ get(System::Int32 index);
}
/// \brief
/// Gets the item in the collection at the specified index.
///
/// \param name
/// The name of the item in the collection.
///
/// \return
/// Returns an instance of a the collected item.
///
property NAMESPACE_OSGEO_FDO_SCHEMA::PropertyDefinition^ Item[System::String^]
{
NAMESPACE_OSGEO_FDO_SCHEMA::PropertyDefinition^ get(System::String^ name);
}
};
END_NAMESPACE_OSGEO_FDO_SCHEMA |
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
use crate::domain::{
handler::AttributeSchema,
types::{AttributeName, AttributeType},
};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "user_attribute_schema")]
pub struct Model {
#[sea_orm(
primary_key,
auto_increment = false,
column_name = "user_attribute_schema_name"
)]
pub attribute_name: AttributeName,
#[sea_orm(column_name = "user_attribute_schema_type")]
pub attribute_type: AttributeType,
#[sea_orm(column_name = "user_attribute_schema_is_list")]
pub is_list: bool,
#[sea_orm(column_name = "user_attribute_schema_is_user_visible")]
pub is_user_visible: bool,
#[sea_orm(column_name = "user_attribute_schema_is_user_editable")]
pub is_user_editable: bool,
#[sea_orm(column_name = "user_attribute_schema_is_hardcoded")]
pub is_hardcoded: bool,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::user_attributes::Entity")]
UserAttributes,
}
impl Related<super::UserAttributes> for Entity {
fn to() -> RelationDef {
Relation::UserAttributes.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
impl From<Model> for AttributeSchema {
fn from(value: Model) -> Self {
Self {
name: value.attribute_name,
attribute_type: value.attribute_type,
is_list: value.is_list,
is_visible: value.is_user_visible,
is_editable: value.is_user_editable,
is_hardcoded: value.is_hardcoded,
}
}
} |
import { Component, OnInit, ViewEncapsulation, ViewChild, AfterViewInit, OnDestroy } from '@angular/core';
import { FormGroup, FormControl, Validators, NgForm, AbstractControl } from '@angular/forms';
import { Constants } from 'src/providers/constants.service';
import { Router } from '@angular/router';
import { UserContextProvider } from 'src/providers/user-context.service';
import { MatTabChangeEvent } from '@angular/material/tabs';
import { AuthService } from 'src/providers/auth.service';
import { Subscription } from 'rxjs';
import { GenericMessageComponent } from '../../generic-message/generic-message.component';
import { MatDialog } from '@angular/material/dialog';
import * as moment from 'moment';
@Component({
selector: 'app-auth',
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class AuthComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('tab') tab: any;
@ViewChild('signupFormRef', { static: false }) signupFormRef: NgForm;
@ViewChild('loginFormRef', { static: false }) loginFormRef: NgForm;
signupForm: FormGroup;
loginForm: FormGroup;
hide: boolean = true;
ICON_BASE: string = Constants.ICON_BASE;
activeTabIndex: number = 0;
signupSub: Subscription;
loginSub: Subscription;
signupLoader: boolean;
loginLoader: boolean;
minDate: Date;
maxDate: Date;
constructor( private router: Router,
private userContextProvider: UserContextProvider,
private authService: AuthService,
private dialog: MatDialog
) { }
ngOnInit(): void {
const currentYear = new Date().getFullYear();
this.minDate = new Date(currentYear - 70, 0, 1);
this.maxDate = new Date(currentYear - 15, 11, 31);
this.createSignupForm();
this.createLoginForm();
this.signupSub = this.authService.signupStatusEmitter.subscribe((resp: { status: boolean, response: any} ) => {
console.log("Resp", resp);
if ( resp.status ) {
this.completePostSignupRituals(resp);
}
});
this.loginSub = this.authService.loginStatusEmitter.subscribe((resp: { status: boolean, response: any}) => {
console.log("In login sub", resp)
this.completePostLoginRituals(resp);
})
}
ngAfterViewInit(): void {
console.log("Mat tab", this.tab);
console.log("Selected Index", this.tab.selectedIndex);
}
ngOnDestroy() {
this.signupSub.unsubscribe();
}
createSignupForm() {
this.signupForm = new FormGroup({
name: new FormControl('', [ Validators.required, Validators.minLength(4), Validators.maxLength(100)]),
email: new FormControl('', [ Validators.required, Validators.email, Validators.maxLength(250)] ),
password: new FormControl('', [ Validators.required, Validators.minLength(6), Validators.maxLength(100) ]),
dob: new FormControl('', [ Validators.required ]),
gender: new FormControl('', [ Validators.required ])
})
}
createLoginForm() {
this.loginForm = new FormGroup({
email: new FormControl('', [ Validators.required, Validators.email, Validators.maxLength(250)] ),
password: new FormControl('', [ Validators.required, Validators.minLength(6), Validators.maxLength(100) ]),
})
}
testProfile() {
console.log("Testing profile")
this.userContextProvider.setLoginStatus(true);
this.userContextProvider.loginStatus.next({ status: true });
this.router.navigate(['profile']);
}
getErrorMessage(formField: string) {
const control = this.activeTabIndex === 0 ? this.loginForm.controls[formField] : this.signupForm.controls[formField] as FormControl;
if ( control ) {
if (control.hasError('required')) {
return formField.toUpperCase() + " is required.";
} else if ( control.hasError('email')) {
return "Must be a email (xxx@xxx.com)";
} else if ( control.hasError('maxlength')) {
return `Exceeded the maximum limit (${control.errors.maxlength.requiredLength}), Remove at least ${control.errors.maxlength.actualLength - control.errors.maxlength.requiredLength} characters`;
} else if ( control.hasError('minlength')) {
return `Minimum characters must be ${control.errors.minlength.requiredLength}, Enter ${control.errors.minlength.requiredLength - control.errors.minlength.actualLength} more characters`;
}
}
}
tabChanged(event: MatTabChangeEvent) {
console.log(this.signupForm);
this.activeTabIndex = event.index;
}
submitSignupForm() {
this.signupLoader = true;
this.authService.signup(this.signupForm.value);
}
submitLoginForm() {
this.loginLoader = true;
this.authService.login(this.loginForm.value);
}
completePostSignupRituals(resp: any) {
this.signupLoader = false;
this.signupForm.reset();
this.signupFormRef.resetForm();
const dialogRef = this.dialog.open(GenericMessageComponent, {
width: window.innerWidth > 500 ? '20%' : '80%',
height: window.innerWidth > 500 ? '40%' : '35%',
data: {
type: "Success",
body: resp.response.message,
}
});
dialogRef.afterClosed().subscribe(() => {
this.tab.selectedIndex = 0;
})
}
completePostLoginRituals(resp: any) {
this.loginLoader = false;
this.loginForm.reset();
this.loginFormRef.resetForm();
if ( resp.status ) {
console.log("User id before navigating", this.authService.userId);
this.router.navigate(['profile', this.authService.userId], { state: { mode: 'Owner'}} );
} else {
const dialogRef = this.dialog.open(GenericMessageComponent, {
width: window.innerWidth > 500 ? '20%' : '80%',
height: window.innerWidth > 500 ? '40%' : '35%',
data: {
type: "Error",
body: resp.error.error.message,
}
});
}
}
} |
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[UniqueEntity(fields: ['email'], message: 'There is already an account with this email')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: "integer")]
private $id;
#[ORM\Column(type: "string", length: 180, unique: true)]
private $email;
#[ORM\Column(type: "json")]
private $roles = [];
#[ORM\Column(type: "string")]
private $password;
#[ORM\Column(type: "string", length: 100)]
private $username;
#[ORM\OneToMany(targetEntity: Comment::class, mappedBy: "user")]
private $comments;
public function __construct()
{
$this->comments = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function getSalt(): ?string
{
// not needed when using the "bcrypt" algorithm in security.yaml
return null;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
/**
* @return Collection|Comment[]
*/
public function getComments(): Collection
{
return $this->comments;
}
public function addComment(Comment $comment): self
{
if (!$this->comments->contains($comment)) {
$this->comments[] = $comment;
$comment->setUser($this);
}
return $this;
}
public function removeComment(Comment $comment): self
{
if ($this->comments->removeElement($comment)) {
// set the owning side to null (unless already changed)
if ($comment->getUser() === $this) {
$comment->setUser(null);
}
}
return $this;
}
/**
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->email;
}
} |
# ArangoProxy How To
## Build
Compile the _arangoproxy_ web server (only when new code is available).
**Go needs to be installed to perform the go build command**
```
toolchain/arangoproxy/cmd> go build -o arangoproxy
```
Go automatically detects the hardware and produces the right executable inside
the `cmd` folder.
## Run
```
toolchain/arangoproxy/cmd> ./arangoproxy [flags]
```
### Flags
- `-help`: show help usage
- `--config {filepath}`: load from config file (default: `configs/local.json`)
- `-no-cache`: clean cache files.
**WARNING**: All collections in the arango instances are erased!
## Configuration
Configuration is loaded with json files.
A configuration file is made of (taken from `local.json`):
```json
{
"webserver": ":8080", // url+port the arangoproxy will be reachable
"logFile": "log.txt", // where to write logs
"datasetsFile": "", // Where datasets examples for aql are stored
// OpenApi module configuration
"openapi": {
// Filepath to write the Swagger/OpenAPI spec for the web interface team
"apiDocsFile": "./openapi/api-docs.json",
// Filepath where the openapi endpoint loads common OpenAPI schemas
"componentsFile": "./openapi/components.yaml"
},
// Cache module configuration
"cache": {
// Filepath where requests (examples input) cache will be saved
"requestsFile": "./cache/requests.txt",
// Filepath where responses (examples output) will be saved
"responsesFile": "./cache/responses.txt"
},
// Arango instances configuration
"repositories": [
{
"type": "local", // Instance type: e.g. nightly, stable ...
"version": "3.10",
"url": "http+tcp://127.0.0.1:8529",
"password": ""
}
]
}
``` |
//
// Copyright (c) 2023, Brian Frank
// Licensed under the Academic Free License version 3.0
//
// History:
// 26 May 2023 Brian Frank Creation
//
using util
using data
using haystack
using defc
using xetoTools
**
** Generate JSON file for spec source
**
class JsonSrc : XetoCmd
{
override Str name() { "json-src" }
override Str summary() { "Generate JSON file for lib source code" }
@Opt { help = "Output file (default to stdout)" }
File? out
@Arg { help = "Lib to compile into table of contents" }
Str? lib
override Int usage(OutStream out := Env.cur.out)
{
super.usage(out)
out.printLine("Examples:")
out.printLine(" xeto json-src ashrae.g36")
return 1
}
// Run
override Int run()
{
if (lib == null)
{
echo("Must specify input lib")
return 1
}
lib := env.lib(this.lib)
src := loadSource(lib)
dict := genDict(lib, src)
withOut(this.out) |out|
{
env.print(dict, out, env.dict1("json", env.marker))
}
return 0
}
// Load Source
private Str:Str[] loadSource(DataLib lib)
{
acc := Str:Str[][:]
entry := env.registry.get(lib.qname)
if (!entry.isSrc) throw Err("Lib source not available: $lib")
entry.srcDir.list.each |file|
{
if (file.ext != "xeto") return
lines := file.readAllLines
acc[file.name] = lines
}
return acc
}
// Generate
private Dict genDict(DataLib lib, Str:Str[] files)
{
acc := Str:Dict[:]
lib.slotsOwn.each |x|
{
filename := x.loc.file.toUri.name
src := toSource(x, files[filename])
acc[x.name] = env.dict2("loc", filename + ":" + x.loc.line, "src", src)
}
return env.dictMap(acc)
}
private Str toSource(DataSpec x, Str[]? file)
{
if (file == null) return ""
// work back to get comment lines
start := x.loc.line - 1
end := start
while (start > 0 && file[start-1].startsWith("//")) start--
// find closing bracket - we assume its a "}" in column zero
for (i := start+1; i<file.size; ++i)
{
line := file[i]
if (line.startsWith("}")) { end = i; break }
}
return file[start..end].join("\n")
}
} |
package mysteryDungeon.cards.Squirtle;
import static mysteryDungeon.MysteryDungeon.makeCardPath;
import com.megacrit.cardcrawl.actions.common.ApplyPowerAction;
import com.megacrit.cardcrawl.actions.common.MakeTempCardInDrawPileAction;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import com.megacrit.cardcrawl.powers.StrengthPower;
import mysteryDungeon.MysteryDungeon;
import mysteryDungeon.abstracts.PokemonCard;
import mysteryDungeon.cards.Status.StatusFreeze;
import mysteryDungeon.characters.Pokemon;
public class SquirtleShellSmash extends PokemonCard {
// TEXT DECLARATION
public static final String ID = MysteryDungeon.makeID(SquirtleShellSmash.class);
private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
public static final String IMG = makeCardPath(SquirtleShellSmash.class);
public static final String NAME = cardStrings.NAME;
public static final String DESCRIPTION = cardStrings.DESCRIPTION;
public static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION;
// /TEXT DECLARATION/
// STAT DECLARATION
private static final CardRarity RARITY = CardRarity.RARE;
private static final CardTarget TARGET = CardTarget.SELF;
private static final CardType TYPE = CardType.POWER;
public static final CardColor COLOR = Pokemon.Enums.SQUIRTLE_BLUE;
private static final int COST = 2;
private static final int BASE_MAGIC_NUMBER = 4;
private static final int BASE_SECOND_MAGIC_NUMBER = 2;
private static final int UPGRADE_MAGIC_NUMBER = 2;
// /STAT DECLARATION/
public SquirtleShellSmash() {
super(ID, NAME, IMG, COST, DESCRIPTION, TYPE, COLOR, RARITY, TARGET);
baseMagicNumber = BASE_MAGIC_NUMBER;
magicNumber = baseMagicNumber;
baseSecondMagicNumber = BASE_SECOND_MAGIC_NUMBER;
secondMagicNumber = baseSecondMagicNumber;
cardsToPreview = new StatusFreeze();
}
// Actions the card should do.
@Override
public void use(AbstractPlayer p, AbstractMonster m) {
addToBot(new ApplyPowerAction(p, p, new StrengthPower(p, magicNumber), magicNumber));
for(int i=0;i<secondMagicNumber;i++)
{
addToBot(new MakeTempCardInDrawPileAction(new StatusFreeze(), 1, true, false, false));
}
}
// Upgraded stats.
@Override
public void upgrade() {
if (!upgraded) {
upgradeName();
upgradeMagicNumber(UPGRADE_MAGIC_NUMBER);
initializeDescription();
}
}
} |
<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class RegistrationController extends AbstractController
{
/**
* @Route("/indexUser", name="for_user")
*/
public function indexUser()
{
return $this->render('user/indexUser.html.twig');
}
/**
* @Route("/listUser", name="display_user")
*/
public function index()
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$user = $this->getDoctrine()->getManager()->getRepository(User::class)->findAll();
return $this->render('user/listUser.html.twig', [
"b"=>$user,
]);
}
private $passwordEncoder;
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
/**
* @Route("/adduser", name="add_user")
*/
public function add_User(Request $request): Response
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Encode the new users password
$user->setPassword($this->passwordEncoder->encodePassword($user, $user->getPassword()));
// Set their role
$user->setRoles(['ROLE_USER']);
// Save
$em = $this->getDoctrine()->getManager();
//var_dump($user);}
$em->persist($user);
$em->flush();
return $this->redirectToRoute('login');
}
return $this->render('registration/registration.html.twig', [
'form_title'=> 'Nouvel Utilisateur',
'form' => $form->createView(),
]);
}
/**
* @Route("/removeUser/{id}", name="supp_user")
*/
public function suppressionUser(User $user): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$em = $this->getDoctrine()->getManager();
$em->remove($user);
$em->flush();
return $this->redirectToRoute('display_user');
}
/**
* @Route("/modifUser/{id}", name="modif_user")
*/
public function modifUser(Request $request,$id): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$user = $this->getDoctrine()->getManager()->getRepository(User::class)->find($id);
$form = $this->createForm(UserType::class,$user);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirectToRoute('display_user');
}
return $this->render('user/updateUser.html.twig',[
'form_title'=> 'Nouvel Utilisateur',
'form'=>$form->createView()]);
}
} |
import { LitElement, html, css } from "lit"
import { query } from "lit/decorators.js";
import { googleIcon, emailIcon, appleIcon, facebookIcon } from "@static/svg/brand-icons"
import { signInPopup } from "/commons/firebase/authentication/signin-providers";
import { Dialogue } from "/components/elements/dia-logue.ts"
import { User, currentUser, Authorization } from "/commons/pubsub/store";
import { doesBrokerExist } from "/commons/firebase/firestore/get-post-data"
export class SignIn extends LitElement {
@query('#signin-dialog')
dialog: Dialogue
@query("#try-again-dialog")
tryAgainDialog: Dialogue
private requestedAuthLevel: Authorization
private returnedAuthLevel: Authorization | undefined
static styles = css`
a {
color: unset;
}
menu-item {
margin: .5em auto;
display: block;
width: 8em;
height: 2em;
box-shadow: var(--small-shadow);
padding: .5em;
}
svg {
margin: .5em;
}
`
render() {return html`
<dia-logue .buttons=${["Cancel"]} id="signin-dialog">
Select your authentication method:
<menu-item disabled=true>
${emailIcon}
Email
</menu-item>
<menu-item @click=${() => this.signIn('google')}>
${googleIcon}
Google
</menu-item>
<menu-item disabled=true>
${appleIcon}
Apple
</menu-item>
<menu-item disabled=true>
${facebookIcon}
Facebook
</menu-item>
<p>Our <a href="/privacy-policy.html">Privacy Policy</a> and <a href="/tos.html">Terms Of Service</a></p>
</dia-logue>
<dia-logue id="try-again-dialog">
<p>
You did not sign in.<br>
Do you want to try again to sign in?<br>
If you cancel, you can not submit your form!
</p>
</dia-logue>
`}
async show(requestedAuthLevel: Authorization = "customer") {
this.returnedAuthLevel = undefined
this.requestedAuthLevel = requestedAuthLevel
await this.dialog.show()
return this.returnedAuthLevel
}
private async authorize (newUser: User) {
const email = newUser.email
const requestedAuthLevel = this.requestedAuthLevel
if (requestedAuthLevel == "broker") {
if (await doesBrokerExist(email)) {
this.returnedAuthLevel = requestedAuthLevel
newUser.authorization = this.returnedAuthLevel
currentUser.pub(newUser)
}
} else if (requestedAuthLevel == "customer") {
this.returnedAuthLevel = requestedAuthLevel
newUser.authorization = this.returnedAuthLevel
currentUser.pub(newUser)
}
}
private async signIn(provider: string) {
const newUser = await signInPopup(provider)
if (!newUser) {
const tryAgain = await this.tryAgainDialog.show()
if (tryAgain == 'Cancel') {
this.dialog.close()
}
} else {
await this.authorize(newUser)
this.dialog.close()
}
}
}
customElements.define('sign-in', SignIn) |
import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Users } from "../data";
import RootLayout from "./MainLayout";
import { AxiosPost } from "../Components/crud";
import Form from "../Components/Layouts/Form";
import FormContainer from "../Components/Layouts/FormContainer";
interface signUpProps {
email: string;
password: string;
alertWarning?: string;
}
function LoginPage() {
const navigate = useNavigate();
const [states, setStates] = useState<signUpProps>({
email: "",
password: "",
alertWarning: "",
});
const formData = [
{
id: 0,
name: "email",
type: "text",
placeholder: "Enter your email",
title: "Email",
setInputState: (value: any) => setStates({ ...states, email: value }),
defaultValue: states.email,
},
{
id: 1,
name: "password",
type: "password",
placeholder: "Enter your password",
title: "Password",
setInputState: (value: any) => setStates({ ...states, password: value }),
defaultValue: states.password,
}
]
const updateStates = (key: string, value: any) => {
setStates({
...states,
[key]: value,
});
};
useEffect(() => {
const user = sessionStorage.getItem("user");
if (user) {
navigate("/dashboard");
}
}, [navigate]);
const submit = async () => {
try {
const res = await AxiosPost("login", {
email: states.email,
password: states.password,
});
if(res.isSuccess) {
sessionStorage.setItem("user", JSON.stringify(res.data));
navigate("/dashboard");
}else{
throw new Error(res.message);
}
}catch (error : any) {
updateStates(`alertWarning`, "Invalid email or password")
console.error(error);
}
};
const validateFields = () => {
states.email.length < 5
? updateStates(`alertWarning`, `Email must be at least 5 characters`)
: states.password.length < 8
? updateStates(`alertWarning`, `Password must be at least 8 characters`)
: submit();
};
return (
<RootLayout>
<FormContainer>
<h1 className="font-bold">Login</h1>
{states.alertWarning?.length !== 0 &&
<div className="bg-red-400 mt-1 text-sm text-white rounded-sm px-1 py-2">{states.alertWarning}</div>}
<Form btnTitle="Login" buttonHandler={validateFields} formData={formData}/>
<div className="text-gray-400 text-sm mt-2">
Don't have an account? <Link to="/register">Sign up</Link>
<div className="mt-2">
<Link to="/reset-password">Forgot password?</Link>
</div>
</div>
</FormContainer>
</RootLayout>
);
}
export default LoginPage; |
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Logo from "./res/logoimg.svg";
import masjidicon from "./res/masjidicon.svg";
import { Link } from "react-router-dom";
import shopicon from "./res/shopicon.svg";
import profileicon from "./res/profile.svg";
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
import NotificationsNoneIcon from "@mui/icons-material/NotificationsNone";
import ChatBubbleOutlineIcon from "@mui/icons-material/ChatBubbleOutline";
import MailOutlineIcon from "@mui/icons-material/MailOutline";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import Cookies from "universal-cookie";
// import FiberManualRecordIcon from '@mui/icons-material/FiberManualRecord';
import AppsIcon from "@mui/icons-material/Apps";
const useStyles = makeStyles((theme) => ({
fullnavbar: {
backgroundColor: "#363B4D",
fontFamily: "'Bungee Inline', cursive",
},
navbar: {
width: "85%",
margin: "0 auto",
[theme.breakpoints.between(320, 768)]: {
width: "90%",
margin: "0 auto",
},
},
icons: {
color: "white",
margin: "auto 0",
display: "flex",
flexDirection: "row",
justifyContent: "space-evenly",
width: "33%",
[theme.breakpoints.between(320, 768)]: {
width: "50%",
},
},
icon: {
[theme.breakpoints.between(320, 768)]: {
fontSize: "16px !important",
},
},
threeicons: {
marginLeft: "auto",
alignItems: "center",
display: "flex",
flexDirection: "row",
justifyContent: "space-evenly",
width: "20%",
[theme.breakpoints.between(320, 768)]: {
width: "40%",
},
},
notification: {
position: "relative",
"&::after": {
content: '" "',
display: "block",
height: 60,
backgroundColor: "red",
width: "8px",
height: "8px",
borderRadius: "50px",
position: "absolute",
top: "4%",
right: "2%",
[theme.breakpoints.between(320, 768)]: {
width: "5px",
height: "5px",
},
[theme.breakpoints.between(1280, 2562)]: {
right: "31%",
},
},
},
status: {
position: "relative",
"&::after": {
content: '" "',
display: "block",
height: 60,
backgroundColor: "#46D490",
width: "12px",
height: "12px",
borderRadius: "50px",
position: "absolute",
top: 0,
right: "2%",
[theme.breakpoints.between(1280, 2562)]: {
right: "31%",
},
},
},
}));
const FeedNav = () => {
const classes = useStyles();
const cookies = new Cookies();
const logoutuser = () => {
cookies.remove("access_token");
window.location.reload();
};
return (
<div className={`w-full h-16 items-center ${classes.fullnavbar}`}>
<div className={`w-full h-16 flex flex-row ${classes.navbar}`}>
<div className={` ${classes.navlogo}`}>
<a href="/">
<img
src={Logo}
alt="logo"
className={`lg:w-12 w-8 lg:mt-0 mt-3 ${classes.logo}`}
/>
</a>
</div>
<div className={`ml-4 items-center ${classes.icons}`}>
<div>
<FavoriteBorderIcon className={`xl:mx-6 ${classes.icon}`} />
</div>
<div className={classes.notification}>
<NotificationsNoneIcon className={`xl:mx-6 ${classes.icon}`} />
</div>
<div>
<ChatBubbleOutlineIcon className={`xl:mx-6 ${classes.icon}`} />
</div>
<div>
<MailOutlineIcon className={`xl:mx-6 ${classes.icon}`} />
</div>
<div>
<AppsIcon className={`xl:mx-6 ${classes.icon}`} />
</div>
</div>
<div className={` flex flex-row items-center ${classes.threeicons}`}>
<div>
<a href="/">
<img
src={masjidicon}
alt="masjid"
className={`h-4 w-4md:h-6 md:w-6 xl:mx-6 ${classes.masjidicon}`}
/>
</a>
</div>
<div>
<a href="/">
<img
src={shopicon}
alt="shop"
className={`h-4 w-4 md:h-5 md:w-5 xl:mx-6 ${classes.shopicon}`}
/>
</a>
</div>
<div className={classes.status}>
<Link to="/userprofilepage">
<img
src={profileicon}
alt="profile"
className={`h-10 w-10 xl:mx-6 border border-green-400 rounded-full ${classes.profileicon}`}
/>
</Link>
</div>
</div>
<div className="mt-3">
<Stack direction="row" spacing={2}>
<Button variant="contained" onClick={logoutuser}>
Logout
</Button>
</Stack>
</div>
</div>
</div>
);
};
export default FeedNav; |
import React, { useState, useEffect } from "react";
import axios from "./api";
import CircularWebcam from "./CircularWebcam";
const Employee = () => {
const [employees, setEmployees] = useState([]);
const [alertInfo, setAlertInfo] = useState({
show: false,
message: "",
type: "",
});
const [showWebcam, setShowWebcam] = useState(false);
const [currentEmployeeId, setCurrentEmployeeId] = useState(null);
useEffect(() => {
fetchEmployees();
}, []);
const handleTrain = (id) => {
setCurrentEmployeeId(id); // Set the current employee ID to know whom to train
setShowWebcam(true); // Show the webcam component for training
};
const handleWebcamResponse = async (response) => {
setShowWebcam(false); // Hide the webcam after receiving the response
if (response.error) {
setAlertInfo({ show: true, message: response.error, type: "error" });
} else {
try {
// Assuming you want to make another API call upon successful initial response
const response = await axios.post("/api/ai/train");
// Check response for success and update state accordingly
if (response.status === 200) { // Assuming 200 OK means success
setAlertInfo({
show: true,
message: "Training successful!",
type: "success",
});
} else {
throw new Error('Training failed with status: ' + response.status);
}
} catch (error) {
setAlertInfo({
show: true,
message: "Training failed: " + error.message,
type: "error"
});
}
}
};
const fetchEmployees = async () => {
try {
const response = await axios.get(
"/api/employees/all"
);
setEmployees(response.data);
} catch (error) {
console.error("Failed to fetch employees", error);
}
};
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const employeeData = {
name: formData.get("name"),
date_of_birth: formData.get("date_of_birth"),
department: formData.get("department"),
address: formData.get("address"),
contact_number: formData.get("contact_number"),
};
try {
await axios.post(
"/api/employees/create",
employeeData
);
setAlertInfo({
show: true,
message: "Employee created successfully!",
type: "success",
});
fetchEmployees();
} catch (error) {
setAlertInfo({
show: true,
message: "Failed to create employee",
type: "error",
});
}
};
const handleDelete = async (id) => {
try {
await axios.delete(`/api/employees/delete/${id}`);
setAlertInfo({
show: true,
message: "Employee deleted successfully!",
type: "success",
});
fetchEmployees();
} catch (error) {
setAlertInfo({
show: true,
message: "Failed to delete employee",
type: "error",
});
}
};
useEffect(() => {
let timer;
if (alertInfo.show) {
timer = setTimeout(() => {
setAlertInfo({ ...alertInfo, show: false });
}, 5000);
}
return () => clearTimeout(timer);
}, [alertInfo]);
return (
<div className="bg-[#032B44] p-6 rounded-lg shadow">
<h1 className="text-xl text-white font-bold mb-6">New Employee</h1>
<form onSubmit={handleSubmit}>
<div className="mb-4">
<label className="text-white block text-sm font-bold mb-2">
Enter the employee name
</label>
<input
type="text"
name="name"
className="shadow appearance-none border rounded w-full py-2 px-3 leading-tight focus:outline-none focus:shadow-outline"
/>
</div>
<div className="mb-4">
<label className="text-white block text-sm font-bold mb-2">Date of Birth</label>
<input
type="date"
name="date_of_birth"
className="shadow appearance-none border rounded w-full py-2 px-3 leading-tight focus:outline-none focus:shadow-outline"
/>
</div>
<div className="mb-4">
<label className="text-white block text-sm font-bold mb-2">Select Department</label>
<select
name="department"
className="shadow border rounded w-full py-2 px-3 leading-tight focus:outline-none focus:shadow-outline"
>
<option value="HR">HR</option>
<option value="IT">IT</option>
<option value="Finance">Finance</option>
<option value="Operations">Operations</option>
<option value="Marketing">Marketing</option>
<option value="Sales">Sales</option>
</select>
</div>
<div className="mb-4">
<label className="text-white block text-sm font-bold mb-2">Address</label>
<input
type="text"
name="address"
className="shadow appearance-none border rounded w-full py-2 px-3 leading-tight focus:outline-none focus:shadow-outline"
/>
</div>
<div className="mb-4">
<label className="text-white block text-sm font-bold mb-2">Contact Number</label>
<input
type="tel"
name="contact_number"
className="shadow appearance-none border rounded w-full py-2 px-3 leading-tight focus:outline-none focus:shadow-outline"
/>
</div>
<button
type="submit"
className="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-2 rounded focus:outline-none focus:shadow-outline transition duration-300 ease-in-out transform hover:-translate-y-1 hover:shadow-lg"
>
Save
</button>
</form>
{alertInfo.show && (
<div
className={`fixed top-5 left-1/2 transform -translate-x-1/2 px-2 py-2 rounded text-white ${
alertInfo.type === "error" ? "bg-red-500" : "bg-green-500"
}`}
>
{alertInfo.message}
</div>
)}
{showWebcam && (
<div
style={{ zIndex: 10 }}
className="fixed top-0 left-0 w-full h-full bg-black bg-opacity-50 flex items-center justify-center"
>
<CircularWebcam
endpointUrl={`/api/ai/upload/${currentEmployeeId}`}
numImages={10}
onResponse={handleWebcamResponse}
buttonLabel={"Train"}
/>
</div>
)}
<div className="mt-8">
<h2 className="text-white text-xl font-bold mb-4">Employees</h2>
<div className="overflow-x-auto">
<table className="text-white min-w-full table-auto">
<thead>
<tr>
<th className="px-2 py-2 text-left">Name</th>
<th className="px-2 py-2 text-left">Date of Birth</th>
<th className="px-2 py-2 text-left">Department</th>
<th className="px-2 py-2 text-left">Address</th>
<th className="px-2 py-2 text-left">Contact Number</th>
<th className="px-2 py-2 text-left">Action</th>
</tr>
</thead>
<tbody>
{employees.map((employee) => (
<tr key={employee.id} className="m-2">
<td className="px-2 py-2 md:px-2 md:py-4">{employee.name}</td>
<td className="px-2 py-2 md:px-2 md:py-4">{employee.date_of_birth}</td>
<td className="px-2 py-2 md:px-2 md:py-4">{employee.department}</td>
<td className="px-2 py-2 md:px-2 md:py-4">{employee.address}</td>
<td className="px-2 py-2 md:px-2 md:py-4">{employee.contact_number}</td>
<td className="px-2 py-2 md:px-2 md:py-4">
<button
onClick={() => handleTrain(employee.id)}
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-1 rounded focus:outline-none focus:shadow-outline transition-transform transform hover:translate-y-1 hover:shadow-lg mr-2"
>
Train
</button>
<button
onClick={() => handleDelete(employee.id)}
className="bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-1 rounded focus:outline-none focus:shadow-outline transition-transform transform hover:translate-y-1 hover:shadow-lg"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
};
export default Employee; |
@extends('layouts.app')
@section('template_title')
Tallere
@endsection
@section('content')
<style>
.row{
justify-content: center;
}
</style>
<div class="container-fluid">
<div class="row">
@if (Auth::user()->rol_id === 1 || Auth::user()->rol_id === 2)
<div class="col-sm-10">
<div class="card">
<div class="card-header list-group-item-warning">
<div style="display: flex; justify-content: space-between; align-items: center;">
<span id="card_title">
<strong>{{ __('Talleres') }}</strong>
</span>
<div class="float-right">
<a href="{{ route('talleres.create') }}" class="btn btn-success btn-sm float-right" data-placement="left">
{{ __('Agregar Taller') }}
</a>
<a href="{{ route('TallerExcel') }}" class="btn btn-warning btn-sm float-right" data-placement="left">
EXCEL
</a>
<a href="{{ route('TalleresPDF') }}" class="btn btn-danger btn-sm float-right" data-placement="left">
PDF
</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead class="thead">
<tr>
<th>Código de Contratación</th>
<th>Nombre Taller</th>
<th>Dirección </th>
<th>Descripción Especialidad</th>
<th>Fecha de Vencimiento </th>
<th>Documento Licitacion </th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
@foreach ($talleres as $tallere)
<tr>
<td>{{ $tallere->Contratacion }}</td>
<td>{{ $tallere->NombreTaller }}</td>
<td>{{ $tallere->DireccionTaller }}</td>
<td>{{ $tallere->DescripcionEsp }}</td>
<td>{{ $tallere->FechaVenTaller }}</td>
<td><a href="/TallerPDF/{{ $tallere->documento }}" class="btn btn-sm btn-info" target="_blank">Ver</a>
<a href="/TallerPDF/{{ $tallere->documento }}" class="btn btn-sm btn-info" download>Descargar</a></td>
<td>
<form action="{{ route('talleres.destroy',$tallere->idTaller) }}" method="POST">
<a class="btn btn-sm btn-warning" href="{{ route('talleres.edit',$tallere->idTaller) }}"><i class="fa fa-fw fa-edit"></i> Editar</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger btn-sm"><i class="fa fa-fw fa-trash"></i> Eliminar</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
@section('js')
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
@if (session('eliminar') == 'ok')
<script>
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
</script>
@endif
<script>
let forms = document.querySelectorAll('form')
forms.forEach(form => {
form.addEventListener('submit', (event) => {
event.preventDefault()
Swal.fire({
title: '¿Está seguro que desea eliminar?',
text: "¡No podrá revertir esto!",
icon: 'warning',
cancelButtonText: "Cancelar",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Eliminar'
}).then((result) => {
if (result.isConfirmed) {
form.submit();
}
})
})
})
</script>
@endsection
</div>
</div>
</div>
{!! $talleres->links() !!}
</div>
@endif
</div>
</div>
@endsection |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Microsoft.Windows.Controls
{
/// <summary>
/// Provides information just before a cell enters edit mode.
/// </summary>
public class DataGridBeginningEditEventArgs : EventArgs
{
/// <summary>
/// Instantiates a new instance of this class.
/// </summary>
/// <param name="column">The column of the cell that is about to enter edit mode.</param>
/// <param name="row">The row container of the cell container that is about to enter edit mode.</param>
/// <param name="editingEventArgs">The event arguments, if any, that led to the cell entering edit mode.</param>
public DataGridBeginningEditEventArgs(DataGridColumn column, DataGridRow row, RoutedEventArgs editingEventArgs)
{
_dataGridColumn = column;
_dataGridRow = row;
_editingEventArgs = editingEventArgs;
}
/// <summary>
/// When true, prevents the cell from entering edit mode.
/// </summary>
public bool Cancel
{
get { return _cancel; }
set { _cancel = value; }
}
/// <summary>
/// The column of the cell that is about to enter edit mode.
/// </summary>
public DataGridColumn Column
{
get { return _dataGridColumn; }
}
/// <summary>
/// The row container of the cell container that is about to enter edit mode.
/// </summary>
public DataGridRow Row
{
get { return _dataGridRow; }
}
/// <summary>
/// Event arguments, if any, that led to the cell entering edit mode.
/// </summary>
public RoutedEventArgs EditingEventArgs
{
get { return _editingEventArgs; }
}
private bool _cancel;
private DataGridColumn _dataGridColumn;
private DataGridRow _dataGridRow;
private RoutedEventArgs _editingEventArgs;
}
} |
/**
* 产品看板-查看系列-系列产品
*/
import React, { useContext, useEffect, useRef } from 'react';
import { Button } from 'antd';
import { Table } from '@/components';
import { connect, routerRedux } from 'dva';
import { errorBoundary } from '@/layouts/ErrorBoundary';
import MyContext from './myContext';
import { handleChangeLabel } from '@/pages/productBillboard/baseFunc';
const SeriesProduct = ({ dispatch, listLoading, productBillboard: { seriesProductData } }) => {
const { proCodeArguments } = useContext(MyContext); // 子组件接受的数据
const totalData = useRef(0); // 页码总数
const dataObj = useRef({}); // 请求参数
const pageNumData = useRef(1); // 当前页面页数
const pageSizeData = useRef(10); // 当前页面展示数量
const proNameData = useRef([]); // 产品全称
const proCodeData = useRef([proCodeArguments]); // 产品代码
const upstairsSeriesData = useRef([]); // 系列名称
const proTypeData = useRef([]); // 产品类型
const investmentManagerData = useRef([]); // 投资经理
const proRiskData = useRef([]); // 风险等级
const proStageData = useRef([]); // 产品阶段
const directionData = useRef(''); // 排序方式
const fieldData = useRef(''); // 排序依据
const batchData = useRef([]); // 批量操作参数
// 跳转产品
const handleGoProduct = record => {
dispatch(
routerRedux.push({
pathname: './productData',
query: { proCode: record.proCode },
}),
);
};
// 表头数据(系列产品)
const columns = [
{
title: '产品全称',
dataIndex: 'proName',
key: 'proName',
sorter: true,
render: (text, record) => {
if (text) {
return (
<Button
type="link"
onClick={() => {
handleGoProduct(record);
}}
>
{text}
</Button>
);
} else return handleChangeLabel(text);
},
width: 400,
},
{
title: '产品代码',
dataIndex: 'proCode',
key: 'proCode',
sorter: true,
},
{
title: '产品简称',
dataIndex: 'proFname',
key: 'proFname',
sorter: true,
},
{
title: '产品阶段',
dataIndex: 'proStage',
key: 'proStage',
sorter: true,
},
{
title: '产品状态',
dataIndex: 'proStatus',
key: 'proStatus',
sorter: true,
},
];
/**
* 更新请求参数(下级系列)
*/
const handleGetDataObj = () => {
dataObj.current = {
pageNum: pageNumData.current, // 当前页
pageSize: pageSizeData.current, // 页展示量
proName: proNameData.current, // 产品名称
proCode: [], // 产品代码
proType: proTypeData.current, // 产品类型
upstairsSeries: [proCodeArguments], // 系列名称
investmentManager: investmentManagerData.current, // 投资经理
proRisk: proRiskData.current, // 风险等级
proStage: proStageData.current, // 产品阶段
direction: directionData.current, // 排序方式
field: fieldData.current, // 排序字段
};
};
/**
*获取系列产品表格
*/
const handleGetSeriesProduct = () => {
handleGetDataObj();
dispatch({
type: 'productBillboard/seriesProductFunc',
payload: dataObj.current,
callback: res => {
totalData.current = res.total;
},
});
};
const handleChangePages = (pages, _, sorter) => {
console.log(pages, _, sorter);
pageNumData.current = pages.current;
pageSizeData.current = pages.pageSize;
fieldData.current = sorter.field;
if (sorter.order === 'ascend') {
directionData.current = 'asc'; // 升序
} else if (sorter.order === 'descend') {
directionData.current = 'desc'; // 降序
} else {
directionData.current = ''; // 默认
}
handleGetSeriesProduct();
};
// 页码属性设置
const paginationProps = {
showQuickJumper: true,
showSizeChanger: true,
current: pageNumData.current,
total: totalData.current,
showTotal: () => {
return `共 ${totalData.current} 条数据`;
},
};
/**
* 渲染表格(下级系列)
*/
const handleAddTable = () => {
if (seriesProductData.rows) {
return (
<Table
bordered
rowKey={record => record.proCode} // key值
pagination={paginationProps}
loading={listLoading} // 加载中效果
style={{ margin: '0 26px 26px 26px', borderRadius: '7px 7px 0 0' }}
columns={columns}
dataSource={seriesProductData.rows}
onChange={handleChangePages}
rowClassName={(record, index) => {
let className = '';
if (index % 2 === 1) className = 'bgcFBFCFF';
return className;
}}
/>
);
}
};
useEffect(() => {
handleGetSeriesProduct();
}, [proCodeArguments]);
return <>{handleAddTable()}</>;
};
const WrappedIndexForm = errorBoundary(
connect(({ productBillboard, loading }) => ({
productBillboard,
listLoading: loading.effects['productBillboard/seriesProductFunc'],
}))(SeriesProduct),
);
export default WrappedIndexForm; |
"use client"
import useCases, { PostIdResponse } from "@/api/useCases"
import { useParams, useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import DOMPurify from "isomorphic-dompurify"
import Image from "next/image"
import PostDeailtsLoader from "@/components/ui/post-detail-loader"
import { AxiosError } from "axios"
import { ArrowLeft } from "lucide-react"
function Post() {
const { id } = useParams()
const [isLoading, setIsLoading] = useState(true)
const [post, setPost] = useState<PostIdResponse | null>(null)
const [error, setError] = useState<{
isFailed: boolean
message: string | undefined
}>({
isFailed: false,
message: "",
})
const router = useRouter()
useEffect(() => {
if (typeof id === "string") {
setIsLoading(true)
useCases.posts
.getOne(id)
.then((response) => {
const postResponse = response.data.data[0]
setPost({
...postResponse,
createdAt: new Date(postResponse.createdAt),
})
})
.catch((err: AxiosError<ApiResponse<string>>) => {
console.log(err)
setError({
isFailed: true,
message: err.response?.data.error[0],
})
})
.finally(() => setIsLoading(false))
}
}, [id])
const sanitizedContent = DOMPurify.sanitize(
post?.content ?? "<p>no content :(</p>",
{
USE_PROFILES: { html: true },
}
)
if (error.isFailed) {
return (
<div className='max-md:mx-0 max-md:w-full w-[700px] flex flex-col min-h-screen bg-white'>
<div className='p-6 ronded-md mt-8'>
<span className='text-3xl font-bold flex justify-center text-gray-400'>
{error.message}
</span>
</div>
</div>
)
}
return isLoading ? (
<PostDeailtsLoader />
) : !isLoading && !post ? (
<p>not found</p>
) : (
post && (
<article className='max-md:mx-0 max-md:w-full w-[700px] bg-white p-16'>
<button
onClick={() => router.back()}
className='bg-secondary text-primary py-1 px-2 text-sm rounded-md flex items-center justify-center gap-1'
>
<ArrowLeft size={18} />
Back
</button>
<div className='max-w-3xl mx-auto'>
{post.headerImage && post.headerImage !== "" && (
<div className='relative'>
<Image
src={post.headerImage}
alt='header image'
className='object-cover w-[720px] h-[250px] mx-auto'
height={250}
width={720}
/>
</div>
)}
<div className='py-2 flex items-center justify-between mb-4'>
<div>
<span className='font-bold text-lg'>
{post.User.name} {post.User.lastname}
</span>
<span className='block text-sm text-gray-400'>
@{post.User.username}
</span>
</div>
<div className='text-xs text-gray-400'>
<span>{post.createdAt.toDateString()}</span>
</div>
</div>
<section
dangerouslySetInnerHTML={{
__html: sanitizedContent,
}}
/>
</div>
</article>
)
)
}
export default Post |
const express = require("express");
const { json } = require("body-parser");
const morgan = require("morgan");
const cors = require("cors");
const session = require('express-session')
const jwt = require('./SRC/helpers/jwt');
const errorHandler = require('./SRC/helpers/error-handler');
const { Database } = require('./SRC/helpers/odbc')
const { connectionString } = require('./SRC/helpers/odbc')
const { login } = require('./SRC/helpers/login')
//swagger Document
const swaggerUi = require('swagger-ui-express');
const fs = require("fs")
const YAML = require('yaml')
const file = fs.readFileSync('./swagger.yaml', 'utf8')
const swaggerDocument = YAML.parse(file)
const app = express();
const port = process.env.PORT || 3000;
//middleware
app.use(json());
app.use(cors());
app.use(morgan("dev"));
app.use(jwt())
app.use(session({secret: process.env.SES_SECRET, resave: true, saveUninitialized: true}))
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
//Routes
app.get('/', (req, res) => {
res.send('Welcome to IBM i NodeJS Template')
})
app.post('/login', login )
app.use('/example', require('./SRC/pages/Example/routes'))
// global error handler
app.use(errorHandler)
//start NodeJS
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
}); |
import { Select, Input, Steps, Button, Spin, notification } from "antd";
import "./index.css";
import FloatLabel from "../../components/float_lable/";
import {useEffect, useMemo, useState, useContext} from "react";
import { useNavigate } from "react-router-dom";
import {useLoginState} from "../../hooks/loginState";
import {Cart, PaymentMethod} from "../../api/types";
import {CartApi} from "../../api/api2/cart";
import PlantCard from "../cart/plant_card";
import Footer from "./footer";
import {PaymentMethodApi} from "../../api/api2/payment_method";
import {OrderApi} from "../../api/api2/order";
import {CartContext} from "../../context/cartContext";
// @ts-ignore
import location from "../../assets/final.json";
const CheckoutTimeLine = () => {
return (
<Steps className="time-line font-opensans"
progressDot
current={1}
size="small"
items={[
{
title: 'Mua sắm',
},
{
title: 'Đặt hàng',
},
{
title: 'Xác nhận',
},
]}
/>
)
}
const ContactForm = ({ email, onChange } : { email: string, onChange?: (s: string) => void }) => {
return (
<>
<div className={"px-6 pt-4"}>
<div className="text-xl font-bold pb-2">
Liên hệ
</div>
<FloatLabel label="Email" name="email" focus={email ? true : undefined}>
<Input
className="text-box text-base"
value={email}
onChange={e => onChange(e.target.value)} />
</FloatLabel>
</div>
</>
)
}
const HalfSelectButton = (props) => {
return (
<div className="w-full">
<FloatLabel label={props.label} name={props.name} focus={props.value ? true : undefined} value={props.value}>
<Select style={{height: "60px", width: "100%", fontSize: "50px"}}
value={props.value}
onChange={e => props.onChange(e)}
options={
props.getData()
}
/>
</FloatLabel>
</div>
)
}
const AddressForm = (props : {
country: string, onCountry?: (c: string) => void,
province: string, onProvince?: (c: string) => void,
city: string, onCity?: (c: string) => void,
ward: string, onWard?: (c: string) => void,
street: string, onStreet?: (c: string) => void,
phone_number: string, onPhone?: (c: string) => void,
extra: string, onExtra?: (c: string) => void,
paymentMethodId: number, onPayment?: (c: number) => void,
onSubmit?: () => void;
payment?: boolean;
}) => {
let [state, user, token] = useLoginState();
let [paymentMethodList, setPaymentMethodList] = useState<PaymentMethod[]>([]);
let load = useMemo(() => {
return () => {
let api = new PaymentMethodApi(token);
api.list()
.then(rs => {
if (rs.success) {
setPaymentMethodList(rs.data);
}
})
}
}, [token]);
let fill = useMemo(() => {
return () => {
if (user?.userAddress) {
let a = user.userAddress;
props.onExtra?.(a.extra);
props.onCity?.(a.city);
props.onProvince?.(a.province);
props.onStreet?.(a.street);
props.onWard?.(a.ward);
props.onCountry?.('VNM');
}
}
}, [user])
useEffect(() => {
load();
}, [token])
useEffect(() => {
fill();
}, [user]);
// @ts-ignore
return (
<div className="space-y-px">
<div className={"px-6 py-4"}>
<div className="text-xl font-bold pb-2">
Địa chỉ giao hàng
</div>
<div className={"grid grid-cols-2 gap-x-6"}>
<div className={"col-span-2"}>
<FloatLabel label="Quốc gia" name="country" value={props.country} focus={props.country ? true : undefined}>
<Select style={{height: "60px", width: "100%"}}
value={props.country}
onChange={e => props.onCountry?.(e)}
options={[{ value: 'VNM', label: 'Việt Nam' }]}
/>
</FloatLabel>
</div>
<HalfSelectButton label="Tỉnh" name="province"
value={props.province} onChange={e => props.onProvince?.(e)}
getData={() => Object.keys(location).map(r => ({
label: r,
value: r
}))}/>
<HalfSelectButton label="Thành phố/Quận" name="city"
value={props.city} onChange={e => props.onCity?.(e)}
getData={
() => props.province
? Object.keys(location[props.province] ?? {}).map(r => ({
label: r,
value: r
}))
: []
}/>
<HalfSelectButton label="Phường" name="ward"
value={props.ward} onChange={e => props.onWard?.(e)}
getData={
() => (props.province && props.city)
? location[props.province]?.[props.city]?.map(r => ({ label: r, value: r })) : []
}
/>
<div className={"col-span-1"}>
<FloatLabel label="Đường" name="street" value={props.street}>
<Input
className="text-box text-xl"
value={props.street}
onChange={e => props.onStreet?.(e.target.value)} />
</FloatLabel>
</div>
<div className={"col-span-2"}>
<FloatLabel label="Địa chỉ cụ thể" name="extraAddress" value={props.extra}>
<Input
className="text-box text-xl"
value={props.extra}
onChange={e => props.onExtra?.(e.target.value)} />
</FloatLabel>
</div>
<FloatLabel label="Số điện thoại" name="phoneNumber" value={props.phone_number}>
<Input
className="text-box text-xl"
value={props.phone_number}
onChange={e => props.onPhone?.(e.target.value)} />
</FloatLabel>
{props.payment !== false && (
<HalfSelectButton label="Phương thức thanh toán" name="paymentMethod"
value={props.paymentMethodId} onChange={e => props.onPayment?.(e)}
// @ts-ignore
getData={() => [{ id: -1, cardNumber: 'Thanh toán khi nhận hàng' }].concat(paymentMethodList).map(r => {
return {
label: r.cardNumber,
value: r.id
}
})}/>
)}
</div>
</div>
<div className={"flex flex-row justify-end"}>
<button
className={"cursor-pointer bg-[#B9E4D5] font-bold text-lg uppercase border-0 mx-6 py-4 px-16 rounded-md"}
onClick={() => props.onSubmit?.()}>
Xác nhận
</button>
</div>
</div>
)
}
const RightHeader = () => {
return (
<div className={"font-opensans opacity-70"}>
<div>
<label className="text-xl font-bold">
30 Day guarantee
</label>
</div>
<div>
<label className="text-lg">
Cây trồng và hạt giống sẽ được bảo quản trong điều kiện tốt nhất khi đang giao. Nếu không, chúng tôi cam kết sẽ thay thế hoàn toàn miễn phí.
</label>
</div>
</div>
)
}
const Checkout = (props) => {
let [loginState, user, token] = useLoginState();
let [cart, setCart] = useState<Cart[]>([]);
let [loading, setLoading] = useState(false);
let f = new Intl.NumberFormat('vi-VN');
let [country, setCountry] = useState('');
let [province, setProvince] = useState('');
let [city, setCity] = useState('');
let [ward, setWard] = useState('');
let [street, setStreet] = useState('');
let [phone_number, setPhone] = useState('');
let [extra, setExtra] = useState('');
let [email, setEmail] = useState('');
let [paymentMethodId, setPayment] = useState(-1);
let cc = useContext(CartContext);
let [noti, ctx] = notification.useNotification();
let fill = useMemo(() => {
return () => {
if (user?.detail) {
setEmail(user?.detail.email);
}
}
}, [user]);
useEffect(() => {
fill();
}, [user])
let load = () => {
setLoading(true);
let c = new CartApi(token);
c.list()
.then(rs => {
if (rs.success) {
setCart(rs.data);
}
})
.finally(() => {
setLoading(false);
});
};
useEffect(() => {
load();
}, [token])
let navigate = useNavigate();
const routeChange = () =>{
navigate(`/success`);
}
return (
<div className="app bg-[#F4F4F4]">
{ctx}
<div className="card font-opensans sticky top-16">
<CheckoutTimeLine/>
<ContactForm email={email} onChange={setEmail}/>
<AddressForm
country={country} onCountry={setCountry}
province={province} onProvince={setProvince}
city={city} onCity={setCity}
ward={ward} onWard={setWard}
street={street} onStreet={setStreet}
phone_number={phone_number} onPhone={setPhone}
extra={extra} onExtra={setExtra}
paymentMethodId={paymentMethodId} onPayment={setPayment}
onSubmit={() => {
let c = new OrderApi(token);
c.createOrder({
country, province, city, ward, street, phoneNumber: phone_number,
extra, email, cart_id: cart.map(r => r.id),
userPaymentMethodId: paymentMethodId
})
.then(rs => {
if (rs.success) {
noti.success({
message: 'Tạo đơn hàng thành công!'
});
navigate('/success');
cc.onChange();
} else {
noti.error({
message: rs.error
});
}
})
.catch(() => {
noti.success({
message: 'Tạo đơn hàng thất bại!'
});
})
.finally(() => {
setLoading(false);
})
}}
/>
</div>
<div className="card font-opensans pb-0">
<RightHeader/>
<br />
<div className={"flex flex-col gap-4 pb-4"}>
{loading && <Spin />}
{!loading && cart.map(c => {
return <PlantCard key={c.id}
cart={c}
onReload={() => {
load();
}}
onDelete={() => {
let cc = new CartApi(token);
cc.delete(c.id)
.then(rs => {
if (rs.success) {
load();
}
})
}}/>
})}
</div>
<div className={"sticky bottom-0 bg-[#F4F4F4]"}>
<Footer cart={cart} />
</div>
</div>
</div>
);
};
export default Checkout;
export { AddressForm, ContactForm }; |
using System;
namespace hw3
{
internal class Program
{
static void Main(string[] args)
{
exercise1();
exercise2();
exercise3();
exercise4();
exercise5();
exercise6();
exercise7();
exercise8();
}
public static void exercise1()
{
Console.WriteLine("\n\nKlavyeden girilen metnin kaç kelimeden oluştuğunu bulan program");
Console.Write("Metin yazınız : ");
string text = controlEmptyInput();
text = text.Trim();
string[] words = text.Split(' ');
Console.WriteLine("{0} kelimeden oluşmaktadır.",words.Length);
}
public static void exercise2()
{
Console.WriteLine("\n\nVerilen bir karakter dizininin substring() metodunu kullanarak string içerisinde arama yapan ve kaç defa geçtiğini bulan program.");
Console.Write("Metin yazınız : ");
string text = controlEmptyInput(); // Input should not be empty
Console.Write("\nArama yap : ");
string search = controlEmptyInput();
int searchLen = search.Length;
int count = 0;
for(int i = 0; i<=text.Length - searchLen; i++)
{
if(text.Substring(i,searchLen) == search)
{
count++;
}
}
Console.WriteLine("{0} kere {1} geçmektedir.", count,search);
}
public static void exercise3()
{
Console.WriteLine("\n\nGirilen sayı çift ise yarısını , tek ise 2 katını alarak ekrana yazdıran program");
Console.Write("Sayı giriniz : ");
int num = controlInputFunc();
int result = (num % 2 == 0) ? num / 2 : num * 2;
Console.WriteLine(result);
}
public static void exercise4()
{
Console.WriteLine("\n\nKlavyeden girilen bir sayının faktöriyelini alan program.");
Console.Write("Sayı giriniz : ");
int num = controlInputFunc(); //Input should be int
int result = 1;
for(int i = 1; i <= num; i++)
{
result *= i;
}
Console.WriteLine(result);
}
public static void exercise5()
{
Console.WriteLine("\n\n1’den başlayıp 200’e kadar klavyeden girilen sayıya bölünen kaç adet sayı olduğunu veren program.");
Console.Write("Sayı giriniz : ");
int num = controlInputFunc(true); // true parameter means "Check the input whether zero or not. If input is zero, ask again the user."
Console.WriteLine("{0} ile bölünen sayılar",num);
for (int i = 1; i <= 200; i++)
{
if(i%num == 0)
{
Console.Write("{0} ",i);
}
}
}
public static void exercise6()
{
Console.WriteLine("\n\nVerilen bir kişi adını bir dizide arayan ve bulunup bulunamadığını belirten program. (Diziyi siz girebilirsiniz ya da kullanıcıdan alabilirsiniz.)");
string[] nameArray = { "Elif", "Feyza", "Ceyda", "Mert", "Aslıhan", "Deniz", "Kenan", "Gürol", "Bade", "Soner", "Meral" };
Console.WriteLine("İsim listesi :");
foreach(string name in nameArray)
Console.Write("{0} ", name);
Console.Write("\nKişi ara : ");
string text = controlEmptyInput();
int result = Array.IndexOf(nameArray, text);
string message = (result == -1) ? "İsim bulunamadı." : "İsim bulundu";
Console.WriteLine(message);
}
public static void exercise7()
{
Console.WriteLine("\n\nDerece olarak verilen sıcaklığı Fahrenheita çeviren program.");
Console.Write("Derece giriniz : ");
int num = controlInputFunc();
double fahrenheit = (num * 1.8) + 32;
Console.WriteLine("{0} derece {1} fahrenheit", num, Math.Round(fahrenheit, 2));
}
public static void exercise8()
{
Console.WriteLine("\n\nGirilen string ifadede boşluk karakterine kadar olan kısmı yazdıran program.");
Console.Write("Metin yazınız : ");
string text = controlEmptyInput();
string[] words = text.Split(' ');
Console.WriteLine("Sonuç : {0}", words[0]);
}
// Input should not be empty in some cases.
public static string controlEmptyInput()
{
string tempStr = Console.ReadLine();
tempStr = tempStr.Trim();
tempStr = (tempStr == "") ? takeInputAgainStr() : tempStr;
return tempStr;
}
public static string takeInputAgainStr()
{
string tempStr;
while (true)
{
Console.Write("Lütfen boş bırakmayın : ");
tempStr = Console.ReadLine();
tempStr = tempStr.Trim();
if (tempStr != "")
{
break;
}
}
return tempStr;
}
public static int controlInputFunc(bool isZeroControl = false)
{
string tempStr = Console.ReadLine();
bool controlInput = Microsoft.VisualBasic.Information.IsNumeric(tempStr); //input should be int, otherwise ask the user again
int num = 0;
if(isZeroControl)
{
num = (controlInput == false || Convert.ToInt32(tempStr) == 0) ? takeInputAgain(isZeroControl) : Convert.ToInt32(tempStr);
}
else
{
num = (controlInput == false) ? takeInputAgain() : Convert.ToInt32(tempStr);
}
return num;
}
//If user enters string but wanted input is int or not zero
public static int takeInputAgain(bool isZeroControl = false)
{
string input;
bool controlInput;
while (true)
{
string message = (isZeroControl) ? "Lütfen 0'dan farklı bir sayı giriniz : " : "Lütfen Sayı giriniz : ";
Console.Write(message);
input = Console.ReadLine();
controlInput = Microsoft.VisualBasic.Information.IsNumeric(input);
if (controlInput)
{
if((isZeroControl && Convert.ToInt32(input) != 0) || !isZeroControl)
{
break;
}
}
}
return Convert.ToInt32(input);
}
}
} |
import 'jest'
import { nanoid } from 'nanoid'
import { sign } from 'jsonwebtoken'
import { ContentType } from 'allure-js-commons'
import { FunctionsClient } from '@supabase/functions-js'
import { Relay, runRelay } from '../relay/container'
import { attach, log } from '../utils/jest-custom-reporter'
import { getCustomFetch } from '../utils/fetch'
const port = 9000
describe('basic tests (hello function)', () => {
let relay: Relay
const jwtSecret = nanoid(10)
const apiKey = sign({ name: 'anon' }, jwtSecret)
beforeAll(async () => {
relay = await runRelay({})
})
afterAll(async () => {
relay && relay.container && (await relay.container.stop())
})
test('invoke hello with auth header', async () => {
/**
* @feature auth
*/
log('create FunctionsClient')
const fclient = new FunctionsClient(`http://0.0.0.0:${relay.container.getMappedPort(port)}`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
})
log('invoke hello')
const { data, error } = await fclient.invoke<string>('hello', {})
log('assert no error')
expect(error).toBeNull()
log(`assert ${data} is equal to 'Hello World'`)
expect(data).toEqual('Hello World')
})
test('invoke hello with setAuth', async () => {
/**
* @feature auth
*/
log('create FunctionsClient')
const fclient = new FunctionsClient(`http://localhost:${relay.container.getMappedPort(port)}`)
attach('setAuth', apiKey, ContentType.TEXT)
fclient.setAuth(apiKey)
log('invoke hello')
const { data, error } = await fclient.invoke<string>('hello', {})
log('assert no error')
expect(error).toBeNull()
log(`assert ${data} is equal to 'Hello World'`)
expect(data).toEqual('Hello World')
})
// no jwt support yet
test.skip('invoke hello with setAuth wrong key', async () => {
/**
* @feature errors
*/
log('create FunctionsClient')
const fclient = new FunctionsClient(`http://localhost:${relay.container.getMappedPort(port)}`)
const wrongKey = sign({ name: 'anon' }, 'wrong_jwt')
attach('setAuth with wrong jwt', wrongKey, ContentType.TEXT)
fclient.setAuth(wrongKey)
log('invoke hello')
const { data, error } = await fclient.invoke<string>('hello', {})
log('check error')
expect(error).not.toBeNull()
expect(error?.message).toEqual('Relay Error invoking the Edge Function')
expect(data).toBeNull()
})
// no jwt support yet
test.skip('invoke hello: auth override by setAuth wrong key', async () => {
/**
* @feature auth
*/
log('create FunctionsClient')
const fclient = new FunctionsClient(`http://localhost:${relay.container.getMappedPort(port)}`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
})
const wrongKey = sign({ name: 'anon' }, 'wrong_jwt')
attach('setAuth with wrong jwt', wrongKey, ContentType.TEXT)
fclient.setAuth(wrongKey)
log('invoke hello')
const { data, error } = await fclient.invoke<string>('hello', {})
log('check error')
expect(error).not.toBeNull()
expect(error?.message).toEqual('Relay Error invoking the Edge Function')
expect(data).toBeNull()
})
test('invoke hello: auth override by setAuth right key', async () => {
/**
* @feature auth
*/
const wrongKey = sign({ name: 'anon' }, 'wrong_jwt')
log('create FunctionsClient with wrong jwt')
const fclient = new FunctionsClient(`http://localhost:${relay.container.getMappedPort(port)}`, {
headers: {
Authorization: `Bearer ${wrongKey}`,
},
})
attach('setAuth with right jwt', apiKey, ContentType.TEXT)
fclient.setAuth(apiKey)
log('invoke hello')
const { data, error } = await fclient.invoke<string>('hello', {})
log('assert no error')
expect(error).toBeNull()
log(`assert ${data} is equal to 'Hello World'`)
expect(data).toEqual('Hello World')
})
test('invoke hello with auth header in invoke', async () => {
/**
* @feature auth
*/
log('create FunctionsClient')
const fclient = new FunctionsClient(`http://localhost:${relay.container.getMappedPort(port)}`)
log('invoke hello with Authorization header')
const { data, error } = await fclient.invoke<string>('hello', {
headers: {
Authorization: `Bearer ${apiKey}`,
},
})
log('assert no error')
expect(error).toBeNull()
log(`assert ${data} is equal to 'Hello World'`)
expect(data).toEqual('Hello World')
})
test('invoke hello with auth header override in invoke', async () => {
/**
* @feature auth
*/
log('create FunctionsClient with wrong jwt')
const fclient = new FunctionsClient(`http://localhost:${relay.container.getMappedPort(port)}`)
const wrongKey = sign({ name: 'anon' }, 'wrong_jwt')
attach('setAuth with wrong jwt', wrongKey, ContentType.TEXT)
fclient.setAuth(wrongKey)
log('invoke hello with Authorization header')
const { data, error } = await fclient.invoke<string>('hello', {
headers: {
Authorization: `Bearer ${apiKey}`,
},
})
log('assert no error')
expect(error).toBeNull()
log(`assert ${data} is equal to 'Hello World'`)
expect(data).toEqual('Hello World')
})
// no jwt yet
test.skip('invoke hello with wrong auth header overridden in invoke', async () => {
/**
* @feature auth
*/
log('create FunctionsClient with wrong jwt')
const fclient = new FunctionsClient(`http://localhost:${relay.container.getMappedPort(port)}`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
})
const wrongKey = sign({ name: 'anon' }, 'wrong_jwt')
log('invoke hello with wrong Authorization header')
const { data, error } = await fclient.invoke<string>('hello', {
headers: {
Authorization: `Bearer ${wrongKey}`,
},
})
log('check error')
expect(error).not.toBeNull()
expect(error?.message).toEqual('Relay Error invoking the Edge Function')
expect(data).toBeNull()
})
it.skip('invoke missing function', async () => {
/**
* @feature errors
*/
log('create FunctionsClient')
const fclient = new FunctionsClient(`http://localhost:${relay.container.getMappedPort(port)}`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
})
log('invoke hello')
const { data, error } = await fclient.invoke<string>('missing', {})
log('check error')
expect(error).not.toBeNull()
expect(error?.message).toEqual('Invalid JWT')
expect(data).toBeNull()
})
test('invoke with custom fetch', async () => {
/**
* @feature fetch
*/
log('create FunctionsClient')
const fclient = new FunctionsClient(`http://localhost:${relay.container.getMappedPort(port)}`, {
customFetch: getCustomFetch(
`http://localhost:${relay.container.getMappedPort(port)}/${'hello'}`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
},
}
),
})
log('invoke hello')
const { data, error } = await fclient.invoke<string>('', {})
log('assert no error')
expect(error).toBeNull()
log(`assert ${data} is equal to 'Hello World'`)
expect(data).toEqual('Hello World')
})
}) |
import os
from Bio import SeqIO
from Bio.Seq import Seq
import pandas as pd
from io import StringIO
from typing import Tuple, List
from itertools import compress
from torch.nn.utils.rnn import pad_sequence
import pytest
# Paths
gencode_source_file_path = '../data/gencode/gencode.v44.pc_transcripts.fa'
# Define bases
bases = ['A', 'T', 'G', 'C', 'N']
# Mapping codons to amino acids, standard capitalised IUPAC codes
# Padded codons (any that include N) are mapped to 'X'
codon_to_aa = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'*', 'TAG':'*',
'TGC':'C', 'TGT':'C', 'TGA':'*', 'TGG':'W',
# Adding the padded codons
'ANN':'X', 'CNN':'X', 'GNN':'X', 'TNN':'X',
'AAN':'X', 'CAN':'X', 'GAN':'X', 'TAN':'X',
'ANA':'X', 'CNA':'X', 'GNA':'X', 'TNA':'X',
'ANC':'X', 'CNC':'X', 'GNC':'X', 'TNC':'X',
'ANG':'X', 'CNG':'X', 'GNG':'X', 'TNG':'X',
'ANT':'X', 'CNT':'X', 'GNT':'X', 'TNT':'X',
'AGN':'X', 'CGN':'X', 'GGN':'X', 'TGN':'X',
'ATN':'X', 'CTN':'X', 'GTN':'X', 'TTN':'X',
'ACN':'X', 'CCN':'X', 'GCN':'X', 'TCN':'X',
'NAA':'X', 'NAC':'X', 'NAG':'X', 'NAT':'X',
'NCA':'X', 'NCC':'X', 'NCG':'X', 'NCT':'X',
'NGA':'X', 'NGC':'X', 'NGG':'X', 'NGT':'X',
'NTA':'X', 'NTC':'X', 'NTG':'X', 'NTT':'X',
'NAN':'X', 'NCN':'X', 'NGN':'X', 'NTN':'X',
'NNN':'X'
}
# Mapping amino acids to integers, 1-20
# Unknown Amino Acid ('X') is mapped to '0'
# Stop codon ('*') is mapped to '21'
aa_to_int = {
'A':1, 'C':2, 'D':3, 'E':4,
'F':5, 'G':6, 'H':7, 'I':8,
'K':9, 'L':10, 'M':11, 'N':12,
'P':13, 'Q':14, 'R':15, 'S':16,
'T':17, 'V':18, 'W':19, 'Y':20,
# Unknown Amino Acid
'X':0, '*':21
}
# Mapping codons to ints, 1-64
# Padded codons (any that include N) are mapped to '0'
codon_to_int = {
'ATA':1, 'ATC':2, 'ATT':3, 'ATG':4,
'ACA':5, 'ACC':6, 'ACG':7, 'ACT':8,
'AAT':9, 'AAC':10, 'AAA':11, 'AAG':12,
'AGA':13, 'AGC':14, 'AGG':15, 'AGT':16,
'CTA':17, 'CTC':18, 'CTT':19, 'CTG':20,
'CCA':21, 'CCC':22, 'CCG':23, 'CCT':24,
'CAT':25, 'CAC':26, 'CAA':27, 'CAG':28,
'CGA':29, 'CGC':30, 'CGG':31, 'CGT':32,
'GTA':33, 'GTC':34, 'GTT':35, 'GTG':36,
'GCA':37, 'GCC':38, 'GCG':39, 'GCT':40,
'GAT':41, 'GAC':42, 'GAA':43, 'GAG':44,
'GGA':45, 'GGC':46, 'GGG':47, 'GGT':48,
'TCA':49, 'TCC':50, 'TCT':51, 'TCG':52,
'TTA':53, 'TTC':54, 'TTT':55, 'TTG':56,
'TAT':57, 'TAC':58, 'TAA':59, 'TAG':60,
'TGA':61, 'TGC':62, 'TGG':63, 'TGT':64,
# Adding the padded codons
'ANN':0, 'CNN':0, 'GNN':0, 'TNN':0,
'AAN':0, 'CAN':0, 'GAN':0, 'TAN':0,
'ANA':0, 'CNA':0, 'GNA':0, 'TNA':0,
'ANC':0, 'CNC':0, 'GNC':0, 'TNC':0,
'ANG':0, 'CNG':0, 'GNG':0, 'TNG':0,
'ANT':0, 'CNT':0, 'GNT':0, 'TNT':0,
'AGN':0, 'CGN':0, 'GGN':0, 'TGN':0,
'ATN':0, 'CTN':0, 'GTN':0, 'TTN':0,
'ACN':0, 'CCN':0, 'GCN':0, 'TCN':0,
'NAA':0, 'NAC':0, 'NAG':0, 'NAT':0,
'NCA':0, 'NCC':0, 'NCG':0, 'NCT':0,
'NGA':0, 'NGC':0, 'NGG':0, 'NGT':0,
'NTA':0, 'NTC':0, 'NTG':0, 'NTT':0,
'NAN':0, 'NCN':0, 'NGN':0, 'NTN':0,
'NNN':0
}
# 0
def load_src_tgt_sequences(source_file: str, max_seq_length: int = 120000) -> Tuple[List[List[int]], List[List[int]]]:
"""
Load source and target sequences from a FASTA file and encode them into numerical sequences.
Args:
source_file (str): Path to the source FASTA file.
max_seq_length (int): Maximum length of the target sequences in nucleotides.
Returns:
Tuple of two numpy arrays:
- aa_enc: Encoded amino acid sequences.
- codon_enc: Encoded codon sequences.
"""
# Input validation
if not os.path.exists(source_file):
raise FileNotFoundError(f"Source file {source_file} not found")
df = parse_fasta(source_file)
# Data extraction
df = extract_cds_columns(df)
aa_seqs, codon_seqs = extract_sequences(df)
# Filter sequences based on max_seq_length
valid_seq_mask = [(len(seq) * 3 <= max_seq_length) for seq in codon_seqs]
aa_seqs = list(compress(aa_seqs, valid_seq_mask))
codon_seqs = list(compress(codon_seqs, valid_seq_mask))
# Sequence encoding
aa_enc = encode_amino_sequence(aa_seqs)
codon_enc = encode_codon_sequence(codon_seqs)
return aa_enc, codon_enc
# 1
def parse_fasta(fasta_file):
records = list(SeqIO.parse(fasta_file, "fasta"))
parsed_records = []
for record in records:
header_parts = record.description.split("|")
transcript_info = {
"transcript_id": header_parts[0],
"gene_id": header_parts[1],
"manual_gene_id": header_parts[2],
"manual_transcript_id": header_parts[3],
"gene_symbol_variant": header_parts[4],
"gene_name": header_parts[5],
"sequence_length": int(header_parts[6]),
"UTR5": header_parts[7].split(":")[1] if len(header_parts) > 7 and "UTR5" in header_parts[7] else None,
"CDS": header_parts[8].split(":")[1] if len(header_parts) > 8 and "CDS" in header_parts[8] else None,
"UTR3": header_parts[9].split(":")[1] if len(header_parts) > 9 and "UTR3" in header_parts[9] else None,
"sequence": str(record.seq)
}
parsed_records.append(transcript_info)
df = pd.DataFrame(parsed_records)
return df
# 2
def extract_cds_columns(df):
"""Extract CDS start/end columns"""
# Split the 'CDS' column once
cds_splits = df['CDS'].str.split('-')
# Check if all rows have exactly two parts after splitting
valid_format = cds_splits.apply(lambda x: len(x) == 2 if x else False)
# For rows with the valid 'start-end' format
df.loc[valid_format, 'cds_start'] = cds_splits[valid_format].str[0].astype(int)
df.loc[valid_format, 'cds_end'] = cds_splits[valid_format].str[1].astype(int)
# For rows without the valid 'start-end' format or if 'CDS' is not found
default_indices = ~valid_format | df['CDS'].isna()
df.loc[default_indices, 'cds_start'] = 1
df.loc[default_indices, 'cds_end'] = df.loc[default_indices, 'sequence'].str.len()
# Ensure 'cds_start' and 'cds_end' are integers
df['cds_start'] = df['cds_start'].astype(int)
df['cds_end'] = df['cds_end'].astype(int)
valid_rows = (df['cds_start'] > 0) & (df['cds_end'] <= df['sequence'].str.len())
valid_df = df[valid_rows]
return valid_df
# Legacy extract CDS
'''
def extract_cds_columns(df):
"""Extract CDS start/end columns"""
# Split the 'CDS' column once
cds_splits = df['CDS'].str.split('-')
# Check if all rows have exactly two parts after splitting
valid_format = cds_splits.apply(lambda x: len(x) == 2 if x else False)
if not all(valid_format):
# Find and report problematic rows
problem_rows = df[~valid_format]
problem_indices = problem_rows.index.tolist()
problem_values = problem_rows['CDS'].tolist()
raise ValueError(f"Error in parsing 'CDS' column. Rows {problem_indices} have problematic values: {problem_values}. Ensure all rows have the format 'start-end'.")
try:
df['cds_start'] = cds_splits.str[0].astype(int)
df['cds_end'] = cds_splits.str[1].astype(int)
except TypeError as e:
# Catch specific exception and raise with additional information
raise ValueError(f"Error converting CDS values to integers. Original error: {e}")
valid_rows = (df['cds_start'] > 0) & (df['cds_end'] <= df['sequence'].str.len())
valid_df = df[valid_rows]
return valid_df
'''
# 3
# 3.1 Codons -> amino acids
def translate_codons_to_amino_acids(codon_seqs: List[str]) -> List[str]:
"""
Translate a list of codon sequences to their corresponding amino acid sequences.
If the codon sequence length isn't a multiple of 3, it will be padded with 'N'
to the nearest multiple of 3.
Parameters:
- codon_seqs (List[str]): A list of codon sequences.
Each codon is expected to be a triplet of nucleotide bases.
Returns:
- List[str]: A list of amino acid sequences corresponding to the input codon sequences.
Raises:
- ValueError: If a provided codon is not recognized.
"""
codon_to_aa = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'*', 'TAG':'*',
'TGC':'C', 'TGT':'C', 'TGA':'*', 'TGG':'W',
# Adding the padded codons
'ANN':'X', 'CNN':'X', 'GNN':'X', 'TNN':'X',
'AAN':'X', 'CAN':'X', 'GAN':'X', 'TAN':'X',
'ANA':'X', 'CNA':'X', 'GNA':'X', 'TNA':'X',
'ANC':'X', 'CNC':'X', 'GNC':'X', 'TNC':'X',
'ANG':'X', 'CNG':'X', 'GNG':'X', 'TNG':'X',
'ANT':'X', 'CNT':'X', 'GNT':'X', 'TNT':'X',
'AGN':'X', 'CGN':'X', 'GGN':'X', 'TGN':'X',
'ATN':'X', 'CTN':'X', 'GTN':'X', 'TTN':'X',
'ACN':'X', 'CCN':'X', 'GCN':'X', 'TCN':'X',
'NAA':'X', 'NAC':'X', 'NAG':'X', 'NAT':'X',
'NCA':'X', 'NCC':'X', 'NCG':'X', 'NCT':'X',
'NGA':'X', 'NGC':'X', 'NGG':'X', 'NGT':'X',
'NTA':'X', 'NTC':'X', 'NTG':'X', 'NTT':'X',
'NAN':'X', 'NCN':'X', 'NGN':'X', 'NTN':'X',
'NNN':'X'
}
result = []
for seq in codon_seqs:
# Pad with 'N' if not multiple of 3
while len(seq) % 3 != 0:
seq += 'N'
amino_acid_seq = ""
for i in range(0, len(seq), 3):
codon = seq[i:i+3]
if codon not in codon_to_aa:
raise ValueError(f"Unrecognized codon: {codon}")
amino_acid_seq += codon_to_aa[codon]
result.append(amino_acid_seq)
return result
# 3.2 Amino acids -> ints
def translate_amino_acids_to_ints(aa_seqs: List[str]) -> List[List[int]]:
"""
Translate a list of amino acid sequences to their corresponding integer sequences.
Parameters:
- aa_seqs (List[str]): A list of amino acid sequences.
Each amino acid is represented as a single character.
Returns:
- List[List[int]]: A list of integer sequences corresponding to the input amino acid sequences.
Raises:
- ValueError: If a provided amino acid is not recognized.
"""
# Mapping amino acids to integers, 1-20
# Unknown Amino Acid ('X') is mapped to '0'
# Stop codon ('*') is mapped to '21'
aa_to_int = {
'A': 1, 'C': 2, 'D': 3, 'E': 4,
'F': 5, 'G': 6, 'H': 7, 'I': 8,
'K': 9, 'L':10, 'M':11, 'N':12,
'P':13, 'Q':14, 'R':15, 'S':16,
'T':17, 'V':18, 'W':19, 'Y':20,
# Unknown and stop codon
'X': 0, '*':21
}
result = []
for seq in aa_seqs:
int_seq = []
for aa in seq:
if aa not in aa_to_int:
raise ValueError(f"Unrecognized amino acid: {aa}")
int_seq.append(aa_to_int[aa])
result.append(int_seq)
return result
# 3.3 Codons -> ints
def translate_codons_to_ints(codon_seqs: List[str]) -> List[int]:
"""
Translate a list of codon sequences to their corresponding integer values.
If the codon sequence length isn't a multiple of 3, it will be padded with 'N'
to the nearest multiple of 3.
Parameters:
- codon_seqs (List[str]): A list of codon sequences.
Each codon is expected to be a triplet of nucleotide bases.
Returns:
- List[int]: A list of integer values corresponding to the input codon sequences.
Raises:
- ValueError: If a provided codon is not recognized.
"""
codon_to_int = {
'ATA': 1, 'ATC': 2, 'ATT': 3, 'ATG': 4,
'ACA': 5, 'ACC': 6, 'ACG': 7, 'ACT': 8,
'AAT': 9, 'AAC':10, 'AAA':11, 'AAG':12,
'AGA':13, 'AGC':14, 'AGG':15, 'AGT':16,
'CTA':17, 'CTC':18, 'CTT':19, 'CTG':20,
'CCA':21, 'CCC':22, 'CCG':23, 'CCT':24,
'CAT':25, 'CAC':26, 'CAA':27, 'CAG':28,
'CGA':29, 'CGC':30, 'CGG':31, 'CGT':32,
'GTA':33, 'GTC':34, 'GTT':35, 'GTG':36,
'GCA':37, 'GCC':38, 'GCG':39, 'GCT':40,
'GAT':41, 'GAC':42, 'GAA':43, 'GAG':44,
'GGA':45, 'GGC':46, 'GGG':47, 'GGT':48,
'TCA':49, 'TCC':50, 'TCT':51, 'TCG':52,
'TTA':53, 'TTC':54, 'TTT':55, 'TTG':56,
'TAT':57, 'TAC':58, 'TAA':59, 'TAG':60,
'TGA':61, 'TGC':62, 'TGG':63, 'TGT':64,
# Adding the padded codons
'ANN':0, 'CNN':0, 'GNN':0, 'TNN':0,
'AAN':0, 'CAN':0, 'GAN':0, 'TAN':0,
'ANA':0, 'CNA':0, 'GNA':0, 'TNA':0,
'ANC':0, 'CNC':0, 'GNC':0, 'TNC':0,
'ANG':0, 'CNG':0, 'GNG':0, 'TNG':0,
'ANT':0, 'CNT':0, 'GNT':0, 'TNT':0,
'AGN':0, 'CGN':0, 'GGN':0, 'TGN':0,
'ATN':0, 'CTN':0, 'GTN':0, 'TTN':0,
'ACN':0, 'CCN':0, 'GCN':0, 'TCN':0,
'NAA':0, 'NAC':0, 'NAG':0, 'NAT':0,
'NCA':0, 'NCC':0, 'NCG':0, 'NCT':0,
'NGA':0, 'NGC':0, 'NGG':0, 'NGT':0,
'NTA':0, 'NTC':0, 'NTG':0, 'NTT':0,
'NAN':0, 'NCN':0, 'NGN':0, 'NTN':0,
'NNN':0
}
result = []
for seq in codon_seqs:
# Pad with 'N' if not multiple of 3
while len(seq) % 3 != 0:
seq += 'N'
int_values = []
for i in range(0, len(seq), 3):
codon = seq[i:i+3]
if codon not in codon_to_int:
raise ValueError(f"Unrecognized codon: {codon}")
int_values.append(codon_to_int[codon])
result.append(int_values)
return result
# 4
def extract_sequences(df) -> Tuple[List[List[int]], List[List[int]]]:
"""
Extracts amino acid and codon sequences from the 'sequence' field in the DataFrame.
Args:
df: A pandas DataFrame containing the 'sequence', 'cds_start', and 'cds_end' columns.
Returns:
A tuple containing two lists:
- aa_seqs_int: A list of amino acid sequences as integers.
- codon_seqs_int: A list of codon sequences as integers.
"""
aa_seqs_int = [] # For storing amino acid sequences as integers
codon_seqs_int = [] # For storing codon sequences as integers
for _, row in df.iterrows():
seq = row['sequence'][row['cds_start']-1:row['cds_end']] # -1 because Python is 0-based
# Extracting codons
codons = [seq[i:i+3] for i in range(0, len(seq), 3) if 1 <= len(seq[i:i+3]) <= 3]
# Getting the amino acid integer sequences
aa_seqs = translate_codons_to_amino_acids(codons)
aa_ints = [aa for seq in translate_amino_acids_to_ints(aa_seqs) for aa in seq]
# Getting the codon integer sequences
codon_ints = [codon for seq in translate_codons_to_ints(codons) for codon in seq]
codon_seqs_int.append(codon_ints)
aa_seqs_int.append(aa_ints)
return aa_seqs_int, codon_seqs_int
# 5 Dummy encode functions
def encode_amino_sequence(aa_seqs: List[List[int]]) -> List[List[int]]:
return aa_seqs
def encode_codon_sequence(codon_seqs: List[List[int]]) -> List[List[int]]:
return codon_seqs
# Legacy encode functions
'''
# 4
def encode_amino_acids(aa_seqs: List[str]) -> List[List[int]]:
"""Encodes a list of amino acid sequences into their corresponding integer sequences."""
return translate_amino_acids_to_ints(aa_seqs)
def encode_codons(codon_seqs: List[str]) -> List[List[int]]:
"""Encodes a list of codon sequences into their corresponding integer sequences."""
return translate_codons_to_ints(codon_seqs)
def encode_amino_sequence(aa_seqs):
"""Integer encode amino acid sequences"""
unique_amino_acids = sorted(set(codon_to_aa.values()))
aa_to_int = {aa: i for i, aa in enumerate(unique_amino_acids)}
if isinstance(aa_seqs, str):
aa_seqs = [aa_seqs]
if not all(isinstance(seq, str) for seq in aa_seqs):
raise TypeError("All sequences should be of type string")
encoded_aa = []
for seq in aa_seqs:
encoded_seq = [aa_to_int.get(aa, len(aa_to_int)) for aa in seq] # use the next integer for unknown AAs
encoded_aa.append(encoded_seq)
return encoded_aa
# 5
def encode_codon_sequence(codon_seqs):
"""Integer encode codon sequences"""
unique_codons = sorted(set(codon_to_aa.keys()))
codon_to_int = {codon: i for i, codon in enumerate(unique_codons)}
if isinstance(codon_seqs, str):
codon_seqs = [codon_seqs]
if not all(isinstance(seq, str) for seq in codon_seqs):
raise TypeError("All sequences should be of type string (Encode Codon error)")
encoded_codons = []
for seq in codon_seqs:
encoded_seq = []
for i in range(0, len(seq), 3):
codon = seq[i:i+3]
encoded_seq.append(codon_to_int.get(codon, len(codon_to_int))) # use the next integer for unknown codons
encoded_codons.append(encoded_seq)
return encoded_codons
'''
# 6
def collate_fn(batch):
src_sequences, tgt_sequences = zip(*batch)
# Padding sequences
src_sequences = pad_sequence(src_sequences, batch_first=True)
tgt_sequences = pad_sequence(tgt_sequences, batch_first=True)
return src_sequences, tgt_sequences
if __name__ == "__main__":
exit()
# Parse the FASTA file
data_df = parse_fasta(gencode_source_file_path)
print("\nParsed FASTA Data:")
print(data_df.head())
# Extract coding sequences
cds_sequences = extract_cds_sequences(data_df)
print("\nCDS Sequences (first 5):")
print(cds_sequences[:5])
# Convert to amino acids
aa_sequences = extract_amino_acids_from_codons(cds_sequences)
print("\nAmino Acid Sequences (first 5):")
print(aa_sequences[:5]) |
import request from 'supertest';
import app from '../../App';
it('should return the details of the current user', async () => {
const signup = await request(app)
.post('/api/users/signup')
.send({
email: 'test@test.com',
password: 'mypassword',
})
.expect(201);
const cookie = signup.get('Set-Cookie');
const response = await request(app)
.get('/api/users/currentuser')
.set('Cookie', cookie)
.send()
.expect(200);
expect(response.body.currentUser.email).toEqual('test@test.com');
});
it('should return null if user is not logged in', async () => {
const response = await request(app)
.get('/api/users/currentuser')
.send()
.expect(200);
expect(response.body.currentUser).toEqual(null);
}); |
#ifndef CONCURRENTQUEUE_H
#define CONCURRENTQUEUE_H
#include <queue>
#include <optional>
#include <mutex>
#include <condition_variable>
template<typename T, class Container = std::deque<T>>
class [[deprecated("Use lca::utils::ConcurrentQueue instead. This class will be deleted after 2022-01-31")]] ConcurrentQueue
{
public:
ConcurrentQueue() = default;
ConcurrentQueue(const ConcurrentQueue& other);
ConcurrentQueue<T>& operator=(const ConcurrentQueue& other);
~ConcurrentQueue() = default;
void push(const T& object);
void push(T&& object);
T waitingFrontPop();
std::optional<T> tryFrontPop();
bool empty() const;
private:
mutable std::mutex mMutex;
std::queue<T, Container> mQueue;
std::condition_variable mConVar;
};
template<typename T, class Container>
ConcurrentQueue<T, Container>::ConcurrentQueue(const ConcurrentQueue& other)
{
std::scoped_lock scopedLock(other.mMutex);
mQueue = other.mQueue;
}
template<typename T, class Container>
ConcurrentQueue<T>& ConcurrentQueue<T, Container>::operator=(const ConcurrentQueue& other)
{
// Check for self assigment
if (this != &other)
{
// Lock both mutexes at the same time
std::unique_lock unique_lock(mMutex, std::defer_lock);
std::unique_lock other_unique_lock(other.mMutex, std::defer_lock);
std::lock(unique_lock, other_unique_lock);
mQueue = other.mQueue;
}
return *this;
}
template<typename T, class Container>
void ConcurrentQueue<T, Container>::push(const T& object)
{
std::unique_lock uniqueLock(mMutex);
const bool was_empty = mQueue.empty();
mQueue.push(object);
// If the queue was empty there may be some consumers waiting for data.
if (was_empty)
{
// Unlock mutex before notifying so waiting threads do not have to wait for the mutex after being woken.
uniqueLock.unlock();
mConVar.notify_one();
}
}
template<typename T, class Container>
void ConcurrentQueue<T, Container>::push(T&& object)
{
std::unique_lock uniqueLock(mMutex);
const bool was_empty = mQueue.empty();
mQueue.push(std::move(object));
// If the queue was empty there may be some consumers waiting for data.
if (was_empty)
{
// Unlock mutex before notifying so waiting threads do not have to wait for the mutex after being woken.
uniqueLock.unlock();
mConVar.notify_one();
}
}
template<typename T, class Container>
T ConcurrentQueue<T, Container>::waitingFrontPop()
{
std::unique_lock uniqueLock(mMutex);
mConVar.wait(uniqueLock, [this] {return !mQueue.empty(); });
T object = std::move(mQueue.front());
mQueue.pop();
return object;
}
template<typename T, class Container>
std::optional<T> ConcurrentQueue<T, Container>::tryFrontPop()
{
std::scoped_lock scopedLock(mMutex);
if (!mQueue.empty())
{
T object = std::move(mQueue.front());
mQueue.pop();
return object;
}
else
{
return std::nullopt;
}
}
template<typename T, class Container>
bool ConcurrentQueue<T, Container>::empty() const
{
std::scoped_lock scopedLock(mMutex);
return mQueue.empty();
}
#endif // Header Guard |
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="rrn:org.xcbl:schemas/xcbl/v4_0/ordermanagement/v1_0/ordermanagement.xsd" xmlns:core="rrn:org.xcbl:schemas/xcbl/v4_0/core/core.xsd" xmlns:dgs="http://www.w3.org/2000/09/xmldsig#" targetNamespace="rrn:org.xcbl:schemas/xcbl/v4_0/ordermanagement/v1_0/ordermanagement.xsd" elementFormDefault="qualified">
<xsd:import namespace="rrn:org.xcbl:schemas/xcbl/v4_0/core/core.xsd" schemaLocation="../../core/core.xsd"/>
<xsd:annotation>
<xsd:documentation xml:lang="en">
XML Common Business Library 4.0
Copyright 2002 Commerce One, Inc.
Permission is granted to use, copy, modify and distribute the
DTD's, schemas and modules in the Commerce One XML Common Business
Library Version 4.0 subject to the terms and conditions specified
at http://www.xcbl.org/license.html
</xsd:documentation>
</xsd:annotation>
<xsd:complexType name="OrderStatusRequestHeaderType">
<xsd:annotation>
<xsd:documentation>holds all <!--code-->OrderStatusRequest<!--/code--> header-level information. This
element occurs once within the document.</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<xsd:element name="OrderStatusRequestID" type="xsd:string">
<xsd:annotation>
<xsd:documentation>contains a reference number to identify the <!--code-->OrderStatusRequest<!--/code-->
document. This value can be used for internal audit purposes. Possible values for the ID are GUIDs, internal
tracking numbers, or system generated numbers. This reference number should not be needed for document correlation purposes since this is a
synchronous transaction. It is valid for the OrderStatusRequestID and the OrderStatusID from the <!--code-->OrderStatusResult<!--/code--> to be the same
value. For applications that do not require this type of document identification, a dummy value can be used as a default for the OrderStatusRequestID.</xsd:documentation>
</xsd:annotation>
</xsd:element>
<xsd:element name="OrderStatusIssueDate" type="xsd:dateTime">
<xsd:annotation>
<xsd:documentation>indicates the date the <!--code-->OrderStatusRequest<!--/code--> is
transmitted.</xsd:documentation>
</xsd:annotation>
</xsd:element>
<xsd:element name="BuyerParty" type="core:PartyType">
<xsd:annotation>
<xsd:documentation>contains the information for the party purchasing the goods.</xsd:documentation>
</xsd:annotation>
</xsd:element>
<xsd:element name="SellerParty" type="core:PartyType">
<xsd:annotation>
<xsd:documentation>identifies the party selling the goods.</xsd:documentation>
</xsd:annotation>
</xsd:element>
<xsd:element minOccurs="0" name="OrderStatusLanguage" type="core:LanguageType">
<xsd:annotation>
<xsd:documentation>identifies the language for <!--code-->OrderStatusRequest<!--/code-->.</xsd:documentation>
</xsd:annotation>
</xsd:element>
<xsd:element minOccurs="0" name="OrderStatusRequestNote" type="xsd:string">
<xsd:annotation>
<xsd:documentation>contains any free-form text pertinent to the entire
<!--code-->OrderStatusRequest<!--/code-->. This element may contain notes or any other similar information that
is not contained explicitly in another structure. It should not be assumed that the receiving application is capable of
doing more than storing and/or displaying this information. </xsd:documentation>
</xsd:annotation>
</xsd:element>
<xsd:element minOccurs="0" name="ListOfStructuredNote" type="core:ListOfStructuredNoteType">
<xsd:annotation>
<xsd:documentation>contains one or more structured notes that allow you to provide
notes that are more than a simple free-text field. such notes may include the
message text, or this text may be referenced with an external identifier or a
URL. An agency may be specified, and is needed in the case where an ID has been
provided for a note that is either included in-line or referenced. This field
is often used to include references to centrally stored clauses in contracts
that are required to appear within business documents.</xsd:documentation>
</xsd:annotation>
</xsd:element>
<xsd:element minOccurs="0" name="OrderStatusListOfAttachment" type="core:ListOfAttachmentType">
<xsd:annotation>
<xsd:documentation>contains a list of attachments applicable to the entire <!--code-->OrderStatusRequest<!--/code-->.
The information is
not specific to a particular line item or package, unless specifically noted.</xsd:documentation>
</xsd:annotation>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:schema> |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<title>Thanh toán</title>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
crossorigin="anonymous"
/>
<!-- Font awesome -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<!-- Custom css - Các file css do chúng ta tự viết -->
<link rel="stylesheet" th:href="@{/css/checkout.css}" type="text/css" />
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js"
integrity="sha512-2rNj2KJ+D8s1ceNasTIex6z4HWyOnEYLVC3FigGOmyQCZc2eBXKgOxQmo3oKLHyfcj53uz4QMsRCWNbLd32Q1g=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"
integrity="sha512-pumBsjNRGGqkPzKHndZMaAG+bir374sORyzM3uulLV14lN5LyykqNk8eEeUlUkB3U0M4FApyaHraT65ihJhDpQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js"
integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V"
crossorigin="anonymous"
></script>
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 300px;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<!-- header -->
<nav class="navbar navbar-expand-md navbar-dark sticky-top nav-header">
<div class="container">
<div class="navbar-collapse collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" th:href="@{/}">Trang chủ <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="products.html">Sự kiện</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Khuyến mãi</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Liên hệ</a>
</li>
</ul>
<!-- <form class="form-inline mt-2 mt-md-0" method="get" action="search.html">
<input class="form-control mr-sm-2" type="text" placeholder="Tìm kiếm" aria-label="Search"
name="keyword_tensanpham">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Tìm kiếm</button>
</form> -->
</div>
<ul class="navbar-nav px-3 nav-header1" >
<li sec:authorize = "hasRole('USER')">
<a th:href="@{/cart}" style="text-decoration: none; color: var(--bs-nav-link-color)">
Giỏ hàng/<span th:text="${cartInfo.cartLines.size()}"></span> sản phẩm</a></li>
<li sec:authorize = "isAuthenticated()">
<a th:href="@{/logout}" style="text-decoration: none; color: var(--bs-nav-link-color)">
Đăng xuất</a></li>
</ul>
</div>
</nav>
<!-- end header -->
<section class="bg-light py-5">
<div class="container">
<div class="row">
<div class="col-xl-8 col-lg-8 mb-4">
<div class="card mb-4 border shadow-0"></div>
<!-- Checkout -->
<form th:action="@{/confirm}" method="POST">
<div class="card shadow-0 border">
<div class="p-4">
<h5 class="card-title mb-3">Thông tin khách hàng</h5>
<div class="row">
<div class="col-6 mb-3">
<p class="mb-0">Họ tên</p>
<div class="form-outline">
<input
type="text"
id="typeText"
th:value="${cartInfo.customer.fullName}"
class="form-control"
disabled="disabled"
/>
</div>
</div>
<div class="col-6 mb-3">
<p class="mb-0">SĐT</p>
<div class="form-outline">
<input type="tel" id="typePhone" th:value="${cartInfo.customer.phone}" class="form-control" disabled="disabled"/>
</div>
</div>
<div class="col-6 mb-3">
<p class="mb-0">Email</p>
<div class="form-outline">
<input
type="email"
id="typeEmail"
th:value="${cartInfo.customer.account.email}"
class="form-control"
disabled="disabled"
/>
</div>
</div>
</div>
<hr class="my-4" />
<div class="row">
<div class="col-sm-8 mb-3">
<p class="mb-0">Địa chỉ</p>
<div class="form-outline">
<input
required
type="text"
id="address"
th:value="${cartInfo.customer.address}"
class="form-control address"
name="address"
/>
</div>
</div>
</div>
<div class="mb-3">
<p class="mb-0">Lưu ý với cửa hàng</p>
<div class="form-outline">
<textarea
class="form-control"
id="textAreaExample1"
rows="2"
name="note"
></textarea>
</div>
</div>
<div class="float-end">
<button type="submit" class="btn btn-success">
Xác nhận
</button>
</div>
</div>
</div>
</form>
<!-- Checkout -->
</div>
<div
class="col-xl-4 col-lg-4 d-flex justify-content-center justify-content-lg-end"
>
<div class="ms-lg-4 mt-4 mt-lg-0" style="max-width: 320px;">
<h6 class="mb-3">Hóa đơn</h6>
<div class="d-flex justify-content-between">
<p class="mb-2">Tiền sách:</p>
<p class="mb-2"><span th:text="${cartInfo.getAmount() + ' VNĐ'}"></span></p>
</div>
<div class="d-flex justify-content-between">
<p class="mb-2">Ship:</p>
<p class="mb-2"><span th:text="${cartInfo.getDeliveryCharges() + ' VNĐ'}"></span></p>
</div>
<hr />
<div class="d-flex justify-content-between">
<p class="mb-2">Tổng tiền:</p>
<p class="mb-2 fw-bold"><span th:text="${cartInfo.getTotalAmount() + ' VNĐ'}"></span></p>
</div>
<hr />
<h6 class="text-dark my-4">Đơn hàng</h6>
<div class="d-flex align-items-center mb-4" th:each="cartLine: ${cartInfo.cartLines}">
<div class="me-3 position-relative">
<img
th:src="@{|/bookImage?id=${cartLine.book.id}|}"
style="height: 96px; width: 96x;"
class="img-sm rounded border"
/>
</div>
<div class="">
<a href="#" class="nav-link">
<span th:text="${cartLine.book.name}"></span>
</a>
<a href="#" class="nav-link">
<span th:text="${'Số lượng: ' + cartLine.quantity}"></span>
</a>
<div class="price text-muted">Đơn giá: <span th:text="${cartLine.book.price + ' VNĐ'}"></span></div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<footer class="footer"></footer>
<div id="myModal" class="modal">
<div class="modal-content">
<h5 style="color: red;"> Chú ý <span class="close">×</span></h5> <hr/>
<p>Vui lòng điền địa chỉ </p>
</div>
</div>
<script>
document.getElementById("formUpdate").addEventListener("submit", function(event) {
event.preventDefault();
var input = document.getElementById("address").value;
if (input === "") {
showModal();
} else {
// Process the form data or perform other actions
console.log("Form submitted with input: " + input);
}
});
document.getElementsByClassName("close")[0].addEventListener("click", hideModal);
function showModal() {
document.getElementById("myModal").style.display = "block";
}
function hideModal() {
document.getElementById("myModal").style.display = "none";
}
</script>
</body>
</html> |
import queue
import networkx as nx
from Gen.AssignmentStatementListener import AssignmentStatementListener
from Gen.AssignmentStatementParser import AssignmentStatementParser
class ASTListener(AssignmentStatementListener):
def __init__(self):
self.ast = AST() # Data structure for holding the abstract syntax tree
self.q = queue.Queue() # Use to print and visualize InClassPresentation
self.g = nx.DiGraph() # Use to visualize InClassPresentation
def print_tree(self, node=None, level=1):
if node is None:
# print()
return
print()
while node is not None:
current_node = node
print(current_node.value, end='')
if node.child is not None:
self.g.add_edge(current_node, node.child, edge_type='C', color='red', weight = 4)
self.q.put(node.child)
else:
tn = TreeNode(value='▓', child=None, brother=None)
self.g.add_edge(current_node, tn, edge_type='C', color='red', weight = 4)
node = node.brother
if node is not None:
print('\t───\t', end='')
self.g.add_edge(current_node, node, edge_type='B', color='green', weight = 4)
else:
tn = TreeNode(value='▓', child=None, brother=None)
self.g.add_edge(current_node, tn, edge_type='B', color='green', weight = 4)
if not self.q.empty():
self.print_tree(node=self.q.get(), level=level+1)
def exitStart(self, ctx: AssignmentStatementParser.StartContext):
self.print_tree(node=self.ast.root, level=1)
def exitStatement(self, ctx: AssignmentStatementParser.StatementContext):
ctx.value_attr = ctx.getChild(0).value_attr
def exitIfst(self, ctx: AssignmentStatementParser.IfstContext):
condPntr = self.ast.make_node(value = ctx.cond().value_attr.value, child=ctx.cond().value_attr.child, brother=None)
ifPntr = self.ast.make_node(value="if", child=condPntr, brother=None)
thenPntr = self.ast.make_node(value="then", child=ctx.statement(0).value_attr, brother=None)
if ctx.getChildCount() > 4:
elsePntr = self.ast.make_node(value="else", child=ctx.statement(1).value_attr, brother=None)
self.ast.add_brother(thenPntr, elsePntr)
self.ast.add_brother(condPntr, thenPntr)
ctx.value_attr = ifPntr
self.ast.root = ifPntr
def exitCond(self, ctx:AssignmentStatementParser.CondContext):
self.ast.add_brother(ctx.expr(0).value_attr, ctx.expr(1).value_attr)
condPntr = self.ast.make_node(value=">", child=ctx.expr(0).value_attr, brother=None)
ctx.value_attr = condPntr
self.ast.root = condPntr
def exitAssign(self, ctx: AssignmentStatementParser.AssignContext):
idPntr = self.ast.make_node(value=ctx.ID().getText(), child=None, brother=ctx.expr().value_attr)
assPntr = self.ast.make_node(value=":=", child=idPntr, brother=None)
ctx.value_attr = assPntr
self.ast.root = assPntr
def exitCompoundst(self, ctx:AssignmentStatementParser.CompoundstContext):
count = ctx.getChildCount()
stPntr = self.ast.make_node(value=ctx.getChild(2).value_attr.value, child=ctx.getChild(2).value_attr.child, brother=None)
compPntr = self.ast.make_node(value="block", child=stPntr, brother=None)
for i in range(2, count-4, 2):
print("hello"+ctx.getChild(i).value_attr.value)
print("print"+ctx.getChild(i+2).value_attr.value)
self.ast.add_brother(stPntr, ctx.getChild(i+2).value_attr)
ctx.value_attr = compPntr
self.ast.root = compPntr
def exitExpr_term_plus(self, ctx: AssignmentStatementParser.Expr_term_plusContext):
self.ast.add_brother(ctx.expr().value_attr, ctx.term().value_attr)
exprPntr = self.ast.make_node(value="+", child=ctx.expr().value_attr, brother=None)
ctx.value_attr = exprPntr
def exitExpr_term_minus(self, ctx: AssignmentStatementParser.Expr_term_plusContext):
self.ast.add_brother(ctx.expr().value_attr, ctx.term().value_attr)
exprPntr = self.ast.make_node(value="-", child=ctx.expr().value_attr, brother=None)
ctx.value_attr = exprPntr
def exitTerm4(self, ctx: AssignmentStatementParser.Term4Context):
ctx.value_attr = ctx.term().value_attr
def exitTerm_fact_mutiply(self, ctx: AssignmentStatementParser.Term_fact_mutiplyContext):
self.ast.add_brother(ctx.term().value_attr, ctx.factor().value_attr)
termPntr = self.ast.make_node(value="*", child=ctx.term().value_attr, brother=None)
ctx.value_attr = termPntr
def exitTerm_fact_divide(self, ctx: AssignmentStatementParser.Term_fact_divideContext):
self.ast.add_brother(ctx.term().value_attr, ctx.factor().value_attr)
termPntr = self.ast.make_node(value="/", child=ctx.term().value_attr, brother=None)
ctx.value_attr = termPntr
def exitFactor3(self, ctx: AssignmentStatementParser.Factor3Context):
ctx.value_attr = ctx.factor().value_attr
def exitFact_expr(self, ctx: AssignmentStatementParser.Fact_exprContext):
ctx.value_attr = ctx.expr().value_attr
def exitFact_id(self, ctx: AssignmentStatementParser.Fact_idContext):
idPntr = self.ast.make_node(value=ctx.ID().getText(), child=None, brother=None)
ctx.value_attr = idPntr
def exitFact_number(self, ctx: AssignmentStatementParser.Fact_numberContext):
ctx.value_attr = ctx.number().value_attr
# ----------------------
def exitNumber_float(self, ctx: AssignmentStatementParser.Number_floatContext):
numberPntr = self.ast.make_node(value=ctx.FLOAT().getText(), child=None, brother=None)
ctx.value_attr = numberPntr
def exitNumber_int(self, ctx: AssignmentStatementParser.Number_intContext):
numberPntr = self.ast.make_node(value=ctx.INT().getText(), child=None, brother=None)
ctx.value_attr = numberPntr
class TreeNode:
def __init__(self, value, child, brother):
self.value = value
self.child = child
self.brother = brother
class AST:
def __init__(self):
self.root = None
self.current = None
def make_node(self, value, child, brother):
tree_node = TreeNode(value, child, brother)
self.current = tree_node
return tree_node
def add_child(self, node, new_child):
if node.child is None:
node.child = new_child
else:
self.current = node.child
while self.current.brother is not None:
self.current = self.current.brother
self.current.brother = new_child
self.current = new_child
def add_brother(self, node, new_brother):
if node.brother is None:
node.brother = new_brother
else:
self.current = node.brother
while self.current.brother is not None:
self.current = self.current.brother
self.current.brother = new_brother
self.current = new_brother |
package ru.practicum.shareit.item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.util.DefaultUriBuilderFactory;
import ru.practicum.shareit.client.BaseClient;
import java.util.Map;
@Service
public class ItemClient extends BaseClient {
private static final String API_PREFIX = "/items";
@Autowired
public ItemClient(@Value("${shareit-server.url}") String serverUrl, RestTemplateBuilder builder) {
super(
builder
.uriTemplateHandler(new DefaultUriBuilderFactory(serverUrl + API_PREFIX))
.requestFactory(HttpComponentsClientHttpRequestFactory::new)
.build()
);
}
public ResponseEntity<Object> getUserItems(Long userId, Integer from, Integer size) {
Map<String, Object> parameters = Map.of(
"from", from,
"size", size
);
return get("?from={from}&size={size}", userId, parameters);
}
public ResponseEntity<Object> getItem(Long userId, Long itemId) {
return get("/" + itemId, userId);
}
public ResponseEntity<Object> add(long userId, ItemToGetDto itemToGetDto) {
return post("", userId, itemToGetDto);
}
public ResponseEntity<Object> update(Long userId, Long itemId,
ItemToGetDto itemToGetDto) {
return patch("/" + itemId, userId, itemToGetDto);
}
public ResponseEntity<Object> addComment(Long userId, Long itemId, CommentToGetDto commentToGetDto) {
return post("/" + itemId + "/comment", userId, commentToGetDto);
}
public ResponseEntity<Object> search(String text, Integer from, Integer size) {
return get("/search?text=" + text + "&from=" + from + "&size=" + size);
}
} |
//
// Created by loumouli on 10/20/23.
//
#include "Course.hpp"
#include <iostream>
using namespace std;
Lists<Student> &StudentList = Singleton<Lists<Student>>::instance();
//Lists<Room> &RoomList = Singleton<Lists<Room>>::instance();
//Lists<Course> &CourseList = Singleton<Lists<Course>>::instance();
Lists<Staff> &StaffList = Singleton<Lists<Staff>>::instance();
template <class BaseClass, class ChildClass>
ChildClass* find_class() {
Lists<BaseClass> &list = Singleton<Lists<BaseClass>>::instance();
for (auto elem : list.get_list()) {
if (dynamic_cast<ChildClass*>(elem) != nullptr)
return (ChildClass *)elem;
}
return nullptr;
}
void setup_course_creation(NeedCourseCreationForm *form, const string& name, int nbr_class, int max_student, Professor *prof) {
form->set_name(name);
form->set_nbr_class(nbr_class);
form->set_max_student(max_student);
form->set_prof(prof);
}
void setup_course_finished(CourseFinishedForm *form, Course *course) {
form->set_course_finished(course);
}
void setup_classroom_creation(NeedMoreClassRoomForm *form, Course *course) {
form->set_course(course);
}
void setup_subscribe(SubscriptionToCourseForm *form, Course *course, Student *student) {
form->set_course(course);
form->set_student(student);
}
void setup(Form *form) {
if (form->get_form_type() == FormType::NeedCourseCreation)
setup_course_creation((NeedCourseCreationForm *)form, string("42"), 5, 30, find_class<Staff, Professor>());
else if (form->get_form_type() == FormType::CourseFinished)
setup_course_finished((CourseFinishedForm *)form, find_class<Course, Course>());
else if (form->get_form_type() == FormType::NeedMoreClassRoom)
setup_classroom_creation((NeedMoreClassRoomForm *)form, find_class<Course, Course>());
else if (form->get_form_type() == FormType::SubscriptionToCourse)
setup_subscribe((SubscriptionToCourseForm *)form, find_class<Course, Course>(), find_class<Student, Student>());
}
int main() {
new Headmaster("HM");
Headmaster *hm = find_class<Staff, Headmaster>();
Secretary *secretary = find_class<Staff, Secretary>();
StaffList.get_list().push_back(new Professor("Prof"));
StudentList.get_list().push_back(new Student("Toto"));
//Create a Course
setup(secretary->createForm(FormType::NeedCourseCreation));
hm->signForm(1);
// Delete the same Course
setup(secretary->createForm(FormType::CourseFinished));
hm->signForm(1);
// Create another Course
setup(secretary->createForm(FormType::NeedCourseCreation));
hm->signForm(1);
// Create a Classroom
setup(secretary->createForm(FormType::NeedMoreClassRoom));
hm->signForm(1);
// Subscribe a Student to a Course
setup(secretary->createForm(FormType::SubscriptionToCourse));
// (*(find_class<Staff, Secretary>()->get_waiting_form().begin()))->execute();
// setup(secretary->createForm(FormType::SubscriptionToCourse));
hm->signForm(1);
// cout << *find_class<Course, Course>();
//sign and execute all the form
return 0;
} |
from django.contrib import admin
from .models import Product, Client, Order
class ProductAdmin(admin.ModelAdmin):
"""Список продуктов."""
list_display = ['title', 'price', 'date_add']
list_filter = ['price', 'date_add']
ordering = ['price', 'date_add']
search_fields = ['description']
readonly_fields = ['date_add']
fieldsets = [
(
None,
{
'classes': ['wide'],
'fields': ['title'],
},
),
(
'Подробности:',
{
'classes': ['collapse'],
'description': 'Подробное описание товара:',
'fields': ['description'],
},
),
(
'Бухгалтерия:',
{
'fields': ['price'],
}
),
(
'Данные:',
{
'description': 'Дата создания заказа:',
'fields': ['date_add'],
}
),
(
'Фото:',
{
'description': 'Изобрвжение товара:',
'fields': ['photo'],
}
),
]
class ClientAdmin(admin.ModelAdmin):
"""Список клиентов."""
list_display = ['name', 'email', 'phone_num', 'registration_date']
list_filter = ['name', 'registration_date']
ordering = ['name', 'registration_date']
search_fields = ['name', 'phone_num', 'email']
fields = ['name', 'email', 'phone_num']
readonly_fields = ['registration_date']
class OrderAdmin(admin.ModelAdmin):
"""Список заказов."""
list_display = ['client', 'total_price', 'date_add']
list_filter = ['client', 'total_price', 'date_add']
ordering = ['client', 'total_price', 'date_add']
search_fields = ['date_add']
fields = ['client', 'product']
readonly_fields = ['total_price', 'date_add']
admin.site.register(Product, ProductAdmin)
admin.site.register(Client, ClientAdmin)
admin.site.register(Order, OrderAdmin) |
import parse from 'html-react-parser';
import { useContext, useState } from 'react';
import { FormattedMessage, IntlShape, injectIntl } from 'react-intl';
import { Link, useParams } from 'react-router-dom';
import Combobox from '../components/base/Combobox';
import Header from '../components/common/Header';
import Navigation from '../components/navigation/Navigation';
import { getLink, getUrl } from '../services/api';
import { Article } from '../services/models/article';
import { store } from '../services/store';
import useFetch from '../services/useFetch';
import useUrl from '../services/useUrl';
type SearchResult = {
items: Array<Article>;
categories: Array<string>;
audience: Array<string>;
didyoumean: string;
tags: Array<string>;
};
type Filter = {
tags: Array<string>;
audience: Array<string>;
category: string | number;
};
const emptyFilter: Filter = {
tags: [],
audience: [],
category: '',
};
interface SearchPageProps {
intl: IntlShape;
}
const SearchPage = ({ intl }: SearchPageProps) => {
const params = useParams();
const queryParam = Object.values(params)[0];
const { state } = useContext(store);
const [query, setQuery] = useState(queryParam);
const [queryField, setQueryField] = useState(queryParam);
const [fuzzy, setFuzzy] = useState(true);
const [showFilter, setShowFilter] = useState(false);
const [filterSettings, setFilterSettings] = useState<Filter>(emptyFilter);
const args = {
controller: 'search',
q: query,
fuzzy: fuzzy ? 1 : 0,
};
const url = useUrl(args);
const { data, error } = useFetch<SearchResult>(url);
if (error) return <></>;
const spellingError = () => {
if (!data) return false;
if (data?.didyoumean === '') return false;
return data?.didyoumean !== query?.toLowerCase();
};
const availableTags = () => {
if (!data?.tags) return [];
let tags = data?.tags.filter(tag => tag in state.taxonomies.tags);
return tags.map(item => {
return state.taxonomies.tags[item];
});
};
const availableCategories = () => {
if (!data?.categories) return [];
let categories = data?.categories.filter(cat => cat in state.taxonomies.categories);
return categories.map(item => {
return state.taxonomies.categories[item];
});
};
const availableAudiences = () => {
if (!data?.audience) return [];
let filteredAudience = data?.audience.filter(aud => aud in state.taxonomies.audience);
return filteredAudience.map(item => {
return state.taxonomies.audience[item];
});
};
const filteredResult = () => {
if (!data) return [];
let filteredItems = data.items;
if (filterSettings.category !== '') {
filteredItems = filteredItems.filter(item => {
return item.category === filterSettings.category;
});
}
if (filterSettings.tags.length !== 0) {
filteredItems = filteredItems.filter(item => {
return item.tags.some(tag => filterSettings.tags.includes(tag));
});
}
if (filterSettings.audience.length !== 0) {
filteredItems = filteredItems.filter(item => {
return filterSettings.audience.includes(item.audience);
});
}
return filteredItems;
};
const changeSearch = (event: any) => {
setQueryField(event.currentTarget?.value);
setFuzzy(true);
setFilterSettings(emptyFilter);
if (event.key !== 'Enter') return;
setQuery(event.target.value);
};
const toggleTagFilterItem = (tagId: string) => {
if (filterSettings.tags.includes(tagId)) {
setFilterSettings(filter => {
return { ...filter, tags: filterSettings.tags.filter(tag => tag !== tagId) };
});
return;
}
setFilterSettings(filter => {
return { ...filter, tags: [...filterSettings.tags, tagId] };
});
};
const toggleAudienceFilterItem = (value: string) => {
if (filterSettings.audience.includes(value)) {
setFilterSettings(filter => {
return { ...filter, audience: filterSettings.audience.filter(tag => tag !== value) };
});
return;
}
setFilterSettings(filter => {
return { ...filter, audience: [...filterSettings.audience, value] };
});
};
// we sould use Memoization here
const audienceAvailable = availableAudiences();
const categoriesAvailable = availableCategories();
const tagsAvailable = availableTags();
document.title = intl.formatMessage({ defaultMessage: 'Search', id: 'search' }) + ': ' + query;
return (
<>
<Navigation />
<Header
aspectRatio="21"
title={intl.formatMessage({ defaultMessage: 'Search', id: 'search' })}
subtitle={query}
/>
<section className="bg-gray-200 py-12 mt-4 lg:mb-4">
<div className="flex gap-4">
<button
onClick={() => {
setShowFilter(!showFilter);
}}
className="button button--primary xl:hidden"
>
<i className="material-icons">tune</i>
</button>
<div className="input input--large">
<label>
<FormattedMessage defaultMessage="Search" id="search" />
</label>
<input
value={queryField}
type="text"
onChange={event => setQueryField(event.target.value)}
onKeyDown={event => changeSearch(event)}
/>
</div>
</div>
</section>
<div className="lg:grid lg:grid--columns-4 grid--gap-4">
<div className={'lg:show ' + (showFilter ? '' : 'hidden')}>
{true && (
<div className={showFilter ? 'bg-gray-100 p-4' : 'bg-gray-200 p-4'}>
<p className="flex flex-center">
<i className="material-icons mr-2">tune</i>
<FormattedMessage defaultMessage="Filter" id="filter" />
</p>
{categoriesAvailable.length !== 0 && (
<>
<p className="uppercase bold text-gray-700">
<FormattedMessage id="category" defaultMessage="Category" />
</p>
<div className="pills">
<Combobox
className="w-full"
nullOption={intl.formatMessage({
defaultMessage: 'No category',
id: 'noCategory',
})}
options={availableCategories()}
onChange={result =>
setFilterSettings(filter => {
return { ...filter, category: result };
})
}
placeholder={intl.formatMessage({
defaultMessage: 'Select Category',
id: 'selectCategory',
})}
/>
</div>
</>
)}
{tagsAvailable.length !== 0 && (
<>
<p className="uppercase bold text-gray-700">
<FormattedMessage
id="tags"
defaultMessage="Tags"
values={{ count: tagsAvailable.length }}
/>
</p>
<div className="pills ">
{availableTags().map((tag, index) => {
if (tag === null) return <></>;
return (
<li
className={
'pills__item link ' +
(filterSettings.tags.includes(tag?.id)
? 'pills__item--primary'
: '')
}
key={index}
onClick={() => {
toggleTagFilterItem(tag.id);
}}
>
{tag.name}
</li>
);
})}
</div>{' '}
</>
)}
{audienceAvailable.length !== 0 && (
<>
<p className="uppercase bold text-gray-700">
<FormattedMessage id="audience" defaultMessage="Audience" />
</p>
<div>
{availableAudiences().map((audience, index) => {
return (
<div className="checkbox" key={index}>
<label>
<input
type="checkbox"
onChange={() => toggleAudienceFilterItem(audience.value)}
checked={filterSettings.audience.includes(audience.value)}
/>
<span>{audience.label}</span>
</label>
</div>
);
})}
</div>
</>
)}
</div>
)}
</div>
<div className="xl:grid__column--span-3">
{spellingError() && fuzzy && (
<div className="alert alert--warning">
<div className="content">
<FormattedMessage
id="didYouMean"
defaultMessage="Search results for {didyoumean}. Search for {alt} instead."
values={{
didyoumean: <b>{data?.didyoumean}</b>,
alt: (
<a
onClick={() => {
setFuzzy(false);
}}
>
{query}
</a>
),
}}
/>
</div>
</div>
)}
<div className="list">
{filteredResult().length === 0 && (
<p>
<FormattedMessage id="noResults" defaultMessage="No search results" />
</p>
)}
{filteredResult().map((item, index) => {
return (
<Link className="list__item" key={index} to={getLink(item.id)}>
{item.pageimage && (
<img
alt=""
className="list__image list__image--edgy"
src={getUrl('_media/' + item.pageimage, { w: '200', lang: state.lang })}
/>
)}
{!item.pageimage && (
<div className="list__icon">
<i className="material-icons">{item.icon}</i>
</div>
)}
<div className="list__content">
<span className="list__title">{item.title}</span>
<span className="list__description">{parse(item.abstract)}</span>
</div>
</Link>
);
})}
</div>
</div>
</div>
</>
);
};
export default injectIntl(SearchPage); |
-- (C) 2002 Roger Villemaire villemaire.roger@uqam.ca
-- We model a window retrasmission protocol (Go-back-N).
-- REMARK Acknowledge N is an ack for all frames of Id strictly before N
-- in the window.
-- The window beginning (WB) is the Id of the first non-acknowledge frame.
-- The window end (WE) is one more (modulo the number of Ids) than the Id of
-- the last non-acklowledge frame.
-- There are two cases to consider
-- 1) WB <= WE
-- Example with 6 Ids
-- | | | | | |
-- 0 1 2 3 4 5
-- | |
-- WB WE
-- Here the window contains frames 1,2,3
--
-- 2) WB > WE
-- Example with 6 Ids
-- | | | | | |
-- 0 1 2 3 4 5
-- | |
-- WE WB
-- Here the window contains frames 4,5,0
--
-- VERIFICATION STRATEGY: We want to show that it is sufficient to have one
-- Id more than the size of the window in order to distinguis between a
-- transmission and a re-transmission.
-- First we need to have at least as much Ids than the size of the window
-- for the meaning of the ack to be unambiguous, since if we had twice the
-- same Id inside the window, we coun't know to which an ack apply.
-- Secondly we don't have to modelize the data. It is sufficient to check
-- that as long that an Id is inside the window the receiver cannot receive
-- a new frame with this same Id (if it appends it must be a re-transmission).
--
dnl-- This file must be proceeded by m4.
dnl-- With NuSMV you must use the following options
dnl-- -m4 -m4options "-IFULL_PATH_OF_THE_NuSMV.m4_FILE"
dnl-- NuSMV.m4 is normally in this directory.
include(NuSMV.m4)dnl
dnl Put a warning message in the file if m4 is directly used.
nusmv_m4_auto_gen dnl
define([:MAX_WS:],[:2:])dnl MAX_WS is the maximal size of the window. Here it is hard coded to 2,
dnl but if you comment out this definition (with either dnl or --) you can
dnl give the value to m4 with the following option
dnl -m4 -m4options "-IFULL_PATH_OF_THE_NuSMV.m4_FILE -DMAX_WS=2"
define([:No_Id:],[:3:])dnl Number of Ids. See the above comment to give this value directly
dnl to NuSMV.
dnl -- We check here that the number of Ids is at least equal to the size of the window.
ifelse(eval(No_Id < MAX_WS),[:1:],[:errprint(__file__:eval(__line__ - 5):The number of Ids must be at least equal to the size of the window in order to have non-ambiguous acknowledge.
)m4exit(1):])
dnl
define([:ID_RANGE:],[:-1..:]eval(No_Id-1))dnl -- the range 0..(No_Id-1) for valid Ids and
dnl -- -1 when the buffer is empty
dnl
define([:VAL_ID_RANGE:],[:0..:]eval(No_Id-1))dnl -- valid Ids.
--------------------------------------------------------------------------
-- SENDER
--------------------------------------------------------------------------
MODULE sender(send_channel,receive_channel)
-- send_channel : ID_RANGE; -- just the frame id
-- receive_channel : ID_RANGE; -- the ack number
VAR
WB : ID_RANGE; -- the first frame awaiting an ack
WE : ID_RANGE; -- one more than the last frame awaiting an ack
DEFINE
-- either 0 is in the window or it is not.
ack_in_window := (receive_channel != -1) & -- non-empty
((WB <= WE &
receive_channel > WB &
receive_channel <= WE
) |
(WB > WE &
(receive_channel > WB |
receive_channel <= WE
)
)
);
window_size :=
case
ack_in_window : (WE - receive_channel) mod No_Id;
TRUE : (WE - WB) mod No_Id;
esac;
new_transmission := window_size < MAX_WS;
-- true if we can increase the window size so if we can transmit something new.
ASSIGN
-- At first the window is empty.
init(WB) := 0;
init(WE) := 0;
next(WB) :=
case
ack_in_window : receive_channel; -- we have an ack, so we move the beginning
-- of the window.
TRUE : WB;
esac;
next(WE) :=
case
new_transmission : (WE + 1) mod No_Id;
-- the window is not of maximal size, we can send something.
TRUE : WE;
esac;
next(send_channel) :=
case
-- the window is not of maximal size, we can send something.
new_transmission : WE;
-- if the window is full we re-transmit the first non-acknowledged frame.
TRUE : WB;
esac;
-- Empty receive channel
next(receive_channel) := -1;
FAIRNESS
running
-- To check that every Id will occurs infinitely often.
forlooprange(I,VAL_ID_RANGE,[:[:
LTLSPEC
(G F (new_transmission & WE = I)):]:])
--------------------------------------------------------------------------
-- RECEIVER
-------------------------------------------------------------------------
MODULE receiver(send_channel,receive_channel)
-- send_channel : ID_RANGE; -- ack
-- receive_channel : ID_RANGE; -- frame Id
VAR
expected_frame : VAL_ID_RANGE; -- the frame we are waiting for.
send_ack : boolean; -- if true we send an ack right now.
-- The fact of posponing the ack simulates the simultaneous travel
-- of some number of frames toward the receiver. Is this really dishonest?
DEFINE
receive := receive_channel = expected_frame;
received_frame := receive_channel;
ASSIGN
init(expected_frame) := 0;
next(expected_frame) :=
case
receive : (expected_frame + 1) mod No_Id;
TRUE : expected_frame;
esac;
next(send_channel) :=
-- We pospone the ack in order to simulate a delay
-- between the sender and the receiver.
case
receive & send_ack : (expected_frame + 1) mod No_Id;
-- ack for the receive now.
!receive & send_ack : expected_frame;
-- ack for the last received frame.
TRUE : send_channel;
esac;
-- empty receive channel
next(receive_channel) := -1;
FAIRNESS
running & send_ack -- we don't indefinitely pospone acks.
--------------------------------------------------------------------------
-- MAIN
-------------------------------------------------------------------------
MODULE main
VAR
channel : ID_RANGE;
ack : ID_RANGE;
sender : process sender(channel,ack);
receiver : process receiver(ack,channel);
ASSIGN
init(channel) := -1; -- empty
init(ack) := -1; -- empty
dnl -- This m4 macro expands to a true NuSMV expression if $1 (its first
dnl -- argument) is in the window.
dnl -- The BEGIN and END mark are there in case you manually use m4 and want
dnl -- to know from were the expansion came from.
define([:IN_WINDOW:],[:
-- BEGIN [:IN_WINDOW:]($1)
((sender.WB <= sender.WE &
$1 >= sender.WB &
$1 < sender.WE
)
|
(sender.WB > sender.WE &
($1 >= sender.WB |
$1 < sender.WE)
)
)
-- END [:IN_WINDOW:]($1)
:])
-- Check that if frame I is transmitted it will stay in the window as long
-- that it is not received.
forlooprange(I,VAL_ID_RANGE,[:[:
LTLSPEC
G ( -- I is transmitted
sender.running &
sender.new_transmission &
sender.WE = I ->
-- I stays in window
X (IN_WINDOW(I)
U
-- up to the moment it is received
(receiver.running & receiver.receive & receiver.received_frame = I)))
:]:])
-- If I is in the window we cannot reuse this Id to send something new.
forlooprange(I,VAL_ID_RANGE,[:[:
LTLSPEC
G ( !( -- I is transmitted
sender.running &
sender.new_transmission &
sender.WE = I &
-- I is in the window
IN_WINDOW(I)))
:]:])
dnl ACK_FOR(ack,I) is a m4 macro which expands to a true NuSMV expressiond
dnl if ack is an acknowledge for I.
dnl Pre-conditions: ack must be in the window (according to ack_in_window) and
dnl I must be in the window (according to IN_WINDOW).
define([:ACK_FOR:],[:
-- BEGIN [:ACK_FOR:]($1,$2)
-- window beginning before window end
((sender.WB <= sender.WE -> $2 < $1)
|
-- end before beginning and ack before end
((sender.WB > sender.WE &
$1 <= sender.WE ) -> (($2 < $1)
|
( $2 >= sender.WB )
)
)
|
-- end before beginning and ack > debut
((sender.WB > sender.WE &
$1 > sender.WE ) -> ($2 < $1 & $2 >= sender.WB)
)
)
-- END [:ACK_FOR:]($1,$2)
:])
-- A frame is received at most once as a new frame.
forlooprange(I,VAL_ID_RANGE,[:[:
LTLSPEC
G ( -- I is transmitted
sender.running &
sender.new_transmission &
sender.WE = I ->
-- I stay in window
X(IN_WINDOW(I)
U
-- as long it is not received
(receiver.running & receiver.receive & receiver.received_frame = I &
X (-- we don't get this frame again...
!(receiver.running & receiver.receive &
receiver.received_frame = I
)
U
-- ...before we get the ack
(sender.running & sender.ack_in_window &ACK_FOR(ack,I)
)
)
)
)
)
:]:]) |
The EXPORT keyword generates a CMake file containing code to import all targets listed in the install command from the installation tree.
EXPORT关键字生成一个CMake文件,该文件包含从安装树导入install命令中列出的所有目标的代码。
CMAKE_CURRENT_LIST_DIR:当 CMake 处理项目中的列表文件时,此变量将始终设置为当前正在处理的列表文件 (CMAKE_CURRENT_LIST_FILE) 所在的目录
这一章是为了导出自己的包以及进行配置
首先,设置需要安装的Targets,然后将其EXPORT导出
`install(TARGETS ${installable_libs}
EXPORT MathFunctionsTargets
DESTINATION lib)`注意,并不会生成MathFunctionsTargets.cmake文件,需要直接使用install(EXPORT)
`install(EXPORT MathFunctionsTargets
FILE MathFunctionsTargets.cmake
DESTINATION lib/cmake/MathFunctions
)`
`
configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in
"${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfig.cmake"
INSTALL_DESTINATION "lib/cmake/example"
NO_SET_AND_CHECK_MACRO
NO_CHECK_REQUIRED_COMPONENTS_MACRO
)`
此外还需要一个config文件
config_package_config_file()。此命令将配置提供的文件,但与标准的configure_file()方式有一些特定的区别。为了正确使用此函数,输入文件除了需要的内容外,还应该有一行文本@PACKAGE_INIT@。该变量将替换为一个代码块,该代码块将设置值转换为相对路径。
将一个模板文件写入到一个配置文件
`write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfigVersion.cmake"
VERSION "${Tutorial_VERSION_MAJOR}.${Tutorial_VERSION_MINOR}"
COMPATIBILITY AnyNewerVersion
)`写入包版本信息
此命令写入find_package()使用的文件,记录所需包的版本和兼容性。在这里,我们使用Tutorial_VERSION_*变量,并表示它与AnyNewerVersion兼容,这表示此版本或任何更高版本与请求的版本兼容。
最后设置下载文件
`install(FILES
${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfigVersion.cmake
DESTINATION lib/cmake/MathFunctions
)`下载文件到本地
当把配置文件和版本文件和targets文件配置后,导出并下载文件targets
使用find_package()查找相关库和头文件
我们已经为我们的项目生成了一个可重用的CMake配置,该配置可以在项目安装或打包后使用
如果我们希望我们的项目也能从构建目录中使用,我们只需要将以下内容添加到顶级CMakeLists.txt的底部,这样能生成${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsTargets.cmake文件用于使用build
`export(EXPORT MathFunctionsTargets
FILE "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsTargets.cmake"
)` |
import {
Body,
Controller,
Get,
NotFoundException,
Param,
Post,
} from '@nestjs/common';
import { MessageCreateDto } from './dto/message-create.dto';
import { ISocketService } from '../../chats/services/socket/socket.service';
import { ApiMessage, toAPIMessage } from '../../serializers/messages';
import { getRoom } from '../../data/firestore/chat-room';
import {
addMessage,
listMessageByRoomId,
IMessage,
} from 'src/data/firestore/message';
import { getUserById } from '../../data/firestore/user';
@Controller('messages')
export class MessageController {
constructor(private socketService: ISocketService) {}
@Post()
async addMessage(@Body() body: MessageCreateDto): Promise<ApiMessage> {
const { text, authorId, replyId, roomId } = body;
const room = await getRoom(roomId);
if (!room) {
throw new NotFoundException();
}
const author = await getUserById(authorId);
if (!author) {
throw new NotFoundException();
}
const m = await addMessage({
text,
authorId,
replyId: replyId || null,
roomId,
});
let messages = await listMessageByRoomId(roomId);
const msgs: ApiMessage[] = [];
messages = messages.sort((a: IMessage, b: IMessage) => {
return a.time.toMillis() - b.time.toMillis();
});
for (const m of messages) {
const am = await toAPIMessage(m, room);
msgs.push(am);
}
await this.socketService.emit('userSendMessage', roomId, msgs);
return await toAPIMessage(m, room);
}
@Get('room/:roomId')
async listMessageByRoomId(
@Param('roomId') roomId: string,
): Promise<ApiMessage[]> {
const room = await getRoom(roomId);
if (!room) {
throw new NotFoundException();
}
let messages = await listMessageByRoomId(roomId);
const result: ApiMessage[] = [];
messages = messages.sort((a: IMessage, b: IMessage) => {
return a.time.toMillis() - b.time.toMillis();
});
for (const m of messages) {
const am = await toAPIMessage(m, room);
result.push(am);
}
return result;
}
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
class Animal{
move = '움직임';
constructor(name){
document.write(`<br>Animal 생성자`);
this.name = name;
this.speed = 0;
}
run(speed){
this.speed = speed;
document.write(`<br>${this.name} : ${this.speed}`);
document.write(`<br>${this.move}`);
}
stop(){
this.speed = 0;
document.write(`<br>${this.name} : stop`);
}
disp(){
document.write(`<br>동물임을 선언함`);
}
}
class Rabbit extends Animal{
leg = 2;
// move = '움직임2';
constructor(name, leg){
document.write(`<br>Rabbit 생성자`);
//super(); err
super(name); //부모 생성자 호출
this.leg = leg; //this() : 구조적으로 있을 수 없다.
}
stop(){ // method overriding
super.stop(); //메소드 내에서 super.메소드 o
document.write(`<br>Rabbit의 stop 메소드`);
this.disp();
this.hide();
}
disp(){ // method overriding
document.write(`<br>토끼 만세`);
document.write(`<br>this.move : ${this.move}`);//this.move : 움직임 // 현재 클래스에서 찾다가 없으면 부모클래스에서 찾음
document.write(`<br>super.move : ${super.move}`);//super.move : undefined
// 메소드 내에서 super.멤버필드 는 안됨. this.맴버필드 o
}
hide(){// Rabbit의 고유 메소드
document.write(`<br>Rabbit의 고유 메소드 : ${this.name} 숨어버리다~`);
}
}
//class Dog extends Animal, Rabbit{ // Classes can only extend a single class.
class Dog extends Animal{
constructor(name){
super(name);
}
disp(){ // method overriding
document.write(`<br>댕댕이 화이팅 : 열심히 ${this.move}`);
}
}
function func(){
const ani = new Animal('동물 수퍼 클래스');
ani.disp();
ani.run(5);
ani.stop();
document.write(`<hr>상속을 알아보자<br>`);
const rabbit = new Rabbit('토끼', 4);
rabbit.disp();
rabbit.run();
document.write(`<br>--------`);
rabbit.stop();
rabbit.hide();
document.write(`<br>^^^^^^^^^^^^^^^^^^^`);
const dog = new Dog('우리 댕댕이');
dog.disp();
dog.run(5);
dog.stop();
document.write(`<br>^^^다형성^^^^^^^^^^^^^^^^`);
let poly = rabbit; // 자바와 다름. 자바스크립트는 일반 변수를 사용한다. 자바처럼 부모 객체 변수를 선언하고 자식의 객체를 주고 부모 객체를 부르고 그런거 없다.
poly.disp();
document.write(`<br>`);
poly = dog;
poly.disp();
}
</script>
</head>
<body onload="func()">
<h1>클래스의 상속</h1>
객체들 간의 관계를 구축하는 방법이다.
부모(수퍼) 클래스 등의 기존 클래스로부터 속성과 동작을 상속을 통해 자식 클래스를 만들 수 있다.
</body>
</html> |
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HeaderComponent } from './header/header.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { MaterialModule } from './material/material.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AuthService } from './auth/auth.service';
import { AuthGuard } from './auth/auth.guard';
import { MessageService } from 'primeng/api';
import { ConfirmationService } from 'primeng/api';
import { ProgramComponent } from './program/program/program.component';
import { LayoutModule } from '@angular/cdk/layout';
import { BatchComponent } from './batch/batch/batch.component';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatSelectModule } from '@angular/material/select';
import { MatRadioModule } from '@angular/material/radio';
import { MatCardModule } from '@angular/material/card';
import { UserComponent } from './user/user/user.component';
import {ListboxModule} from 'primeng/listbox';
import { SignupComponent } from './login/sign-up/sign-up/sign-up.component';
import { ForgotPasswordComponent } from './login/forgot-password/forgot-password.component';
import { VerificationCodeComponent } from './login/forgot-password/verification-code/verification-code.component';
import { DropdownModule } from 'primeng/dropdown';
import {MessagesModule} from 'primeng/messages';
import { SessionComponent } from './session/session/session.component';
import { ResetPasswordComponent } from './login/forgot-password/reset-password/reset-password.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
HomeComponent,
LoginComponent,
ProgramComponent,
BatchComponent,
UserComponent,
SignupComponent,
ForgotPasswordComponent,
VerificationCodeComponent,
ResetPasswordComponent,
SessionComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MaterialModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
LayoutModule,
MatInputModule,
MatButtonModule,
MatSelectModule,
MatRadioModule,
MatCardModule,
ListboxModule,
DropdownModule,
MessagesModule
],
providers: [AuthService, AuthGuard, MessageService, ConfirmationService],
bootstrap: [AppComponent]
})
export class AppModule { } |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HerosComponent } from './heros/heros.component';
import { DashboardComponent } from './dashboard/dashboard.component';
const router: Routes = [
{ path: '', redirectTo: "dashboard", pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'heros', component: HerosComponent }
]
@NgModule({
imports: [RouterModule.forRoot(router)],
exports: [RouterModule]
})
export class AppRoutingModule { } |
import {
Box,
Checkbox,
TableHead,
TableSortLabel,
} from '@mui/material';
import { ArrowDownward as ArrowDownwardIcon } from '@mui/icons-material';
import { visuallyHidden } from '@mui/utils';
import {
HeadCell,
StyledTableCell,
StyledTableRow,
TableProps,
} from '..';
import { ShortUrl, User } from '../../types';
export const ShortUrlTableHeadCells: readonly HeadCell<ShortUrl>[] = [
{
id: 'slug',
disablePadding: true,
align: 'left',
label: 'Slug',
},
{
id: 'originalUrl',
disablePadding: false,
align: 'left',
label: 'Original Url',
style: { display: { xs: 'none', sm: 'table-cell' } },
},
{
id: 'visits',
disablePadding: false,
align: 'right',
label: 'Visits',
},
{
id: 'expiry',
disablePadding: false,
align: 'left',
label: 'Expires',
style: { display: { xs: 'none', sm: 'table-cell' } },
},
{
id: 'enabled',
disablePadding: false,
align: 'right',
label: 'Enabled',
style: { display: { xs: 'none', sm: 'none', md: 'table-cell' } },
},
{
id: 'userId',
disablePadding: false,
align: 'right',
label: 'User',
isAdmin: true,
},
{
id: 'createdAt',
disablePadding: false,
align: 'right',
label: 'Created',
style: { display: { xs: 'none', sm: 'none', md: 'none', lg: 'table-cell' } },
},
];
export const UserTableHeadCells: readonly HeadCell<User>[] = [
{
id: 'id',
disablePadding: true,
align: 'left',
label: 'ID',
},
{
id: 'username',
disablePadding: false,
align: 'left',
label: 'Username',
},
{
id: 'shortUrls',
disablePadding: false,
align: 'right',
label: 'No. URLs',
},
{
id: 'enabled',
disablePadding: false,
align: 'right',
label: 'Enabled',
style: { display: { xs: 'none', sm: 'table-cell' } },
},
{
id: 'admin',
disablePadding: false,
align: 'right',
label: 'Admin',
style: { display: { xs: 'none', sm: 'none', md: 'table-cell' } },
},
{
id: 'createdAt',
disablePadding: false,
align: 'right',
label: 'Created',
style: { display: { xs: 'none', sm: 'none', md: 'table-cell' } },
},
];
export const SortableTableHead = <T extends unknown>(props: TableProps<T>) => {
const {
headCells, isAdmin,
order, orderBy, numSelected, rowCount,
onRequestSort, onSelectAllClick,
} = props;
return (
<TableHead>
<StyledTableRow>
<StyledTableCell padding="checkbox">
<Checkbox
color="primary"
indeterminate={numSelected > 0 && numSelected < rowCount}
checked={rowCount > 0 && numSelected === rowCount}
onChange={onSelectAllClick}
inputProps={{
'aria-label': 'select all',
}}
style={{color: 'white'}}
/>
</StyledTableCell>
{headCells.map((headCell: HeadCell<T>, index: number) => ((isAdmin && (headCell.isAdmin || !headCell.isAdmin)) || (!isAdmin && !headCell.isAdmin)) && (
<StyledTableCell
key={index}
align={headCell.align ?? 'left'}
padding={headCell.disablePadding ? 'none' : 'normal'}
sortDirection={orderBy === headCell.id ? order : false}
sx={{ minWidth: headCell.minWidth, color: 'white', ...headCell.style, whiteSpace: 'nowrap' }}
>
<TableSortLabel
active={orderBy === headCell.id}
direction={orderBy === headCell.id ? order : 'asc'}
style={{color: 'white'}}
IconComponent={ArrowDownwardIcon}
onClick={onRequestSort(headCell.id as keyof T)}
>
<strong>{headCell.label}</strong>
{orderBy === headCell.id ? (
<Box component="span" sx={visuallyHidden}>
{order === 'desc' ? 'sorted descending' : 'sorted ascending'}
</Box>
) : null}
</TableSortLabel>
</StyledTableCell>
))}
<StyledTableCell align="right">
<strong>Actions</strong>
</StyledTableCell>
</StyledTableRow>
</TableHead>
);
}; |
from typing import Optional
import subprocess
import math
import threading
import sys
import dataclasses
from dataclasses import dataclass, field
# import PIL
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QPainterPath, QFont, QPixmap
from PyQt5.QtWidgets import (QGraphicsItem, QGraphicsTextItem, QGraphicsPixmapItem,
QGraphicsDropShadowEffect)
from .models import xy
from .shape import Ellipse, Rectangle, RoundedRectangle, Circle, Shapes, Shape
from .ss import CachePaperData
@dataclass
class EntryState:
index: int
coords: xy
shape: Shapes
shape_coords: Optional[tuple[int, int]] = None
text: str = ""
hidden: bool = False
collapsed: bool = True
hash: str = ""
side: str = "l"
# expand 'e' for expand, 't' for toggle, 'd' for disabled
expand: str = "e"
color: str = "red"
pdf: str = ""
paper_data: Optional[CachePaperData] = None
family: dict = field(default_factory=dict)
connections: dict[str, list] = field(default_factory=dict)
font_attribs: dict = field(default_factory=dict)
part_expand: dict = field(default_factory=dict)
def __post_init__(self):
for k in {"siblings", "parents", "children"}:
if k not in self.family:
self.family[k] = []
for k in {"u", "d", "l", "r"}:
if k not in self.connections:
self.connections[k] = []
if not self.font_attribs:
self.font_attribs = {'family': 'Calibri', 'point_size': 12}
if not self.part_expand:
self.part_expand = {'u': 'e', 'd': 'e', 'l': 'e', 'r': 'e'}
def __setattr__(self, attr, value):
_fields = [x.name for x in dataclasses.fields(EntryState)]
if attr not in _fields:
raise AttributeError(f"Unknown attribute {attr}")
if attr == "index":
if not value:
raise ValueError("Invalid index")
if attr == "shape" and not Shapes.has(value):
raise ValueError("Invalid Shape")
if attr == "connections":
if not all(x in ["u", "d", "l", "r"] for x in value.keys()):
raise AttributeError("Got some unknown connection directions")
super().__setattr__(attr, value)
def set_connections(self, connections):
for direction in ["u", "d", "l", "r"]:
if direction in connections:
self.connections[direction].extend(connections[direction])
class Entry(QGraphicsTextItem):
# Class variables
_mupdf = None
_imsize = (16, 16)
# shape_item is the reference to the item
# state.shape is the type of shape it is
# self.item = CustomTextItem(self.text, self.shape)
# Color of the thought is controlled by the Brush of the shape_item
def __init__(self, scene, index, text, shape=None, coords=None, group=None, data={},
paper_data=None):
super().__init__(text)
self._scene = scene
self.initalize_state(index, shape, coords, text, data)
self.set_shape()
self.set_variables()
self.paper_data = paper_data # why?
# print(self.qf.boundingRect(self.text).getRect())
if not coords:
return
else:
self.draw_entry()
@property
def index(self) -> int:
return self.state.index
@index.setter
def index(self, val: int):
self.state.index = val
@property
def color(self) -> str:
return self.state.color
@color.setter
def color(self, val: str):
self.state.color = val
@property
def paper_data(self) -> Optional[CachePaperData]:
return self.state.paper_data
@paper_data.setter
def paper_data(self, val: CachePaperData):
self.state.paper_data = val
@property
def family(self):
return self.state.family
@property
def connections(self):
return self.state.connections
def set_shape(self):
if self.state.shape == Shapes.ellipse:
self.shape_item: Shape = Ellipse(self, self.state.color)
elif self.state.shape == Shapes.rectangle:
self.shape_item = Rectangle(self, self.state.color)
elif self.state.shape == Shapes.rounded_rectangle:
self.shape_item = RoundedRectangle(self, self.state.color)
elif self.state.shape == Shapes.circle:
self.shape_item = Circle(self, self.state.color)
else:
raise AttributeError(f"{self.state.shape} is not a valid shape")
# def setBrush(self, brush):
# self.shape_item.setBrush(brush)
# def pos(self):
# rect_ = super(Thought, self).boundingRect().getRect()
# return (super().pos().x() - rect_[2], rect_[0])
# def setPos(self, pos):
# self.shape_item.prepareGeometryChange()
# super().setPos(pos[0], pos[1])
def shape(self):
path = QPainterPath()
path.addRect(self.boundingRect())
return path
def pos(self):
return self.shape_item.pos()
# Depending on the direction the thought is added, I only have to
# change the sign in the thought item
# width and height are in the bottom right diagonal as positive
# Assumption is that they're added to the end of the groups
# which is right and down
def boundingRect(self):
# rect_ = super(Thought, self).boundingRect().getRect()
# if self.state.side == 'left':
# return QRectF(rect_[0] - rect_[2], rect_[1], rect_[2], rect_[3]) # only invert x axis
# elif self.state.side == 'right':
# return QRectF(rect_[0], rect_[1], rect_[2], rect_[3]) # normal
# elif self.state.side == 'up':
# return QRectF(rect_[0], rect_[1] - rect_[3], rect_[2], rect_[3]) # only invert y axis
# elif self.state.side == 'down':
# return QRectF(rect_[0], rect_[1], rect_[2], rect_[3]) # normal
return super().boundingRect()
def focusInEvent(self, event):
self._scene.typing = True
super().focusInEvent(event)
def focusOutEvent(self, event):
self.text = self.toPlainText()
ts = self.textCursor()
ts.clearSelection()
self.setTextCursor(ts)
self._scene.typing = False
event.accept() # super().focusOutEvent(event)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Escape or (event.key() == Qt.Key_G and event.modifiers() & Qt.ControlModifier):
self.setTextInteractionFlags(Qt.NoTextInteraction)
event.accept()
else:
super().keyPressEvent(event)
def set_editable(self, editable=True):
self.setTextInteractionFlags(Qt.TextEditorInteraction)
self.setFocus()
# cursor = self.textCursor()
# cursor.select(cursor.Document)
# cursor.movePosition(cursor.End)
# print(cursor.selection().toPlainText())
# I'll fix this later
def mouseDoubleClickEvent(self, event):
if event.button() == Qt.LeftButton:
self.set_editable(True)
event.accept()
def paint(self, painter, style, widget):
self.shape_item.prepareGeometryChange()
# painter.drawRect(self.boundingRect())
# self.document().drawContents(painter, self.boundingRect())
# painter.drawText(self.boundingRect(), self.document().toPlainText())
# self.document().drawContents(painter, self.boundingRect())
# This works now. After every paint() self._scene is also updated
super().paint(painter, style, widget)
self._scene.update()
def draw_entry(self):
self.prepareGeometryChange()
effect = QGraphicsDropShadowEffect()
effect.setBlurRadius(10)
self.shape_item.setGraphicsEffect(effect)
self._scene.addItem(self)
self._scene.addItem(self.shape_item)
self.setParentItem(self.shape_item)
# rect_ = self.boundingRect().getRect()
# now the entry is simply added on the left of the cursor
if not self.state.shape_coords:
if self.state.side == 'l':
self.shape_item.setPos(self.mapFromScene(self.state.coords.x, self.state.coords.y))
# self.shape_item.setPos(self.mapFromScene(self.state.coords.x - rect_[2], self.state.coords.y))
elif self.state.side == 'u':
self.shape_item.setPos(self.mapFromScene(self.state.coords.x, self.state.coords.y))
# self.shape_item.setPos(self.mapFromScene(self.state.coords.x, self.state.coords.y - rect_[3]))
else:
self.shape_item.setPos(self.mapFromScene(self.state.coords.x, self.state.coords.y))
self.state.shape_coords = (self.shape_item.pos().x(), self.shape_item.pos().y())
else:
self.shape_item.setPos(self.state.shape_coords[0], self.state.shape_coords[1])
# I can paint this directly on to the ellipse also, I don't know which
# will be faster, but then I'll have to calculate bbox while clicking
pix = self.pdf_icon()
if self.state.shape in {Shapes.rectangle, Shapes.rounded_rectangle}:
self.icon = QGraphicsPixmapItem(pix, self.shape_item)
self.icon.setPos(-20, -10)
# self._scene.addItem(item.icon)
elif self.state.shape == Shapes.ellipse:
self.icon = QGraphicsPixmapItem(pix, self.shape_item)
self.icon.setPos(-16, -16)
elif self.state.shape == Shapes.circle:
self.icon = QGraphicsPixmapItem(pix, self.shape_item)
self.icon.setPos(-8, -24)
self.handle_icon()
self.icon.open_pdf = self.open_pdf
# self.itemChange = self.shape_item_change
self.setSelected = self.shape_item.setSelected
self.check_hide(self.state.hidden)
# self.icon.hoverEnterEvent = self.icon_hover_event
# self.icon.hoverLeaveEvent = self.icon_hover_event
# self.icon.mouseReleaseEvent = self.icon_release_event
def to_pixmap(self):
self.shape_item.to_pixmap()
def handle_icon(self):
if self.pdf:
self.icon.setCursor(Qt.PointingHandCursor)
else:
self.icon.setCursor(Qt.ArrowCursor)
def pdf_icon(self):
if self.pdf:
return self._color_file
else:
return self._grey_file
def set_variables(self):
# This I'll have to check each time
# self.selected = self.shape_item.isSelected
# self.content = self.text
self.icon = None
# Right now it's not passing control back to the parent
# But multiple items move if I do control click
# self.setTextInteractionFlags(Qt.TextEditorInteraction)
self.setDefaultTextColor(Qt.black)
# self.setFlags(self.flags() | QGraphicsItem.ItemIsSelectable)
self._color_file = QPixmap('icons/pdf.png').scaled(
20, 20, aspectRatioMode=Qt.KeepAspectRatioByExpanding, transformMode=Qt.SmoothTransformation)
self._grey_file = QPixmap('icons/pdfgrey.png').scaled(
20, 20, aspectRatioMode=Qt.KeepAspectRatioByExpanding, transformMode=Qt.SmoothTransformation)
self.focus_toggle = False
self.old_coords = None
self.insert_dir = 'u'
# rect = self.shape_item.boundingRect().getRect()
# Relative coords. left, up, right, down
# self.shape_item.set_link_coords(
# ((rect[0], rect[1] + rect[3]/2), (rect[0] + rect[2]/2, rect[1]),
# (rect[0] + rect[2], rect[1]+rect[3]/2), (rect[0] + rect[2]/2, rect[1] + rect[3])))
# self.nearest_child = {'pos': {'horizontal': None, 'vertical': None},
# 'neg': {'horizontal': None, 'vertical': None}}
def serialize(self):
data = {}
data['index'] = self.state.index
data['coords'] = (self.state.coords.x, self.state.coords.y)
data['shape_coords'] = self.state.shape_coords
data['text'] = self.state.text
data['font_attribs'] = self.state.font_attribs
data['pdf'] = self.pdf
data['expand'] = self.state.expand
data['part_expand'] = self.state.part_expand
data['hidden'] = self.state.hidden
data['hash'] = self.state.hash
data['shape'] = self.state.shape
data['color'] = self.state.color
data['side'] = self.state.side
data['paper_data'] = self.state.paper_data
# set is not serializable for some reason
# May have to amend this later
family_dict = {}
for direction in ['u', 'd', 'l', 'r']:
if direction in self.family:
values = family_dict[direction]
family_dict[direction] = list(values) if isinstance(values, set) else values
family_dict['parents'] = list(self.family['parents'])
family_dict['children'] = list(self.family['children'])
data['family'] = family_dict
return data
def set_state_property(self, name: str, value):
if name == "connections":
self.state.set_connections(value)
elif name == "family":
self.set_family(value)
elif name == "text":
self.setPlainText(value)
self.state.text = value
else:
setattr(self.state, name, value)
@property
def pdf(self):
return self.state.pdf.replace('file://', '', 1)\
if self.state.pdf.startswith('file://') else self.state.pdf
def initalize_state(self, index: int, shape: Shapes, coords, text: str, data: dict):
self.state = EntryState(index, xy(coords), shape, text=text,
**data)
print("family", data.get("family", None))
# set text (I guess)
self.setPlainText(self.state.text)
# set font
font = QFont()
font.setFamily(self.state.font_attribs['family'])
font.setPointSize(self.state.font_attribs['point_size'])
self.setFont(font)
# something with hidden
self.old_hidden = self.state.hidden
def connections_in_direction(self, direction):
return self.state.connections[direction]
def add_connection_at_end_in_direction(self, index, direction):
self.state.connections[direction].append(index)
def add_connections_at_end_in_direction(self, indices, direction):
self.state.connections[direction].extend(indices)
def add_connection_at_beginning_in_direction(self, index, direction):
self.state.connections[direction].insert(0, index)
def add_connections_at_beginning_in_direction(self, indices, direction):
self.state.connections[direction] = [*indices, *self.state.connections[direction]]
def add_parent(self, index):
if index not in self.family['parents']:
self.family['parents'].append(index)
def add_parents(self, parents):
for p in parents:
if p not in self.family['parents']:
self.family['parents'].append(p)
def add_child(self, index):
if index not in self.family["children"]:
self.family['children'].append(index)
def add_children(self, children):
for c in children:
if c not in self.family['children']:
self.family['children'].append(c)
def add_sibling(self, index):
self.family['siblings'].append(index)
def add_siblings(self, siblings):
self.family['siblings'].extend([*siblings])
def set_family(self, family):
if "children" in family:
self.add_children(family["children"])
if "parents" in family:
self.add_parents(family["parents"])
if "siblings" in family:
self.add_siblings(family["siblings"])
def toggle_expand(self, expand, direction=None):
if not direction:
if expand == 't':
if self.expand == 'e':
self.expand = 'd'
else:
self.expand = 'e'
else:
self.expand = expand
for i in self.part_expand.keys():
self.part_expand[i] = self.expand
return self.expand
else:
if expand == 't':
if self.part_expand[direction] == 'e':
self.part_expand[direction] = 'd'
else:
self.part_expand[direction] = 'e'
else:
self.part_expand[direction] = expand
return self.part_expand[direction]
def check_hide(self, hidden):
# if self.old_hidden != hidden:
# self.old_hidden = hidden
self.state.hidden = hidden
if self.state.hidden:
self.hide()
else:
self.restore()
def set_transluscent(self, opacity=0.7):
self.shape_item.setOpacity(opacity)
self.icon.setOpacity(opacity)
self.setOpacity(opacity)
def set_opaque(self):
self.shape_item.setOpacity(1.0)
self.icon.setOpacity(1.0)
self.setOpacity(1.0)
def update_parent(self, p_ind):
pass
# What about the links in the two functions below?
# Must handle them
def hide(self):
self.setVisible(False)
self.icon.setVisible(False)
self.shape_item.setVisible(False)
def restore(self):
self.setVisible(True)
self.icon.setVisible(True)
self.shape_item.setVisible(True)
def open_pdf(self):
if self.pdf:
self.mupdf = subprocess.Popen(['mupdf', self.pdf])
def close_pdf(self):
self.mupdf.kill()
self.mupdf_lock = False
def remove(self):
self._scene.removeItem(self.shape_item)
self._scene.removeItem(self.icon)
self._scene.removeItem(self) |
import { useEffect, useState } from 'react';
import { Filters } from '../Filters';
import { useDispatch, useSelector } from 'react-redux';
import { CardCar } from '../CardCar';
import { Modal } from '../Modal/Modal';
import {
getAdvert,
selectFavorites,
selectFilter,
selectIsLoading,
} from '../../redux/advert';
import { Spiner } from '../Spiner';
export const Favorites = () => {
const [page, setPage] = useState(1);
const [selectedCar, setSelectedCar] = useState(false);
const favorite = useSelector(selectFavorites);
const isLOading = useSelector(selectIsLoading);
const { make, price } = useSelector(selectFilter);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getAdvert(page));
}, [dispatch, favorite, page]);
const filter =
make !== '' || price !== ''
? favorite.filter(
(itm) =>
itm.make === make ||
Number(itm.rentalPrice.replace('$', '')) <= price
)
: favorite;
const handleModal = (car) => {
setSelectedCar(car);
};
return (
<>
{selectedCar && (
<Modal car={selectedCar} setSelectedCar={setSelectedCar} />
)}
{isLOading ? (
<Spiner />
) : (
<>
<Filters page={page} setPage={setPage} />
<CardCar
cars={filter}
handleModal={handleModal}
page={page}
setPage={setPage}
/>
</>
)}
</>
);
}; |
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2021 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef RIPPLE_SIDECHAIN_IMPL_CHAINLISTENER_H_INCLUDED
#define RIPPLE_SIDECHAIN_IMPL_CHAINLISTENER_H_INCLUDED
#include <ripple/protocol/AccountID.h>
#include <ripple/app/sidechain/impl/InitialSync.h>
#include <ripple/beast/utility/Journal.h>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/address.hpp>
#include <memory>
#include <mutex>
#include <string>
namespace ripple {
namespace sidechain {
class Federator;
class WebsocketClient;
class ChainListener
{
protected:
enum class IsMainchain { no, yes };
bool const isMainchain_;
// Sending xrp to the door account will trigger a x-chain transaction
AccountID const doorAccount_;
std::string const doorAccountStr_;
std::weak_ptr<Federator> federator_;
mutable std::mutex m_;
// Logic to handle potentially collecting and replaying historical
// transactions. Will be empty after replaying.
std::unique_ptr<InitialSync> GUARDED_BY(m_) initialSync_;
beast::Journal j_;
ChainListener(
IsMainchain isMainchain,
AccountID const& account,
std::weak_ptr<Federator>&& federator,
beast::Journal j);
virtual ~ChainListener();
std::string const&
chainName() const;
void
processMessage(Json::Value const& msg) EXCLUDES(m_);
template <class E>
void
pushEvent(E&& e, int txHistoryIndex, std::lock_guard<std::mutex> const&)
REQUIRES(m_);
public:
void
setLastXChainTxnWithResult(uint256 const& hash) EXCLUDES(m_);
void
setNoLastXChainTxnWithResult() EXCLUDES(m_);
Json::Value
getInfo() const EXCLUDES(m_);
using RpcCallback = std::function<void(Json::Value const&)>;
/**
* send a RPC and call the callback with the RPC result
* @param cmd PRC command
* @param params RPC command parameter
* @param onResponse callback to process RPC result
*/
virtual void
send(
std::string const& cmd,
Json::Value const& params,
RpcCallback onResponse) = 0;
};
} // namespace sidechain
} // namespace ripple
#endif |
package icon
import (
"context"
"fmt"
"math/big"
"github.com/icon-project/centralized-relay/relayer/chains/icon/types"
"github.com/icon-project/centralized-relay/relayer/kms"
"github.com/icon-project/centralized-relay/relayer/provider"
providerTypes "github.com/icon-project/centralized-relay/relayer/types"
"github.com/icon-project/goloop/module"
"go.uber.org/zap"
)
type Config struct {
provider.CommonConfig `json:",inline" yaml:",inline"`
StepMin int64 `json:"step-min" yaml:"step-min"`
StepLimit int64 `json:"step-limit" yaml:"step-limit"`
StepAdjustment int64 `json:"step-adjustment" yaml:"step-adjustment"`
}
// NewProvider returns new Icon provider
func (c *Config) NewProvider(ctx context.Context, log *zap.Logger, homepath string, debug bool, chainName string) (provider.ChainProvider, error) {
if err := c.Validate(); err != nil {
return nil, err
}
if err := c.sanitize(); err != nil {
return nil, err
}
client := NewClient(ctx, c.RPCUrl, log)
NetworkInfo, err := client.GetNetworkInfo()
if err != nil {
return nil, fmt.Errorf("failed to get network id: %v", err)
}
c.ChainName = chainName
c.HomeDir = homepath
return &Provider{
log: log.With(zap.Stringp("nid ", &c.NID), zap.Stringp("name", &c.ChainName)),
client: client,
cfg: c,
networkID: NetworkInfo.NetworkID,
contracts: c.eventMap(),
}, nil
}
func (c *Config) Validate() error {
if c.RPCUrl == "" {
return fmt.Errorf("icon provider rpc endpoint is empty")
}
if err := c.Contracts.Validate(); err != nil {
return fmt.Errorf("contracts are not valid: %s", err)
}
// TODO: validation for keystore
// TODO: contractaddress validation
// TODO: account should have some balance no balance then use another accoutn
return nil
}
func (c *Config) sanitize() error {
if c.StepAdjustment == 0 {
c.StepAdjustment = 50
}
return nil
}
func (p *Config) SetWallet(addr string) {
p.Address = addr
}
func (p *Config) GetWallet() string {
return p.Address
}
// Enabled returns true if the chain is enabled
func (c *Config) Enabled() bool {
return !c.Disabled
}
type Provider struct {
log *zap.Logger
cfg *Config
wallet module.Wallet
client *Client
kms kms.KMS
contracts map[string]providerTypes.EventMap
networkID types.HexInt
LastSavedHeightFunc func() uint64
}
func (p *Provider) NID() string {
return p.cfg.NID
}
func (p *Provider) Init(ctx context.Context, homepath string, kms kms.KMS) error {
p.kms = kms
return nil
}
func (p *Provider) Type() string {
return "icon"
}
func (p *Provider) Config() provider.Config {
return p.cfg
}
func (p *Provider) Name() string {
return p.cfg.ChainName
}
func (p *Provider) NetworkID() types.HexInt {
return p.networkID
}
func (p *Provider) Wallet() (module.Wallet, error) {
if p.wallet == nil {
if err := p.RestoreKeystore(context.Background()); err != nil {
return nil, err
}
}
return p.wallet, nil
}
func (p *Provider) FinalityBlock(ctx context.Context) uint64 {
return p.cfg.FinalityBlock
}
// MessageReceived checks if the message is received
func (p *Provider) MessageReceived(ctx context.Context, messageKey *providerTypes.MessageKey) (bool, error) {
callParam := p.prepareCallParams(MethodGetReceipts, p.cfg.Contracts[providerTypes.ConnectionContract], map[string]interface{}{
"srcNetwork": messageKey.Src,
"_connSn": types.NewHexInt(messageKey.Sn.Int64()),
})
var status types.HexInt
if err := p.client.Call(callParam, &status); err != nil {
return false, fmt.Errorf("MessageReceived: %v", err)
}
return status == types.NewHexInt(1), nil
}
// ReverseMessage reverts a message
func (p *Provider) RevertMessage(ctx context.Context, sn *big.Int) error {
params := map[string]interface{}{"_sn": types.NewHexInt(sn.Int64())}
message := p.NewIconMessage(types.Address(p.cfg.Contracts[providerTypes.ConnectionContract]), params, MethodRevertMessage)
txHash, err := p.SendTransaction(ctx, message)
if err != nil {
return err
}
txr, err := p.client.WaitForResults(ctx, &types.TransactionHashParam{Hash: types.NewHexBytes(txHash)})
if err != nil {
return err
}
if txr.Status != types.NewHexInt(1) {
return fmt.Errorf("failed: %s", txr.TxHash)
}
return nil
}
// SetAdmin sets the admin address of the bridge contract
func (p *Provider) SetAdmin(ctx context.Context, admin string) error {
callParam := map[string]interface{}{
"_relayer": admin,
}
message := p.NewIconMessage(types.Address(p.cfg.Contracts[providerTypes.ConnectionContract]), callParam, MethodSetAdmin)
txHash, err := p.SendTransaction(ctx, message)
if err != nil {
return fmt.Errorf("SetAdmin: %v", err)
}
txr, err := p.client.WaitForResults(ctx, &types.TransactionHashParam{Hash: types.HexBytes(txHash)})
if err != nil {
return fmt.Errorf("SetAdmin: WaitForResults: %v", err)
}
if txr.Status != types.NewHexInt(1) {
return fmt.Errorf("SetAdmin: failed to set admin: %s", txr.TxHash)
}
return nil
}
// GetFee
func (p *Provider) GetFee(ctx context.Context, networkID string, responseFee bool) (uint64, error) {
callParam := p.prepareCallParams(MethodGetFee, p.cfg.Contracts[providerTypes.ConnectionContract], map[string]interface{}{
"to": networkID,
"response": types.NewHexInt(1),
})
var status types.HexInt
if err := p.client.Call(callParam, &status); err != nil {
return 0, fmt.Errorf("GetFee: %v", err)
}
fee, err := status.BigInt()
if err != nil {
return 0, fmt.Errorf("GetFee: %v", err)
}
return fee.Uint64(), nil
}
// SetFees
func (p *Provider) SetFee(ctx context.Context, networkID string, msgFee, resFee *big.Int) error {
callParam := map[string]interface{}{
"networkId": networkID,
"messageFee": types.NewHexInt(msgFee.Int64()),
"responseFee": types.NewHexInt(resFee.Int64()),
}
msg := p.NewIconMessage(types.Address(p.cfg.Contracts[providerTypes.ConnectionContract]), callParam, MethodSetFee)
txHash, err := p.SendTransaction(ctx, msg)
if err != nil {
return fmt.Errorf("SetFee: %v", err)
}
txr, err := p.client.WaitForResults(ctx, &types.TransactionHashParam{Hash: types.NewHexBytes(txHash)})
if err != nil {
fmt.Println("SetFee: WaitForResults: %v", err)
return fmt.Errorf("SetFee: WaitForResults: %v", err)
}
if txr.Status != types.NewHexInt(1) {
return fmt.Errorf("SetFee: failed to claim fees: %s", txr.TxHash)
}
return nil
}
// ClaimFees
func (p *Provider) ClaimFee(ctx context.Context) error {
msg := p.NewIconMessage(types.Address(p.cfg.Contracts[providerTypes.ConnectionContract]), map[string]interface{}{}, MethodClaimFees)
txHash, err := p.SendTransaction(ctx, msg)
if err != nil {
return fmt.Errorf("ClaimFees: %v", err)
}
txr, err := p.client.WaitForResults(ctx, &types.TransactionHashParam{Hash: types.NewHexBytes(txHash)})
if err != nil {
return fmt.Errorf("ClaimFees: WaitForResults: %v", err)
}
if txr.Status != types.NewHexInt(1) {
return fmt.Errorf("ClaimFees: failed to claim fees: %s", txr.TxHash)
}
return nil
}
// ExecuteRollback
func (p *Provider) ExecuteRollback(ctx context.Context, sn uint64) error {
params := map[string]interface{}{"_sn": types.NewHexInt(int64(sn))}
message := p.NewIconMessage(types.Address(p.cfg.Contracts[providerTypes.XcallContract]), params, MethodExecuteRollback)
txHash, err := p.SendTransaction(ctx, message)
if err != nil {
return err
}
txr, err := p.client.WaitForResults(ctx, &types.TransactionHashParam{Hash: types.NewHexBytes(txHash)})
if err != nil {
return err
}
if txr.Status != types.NewHexInt(1) {
return fmt.Errorf("failed: %s", txr.TxHash)
}
return nil
}
// SetLastSavedBlockHeightFunc sets the function to save the last saved block height
func (p *Provider) SetLastSavedHeightFunc(f func() uint64) {
p.LastSavedHeightFunc = f
}
// GetLastSavedBlockHeight returns the last saved block height
func (p *Provider) GetLastSavedBlockHeight() uint64 {
return p.LastSavedHeightFunc()
} |
import speech_recognition as sr
import pywhatkit
import pyttsx3
import datetime
import wikipedia
import pyjokes
# Initialize the text-to-speech engine
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id) # Use a female voice; adjust the index if necessary
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
listener = sr.Recognizer()
try:
with sr.Microphone() as source:
print('Listening...')
listener.adjust_for_ambient_noise(source)
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'alexa' in command:
command = command.replace('alexa', '')
return command
except sr.UnknownValueError:
talk("Sorry, I couldn't understand that.")
return ""
except sr.RequestError:
talk("Sorry, there was an error processing your request.")
return ""
def run_alexa():
command = take_command()
if command:
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('Playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
print(time)
talk('Current time is ' + time)
elif 'who the heck is' in command:
person = command.replace('who the heck is', '')
info = wikipedia.summary(person, 1)
print(info)
talk(info)
elif 'date' in command:
talk("Sorry, I can't do that.")
elif 'are you single' in command:
talk('I am in a relationship with WiFi.')
elif 'joke' in command:
talk(pyjokes.get_joke())
else:
talk('Please say the command again.')
while True:
run_alexa()
import speech_recognition as sr
import pywhatkit
import pyttsx3
import datetime
import wikipedia
import pyjokes
# Initialize the text-to-speech engine
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id) # Use a female voice; adjust the index if necessary
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
listener = sr.Recognizer()
try:
with sr.Microphone() as source:
print('Listening...')
listener.adjust_for_ambient_noise(source)
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'alexa' in command:
command = command.replace('alexa', '')
return command
except sr.UnknownValueError:
talk("Sorry, I couldn't understand that.")
return ""
except sr.RequestError:
talk("Sorry, there was an error processing your request.")
return ""
def run_alexa():
command = take_command()
if command:
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('Playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
print(time)
talk('Current time is ' + time)
elif 'who the heck is' in command:
person = command.replace('who the heck is', '')
info = wikipedia.summary(person, 1)
print(info)
talk(info)
elif 'date' in command:
talk("Sorry, I can't do that.")
elif 'are you single' in command:
talk('I am in a relationship with WiFi.')
elif 'joke' in command:
talk(pyjokes.get_joke())
else:
talk('Please say the command again.')
while True:
run_alexa() |
import clsx from 'clsx';
import React, { useEffect, useRef } from 'react';
interface CodeInputProps {
value: (string | undefined)[];
onChange: (value: (string | undefined)[]) => void;
disabled?: boolean;
}
export const CodeInput: React.FC<CodeInputProps> = ({
value,
onChange,
disabled,
}) => {
const refs = useRef<(HTMLInputElement | null)[]>(value.map(() => null));
useEffect(() => {
refs.current[0]?.focus();
}, []);
return (
<div className="flex flex-row justify-between items-center w-full">
{value.map((item, index) => (
<input
disabled={disabled}
ref={(el) => {
refs.current[index] = el;
}}
className={clsx(
disabled
? 'bg-disabled border-disabled'
: 'border-borderInactive focus:border-meeColor',
'border rounded-4 focus:border-3 h-14 w-14 text-base text-center outline-none'
)}
size={4}
key={index}
value={item ?? ''}
onChange={(e) => {
const v = e.target.value;
if (v.length > 1) {
return;
}
const newValue = [...value];
newValue[index] = v.length === 0 ? undefined : v;
onChange(newValue);
if (index < value.length - 1 && v.length === 1) {
refs.current[index + 1]?.focus();
}
}}
/>
))}
</div>
);
}; |
import { z } from 'zod';
import { messages } from '@/config/messages';
import {
validateEmail,
validatePassword,
validateConfirmPassword,
} from '@/utils/validators/common-rules';
// form zod validation schema
export const signUpSchema = z.object({
firstName: z.string().min(1, { message: messages.firstNameRequired }),
lastName: z.string().optional(),
email: validateEmail,
password: validatePassword,
confirmPassword: validateConfirmPassword,
isAgreed: z.boolean(),
});
// generate form types from zod validation schema
export type SignUpSchema = z.infer<typeof signUpSchema>; |
// @ts-check
//
// The line above enables type checking for this file. Various IDEs interpret
// the @ts-check directive. It will give you helpful autocompletion when
// implementing this exercise.
/**
* Determines how long it takes to prepare a certain juice.
*
* @param {string} name
* @returns {number} time in minutes
*/
export function timeToMixJuice(name) {
switch (name) {
case 'Pure Strawberry Joy':
return 0.5;
case 'Energizer':
return 1.5;
case 'Green Garden':
return 1.5;
case 'Tropical Island':
return 3;
case 'All or Nothing':
return 5;
default:
return 2.5;
}
}
/**
* Calculates the number of limes that need to be cut
* to reach a certain supply.
*
* @param {number} wedgesNeeded
* @param {string[]} limes
* @returns {number} number of limes cut
*/
export function limesToCut(wedgesNeeded, limes) {
let wedgesHave = 0;
let cutLimes = 0;
for (let i = 0; i < limes.length; i++) {
if (wedgesHave <= wedgesNeeded && wedgesNeeded > 0) {
switch (limes[i]) {
case 'small':
wedgesHave += 6;
break;
case 'medium':
wedgesHave += 8;
break;
case 'large':
wedgesHave += 10;
break;
}
cutLimes++;
}
}
return cutLimes;
}
/**
* Determines which juices still need to be prepared after the end of the shift.
*
* @param {number} timeLeft
* @param {string[]} orders
* @returns {string[]} remaining orders after the time is up
*/
export function remainingOrders(timeLeft, orders) {
let timeSpent = 0;
for (let i = 0; i < orders.length; i++) {
while (timeSpent < timeLeft) {
timeSpent += timeToMixJuice(orders[i]);
orders.shift();
}
}
return orders;
} |
import { yupResolver } from "@hookform/resolvers/yup";
import { Alert, Box, Button, Grid } from "@mui/material";
import { type AxiosError, type AxiosResponse } from "axios";
import { type ReactElement } from "react";
import { Helmet } from "react-helmet";
import { FormProvider, type SubmitHandler, useForm } from "react-hook-form";
import { FiDollarSign } from "react-icons/fi";
import { useMutation, useQuery } from "react-query";
import { useNavigate, useParams } from "react-router-dom";
import type {
LabelDto,
UpdateLabelDto,
VendorLabelDetailsResponseDto,
} from "../api/api-types";
import { type ApiError } from "../api/apiError";
import DashboardCard from "../components/DashboardCard/DashboardCard";
import LabelForm from "../components/Forms/LabelForm/LabelForm";
import PageHeading from "../components/PageHeading/PageHeading";
import MainLayout from "../layouts/MainLayout";
import { api } from "../utils/api";
import { UpdateLabelValidator } from "../validators/LabelUpdateValidation";
import FullLoader from "../components/atoms/FullLoader/FullLoader";
import { LabelStatusEnum } from "../enum/LabelStatusEnum";
export const LabelDetailsView = (): ReactElement => {
const navigate = useNavigate();
const { id } = useParams();
if (id === undefined) {
navigate("/labels");
return <></>;
}
const query = useQuery<
AxiosResponse<VendorLabelDetailsResponseDto>,
AxiosError<ApiError>
>(
"get-label",
async () =>
await api.get<VendorLabelDetailsResponseDto>(`/vendor/labels/${id}`),
);
const mutation = useMutation<
AxiosResponse<LabelDto>,
AxiosError<ApiError>,
UpdateLabelDto
>(async (form) => await api.patch(`/labels/${id}`, form), {
onSuccess: async () => {
await query.refetch();
},
});
const handleUpdate: SubmitHandler<UpdateLabelDto> = (form): void => {
mutation.mutate(form);
};
const handleSubmit = (): void => {
mutation.mutate({
status: LabelStatusEnum.Submitted,
});
};
const methods = useForm<UpdateLabelDto>({
resolver: yupResolver(UpdateLabelValidator),
mode: "onChange",
});
const disableEdit = query.data?.data.status !== "Draft";
const handleRefetch = async (): Promise<void> => {
await query.refetch();
};
if (query.isLoading || mutation.isLoading) {
return <FullLoader />;
}
if (query.data) {
return (
<>
<Helmet>
<title>{`${query.data.data.name} | ${
import.meta.env.VITE_TITLE as string
}`}</title>
</Helmet>
<MainLayout>
{mutation.error && (
<Alert severity='error' sx={{ marginBottom: 2 }}>
{mutation.error.response?.data.message}
</Alert>
)}
<p>{query.data.data.status}</p>
<PageHeading title={query.data.data.name}>
{!disableEdit && (
<Grid container spacing={2}>
<Grid item>
<Button
variant='outlined'
onClick={methods.handleSubmit(handleUpdate)}>
Update Label
</Button>
</Grid>
<Grid item>
<Button variant='contained' onClick={handleSubmit}>
Submit
</Button>
</Grid>
</Grid>
)}
</PageHeading>
<Box mb={2}>
<Grid container spacing={2}>
<Grid item xs={12} lg={3}>
<DashboardCard
title='Commission'
value={`${query.data.data.commissionRate}%`}
icon={<FiDollarSign />}
color='red'
/>
</Grid>
<Grid item xs={12} lg={3}>
<DashboardCard
title='Commission'
value={0}
icon={<FiDollarSign />}
color='red'
/>
</Grid>{" "}
<Grid item xs={12} lg={3}>
<DashboardCard
title='Commission'
value={0}
icon={<FiDollarSign />}
color='red'
/>
</Grid>
<Grid item xs={12} lg={3}>
<DashboardCard
title='Commission'
value={0}
icon={<FiDollarSign />}
color='red'
/>
</Grid>
</Grid>
</Box>
<FormProvider {...methods}>
<LabelForm
data={query.data.data}
disableEdit={disableEdit}
onRefetch={handleRefetch}
/>
</FormProvider>
</MainLayout>
</>
);
}
return <></>;
};
export default LabelDetailsView; |
require "rails_helper"
RSpec.describe FarmersMarketsController, :type => :routing do
describe "routing" do
it "routes to #index" do
expect(:get => "/farmers_markets").to route_to("farmers_markets#index")
end
it "routes to #new" do
expect(:get => "/farmers_markets/new").to route_to("farmers_markets#new")
end
it "routes to #show" do
expect(:get => "/farmers_markets/1").to route_to("farmers_markets#show", :id => "1")
end
it "routes to #edit" do
expect(:get => "/farmers_markets/1/edit").to route_to("farmers_markets#edit", :id => "1")
end
it "routes to #create" do
expect(:post => "/farmers_markets").to route_to("farmers_markets#create")
end
it "routes to #update" do
expect(:put => "/farmers_markets/1").to route_to("farmers_markets#update", :id => "1")
end
it "routes to #destroy" do
expect(:delete => "/farmers_markets/1").to route_to("farmers_markets#destroy", :id => "1")
end
end
end |
import React from "react";
type ButtonType = "button" | "submit" | "reset";
interface ButtonProps {
children: React.ReactNode;
classname: string;
onClick: () => void;
type?: ButtonType;
}
const Button = (props: ButtonProps) => {
const {
children,
classname = "bg-black",
onClick = () => {},
type = "button",
} = props;
return (
<div>
<button
className={`h-10 px-6 font-semibold rounded-md ${classname} text-white`}
type={type}
onClick={onClick}>
{children}
</button>
</div>
);
};
export default Button; |
# Table of patients, PCR result
output$table_patients_pcr_res <- renderTable({
req(dengue_dta_filt())
req(dengue_dta_filt() %>% nrow() >= 1)
dengue_dta_filt() %>%
filter(pcr_result %in% c("Negative", "Equivocal", "Positive")) %>%
pull(pcr_result) %>%
table_method_results()
})
# Plot of patients, PCR results
output$plot_patients_pcr_res <- renderHighchart({
req(dengue_dta_filt())
req(dengue_dta_filt() %>% nrow() >= 1)
cols <- cols_nep[c("Negative", "Equivocal", "Positive") %in% dengue_dta_filt()$pcr_result]
dengue_dta_filt() |>
filter(! is.na(collection_year), ! is.na(collection_month)) |>
filter(pcr_result %in% c("Negative", "Equivocal", "Positive")) |>
mutate(pcr_result = factor(pcr_result, levels = c("Negative", "Equivocal", "Positive"))) |>
mutate(collection_year_month = as_date(glue("{collection_year}-{collection_month}-01"))) |>
count(collection_year_month, pcr_result) |>
hchart(type = "column", hcaes(x = "collection_year_month", y = "n", group = "pcr_result")) |>
hc_yAxis(title = list(text = "Results")) |>
hc_xAxis(title = "") |>
hc_colors(cols) |>
hc_plotOptions(series = list(stacking = "normal")) |>
hc_exporting(enabled = TRUE, buttons = list(contextButton = list(menuItems = hc_export_kind)))
})
# Table of patients, PCR serotype
output$table_patients_pcr <- renderTable({
req(dengue_dta_filt())
req(dengue_dta_filt() %>% nrow() >= 1)
dengue_dta_filt() |>
filter(stringr::str_detect(pcr_serortype_result, "DENV")) |>
pull(pcr_serortype_result) |>
table_method_results()
})
# Plot of patients, PCR serotype
output$plot_patients_pcr <- renderHighchart({
req(dengue_dta_filt())
req(dengue_dta_filt() %>% nrow() >= 1)
# List provided by Audrey DP on 2023-07-05.
display_cat <- c(
"DENV-1",
"DENV-2",
"DENV-3",
"DENV-4",
"DENV-1/2",
"DENV-1/3",
"DENV-1/4",
"DENV-2/3",
"DENV-2/4",
"DENV-3/4",
"No typing",
"Not done"
)
dengue_dta_filt() |>
filter(
! is.na(collection_year),
! is.na(collection_month),
pcr_serortype_result %in% display_cat
) |>
mutate(collection_year_month = as_date(glue("{collection_year}-{collection_month}-01"))) |>
count(collection_year_month, pcr_serortype_result) |>
hchart(type = "column", hcaes(x = "collection_year_month", y = "n", group = "pcr_serortype_result")) |>
hc_yAxis(title = list(text = "PCR Results")) |>
hc_xAxis(title = "") |>
hc_plotOptions(series = list(stacking = "normal")) |>
hc_exporting(enabled = TRUE, buttons = list(contextButton = list(menuItems = hc_export_kind)))
}) |
"""Module for endpoint routing and back-end process"""
from flask import render_template, redirect, request, session, flash
from app import app
import users
import budgets
import user_budgets
import category_search
import services.budget_service
import services.user_service
@app.route("/")
def index():
"""Function routing to login page"""
return redirect("/login")
@app.route("/register", methods=["GET", "POST"])
def create_user():
"""Function handling when a new user is created"""
if request.method == "GET":
return render_template("register.html")
if request.method == "POST":
username = request.form["username"]
password1 = request.form["password1"]
password2 = request.form ["password2"]
role = request.form["role"]
if len(username) < 1 or len(username) > 25:
flash("Username should be between 1-25 characters.")
return render_template("register.html")
if users.user_exists(username):
flash("Username is already taken.")
return render_template("register.html")
if len(password1) < 5 or len(password1) > 25:
flash("Password should be between 5-25 characters.")
return render_template("register.html")
if password1 != password2:
flash("Given passwords are not the same.")
return render_template("register.html")
if password1 == "":
flash("Password is empty.")
return render_template("register.html")
if role not in ("1", "2"):
flash("Unknown user type.")
return render_template("register.html")
if not users.create_user(username, password1, role):
flash("Registration not succesfull, check username and password.")
return render_template("register.html")
flash("User created succesfully, you can login now!", "success")
return redirect("/login")
return render_template("register.html")
@app.route("/login", methods=["GET", "POST"])
def login():
"""Function handling the login"""
if request.method == "GET":
return render_template("login.html")
if request.method == "POST":
username = request.form["username"]
password = request.form["password1"]
if not users.login(username, password):
return render_template("error.html", message="Wrong username, password or no user created.")
# Store the user role and creator_id in session if the login was succesful
user_id = session.get("user_id")
user_role = users.get_user_role(user_id)
session["creator_id"] = user_id
if user_role:
session["role"] = user_role
return redirect("/profile")
@app.route("/logout")
def logout():
"""Function to log out from your personal pages"""
users.logout()
return redirect("/login")
@app.route("/profile", methods=["GET"])
def profile():
"""Function to view the profile page"""
return render_template("profile.html")
@app.route("/profile/admin", methods=["GET", "POST"])
def admin_list():
"""Route to admin user page and functionalities"""
if request.method == "GET":
user_id = session.get("user_id")
user_role = users.get_user_role(user_id)
if user_role and user_role == 2:
all_users = users.get_user_list()
all_budgets = user_budgets.get_all_budgets()
return render_template("admin.html", users=all_users, budgets=all_budgets)
else:
flash("Access denied. The page is only for admin users.", "error")
return redirect("/profile")
# Remove existing budget
if request.method == "POST":
services.user_service.require_role(2)
services.user_service.check_csrf()
budget_id = request.form.get("budget_id")
creator_id = user_budgets.get_budget_creator(budget_id)
creator_name = users.get_username(creator_id)
budget_exists = user_budgets.check_budget_exists(budget_id)
if not budget_exists:
flash ("No budgets to delete.", "error")
return redirect("/profile/admin")
success = user_budgets.delete_budget(budget_id)
if success:
flash (f"""Budget was removed successfully! You deleted a budget from
username {creator_name}""", "success")
return redirect("/profile/admin")
else:
flash ("Failed to delete the budget, try again.", "error")
return redirect("/profile/admin")
@app.route("/profile/newbudget", methods=["GET", "POST"])
def create_new_budget():
"""Function handling to create a new budget"""
if request.method == "GET":
return render_template("new_budget.html")
if request.method == "POST":
services.user_service.check_csrf()
name = request.form["name"]
if len(name) < 1 or len(name) > 25:
flash("Should be between 1-25 characters.")
return redirect("/profile/newbudget")
creator_id = session.get("user_id")
budget_count = budgets.get_budget_count(creator_id)
if budgets.budget_exists(name):
flash("The name of the budget already exists, create a new one.", "error")
return redirect("/profile/newbudget")
if budget_count >= 5:
flash("You have reached the maximum limit of 5 budgets.", "error")
return redirect("/profile/newbudget")
if budgets.new_budget(name, creator_id):
flash("Budget created successfully, you can now add transactions to it!", "success")
return redirect("/profile")
else:
flash("Failed to create the budget, try again!")
return redirect("/profile/newbudget")
return render_template("new_budget.html")
@app.route("/profile/mybudgets", methods=["GET"])
def view_budgets():
"""Function to view all personal budgets"""
creator_id = session.get("user_id")
budgets_list = budgets.see_budgets(creator_id)
if len(budgets_list) < 1:
return render_template("error_budgets.html",
message_budgets="No budgets created yet. Please add a budget first.")
return render_template("my_budgets.html", budgets=budgets_list)
@app.route("/profile/mybudgets/addtransactions", methods=["GET", "POST"])
def add_new_transactions():
"""Add transactions to a selected budget"""
# Store the budget_id in session for GET or POST
if "budget_id" in request.args:
budget_id = request.args.get("budget_id")
session["budget_id"] = budget_id
elif "budget_id" in request.form:
budget_id = request.form["budget_id"]
session["budget_id"] = budget_id
# Get the budget id from session and select it for front-end and creator_id check below
budget_id = session.get("budget_id")
selected_budget = budgets.get_budget_id(budget_id)
# Check that session creator is the creator of the budget to prevent checking other
# peoples budgets
creator_id = session.get("user_id")
if selected_budget is None or selected_budget.creator_id != creator_id:
flash("Invalid Request: The information you are trying to access is not available.")
return redirect("/profile/mybudgets")
if request.method == "POST":
services.user_service.check_csrf()
income = request.form["income"]
expense = request.form["expense"]
income_category = request.form["income_category"]
expense_category = request.form["expense_category"]
message = request.form.get("message")
# Process the add transaction form so that all necessary fields are added
is_valid, error_message = services.budget_service.validate_fields(income, expense,
income_category, expense_category)
if not is_valid:
flash(error_message, "error")
return redirect(f"/profile/mybudgets/addtransactions?budget_id={budget_id}")
# Add the transaction if all of the mandatory fields where added
if user_budgets.add_transaction(budget_id, income, expense, income_category,
expense_category, message):
flash("Transaction added succesfully!", "success")
return redirect("/profile/mybudgets")
return render_template("add_transactions.html", selected_budget=selected_budget)
@app.route("/profile/mybudgets/netresult", methods=["POST"])
def view_net_result():
"""Function to show the net result for selected budget"""
services.user_service.check_csrf()
budget_id = request.form.get("budget_id")
select_budget = budgets.get_budget_id(budget_id)
net_result = user_budgets.calculate_net_result(budget_id)
total_income = user_budgets.get_total_income(budget_id)
total_expense = user_budgets.get_total_expense(budget_id)
return render_template("net_result.html",
selected_budget=select_budget,
budget_id=budget_id,
net_result=net_result,
total_income=total_income,
total_expense=total_expense)
@app.route("/profile/mybudgets/searchtransactions", methods= ["POST"])
def route_search():
"""Routes to category search page and functionalities"""
services.user_service.check_csrf()
budget_id = request.form.get("budget_id")
session["budget_id"] = budget_id
income_category = category_search.view_income_category(budget_id)
expense_category = category_search.view_expense_category(budget_id)
select_budget = budgets.get_budget_id(budget_id)
return render_template("search_transactions.html",
selected_budget=select_budget,
budget_id=budget_id,
income_category=income_category,
expense_category=expense_category)
@app.route("/profile/mybudgets/searchtransactions/category", methods= ["GET"])
def search_category():
"""Routes to categorylisting page and shows the transactions for selected category"""
budget_id = session.get("budget_id")
category = request.args.get("category")
select_budget = budgets.get_budget_id(budget_id)
totals=category_search.get_category_totals(budget_id, category)
if category:
transactions = category_search.search_by_category(budget_id, category)
return render_template("category.html",
transactions=transactions,
selected_budget=select_budget,
category=category,
total_income=totals["total_income"],
total_expense=totals["total_expense"]) |
import transIct from "../../assets/images/trans-ict.png";
import { SlLocationPin } from "react-icons/sl";
import { HiOutlineMail } from "react-icons/hi";
import { LuClock9 } from "react-icons/lu";
import { BsFillTelephoneFill } from "react-icons/bs";
import { FollowUsData } from "../../data/topNavbarData";
const Drawer = ({ handleToggleDrawer }) => {
const contactData = [
{
icon: <SlLocationPin className="text-white" />,
text: "State Of Themepul City, BD",
},
{
icon: <HiOutlineMail className="text-white" />,
text: "info@tronix.com",
},
{
icon: <LuClock9 className="text-white" />,
text: "Week Days: 09.00 to 18.00",
},
{
icon: <BsFillTelephoneFill className="text-white" />,
text: "(+259) 2257 6156",
},
];
return (
<div className="hidden lg:flex fixed top-0 right-0 z-40 h-screen p-10 overflow-y-auto bg-white w-[360px] border-l-2 border-[#800000]">
<div className="space-y-8">
<div>
<a href="https://flowbite.com/" className="flex items-center">
<img src={transIct} alt="TransIct Logo" className="w-48" />
</a>
<button
type="button"
onClick={handleToggleDrawer}
aria-controls="drawer-right-example"
className="text-white bg-[#800000] hover:bg-gray-200 hover:text-gray-900 rounded-full text-sm w-[50px] h-[50px] absolute top-4 right-2.5 inline-flex items-center justify-center"
>
<svg
className="w-3 h-3"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 14 14"
>
<path
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"
/>
</svg>
<span className="sr-only">Close menu</span>
</button>
</div>
<div className="grid gap-3">
<h4 className="capitalize text-[#1C1C25] text-3xl">about us</h4>
<p className="text-[#7B7E86] text-base">
The argument in favor of using filler text goes something like this:
If you use real content in the Consulting Process, anytime you reach
a review
</p>
</div>
<div className="grid gap-8">
<div className="grid gap-3">
<h4 className="capitalize text-[#1C1C25] text-3xl">contact info</h4>
<div className="grid gap-3">
{contactData.map((contact, index) => (
<div className="flex items-center gap-4" key={index}>
<button
className={`flex items-center justify-center border-[1.5px] bg-[#800000] font-bold w-8 h-8 rounded-full`}
>
{contact.icon}
</button>
<p className="text-base text-[#7B7E86] font-medium">
{contact.text}
</p>
</div>
))}
</div>
</div>
<div className="flex space-x-3">
{FollowUsData.map((followUsData, index) => (
<div className="flex justify-center items-center rounded-full w-10 h-10 bg-black">
<a
key={index}
href={followUsData.link}
className="text-white rounded"
aria-current="page"
>
{followUsData.icon}
</a>
</div>
))}
</div>
</div>
</div>
</div>
);
};
export default Drawer; |
package sql_connection
import (
"context"
"database/sql"
"sync"
db "git-codecommit.eu-central-1.amazonaws.com/v1/repos/pkgs/db"
)
type Pool struct {
connections map[string]*sql.DB
locker *sync.RWMutex
}
func NewPool() *Pool {
return &Pool{locker: &sync.RWMutex{}, connections: map[string]*sql.DB{}}
}
type ErrCloseFailure struct {
Errors []error
}
func (e ErrCloseFailure) Error() string {
return "cloud not close all connections"
}
func (p *Pool) GetWithContext(_ context.Context, connectionString string) (*sql.DB, error) {
p.locker.RLock()
if v, exists := p.connections[connectionString]; exists {
p.locker.RUnlock()
return v, nil
}
p.locker.RUnlock()
p.locker.Lock()
defer p.locker.Unlock()
connection, err := db.InitializeConnection(connectionString)
if err != nil {
return nil, err
}
p.connections[connectionString] = connection
return connection, nil
}
func (p *Pool) Get(connectionString string) (*sql.DB, error) {
p.locker.RLock()
if v, exists := p.connections[connectionString]; exists {
p.locker.RUnlock()
return v, nil
}
p.locker.RUnlock()
p.locker.Lock()
defer p.locker.Unlock()
connection, err := db.InitializeConnection(connectionString)
if err != nil {
return nil, err
}
p.connections[connectionString] = connection
return connection, nil
}
func (p *Pool) Close() error {
p.locker.Lock()
defer p.locker.Unlock()
var errs []error
for _, connection := range p.connections {
if closeErr := connection.Close(); closeErr != nil {
errs = append(errs, closeErr)
}
}
if len(errs) > 0 {
return &ErrCloseFailure{Errors: errs}
}
p.connections = map[string]*sql.DB{}
return nil
} |
package com.gson.algo.leetcode.math;
/**
* https://leetcode.cn/problems/stone-game-vii/
*/
public class 石子游戏VII {
/**
* 设置dp[i][j],表示 剩余石子范围i~j, 当前轮次中先手操作后,(先手的得分 - 后手的得分)的最大值。先手可能是A,有可能是B
*
* 本题,对于A,B来说,到自身局时,都是力争求得 (自己得分-对手得分)最大值,这才是自身的选择方案。
*
* i >= j,dp[i][j]明显为0。
* 当 j - i = 1时,当前用户肯定选择价值小的石头,这样自己的得分高,且对方下一步不得分。
* 当 j - i > 1时,当前用户可以选择石子i,也可以选择石子j。
* 当选择石子i时,当前用户得分sum(i+1到j), 对方下一步得分会领先自己dp[i+1,j],
* 则当前用户本轮会领先对手sum(i+1到j)-dp[i+1,j]。
*
* 当选择石子j时,分析类似。
*
* 当前用户从这两个选择中,选择表现最好的那个
*
* dp[i][j] = max( sum(i+1,j) - dp[i+1][j], sum(i,j-1) - dp[i,j-1]
* 遍历过程中,j是自增的,i是自减的
* @param stones
* @return
*/
public int stoneGameVII(int[] stones) {
int n = stones.length;
int[] preSum = new int[n+1];
// preSum[i]表示前i个石子的和。(i>0)
for (int i = 0; i < n; i++) {
preSum[i+1] = preSum[i] + stones[i];
}
int[][] dp = new int[n][n];
// i自减,j自增
for (int i = n-1; i >= 0; i--) {
for (int j = i+1; j < n; j++) {
dp[i][j] = Math.max(preSum[j+1] - preSum[i+1] - dp[i+1][j], preSum[j] - preSum[i] - dp[i][j-1]);
}
}
return dp[0][n-1];
}
} |
#ifndef CORE_GRAPHICS_RAY_H_
#define CORE_GRAPHICS_RAY_H_
namespace ml {
template<class FloatType>
class Ray
{
public:
Ray(const point3d<FloatType> &o, const point3d<FloatType> &d) {
m_Origin = o;
m_Direction = d;
m_InverseDirection = point3d<FloatType>((FloatType)1.0/d.x, (FloatType)1.0/d.y, (FloatType)1.0/d.z);
m_Sign.x = (m_InverseDirection.x < (FloatType)0);
m_Sign.y = (m_InverseDirection.y < (FloatType)0);
m_Sign.z = (m_InverseDirection.z < (FloatType)0);
}
~Ray() {
}
point3d<FloatType> getHitPoint(FloatType t) const {
return m_Origin + t * m_Direction;
}
const point3d<FloatType>& origin() const {
return m_Origin;
}
const point3d<FloatType>& direction() const {
return m_Direction;
}
const point3d<FloatType>& inverseDirection() const {
return m_InverseDirection;
}
const vec3i& sign() const {
return m_Sign;
}
private:
point3d<FloatType> m_Direction;
point3d<FloatType> m_InverseDirection;
point3d<FloatType> m_Origin;
vec3i m_Sign;
};
template<class FloatType>
std::ostream& operator<<(std::ostream& os, const Ray<FloatType>& r) {
os << r.origin() << " | " << r.direction();
return os;
}
typedef Ray<float> Rayf;
typedef Ray<double> Rayd;
} // namespace ml
#endif // CORE_GRAPHICS_RAY_H_ |
# MongoDB Atlas Vector Search on Images
# Atlas Vector Search on Images
Ever wonder how you can search through images of products by simply describing what you're looking for? Well this little demo will help you understand how this is acheived by using a combination of the [HuggingFace Sentence Transformer framework](https://huggingface.co/sentence-transformers) and the [Vector Search](https://www.mongodb.com/products/platform/atlas-vector-search) cabapility of MongoDB Atlas.
The demo leverages the 44,000 images from the _fashion products_ dataset on [Kaggle](https://www.kaggle.com/datasets/paramaggarwal/fashion-product-images-small).
A [pre-trained model](https://huggingface.co/sentence-transformers/clip-ViT-L-14) from the [huggingface framework](https://huggingface.co/sentence-transformers) is applied to the images from the dataset which generates a textual descripton of the image as vector embeddings.
These are stored in a MongoDB collection (along with some generated price and rating data) where a search index is created to allow the images to be queried using semantic search. The data model looks like this:
```json
{
"imageFile": "images/7475.jpg",
"price": 15.66,
"discountPercentage": 7,
"avgRating" : 3.47
}
```
A simple UI is used to capture a search criteria and generate a vector which is then used to perform a _nearest neighbour_ search to return the most relevant products.
The demo also shows how additional filtering can be applied in combination with the search criteria via the `"Advanced"` search screen.
## Set Up
### MongoDB Atlas
Configure a MongoDB Atlas cluster following the instructions from [here](https://www.mongodb.com/docs/atlas/getting-started/).
If you create a dedicated cluster, ensure that your chose the latest version (it should running version 7.0.2 or greater) and update the connection details in [settings.py](settings.py).
Note
```
MONGODB_URI = "<enter your Atlas connection string here>"
```
### Python Installation
Install Python and the dependencies captured in the [requirements.txt](requirements.txt) file (only dependencies are `flask`, `pymongo` & `sentence transformers`)
```bash
pip install -r requirements.txt
```
### Load the Image Data
Download the image files from Kaggle and them to the directory from which the app can display them as part of the results. To do this, download the dataset from [here](https://www.kaggle.com/datasets/paramaggarwal/fashion-product-images-small/download?datasetVersionNumber=1) and unzip its contents so that all the image files are in a directory called "_images_" in the [static](static) directory.
Once this is done, you have two ways in which you can get the image data loaded into your MongoDB Atlas cluster:
+ You can execute the encoder_and_loader.py script to generate the vector embeddings and load the data into your MongoDB Atlas cluster from your client. This will take a fair bit of time as we're processing 44,000 images and because its running on the client side, increasing the cluster resources won't really help. The script is written to be multi-threaded so feel free to increase the number of threads based on your environment. On my M1 Macbook this took around 3 hrs to load.
```
python3 encoder_and_loader.py
```
+ Alternatively (__and this will be much quicker__) use the mongodump file to load this data directly into your cluster using the `mongorestore` command line tool. If you do chose to use this approach make sure you clone this repo have the command line tools installed on your laptop. See [here](https://www.mongodb.com/docs/database-tools/installation/installation/) for more details. Then restore the collection using the `mongorestore` command as per the following example (run this from the MongoDBExportZip directory of the repo), for example:
```sh
cd MDBExportZip
mongorestore --uri mongodb+srv://<username>:<password>@anandorgdev.zbcqwov.mongodb.net --gzip
```
You should see the output end with after 2-3 minutes:
```
2023-10-13T14:22:46.068+0100 [###################.....] vector_search.products 344MB/424MB (81.0%)
2023-10-13T14:22:49.067+0100 [###################.....] vector_search.products 353MB/424MB (83.3%)
2023-10-13T14:22:52.067+0100 [####################....] vector_search.products 363MB/424MB (85.5%)
2023-10-13T14:22:55.067+0100 [#####################...] vector_search.products 372MB/424MB (87.8%)
2023-10-13T14:22:58.067+0100 [######################..] vector_search.products 391MB/424MB (92.3%)
2023-10-13T14:23:01.067+0100 [######################..] vector_search.products 391MB/424MB (92.3%)
2023-10-13T14:23:04.068+0100 [######################..] vector_search.products 401MB/424MB (94.5%)
2023-10-13T14:23:07.066+0100 [#######################.] vector_search.products 410MB/424MB (96.8%)
2023-10-13T14:23:10.068+0100 [#######################.] vector_search.products 410MB/424MB (96.8%)
2023-10-13T14:23:13.068+0100 [#######################.] vector_search.products 420MB/424MB (99.0%)
2023-10-13T14:23:16.071+0100 [########################] vector_search.products 424MB/424MB (100.0%)
2023-10-13T14:23:16.323+0100 [########################] vector_search.products 424MB/424MB (100.0%)
2023-10-13T14:23:16.323+0100 finished restoring vector_search.products (44441 documents, 0 failures)
2023-10-13T14:23:16.324+0100 no indexes to restore for collection vector_search.products
2023-10-13T14:23:16.324+0100 44441 document(s) restored successfully. 0 document(s) failed to restore.
anand.sanghani@M-FRFJ6FPH37 MDB-VectorSearch-Images %
```
__Important__: If you do chose to use this method then please be aware that the mongodump file containing the data is stored using [Git lfs](https://git-lfs.com/) as it's around 200MB. So you will need to ensure that you have installed this on your machine and that you clone this repo using git lfs (e.g. `git lfs clone git@github.com:sanghani73/MDB-VectorSearch-Images.git`).
### Create Index
Create the search index on the database and collection specified in [settings.py](settings.py). Use the default index name (which is `default `) and the following JSON for the index configuration:
```json
{
"mappings": {
"fields": {
"imageVector": [
{
"dimensions": 768,
"similarity": "cosine",
"type": "knnVector"
}
],
"price": {
"type": "number"
},
"averageRating": {
"type": "number"
}
}
}
}
```
## Run
To start the demo application, run [app.py](app.py) if you are running this on an Atlas cluster that is running 7.0.2 or greater.
```python
python3 app.py
```
If however you created this on a sandbox (or other shared cluster) and the version is less that 7.0.2 then run [app-MDBv6.py](app-MDBv6.py) as this will use the [knnBeta](https://www.mongodb.com/docs/atlas/atlas-search/knn-beta/) search operator (which has been deprecated so will stop working at some point in time).
```python
python3 app-MDBv6.py
```
This will launch the app in a local `flask` server on the default port [http://127.0.0.1:5000](http://127.0.0.1:5000) |
#![allow(dead_code)]
use super::custom_error_repo::CustomErrors;
use crate::landlord::domain_layer::landlord::Landlord;
use crate::AppState;
use uuid::Uuid;
pub struct LandlordRepository {
app_state: AppState,
}
impl LandlordRepository {
pub async fn new() -> Self {
LandlordRepository {
app_state: AppState::new().await,
}
}
pub async fn get_all(&self) -> Result<Vec<Landlord>, String> {
let records = sqlx::query_as::<_, Landlord>("SELECT * FROM landlords")
.fetch_all(&self.app_state.database.db)
.await;
match records {
Ok(users) => Ok(users),
Err(e) => Err(e.to_string()),
}
}
pub async fn get_by_id(&self, landlord_id: Uuid) -> Result<Landlord, String> {
let record = sqlx::query_as::<_, Landlord>("SELECT * FROM landlords WHERE landlord_id = $1")
.bind(landlord_id)
.fetch_one(&self.app_state.database.db)
.await;
match record {
Ok(landlord) => Ok(landlord),
Err(e) => Err(e.to_string()),
}
}
pub async fn save(&self, landlord: Landlord) -> Result<Landlord, String> {
let record = sqlx::query_as::<_, Landlord>(
"INSERT INTO landlords (landlord_id, first_name, last_name, email, phone_number, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *",
)
.bind(landlord.landlord_id)
.bind(landlord.title)
.bind(landlord.name)
.bind(landlord.surname)
.bind(landlord.company)
.bind(landlord.phone)
.bind(landlord.email)
.bind(landlord.status)
.bind(landlord.donotdelete)
.bind(landlord.createdby)
.bind(landlord.createdat)
.fetch_one(&self.app_state.database.db)
.await;
match record {
Ok(landlord) => Ok(landlord),
Err(e) => Err(e.to_string()),
}
}
} |
// See https://aka.ms/new-console-template for more information
using Microsoft.EntityFrameworkCore;
Console.WriteLine("Hello, World!");
ApplicationDbContext context = new();
#region One to One İlişkisel Senaryolarda veri ekleme
//{principal : müdür, ana}
#region 1. Yöntem -> Principal Entity üzerinden Depenent Entity verisi ekleme
//Person person = new();
//person.Name = "Talha";
//person.Address = new() { PersonAddress = "Kepez/Antalya" };
//await context.AddAsync(person);
//await context.SaveChangesAsync();
#endregion
// Principal entity => 1 e 1 ilişkide dependent entity olmayan entity'dir yani Personel entity'sidir : Adress entity'de Id alanı Personele Entity'sine foreign key'di : eğerki Id'yi foreign olarak vermesek yeni bir alan olusturulacak'tı default olarak PersonelId diye => yani diğer entity'e bağlı olmıyan entity : principal entity'dir
// Dependent entity = diğer entity'e bağlı olan entity'dir => Adress entity'i
// Eğer ki principal entity üzerinden ekleme geçekleştiriliyor ise dependent entity nesnesi verilmek zorunda değildir. Ama dependent entity üzerinden ekleme işlemi gerçekleştiriliyor ise burada princeple entity nesnesine ihtiyacımız vardır(zaruridir.).
#region 2. Yöntem -> Dependent entity üzerinden principal entity verisi ekleme
//Address adress = new()
//{
// PersonAddress = "Bahçelievler/İstanbul",
// Person = new() { Name = "Turgay" }
//};
//await context.AddAsync(adress);
//await context.SaveChangesAsync();
#endregion
//class Person
//{
// public int Id { get; set; }
// public string Name { get; set; }
// public Address Address { get; set; }
//}
//class Address
//{
// public int Id { get; set; }
// public string PersonAddress { get; set; }
// public Person Person { get; set; }
//}
//class ApplicationDbContext : DbContext
//{
// public DbSet<Person> Persons { get; set;}
// public DbSet<Address> Addresss { get; set;}
// protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
// {
// optionsBuilder.UseSqlServer("Server=localhost\\SQLEXPRESS;Database=ApplicationDb;Trusted_Connection=True;TrustServerCertificate=True");
// }
// protected override void OnModelCreating(ModelBuilder modelBuilder)
// {
// modelBuilder.Entity<Address>()
// .HasOne(a => a.Person)
// .WithOne(p => p.Address)
// .HasForeignKey<Address>(a => a.Id);
// }
//}
#endregion
#region One to Many ilişkisel senaryolarda veri ekleme
// 1. ve 2. yöntemler hiç olmayan verilerin ilişkisel olarak eklenmesini sağlarken, bu 3. yöntem önceden eklenmiş olan bir principal entity verisi ile yeni dependent entitylerin ilişkisel olarak eşleştirilmesini sağlamaktadır.
#region 1. Yöntem -> Principal entity üzerinden dependent entity verisi ekleme
#region Nesne referansı üzerinden ekleme
//Blog blog = new() { Name = "Talhasatir.com Blog" };
//blog.Posts.Add(new() { Title = "Post 1" });
//blog.Posts.Add(new() { Title = "Post 2" });
//blog.Posts.Add(new() { Title = "Post 3" });
//await context.AddAsync(blog);
//await context.SaveChangesAsync();
#endregion
#region Object Initializer üzerinden ekleme
//Blog blog2 = new()
//{
// Name = "A Blog",
// Posts = new HashSet<Post>() { new() { Title = "Post 4" }, new() { Title = "Post 5"} }
//};
//await context.AddAsync(blog2);
//await context.SaveChangesAsync();
#endregion
#endregion
#region 2. Yöntem -> Dependent entity üzerinden principal entity verisi ekleme
// bu yöntem yanlıştır kullanılmamlıdır. => bu işlem sonucunda bir tane dependen entity verisi ekleyebiliyoruz bu yöntemde.
//Post post = new()
//{
// Title = "Post 6",
// Blog = new() { Name = "B Blog" }
//};
//await context.AddAsync(post);
//await context.SaveChangesAsync();
#endregion
#region 3. Yöntem -> Foreign key kolonu üzerinden veri ekleme
//Post post = new()
//{
// Title = "Post 7",
// BlogId = 1
//};
//await context.AddAsync(post);
//await context.SaveChangesAsync();
#endregion
// Posts = new HashSet<Post>() yapısı neden olusturuldu => nesne tabanlı programlamada herhangi bir referans null ise bu referans üzerinden bir mumber'a erişmek => null referance exception hatası verir; bu yüzden biz blog nesnesi üzerinden Posts'a erişmek için biz bu Posts'ın null olmadığından emin olmamız gerekiyor : o yüzden biz Posts'u Blog class'ının constracter'da new'liyoruz. : böylece null olmıyacağından null referance exception hatasına düşmeyeceğizdir.
//class Blog
//{
// public Blog()
// {
// Posts = new HashSet<Post>(); // HashSet(unic bir yapılanma vardır, list'e göre daha az maliyeti vardır,yüksek performans çalışır), List'de kullanılabilir // Nesne referansı üzerinden ekleme işlemi için burası tanımlı olmalıdır.
// }
// public int Id { get; set; }
// public string Name { get; set; }
// public ICollection<Post> Posts { get; set; }
//}
//class Post
//{
// public int Id { get; set; }
// public int BlogId { get; set; }
// public string Title { get; set; }
// public Blog Blog { get; set; }
//}
//public class ApplicationDbContext : DbContext
//{
// DbSet<Blog> Blogs { get; set; }
// DbSet<Post> Posts { get; set; }
// protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
// {
// optionsBuilder.UseSqlServer("Server=localhost\\SQLEXPRESS;Database=ApplicationDb;Trusted_Connection=True;TrustServerCertificate=True");
// }
//}
#endregion
#region Many to Many İlişkisel senaryolarda veri ekleme
#region 1. yöntem
// n t n ilişkisi eğer ki default convention üzerinden tanımlanmış ise kullanılan bir yöntemdir
//Book book = new()
//{
// BookName = "A Kitabı",
// Authors = new HashSet<Author>()
// {
// new() { AuthorName = "Hilmi"},
// new() { AuthorName = "Ayşe"},
// new() { AuthorName = "Fatma"},
// }
//};
//await context.AddAsync(book);
//await context.SaveChangesAsync();
//class Book
//{
// public Book()
// {
// Authors = new HashSet<Author>();
// }
// public int Id { get; set; }
// public string BookName { get; set; }
// public ICollection<Author> Authors { get; set; }
//}
//class Author
//{
// public Author()
// {
// Books = new HashSet<Book>();
// }
// public int Id { get; set; }
// public string AuthorName { get; set; }
// public ICollection<Book> Books { get; set; }
//}
#endregion
#region 2. yöntem
// n t n ilişkisi eğer ki fluent api ile tanımlanmış ise kullanılan bir yöntemdir
// burada mustafa yazarını hem var olan 1 id'li kitap ile eşleştirdim ; hemde yeni bir kitap oluşturup bu kitap ile eşleştirmesini gerçekleştirdim : 2 sinide aynı anda yapabiliyoruz.
//Author author = new()
//{
// AuthorName = "Mustafa",
// Books = new HashSet<BookAuthor>()
// {
// new() {BookId = 1},
// new() {Book = new() { BookName = "B Kitabı"}}
// }
//};
//await context.AddAsync(author);
//await context.SaveChangesAsync();
class Book
{
public Book()
{
Authors = new HashSet<BookAuthor>();
}
public int Id { get; set; }
public string BookName { get; set; }
public ICollection<BookAuthor> Authors { get; set; }
}
class BookAuthor
{
public int BookId { get; set; }
public int AuthorId { get; set; }
public Book Book { get; set; }
public Author Author { get; set; }
}
class Author
{
public Author()
{
Books = new HashSet<BookAuthor>();
}
public int Id { get; set; }
public string AuthorName { get; set; }
public ICollection<BookAuthor> Books { get; set; }
}
#endregion
class ApplicationDbContext : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=localhost\\SQLEXPRESS;Database=ApplicationDb;Trusted_Connection=True;TrustServerCertificate=True");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BookAuthor>()
.HasKey(ba => new { ba.BookId, ba.AuthorId });
modelBuilder.Entity<BookAuthor>()
.HasOne(ba => ba.Book)
.WithMany(b => b.Authors)
.HasForeignKey(ba => ba.BookId);
modelBuilder.Entity<BookAuthor>()
.HasOne(ba => ba.Author)
.WithMany(a => a.Books)
.HasForeignKey(ba => ba.AuthorId);
}
}
#endregion |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int N;//定义一个全局变量用来表示字符节点个数
//节点结构
typedef struct{
char data;//字符节点
int weight;//权重
int parent; //父亲
int lchild;//左孩子
int rchild;//右孩子
}hafuman;
//编码数据结构
typedef struct{
char bits[53];//存放编码数据
int start; //标记开始存放的点
}hafumancode;
void buil_tree(hafuman *tree,int n)//哈夫曼树建立 , 文件保存到HTree.txt
{
getchar();
int i,j;
int min,cmin;
int m,cm;
char ch;
FILE *fp;
if((fp=fopen("HTree.txt","w+"))==NULL)//打开文件
{
printf("哈夫曼文件打开失败\n");
return;
}
//tree=(hafuman*)malloc(sizeof(hafuman)*(2*n));//申请节点空间
for(i=0;i<n;i++)
{
tree[i].lchild=-1;//初始化
tree[i].rchild=-1;
tree[i].parent=-1;
}
for(i=n;i<2*n-1;i++)//初始化其他剩下的结点
{
tree[i].data='*';
tree[i].weight=-1;
tree[i].lchild=-1;
tree[i].rchild=-1;
tree[i].parent=-1;
}
for(i=n;i<2*n-1;i++)
{
min=cmin=999;//min时最小权值,cmin为次小权值
m=cm=0;//m为最小的那个位置,cm为次小的位置
for(j=0;j<i;j++)
{
if(tree[j].parent==-1&&tree[j].weight<min)
{
cmin=min;// 找到更小的就把最小那个值赋给次小的
cm=m;
min=tree[j].weight;// 更小的那个值给最小的
m=j;//位置也相应赋值
}
else if(tree[j].parent==-1&&tree[j].weight<cmin)
{
cmin=tree[j].weight;
cm=j;
}
}
tree[i].weight=tree[m].weight+tree[cm].weight;//父亲节点权值为两个孩子的和
tree[i].lchild=m;//左孩子最小
tree[i].rchild=cm;//右孩子次小
//tree[i].parent=-1;
tree[m].parent=i;//记录孩子的父母
tree[cm].parent=i;
}
for(i=0;i<n;i++)
{
fprintf(fp,"%c %d %d %d %d\n",tree[i].data,tree[i].parent,tree[i].lchild,tree[i].rchild,tree[i].weight);
}
for(i=n;i<2*n-1;i++)
{
fprintf(fp," %d %d %d %d\n",tree[i].parent,tree[i].lchild,tree[i].rchild,tree[i].weight);
}
if(fclose(fp))
{
printf("哈夫曼关闭失败!\n");
exit(1);
}
}
void hafuman_input_creat(hafuman tree[])//手动建立哈夫曼树
{
int i,j;
char ch;
printf("请输入字符个数(输入一个大于0小于60的数)\n");
scanf("%d",&N);
getchar();//每一次输入都要把换行符去掉
while(!(N>0&&N<=60))//判断字符格式对不对
{
printf("输入方式不对,,请重新输入\n");
fflush(stdin);
scanf("%d",&N);
getchar();
}
for(i=0;i<N;i++)
{
printf("请输入第【%d】个字符,请输入字母\n",i+1);
scanf("%c",&tree[i].data);
getchar();
while(!(tree[i].data>='a'&&tree[i].data<='z')||(tree[i].data>='A'&&tree[i].data<='Z'))
{
printf("输入方式不对,,请重新输入\n");//判断格式
fflush(stdin);
scanf("%c",&tree[i].data);
getchar();
}
printf("请输入第【%d】个字符的权值\n",i+1);
scanf("%d",&tree[i].weight);
getchar();
while(!(tree[i].weight>=0&&tree[i].weight<999))
{
printf("输入方式不对,,请重新输入\n");//判断格式
fflush(stdin);
scanf("%d",&tree[i].weight);
getchar();
}
}
buil_tree(tree,N);
printf("手动输入哈夫曼建树完毕!已经将哈夫曼树保存到HTree.txt中\n\n");
}
void hafuman_source_creat(hafuman *tree)//读取源文件建立哈夫曼树 ,文件保存到HTree.txt
{
FILE *sf,*df;
char c,q;
char ch[53],sourcename[30];
int i=0,j,m=0,sum=0;
double count[53];//统计不同字符个数
printf("请输入源文件所在路径:\n");
scanf("%s",sourcename);//输入源文件路径
if((sf=fopen(sourcename,"r"))==NULL)//打开文件
{
printf("文件打开失败,找不到源文件\n");
return;
}
c=fgetc(sf);//先读入一个字符
ch[0]=c;
sum=1;//统计文件全部字符个数
j=1;
for(i=0;i<53;i++)//初始化
{
count[i]=0;
}
while(!feof(sf))
{
for(i=0;i<j;i++)//j是统计当前ch[]数组中存入的元素个数,也就是源文件中不同字符的个数
{
if(c==ch[i])
{
count[i]++;//统计相同字符的个数,也就是权值
m=-1;//m是作为判断标志,判断刚从文件读出的字符是否和之前的一样
}
}
if(m==0)
{
ch[j]=c;//如果刚从文件读出来的字符是新的字符,没有和之前一样的就进入数组ch[]
count[j]++;//每次读入的新字符也要加进权值中
j++;//j加一
}
c=fgetc(sf);
sum++;
m=0;//每次都要初始化
}
N=j;//赋值给N,统计字符个数
if((df=fopen("qzdata.txt","w"))==NULL)//打开权值存储文件
{
printf("权值文件打开失败\n");
return;
}
for(i=0;i<j;i++)//写入权值文件
{
fprintf(df,"%c %.1f\n",ch[i],count[i]);
}
if(fclose(df))
{
printf("权值文件关闭失败!\n");
return;
}
printf("源文件全部字符有:\n");
rewind(sf);//回到文件首部,重新读
while(!feof(sf))//输出全部字符
{
q=fgetc(sf);
printf("%c",q);
}
printf("\n");
printf("源文件字符总数有【%d】个\n\n",sum-1);
for(i=0;i<j;i++)
{
printf("文件第【%d】个字符为【%c】\n",i+1,ch[i]);
printf("-------------权值为【%.0f】\n",count[i]);
}
printf("统计的字符权值已经存入权值qzdata.txt文件中\n");
for(i=0;i<j;i++)//把值赋给节点,用节点建树
{
tree[i].data=ch[i];
tree[i].weight=count[i];
}
buil_tree(tree,j);//调用建树函数
printf("源文件哈夫曼建树完毕!已经将哈夫曼树保存到HTree.txt中\n\n");
if(fclose(sf))
{
printf("文件关闭失败\n");
return;
}
}
void hafuman_code_creat(hafuman *tree,hafumancode *code)//构建哈夫曼编码 ,文件保存到HNode.txt
{
int i,parents,child;
FILE *fp,*ff;
char ch;
int k;
hafumancode temp;//定义一个指向编码结构
for(i=0;i<N;i++)//开始构建
{
child=i;//从每一个叶子节点开始构建
parents=tree[i].parent;
temp.start=N;//start记录读取位置
while(parents!=-1)
{
if(tree[parents].lchild==child)
{
temp.bits[--temp.start]='0';//左孩子为0
}
else
{
temp.bits[--temp.start]='1';//右孩子为1
}
child=parents;
parents=tree[child].parent;
}
code[i]=temp;//保存每一次的哈夫曼编码
}
if((ff=fopen("HNode.txt","w+"))==NULL)//打开
{
printf("节点文件打开失败!\n");
return;
}
printf("构建的哈夫曼树编码为:\n\n");
for(i=0;i<N;i++)
{
fprintf(ff,"%c ",tree[i].data);//先存字符再存编码
printf("字符【%c】哈夫曼编码为:",tree[i].data);//输出字符编码
for(k=code[i].start;k<N;k++)
{
fprintf(ff,"%c ",code[i].bits[k]);//编码存入文件
printf("%c ",code[i].bits[k]);
}
ch='\n';
fputc(ch,ff);//把一个换行符写进文件
printf("\n");
}
printf("\n构建的哈夫曼编码已经存入文件HNode.txt中!\n");
if(fclose(ff))
{
printf("哈夫曼编码文件关闭失败!\n");
return;
}
}
void hafuman_encode(hafuman tree[],hafumancode *code)//源文件加密 ,文件保存到CodeFile.txt
{
int i,m=0;
char sourcename[30];
char ch,q;
FILE *sf,*cf,*bf;//cf是密文文件
int k=0,sum=0;//sum统计个数
printf("请输入要编码的源文件路径:\n");
scanf("%s",sourcename);
if((sf=fopen(sourcename,"r+"))==NULL)// 打开文件
{
printf("源文件文件打开失败!\n");
return;
}
if((cf=fopen("CodeFile.txt","w+"))==NULL)
{
printf("加密文件文件打开失败!\n");
return;
}
printf("源文件全部字符有:\n");
while(!feof(sf))//输出全部字符
{
q=fgetc(sf);
printf("%c",q);
}
printf("\n\n");
printf("对源文编码加密如下:\n");
rewind(sf);//回到文件首部,重新读
ch=fgetc(sf);
while(!feof(sf))
{
for(i=0;i<N;i++)//找到对应的哈夫曼节点就输出编码
{
if(ch==tree[i].data)
{
for(k=code[i].start;k<N;k++)//输出编码
{
fprintf(cf,"%c",code[i].bits[k]);
printf("%c",code[i].bits[k]);
sum++;
m=-1;//用来判断是否找到相应字符
}
break;
}
}
if(m==0)
printf("\n找不到相应字符!!!\n");
ch=fgetc(sf);
m=0;
}
printf("\n\n");
printf("一共有【%d】个字符,加密结果已经存入CodeFile.txt中\n",sum);
if(fclose(sf))
{
printf("源文件关闭失败!\n");
return;
}
if(fclose(cf))
{
printf("编码加密文件关闭失败!\n");
return;
}
}
void hafuman_decoding(hafuman tree[],hafumancode *code)//译码,并把文件保存到TextFile.txt
{
FILE *cf,*tf;
int i;
char ch;
if((cf=fopen("CodeFile.txt","r"))==NULL )
{
printf("加密文件文件打开失败!\n");
return;
}
if((tf=fopen("TextFile.txt","w+"))==NULL)
{
printf("译文文件文件打开失败!\n");
return;
}
ch=fgetc(cf);
i=2*N-2;//从根节点开始
while(!feof(cf))
{
if(ch=='0')
{
i=tree[i].lchild; //判断是左孩子还是右孩子
}
else if(ch=='1')
{
i=tree[i].rchild;
}
if(tree[i].lchild==-1)//到叶子节点停止
{
fprintf(tf,"%c",tree[i].data);//写入文件
i=2*N-2;//每次都要从根节点开始
}
ch=fgetc(cf);
}
fclose(cf);//关闭文件
fclose(tf);
if(tree[i].lchild!=0&&i!=2*N-2)//判断电文代码
{
printf("电文有误!!\n");
}
else
{
printf("译码成功!!\n译码后的内容为:\n\n");
if((tf=fopen("TextFile.txt","r+"))==NULL)
{
printf("译文文件文件打开失败!\n");
return;
}
ch=fgetc(tf);
while(!feof(tf))//从文件里输出译码后内容
{
printf("%c",ch);
ch=fgetc(tf);
}
printf("\n");
if(fclose(tf))
{
printf("译码文件关闭失败!!\n");
return;
}
}
}
void output_hafuman_tree(hafuman tree[])//哈夫曼树输出函数
{
int i;
FILE *fp;
if((fp=fopen("HTree.txt","r+"))==NULL)//打开文件
{
printf("文件打开失败\n");
return;
}
for(i=0;i<N;i++)//输出哈夫曼树节点内容
{
printf("第【%d】个字符【%c】节点哈夫曼树节点为:\n",i+1,tree[i].data);
printf("***父母---左孩子---右孩子---权值***\n");
printf(" %d %d %d %d\n\n",tree[i].parent,tree[i].lchild,tree[i].rchild,tree[i].weight);
}
for(i=N;i<2*N-1;i++)
{
printf("第【%d】个节点哈夫曼树节点为:\n",i+1);
printf("***父母---左孩子---右孩子---权值***\n");
printf("* %d %d %d %d *\n\n",tree[i].parent,tree[i].lchild,tree[i].rchild,tree[i].weight);
}
if(fclose(fp))
{
printf("关闭失败!\n");
return;
}
}
//主函数设计
int main(int argc, char *argv[])
{
int choose;
int choose1;
int n;
hafuman tree[60];
hafumancode code[60];
while(1)
{
//system("cls");//清屏函数
printf("\n*****欢迎使用哈夫曼编码/译码系统*****\n");
printf("**-------您可以进行以下操作------------------**\n");
printf("** 1.建立哈夫曼树 **\n");
printf("** 2.构造哈夫曼树编码 **\n");
printf("** 3.编码加密 **\n");
printf("** 4.显示哈夫曼树 **\n");
printf("** 5.译码 **\n");
printf("** 0.退出系统 **\n");
printf("**---------------------------------------------------**\n");
printf("请选择一个操作\n");
scanf("%d",&choose);
printf("\n");
switch(choose)
{
case 1:
printf("请选择建立方式:1.从源文件夹读取 2.手动输入\n");
scanf("%d",&choose1);
switch(choose1)
{
case 1:
hafuman_source_creat(tree);//通过源文件建哈夫曼树
break;
case 2:
hafuman_input_creat(tree);//手动输入建立
break;
default:
printf("**输入的选择无效* *请重新输入* *谢谢**\n\n");
break;
}
break;
case 2:
hafuman_code_creat(tree,code);//构建哈夫曼编码
break;
case 3:
hafuman_encode(tree,code);//编码加密
break;
case 4:
output_hafuman_tree(tree);//输入哈夫曼树节点
break;
case 5:
hafuman_decoding(tree,code);//译码
break;
case 0:
printf("感谢您使用本系统,祝您新年快乐,生活愉快,万事如意\n");
exit(0);
break;
default:
printf("**输入的选择无效---重新输入---谢谢 **\n\n");
break;
}
}
return 0;
} |
import { Component, OnInit, ViewChild } from '@angular/core';
import { jqxLoaderComponent } from 'jqwidgets-scripts/jqwidgets-ts/angular_jqxloader';
import { ApiService } from '../../api/api.service';
import { RequestHelper } from '../../api/request/request-helper';
import { StoreProcedures } from '../../api/request/store-procedures.enum';
import { InputParameter } from '../../api/request/input-parameter';
import {
DynamicField,
DynamicFieldCombo
} from '../dynamic-input/dynamic-field';
import { ResultToGraphicCollection } from '../../map-service/result-to-graphic-collection';
import { MapService } from '../../map-service/map.service';
import { CallModal, FlashToGeometry } from '../../map-service/map-action';
import { EmapActions, Emodal } from '../../map-service/emap-actions.enum';
@Component({
selector: 'app-searches',
templateUrl: './searches.component.html',
styleUrls: ['./searches.component.css']
})
export class SearchesComponent implements OnInit {
@ViewChild('jqxLoader') jqxLoader: jqxLoaderComponent;
searchesList: Array<any>;
searchItemSelected: any;
dynamicItems: Array<any>;
paramItems: Array<any>;
searchResults: Array<any>;
closeFunction: Function;
constructor(private apiService: ApiService, private mapService: MapService) {}
ngOnInit() {
this.loadDropDownSearches();
}
private loadDropDownSearches() {
this.apiService
.callStoreProcedureV2(
RequestHelper.getParamsForStoredProcedureV2(
StoreProcedures.ObtenerBusquedas,
[]
)
)
.subscribe(json => {
if (json[0] != null) {
this.loadDropDownSearchesCompleted(JSON.parse(json[0]));
}
});
}
private loadDropDownSearchesCompleted(json: any) {
if (json['Table1'] != null) {
// ATTR: IDBUSQUEDA, DESCRIPCION, PRODCEDIMIENTO
this.searchesList = json['Table1'];
}
}
searchItemChanged(itemSelected: any): void {
this.startProgress();
this.apiService
.callStoreProcedureV2(
RequestHelper.getParamsForStoredProcedureV2(
StoreProcedures.ObtenerParametrosBusquedas,
[new InputParameter('una_Busqueda', itemSelected.IDBUSQUEDA)]
)
)
.subscribe(json => {
this.stopProgress();
if (json[1] != null) {
this.createDynamicInputs(JSON.parse(json[1]));
}
});
}
private createDynamicInputs(json: any) {
/* ARRAY ATTRIBUTES:
IDBUSQUEDA, PARAMETRO, ORDEN, TIPOPARAMETRO, PROCEDIMIENTO, TIPODATO, CLASEPARAMETRO
, ETIQUETA, COMBODEPARTAMENTO, COMBOLOCALIDAD, COMBOPADRE, COMBOHIJO, CODIGO*/
if (json['Table1'] != null) {
this.paramItems = json['Table1'];
this.dynamicItems = this.paramItems.map(item => {
let control = null;
if (item.TIPOPARAMETRO === 'COMBO') {
control = new DynamicFieldCombo(item);
} else {
control = new DynamicField(item);
}
return control;
});
}
}
onBuscarButtonClick(): void {
this.startProgress();
this.searchResults = new Array<any>();
const parameters = this.getSearchParameters();
this.apiService
.callStoreProcedureV2(
RequestHelper.getParamsForStoredProcedureV2(
this.searchItemSelected.PROCEDIMIENTO,
parameters
)
)
.subscribe(json => {
this.stopProgress();
this.processSearchResponse(json);
});
}
getSearchParameters(): InputParameter[] {
const inputParameters = new Array<InputParameter>();
this.dynamicItems.forEach(item => {
if (item.ClaseParametro === 'E') {
switch (item.TipoParametro) {
case 'TEXT':
case 'DATE':
inputParameters.push(
new InputParameter(item.Parametro, item.Value)
);
break;
case 'COMBO':
inputParameters.push(
new InputParameter(
item.Parametro,
item.Value != null ? item.Value.value : null
)
);
break;
case 'CHECK':
inputParameters.push(
new InputParameter(item.Parametro, item.Value ? '1' : '0')
);
break;
}
}
});
return inputParameters;
}
private processSearchResponse(json: any) {
const values = Object.values(json);
if (values.length > 0) {
const responseContent = JSON.parse(values[0].toString());
if (responseContent.ErrorMessage != null) {
alert(responseContent.ErrorMessage);
} else {
const responseValues = Object.values(responseContent);
if (responseValues == null || responseValues.length === 0) {
alert('No hay resultados en la búsqueda.');
} else {
ResultToGraphicCollection.convert(
<Array<any>>responseValues[0],
results => {
this.searchResults = results;
this.mapService.executeMapAction(<FlashToGeometry>{
EMapAction: EmapActions.ZoomToGeometry,
geometry: results[0].geometry
});
}
);
}
}
}
}
onVerDatosClick(): void {
if (this.searchResults != null && this.searchResults.length > 0) {
this.mapService.executeMapAction(<CallModal>{
EMapAction: EmapActions.CallModal,
EModal: Emodal.ViewSelection,
parameters: this.searchResults
});
}
}
onCancelarClick(): void {
this.closeFunction();
}
private startProgress(): void {
if (this.jqxLoader) {
this.jqxLoader.open();
}
}
private stopProgress(): void {
if (this.jqxLoader) {
this.jqxLoader.close();
}
}
start(): void {
this.searchItemSelected = null;
this.dynamicItems = null;
this.searchResults = null;
}
} |
/**
* If you are not familiar with React Navigation, refer to the "Fundamentals" guide:
* https://reactnavigation.org/docs/getting-started
*
*/
import { FontAwesome } from '@expo/vector-icons';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { NavigationContainer, DefaultTheme, DarkTheme } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import * as React from 'react';
import { ColorSchemeName, Image, Touchable, TouchableOpacity } from 'react-native';
import { AntDesign, MaterialIcons, Ionicons } from '@expo/vector-icons';
import Colors from '../constants/Colors';
import useColorScheme from '../hooks/useColorScheme';
import ModalScreen from '../screens/ModalScreen';
import NotFoundScreen from '../screens/NotFoundScreen';
import HomeScreen from '../screens/HomeScreen';
import ComingSoonScreen from '../screens/ComingSoonScreen';
import { RootStackParamList, RootTabParamList, RootTabScreenProps } from '../types';
import LinkingConfiguration from './LinkingConfiguration';
import { Avatar, Icon } from 'react-native-elements';
import MovieDetailScreen from '../screens/MovieDetailScreen';
export default function Navigation({ colorScheme }: { colorScheme: ColorSchemeName }) {
return (
<NavigationContainer
linking={LinkingConfiguration}
theme={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
<RootNavigator />
</NavigationContainer>
);
}
/**
* A root stack navigator is often used for displaying modals on top of all other content.
* https://reactnavigation.org/docs/modal
*/
const Stack = createNativeStackNavigator<RootStackParamList>();
function RootNavigator() {
return (
<Stack.Navigator>
<Stack.Screen name="Root" component={BottomTabNavigator} options={{ headerShown: false }} />
<Stack.Screen name="NotFound" component={NotFoundScreen} options={{ title: 'Oops!' }} />
<Stack.Group screenOptions={{ presentation: 'modal' }}>
<Stack.Screen name="Modal" component={ModalScreen} />
</Stack.Group>
</Stack.Navigator>
);
}
/**
* A bottom tab navigator displays tab buttons on the bottom of the display to switch screens.
* https://reactnavigation.org/docs/bottom-tab-navigator
*/
const BottomTab = createBottomTabNavigator<RootTabParamList>();
function BottomTabNavigator() {
const colorScheme = useColorScheme();
return (
<BottomTab.Navigator
initialRouteName="Home"
screenOptions={{
tabBarActiveTintColor: Colors[colorScheme].tint,
}}>
<BottomTab.Screen
name="Home"
component={HomeScreen}
options={({ navigation }: RootTabScreenProps<'Home'>) => ({
headerTitle: '',
headerTransparent: true,
headerBackgroundContainerStyle: {
opacity: 0.6,
backgroundColor: 'black',
shadowOffset: {
width: -10,
height: 20
},
shadowColor: 'black',
shadowOpacity: 1,
shadowRadius: 10
},
tabBarStyle: { backgroundColor: 'black', height: 90, borderTopWidth: 0 },
tabBarIcon: ({ color }) => <AntDesign name="home" color={color} size={24} />,
headerLeft: () => (
<Image
style={{ width: 35, height: 35, marginLeft: 12 }}
source={{
uri: 'https://assets.nflxext.com/ffe/siteui/common/icons/nficon2016.ico'
}} />
),
headerRight: () => (
<TouchableOpacity style={{ flexDirection: 'row', width: 70, alignItems: 'center', justifyContent: 'space-between', marginRight: 20 }}>
<Ionicons name='notifications' size={25} color='white' />
<Avatar size={25} source={{ uri: 'https://occ-0-2706-2705.1.nflxso.net/dnm/api/v6/K6hjPJd6cR6FpVELC5Pd6ovHRSk/AAAABYo-77w9gFw_bfvYXpqLi1OrTW3u_MQ3JRXXeXnOqz74mgOhPdElhW0zuVDBSMSx1-5IY97zLiQPDNx2_2iq2CI.png?r=a30' }} />
</TouchableOpacity>
),
})}
/>
<BottomTab.Screen
name="ComingSoon"
component={MovieDetailScreen}
options={{
tabBarStyle: { backgroundColor: 'black', height: 90, borderTopWidth: 0 },
title: 'Coming Soon',
tabBarIcon: ({ color }) => <MaterialIcons name="video-library" color={color} size={24} />,
}}
/>
<BottomTab.Screen
name="Search"
component={ComingSoonScreen}
options={{
tabBarStyle: { backgroundColor: 'black', height: 90, borderTopWidth: 0 },
title: 'Search',
tabBarIcon: ({ color }) => <Ionicons name="search" color={color} size={24} />,
}}
/>
<BottomTab.Screen
name="Downloads"
component={ComingSoonScreen}
options={{
tabBarStyle: { backgroundColor: 'black', height: 90, borderTopWidth: 0 },
title: 'Downloads',
tabBarIcon: ({ color }) => <AntDesign name="download" color={color} size={24} />,
}}
/>
</BottomTab.Navigator>
);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.