text
stringlengths 184
4.48M
|
---|
Feature: Registro de usuario en la plataforma
Scenario: El uusuario visualiza el formulario de registro en la plataforma
Given el usuario cuenta con el rol de usuario no registrado
When el usuario selecciona el icono de Perfil
And el usuario selecciona la opcion "Registrate aqui"
Then el sistema muestra un formulario "Crear una cuenta" con los campos <Nombres>, <Apellidos>, <Email> y <Password> los cuales son requeridos
Examples: Datos de salida
| Crear una cuenta |
| Nombres | Apellidos | Email | Password |
| Ximena | Gutierrez | [email protected] | xxxxxxx |
Scenario: El usuario se registra en la plataforma
Given el usuario cuenta con el rol de usuario no registrado
When el usuario selecciona el icono de Perfil
And el usuario selecciona la opcion "Registrate aqui"
And el usuario completa los campos <Nombres>, <Apellidos>, <Email> y <Password>
And el usuario selecciona el boton "Registrarse"
Entonces el sistema crea la cuenta del usuario en la plataforma
And el sistema dirige al usuario a la pantalla principal
Examples: Datos de entrada
| Nombres | Apellidos | Email | Password |
| Ximena | Gutierrez | [email protected] | xxxxxxx |
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="box">
<!--3.使用组件-->
<demo></demo>
<demo></demo>
<demo-T2></demo-T2>
vm:{{msg1}}
</div>
<div id="box2">
<!--访问不到demo的内容-->
</div>
<!--2.定义模板内容-->
<template id="mytemp">
<div>
<img src="loading.gif" height="100px"/>
<h3 @click="fn">这里是标题内容 {{msg}}</h3>
</div>
</template>
</body>
<script type="text/javascript">
let vm = new Vue({
el:'#box',
data:{msg1:'msg'},
//1.定义局部组件
components:{
//组件名称
'demo':{
template:'#mytemp',
data:function(){
return {msg:'局部组件'}
},
methods:{
fn(){console.log('fn')}
}
},
'demoT2':{
template:'<div>我是一个div</div>'
}
}
})
let vm2 = new Vue({
el:'#box2'
})
</script>
</html>
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CSS3</title>
<link rel="stylesheet" href="css/reveal.min.css"/>
<link rel="stylesheet" href="css/theme/default.css" id="theme"/>
<!-- For syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css"/>
<link rel="stylesheet" href="css/main.css"/>
</head>
<body class="day2">
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<!--Slide 1-->
<section>
<p><strong>Thought</strong>Works<sup style="font-size: 14px">®</sup></p>
<h2>CSS-Center</h2>
<small>Presented by</small>
<p>Yanmin XING</p>
</section>
<!--Slide 2-->
<section>
<h3>Content</h3>
<ul>
<li>Horizontally center</li>
<li>Vertical center</li>
</ul>
</section>
<!--Slide 3-->
<section>
<h3>Horizontally center</h3>
<ul>
<li>text-align</li>
<li>margin & width</li>
</ul>
<br>
</section>
<section>
<section>
<h3>text-align</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="jbWOWq" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/jbWOWq/'>Centering Inline Elements</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
<section>
<h3>text-align</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="ZbQYBM" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/ZbQYBM/'>Centering Row of Blocks</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
<section>
<h3>text-align</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="Gpogvr" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/Gpogvr/'>Gpogvr</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
</section>
<section>
<section>
<h3>margin & width</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="MaKYvP" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/MaKYvP/'>Centering Single Block Level Element</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
<section>
<h3>margin & width</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="qObEPB" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/qObEPB/'>Centering Blocks on Top of Each Other</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
<section>
<h3>margin & width</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="WQrbXM" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/WQrbXM/'>WQrbXM</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
</section>
<section>
<h3>Include</h3>
<p>当要水平居中的元素为一个或多个行内元素时建议采用text:align;为一个或多个block元素时用margin & width</p>
</section>
<section>
<h3>Vertical center</h3>
<ul>
<li>padding</li>
<li>line-height</li>
<li>vertical-align</li>
<li>absolute & top & transform</li>
</ul>
<br>
</section>
<section>
<section>
<h3>line-height</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="VveYRm" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/VveYRm/'>Centering a line with line-height</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
<section>
<img src="images/b.png" alt="">
</section>
<section>
<img src="images/a.png" alt="">
</section>
<section>
<h3>Include</h3>
<p>这种方法对运用在小元素上是非常有用的,比如说让一个button、图片或者单行文本字段。</p>
</section>
</section>
<section>
<section>
<h3>vertical-align</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="BojNjP" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/BojNjP/'>vertical-align examples</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
<section>
<h3>Include</h3>
<p>这种方法对于单行内高度不等的多个行内元素的垂直居中对齐较适用</p>
</section>
</section>
<section>
<section>
<h3 style="font-size: 46px;">absolute & top & margin-top</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="EVPaqj" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/EVPaqj/'>Center Block with Fixed Height</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
<section>
<h3 style="font-size: 46px;">absolute & top & transform</h3>
<p data-height="268" data-theme-id="18843" data-slug-hash="OyMPKv" data-default-tab="result" data-user="Ellmi" class='codepen'>See the Pen <a href='http://codepen.io/Ellmi/pen/OyMPKv/'>Center Block with Unknown Height</a> by Yanmin (<a href='http://codepen.io/Ellmi'>@Ellmi</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
</section>
<section>
<h3>Include</h3>
<p>这种方法在需要计算padding时以达到居中对齐的case时替换适用,在高度固定时,要留意内容大小超过容器时的效果,当高度不固定时,因为元素进行绝对定位后脱离文档流,要注意对周边元素的影响.</p>
</section>
</section>
<section>
<h2>Thank you</h2>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
center: true,
history: true,
theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/fade/none
// Parallax scrolling
// parallaxBackgroundImage: 'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg',
// parallaxBackgroundSize: '2100px 900px',
// Optional libraries used to extend on reveal.js
dependencies: [
// { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
// { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
</script>
</body>
</html>
|
import { Flex, Divider, Text, Stack, SimpleGrid, Box, Table, Tbody, Tr, Td, Badge } from '@chakra-ui/react'
import { useContract, useContractRead, useAddress } from '@thirdweb-dev/react'
import { contracts } from '../../blockchain/post-deployment/addresses'
import { abi } from '../../blockchain/out/ChainopolyCenter.sol/ChainopolyCenter.json'
import { useState, useEffect } from 'react'
import Auction from './Auction'
import { ethers } from 'ethers'
import { toUtf8Bytes } from '@ethersproject/strings'
import { useToast } from '@chakra-ui/react'
export default function GameData(props: any) {
/* **************************************************** */
/* ETHERS SETUP */
/* **************************************************** */
const provider = new ethers.providers.JsonRpcProvider()
const e_chainopolyCenter = new ethers.Contract(contracts.ChainopolyCenter, abi, provider)
const signer = provider.getSigner()
/* **************************************************** */
/* THIRD WEB SETUP */
/* **************************************************** */
const player = useAddress()
const { contract: chainopolyCenter } = useContract(contracts.ChainopolyCenter, abi)
let { data: playerGameID, isLoading: loadingID } = useContractRead(chainopolyCenter, 'getPlayerGameID', [player])
/* ****************************************************** */
/* HELPER FUNCTIONS */
/* ****************************************************** */
function sliceAddress(address: string): string {
return `${address.slice(0, 4)}...${address.slice(-4)}`
}
function decodeAddress(address: string): string {
return '0x' + address.slice(26)
}
async function whoseTurnIsIt(): Promise<void> {
try {
const [playerInTurn, mins, secs] = await e_chainopolyCenter.connect(signer).whoseTurnIsIt()
props.setPlayerInTurn(playerInTurn)
setPlayerInTurn(playerInTurn)
setMins(Number(mins))
setSecs(Number(secs))
setPlayerInTurnUsername(await getUsername(playerInTurn))
} catch (error) {
setPlayerInTurn(ethers.constants.AddressZero)
}
}
async function getHousesAndHotelsLeft(): Promise<{ houses: number; hotels: number }> {
if (chainopolyCenter && playerGameID > 0 && !loadingID) {
const [houses, hotels] = await chainopolyCenter.call('housesAndHotelsLeft')
setHousesAndHotelsLeft({ houses, hotels })
return { houses, hotels }
} else return { houses: 0, hotels: 0 }
}
async function getStablecoinStationCash(): Promise<number> {
if (props.playerGameID > 0) {
const cash = await e_chainopolyCenter.connect(signer).cashInFreeStablecoinStation()
setCashInStablecoinStation(cash)
return cash
}
return 0
}
async function getUsername(player: any): Promise<string> {
let username = await e_chainopolyCenter.connect(signer).getUsername(player)
return username
}
/* **************************************************** */
/* EVENTS */
/* **************************************************** */
let events: any = []
const [lastDiceRoll, setLastDiceRoll] = useState(0)
const [landlord, setLandlord] = useState('')
const [rentPaid, setRentPaid] = useState(0)
const [newPosition, setNewPosition] = useState(0)
const [doubles, setDoubles] = useState(false)
const [playerEnding, setPlayerEnding] = useState('')
const [transferAmount, setTransferAmount] = useState(0)
const [from, setFrom] = useState('')
const [to, setTo] = useState('')
const [nextPlayer, setNextPlayer] = useState('')
const toast = useToast()
let lastEventIndex = 0
async function getEvents(): Promise<void> {
const amountOfEventsBeforeAction = events.length
events = await chainopolyCenter?.events.getAllEvents({ order: 'asc' })
if (events.length - 1 > lastEventIndex) {
decodeEvents(amountOfEventsBeforeAction, events.length - amountOfEventsBeforeAction)
lastEventIndex = events.length - 1
}
}
function decodeEvents(eventsBefore: number, amountOfEvents: number) {
const hash = ethers.utils.keccak256
const DiceRolled = hash(toUtf8Bytes('DiceRolled(uint256,bool)'))
const PlayerMoved = hash(toUtf8Bytes('PlayerMoved(address,uint256)'))
const PlayerHasToDecideToBuyOrNot = hash(toUtf8Bytes('PlayerHasToDecideToBuyOrNot(address,uint256,string)'))
const AuctionStarted = hash(toUtf8Bytes('AuctionStarted(uint256,uint256)'))
const AuctionWon = hash(toUtf8Bytes('AuctionWon(address,uint256,uint256)'))
const IncomeTaxPaid = hash(toUtf8Bytes('IncomeTaxPaid(address,uint256)'))
const LuxuryTaxPaid = hash(toUtf8Bytes('LuxuryTaxPaid(address,uint256)'))
const Transfer = hash(toUtf8Bytes('Transfer(address,address,uint256)'))
const RentPaid = hash(toUtf8Bytes('RentPaid(address,address,uint256)'))
const TurnEnded = hash(toUtf8Bytes('TurnEnded(address,address)'))
const DefiBootyBagCardDrawn = hash(toUtf8Bytes('DefiBootyBagCardDrawn(address,uint256)'))
const PlayerUsedBlocktrain = hash(toUtf8Bytes('PlayerUsedBlocktrain(address,uint256,uint256)'))
const PlayerSentToJail = hash(toUtf8Bytes('PlayerSentToJail(address)'))
const RolledOutOfJail = hash(toUtf8Bytes('RolledOutOfJail(address)'))
const GetOutOfJailCardUsed = hash(toUtf8Bytes('GetOutOfJailCardUsed(address)'))
const OfferMade = hash(toUtf8Bytes('OfferMade(address,address,uint256)'))
const OfferCancelled = hash(toUtf8Bytes('OfferCancelled(uint256)'))
const OfferRejected = hash(toUtf8Bytes('OfferRejected(uint256)'))
const OfferAccepted = hash(toUtf8Bytes('OfferAccepted(uint256)'))
const ZeroKnowledgeChanceCardDrawn = hash(toUtf8Bytes('ZeroKnowledgeChanceCardDrawn(address,uint256)'))
const PropertyBought = hash(toUtf8Bytes('PropertyBought(address,uint256,string,uint256)'))
const PropertySold = hash(toUtf8Bytes('PropertySold(address,uint256,uint256)'))
for (let i = eventsBefore; i < amountOfEvents; i++) {
if (events[i].transaction.topics[0] == DiceRolled) {
const numberRolled = events[i].transaction.topics[1]
const doubles = events[i].transaction.topics[2]
setLastDiceRoll(Number(numberRolled))
setDoubles(Boolean(doubles))
} else if (events[i].transaction.topics[0] == PlayerMoved) {
const player = events[i].transaction.topics[1]
const newPosition = events[i].transaction.topics[2]
if (player == props.signer.getAddress()) setNewPosition(Number(newPosition))
} else if (events[i].transaction.topics[0] == PlayerHasToDecideToBuyOrNot) {
const player = events[i].transaction.topics[1]
const property = events[i].transaction.topics[2]
const propertyName = events[i].transaction.topics[3]
} else if (events[i].transaction.topics[0] == AuctionStarted) {
const property = events[i].transaction.topics[1]
const initialPrice = events[i].transaction.topics[2]
} else if (events[i].transaction.topics[0] == AuctionWon) {
const winner = events[i].transaction.topics[1]
const property = events[i].transaction.topics[2]
const highestBid = events[i].transaction.topics[3]
} else if (events[i].transaction.topics[0] == RentPaid) {
const player = decodeAddress(events[i].transaction.topics[1])
const landlord = decodeAddress(events[i].transaction.topics[2])
const rent = Number(events[i].transaction.topics[3])
setRentPaid(rent)
setLandlord(landlord)
if (player == props.signer.getAddress() || landlord == props.signer.getAddress()) {
toast({
title: 'Rent Paid',
description: `${sliceAddress(player)} paid $${rent} in rent to ${sliceAddress(landlord)}`,
status: 'success',
duration: 1000,
isClosable: true,
})
}
} else if (events[i].transaction.topics[0] == PropertyBought) {
const buyer = events[i].transaction.topics[1]
const property = events[i].transaction.topics[2]
const propertyName = events[i].transaction.topics[3]
const pricePaid = events[i].transaction.topics[4]
} else if (events[i].transaction.topics[0] == TurnEnded) {
const playerEnding = decodeAddress(events[i].transaction.topics[1])
const nextPlayer = decodeAddress(events[i].transaction.topics[2])
setPlayerEnding(playerEnding)
setNextPlayer(nextPlayer)
const ending = 'ending'
if (!toast.isActive(ending)) {
toast({
title: 'Turn ended',
description: `${sliceAddress(playerEnding)} passes turn to ${sliceAddress(nextPlayer)}`,
status: 'success',
duration: 1000,
isClosable: true,
id: 'ending',
})
}
} else if (events[i].transaction.topics[0] == Transfer) {
setFrom(decodeAddress(events[i].transaction.topics[1]))
setTo(decodeAddress(events[i].transaction.topics[2]))
setTransferAmount(Number(events[i].transaction.topics[3]))
const transfer = 'transfer'
if (!toast.isActive(transfer)) {
toast({
title: 'Transfer',
description: `${sliceAddress(from)} transferred $${transferAmount} to ${sliceAddress(to)}`,
status: 'success',
duration: 1000,
id: 'transfer',
isClosable: true,
})
}
}
}
}
/* **************************************************** */
/* REACT STATE */
/* **************************************************** */
const [playerInTurnUsername, setPlayerInTurnUsername] = useState('')
const [playerInTurn, setPlayerInTurn] = useState('')
const [secs, setSecs] = useState(0)
const [mins, setMins] = useState(0)
const [playerToQuery, setPlayerToQuery] = useState('')
const [cashInStablecoinStation, setCashInStablecoinStation] = useState(0)
const [housesAndHotelsLeft, setHousesAndHotelsLeft] = useState({ houses: 0, hotels: 0 })
/* **************************************************** */
/* USE EFFECT */
/* **************************************************** */
useEffect(() => {
const interval = setInterval(() => {
getHousesAndHotelsLeft()
getStablecoinStationCash()
whoseTurnIsIt()
if (events.length - 1 > lastEventIndex) getEvents()
}, 500)
return () => clearInterval(interval)
}, [player, mins, secs])
/* ****************************************************** */
/* RETURN */
/* ****************************************************** */
return (
<Flex fontSize={'2xl'} alignContent={'center'} p={4} border={'1px'}>
<Stack align={'center'}>
{/* GAME STATUS */}
<Text fontSize="2xl" align={'center'}>{`Game #${props.playerGameID}`}</Text>
<Divider />
<Badge fontSize="2xl" colorScheme="purple">
{props.gameStatus}
</Badge>
{/* GAME VARIANTS */}
<Box>
{sliceAddress(from)}
{sliceAddress(to)}
{Number(playerGameID) > 0 && (
<SimpleGrid columns={1}>
{Object.entries(props.variants).map(([variant, isActive]) =>
isActive ? (
<Badge m={1} colorScheme="green" key={variant}>
{variant}
</Badge>
) : (
<Badge m={1} colorScheme="red" key={variant}>
{variant}
</Badge>
)
)}
</SimpleGrid>
)}
</Box>
<Table variant="striped" fontSize={'xs'}>
<Tbody>
<Tr>
<Td>Current turn: </Td>
<Td>
{playerInTurn == player
? `Your turn!`
: playerInTurnUsername == ''
? `It's ${sliceAddress(playerInTurn)}'s turn`
: `It's ${playerInTurnUsername}'s turn`}
</Td>
</Tr>
<Tr>
<Td>Time left for current turn: </Td>
<Td fontWeight={'bold'}>
{mins == 0 && secs == 0 ? `No time left` : secs > 9 ? `${mins} : ${secs}` : `${mins} : 0${secs}`}
</Td>
</Tr>
{props.joinedPlayers.length > 0 ? (
<Tr>
<Td>Joined players: </Td>
<Td>
{props.joinedPlayers.map((player: any, index: number) => (
<div key={index}>
{index + 1}. {sliceAddress(player)}
</div>
))}
</Td>
</Tr>
) : (
<></>
)}
<Tr>
<Td>Rounds: </Td>
<Td>{props.currentRounds}</Td>
</Tr>
<Tr>
<Td>Dice rolled: </Td>
<Td>{String(props.diceRolledThisTurn)}</Td>
</Tr>
<Tr>
<Td>Doubles count: </Td>
<Td>{props.doublesCount}</Td>
</Tr>
<Tr>
<Td>Cash in Stablecoin Station</Td>
<Td> ${Number(cashInStablecoinStation)}</Td>
</Tr>
<Tr>
<Td>Houses: </Td>
<Td>{Number(housesAndHotelsLeft.houses)}</Td>
</Tr>
<Tr>
<Td>Hotels: </Td>
<Td>{Number(housesAndHotelsLeft.hotels)}</Td>
</Tr>
<Tr>
<Td>Player near bankruptcy</Td>
<Td>{sliceAddress(props.playerNearBankruptcy)}</Td>
</Tr>
<Tr>
<Td>Time per turn: </Td>
<Td>{props.timePerTurn / 60} minutes</Td>
</Tr>
<Tr>
<Td>Blocktrain fee: </Td>
<Td>${props.blocktrainFee}</Td>
</Tr>
<Tr>
<Td>Minimum rounds: </Td>
<Td>{props.minimumRounds}</Td>
</Tr>
</Tbody>
</Table>
{props.gameStatus == 'Auctioning' ? <Auction gameStatus={props.gameStatus} /> : <></>}
</Stack>
</Flex>
)
}
|
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.run.deployment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.android.ddmlib.Client;
import com.android.ddmlib.IDevice;
import com.android.tools.idea.execution.common.AndroidExecutionTarget;
import com.android.tools.idea.execution.common.DeployableToDevice;
import com.android.tools.idea.run.AndroidDevice;
import com.android.tools.idea.run.AndroidRunConfigurationBase;
import com.android.tools.idea.run.DeploymentApplicationService;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
import com.intellij.execution.ExecutionTarget;
import com.intellij.execution.application.ApplicationConfiguration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
@RunWith(JUnit4.class)
public final class DeviceAndSnapshotComboBoxExecutionTargetTest {
private final AsyncDevicesGetter myGetter = Mockito.mock(AsyncDevicesGetter.class);
@Test
public void isApplicationRunningAsync() throws Exception {
// Arrange
var ddmlibDevice = Mockito.mock(IDevice.class);
var androidDevice = Mockito.mock(AndroidDevice.class);
Mockito.when(androidDevice.isRunning()).thenReturn(true);
Mockito.when(androidDevice.getLaunchedDevice()).thenReturn(Futures.immediateFuture(ddmlibDevice));
var device = new VirtualDevice.Builder()
.setKey(Keys.PIXEL_4_API_30)
.setConnectionTime(Instant.parse("2023-07-19T22:34:37.356453499Z"))
.setName("Pixel 4 API 30")
.setAndroidDevice(androidDevice)
.build();
Mockito.when(myGetter.get()).thenReturn(Optional.of(List.of(device)));
var service = Mockito.mock(DeploymentApplicationService.class);
Mockito.when(service.findClient(ddmlibDevice, "com.google.myapplication")).thenReturn(List.of(Mockito.mock(Client.class)));
var target = new DeviceAndSnapshotComboBoxExecutionTarget(Set.of(new QuickBootTarget(Keys.PIXEL_4_API_30)), myGetter, () -> service);
// Act
var future = target.isApplicationRunningAsync("com.google.myapplication");
// Assert
// noinspection BlockingMethodInNonBlockingContext
assertTrue(future.get(60, TimeUnit.SECONDS));
}
@Test
public void getDevices() {
// Arrange
Key key = new VirtualDeviceName("Pixel_3_API_29");
Device device = new VirtualDevice.Builder()
.setName("Pixel 3 API 29")
.setKey(key)
.setAndroidDevice(Mockito.mock(AndroidDevice.class))
.build();
Mockito.when(myGetter.get()).thenReturn(Optional.of(Collections.singletonList(device)));
AndroidExecutionTarget target = new DeviceAndSnapshotComboBoxExecutionTarget(Collections.singleton(new QuickBootTarget(key)), myGetter);
// Act
Object actualDevices = target.getRunningDevices();
// Assert
assertEquals(Collections.emptyList(), actualDevices);
}
@Test
public void getDisplayNameCase1() {
// Arrange
Key key = new VirtualDeviceName("Pixel_3_API_29");
Device device = new VirtualDevice.Builder()
.setName("Pixel 3 API 29")
.setKey(key)
.setAndroidDevice(Mockito.mock(AndroidDevice.class))
.build();
Mockito.when(myGetter.get()).thenReturn(Optional.of(Collections.singletonList(device)));
ExecutionTarget target = new DeviceAndSnapshotComboBoxExecutionTarget(Collections.singleton(new QuickBootTarget(key)), myGetter);
// Act
Object actualDisplayName = target.getDisplayName();
// Assert
assertEquals("Pixel 3 API 29", actualDisplayName);
}
@Test
public void getDisplayNameDefault() {
// Arrange
Key key1 = new VirtualDeviceName("Pixel_2_API_29");
Key key2 = new VirtualDeviceName("Pixel_3_API_29");
Collection<Target> targets = Sets.newHashSet(new QuickBootTarget(key1), new QuickBootTarget(key2));
Device device1 = new VirtualDevice.Builder()
.setName("Pixel 2 API 29")
.setKey(key1)
.setAndroidDevice(Mockito.mock(AndroidDevice.class))
.build();
Device device2 = new VirtualDevice.Builder()
.setName("Pixel 3 API 29")
.setKey(key2)
.setAndroidDevice(Mockito.mock(AndroidDevice.class))
.build();
Mockito.when(myGetter.get()).thenReturn(Optional.of(Arrays.asList(device1, device2)));
ExecutionTarget target = new DeviceAndSnapshotComboBoxExecutionTarget(targets, myGetter);
// Act
Object actualDisplayName = target.getDisplayName();
// Assert
assertEquals("Multiple Devices", actualDisplayName);
}
@Test
public void deviceTargetNotSuggestedForConfigurationsThatDoNotDeployToLocalDevice() {
var target = new DeviceAndSnapshotComboBoxExecutionTarget(Collections.emptyList(), myGetter);
var androidDeployableLocally = Mockito.mock(AndroidRunConfigurationBase.class);
Mockito.when(androidDeployableLocally.getUserData(DeployableToDevice.getKEY())).thenReturn(true);
var androidNonDeployableLocally = Mockito.mock(AndroidRunConfigurationBase.class);
var nonDeployableLocally = Mockito.mock(ApplicationConfiguration.class);
assertTrue(target.canRun(androidDeployableLocally));
assertFalse(target.canRun(androidNonDeployableLocally));
assertFalse(target.canRun(nonDeployableLocally));
}
}
|
from typing import List
from sqlalchemy.orm import aliased
from sqlalchemy.sql import text
from sqlalchemy import func
from fastapi import APIRouter
from core.database import get_session
from db.session import SessionLocal
from models.estadisticas_grupo import EstadisticasGrupo
from models.grupo import Grupo
from models.equipo import Equipo
from schemas import estadisticas
router = APIRouter()
@router.get("/grupos/{grupo_id}", response_model=List[estadisticas.EstadisticasGrupo])
def estadisticas_grupo(grupo_id: int):
"""
Get positions by group
"""
query = """
select
g.nombre as grupo,
e.equipo_id,
eq.nombre,
e.pts,
e.goles_favor,
e.goles_contra,
e.diferencia
from
estadisticas_grupo e
join grupos g on e.grupo_id = g.id
join equipos eq on e.equipo_id = eq.id
where grupo_id = {grupo_id}
order by e.pts desc, e.diferencia desc
"""
query = text(query.format(grupo_id=grupo_id))
with get_session() as session:
results = session.execute(query).fetchall()
return [
dict(zip(row._mapping.keys(), row))
for row in results
]
@router.get("/clasificados", response_model=List[estadisticas.EquiposClasificados])
def equipos_clasificados():
"""
Get qualifiers by group
"""
query = text("""
with estadisticas as (
select
g.nombre as grupo,
ROW_NUMBER() OVER (PARTITION BY g.nombre ORDER BY e.pts DESC, e.diferencia DESC) AS equipo_posicion,
e.equipo_id,
eq.nombre,
e.pts,
e.goles_favor,
e.goles_contra,
e.diferencia
from
estadisticas_grupo e
join grupos g on e.grupo_id = g.id
join equipos eq on e.equipo_id = eq.id
order by e.pts desc, e.diferencia desc
)
select e.*
from estadisticas e
where e.equipo_posicion <= 2
order by grupo asc, equipo_posicion asc
""")
with get_session() as session:
results = session.execute(query).fetchall()
return [
dict(zip(row._mapping.keys(), row))
for row in results
]
|
<!-- Utiliza selectores CSS para dar estilo a elementos -->
<!--
Cuando escribiste <h2 style="color: red;">CatPhotoApp</h2>, estabas aplicando un estilo a ese elemento h2 específico usando CSS en línea; CSS significa hojas de estilo en cascada (Cascading Style Sheets).
Inline CSS es una de las formas de especificar el estilo de un elemento, pero existe una mejor forma de aplicar estilos CSS.
<style>
</style>
-->
<!-- Ejercicio -->
<!-- Elimina el atributo de estilo de tu elemento h2 y crea un bloque style para agregar tu código CSS. Añade el código CSS necesario para hacer que todos los elementos h2 sean de color azul (blue). -->
<style>
h2 {
color: blue;
}
</style>
<h2>CatPhotoApp</h2>
<main>
<p>Click here to view more <a href="#">cat photos</a>.</p>
<a href="#"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>
<div>
<p>Things cats love:</p>
<ul>
<li>cat nip</li>
<li>laser pointers</li>
<li>lasagna</li>
</ul>
<p>Top 3 things cats hate:</p>
<ol>
<li>flea treatment</li>
<li>thunder</li>
<li>other cats</li>
</ol>
</div>
<form action="https://freecatphotoapp.com/submit-cat-photo">
<label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<label><input type="checkbox" name="personality" checked> Loving</label>
<label><input type="checkbox" name="personality"> Lazy</label>
<label><input type="checkbox" name="personality"> Energetic</label><br>
<input type="text" placeholder="cat photo URL" required>
<button type="submit">Submit</button>
</form>
</main>
|
import { Telegraf, Markup } from 'telegraf';
import { Token } from './config.js';
import { ApiId} from './config.js';
import pkg from 'pg';
const { Client } = pkg;
import { bd_connect } from './bd.js'
import fetch from "node-fetch";
const config_bd = bd_connect
const pic = 'https://pythonist.ru/wp-content/uploads/2020/03/photo_2021-02-03_10-47-04-350x2000-1.jpg'
const client = new Client(config_bd)
client.connect(async (err) => {
if (err) console.log(err);
else {
console.log("All is OK");
}
});
const bot = new Telegraf(Token);
const start_hello = 'Здравствуйте. Нажмите на любую интересующую Вас кнопку'
let rassul_flag = false
bot.start((ctx) => ctx.reply(start_hello, main_menu(ctx)))
bot.on('text', (ctx) => {
switch (ctx.message.text) {
case ("Хочу почитать!"): read_python(ctx); ; break;
case ("Погода в Канаде"): weather(ctx); break;
case ("Сделать рассылку"): ctx.replyWithHTML(`<b>Вы выбрали рассылку всем пользователям. Вы уверен что хотите это сделать?</b>`, shure()); break;
case ("Отмена"): ctx.reply('😞',otm()); break;
case ("Уверен"): rassul_flag = true; ctx.replyWithHTML(`<b>Введите сообщение, которое хотите отправить всем пользователям.</b>`); break;
default: if(rassul_flag) {rassul(ctx);}
else {ctx.reply('Извините, я пока не настолько умный')}
break;
}})
function rassul(contx){
let message_text = contx.message.text
const chat_id = contx.from.id
const text_command = 'Select chat_id from "users" where chat_id != $1'
const vars_command = [chat_id]
try {
client.query(text_command, vars_command, async (err, res) => {
if (err) {
console.log(err.stack)
} else {
for (let i=0; i<res.rowCount; i++)
{
contx.telegram.sendMessage(res.rows[i].chat_id, message_text)
}
contx.reply('Сообщение успешно доставлено', otm())
}
})
}
catch{}
}
function otm()
{
rassul_flag = false
return Markup.keyboard([
["Погода в Канаде"],
["Хочу почитать!"],
["Сделать рассылку"]
]).resize();
}
function shure(){
return Markup.keyboard([
["Уверен", "Отмена"]
]).resize();
}
function read_python(cont){
let caption_pic = 'Идеальный карманный справочник для быстрого ознакомления с особенностями работы разработчиков на Python. Вы найдете море краткой информации о типах и операторах в Python, именах специальных методов, встроенных функциях, исключениях и других часто используемых стандартных модулях.'
cont.replyWithPhoto(pic, {
caption: caption_pic
})
cont.replyWithDocument({source: './karmaniy_spravochnik_po_piton.zip'})
}
function weather(context){
let temperature, temperature_feel, message
fetch(`https://api.openweathermap.org/data/2.5/weather?q=Ottava&appid=${ApiId}`)
.then(function (resp){return resp.json()})
.then(function (data){
temperature = data.main.temp-273,15
temperature = temperature.toFixed(2)
temperature_feel = data.main.feels_like-273,15
temperature_feel =temperature_feel.toFixed(2)
message=`Погода в городе Оттава, Канада: \nТемпература: ${temperature}\n Ощущается как: ${temperature_feel}`
context.reply(message)
})
.catch()
}
function main_menu(cont) {
const username = '@' + cont.from.username
const chat_id = cont.from.id
const tetx_main_check = 'Select * from "users" where username = $1'
const values_main_check = [username]
try {
client.query(tetx_main_check, values_main_check, async (err, res) => {
if (err) {
console.log(err.stack)
} else {
if (res.rowCount == 0) {
const tetx_main = 'INSERT INTO "users" (username, first_name, chat_id) VALUES ($1, $2, $3)'
const values_main = [username, cont.from.first_name, chat_id]
try {
client.query(tetx_main, values_main);
}
catch (err) { console.log(err.stack) }
}
else {
const tetx_main_upd = 'Update "users" set username = $1, first_name= $2, chat_id = $3 where username = $1'
const values_main_upd = [username, cont.from.first_name, chat_id]
try {
await client.query(tetx_main_upd, values_main_upd);
}
catch (err) { console.log(err.stack) }
}
}
});
}
catch { }
return Markup.keyboard([
["Погода в Канаде"],
["Хочу почитать!"],
["Сделать рассылку"]
]).resize();
}
bot.launch();
|
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Communautés des Camerounais de Madagascar</title>
<link rel="shortcut icon" href="./images/favicon.png" type="image/x-icon">
<!-- --------- fontawesome ------------------->
<link rel="stylesheet" href="./css/all.css">
<link rel="stylesheet" href="./css/v4-shims.min.css">
<!-- ------------ bootstrap 4.4.1 ------------------------- -->
<link rel="stylesheet" href="./css/bootstrap-4.4.1.min.css">
<!-- --------- Owl-Carousel ------------------->
<link rel="stylesheet" href="./css/owl.carousel.min.css">
<link rel="stylesheet" href="./css/owl.theme.default.min.css">
<!-- ------------ AOS Library ------------------------- -->
<link rel="stylesheet" href="./css/aos.css">
<!-- ------------ style personnalisée ------------------------- -->
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<div class="navtop bg-warning py-1">
<div class="site-title ml-5" data-aos="fade-right" data-aos-delay="200">
<h1 class="no-m-p">Covid-19 à Madagascar [DONGMO Raymond Lionel IMTICIA5 N°8]</h1>
</div>
<div class="media-conctact mr-5" data-aos="fade-left" data-aos-delay="200">
<div class="icoms mr-5"><i class="fa fa-phone"><span> 80584</span></i></div>
<div class="social-network" data-aos="fade-up" data-aos-delay="300">
<a href="" class="fa fa-facebook"></a>
<a href="" class="fa fa-whatsapp"></a>
<a href="" class="fa fa-twitch"></a>
<a href="" class="fa fa-instagram"></a>
</div>
</div>
</div>
<div class="menu-principal">
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
<div class="navbar-header">
<a href="#" class="navbar-brand"><img width="90px" height="38px" class="img-fluid" src="./images/logo1.png" alt="Covid-19" title="Covid-19 à Madagascar"></a>
</div>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon" deluminate_imagetype="unknown"></span>
</button>
<div class="collapse navbar-collapse justify-content-end mr-5" id="navbarCollapse">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">ACCUEIL <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Centres de traitement
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#"> CCO IVATO </a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">ETSY MAHAMASINA</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Palais des sports de la capitale</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
pharmacie de garde
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266"> Pharmacie d'Ambohibao </a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266">Pharmacie d'Anosizato</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266">Pharmacie de la Pergola</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266"> Pharmacie Ny Aina </a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266">Pharmacie Métropole</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266">Pharmacie Hanitra</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Actualités</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
</div>
</header>
<!-- fin menu navigation -->
<main class="site-content">
<!--site intro-->
<section class="intro slider" id="slider">
<div class="slider-intro my-5 py-4">
<div class="row">
<div class="image col-md-6 py-4 px-1">
<img class="img-fluid" src="images/font-covid19.png" alt="">
</div>
<div class="stat col-md-6 py-3" data-aos="zoom-in" data-aos-delay="300">
<div class="mada pb-3">
<h4 class="tete pb-2 px-3">Vue d'ensemble des cas</h4>
<h5 class="text-center">Madagascar</h5>
<div class="donne row">
<div class="col-sm-4 spart">
<h6 class="yello">Nombre total de cas</h6>
<h2>17 587</h2>
<span>+ 0 <i class="fa fa-arrow-down"></i></span>
</div>
<div class="col-sm-4 spart">
<h6 class="green">Guérisons</h6>
<h2>16 992</h2>
<span>+ 0 <i class="fa fa-arrow-down"></i></span>
</div>
<div class="col-sm-4">
<h6 class="red">Décès</h6>
<h2>259</h2>
<span>+ 0 <i class="fa fa-arrow-down"></i> </span>
</div>
</div>
</div>
<div class="monde">
<h5 class="text-center p-2">Monde entier</h5>
<div class="donne row">
<div class="col-sm-4 spart">
<h6 class="yello">Nombre total de cas</h6>
<h2>73 476 721</h2>
<span>+ 496 156 <i class="fa fa-arrow-up"></i></span>
</div>
<div class="col-sm-4 spart">
<h6 class="green">Guérisons</h6>
<h2>41 616 042 </h2>
</div>
<div class="col-sm-4">
<h6 class="red">Décès</h6>
<h2>1 635 464</h2>
<span>+ 8 443 <i class="fa fa-arrow-up"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--fin site intro-->
<!--presntation-->
<section class="presentation mx-5">
<div class="nous-mission-valeur-vision">
<div class="row mx-2">
<div class="col-md-7">
<div class="nous">
<h1 class="titre nous-titre text-center py-2">Conseils au grand public</h1>
<div class="nous-text px-3 pt-3">
<h2> Protégez-vous et protégez les autres de la COVID-19 </h2>
<p>
Si la COVID-19 se propage dans votre communauté, protégez-vous en prenant quelques précautions simples, comme maintenir une distance physique avec autrui, porter un masque, bien ventiler les pièces, éviter les rassemblements, vous laver les mains, et
tousser dans votre coude replié ou un mouchoir. Suivez les recommandations locales là où vous vivez et travaillez. Faites tout cela !
</p>
<h2>Que faire pour vous protéger et protéger les autres de la COVID-19</h2>
<p>
<ul>
<li>
Laissez une distance d’au moins un mètre entre vous et les autres pour réduire le risque d'infection lorsque vous toussez, éternuez ou parlez. Gardez une distance encore plus grande entre vous et les autres lorsque vous êtes à l'intérieur. Plus vous êtes
éloigné, mieux c'est.
</li>
<li>
Considérez le port du masque comme normal lorsque vous êtes avec d'autres personnes. Pour que les masques soient aussi efficaces que possible, il est essentiel de les porter, de les ranger et de les laver ou de les jeter correctement.
</li>
<li>Lavez-vous les mains avant de mettre votre masque, ainsi qu'avant de l’enlever et après l'avoir fait.</li>
<li>Assurez-vous qu'il couvre à la fois votre nez, votre bouche et votre menton.</li>
<li>Lorsque vous enlevez votre masque, placez-le dans un sac en plastique propre et lavez-le, chaque jour, s’il s’agit d’un masque en tissu ou jetez-le dans un poubelle si c’est un masque médical.</li>
<li> N’utilisez pas de masques avec des valves d’expiration.</li>
</ul>
</p>
</div>
</div>
</div>
<div class="v-m-v col-md-5">
<div class="vision-mission-valeur px-2">
<div class="mision mb-3">
<h2 class="titre mision-titre first">Comment rendre votre environnement plus sûr</h2>
<div class="mission-text">
<ul>
<li>Évitez les espaces clos, très fréquentés, où vous serez en contact étroit avec d'autres personnes.</li>
<li>Si vous retrouvez d'autres personnes, faites-le à l'extérieur. </li>
<li>Si vous retrouvez d'autres personnes, faites-le à l'extérieur. </li>
</ul>
</div>
</div>
<div class="vision mb-3">
<h2 class="titre mision-titre" data-aos="fade-right" data-aos-delay="500">N’oubliez pas les principes de base d’une bonne hygiène </h2>
<div class="mission-text">
<ul>
<li>Lavez-vous les mains régulièrement et soigneusement avec une solution hydroalcoolique ou à l’eau et au savon.</li>
<li>Évitez de vous toucher les yeux, le nez et la bouche. </li>
<li>En cas de toux ou d’éternuement, couvrez-vous la bouche et le nez avec le pli du coude ou avec un mouchoir.</li>
<li>Nettoyez et désinfectez les surfaces fréquemment, en particulier celles qui sont régulièrement touchées</li>
</ul>
</div>
</div>
<div class="valeur mb-3" data-aos="fade-right" data-aos-delay="200">
<h2 class="titre mision-titre" data-aos="fade-right" data-aos-delay="300">Restez chez vous si vous ne vous sentez pas bien</h2>
<div class="mission-text">
<ul>
<li>Apprenez à connaître tout l’éventail des symptômes de la COVID-19.</li>
<li>Restez chez vous et isolez-vous si vous avez des symptômes mineurs tels que la toux, des maux de tête, une légère fièvre..</li>
<li>En cas de fièvre, de toux et de difficulté à respirer, demandez immédiatement l'avis d'un médecin.</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--fin presentation-->
<!--les pharmacies de garde-->
<section class="membre blog">
<div class="membre-intro" data-aos="fade-in" data-aos-delay="200">
<h2 class="text-center titre mt-5">Les pharmacies de garde</h2>
<p class="intro text-center mx-5 px-5 mb-3">
vous pouvez à tout moment contacter l'une des ces pharmacies pour obtenir des medicaments de premier secour.
</p>
</div>
<div class="container">
<div class="owl-carousel owl-theme blog-post">
<div class="blog-content" data-aos="fade-right" data-aos-delay="200">
<img src="./images/Logo-Pharmacie-1.jpg" alt="post-1">
<div class="blog-title">
<h5>Pharmacie d'Ambohibao</h5>
<span> Ouvert 24h/24</span>
<div class="social-network mt-2" data-aos="fade-up" data-aos-delay="300">
<i href="" class="fa fa-phone">020 22 444 33</i>
<a href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266"> <i class="fa fa-map"></i> 4, Antananarivo</a>
</div>
</div>
</div>
<div class="blog-content" data-aos="fade-in" data-aos-delay="200">
<img src="./images/Pharmacie-Anosizato.jpg" alt="post-1">
<div class="blog-title">
<h5>Pharmacie d'Anosizato</h5>
<span> Ouvert 24h/24</span>
<div class="social-network mt-2" data-aos="fade-up" data-aos-delay="300">
<i href="" class="fa fa-phone">020 22 631 43</i>
<a href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266"><i class="fa fa-map"></i> Lot AZ 83 AII Anosizato andrefana </a>
</div>
</div>
</div>
<div class="blog-content" data-aos="fade-left" data-aos-delay="200">
<img src="./images/Pharmacie-de-la-Pergola.jpg" alt="post-1">
<div class="blog-title">
<h5>Pharmacie de la Pergola</h5>
<span> Ouvert 24h/24</span>
<div class="social-network mt-2" data-aos="fade-up" data-aos-delay="300">
<i href="" class="fa fa-phone">020 22 444 33</i>
<a href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266"><i class="fa fa-map"></i> 4, Antananarivo</a>
</div>
</div>
</div>
<div class="blog-content" data-aos="fade-right" data-aos-delay="200">
<img src="./images/phqr-my-aina.png" alt="post-1">
<div class="blog-title">
<h5>Pharmacie Ny Aina</h5>
<span> Ouvert 24h/24</span>
<div class="social-network mt-2" data-aos="fade-up" data-aos-delay="300">
<i href="" class="fa fa-phone">020 22 229 95</i>
<a href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266">
<i class="fa fa-map"></i> Rue Foloalindahy Malagasy</a>
</div>
</div>
</div>
<div class="blog-content" data-aos="fade-right" data-aos-delay="200">
<img src="./images/metropole3-1178x800.jpg" alt="post-1">
<div class="blog-title">
<h5>Pharmacie Métropole</h5>
<span> Ouvert ⋅ Ferme à 18:00</span>
<div class="social-network mt-2" data-aos="fade-up" data-aos-delay="300">
<i href="" class="fa fa-phone">020 22 200 25</i>
<a href="https://www.google.com/maps/dir//Pharmacie+d'Ambohibao,+4,+Antananarivo/@-18.8456135,47.4039057,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f081b156b34b51:0xb3d1d79b2fab3a45!2m2!1d47.4739462!2d-18.8456266">
<i class="fa fa-map"></i> 7 Lalana Ratsimilaho</a>
</div>
</div>
</div>
<div class="blog-content" data-aos="fade-right" data-aos-delay="200">
<img src="./images/Pharmacie-Hanitra.jpg" alt="post-1">
<div class="blog-title">
<h5>Pharmacie Hanitra</h5>
<span> Ouvert ⋅ Ferme à 18:00</span>
<div class="social-network mt-2" data-aos="fade-up" data-aos-delay="300">
<i href="" class="fa fa-phone"> 020 22 312 81</i>
<a href="https://www.google.com/maps/dir//Pharmacie+Hanitra,+Lalana+Kaleba+Razafimino,+Antananarivo/@-18.916315,47.4671334,12z/data=!3m1!4b1!4m9!4m8!1m1!4e2!1m5!1m1!1s0x21f07de5568daedd:0x379eecb7b88a89c3!2m2!1d47.5371739!2d-18.9163281">
<i class="fa fa-map"></i> Lalana Kaleba Razafimino</a>
</div>
</div>
</div>
</div>
<div class="owl-navigation">
<span class="owl-nav-prev"><i class="fas fa-long-arrow-alt-left"></i></span>
<span class="owl-nav-next"><i class="fas fa-long-arrow-alt-right"></i></span>
</div>
</div>
</div>
</section>
<!--fin pharmacies-->
<!--les centres de traitement-->
<section class="activites mx-5 pb-2">
<div class="activites-header" data-aos="fade-in" data-aos-delay="200">
<h1 class="titre text-center">Les différents centre de traitement </h1>
</div>
<div class="activites-content">
<div class="row">
<div class="activite col-md-6" data-aos="flip-up" data-aos-delay="200">
<div class="profile">
<div class="title">
<h3 class="titre">CCO IVATO</h3>
</div>
<div class="description">
Outre ces nouveaux centres de traitement du COVID-19, le CHU Anosiala, l’hôpital Manarapenitra d’Andohatapenaka ainsi que le Centre Médical Covid-19 du Village Voara Andohatapenaka
</div>
<div class="image-d swiper-slide">
<img class="img-fluid" src="./images/R01_1987.jpg" alt="">
</div>
</div>
</div>
<div class="activite col-md-6" data-aos="flip-up" data-aos-delay="300">
<div class="profile">
<div class="title">
<h3 class="titre">ETSY MAHAMASINA</h3>
</div>
<div class="description">
CENTRE DE TRAITEMENT COVID-19
</div>
<div class="image-d"><img class="img-fluid" src="./images/mqdefault.png" alt=""></div>
</div>
</div>
</div>
<div class="row">
<div class="activite col-md-6" data-aos="flip-up" data-aos-delay="200">
<div class="profile">
<div class="title">
<h3 class="titre"> HJRA : HOPITAL JOSEPH RAVOAHANGY </h3>
</div>
<div class="description">
contact hopital, clinique, matérnité à antananarivo, madagascar
</div>
<div class="image-d"><img class="img-fluid" src="./images/timthumb.jpeg" alt=""></div>
</div>
</div>
<div class="activite col-md-6" data-aos="flip-up" data-aos-delay="300">
<div class="profile">
<div class="title">
<h3 class="titre">Centre Hospitalier Universitaire Joseph Raseta Befelatanana</h3>
</div>
<div class="description">
Le Centre Hospitalier Universitaire Joseph Raseta Befelatanana connu comme l’hopital Befelatanana est l’un des principaux établissements hospitaliers d’Antananarivo
</div>
<div class="image-d"><img class="img-fluid" src="./images/centre-hospitalier.png" alt=""></div>
</div>
</div>
</div>
</div>
</section>
<!-- fin centres-->
<section class="actualite mx-5 pb-4 mt-4">
<div class="actu-header header-tilte my-4" data-aos="fade-in" data-aos-delay="200">
<h1 class="top-pres titre text-center">Quelques Actualités</h1>
</div>
<div class="row site-content mx-4">
<div class="posts col-md-9">
<div class="card mb-3" style="width: 100%;">
<div class="card-items" data-aos="zoom-in" data-aos-delay="200">
<div class="card-titre text-center bg-dark">
<h1 class="titre"><a href="#">un nouveau centre de traitement inauguré dans la capitale</a></h1>
</div>
<div class="row no-gutters">
<div class="post-image col-md-6">
<img src="./images/coronavirus-madagascar-cvo.jpg" class="card-img" alt="...">
<div class="post-info flex-row text-center">
<span><i class="fas fa-calendar-alt text-gray"></i> 27 juillet 2020 </span>
</div>
</div>
<div class="col-md-6">
<div class="card-body">
<p class="card-text">
Une capacité d’accueil d’environ 250 patients Pour faire face à la propagation du nouveau coronavirus, notamment dans la capitale Antananarivo, qui est l’un des foyers actuels du virus dans le pays, un nouveau centre de traitement Covid-19 (CTC) vient
d’être inauguré.
</p>
<div class="btn-card-footer text-center"> <a class="btn btn-warning" href="">Plus d'information</a> </div>
</div>
</div>
</div>
</div>
<hr>
<div class="card-items" data-aos="zoom-in" data-aos-delay="200">
<div class="card-titre text-center bg-dark">
<h1 class="titre"><a href="#">l’étrange stratégie sanitaire de Madagascar</a></h1>
</div>
<div class="row no-gutters">
<div class="post-image col-md-6">
<img src="./images/3e0a1c3_651118083-000-8vq2hj.jpg" class="card-img" alt="...">
<div class="post-info flex-row text-center">
<span><i class="fas fa-calendar-alt text-gray"></i> 16 décembre 2020</span>
</div>
</div>
<div class="col-md-6">
<div class="card-body">
<p class="card-text">
<p> Madagascar, qui avait jusqu’au 7 décembre pour s’inscrire sur la liste des pays bénéficiaires, a préféré passer son tour.</p> Le gouvernement se montre sceptique à l’égard de la vaccination, préférant pour l’instant
mettre en avant un remède traditionnel dont l’efficacité n’a pas été prouvée.
</p>
<div class="btn-card-footer text-center"> <a class="btn btn-warning" href="">Plus d'information</a> </div>
</div>
</div>
</div>
</div>
<hr>
<div class="card-items" data-aos="zoom-in" data-aos-delay="200">
<div class="card-titre text-center bg-dark">
<h1 class="titre"><a href="#">Madagascar n’adhère pas au programme mondial de vaccination contre la Covid-19</a></h1>
</div>
<div class="row no-gutters">
<div class="post-image col-md-6">
<img src="./images/vaccin-anticoronavirus.jpg" class="card-img" alt="...">
<div class="post-info flex-row text-center">
<span><i class="fas fa-calendar-alt text-gray"></i> 11 décembre 20202</span>
</div>
</div>
<div class="col-md-6">
<div class="card-body">
<p class="card-text">
Alors que la plupart des pays en Afrique essaient de s’assurer les doses de vaccins nécessaires contre la Covid-19, Madagascar ne semble pas être emballée. Le pays ne veut pas participer au programme de vaccination l’OMS.
</p>
<div class="btn-card-footer text-center"> <a class="btn btn-warning" href="">Plus d'information</a> </div>
</div>
</div>
</div>
</div>
<hr>
<div class="card-items" data-aos="zoom-in" data-aos-delay="200">
<div class="card-titre text-center bg-dark">
<h1 class="titre"><a href="#">l’explosion des cas de Covid-19 met en cause la stratégie du gouvernement</a></h1>
</div>
<div class="row no-gutters">
<div class="post-image col-md-6">
<img src="./images/186a7de_448397348-000_1U52G7.jpg" class="card-img" alt="...">
<div class="post-info flex-row text-center">
<span><i class="fas fa-calendar-alt text-gray"></i> 14 juillet 20202</span>
</div>
</div>
<div class="col-md-6">
<div class="card-body">
<p class="card-text">
En un mois, les chiffres de contamination au nouveau coronavirus et de décès ont quasiment été multipliés par quatre.
</p>
<div class="btn-card-footer text-center"> <a class="btn btn-warning" href="">Plus d'information</a> </div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="btn-footer text-center" data-aos="fade-down" data-aos-delay="400">
<a href="">Plus d'Actualités</a>
</div>
</div>
<!-- sidebar -->
<aside class="sidebar col-md-3">
<div class="category">
<h2>Categorie</h2>
<ul class="category-list">
<li class="list-items" data-aos="fade-left" data-aos-delay="100">
<a href="#">Educations</a>
<span>(05)</span>
</li>
<li class="list-items" data-aos="fade-left" data-aos-delay="200">
<a href="#">Vivre à Madagascar</a>
<span>(02)</span>
</li>
<li class="list-items" data-aos="fade-left" data-aos-delay="300">
<a href="#">Emplois</a>
<span>(07)</span>
</li>
<li class="list-items" data-aos="fade-left" data-aos-delay="400">
<a href="#">Tourisme</a>
<span>(01)</span>
</li>
<li class="list-items" data-aos="fade-left" data-aos-delay="500">
<a href="#">Alimentations</a>
<span>(08)</span>
</li>
</ul>
</div>
<div class="popular-post">
<h2>Actualités populaires</h2>
<div class="post-content" data-aos="flip-up" data-aos-delay="200">
<div class="post-image">
<div>
<img src="./images/aj_air-france-b777-300ER.jpg" class="img" alt="blog1">
</div>
<div class="post-info flex-row">
<span><i class="fas fa-calendar-alt text-gray"></i> 14 décembre 2020</span>
</div>
</div>
<div class="post-title">
<a href="#">Air France se pose de nouveau à Madagascar</a>
</div>
</div>
<div class="post-content" data-aos="flip-up" data-aos-delay="300">
<div class="post-image">
<div>
<img src="./images/des-plus-vulnerables.jpeg" class="img" alt="blog1">
</div>
<div class="post-info flex-row">
<span><i class="fas fa-calendar-alt text-gray"></i> 23 novembre 2020</span>
</div>
</div>
<div class="post-title">
<a href="#">Mourir de faim dans le sud de Madagascar</a>
</div>
</div>
<div class="post-content" data-aos="flip-up" data-aos-delay="400">
<div class="post-image">
<div>
<img src="./images/BB1bYANh.jpeg" class="img" alt="blog1">
</div>
<div class="post-info flex-row">
<span><i class="fas fa-calendar-alt text-gray"></i> 16 décembre 2020</span>
</div>
</div>
<div class="post-title">
<a href="#">résurgence des contaminations mais un taux de mortalité faible</a>
</div>
</div>
<div class="post-content" data-aos="flip-up" data-aos-delay="500">
<div class="post-image">
<div>
<img src="./images/mada-actu.png" class="img" alt="blog1">
</div>
<div class="post-info flex-row">
<span><i class="fas fa-calendar-alt text-gray"></i> 16 décembre 2020</span>
</div>
</div>
<div class="post-title">
<a href="#">Bilan positif des sensibilisations sur les instruments de mesure aux marchés</a>
</div>
</div>
</div>
<div class="sidebar-recherche" data-aos="fade-up" data-aos-delay="300">
<h2>Recherche</h2>
<div class="form-element">
<input type="text" class="input-element" placeholder="Rechercher dans Actualité">
<button class="btn form-btn">Rechercher</button>
</div>
</div>
</aside>
</div>
</section>
</main>
<!-- --------------------------- Footer ---------------------------------------- -->
<footer class="footer">
<div class="footer-content px-5">
<div class="contact-n colonne" data-aos="fade-right" data-aos-delay="200">
<h2>Contactez nous</h2>
<p>
<div class="phone"><i class="fa fa-phone-alt"></i>088547</div>
<div class="Email"><i class="fa fa-envelope-o"></i>md'[email protected]</div>
<div class="btn-contact"><button class="btn btn-info"><a href="template/contact.html">Laisser un message!</a> </button></div>
</p>
</div>
<div class="mini-galerie colonne" data-aos="fade-left" data-aos-delay="200">
<h2>Galerie</h2>
<div class="galerie-content">
<img src="./images/antananarivo.jpg" alt="insta1">
<img src="./images/covid19.jpg" alt="insta2">
<img src="./images/R01_1987.jpg" alt="insta3">
<img src="./images/vaccin-anticoronavirus.jpg" alt="insta4">
<img src="./images/Logo-Pharmacie-1.jpg" alt="insta5">
<img src="./images/BB1bYANh.jpeg" alt="insta6">
</div>
<div class="btn-plus-g text-center"><button class="btn btn-info"><a href="templates/galerie.html">Plus de photos</a> </button></div>
</div>
<div class="follow colonne" data-aos="fade-left" data-aos-delay="200">
<h2>Suivez-nous</h2>
<p>Nous sommes présents sur <i class="fa fa-arrow-down"></i></p>
<div class="text-center mt-4">
<i class="fab fa-facebook-f"></i>
<i class="fab fa-twitter"></i>
<i class="fab fa-instagram"></i>
<i class="fab fa-youtube"></i>
</div>
</div>
</div>
<div class="move-up">
<span><i class="fas fa-arrow-circle-up fa-2x"></i></span>
</div>
<div class="end flex-row">
<span class="text-gray text-center">
Copyright ©2020 Tout droit réservé | par drl_dev
<a href="" target="_black"><i class="fa fa-link"></i>
site.com</a>
</span>
</div>
</footer>
<script src="./js/jquery3.4.1.min.js"></script>
<script src="./js/bootstrap-4.4.1.min.js"></script>
<!-- --------- Owl-Carousel js ------------------->
<script src="./js/owl.carousel.min.js"></script>
<!-- ------------ AOS js Library ------------------------- -->
<script src="./js/aos.js"></script>
<script src="./js/mainM2.js"></script>
</body>
</html>
|
import classNames from 'classnames/bind';
import styles from './SmallHeader.module.scss/';
import HeadlessTippy from '@tippyjs/react/headless';
import { Link } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUser } from '@fortawesome/free-solid-svg-icons';
import { memo, useEffect, useRef, useState } from 'react';
import httpRequest from '../../../httpRequest/httprequest';
import SmallSearch from '../SmallSearch/SmallSearch';
const cx = classNames.bind(styles);
function SmallHeader() {
const [genre, setGenre] = useState([]);
const isFirst = useRef(true);
const getnav = async () => {
// await httpRequest
// .get('/configuration/countries', { params: { api_key: import.meta.env.VITE_API_Key } })
// .then((res) => setCountries(res.data));
let movieGenres = await httpRequest.get('/genre/movie/list', {
params: { api_key: import.meta.env.VITE_API_Key },
});
let tvGenres = await httpRequest.get('/genre/tv/list', { params: { api_key: import.meta.env.VITE_API_Key } });
setGenre([...movieGenres.data.genres, ...tvGenres.data.genres]);
};
const countries = [
'Argentina',
'Australia',
'Austria',
'Belgium',
'Brazil',
'Canada',
'China',
'Denmark',
'Viet Nam',
'Finland',
'France',
'Germany',
'Hong Kong',
'Hungary',
'India',
'International',
'Ireland',
'Israel',
'Italy',
'Japan',
'Luxembourg',
'Mexico',
'Netherlands',
'New Zealand',
'Norway',
'Philippines',
'Poland',
'Romania',
'Russia',
'South Africa',
'South Korea',
'Spain',
'Sweden',
'Switzerland',
'Thailand',
'Turkey',
'United Kingdom',
'United States',
];
useEffect(() => {
if (isFirst.current) {
getnav();
isFirst.current = false;
}
}, []);
return (
<div className={cx('Header-Wrapper')}>
<nav className={cx('Header-nav')}>
<Link to="/" className={cx('Header-logo-link')}>
<div className={cx('Header-logo')}>
<img src="https://s1.bunnycdn.ru/assets/sites/flixtor/logo.png" alt="" />
<h1 className={cx('Header-logo-title')}>FlixTor.video</h1>
</div>
</Link>
<ul className={cx('Header-nav-list')}>
<Link to={'/'}>
<li className={cx('Header-nav-list-item')}>Home</li>
</Link>
<div>
<HeadlessTippy
interactive
placement="bottom-start"
render={(attrs) => (
<ul className={cx('genre-child')} tabIndex="-1" {...attrs}>
{genre.map((item, index) => (
<Link
key={index}
to={`/genre/${item.name}?page=1`}
className={cx('genre-child-link')}
>
<li className={cx('genre-child-item')}>{item.name}</li>
</Link>
))}
</ul>
)}
>
<li className={cx('Header-nav-list-item')}>genre</li>
</HeadlessTippy>
</div>
<div>
<HeadlessTippy
interactive
placement="bottom-start"
render={(attrs) => (
<ul className={cx('country-child')} tabIndex="-1" {...attrs}>
{countries.sort().map((item, index) => (
<Link
key={index}
to={`/country/${item}?page=1`}
className={cx('country-child-link')}
>
<li className={cx('country-child-item')}>{item}</li>
</Link>
))}
</ul>
)}
>
<li className={cx('Header-nav-list-item')}>country</li>
</HeadlessTippy>
</div>
<Link to={'/movie?page=1'}>
<li className={cx('Header-nav-list-item')}>movies</li>
</Link>
<Link to="/tv?page=1">
<li className={cx('Header-nav-list-item')}>tv shows</li>
</Link>
{/* <Link to="/">
<li className={cx('Header-nav-list-item')}>top imdb</li>
</Link> */}
</ul>
<SmallSearch />
<div className={cx('Header-login-register')}>
<FontAwesomeIcon icon={faUser} />
<span>Login/ </span>
<span>Register</span>
</div>
</nav>
</div>
);
}
export default memo(SmallHeader);
|
/** @typedef {import("../validator").BasicValidation} BasicValidation */
/**
* @param {String} rangeA1
*
* @returns {BasicValidation}
*/
export function validateRangeA1Notation_(rangeA1) {
/**
* @param {String} message
* @returns {BasicValidation}
*/
function _bad(message) {
return {
is_valid: false,
message,
};
}
/**
* @param {String} str
* @param {RegExp} re
*
* @returns {String|null}
*/
function _regexExtract(str, re) {
const match = str.match(re);
return match ? match[0] : null;
}
if (typeof rangeA1 !== "string") {
return _bad("Range must be a string");
}
if (rangeA1 === "") {
return _bad("Range cannot be empty string");
}
const unexpectedChar = _regexExtract(rangeA1, /[^$A-Z:0-9]/i);
if (unexpectedChar) {
if (unexpectedChar === " ") {
return _bad("Range has unexpected space: ' '");
}
return _bad("Range has unexpected char: " + unexpectedChar);
}
if (/:{2,}/.test(rangeA1)) {
return _bad("Range has more than 1 ':' in a row");
}
if (/\${2,}/.test(rangeA1)) {
return _bad("Range has more than 1 '$' in a row");
}
if (/^\d+$/.test(rangeA1)) {
return _bad("Range cannot be of numbers only");
}
if (/^[A-Z]+$/i.test(rangeA1)) {
return _bad("Range cannot be of letters only");
}
if (/^\$+$/.test(rangeA1)) {
return _bad("Range cannot be of '$' only");
}
if (/^:+$/.test(rangeA1)) {
return _bad("Range cannot be of ':' only");
}
if (/^:.*$/.test(rangeA1)) {
return _bad("Range cannot start with ':'");
}
if (/^.*:$/.test(rangeA1)) {
return _bad("Range cannot end with ':'");
}
if (/\$:/.test(rangeA1)) {
return _bad("Range cannot have lock '$' after colon ':'");
}
if (/\$$/.test(rangeA1)) {
return _bad("Range cannot have lock '$' in the end");
}
if (/^\d+[A-Z]+.*/i.test(rangeA1)) {
return _bad("Range cannot start with number before letter");
}
if (/\d+[A-Z]+/i.test(rangeA1)) {
return _bad("Range cannot have number before letter");
}
if (/\d+\$[A-Z]+/i.test(rangeA1)) {
return _bad("Range cannot have number before '$' and letter");
}
if (/\d+\$\d+/i.test(rangeA1)) {
return _bad("Range cannot have '$' below to numbers");
}
if (/[A-Z]+\$[A-Z]+/i.test(rangeA1)) {
return _bad("Range cannot have '$' below to letters");
}
const parts = rangeA1.split(":");
if (parts.length > 2) {
return _bad("Range cannot have more than 2 parts: star and ending cell");
}
const _ok = {
is_valid: true,
message: "ok",
};
/**
* @param {String} str
* @returns {'cell' | 'column' | 'row'}
*/
function _getSemiRangeType(str) {
const cleaned = str.replace(/\$/g, "");
if (/^\d+$/.test(cleaned)) return "row";
if (/^[A-Z]+$/i.test(cleaned)) return "column";
return "cell";
}
if (parts.length === 2) {
const type1 = _getSemiRangeType(parts[0]);
if (type1 === "cell") return _ok;
const type2 = _getSemiRangeType(parts[1]);
if (type2 === "cell") return _ok;
if (type1 !== type2) {
return _bad(`Cannot form range from ${type1} and ${type2}`);
}
}
return _ok;
}
|
import React from 'react';
import './App.css';
import Nav from './components/nav/nav';
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import News from './components/news/news';
import Music from './components/music/music';
import Settings from './components/settings/settings';
import DialogsContainer from './components/dialogs/dialogsContainer';
import { UsersPage } from './components/users/userContainer';
import ProfileContainer from './components/profile/profileContainer';
import HeaderContainer from './components/header/headerContainer';
import Login from './components/login/login';
const App = () => {
return (
<BrowserRouter>
<div className='app-wrapper'>
<HeaderContainer />
<Nav />
<div className='app-wrapper-content'>
<Routes>
<Route path="/" element={<Navigate to="/profile" />} />
<Route path='/dialogs' element={<DialogsContainer />} />
<Route path='/profile/*' element={<ProfileContainer />} />
<Route path='/news' element={<News />} />
<Route path='/music' element={<Music />} />
<Route path='/users' element={<UsersPage/>} />
<Route path='/settings' element={<Settings />} />
<Route path='/login' element={<Login/>} />
</Routes>
</div>
</div>
</BrowserRouter>
);
}
export default App;
|
package com.example.fastcampusmysql.util;
import com.example.fastcampusmysql.domain.member.entity.Member;
import org.jeasy.random.EasyRandom;
import org.jeasy.random.EasyRandomParameters;
public class MemberFixtureFactory {
// default seed를 사용하는 메서드
static public Member create() {
var param = new EasyRandomParameters();
return new EasyRandom(param).nextObject(Member.class);
}
static public Member create(Long seed) {
// fixture library의 EasyRandom
// -> 오픈소스
// -> Java bean을 만들어주는 라이브러리
// -> 테스트 코드를 짤 때 굉장히 편함
// -> https://github.com/j-easy/easy-random
// -> seed(), objectPoolSize(), randomizationDepth(), timeRange() 등을 지정해주면 nextObject() 호출을 통해 값을 랜덤하게 채워서 객체가 만들어짐
// EasyRandom -> 일정 상태 정도의 star를 받음
// -> 넷플리스, JetBrains, Mulesoft 등이 사용하고 있음
// -> Netflix 등을 누르면 해당 코드를 사용하고 있는 부분으로 연결됨 -> 이를 통해 큰 기업에서는 테스트 코드를 어떻게 짜는지 알 수 있음
// EasyRandom 사용 시에 여러 어려움을 겪을 수 있음
// -> https://github.com/j-easy/easy-random/wiki
// -> 위 사이트를 통해 대략적인 EasyRandom에 대한 설명을 볼 수 있고, Configuration Parameters 부분을 읽어보면 유연하게 사용할 수 있음
// EasyRandom를 보면
// -> 기본 생성자가 있고, 파라미터를 주입받지 않고 만들어줌
// -> EasyRandomParameters를 주입받는 생성자가 존재
// -> EasyRandomParameters를 통해서 타입별로 어떤 랜덤한 값을 넣어줄 것인지, 범위는 어떻게 정할 것인지 등을 정할 수 있음
// EasyRandom -> 시드 기반으로 동작
// -> 랜덤한 수를 만들 때 시드를 주는 것처럼 시드가 동일한 상태에서 nextObject()를 계속 동일한 시드의 EasyRandom을 만들어서 nextObject()를 호출하면 계속 똑같은 값을 가진 객체가 반환됨
// -> 그래서, 이를 공유할 수 있어야 함
// 시드를 다르게 줘야 함
// -> EasyRandomParameters 내부를 들어가보면 seed라는 값이 있음
// -> seed는 setSeed()를 통해 설정 가능
// -> setSeed()는 void 타입인데, seed() 메서드는 EasyRandomParameters를 반환하므로 이를 사용(setSeed()를 진행하고 해당 객체를 그대로 반환)
// EasyRandom의 좋은 점 -> org.jeasy.random 안에 들어가보면 randomizers라는 패키지가 보임
// -> 여기서 여러가지 객체를 Randomizer로 쓸 수 있음!
var param = new EasyRandomParameters().seed(seed);
return new EasyRandom(param).nextObject(Member.class);
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
* { color: #223322; }
input { font-family: 나눔고딕코딩; font-weight: bold; }
input:focus { background-color: #eeeedd; }
input.btn { width: 80px; font-weight: bold; font-family: 맑은 고딕; }
input.btn.hover { color: orange; }
td { text-align: center; }
.txt { text-align: right; }
textarea { font-family: 나눔고딕코딩; font-weight: bold; }
</style>
<script type="text/javascript">
function startGame()
{
// alert("hi");
var strArr = ["가위", "바위", "보"];
// ※ 『Math.random()』 -- 0.0 ~ 1.0 사이의 실수 형태의 난수 발생
// alert(Math.random());
//--==>> 0.766998641307403
//--==>> 0.4109600484810563
//--==>> 0.8891190658099526
//--==>> 0.5872271195933243
//--==>> 0.6510073930869265
// 현재 우리에게 필요한 것은
// 1 ~ 3 의 정수 형태의 난수
var c = parseInt(Math.random()*3) + 1;
// alert(c);
//--==>> 2
//--==>> 1
//--==>> 3
//--==>> 2
//--==>> 2
var u = parseInt(document.getElementById("txtUser").value);
var msg = "";
msg += "사용자:" + strArr[u-1] + ", 컴퓨터:" + strArr[c-1];
// alert(msg);
// if (u==1 && c==1 || u==2 && c==2 || u==3 && c==3)
if (u==c)
{
msg += " → 비겼습니다.";
}
// else if (u==1 && c==2 || u==2 && c==3 || u==3 && c==1)
else if(u%3 == (c+2)%3)
{
msg += " → 컴퓨터가 이겼습니다.";
}
else
{
msg += " → 당신이 이겼습니다.";
}
document.getElementById("txtResult").value = msg;
}
</script>
</head>
<body>
<div>
<h1>자바스크립트 난수 발생 함수</h1>
<hr>
</div>
<!--
가위 바위 보 게임을 구성한다.
HTML, CSS, Javascrpt 를 활용한다.
자바스크립트 난수 발생 함수를 찾아 활용한다.
페이지 레이아웃
---------------------------------------------------------
입력(1.가위 2.바위 3.보) : [ 2 ] <게임결과확인>
[ 사용자:바위 컴퓨터:보 → 컴퓨터가 이겼습니다. ]
---------------------------------------------------------
-->
<div>
입력(1.가위 2.바위 3.보)
<input type="text" id="txtUser" style="width: 65px;">
<button type="button" class="btn" style="width: 120px;"
onclick="startGame()">게임 결과 확인</button>
<br><br>
<input type="text" id="txtResult" style="width: 375px;" readonly="readonly" class="txt">
</div>
</body>
</html>
|
package br.edu.infnet.elberthapp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import br.edu.infnet.elberthapp.model.domain.Produto;
import br.edu.infnet.elberthapp.model.domain.Sobremesa;
import br.edu.infnet.elberthapp.model.domain.Usuario;
import br.edu.infnet.elberthapp.model.service.SobremesaService;
@Controller
public class SobremesaController {
private String mensagem;
@Autowired
private SobremesaService sobremesaService;
@Autowired
private ProdutoController produtoController;
@GetMapping(value = "/sobremesa")
public String telaCadastro() {
return "sobremesa/cadastro";
}
@GetMapping(value = "/sobremesa/listar")
public String telaLista(Model model, @SessionAttribute("user") Usuario usuario) {
model.addAttribute("msg", mensagem);
model.addAttribute("listagem", sobremesaService.obterLista(usuario));
return "sobremesa/lista";
}
@PostMapping(value = "/sobremesa/incluir")
public String incluir(Sobremesa sobremesa, @SessionAttribute("user") Usuario usuario) {
sobremesa.setUsuario(usuario);
sobremesaService.incluir(sobremesa);
mensagem = "A inclusão da sobremesa "+ sobremesa.getNome()+" ("+sobremesa.getValor()+") foi realizada com sucesso!";
return "redirect:/sobremesa/listar";
}
@GetMapping(value = "/sobremesa/{id}/excluir")
public String excluir(@PathVariable Integer id) {
Produto produto = null;
try {
produto = produtoController.exclusao(id);
mensagem = "A exclusão da sobremesa "+produto.getNome()+" foi realizada com sucesso!";
} catch (Exception e) {
mensagem = "Impossível realizar a exclusão do produto ("+id+")! Este produto está associado a um pedido.";
}
return "redirect:/sobremesa/listar";
}
}
|
defmodule SprintPlanning.User do
use Ecto.Schema
import Ecto.Changeset
alias SprintPlanning.User
@primary_key {:id, :binary_id, autogenerate: true}
@derive {Phoenix.Param, key: :id}
schema "users" do
field :email, :string
field :password, :string
timestamps()
end
@doc false
def changeset(%User{}=user, attrs) do
user
|> cast(attrs, [:email, :password])
|> validate_required([:email, :password])
end
end
|
import { Component, OnInit } from '@angular/core';
import { NgbDateStruct, NgbCalendar } from '@ng-bootstrap/ng-bootstrap';
import { DashboardService } from './dashboard.service';
import { ToastService } from 'src/app/core/services/toast.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss'],
preserveWhitespaces: true
})
export class DashboardComponent implements OnInit {
userCount: number = 0;
ambulanceCount: number = 0;
crewMemberCount: number = 0;
hospitalCount: number = 0;
hospitalUserCount: number = 0;
systemUserCount: number = 0;
completedBookingCount: number = 0;
pendingBookingCount: number = 0;
dates: string[] = [];
counts: number[] = [];
/**
* Apex chart
*/
public monthlyBookingsChartOptions: any = {};
// colors and font variables for apex chart
obj = {
primary: "#6571ff",
secondary: "#7987a1",
success: "#05a34a",
info: "#66d1d1",
warning: "#fbbc06",
danger: "#ff3366",
light: "#e9ecef",
dark: "#060c17",
muted: "#7987a1",
gridBorder: "rgba(77, 138, 240, .15)",
bodyColor: "#000",
cardBg: "#fff",
fontFamily: "'Roboto', Helvetica, sans-serif"
}
/**
* NgbDatepicker
*/
currentDate: NgbDateStruct;
constructor(
private calendar: NgbCalendar,
private dashboardService: DashboardService,
private toast: ToastService,
) { }
ngOnInit(): void {
this.getSummary();
this.getPastMonthBookingSummary();
this.currentDate = this.calendar.getToday();
// this.monthlyBookingsChartOptions = getMonthlyBookingsChartOptions(this.obj, this.dates, this.counts);
// Some RTL fixes. (feel free to remove if you are using LTR))
if (document.querySelector('html')?.getAttribute('dir') === 'rtl') {
this.addRtlOptions();
}
}
async getSummary() {
try {
const response = await this.dashboardService.getSummary();
if (response.status == 200) {
this.userCount = response.data.userCount;
this.ambulanceCount = response.data.ambulanceCount;
this.crewMemberCount = response.data.crewMemberCount;
this.hospitalCount = response.data.hospitalCount;
this.hospitalUserCount = response.data.hospitalUserCount;
this.systemUserCount = response.data.systemUserCount;
this.completedBookingCount = response.data.completedBookingCount;
this.pendingBookingCount = response.data.pendingBookingCount;
}
} catch (error: any) {
this.toast.show(error.statusText, 'error');
}
}
async getPastMonthBookingSummary() {
try {
const response = await this.dashboardService.getBookingSummaryForPastMonth();
if (response.status == 200) {
response.data.forEach((data: any) => {
this.dates.push(data.date);
this.counts.push(data.count);
});
this.monthlyBookingsChartOptions = getMonthlyBookingsChartOptions(this.obj, this.dates, this.counts);
}
} catch (error: any) {
this.toast.show(error.statusText, 'error');
}
}
addRtlOptions() {
// Monthly bookings chart
this.monthlyBookingsChartOptions.yaxis.labels.offsetX = -10;
this.monthlyBookingsChartOptions.yaxis.title.offsetX = -70;
}
}
function getMonthlyBookingsChartOptions(obj: any, dates: string[], counts: number[]) {
return {
series: [{
name: 'Bookings',
data: counts
}],
chart: {
type: 'bar',
height: '318',
parentHeightOffset: 0,
foreColor: obj.bodyColor,
background: obj.cardBg,
toolbar: {
show: false
},
},
colors: [obj.primary],
fill: {
opacity: .9
},
grid: {
padding: {
bottom: -4
},
borderColor: obj.gridBorder,
xaxis: {
lines: {
show: true
}
}
},
xaxis: {
type: 'datetime',
categories: dates,
axisBorder: {
color: obj.gridBorder,
},
axisTicks: {
color: obj.gridBorder,
},
},
yaxis: {
title: {
text: 'Number of Bookings',
style: {
size: 9,
color: obj.muted
}
},
labels: {
offsetX: 0,
},
},
legend: {
show: true,
position: "top",
horizontalAlign: 'center',
fontFamily: obj.fontFamily,
itemMargin: {
horizontal: 8,
vertical: 0
},
},
stroke: {
width: 0
},
dataLabels: {
enabled: true,
style: {
fontSize: '10px',
fontFamily: obj.fontFamily,
},
offsetY: -27
},
plotOptions: {
bar: {
columnWidth: "50%",
borderRadius: 4,
dataLabels: {
position: 'top',
orientation: 'vertical',
}
},
}
}
}
|
import { useSelector, useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { getContacts } from 'redux/contacts/contacts-selector';
import { fetchContacts } from 'redux/operations';
import ContactForm from './ContactForm/ContactForm';
import ContactList from './ContactList/ContactList';
import Filter from './Filter/Filter';
import css from './App.module.css';
const App = () => {
const contacts = useSelector(getContacts);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchContacts());
}, [dispatch]);
const isContacts = Boolean(contacts.length);
return (
<div className={css.wrap}>
<h1>Phonebook</h1>
<ContactForm />
<h2>Contacts</h2>
{isContacts && <Filter />}
{isContacts && <ContactList />}
{!isContacts && <p>No contacts in list</p>}
</div>
);
};
export default App;
|
import ValueObject from 'App/ValueObjects/ValueObject'
import Card from 'App/ValueObjects/Card'
export enum DeckType {
FULL = 'FULL',
SHORT = 'SHORT',
}
export default class Deck extends ValueObject<Deck> {
public deckId: string
public type: DeckType
public shuffled: boolean
public remaining: number
public cards: Card[]
public serialize(): {} {
return {
deckId: this.deckId,
type: this.type,
// SQLite will return this as a number, so we convert it to a boolean here
shuffled: !!this.shuffled,
remaining: this.remaining || 0,
cards: this.cards?.map((card) => card.serialize()) || undefined,
}
}
}
|
import { useRowExpansion } from "@/hooks/useRowExpansion";
import type { CellFunctions, Columns } from "@/types/table";
import { type ReactNode, type Dispatch, type SetStateAction } from "react";
import {
Table,
TableHeader,
TableRow,
TableHead,
TableBody,
TableCell,
} from "./table";
type TableProps<T, P> = {
columns: Columns<T, P>[];
data: T[];
setRowData?: Dispatch<SetStateAction<T | null>>;
cellProps?: P | undefined;
expandedComponent?: (props: { rowData: T }) => ReactNode;
};
const DataTable = <T, P>({
columns,
data,
setRowData,
cellProps,
expandedComponent,
}: TableProps<T, P>) => {
return (
<div className="rounded-md bg-white">
<Table>
<TableHeader>
<TableRow>
{columns.map((column, i) => (
<TableHead className="font-semibold text-black" key={i}>
{column.title}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{data.map((data, i) => (
<Row
data={data}
columns={columns}
setRowData={setRowData}
cellProps={cellProps}
expandedComponent={expandedComponent}
key={i}
/>
))}
</TableBody>
</Table>
</div>
);
};
type RowProps<T, P> = {
columns: Columns<T, P>[];
data: T;
setRowData?: Dispatch<SetStateAction<T | null>>;
cellProps?: P | undefined;
expandedComponent?: (props: { rowData: T }) => ReactNode;
};
const Row = <T, P>({
columns,
data,
setRowData,
cellProps,
expandedComponent,
}: RowProps<T, P>) => {
const { toggleRowExpansion, isRowExpanded } = useRowExpansion<T>();
const cellFunctions: CellFunctions<T> = {
isRowExpanded,
toggleRowExpansion,
};
return (
<>
<TableRow
onClick={() => {
setRowData && setRowData(data);
}}
>
{columns.map((column, i) => (
<TableCell key={i}>
{column.cell(data, { cellProps, cellFunctions })}
</TableCell>
))}
</TableRow>
{isRowExpanded && (
<TableRow>
<TableCell colSpan={12} className="bg-secondary">
{expandedComponent && expandedComponent({ rowData: data })}
</TableCell>
</TableRow>
)}
</>
);
};
export default DataTable;
|
<!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">
<meta name="title" content="PhoneInfoGet">
<meta name="description" content="website that lets you track ip address, track location of IP address quickly">
<meta name="keywords" content="ip,locator,ip-locator-,ip,address finder,address,what is my ip ?,what's my ip,my ip">
<meta name="robots" content="index, nofollow">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="English">
<meta name="revisit-after" content="2 days">
<meta name="author" content="MenoCorp">
<title>PhoneInfoGet</title>
{% load static %}
<!--local stylesheet-->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!--Jquery CDN-->
<!--Bootstrap CDN-->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<!--font awesome CDN-->
<script src="https://kit.fontawesome.com/5de3ed83f2.js" crossorigin="anonymous"></script>
<!--Favicon-->
<link rel="shortcut icon" href="{% static 'image/favicon.png' %}">
<!--Navigation Bar-->
<nav class="navbar navbar-expand-lg">
<button class="navbar-toggler " type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon ">
<!--navbar toggle icon--> <i class="fa fa-navicon" style="color:#fff; font-size:28px;"></i>
</span>
</button>
<!--navbar brand name-->
<a class="navbar-brand text-white" href="#">PhoneInfoGet[IP]</a>
<div class="collapse navbar-collapse" id="navbarTogglerDemo03">
<form class="form-inline my-2 my-lg-0 ml-auto" method="GET">
<input class="form-control mr-sm-2" autocomplete="off" name="ip_address" id="ip_address" type="text" placeholder="Search IP" aria-label="Search" required>
<button class="btn btn-outline-warning mr-sm-2 my-2 my-sm-0" type="submit">Search</button>
</form>
<button class="btn btn-dark my-2 my-sm-0" type="submit">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-terminal" viewBox="0 0 16 16">
<path d="M6 9a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3A.5.5 0 0 1 6 9zM3.854 4.146a.5.5 0 1 0-.708.708L4.793 6.5 3.146 8.146a.5.5 0 1 0 .708.708l2-2a.5.5 0 0 0 0-.708l-2-2z"/>
<path d="M2 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2zm12 1a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h12z"/>
</svg>
shell
</button>
</div>
</nav>
</head>
<body>
<div class="container-fluid">
<div class="container">
<br>
<h3 class="text-center detection">IP Address Detected : <b>{{ data.ip }}</b></h3>
<br>
</div>
</div>
<div class="container-fluid">
<center>
<!--table to show IP's data-->
<table class="table table-hover table-responsive-md text-center">
<thead>
<tr>
<th class="text-light">Attributes</th>
<th class="text-light">Data</th>
</tr>
</thead>
<tbody>
<tr>
<td>Address</td>
<td>{{data.address}}</td>
</tr>
<tr>
<td>City</td>
<td><i class="fa fa-info-circle"></i><a href="{{page_link}}" target="_blank" rel="noopener">{{data.city}}</a> </td>
</tr>
<tr>
<td>Postal</td>
<td>{{data.postal}}</td>
</tr>
<tr>
<td>Region</td>
<td>{{data.raw.region}}</td>
</tr>
<tr>
<td>State</td>
<td>{{data.state}}</td>
</tr>
<tr>
<td>Country</td>
<td>{{data.country}}</td>
</tr>
<tr>
<td>Organisation</td>
<td>{{data.org}}</td>
</tr>
<tr>
<td>Latitude</td>
<td>{{data.lat}}</td>
</tr>
<tr>
<td>Longitude</td>
<td>{{data.lng}}</td>
</tr>
<tr>
<td>Timezone</td>
<td>{{data.raw.timezone}}</td>
</tr>
</tbody>
</table>
</center>
</div>
<!--Google Map Embed iframe-->
<div class="embed-responsive embed-responsive-21by9">
<iframe class="embed-responsive-item" src="{{ map_url }}" title="Google Map Location"allowfullscreen></iframe>
</div>
<!--Local js-->
<script src="{% static 'js/index.js' %}"></script>
</body>
<!-- Footer -->
<footer class="page-footer font-small pt-3">
<!-- Footer Elements -->
<div class="container">
<!-- Grid row-->
<div class="row" id="social-media-container" >
<!-- Grid column -->
{% comment %} <div class="col-md-12 text-center">
<div class="mt-3 flex-center">
<!-- Facebook -->
<a class="fb-ic" href="https://facebook.com/shaikhsajid1111" target="_blank" rel="noopener">
<i class="fab fa-facebook-f fa-2x white-text mr-3 fa-lg"> </i>
</a>
<!-- Twitter -->
<a class="tw-ic" href="https://twitter.com/shaikhsajid1111" target="_blank" rel="noopener">
<i class="fab fa-twitter white-text mr-3 fa-lg fa-2x"> </i>
</a>
<!-- Github +-->
<a class="git-ic" href="https://github.com/shaikhsajid1111" target="_blank" rel="noopener">
<i class="fab fa-github white-text mr-3 fa-lg fa-2x"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/shaikhsajid1111" target="_blank" rel="noopener">
<i class="fab fa-instagram white-text mr-3 fa-lg fa-2x"> </i>
</a>
</div>
</div> {% endcomment %}
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
<!-- Footer Elements -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3 text-white"> © 2023 Copyright:
<a href="mailto:[email protected]" class="text-warning" target="_blank" rel="noopener"> MenoCorp</a>
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
</html>
|
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const { body, validationResult } = require('express-validator');
// Load environment variables from .env file
dotenv.config();
// Import User model
const User = require('../models/User');
// Register route
exports.register = [
// Input validation and sanitization using express-validator
body('name', 'Name is required').not().isEmpty(),
body('email', 'Email is required').isEmail(),
body('password', 'Password is required').not().isEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
// Check if the user already exists
const existingUser = await User.findOne({ email: req.body.email });
if (existingUser) {
return res.status(400).json({ message: 'User already exists' });
}
// Create a new user
const newUser = new User({
name: req.body.name,
email: req.body.email,
});
// Hash the password using bcrypt
newUser.setPassword(req.body.password);
// Save the user to the database
await newUser.save();
// Generate a JWT token
const token = jwt.sign(
{ userId: newUser._id },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
// Send the token as a response
res.status(201).json({ token });
} catch (error) {
console.error(error);
res.status(500).send({ message: 'Internal Server Error' });
}
},
];
// Login route
exports.login = [
// Input validation and sanitization using express-validator
body('email', 'Email is required').isEmail(),
body('password', 'Password is required').not().isEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
// Find the user by email
const user = await User.findOne({ email: req.body.email });
if (!user) {
return res.status(400).json({ message: 'Invalid email or password' });
}
// Check if the password is correct
const isPasswordValid = user.checkPassword(req.body.password);
if (!isPasswordValid) {
return res.status(400).json({ message: 'Invalid email or password' });
}
// Generate a JWT token
const token = jwt.sign(
{ userId: user._id },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
// Send the token as a response
res.status(200).json({ token });
} catch (error) {
console.error(error);
res.status(500).send({ message: 'Internal Server Error' });
}
},
];
|
import { Component, Input, OnInit } from '@angular/core';
import { UnsubscribeComponent } from '../../../shared/classes/unsubscribe.base';
import { GridInputsWithRequest } from '../../../models/interfaces/grid-inputs';
import {
Column,
eCrud,
eEntities,
eFieldControlType,
eGridRefreshType,
eGridRowActions,
eLayoutWidgetSize,
GridRowActions,
GridService,
JbButtonType,
SearchField,
ShowSettings,
WebApiRequest
} from 'jibe-components';
import { GridAction } from 'jibe-components/lib/grid/models/grid-action.model';
import { SpecificationRequisition } from '../../../models/interfaces/specification-requisition';
import { SpecificationDetailsService } from '../../../services/specification-details/specification-details.service';
import {
SpecificationRequisitionsDisplayTexts,
SpecificationRequisitionsFieldNames
} from '../../../models/enums/specification-requisitions.enum';
import { eSpecificationAccessActions } from '../../../models/enums/access-actions.enum';
import { eApiBaseDryDockAPI } from '../../../models/constants/constants';
@Component({
selector: 'jb-specification-requisitions',
templateUrl: './specification-requisitions.component.html',
styleUrls: ['./specification-requisitions.component.scss']
})
export class SpecificationRequisitionsComponent extends UnsubscribeComponent implements OnInit {
@Input() specificationUid: string;
gridData: GridInputsWithRequest;
readonly eLayoutWidgetSize = eLayoutWidgetSize;
readonly JbButtonType = JbButtonType;
private columns: Column[] = [
{
DisplayText: SpecificationRequisitionsDisplayTexts.Number,
FieldName: SpecificationRequisitionsFieldNames.Number,
IsActive: true,
IsMandatory: true,
IsVisible: true,
ReadOnly: true
},
{
DisplayText: SpecificationRequisitionsDisplayTexts.Subject,
FieldName: SpecificationRequisitionsFieldNames.Subject,
IsActive: true,
IsMandatory: true,
IsVisible: true,
ReadOnly: true
},
{
DisplayText: SpecificationRequisitionsDisplayTexts.Priority,
FieldName: SpecificationRequisitionsFieldNames.Priority,
IsActive: true,
IsMandatory: true,
IsVisible: true,
ReadOnly: true
},
{
DisplayText: SpecificationRequisitionsDisplayTexts.Supplier,
FieldName: SpecificationRequisitionsFieldNames.Supplier,
IsActive: true,
IsMandatory: true,
IsVisible: true,
ReadOnly: true
},
{
DisplayText: SpecificationRequisitionsDisplayTexts.PoDate,
FieldName: SpecificationRequisitionsFieldNames.PoDate,
IsActive: true,
IsMandatory: true,
IsVisible: true,
ReadOnly: true,
FieldType: eFieldControlType.Date,
ControlType: eFieldControlType.Date
},
{
DisplayText: SpecificationRequisitionsDisplayTexts.DeliveryDate,
FieldName: SpecificationRequisitionsFieldNames.DeliveryDate,
IsActive: true,
IsMandatory: true,
IsVisible: true,
ReadOnly: true,
FieldType: eFieldControlType.Date,
ControlType: eFieldControlType.Date
},
{
DisplayText: SpecificationRequisitionsDisplayTexts.Port,
FieldName: SpecificationRequisitionsFieldNames.Port,
IsActive: true,
IsMandatory: true,
IsVisible: true,
ReadOnly: true
},
{
DisplayText: SpecificationRequisitionsDisplayTexts.Amount,
FieldName: SpecificationRequisitionsFieldNames.Amount,
IsActive: true,
IsMandatory: true,
IsVisible: true,
ReadOnly: true,
FieldType: eFieldControlType.Number,
Precision: '1.2-2'
},
{
DisplayText: SpecificationRequisitionsDisplayTexts.Status,
FieldName: SpecificationRequisitionsFieldNames.Status,
IsActive: true,
IsMandatory: true,
IsVisible: true,
ReadOnly: true
}
];
private searchFields: SearchField[] = [
{
field: SpecificationRequisitionsFieldNames.Number,
pattern: 'contains'
},
{
field: SpecificationRequisitionsFieldNames.Subject,
pattern: 'contains'
}
];
private showSettings: ShowSettings = {
showButton: true,
showAdditionalFilters: false,
showThreeDotsMenu: false,
showSearchBox: true,
showFilterChips: false
};
constructor(
private specificationDetailsService: SpecificationDetailsService,
private gridService: GridService
) {
super();
}
async ngOnInit(): Promise<void> {
this.setGridData();
}
setGridData() {
this.gridData = {
gridName: `specification-requisitions-${this.specificationUid}`,
columns: this.columns,
request: this.getApiRequest(),
searchFields: this.searchFields,
advancedSettings: [],
showSettings: this.showSettings,
actions: []
};
this.gridData.actions = this.getGridRowActions();
}
onGridAction(event: GridAction<eGridRowActions, SpecificationRequisition>) {
// eslint-disable-next-line default-case
switch (event.type) {
case eGridRowActions.Delete:
this.deleteSpecificationRequisition(event.payload);
break;
default:
break;
}
}
private getGridRowActions() {
const actions: GridRowActions[] = [];
if (this.specificationDetailsService.hasAccess(eSpecificationAccessActions.editRequisition)) {
actions.push({
name: eGridRowActions.Delete,
gridName: this.gridData.gridName
});
}
return actions;
}
private getApiRequest(): WebApiRequest {
return {
entity: eEntities.DryDock,
apiBase: eApiBaseDryDockAPI,
action: 'specification-details/get-specification-requisitions',
crud: eCrud.Post,
body: { uid: this.specificationUid }
};
}
private deleteSpecificationRequisition(specificationRequisition: SpecificationRequisition) {
this.specificationDetailsService.deleteSpecificationRequisition(this.specificationUid, specificationRequisition.uid).subscribe(() => {
this.gridService.refreshGrid(eGridRefreshType.Table, this.gridData.gridName);
});
}
}
|
import 'package:flutter/material.dart';
import 'package:skeletonizer/skeletonizer.dart';
class TaskListSkeleton extends StatelessWidget {
const TaskListSkeleton({super.key});
@override
Widget build(BuildContext context) {
return Skeletonizer(
enabled: true,
child: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 6.0),
child: Card(
color: Colors.white,
surfaceTintColor: Colors.white,
shadowColor: Colors.white70,
child: ListTile(
onTap: () {},
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Item number $index as title',
style: const TextStyle(fontSize: 20.0),
),
const Text(
'abcsddsfdsfsddffds',
style: TextStyle(fontSize: 12.0),
),
]),
subtitle: const Row(children: [
Text(
'26 April, 2024',
style: TextStyle(fontSize: 12.0),
),
SizedBox(
width: 10.0,
),
Icon(Icons.abc, size: 10.0),
SizedBox(
width: 4.0,
),
Text('High'),
]),
),
),
);
},
),
);
}
}
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:background="@drawable/dots"
tools:context=".MainActivity$PlaceholderFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:textSize="24dp"
android:gravity="center_horizontal"
android:background="#32000000"
android:text="Registration"/>
<ScrollView android:id="@+id/registeration_form" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent" android:orientation="vertical"
android:layout_height="match_parent">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="12dp"
android:layout_marginTop="32dp"
android:textColor="@color/white"
android:paddingBottom="12dp"
android:drawableLeft="@drawable/name_icon"
android:background="#338096cc"
android:elevation="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:hint="Name"
android:textColorHint="@color/white"
android:paddingLeft="8dp"
android:layout_below="@+id/name_text"
android:textSize="16sp"
android:inputType="textPersonName" />
<EditText
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#338096cc"
android:paddingTop="12dp"
android:layout_marginTop="8dp"
android:drawableLeft="@drawable/phone_icon"
android:paddingBottom="12dp"
android:elevation="16dp"
android:hint=" Phone Number"
android:textColor="@color/white"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:textColorHint="@color/white"
android:paddingLeft="8dp"
android:layout_below="@+id/name_text"
android:textSize="16sp"
android:inputType="phone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:paddingBottom="8dp"
android:background="#338096cc"
android:orientation="vertical">
<TextView
android:id="@+id/register_type"
android:text="Register As An "
android:paddingTop="8dp"
android:textStyle="bold"
android:paddingLeft="8dp"
android:textColor="@color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"/>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:layout_gravity="center_horizontal"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_employee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:textStyle="bold"
android:textSize="16sp"
android:buttonTint="@color/wallet_highlighted_text_holo_dark"
android:checked="true"
android:text="Employee"/>
<RadioButton android:id="@+id/radio_employer"
android:layout_width="wrap_content"
android:textStyle="bold"
android:buttonTint="@color/wallet_highlighted_text_holo_dark"
android:textColor="@color/white"
android:textSize="16sp"
android:layout_height="wrap_content"
android:text="Employer"/>
</RadioGroup>
</LinearLayout>
<Button
android:id="@+id/buttonLoadPicture"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginTop="30dp"
android:layout_below="@+id/photo"
android:background="@drawable/camera"
android:layout_gravity="center"/>
<ImageView
android:layout_width="100dp"
android:layout_gravity="center_horizontal"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:id="@+id/tempiv"/>
<TextView
android:id="@+id/photo"
android:text="Pick Profile Picture" android:layout_width="wrap_content"
android:textColor="@color/white"
android:textSize="16sp"
android:layout_gravity="center_horizontal"
android:textStyle="bold"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<Button
android:id="@+id/register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_below="@+id/photo"
android:background="@drawable/oval_background"
android:text="Register"
android:textColor="@color/white"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
|
import { useQuery } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { useState } from "react";
import { getGenres } from "../../api/api-services";
import { Comic } from "../../models/Comic";
import QueryResults from "./components/QueryResults";
import SearchForm from "./components/SearchForm";
export default function SearchPage() {
const [searchResult, setSearchResult] = useState<Comic[]>();
const [selectedGenres, setSelectedGenres] = useState<string[]>([]);
const [selectedSort, setSelectedSort] = useState<string>("");
const [selectedStatus, setSelectedStatus] = useState<number>(0);
const { data: genresData, isLoading: loadingGenres } = useQuery({
queryKey: [`getGenres`],
queryFn: () => getGenres(),
});
if (loadingGenres) {
return <div className="m-4">Loading...</div>;
}
if (!genresData)
return (
<div className="flex flex-col items-center justify-center">
<div className="m-4">Genres not found. Return Home</div>
<Link to="/" className="text-blue-600 underline">
Home
</Link>
</div>
);
return (
<div className="flex h-full flex-col items-center text-slate-50">
{genresData && (
<SearchForm
setSearchResult={setSearchResult}
selectedGenres={selectedGenres}
setSelectedGenres={setSelectedGenres}
selectedSort={selectedSort}
setSelectedSort={setSelectedSort}
selectedStatus={selectedStatus}
setSelectedStatus={setSelectedStatus}
genresData={genresData}
/>
)}
{searchResult && <QueryResults searchResult={searchResult} />}
</div>
);
}
|
/**
* Iterator for the dynamic array
* @file DynamicArrayIterator.h
* @author Kyle Givler
*/
#ifndef _DYNAMIC_ARRAY_ITERATOR_H_
#define _DYNAMIC_ARRAY_ITERATOR_H_
#include <iterator>
template <class T>
class DynamicArray;
template <class T>
class DynamicArrayIterator : public std::iterator<std::input_iterator_tag, int>
{
private:
const DynamicArray<T> *containerPtr;
size_t index;
public:
DynamicArrayIterator(DynamicArray<T> *array, int index) : containerPtr(array), index(index) {}
DynamicArrayIterator(const DynamicArrayIterator<T> &dit) : containerPtr(dit.containerPtr), index(dit.index) {}
DynamicArrayIterator<T>& operator++()
{
index++;
return *this;
}
DynamicArrayIterator<T> operator++(int)
{
DynamicArrayIterator tmp(*this);
operator++();
return tmp;
}
bool operator==(const DynamicArrayIterator<T> &rhs)
{
return ( (containerPtr == rhs.containerPtr) && (index == rhs.index) );
}
bool operator!=(const DynamicArrayIterator<T> &rhs) {return (!operator==(rhs)) ;}
const T operator*()
{
T item;
containerPtr->getByPosition(index, item);
return ( item );
}
};
#endif
|
import React from 'react';
import { useSelector } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import Breadcrumb from '../../components/Breadcrumb';
import Cart from '../../components/Cart/Cart';
import CartSummary from '../../components/Cart/CartSummary';
const CartPage = () => {
const cartItems = useSelector((state) => state.cart.cartItems);
const navigate = useNavigate();
const handleCheckoutClick = () => {
navigate('/checkout');
};
const breadcrumbItems = [
{ label: 'Products', url: '/products' },
{ label: 'Cart' },
];
if (!cartItems || cartItems.length === 0) {
return (
<div className="min-h-screen flex flex-col justify-center items-center space-y-4 bg-gray-100">
<p className="text-2xl font-bold text-gray-700">
THERE ARE NO ITEMS IN YOUR CART.
</p>
<Link
to={'/products'}
className="btn btn-active btn-neutral"
>
Shop Now
</Link>
</div>
);
}
return (
<>
<Breadcrumb items={breadcrumbItems} />
<div className="min-h-screen grid grid-cols-1 gap-4 lg:grid-cols-3 lg:gap-8 m-8">
<div className="h-full rounded-lg lg:col-span-2">
<Cart cartItems={cartItems} />
</div>
<div className="h-full rounded-lg ">
<CartSummary />
<button
onClick={handleCheckoutClick}
className="bg-black font-bold text-white px-4 py-2 mb-2 w-full hover:bg-gray-900"
>
PROCEED TO CHECKOUT
</button>
<p className="text-center text-gray-600">
<a className="underline hover:text-gray-800" href="/products">
Continue Shopping
</a>
</p>
</div>
</div>
</>
);
};
export default CartPage;
|
import { get } from 'lodash'
import React, { Component } from 'react'
import { PropTypes } from 'prop-types'
import classNames from 'classnames'
import { Icon, Tag } from '@kube-design/components'
import { Indicator } from 'components/Base'
import StatusReason from 'clusters/components/StatusReason'
import { CLUSTER_PROVIDER_ICON, CLUSTER_GROUP_TAG_TYPE } from 'utils/constants'
import styles from './index.scss'
export default class ClusterTitle extends Component {
static propTypes = {
theme: PropTypes.oneOf(['dark', 'light']),
size: PropTypes.oneOf(['normal', 'small', 'large']),
}
static defaultProps = {
theme: 'dark',
size: 'normal',
}
iconSizeMap = {
large: 48,
normal: 40,
small: 20,
}
render() {
const {
theme,
size,
className,
cluster,
tagClass,
noStatus,
onClick,
} = this.props
if (!cluster) {
return null
}
const isReady = get(cluster.conditions, 'Ready.status') === 'True'
const sizeVal = this.iconSizeMap[size]
return (
<div
className={classNames(
styles.wrapper,
styles[theme],
styles[size],
className
)}
>
<div className={styles.icon} style={{ height: sizeVal }}>
<Icon
name={CLUSTER_PROVIDER_ICON[cluster.provider] || 'kubernetes'}
size={sizeVal}
type={theme}
/>
{!noStatus && isReady && (
<Indicator className={styles.indicator} status="ready" />
)}
</div>
<div className={styles.title}>
<div className={styles.name}>
{onClick ? (
<a title={cluster.name} onClick={onClick}>
{cluster.name}
</a>
) : (
<span title={cluster.name}>{cluster.name}</span>
)}
{cluster.group && (
<Tag
className={classNames('margin-l12', tagClass)}
type={CLUSTER_GROUP_TAG_TYPE[cluster.group]}
>
{t(`ENV_${cluster.group.toUpperCase()}`, {
defaultValue: cluster.group,
})}
</Tag>
)}
{cluster.isHost && (
<Tag
className={classNames('margin-l12', tagClass)}
type="warning"
>
{t('Host Cluster')}
</Tag>
)}
{size === 'small' && !noStatus && !isReady && (
<StatusReason data={cluster} />
)}
</div>
<div className={styles.description}>
{isReady || noStatus ? (
<p className="ellipsis">{cluster.description || '-'}</p>
) : (
<StatusReason data={cluster} />
)}
</div>
</div>
</div>
)
}
}
|
#pragma once
#ifndef __MODEL_H__
#define __MODEL_H__
#include <iostream>
#include <rbdl/rbdl.h>
#include <rbdl/Body.h>
#include <rbdl/addons/urdfreader/urdfreader.h>
#include <Eigen/Dense>
#include <Eigen/Geometry>
using namespace std;
using namespace Eigen;
class Model
{
public:
RigidBodyDynamics::Model _model;
Eigen::VectorXd _q, _qdot; // joint angle and joint angular velocity of the model
Eigen::Vector3d _pos, _posdot, _ori, _oridot; // position and orientation of the model
Eigen::VectorXd _bg, _b, _g; // b = Coriolis and centrifugal force, g = gravitational force, bg = b + g
Eigen::MatrixXd _A, _J, _J_des; // inertial matrix and jacobian matrix of the model
Eigen::Matrix3d _R; // rotation matrix of end-effector of the model
Model();
virtual ~Model();
void getModel();
void updateKinematics(VectorXd &q, VectorXd &qdot);
void updateDynamics();
void getJacobian();
void getState();
double getDOFs();
Eigen::Vector3d getDesiredPositionFromJointAngle(VectorXd q);
Eigen::Vector3d getDesiredOrientationFromJointAngle(VectorXd q);
Eigen::MatrixXd getDesiredJacobianFromJointAngle(VectorXd q);
private:
void configurateBody();
void initialize();
Eigen::VectorXd _body_point_local_ee; // translation of the end-effector calculated from the final joint coordinate
Eigen::VectorXd _zero; // 3x1 zero column vector
int _dofs;
int _ee_id;
bool _bool_update_kinemtaics, _bool_update_dynamics, _bool_get_state, _bool_get_jacobian;
};
#endif
|
#读书《赤裸裸的统计学》,作者查尔斯。韦兰。
统计学就像是一种高智商武器:正确地使用它能够帮助我们,但错误地使用它也会产生灾难性的后果。本书不会将你变成一个统计学专家,但会让你充分了解这个领域的基本概念,并对这个领域保持谨慎和尊重,不至于酿成大祸。
本书从数据、概率、中心极限定理、推断与检验、回归分析和项目评估几个方面循序渐进介绍了如何在日常生活和科学研究中正确应用统计概念。
瑞典数学家、作家安德烈斯的一句话:用数据说谎容易,但是用数据说出真相却很难。数据只不过是知识的原材料,而统计学则是我们分析信息获得有意义结果的最有力工具。如果你想要理解日常生活中出现的数字背后的含义,并见识到“数据”的巨大力量,统计学就是你的不二法宝。但是尽管优质的数据就是好的线索,但首先我们必须收集到优质数据,而这要比看上去困难得多。
中心极限定理的核心要义就是,一个大型样本的正确抽样与其所代表的群体存在相似关系。当然,每个样本之间肯定会存在差异,但是任一样本与整体之间存在巨大差异的概率是较低的。
统计学的一个核心功能就是使用手中已有的数据进行合理推测,换句话说,我们能够使用“已知世界”的数据来对“未知世界”进行推断。统计推断是一个让数据说话、让有价值的结论浮出水面的过程。统计推断正是我们之前已经讨论过的两个概念的合体:数据和概率(期间需要来自中心极限定理的一点儿帮助)。统计推断过程中最常使用的工具之一就是“假设检验”。
回归分析能够在控制其他因素的前提下,对某个具体变量与某个特定结果之间的关系进行量化。也就是说,我们能够在保持其他变量效果不变的情况下,将某个变量的效果分离出来。回归分析最核心的一点是,寻找的是两个变量之间的最佳拟合线性关系;而且只有当变量之间的关系为线性时,回归分析才可派上用场。
项目评估阶段,探索与测量某些介人手段的因果作用。在难以弄清原因和结果的时候,项目评估提供了一系列用于隔离治疗效果的工具。对于任何一个项目评估来说,其目的都是为评价介人手段的效果提供某种“反现实”。在随机控制实验中,对照组就是“反现实”,但当对照实验不具有可行性或有违道德时,我们就需要寻求其他方式来模拟“反现实”。对这个世界的探索在很多时候就依赖于寻找“反现实”的聪明才智。
对于整本书一直在贯彻的统计推断过程,就是先提出一个零假设,然后依据一些观察数据来检验其真伪。如果得到零假设结果的概率非常低,那么我们就可以推翻零假设。当样本量比较少的情况下,就需要采用t分布。t分布的引人只不过稍微丰富了这个工具,我们的思路并没有改变,t分布唯一的变化就在于这些结果的发生概率与正态分布曲线有所不同。概率曲线的“尾巴”越“肥大”,数据离散的程度越高,巧合的情况就越容易出现,推翻零假设的信心越显不足。
群里统计大神推荐了一系列统计学习书,包括《统计会犯错》、《真理相遇统计》、《统计学:从数据到结论》、《统计与真理:怎样运用偶然性》,以及本书,本书写作中有部分是在向《统计会犯错》的作者Alex Reinhart致敬。对于读者入门建议先读本书,建立统计学基本思路,然后再循序渐进,接触其他四本更深入介绍统计学的专著。
|
import React from 'react';
import * as Yup from 'yup';
import { Formik, Form } from 'formik';
import { Link } from 'react-router-dom';
import { Button, Box, Typography } from '@mui/material';
import Header from '../header/Header';
import { InputField, PasswordInputField } from '../common/CommonInput';
import { Validate } from '../../shared/validators';
import SubFooter from '../footer/SubFooter';
import { LOGIN } from '../../shared/common';
import { GoogleLoginPage } from './GoogleLogin';
export default function Login() {
const validateLogin = Yup.object().shape({
email: Validate.email,
password: Validate.password,
});
const initialValues = {
email: '',
password: '',
};
const HandleLogin = (values) => {
console.log({ values });
};
return (
<Box>
<Header />
<Box className='login-signup-forgot'>
<Formik
initialValues={initialValues}
validationSchema={validateLogin}
onSubmit={HandleLogin}
>
<Form>
<Typography variant='h4' align='center'>
{LOGIN.heading}
</Typography>
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
<InputField label='Email' name='email' type='email' />
<PasswordInputField
label='Password'
name='password'
type='password'
/>
<Link to='/reset-password'>
<Typography className='text-center margin-top'>
{LOGIN.forgot_password}
</Typography>
</Link>
<Box className='MuiAutocomplete-endAdornment' sx={{marginBottom:'1rem'}}>
<GoogleLoginPage />
</Box>
<Button className='yellow-button' type='submit'>
{LOGIN.submit}
</Button>
<Link to='/signup'>
<Typography className='text-center margin-top'>
{LOGIN.create}
</Typography>
</Link>
</Box>
</Form>
</Formik>
</Box>
<SubFooter />
</Box>
);
}
|
import 'package:flutter/material.dart';
import 'package:my_app_movies_bloc/src/blocs/movies_bloc.dart';
import 'package:my_app_movies_bloc/src/models/item_model.dart';
class MoviesList extends StatelessWidget {
MoviesList({super.key, required this.snapshot});
final AsyncSnapshot<ItemModel> snapshot;
final bloc = MoviesBloc();
@override
Widget build(BuildContext context) {
return GridView.builder(
padding: const EdgeInsets.only(
left: 10,
right: 10,
),
itemCount: snapshot.data!.results.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
child: Card(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(
'https://image.tmdb.org/t/p/w185${snapshot.data!.results[index].poster_path}',
//fit: BoxFit.fill,
),
),
),
),
),
onTap: () {
Navigator.pushNamed(
context,
"/details-movies",
arguments: snapshot.data!.results[index],
);
},
);
});
}
}
|
import React from "react";
import Box from "@mui/material/Box";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemText from "@mui/material/ListItemText";
import Typography from "@mui/material/Typography";
import Title from "../general/Title";
const AdmissionProcedures = () => {
return (
<Box
className=" py-10 bg-[#f7f7f7]"
data-aos="fade-down"
data-aos-duration="1200"
data-aos-easing="ease-in-sine">
<Box className="container">
<Title title="Admission Procedures" subtitle="HUST" />
<Box>
<List>
<ListItem>
<ListItemText
primary="1. Open your browser and log on to hust.edu.ng/admission"
secondary="Instructions: Follow the provided URL to access the admission page, or click the apply now button below"
/>
</ListItem>
<ListItem>
<ListItemText
primary="2. Create your account with your email and password"
secondary="Instructions: Use your email and create a secure password for your account."
/>
</ListItem>
<ListItem>
<ListItemText
primary="3. Email Verification"
secondary="Check the email address you supplied and click on the verification URL sent to you, to activate your account. If you did not see the mail in your inbox; kindly check your spam mail. (Please keep your username and password secured)"
/>
</ListItem>
<ListItem>
<ListItemText
primary="4. Log into the HUST admission application portal"
secondary="Instructions: Use your registered email and password to log in."
/>
</ListItem>
<ListItem>
<ListItemText
primary="5. Purchase the admission form online"
secondary="After which a registration Number will be generated and sent to your registered email on successful payment."
/>
</ListItem>
<ListItem>
<ListItemText
primary="6. Complete the application form"
secondary="The HUST online application form is user-friendly and you can complete the form in any order. You can even save the form and come back to complete it later."
/>
</ListItem>
<ListItem>
<ListItemText
primary="7. Make Corrections to Your Data"
secondary="The online application form is designed to ensure that if you omitted any required field in the process of completing the form, the list of fields omitted are displayed before you are allowed to submit."
/>
</ListItem>
<ListItem>
<ListItemText
primary="8. Submit Application Form"
secondary="Check your form carefully for errors. When you are satisfied with it and are ready to submit, click on the preview button to double-check, then click on the Submit button."
/>
</ListItem>
<ListItem>
<ListItemText
primary="After the form has been submitted, you can print a copy of your form."
secondary="You can always log in to the application portal to view APPLICATION STATUS and APPLICATION INFO."
/>
</ListItem>
</List>
<Typography variant="h6" mt={3} mb={2}>
Contact Us
</Typography>
<Typography variant="body1">
For further assistance, please contact us at:
</Typography>
<Typography variant="body1">Phone: +234-(0)-911-942-9029</Typography>
<Typography variant="body1">Email: [email protected]</Typography>
</Box>
</Box>
</Box>
);
};
export default AdmissionProcedures;
|
#include <iostream>
#include <fstream>
#include <unordered_set>
using namespace std;
//struct to hold x and y coordinates
struct coord
{
int x;
int y;
//constructor
coord(int x, int y) : x(x), y(y) {}
//overload == operator
bool operator==(const coord& rhs) const
{
return x == rhs.x && y == rhs.y;
}
};
//hash function for the struct
namespace std
{
template<>
struct hash<coord>
{
std::size_t operator()(const coord& k) const
{
//hash combine
return std::hash<int>()(k.x) ^ (std::hash<int>()(k.y) << 1);
}
};
}
//function to update the position
coord updatePosition(coord curentPosition, char n)
{
if (n == '<')
{
curentPosition.x--;
}
else if (n == '>')
{
curentPosition.x++;
}
else if (n == '^')
{
curentPosition.y++;
}
else if (n == 'v')
{
curentPosition.y--;
}
return curentPosition;
}
int main() {
unordered_set <coord> houseVisits;
char n;
fstream fileIn("input.txt", fstream::in);
// start from 0 0 for both of them
auto santaPosition = coord(0, 0);
auto robotPosition = coord(0, 0);
houseVisits.insert(coord(0, 0));
int i = 0;
while (fileIn >> n)
{
// if even Santa moves
if (i % 2 == 0)
{
santaPosition = updatePosition(santaPosition, n);
houseVisits.insert(santaPosition);
}
else // if odd RoboSanta moves
{
robotPosition = updatePosition(robotPosition, n);
houseVisits.insert(robotPosition);
}
i++;
}
cout << houseVisits.size() << endl;
}
|
import pytest
from . import catalog
from . import utils
ELASTIC_INDEX = 'menu_items'
def make_places():
one = catalog.Place(
id=1,
slug='slug_1',
name='Рест без айтемов',
business=catalog.Business.Shop,
)
two = catalog.Place(
id=7,
slug='slug_7',
name='Ресторан с айтемами из эластика',
business=catalog.Business.Restaurant,
)
return [one, two]
@pytest.mark.config(
EATS_FULL_TEXT_SEARCH_ELASTIC_SEARCH_SETTINGS={
'enable': True,
'index': ELASTIC_INDEX,
'size': 1000,
},
)
@pytest.mark.config(
EATS_FULL_TEXT_SEARCH_RANKING_SETTINGS={'enable_umlaas_eats': False},
)
async def test_elastic_search_unavailable(
taxi_eats_full_text_search, mockserver, eats_catalog, load_json,
):
"""
Проверяем что поиск по каталогу работает
Если Elastic Search 500-тит
"""
request_params = {
'text': 'My Search Text',
'location': {'latitude': 55.752338, 'longitude': 37.541323},
'region_id': 1,
'shipping_type': 'all',
'delivery_time': {'time': '2021-03-12T21:00:00+00:00', 'zone': 3},
}
eats_catalog.add_block(
catalog.Block(id='open', type='open', list=list(make_places())),
)
@mockserver.json_handler('/saas-search-proxy/')
def saas(request):
return load_json('saas_response.json')
@mockserver.json_handler(
'/eats-fts-elastic-search/{}/_search'.format(ELASTIC_INDEX),
)
def elastic_search(request):
return mockserver.make_response(status=500)
@mockserver.json_handler('/eats-nomenclature/v2/place/assortment/details')
def _nomenclature(request):
return {'categories': [], 'items': {}}
response = await taxi_eats_full_text_search.post(
'/eats/v1/full-text-search/v1/search',
json=request_params,
headers=utils.get_headers(),
)
assert eats_catalog.times_called > 0
assert saas.times_called > 0
assert elastic_search.times_called > 0
assert response.status == 200
assert response.json() == load_json('search_response.json')
|
package rpc
import (
"encoding/json"
"reflect"
)
func GenerateRPCSpec(svc interface{}) ([]byte, error) {
svcType := reflect.TypeOf(svc)
methods := make([]map[string]interface{}, 0)
for i := 0; i < svcType.NumMethod(); i++ {
method := svcType.Method(i)
if tag, ok := method.Type.Field(0).Tag.Lookup("rpc"); ok && tag == "method" {
methodName := method.Name
methodDetails := map[string]interface{}{
"name": methodName,
"parameters": []string{},
"returns": []string{},
}
for j := 0; j < method.Type.NumIn(); j++ {
paramType := method.Type.In(j)
methodDetails["parameters"] = append(methodDetails["parameters"].([]string), paramType.Name())
}
for k := 0; k < method.Type.NumOut(); k++ {
returnType := method.Type.Out(k)
methodDetails["returns"] = append(methodDetails["returns"].([]string), returnType.Name())
}
methods = append(methods, methodDetails)
}
}
return json.MarshalIndent(map[string]interface{}{"methods": methods}, "", " ")
}
|
package com.cahke.website.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.cahke.website.models.User;
import com.cahke.website.services.UserService;
import jakarta.servlet.http.HttpServletRequest;
@Controller
public class PesquisaController {
private final UserService userService;
public PesquisaController(UserService userService) {
this.userService = userService;
}
@GetMapping("/pesquisar")
public String pesquisar(
@RequestParam(name = "termos", required = false) List<String> termos,
@RequestParam(name = "remove_termos", required = false) String removeTermos,
Model model,
HttpServletRequest req) {
if (removeTermos != null) {
termos.remove(removeTermos);
}
List<User> users = new ArrayList<>();
List<String> termosUnicos = new ArrayList<>();
if (termos != null && !termos.isEmpty()) {
for (String termo : termos) {
if (!termosUnicos.contains(termo)) {
System.out.println(termosUnicos.toString());
System.out.println(termos.toString());
termosUnicos.add(termo);
List<User> usersPorNome = userService.findByNomeContainingIgnoreCase(termo);
users.addAll(usersPorNome);
}
}
} else {
users = userService.findAll();
}
model.addAttribute("termos", termosUnicos);
model.addAttribute("users", users);
return "dashboard";
}
@GetMapping("/limpar-filtros")
public String limparFiltros() {
return "redirect:/";
}
}
|
/* TITULO: Control de una hélice con motor DC y driver L9110H.
AUTOR:
MARIANO DEL CAMPO GARCÍA (@2016) --> INGENIERO TÉCNICO INDUSTRIAL ESPECIALIDAD ELECTRÓNICA
- FACEBOOK: https://www.facebook.com/mariano.delcampogarcia
- TWITTER: https://twitter.com/MarianoCampoGa
- CORREO: [email protected]
DESCRIPCIÓN DEL PROGRAMA
Con este programa se controlar una hélice con motor DC (Fan Motor) mediante el driver L9110H. A través del
monitor serie podremos seleccionar las diferentes opciones de velocidad y sentido de giro del motor DC,
además de poder realizar dos tipos difrentes de parada (con freno motor y sin él).
ESQUEMA DE CONEXION
+-----+
+----[PWR]-------------------| USB |--+
| +-----+ |
| GND/RST2 [ ][ ] |
| MOSI2/SCK2 [ ][ ] A5/SCL[ ] |
| 5V/MISO2 [ ][ ] A4/SDA[ ] |
| AREF[ ] |
| GND[ ] |
| [ ]N/C SCK/13[ ] |
| [ ]IOREF MISO/12[ ] |
| [ ]RST MOSI/11[ ]~|
| [ ]3V3 +---+ 10[ ]~|
| [ ]5v -| A |- 9[ ]~| INA del "Fan motor"
| [ ]GND -| R |- 8[ ] | INB del "Fan motor"
| [ ]GND -| D |- |
| [ ]Vin -| U |- 7[ ] |
| -| I |- 6[ ]~|
| [ ]A0 -| N |- 5[ ]~|
| [ ]A1 -| O |- 4[ ] |
| [ ]A2 +---+ INT1/3[ ]~|
| [ ]A3 INT0/2[ ] |
| [ ]A4/SDA RST SCK MISO TX>1[ ] |
| [ ]A5/SCL [ ] [ ] [ ] RX<0[ ] |
| [ ] [ ] [ ] |
| UNO_R3 GND MOSI 5V ____________/
\_______________________/
NOTAS:
- La alimentación y la masa del "Fan Motor" van directamente conectadas a +5V y GND respectivamente.
*/
// Declaración de constantes globales
#define MOTOR_PWM 9 // Pin digital 9 para el pin INA (Velocidad PWMM del motor)
#define MOTOR_GIRO 8 // Pin digital 8 para el pin INB (Sentido de giro del motor)
#define PWM_LENTO 100 // PWM para la velocidad lenta
#define PWM_RAPIDO 255 // PWM para la velocidad rápida
#define RETARDO_GIRO 1000 // Retardo para el cambio del sentido de giro del motor
boolean entrada_valida; // Variable para el control del MENU
byte c; // Variable que almacena el carácter recibido por el puerto serie
int anterior = 0; // Variable que almacena el número de la secuencia del MENU
void setup()
{
Serial.begin(9600);
pinMode(MOTOR_GIRO, OUTPUT); // Pin digital 8 como salida
pinMode(MOTOR_PWM, OUTPUT); // Pin digital 9 como salida
digitalWrite(MOTOR_GIRO, LOW); // MOTOR_DIR a nivel BAJO
digitalWrite(MOTOR_PWM, LOW); // MOTOR_PWM a nivel BAJO
}
void loop()
{
// Dibuja el MENU a través del monitor serie
Serial.println("--------------------------------");
Serial.println("---------- MENU ----------");
Serial.println("--------------------------------");
Serial.println("1 - AVANCE RAPIDO");
Serial.println("2 - HACIA ADELANTE");
Serial.println("3 - PARADA SUAVE");
Serial.println("4 - MARCHA ATRAS");
Serial.println("5 - RETROCESO RAPIDO");
Serial.println("6 - FRENO MOTOR");
Serial.println("X - CUALQUIER TECLA SACA MENU");
Serial.println("--------------------------------");
Serial.print(">> Selecciona una opcion... ");
do
{
// Espera el siguiente carácter enviado desde el monitor serie
while(!Serial.available())
; // Se mantiene en un bucle de espera
c = Serial.read(); // Almaceno el carácter recibido
Serial.write(c);
// Evalúo el carácter recibido
switch(c)
{
case '1': // AVANCE RAPIDO
Serial.println("\n--------------------------------");
Serial.println( "AVANCE RAPIDO!!!" );
Serial.println("--------------------------------");
Serial.print(">> Selecciona una opcion... ");
if(anterior!=2)
{
// Se detienen los motores brevemente antes del cambio del sentido de giro
digitalWrite(MOTOR_GIRO, LOW);
digitalWrite(MOTOR_PWM, LOW);
}
if(anterior == 3 || anterior == 4)
{
delay(RETARDO_GIRO); // Retardo para el cambio del sentido de giro
}
// Ajusta la velocidad y el sentido de giro del motor
digitalWrite(MOTOR_GIRO, HIGH); // Sentido de giro -> Hacia adelante
analogWrite(MOTOR_PWM, 255-PWM_RAPIDO); // Velocidad -> Rápida
entrada_valida = true;
anterior = 1;
break;
case '2': // HACIA ADELANTE
Serial.println("\n--------------------------------");
Serial.println( "HACIA ADELANTE!!!" );
Serial.println("--------------------------------");
Serial.print(">> Selecciona una opcion... ");
if(anterior!=1)
{
// Se detienen los motores brevemente antes del cambio del sentido de giro
digitalWrite(MOTOR_GIRO, LOW);
digitalWrite(MOTOR_PWM, LOW);
}
if(anterior == 3 || anterior == 4)
{
delay(RETARDO_GIRO); // Retardo para el cambio del sentido de giro
}
// Ajusta la velocidad y el sentido de giro del motor
digitalWrite(MOTOR_GIRO, HIGH); // Sentido de giro -> Hacia adelante
analogWrite(MOTOR_PWM, 255-PWM_LENTO); // Velocidad -> Lenta
entrada_valida = true;
anterior = 2;
break;
case '3': // PARADA SUAVE
Serial.println("\n--------------------------------");
Serial.println( "PARADA SUAVE!!!" );
Serial.println("--------------------------------");
Serial.print(">> Selecciona una opcion... ");
// Se detienen los motores
digitalWrite(MOTOR_GIRO, LOW);
digitalWrite(MOTOR_PWM, LOW);
entrada_valida = true;
break;
case '4': // MARCHA ATRAS
Serial.println("\n--------------------------------");
Serial.println( "MARCHA ATRAS!!!" );
Serial.println("--------------------------------");
Serial.print(">> Selecciona una opcion... ");
if(anterior!=4)
{
// Se detienen los motores brevemente antes del cambio del sentido de giro
digitalWrite(MOTOR_GIRO, LOW);
digitalWrite(MOTOR_PWM, LOW);
}
if(anterior == 1 || anterior == 2)
{
delay(RETARDO_GIRO); // Retardo para el cambio del sentido de giro
}
// Ajusta la velocidad y el sentido de giro del motor
digitalWrite(MOTOR_GIRO, LOW); // Sentido de giro -> Hacia atrás
analogWrite(MOTOR_PWM, PWM_LENTO ); // Velocidad -> Lenta
entrada_valida = true;
anterior = 3;
break;
case '5': // RETROCESO RAPIDO
Serial.println("\n--------------------------------");
Serial.println( "RETROCESO RAPIDO!!!" );
Serial.println("--------------------------------");
Serial.print(">> Selecciona una opcion... ");
if(anterior!=3)
{
// Se detienen los motores brevemente antes del cambio del sentido de giro
digitalWrite(MOTOR_GIRO, LOW);
digitalWrite(MOTOR_PWM, LOW);
}
if(anterior == 1 || anterior == 2)
{
delay(RETARDO_GIRO); // Retardo para el cambio del sentido de giro
}
// Ajusta la velocidad y el sentido de giro del motor
digitalWrite(MOTOR_GIRO, LOW); // Sentido de giro -> Hacia atrás
analogWrite(MOTOR_PWM, PWM_RAPIDO); // Velocidad -> Rápida
entrada_valida = true;
anterior = 4;
break;
case '6': // FRENO MOTOR (No utilizar con frecuencia)
Serial.println("\n--------------------------------");
Serial.println( "FRENO MOTOR!!!" );
Serial.println("--------------------------------");
Serial.print(">> Selecciona una opcion... ");
// Se invierte el sentido de giro del motor y se para
digitalWrite(MOTOR_GIRO, HIGH);
digitalWrite(MOTOR_PWM, HIGH);
entrada_valida = true;
break;
default:
Serial.println("\n");
// Si se introduce un carácter que no está en el MENU, se vuelve a mostrar el MENU
entrada_valida = false;
break;
}
} while(entrada_valida == true);
}
|
using HTTP
using JSON
using Plots
using Clustering
using YAML
using Statistics
config = YAML.load_file("../parameter.yaml")
CLUSTER_NUM = config["CLUSTER_NUM"]
NOW_MULTIPLE = config["NOW_MULTIPLE"]
multiple = NOW_MULTIPLE
# 計時
start = time()
response = HTTP.get("http://localhost:8000?size=" * string(multiple))
if response.status == 200
# 解析 JSON 格式的回應
points_str = String(response.body)
points = JSON.parse(points_str)
points = JSON.parse(points)
# 將 x 和 y 座標分別存成列表
x_values = Float64[parse(Float64, point["x"]) for point in points]
y_values = Float64[parse(Float64, point["y"]) for point in points]
dx = hcat(x_values, y_values)
println("size of dx", size(dx)) # size of dx(142, 2)
# 計算 k-means
result = kmeans(dx', CLUSTER_NUM)
# 繪製散佈圖
scatter(x_values, y_values, group=result.assignments, xlabel="X", ylabel="Y", title="K-means Clustering")
# 分別計算並印出每群的 mean stddev
labels = result.assignments
for i in 1:CLUSTER_NUM
cluster_points = dx[labels .== i, :]
cluster_mean = mean(cluster_points, dims=1)
cluster_stddev = std(cluster_points, dims=1)
print("group $i means: ", cluster_mean)
println(" stddev: ", cluster_stddev)
end
# 計時結束
global end_time = time() - start
println("time: ", end_time)
if !isfile("./data/time.yaml")
touch("./data/time.yaml")
end
# YAML.write_file("./data/time.yaml", "time_" * string(NOW_MULTIPLE) * ": " * string(end_time))
# 儲存圖片
savefig("./data/result_" * string(NOW_MULTIPLE) * ".png")
end
|
import datetime
import os
from sqlalchemy import create_engine, String, DateTime, TEXT
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
class ClientDatabase:
"""
Класс - оболочка для работы с базой данных клиента.
Использует SQLite базу данных, реализован с помощью
SQLAlchemy 2.0 ORM и используется декларативный подход.
"""
class Base(DeclarativeBase):
"""Базовый декларативный класс для дальнейшего наследования."""
pass
class KnownUsers(Base):
"""
Класс, реализующий создание таблицы всех пользователей в базе данных,
а также взаимодействие с ней.
"""
__tablename__ = 'known_users'
id: Mapped[int] = mapped_column(primary_key=True)
username: Mapped[str] = mapped_column(String(50))
def __init__(self, username):
super().__init__()
self.id = None
self.username = username
def __repr__(self):
return f'Username: {self.username}'
class MessageHistory(Base):
"""
Класс, реализующий создание таблицы статистики переданных сообщений,
а также взаимодействие с ней.
"""
__tablename__ = 'message_history'
id: Mapped[int] = mapped_column(primary_key=True)
from_user: Mapped[str] = mapped_column(String(50))
to_user: Mapped[str] = mapped_column(String(50))
message: Mapped[str] = mapped_column(TEXT)
date: Mapped[datetime.datetime] = mapped_column(
DateTime(timezone=True), default=datetime.datetime.now())
def __init__(self, from_user, to_user, message):
super().__init__()
self.id = None
self.from_user = from_user
self.to_user = to_user
self.message = message
def __repr__(self):
return f'Message: {self.message}\nFrom: {self.from_user}\nTo: {self.to_user}'
class Contacts(Base):
"""
Класс, реализующий создание таблицы контактов, а также взаимодействие с ней.
"""
__tablename__ = 'contacts'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50), unique=True)
def __init__(self, name):
super().__init__()
self.id = None
self.name = name
def __repr__(self):
return f'Contact name: {self.name}'
def __init__(self, name):
path = os.path.dirname(os.path.realpath(__file__))
filename = f'client_{name}.db3'
self.engine = create_engine(f'sqlite:///{os.path.join(path, filename)}',
echo=False, pool_recycle=7200,
connect_args={'check_same_thread': False})
self.Base.metadata.create_all(self.engine)
Session = sessionmaker(bind=self.engine)
self.session = Session()
self.session.query(self.Contacts).delete()
self.session.commit()
def add_contact(self, contact):
"""
Метод, добавляющий контакт в базу данных
:param contact:
:return:
"""
if not self.session.query(
self.Contacts).filter_by(name=contact).count():
contact_row = self.Contacts(contact)
self.session.add(contact_row)
self.session.commit()
def contacts_clear(self):
"""
Метод, очищающий таблицу со списком контактов.
:return:
"""
self.session.query(self.Contacts).delete()
def del_contact(self, contact):
"""
Метод, удаляющий указанный контакт.
:param contact:
:return:
"""
self.session.query(self.Contacts).filter_by(name=contact).delete()
def add_users(self, users_list):
"""
Метод, заполняющий таблицу известных пользователей.
:param users_list:
:return:
"""
self.session.query(self.KnownUsers).delete()
for user in users_list:
user_row = self.KnownUsers(user)
self.session.add(user_row)
self.session.commit()
def save_message(self, from_user, to_user, message):
"""
Метод, сохраняющий сообщение в базе данных.
:param from_user:
:param to_user:
:param message:
:return:
"""
message_row = self.MessageHistory(from_user, to_user, message)
self.session.add(message_row)
self.session.commit()
def get_contacts(self):
"""
Метод, возвращающий список всех контактов.
:return:
"""
return [contact[0]
for contact in self.session.query(self.Contacts.name).all()]
def get_users(self):
"""
Метод, возвращающий список всех известных пользователей.
:return:
"""
return [user[0]
for user in self.session.query(self.KnownUsers.username).all()]
def check_user(self, user):
"""
Метод, выполняющий проверку присутствия пользователя в базе данных.
:param user:
:return:
"""
if self.session.query(self.KnownUsers).filter_by(
username=user).count():
return True
else:
return False
def check_contact(self, contact):
"""
Метод, выполняющий проверку присутствия контакта в базе данных.
:param contact:
:return:
"""
if self.session.query(self.Contacts).filter_by(name=contact).count():
return True
else:
return False
def get_history(self, from_who=None, to_who=None):
"""
Метод, возвращающий историю сообщения определенного пользователя.
:param from_who:
:param to_who:
:return:
"""
query = self.session.query(self.MessageHistory)
if from_who:
query = query.filter_by(from_user=from_who)
if to_who:
query = query.filter_by(to_user=to_who)
return [(history_row.from_user, history_row.to_user, history_row.message, history_row.date)
for history_row in query.all()]
if __name__ == '__main__':
test_db = ClientDatabase('test1')
for i in ['test3', 'test4', 'test5']:
test_db.add_contact(i)
test_db.add_contact('test4')
test_db.add_users(['test1', 'test2', 'test3', 'test4', 'test5'])
test_db.save_message(
'test1',
'test2',
f'Привет! я тестовое сообщение от {datetime.datetime.now()}!')
test_db.save_message(
'test2',
'test1',
f'Привет! я другое тестовое сообщение от {datetime.datetime.now()}!')
print(test_db.get_contacts())
print(test_db.get_users())
print(test_db.check_user('test1'))
print(test_db.check_user('test10'))
print(test_db.get_history('test2'))
print(test_db.get_history(to_who='test2'))
print(test_db.get_history('test3'))
test_db.del_contact('test4')
print(test_db.get_contacts())
|
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: NinjaCard(),
));
class NinjaCard extends StatefulWidget {
@override
_NinjaCardState createState() => _NinjaCardState();
}
class _NinjaCardState extends State<NinjaCard> {
// State that will change
int ninjaLevel = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[900],
appBar: AppBar(
title: Text('Ninja ID Card'),
centerTitle: true,
backgroundColor: Colors.grey[850],
elevation: 0.0,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Function that trigger the build function updating the widget
setState(() {
ninjaLevel += 1;
});
},
child: Icon(
Icons.add,
),
backgroundColor: Colors.grey[800],
),
body: Padding(
padding: EdgeInsets.fromLTRB(30.0, 40.0, 30.0, 0.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: CircleAvatar(
backgroundImage: AssetImage('assets/thumb.jpg'),
radius: 40.0,
),
),
Divider(
height: 90.0,
color: Colors.grey[800],
),
Text(
'NAME',
style: TextStyle(
color: Colors.grey,
letterSpacing: 2.0,
),
),
SizedBox(height: 10.0),
Text(
'Andrea',
style: TextStyle(
color: Colors.amberAccent[200],
letterSpacing: 2.0,
fontSize: 28.0,
fontWeight: FontWeight.bold),
),
SizedBox(height: 30.0),
Text(
'CURRENT NINJA LEVEL',
style: TextStyle(
color: Colors.grey,
letterSpacing: 2.0,
),
),
SizedBox(height: 10.0),
Text(
'$ninjaLevel',
style: TextStyle(
color: Colors.amberAccent[200],
letterSpacing: 2.0,
fontSize: 28.0,
fontWeight: FontWeight.bold),
),
SizedBox(height: 30.0),
Row(
children: [
Icon(
Icons.email,
color: Colors.grey[400],
),
SizedBox(width: 10.0),
Text(
'[email protected]',
style: TextStyle(
color: Colors.grey[400],
fontSize: 18.0,
letterSpacing: 1.0,
),
)
],
)
],
),
),
);
}
}
|
#pragma once
#include "core/Timestep.h"
#include "event/Event.h"
#include "renderer/RenderDevice.h"
#include "renderer/Swapchain.h"
namespace Neptune
{
// ----- Layer -----------------
class Layer
{
public:
virtual ~Layer() = default;
virtual void OnInit(const Neptune::Ref<Neptune::RenderDevice>& device) {}
virtual void OnTerminate() {}
virtual void OnUpdate(Timestep ts) {}
virtual void OnRender(const Ref<Framebuffer>& framebuffer) {}
virtual void OnImGuiRender() {}
virtual void OnEvent(Scope<Event>& e) {}
const String& GetDebugName() const noexcept { return m_DebugName; }
protected:
Layer(const String& name = "Layer")
: m_DebugName(name) {}
private:
String m_DebugName;
};
} // namespace Neptune
|
<!DOCTYPE html>
<html>
<head>
<title>Age Calculator Demo</title>
<link rel="stylesheet" href="style/basic.css" />
<link rel="stylesheet" href="style/custom.css">
<script src="js/time.js"></script>
<style>
/* Setting alignment and fonts */
#box {
display: flex;
text-align: center;
font-family:
"Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS",
sans-serif;
background-color: white;
}
/* Defining card properties */
.card {
min-width: 30%;
box-shadow: 0 4px 8px 0 #ee7e07b4;
transition: 0.3s;
border-radius: 5px;
margin: auto;
padding: 2%;
padding-top: 0%;
}
header {
font-size: larger;
}
header h1 {
background-color: rgba(231, 231, 231, 0.711);
color: green;
font-size: xx-large;
padding: 1%;
}
/* Setting font and margin for text before input box */
label {
font-size: large;
margin: 2%;
}
button {
font-size: large;
padding: 1%;
}
input {
width: 200px;
height: 50px;
font-size: larger;
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
#inputDob {
margin: 2%;
}
p {
font-size: larger;
margin: 5%;
}
#currentAge {
min-width: 30%;
box-shadow: 0 4px 8px 0 rgba(130, 234, 234, 100);
transition: 0.3s;
border-radius: 5px;
margin: auto;
margin-top: 5%;
padding: 5%;
padding-top: 7%;
font-size: larger;
}
</style>
</head>
<body>
<header id="head" class="centxt">
<img class="himg threedtxtbox" src="img/lhproject_main.png" alt="Main Header" title="LOCALHOST" />
<script>
var str = document.title;
document.write("<h2>" + str);
</script>
</header>
<br/>
<!-- Main Menu -->
<nav id="nav-main">
<div class="nav_bar">
<div class="dropdown">
<button class="dropbtn">
<a href="index.html">Home</a>
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<!--Drop Content-->
</div>
</div>
<div class="dropdown">
<button class="dropbtn">
<a href="todo.html">Things To Do</a>
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="ThingsDone.html">Things Done</a>
</div>
</div>
<div class="dropdown">
<button class="dropbtn">
<a href="#">My Blogs</a>
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="blog_index.html">Blog Index</a>
<a href="Blogs.html">Blog Detail</a>
<a href="blogArchive.html">Blog Archive</a>
</div>
</div>
<div class="dropdown">
<button class="dropbtn">
<a href="img_gal.html">Image Gallery</a>
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<!--Drop Content-->
</div>
</div>
<div class="dropdown">
<button class="dropbtn">
<a href="#">Calendar Menu</a>
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="12month.html">12 Month Calendar</a>
<a href="Calendar.html">Web Calendar</a>
<a href="EasyCal.html">Easy UI Calendar</a>
</div>
</div>
<div class="dropdown">
<button class="dropbtn">
<a href="#">Demo Pages</a>
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="demo_one.html">Content Demo 1</a>
<a href="demo_two.html">Content Demo 2</a>
<a href="demo_three.html">Content Demo 3</a>
<a href="demo_four.html">Content Demo 4</a>
<a href="calage.html">Calculate Age Demo</a>
<a href="cssunits.html">Css Unit Demo</a>
<a href="Test.html">Other Tests</a>
<a href="Template.html">My Template</a>
</div>
</div>
<div class="dropdown">
<button class="dropbtn">
<a href="myproject.html">My project</a>
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="login.html">Login Demo</a>
<a href="useful.html">Useful Links</a>
<a href="Imagemap.html">Image Map</a>
<a href="mouseover_demo.html">Mouse Over Demo</a>
<a href="myanigif.html">My Animated Banner</a>
</div>
</div>
</div>
</nav>
<!-- Main Menu Ends Here -->
<main id="Sect_Main">
<br />
<div id="box">
<div class="card">
<header>
<h1>Age Calculator Demo</h1>
</header>
<div>
<label>Enter your Date of Birth</label>
<input id="inputDob"
type="date"
value="1965-07-12" />
<p class="note">Enter Disired Date above</p>
</div>
<br />
<!-- Take the date from which age is to be calculated -->
<div>
<label>Current Date</label><br>
<input id="cdate"
type="date"
value="" />
</div>
<br />
<button type="button"
onclick="getDOB()">
Calculate
</button>
<br />
<div id="currentAge"></div>
<script>
// Define funtion to get calculated Age
function getDOB() {
// Getting input from html input element
let data =
document.getElementById("inputDob").value;
// Convert input data to usable format
// as day,month and year
let dob = new Date(data);
let day = dob.getDate();
let month = dob.getMonth();
let year = dob.getFullYear();
// Getting current date and calculating the difference
let now =
new Date(document.getElementById("cdate").value);
console.log(now);
let yearDiff = now.getFullYear() - year;
let monthDiff = now.getMonth() - month;
let dateDiff = now.getDate() - day;
// Calculating the Age
if (yearDiff < 0) console.log("invalid date");
else if (monthDiff > 0) {
console.log(yearDiff);
} else if (monthDiff === 0 && dateDiff >= 0) {
console.log(yearDiff);
} else {
yearDiff = yearDiff - 1;
if (monthDiff <= 0)
if (dateDiff > 0) monthDiff = 12 + monthDiff;
else monthDiff = 11 - monthDiff;
}
if (dateDiff < 0) {
dateDiff = 30 + dateDiff;
monthDiff -= 1;
}
// Show calculated age as output
// and invalid if wrong input is given
if (yearDiff < 0)
document.getElementById("currentAge").innerHTML = "Invalid Date";
else
document.getElementById("currentAge").innerHTML =
"Your current Age is " + yearDiff + " years "
+ monthDiff + " months " + dateDiff + " days";
}
// Function to provide default date value
function currentDate() {
console.log(formatted());
let d = document.getElementById("cdate");
d.value = formatted();
}
function formatted(date = new Date()) {
return [
date.getFullYear(),
short(date.getMonth() + 1),
short(date.getDate()),
].join("-");
}
function short(num) {
return num.toString().padStart(2, "0");
}
// Calling current date function to set default date value
currentDate();
</script>
<br />
<a href="agecodejs.txt" target="_blank">See JS Code</a><br />
<a href="ageform.txt" target="_blank">See form that the javascript uses to generate answer</a>
</div>
</div>
<br />
</main>
<footer>
<time id="row1">
</time>
<br />
<time id="row2">
</time>
<script type="text/javascript">
updateClock();
</script>
</footer>
</body>
</html>
|
import { Component, OnInit } from "@angular/core";
import {
UntypedFormBuilder,
UntypedFormGroup,
Validators,
} from "@angular/forms";
import { RoleService } from "src/app/core/services/app/role.service";
import { UserService } from "src/app/core/services/user/user.service";
import { OptionListService } from "src/app/core/services/utils/option-list.service";
import Rol from "src/app/core/types/rol/rol";
import nUser from "src/app/core/types/user/nUser";
import oUser from "src/app/core/types/user/oUser";
import User from "src/app/core/types/user/user";
@Component({
selector: "app-users",
templateUrl: "./users.component.html",
styleUrls: ["./users.component.scss"],
})
export class UsersComponent implements OnInit {
alert: { type: string; message: string; active: boolean } = {
type: "success",
message: "",
active: false,
};
isNewUser: boolean = false;
isEditUser: boolean = false;
isShowInformation: boolean = false;
isLoadingNewUser: boolean = false;
isLoadingUser: boolean = false;
isLoadingChangePassword: boolean = false;
isLoadingRemoveRole: boolean = false;
isLoadingChangeRole: boolean = false;
listUsers: User[] = [];
listRols: Rol[] = [];
listDocumentType: any[] = [];
selectedRole: any;
changePassword: any = { oldPassword: "", password: "" };
newUser: nUser = {
address: "",
documentNumber: "",
documentTypeId: "none",
email: "",
lastname: "",
mobile: "",
name: "",
nickname: "",
password: "",
playerIdPush: "",
};
currentUser: User | any = {
id: "",
name: "",
isLockedOut: false,
lastname: "",
mobile: "",
email: "",
nickname: "",
playerPushId: "",
roleName: "",
status: false,
telephone: "",
createdOn: "",
modifieddOn: "",
};
currentOUser: oUser | any = {
address: "",
documentNumber: "",
documentTypeId: "",
email: "",
id: "",
lastname: "",
mobile: "",
name: "",
nickname: "",
};
newUserForm!: UntypedFormGroup;
constructor(
private formBuilder: UntypedFormBuilder,
private _userServices: UserService,
private _rolServices: RoleService,
private _optionListServices: OptionListService
) {}
ngOnInit(): void {
this.loadData();
this.newUserForm = this.formBuilder.group({
address: [
"",
[
Validators.required,
Validators.maxLength(100),
Validators.pattern("^[wds#-]*$"),
],
],
documentNumber: [
"",
[
Validators.required,
Validators.maxLength(20),
Validators.pattern("^[a-zA-Z0-9-]*$"),
],
],
email: ["", [Validators.required, Validators.email]],
lastname: [
"",
[
Validators.required,
Validators.maxLength(50),
Validators.pattern("^[a-zA-Z ]*$"),
],
],
mobile: [
"",
[
Validators.required,
Validators.maxLength(10),
Validators.pattern("^[d]*$"),
],
],
name: [
"",
[
Validators.required,
Validators.maxLength(30),
Validators.pattern("^[a-zA-Z ]*$"),
],
],
nickname: [
"",
[
Validators.required,
Validators.maxLength(20),
Validators.minLength(8),
Validators.pattern("^[wd]*$"),
],
],
password: [
"",
[
Validators.required,
Validators.maxLength(20),
Validators.minLength(8),
Validators.pattern("^[a-z.*-_]*$"),
],
],
});
}
loadData(direction?: string): void {
this.isLoadingUser = true;
this._userServices.getList().then(({ data }) => {
this.listUsers = data;
if (this.listUsers.length > 0 && !direction) {
this.getUser(this.listUsers[0]);
}
this.isLoadingUser = false;
});
this._rolServices.getList().then(({ isError, data }) => {
if (isError) {
return;
}
this.listRols = data;
});
this._optionListServices
.getListByKey("DOCUMENT")
.then(({ isError, data }) => {
if (isError) {
return;
}
this.listDocumentType = data;
});
}
async getUser({ id, ...user }: User): Promise<void> {
this.isNewUser = false;
this.isEditUser = false;
this._userServices.getById(id).then(({ isError, data }) => {
if (isError) {
return;
}
this.currentOUser = data;
if (this.currentOUser) {
this.currentUser = { id, ...user };
this.isShowInformation = true;
}
this._rolServices.getUserList(this.currentUser.id).then(({ isError, data }) => {
if (isError) {
return;
}
this.currentUser.rolData = data;
});
});
}
fnShowEditUser(): void {
const { name, lastname, nickname } = this.currentUser;
const { documentNumber, mobile, address, email } = this.currentOUser;
this.f["name"].setValue(name);
this.f["lastname"].setValue(lastname);
this.f["documentNumber"].setValue(documentNumber);
this.f["mobile"].setValue(mobile);
this.f["address"].setValue(address);
this.f["email"].setValue(email);
this.f["email"].disable();
this.f["nickname"].setValue(nickname);
this.f["nickname"].disable();
this.isShowInformation = false;
this.isNewUser = false;
this.isEditUser = true;
}
fnShowNewUser(): void {
this.newUserForm.reset();
this.newUserForm.enable();
this.isShowInformation = false;
this.isNewUser = true;
this.isEditUser = false;
}
fnCloseNewUser(): void {
this.isShowInformation = true;
this.isNewUser = false;
this.isEditUser = false;
this.newUserForm.reset();
}
fnNewUser(): void {
this.isLoadingNewUser = true;
this.newUserForm.disable();
console.log(this.newUserForm)
// if (!this.newUserForm.valid) {
// this.fnShowAlert(
// { type: "error", message: "Verifique los datos ingresados" },
// () => {
// this.isLoadingNewUser = false;
// }
// );
// return;
// }
if (this.isEditUser) {
this.updateUser();
return;
}
this.createUser();
return;
}
createUser(): void {
this._userServices
.create({
...this.newUserForm.value,
documentTypeId: "",
playerIdPush: "",
})
.then(({ isError, message, data }) => {
if (isError) {
this.fnShowAlert(
{
type: "error",
message:
message ?? "Verifique los datos ingresados",
},
() => {
this.isLoadingNewUser = false;
return;
}
);
}
this.fnShowAlert(
{
type: "success",
message: message ?? "Datos ingresados correctamente",
},
() => {
this.isLoadingNewUser = false;
this.newUserForm.enable();
this.loadData("home");
}
);
});
}
updateUser(): void {
this._userServices
.update(this.currentUser.id, this.newUserForm.value)
.then(({ isError, message, data }) => {
if (isError) {
this.fnShowAlert(
{
type: "error",
message:
message ?? "Verifique los datos ingresados",
},
() => {
this.isLoadingNewUser = false;
return;
}
);
}
this.fnShowAlert(
{
type: "success",
message: message || "Datos actualizados correctamente",
},
() => {
this.isLoadingNewUser = false;
this.newUserForm.enable();
this.loadData("home");
}
);
});
}
get f() {
return this.newUserForm.controls;
}
fnChangeRol(role: Rol): void {
this.selectedRole = role;
}
fnDisabledBtnChangePassword(): boolean {
return (
!this.changePassword.oldPassword ||
!this.changePassword.password ||
this.changePassword.password.length < 8
);
}
fnChangePassword(): void {
this.isLoadingChangePassword = true;
this._userServices
.changeUserPassword(this.currentUser.id, this.changePassword.password)
.then(({ isError, data, message }) => {
if (isError) {
this.fnShowAlert({ type: "error", message }, () => {});
return;
}
this.fnShowAlert(
{
type: "success",
message: message || "Cambio realizado correctamente",
},
() => {
this.changePassword = { oldPassword: "", password: "" };
}
);
this.isLoadingChangePassword = false;
});
}
fnRemoveRole(): void {
this._rolServices
.deleteUserToRole("", this.currentUser.id)
.then(({ isError, message }) => {
if (isError) {
this.fnShowAlert({ type: "error", message }, () => {});
return;
}
this.fnShowAlert(
{
type: "success",
message: message ?? "Cambio realizado correctamente",
},
() => {}
);
this.isLoadingRemoveRole = false;
});
}
fnChangeRole(): void {
this.isLoadingChangeRole = true;
this._rolServices
.changeUserToRole(this.selectedRole.id, this.currentUser.id)
.then(({ isError, message }) => {
if (isError) {
this.fnShowAlert({ type: "error", message }, () => {});
return;
}
this.fnShowAlert(
{
type: "success",
message: message || "Cambio realizado correctamente",
},
() => {}
);
this.isLoadingChangeRole = false;
});
}
fnShowAlert(
content: { type: string; message: string },
callback: () => any
): void {
this.alert = {
...content,
active: true,
};
callback();
setTimeout(() => {
this.alert.active = false;
}, 2500);
}
}
|
def has_reflection(idx, pattern, offset=0):
prev_idx = idx - offset
next_idx = idx + offset + 1
if prev_idx < 0 or next_idx == len(pattern):
return True
if pattern[prev_idx] == pattern[next_idx]:
return has_reflection(idx, pattern, offset=offset + 1)
return False
def has_smudged_reflection(idx, pattern, offset=0, still_smudged=True):
prev_idx = idx - offset
next_idx = idx + offset + 1
if idx == 0 or prev_idx < 0 or next_idx == len(pattern):
return True
if pattern[prev_idx] == pattern[next_idx]:
return has_smudged_reflection(
idx, pattern, offset=offset + 1, still_smudged=still_smudged
)
elif still_smudged and differs_by_one_bit(pattern[prev_idx], pattern[next_idx]):
return has_smudged_reflection(
idx, pattern, offset=offset + 1, still_smudged=False
)
return False
def convert_to_binary(line):
trans_table = line.maketrans("#.", "10")
return line.translate(trans_table)
def differs_by_one_bit(pattern1, pattern2):
xor = int(pattern1, 2) ^ int(pattern2, 2)
return xor and ((xor & (xor - 1)) == 0)
def print_patterns(patterns):
for pattern in patterns:
flipped = ["".join(x) for x in list(zip(*reversed(pattern["mirrors"])))]
for idx in range(max(len(pattern["mirrors"]), len(flipped))):
print(
f"{pattern['mirrors'][idx] if idx < len(pattern['mirrors']) else ' ' * len(pattern['mirrors'][0])} | {flipped[idx] if idx < len(flipped) else ''}"
)
print(f'Orig: {pattern["orig_reflection"]} New: {pattern["new_reflection"]}')
print(25 * "-")
def main():
patterns = []
with open("../inputs/day13_input.txt", encoding="utf-8") as f:
read_data = f.read()
pattern = []
for line in read_data.splitlines():
if not len(line.strip()):
patterns.append(
{
"mirrors": pattern,
"orig_reflection": None,
"new_reflection": None,
}
)
pattern = []
else:
pattern.append(convert_to_binary(line))
patterns.append(
(
{
"mirrors": pattern,
"orig_reflection": None,
"new_reflection": None,
}
)
)
# find original reflections
for pattern in patterns:
mirrors = pattern["mirrors"]
reflected = False
# check for horizontal reflection
for idx in range(len(mirrors) - 1):
if mirrors[idx] == mirrors[idx + 1]:
if has_reflection(idx, mirrors):
pattern["orig_reflection"] = (idx + 1, "h")
reflected = True
break
# check for vertical reflection
if not reflected:
flipped_mirrors = ["".join(x) for x in list(zip(*reversed(mirrors)))]
for idx in range(len(flipped_mirrors) - 1):
if flipped_mirrors[idx] == flipped_mirrors[idx + 1]:
if has_reflection(idx, flipped_mirrors):
pattern["orig_reflection"] = (idx + 1, "v")
break
orig_reflections = [p["orig_reflection"] for p in patterns]
sum_h = sum([loc for loc, direction in orig_reflections if direction == "h"]) * 100
sum_v = sum([loc for loc, direction in orig_reflections if direction == "v"])
# find smudge and new reflections
for pattern in patterns:
mirrors = pattern["mirrors"]
orig_r = pattern["orig_reflection"]
reflected = False
# check for horizontal reflection
for idx in range(len(mirrors) - 1):
# don't look in the same place for the reflection
if orig_r[1] == "h" and idx + 1 == orig_r[0]:
continue
# breakpoint()
if mirrors[idx] == mirrors[idx + 1]:
if has_smudged_reflection(idx, mirrors):
pattern["new_reflection"] = (idx + 1, "h")
reflected = True
break
# check if mirrors differ by a single bit (smudged)
elif differs_by_one_bit(mirrors[idx], mirrors[idx + 1]):
if has_smudged_reflection(idx, mirrors) and orig_r != (idx + 1, "h"):
pattern["new_reflection"] = (idx + 1, "h")
reflected = True
break
# check for vertical reflection
if not reflected:
flipped_mirrors = ["".join(x) for x in list(zip(*reversed(mirrors)))]
for idx in range(len(flipped_mirrors) - 1):
# don't look in the same place for the reflection
if orig_r[1] == "v" and idx + 1 == orig_r[0]:
continue
if flipped_mirrors[idx] == flipped_mirrors[idx + 1]:
if has_smudged_reflection(idx, flipped_mirrors):
pattern["new_reflection"] = (idx + 1, "v")
reflected = True
break
# check if mirrors differ by a single bit (smudged)
elif differs_by_one_bit(flipped_mirrors[idx], flipped_mirrors[idx + 1]):
if has_smudged_reflection(idx, flipped_mirrors):
pattern["new_reflection"] = (idx + 1, "v")
reflected = True
break
new_reflections = [p["new_reflection"] for p in patterns]
sum_h = sum([loc for loc, direction in new_reflections if direction == "h"]) * 100
sum_v = sum([loc for loc, direction in new_reflections if direction == "v"])
print(sum_h + sum_v)
if __name__ == "__main__":
main()
|
import { IsNotEmpty, IsNumberString, IsString } from 'class-validator';
export class CreateReviewDto {
@IsNotEmpty()
@IsString()
title: string;
@IsNotEmpty()
@IsString()
description: string;
@IsNotEmpty()
@IsNumberString()
rating: number;
@IsNotEmpty()
@IsString()
country: string;
@IsNotEmpty()
@IsString()
city: string;
}
|
import mongoose from "mongoose";
import bcrypt from "bcrypt";
import validator from "validator";
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
}, { timestamps: true })
// static signup method, customize function
// *** "this" cannot used in "arrow function"
// <schema name>.statics.<function name> = async function () { }
userSchema.statics.signup = async function (email, password) {
// validation
if (!email || !password) {
throw Error('All fields must be filled')
}
if (!validator.isEmail(email)) {
throw Error('Email is not valid')
}
if (!validator.isStrongPassword(password)) {
throw Error('Password not strong enough')
}
const exists = await this.findOne({ email })
if (exists) {
throw Error('Email already in use')
}
const salt = await bcrypt.genSalt(10) // define how many salt you want to add
const hash = await bcrypt.hash(password, salt) // chop and stir with salt
const user = await this.create({ email, password: hash })
return user
}
userSchema.statics.login = async function (email, password) {
// validation
if (!email || !password) {
throw Error('All fields must be filled')
}
const user = await this.findOne({ email })
if (!user) {
throw Error('Incorrect email')
}
// compare input password and database password
const match = await bcrypt.compare(password, user.password)
if (!match) {
throw Error('Incorrect password')
}
return user
}
export default mongoose.model('User', userSchema)
|
<template>
<img
v-if="Object.keys(entries).length"
class="d-none"
:src="Object.keys(entries)[0]"
@load="
({ target }) => {
coverHeight = (target as HTMLImageElement).height;
coverWidth = (target as HTMLImageElement).width;
}
"
/>
<div
id="book-and-toc-container"
class="start-0 top-0 d-flex flex-row align-items-center justify-content-space-around"
>
<b-container class="book-container d-flex w-50 h-100 m-0">
<div id="book" class="flip-book">
<div
v-for="(url, index) in Object.keys(entries)"
:key="`page-${index}`"
class="page"
:class="{ single: isSinglePage }"
>
<div class="page-content" :class="{ 'first-page': index === 0 }">
<div
class="page-image"
:style="{
backgroundImage: `url(${url})`,
marginLeft: 0,
}"
>
<div
v-if="
showAiDetections !== undefined &&
xOffset !== undefined &&
displayRatioNoCropping &&
aiDetails[url].panels?.length
"
class="position-absolute h-100"
:style="{
left: `${xOffset || 0}px`,
width: `${displayedWidth! - (xOffset || 0)*2}px`,
}"
>
<div
v-for="({ bbox: { x, y, width, height } }, idx) in aiDetails[
url
].panels"
:key="`ocr-match-${idx}`"
class="position-absolute ocr-match panel"
:style="{
left: `${x * displayRatioNoCropping}px`,
top: `${y * displayRatioNoCropping}px`,
width: `${width * displayRatioNoCropping}px`,
height: `${height * displayRatioNoCropping}px`,
}"
></div>
<div
class="position-absolute"
:style="toPx(firstPanelPosition(url))"
>
<div
v-for="({ box }, idx) in aiDetails[url].texts?.ocrResults ||
[]"
:key="`ocr-match-${idx}`"
class="position-absolute ocr-match text"
:style="{
clipPath: `polygon(${box
.map(([x, y]) =>
(['width', 'height'] as const)
.map(
(dimension, idx) =>
`${
[x, y][idx] /
(aiDetails[url].panels[0].bbox[dimension] /
100)
}%`
)
.join(' ')
)
.join(',')})`,
}"
>
{{
`polygon(${box.map(([x, y]) => `${x}% ${y}%`).join(",")})`
}}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</b-container>
<b-card
no-body
class="table-of-contents d-flex w-50 h-100 m-0 overflow-auto"
body-class="flex-grow-1 w-100 h-100"
>
<template #header>
<IssueSuggestionModal />
<IssueSuggestionList />
<div>
<b-button
variant="success"
pill
class="ms-2 hint"
:disabled="ai.status.value === 'loading'"
:class="ai.status.value"
@click="ai.runKumiko(indexationId)"
>
<i-bi-lightbulb-fill
/></b-button></div
></template>
<b-tabs
v-if="entries"
v-model="currentTabIndex"
pills
card
vertical
class="flex-grow-1"
:class="{ disabled: !acceptedIssue?.data }"
nav-wrapper-class="w-100 h-100 flex-grow-1"
nav-class="w-100 h-100"
>
<b-tab
v-for="(entryurl, index) in Object.keys(entries)"
:key="entryurl"
title-link-class="w-100 h-100 d-flex align-items-left"
title-item-class="w-100"
><template #title
><Entry
:entryurl="entryurl"
:editable="currentTabIndex === index" /></template
></b-tab>
</b-tabs>
</b-card>
</div>
</template>
<script setup lang="ts">
import { PageFlip } from "page-flip";
import { storeToRefs } from "pinia";
import { computed, ref, watch } from "vue";
import useAi from "~/composables/useAi";
import { ai as aiStore } from "~/stores/ai";
import { suggestions } from "~/stores/suggestions";
import { user } from "~/stores/user";
const route = useRoute();
const ai = useAi();
const aiDetails = storeToRefs(aiStore()).aiDetails;
const coverWidth = ref(null as number | null);
let coverHeight = ref(null as number | null);
let book = ref(null as PageFlip | null);
const currentTabIndex = ref(0 as number);
const {
storyversionKindSuggestions,
acceptedIssue,
entrySuggestions: entries,
} = storeToRefs(suggestions());
const { showAiDetectionsOn: showAiDetections } = user();
const indexationId = computed(() => route.params.id as string);
const isSinglePage = computed(() => Object.keys(entries.value).length === 1);
const displayedWidth = computed(() => book.value?.getSettings().width);
const displayedHeight = computed(() => book.value?.getSettings().height);
const xOffset = computed(
() =>
displayedHeight.value &&
pageRatio.value &&
displayedWidth.value &&
(displayedWidth.value - displayedHeight.value * pageRatio.value) / 2
);
const pageRatio = computed(() => coverWidth.value! / coverHeight.value!);
const displayRatioNoCropping = computed(
() =>
displayedHeight.value &&
coverHeight.value &&
displayedHeight.value / coverHeight.value
);
const firstPanelPosition = (url: string) => {
const { bbox } = aiDetails.value[url].panels[0];
return {
left: bbox.x * displayRatioNoCropping.value!,
top: bbox.y * displayRatioNoCropping.value!,
width: bbox.width * displayRatioNoCropping.value!,
height: bbox.height * displayRatioNoCropping.value!,
};
};
const toPx = (position: Record<string, number>) =>
Object.entries(position).reduce(
(acc, [key, value]) => ({
...acc,
[key]: `${value}px`,
}),
{}
);
watch(
() => currentTabIndex.value,
(newValue) => {
if (book.value) {
book.value.flip(newValue);
}
}
);
watch(
() => coverWidth.value,
(newValue) => {
const availableWidthPerPage = document.body.clientWidth / 2 - 15;
if (newValue && newValue > availableWidthPerPage) {
coverHeight.value! /= newValue / availableWidthPerPage;
}
}
);
watch(
() => coverWidth.value && coverHeight.value,
(hasCoverDimensions) => {
if (hasCoverDimensions) {
const bookContainer = document.querySelector(".book-container")!;
book.value = new PageFlip(
document.getElementById("book") as HTMLElement,
{
width: Math.min(bookContainer.clientWidth / 2, coverWidth.value!),
height: Math.min(bookContainer.clientHeight, coverHeight.value!),
maxShadowOpacity: 0.5,
showCover: true,
usePortrait: false,
mobileScrollSupport: false,
}
);
book.value.loadFromHTML(document.querySelectorAll(".page"));
book.value.on("flip", ({ data }) => {
currentTabIndex.value = parseInt(data.toString());
});
}
},
{ immediate: true }
);
watch(
() => storyversionKindSuggestions.value,
async () => {
await ai.runCoverSearch(indexationId.value);
await ai.runStorycodeOcr(indexationId.value);
ai.status.value = "loaded";
},
{ deep: true }
);
</script>
<style scoped lang="scss">
#book-and-toc-container {
height: 100%;
}
@keyframes pulse-yellow {
0% {
color: #999;
}
50% {
color: yellow;
}
100% {
color: #999;
}
}
.table-of-contents {
background-color: #eee;
color: black;
white-space: nowrap;
.hint {
svg {
color: #999;
}
&:hover,
&.loaded {
svg {
color: yellow;
}
}
&.loading {
svg {
animation: pulse-yellow 2s infinite;
}
}
}
.card-header {
text-align: center;
:deep(a),
:deep(h6) {
color: #666;
}
h3 {
margin: 6px 6px 0 6px;
text-align: center;
}
}
.col-auto {
width: 100%;
}
:deep(ul) {
overflow-x: auto;
}
:deep(.tab-content) {
display: none;
}
}
.flip-book {
max-width: 100% !important;
margin: auto;
background-size: cover;
}
.page {
color: #785e3a;
overflow: hidden;
.page-content {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: stretch;
background: white;
.page-image {
height: 100%;
background-size: contain;
background-position: center center;
background-repeat: no-repeat;
}
&.first-page {
background: transparent;
.page-image {
transform: rotate3d(0, 1, 0, -90deg);
transform-origin: left;
transition: all 1s linear;
transform: rotate3d(0, 1, 0, 0deg);
}
}
}
&.--left {
// for left page (property will be added automatically)
border-right: 0;
.page-image {
box-shadow: inset -7px 0 30px -7px rgba(0, 0, 0, 0.4);
}
}
&.--right {
// for right page (property will be added automatically)
border-left: 0;
.page-image {
box-shadow: inset 7px 0 30px -7px rgba(0, 0, 0, 0.4);
}
}
&.hard {
// for hard page
background-color: #f2e8d9;
}
&.page-cover {
background-color: #e3d0b5;
color: #785e3a;
}
&.single {
left: initial !important;
right: 0 !important;
}
.ocr-match {
border: 1px solid red;
&.text {
background: rgba(0, 0, 0, 0.4);
width: 100%;
height: 100%;
}
}
}
</style>
|
extends Node2D
const TOWER_MULT = [
0.1,
0.5,
1.0,
0.0,
]
const DROP_RATES = [0, 0, 1, 0]
# Shader stuff
const PLANT_MATERIAL := preload("res://shaders/PlantMaterial.tres")
onready var plant_material := PLANT_MATERIAL.duplicate()
const BORDER_COLOR_WARMUP := Color(1, 1, 1, 0)
const BORDER_COLOR_READY := Color(1, 1, 1, 1)
const BORDER_COLOR_ROTTING := Color(0.7, 0, 0, 1)
const TIME_WARMUP := 0.5
const TIME_ROT_WARN := 8.0
onready var timer: Timer = $Timer
onready var animator: AnimationPlayer = $AnimationPlayer
onready var tween: Tween = $Tween
onready var sprite: Sprite = $Sprite
onready var MAX_STATE := Globals.GrowState.size() - 1
onready var stats := $StatsStatic
export var MIN_GROW_TIME = 1
export var MAX_GROW_TIME = 1
export var FINAL_FORM_MULT = 4
export var plant_type = Globals.ItemType.PlantChili
var state = Globals.GrowState.Seedling
var tower_stats = []
var _current_duration := 0.0
var is_active := false setget _set_is_active
var can_rot := true
var settings := Settings.get_settings()
func _ready():
_start_timer()
settings.connect("settings_changed", self, "_on_settings_changed")
func _on_grow():
if not is_active or (not can_rot and state == Globals.GrowState.Grown):
return
state += 1
if state < MAX_STATE:
_start_timer()
if state >= MAX_STATE:
is_active = false
timer.stop()
animator.play("grow") # calls _update_sprite_frame() after a short time
update_tower_stat()
# called by AnimationPlayer at peak of animation
func _update_sprite_frame():
sprite.set_frame(state)
_update_shader()
func _update_shader(start_time := 0.0):
if state == Globals.GrowState.Grown:
sprite.material = plant_material if settings.shaders_on else null
var time_rot := min(TIME_ROT_WARN, _current_duration)
var time_warmup := min(TIME_WARMUP, _current_duration - time_rot)
var time_ready := _current_duration - (time_warmup + time_rot)
tween.interpolate_method(self, "_set_shader_color", BORDER_COLOR_WARMUP, BORDER_COLOR_READY, time_warmup)
# following seems useless but is important if shaders turned off in the middle of animation
tween.interpolate_method(self, "_set_shader_color", BORDER_COLOR_READY, BORDER_COLOR_READY, time_ready, 0, 2, time_warmup)
tween.interpolate_method(self, "_set_shader_color", BORDER_COLOR_READY, BORDER_COLOR_ROTTING, time_rot, 0, 2, time_warmup + time_ready)
tween.start()
if start_time > 0:
tween.seek(start_time)
else:
sprite.material = null
tween.stop_all()
func _on_settings_changed(settings_name):
if settings_name == "shaders_on":
_update_shader(_current_duration - timer.time_left)
func _set_shader_color(color: Color):
if sprite.material != null:
sprite.material.set_shader_param("color", color)
func _start_timer():
_current_duration = rand_range(MIN_GROW_TIME, MAX_GROW_TIME)
if state == Globals.GrowState.Grown:
_current_duration *= FINAL_FORM_MULT
timer.start(_current_duration)
func _set_is_active(v: bool):
is_active = v
modulate.a = 1.0 if is_active else 0.4
func _buff_tower(towers):
for tower in towers:
var new_stat = stats.duplicate()
tower.stats.add_child(new_stat)
tower_stats.append([tower, new_stat])
update_tower_stat()
# check if the plant is kept alive (i.e. not rotten) by any of the towers
func _check_tower_keep_alive(towers):
for tower in towers:
if tower.keep_alive:
can_rot = false
return
can_rot = true
func get_mult_state():
return TOWER_MULT[state]
func update_tower_stat():
var new_tower_stats := []
for tower_stat in tower_stats:
if is_instance_valid(tower_stat[0]):
tower_stat[1].multiplicator = get_mult_state()
tower_stat[0].stats.calc_stats()
new_tower_stats.append(tower_stat)
tower_stats = new_tower_stats
# Returns number of drops
func harvest() -> int: # The Holy Harvest Function
var drops = DROP_RATES[state]
if state == Globals.GrowState.Rotten or state == Globals.GrowState.Grown:
state = 0
is_active = true
sprite.set_frame(state)
emit_signal("on_grow", state)
_update_shader()
_start_timer()
update_tower_stat()
return drops
|
import { Component } from "react"
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { finishTask } from "../redux/actions/to-do.action";
class ToDoList extends Component {
handleInputChange = ({ target }, task) => {
const { dispatch } = this.props;
const value = target.type === 'checkbox' ? target.checked : target.value;
dispatch(finishTask({
...task,
finished: value
}))
};
render() {
const {tasks} = this.props
return (
<ul>
{tasks.map((task) => (
<li key={task.title}>
<span>{task.title}</span>
<input
type="checkbox"
checked={task.completed}
onChange={(event) => this.handleInputChange(event, task)}
/>
</li>
))}
</ul>
)
}
}
const mapStateToProps = ({ toDo }) => ({
tasks: toDo.tasks,
});
ToDoList.propTypes = {
tasks: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.string,
})).isRequired,
};
export default connect(mapStateToProps)(ToDoList);
|
import * as Yup from "yup";
import axios, { AxiosError } from "axios";
export interface APIError {
code: string;
developerMessage?: string;
errorType?: string | null;
field?: string | null;
message: string;
}
export interface APIErrorResponse {
errors: APIError[];
path: string;
}
// Validation schema of the APIError interface
const APIErrorValidationSchema = Yup.object().shape({
code: Yup.string().required(),
developerMessage: Yup.string().optional(),
errorType: Yup.string().nullable().optional(),
field: Yup.string().nullable().optional(),
message: Yup.string().required(),
});
// Validation schema of the APIErrorResponse interface
const APIErrorResponseValidationSchema = Yup.object().shape({
errors: Yup.array().of(APIErrorValidationSchema).required(),
path: Yup.string().required(),
});
/**
* Validate an object if it fits the schema of an APIErrorResponse object.
* @param payload
*/
function isAPIErrorResponse(payload: any): payload is APIErrorResponse {
return APIErrorResponseValidationSchema.isValidSync(payload);
}
/**
* Validate if an error is an axios-error containing an APIErrorResponse object
* @param payload
*/
export function isAPIError(
payload: any
): payload is AxiosError<APIErrorResponse> {
return (
axios.isAxiosError(payload) && isAPIErrorResponse(payload.response?.data)
);
}
|
//
// Category.swift
// E-Store
//
// Created by Laptop MCO on 09/08/23.
//
import Foundation
struct Category {
let id: Int
let name: String
let image: String
}
extension Category: Codable {
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case image = "image"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(Int.self, forKey: .id) ?? 0
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
image = try container.decodeIfPresent(String.self, forKey: .image) ?? ""
}
// func encode(to encoder: Encoder) throws {
// var container = encoder.container(keyedBy: CodingKeys.self)
// try container.encodeIfPresent(id, forKey: .id)
// try container.encodeIfPresent(name, forKey: .name)
// try container.encodeIfPresent(image, forKey: .image)
// }
}
|
"use client";
import React from "react";
import { useRouter } from "next/navigation";
import { Button } from "../ui/button";
import BasketButton from "./BasketButton";
import { useAuth } from "@/context/AuthContext";
import {
DropdownMenu,
DropdownMenuItem,
DropdownMenuShortcut,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { LogOut } from "lucide-react";
import UserInfoButton from "./UserInfoButton";
function Navbar() {
const router = useRouter();
const { loginUser } = useAuth();
return (
<div className="flex flex-row justify-between bg-rose-500 h-16">
<div className="flex justify-center items-center w-2/12 mx-5 ">
<h1
className="text-white font-bold text-3xl"
onClick={() => {
router.push("/");
}}
>
FBilet
</h1>
</div>
<div className="flex flex-row justify-around items-center w-3/12 mx-10 ">
{!loginUser && (
<>
<div className="flex justify-center w-1/3 h-2/3">
<Button
onClick={() => {
router.push("/login");
}}
className="w-full h-full rounded-full bg-white text-rose-500 font-medium text-lg border-slate-200 "
>
Login
</Button>
</div>
<div className="flex justify-center w-1/3 h-2/3">
<Button
onClick={() => {
router.push("/signUp");
}}
className="w-full h-full rounded-full bg-white text-rose-500 font-medium text-lg border-slate-200 "
>
SignUp
</Button>
</div>
</>
)}
{loginUser && (
<>
<div className="flex justify-center w-1/3 h-2/3">
<BasketButton />
</div>
<div className="flex justify-center w-1/3 h-2/3">
<UserInfoButton />
</div>
</>
)}
</div>
</div>
);
}
export default Navbar;
|
<template>
<div :class="$style.wrapper">
<nav :class="$style.boards">
<li
v-for="board in $store.state.boards"
:key="board.id"
@click="$store.commit('setOpenedBoard', board.boardName)"
:class="{
[$style.activeBoard]: board.boardName === $store.state.openedBoard,
}"
>
{{ board.boardName }}
</li>
</nav>
<main :class="$style.content">
<div :class="$style.lists" v-if="$store.state.openedBoard">
<div
v-for="list in $store.getters.getLists"
:key="list.id"
:class="$style.list"
@drop="onDrop($event, list.listName)"
@dragover.prevent
@dragenter.prevent
>
<p>{{ list.listName }}</p>
<div
v-for="task in $store.getters.getTasks.filter(
(i) => i.listName === list.listName
)"
:key="task.id"
:class="$style.task"
@dragstart="onDragStart($event, task)"
draggable="true"
>
{{ task.name }}
</div>
</div>
</div>
<p v-else :class="$style.choose">Выберите доску</p>
</main>
</div>
</template>
<script>
export default {
name: "App",
methods: {
onDragStart(e, task) {
e.dataTransfer.dropEffect = "move";
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("taskId", task.id);
},
onDrop(e, listName) {
const taskId = e.dataTransfer.getData("taskId");
this.$store.commit("dropTask", { taskId, listName });
},
},
};
</script>
<style lang="scss" module>
body {
padding: 0;
margin: 0;
}
.wrapper {
display: grid;
height: 100vh;
grid-template-columns: 1fr 4fr;
.boards {
background-color: #f3f3f3;
height: 100%;
color: grey;
padding: 4rem 0 0 0;
li {
text-align: center;
margin: 0 0 2rem 0;
list-style-type: none;
cursor: pointer;
}
.activeBoard {
color: black;
}
}
.content {
height: 100%;
background-color: #b5b1b1;
.lists {
display: flex;
height: 100%;
.list {
width: 15rem;
height: 100%;
padding: 1rem;
text-align: center;
border-right: 1px solid #000;
.task {
cursor: pointer;
background-color: #f3f3f3;
height: 3rem;
display: flex;
align-items: center;
justify-content: center;
margin: 0 0 1.5rem;
border-radius: 0.5rem;
}
}
}
.choose {
text-align: center;
padding: 4rem 0 0 0;
font-size: 1.5rem;
}
}
}
</style>
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CounterComponent } from './components/counter/counter.component';
import { FlightBookerComponent } from './components/flight-booker/flight-booker.component';
import { TemperatureComponent } from './components/temperature/temperature.component';
import { TimerComponent } from './components/timer/timer.component';
import { WorkshopComponent } from './components/workshop/workshop.component';
const routes: Routes = [
{ path: '', component: WorkshopComponent },
{ path: 'counter', component: CounterComponent},
{ path: 'flight-booker', component: FlightBookerComponent},
{ path: 'temperature', component: TemperatureComponent},
{ path: 'timer', component: TimerComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import './App.css';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { useState } from 'react';
import LoginPage from './pages/LoginPage';
import SignUpPage from './pages/SignUpPage';
import HomePage from './pages/HomePage';
import AdminPage from './pages/AdminPage';
import EditUser from './Users/EditUser';
import PostCreation from './pages/PostCreation';
import SelectionPage from './pages/SelectionPage';
import AgileBoard from './pages/AgileBoard';
import ProfilePage from './pages/ProfilePage';
import EditPostCreation from './pages/EditPostPage';
import ChatPage from './pages/ChatPage';
import StickyNotePage from './pages/StickyNotePage';
function App() {
//Using a useState to keep track of log
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<Router>
<Routes>
<Route
exact path='/'
Component={LoginPage}
/>
<Route
exact path='/homepage'
Component={HomePage}
/>
<Route
exact path='/signup'
Component={SignUpPage}
/>
<Route
exact path='/adminpage'
Component={AdminPage}
/>
<Route
exact path='/edituser/:id'
Component={EditUser}
/>
<Route
exact path='/postcreation'
Component={PostCreation}
/>
<Route
exact path='/selectionpage'
Component={SelectionPage}
/>
<Route
exact path='/agileboardcreation'
Component={AgileBoard}
/>
<Route
exact path='/profilepage/:id'
Component={ProfilePage}
/>
<Route
exact path='/editpostcreation/:projectId'
Component={EditPostCreation}
/>
<Route
exact path='/chatpage'
Component={ChatPage}
/>
<Route
exact path='/StickyNotePage'
Component={StickyNotePage}
/>
</Routes>
</Router>
);
}
export default App;
|
package org.poo.challenge;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
public class Bootcamp {
private String name;
private String description;
private LocalDate startDate = LocalDate.now();
private LocalDate finalDate = startDate.plusDays(45);
private Set<Dev> subscribedDevs = new HashSet<>();
private Set<Content> contents = new LinkedHashSet<>();
public Bootcamp(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public LocalDate getStartDate() {
return startDate;
}
public LocalDate getFinalDate() {
return finalDate;
}
public Set<Dev> getSubscribedDevs() {
return subscribedDevs;
}
public Set<Content> getContents() {
return contents;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bootcamp bootcamp = (Bootcamp) o;
return Objects.equals(name, bootcamp.name) && Objects.equals(description, bootcamp.description) && Objects.equals(startDate, bootcamp.startDate) && Objects.equals(finalDate, bootcamp.finalDate) && Objects.equals(subscribedDevs, bootcamp.subscribedDevs) && Objects.equals(contents, bootcamp.contents);
}
@Override
public int hashCode() {
return Objects.hash(name, description, startDate, finalDate, subscribedDevs, contents);
}
}
|
import React, { useState } from 'react'
import { useNavigate } from "react-router-dom";
import AdminHearder from './AdminHearder';
function AddNewMeal() {
const [image, setImage] = useState("");
const [name, setName] = useState("");
const [price, setPrice] = useState("");
const [category, setCategory] = useState("");
const [description, setDescription] = useState("");
const [isPending, setisPending] = useState(false);
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
const meal = { image, name, price, category, description };
console.log(meal);
setisPending(true);
fetch("http://127.0.0.1:3000/meals", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(meal),
})
.then((res) => res.json())
.then(() => {
setImage("");
setName("");
setPrice("");
setCategory("");
setDescription("");
setisPending(false);
navigate("/dashboard");
});
};
return (
<div>
<AdminHearder/>
<div className="p-8 bg-orange-50 ">
<h2 className="text-3xl text-gray-600 font-bold">Add a New Post</h2>
<form className="p-4 flex flex-col" onSubmit={handleSubmit}>
<label className="pb-4 mt-4">Meal Name:</label>
<input
className="p-2 border border-solid border-gray-300"
type="text"
required
value={name}
placeholder="Add meal name"
onChange={(e) => setName(e.target.value)}
/>
<label className="pb-4 mt-4">Meal Price:</label>
<input
className="p-2 border border-solid border-gray-300 "
type="text"
required
value={price}
placeholder="Add price"
onChange={(e) => setPrice(e.target.value)}
/>
<label className="pb-4 mt-4">Meal Category:</label>
<input
className="p-2 border border-solid border-gray-300"
type="text"
required
value={category}
placeholder="Add a category"
onChange={(e) => setCategory(e.target.value)}
/>
{/* <label className='pb-4 mt-4'>Article Author:</label>
<input className='p-2 border border-solid border-gray-300 '
type="text"
required
value={author}
placeholder="Add your name"
onChange={(e)=>setAuthor(e.target.value)}
/> */}
<label className="mt-4 pb-4">Meal Description: </label>
<textarea
className="py-10 border border-solid border-gray-300"
required
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
{!isPending && (
<button className="mx-80 p-2 mt-6 border border-gray-400 rounded-full text-gray-600 bg-orange-400">
Add Meal
</button>
)}
{isPending && <button disabled>Adding Meal</button>}
</form>
</div>
</div>
);
}
export default AddNewMeal
|
function countSort(arr, exp, swaps) {
const length = arr.length;
let output = Array(length); // output array
let count = Array(10).fill(0, 0);
// Store count of digits in count[]
for (let i = 0; i < length; i++) {
const digit = Math.floor(arr[i] / exp) % 10;
count[digit]++;
}
// Change count[i] so that digits are in correct position
for (let i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
for (let i = length - 1; i >= 0; i--) {
const digit = Math.floor(arr[i] / exp) % 10;
swaps.push({sort: "radix", indices: [i, count[digit] - 1], type: "insert"});
output[count[digit] - 1] = arr[i];
count[digit]--;
}
return output;
}
export function radixSort(array) {
const swaps = [];
const maxNumber = getMax(array, swaps);
let copy = [...array];
let exp; // exp is 10^i where i is current digit number
// NOTE: instead of passing digit number, exp is passed.
// exp is 10^i where i is current digit number
// This uses integer division to get the digit
for (exp = 1; Math.floor(maxNumber / exp) > 0; exp *= 10) {
const sortedIteration = countSort(copy, exp, swaps);
copy = sortedIteration;
}
const sortedIteration = countSort(copy, exp * 10, swaps);
copy = sortedIteration;
for(let i = 0; i < array.length; i++) {
array[i] = copy[i];
}
return swaps;
}
function getMax(array, swaps) {
let max = array[0];
swaps.push({sort: "radix", indices: [0, max], type: "comp"});
for (let i = 1; i < array.length; i++)
if (array[i] > max) max = array[i];
return max;
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DetailsComponent } from './components/details/details.component';
import { HomeComponent } from './components/home/home.component';
import { MylistComponent } from './components/mylist/mylist.component';
const routes: Routes = [
{ path: '', component: HomeComponent},
{ path: 'watch',
children: [
{ path: ':media_type/:id', component: DetailsComponent }
]
},
{ path: 'mylist', component: MylistComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigModule } from '@nestjs/config';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
import { UsersModule } from './users/users.module';
import { AuthModule } from './auth/auth.module';
import { SwipesModule } from './swipes/swipes.module';
import { EventsModule } from './events/events.module';
import { ChatsModule } from './chats/chats.module';
require('dotenv').config();
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: `.${process.env.NODE_ENV}.env`,
}),
JwtModule.register({
secret: process.env.PRIVATE_KEY || 'SECRET',
}),
ServeStaticModule.forRoot({
rootPath: join(__dirname, '.', 'public'),
}),
MongooseModule.forRoot(`mongodb+srv://${process.env.DB_LOGIN}:${process.env.DB_PASSWORD}@findpasttime.kcuol.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`),
UsersModule,
AuthModule,
SwipesModule,
EventsModule,
ChatsModule,
],
controllers: [],
providers: [],
exports: [JwtModule],
})
export class AppModule {}
|
---
description: 有关打包和保护内容的信息使您能够保护内容。
title: 包装和保护内容
source-git-commit: 02ebc3548a254b2a6554f1ab34afbb3ea5f09bb8
workflow-type: tm+mt
source-wordcount: '805'
ht-degree: 0%
---
# 包装和保护内容 {#packaging-protecting-content}
有关打包和保护内容的信息使您能够保护内容。
## 保护服务器 {#securing-the-server}
您需要对进行策略管理和内容打包的计算机进行物理保护。
有关更多信息,请参阅 [物理安全和访问](../../secure-deployment-guidelines/physical-sec-and-access.md).
如果您的内容打包实施需要网络连接,则必须加固操作系统并实施适当的防火墙解决方案。 有关更多信息,请参阅 [网络拓扑](../../secure-deployment-guidelines/overview/network-topology.md).
## 安全打包内容 {#securely-packaging-content}
Adobe Primetime DRM Media Packager命令行工具的配置文件要求在打包期间使用PKCS12凭据。
在参考实施命令行工具中,PKCS12凭据文件的密码存储在 `flashaccess.properties` 文件格式为明文。 因此,在保护承载此文件的计算机时,请格外小心,并确保计算机处于安全环境中。 有关更多信息,请参阅 [物理安全和访问](../../secure-deployment-guidelines/physical-sec-and-access.md).
Packager还使用License Server和License Server传输证书,必须保护此信息的完整性和机密性。 应仅允许授权实体使用打包程序。 如果您的私钥泄露,请立即通知Adobe Systems Incorporated以吊销证书。
>[!NOTE]
>
>利用API,可对多个内容使用相同的密钥。 为确保最高级别的安全性,您应该只对多位速率FMS内容使用此功能。 请勿对代表不同内容的多个文件使用同一密钥。
Primetime DRM打包API在某些情况下会发出警告。 查看这些警告,以确定文件是否已成功加密。 警告消息可能是以下内容之一:
* 策略已过期,无法对无法识别的标记或跟踪进行加密。
* 无法加密影片片段,这些片段中的引用可能无效。
* 无法对元数据加密。
如果使用属性不正确的策略打包内容,则需要更新策略。 更新的策略必须通过策略更新列表或其他投放机制提供给许可证服务器。 某些策略属性在创建策略后无法更改。 如果这些属性不正确,请将内容从分发站点拉回,撤销策略以便将来不会授予任何许可证,然后再次加密内容。
包装完成后,包装密钥被垃圾收集,不会显式销毁。 因此,封装密钥在内存中保留了一段时间。 您必须防止对计算机进行未经授权的访问,并确保不会公开任何可能泄露此信息的文件,例如核心转储。
## 安全存储策略 {#securely-storing-policies}
Adobe Primetime DRM SDK允许您开发可用于内容打包和策略创建的应用程序。
创建这些应用程序时,您可以允许某些用户创建和修改策略,并限制其他用户只将现有策略应用于内容。 您必须实施必要的访问控制,并为策略创建和策略应用创建具有不同权限的用户帐户。
在策略用于打包之前,不会对其进行签名或防止对其进行修改。 如果您担心打包工具用户可能会修改策略,请签署策略以确保无法修改策略。
有关使用SDK创建应用程序的更多信息,请参阅 [API Primetime API参考](https://help.adobe.com/en_US/primetime/api/index.html#api-Adobe_Primetime_API_References).
## 非对称密钥加密 {#asymmetric-key-encryption}
非对称密钥加密(也称为公钥加密)使用密钥对。 一个密钥用于加密,另一个密钥用于解密。
解密密钥,或 *`private key`*,保密;加密密钥,或 *`public key`*,可供有权加密内容的任何用户使用。 有权访问公钥的任何人都可以加密内容。 但是,只有对私钥具有访问权限的用户才能解密内容。 无法从公钥重建私钥。
当您打包内容时,许可证服务器的公共密钥用于加密DRM元数据中的内容加密密钥(CEK)。 您必须确保只有许可证服务器才能访问许可证服务器的私钥。 如果其他人拥有密钥,则可以解密并查看内容。
>[!CAUTION]
>
>确保从可信来源获取包含公钥的许可证服务器证书。 这样,您就可以确保它是许可证服务器的密钥,而不是恶意公钥。 如果攻击者用他们的公钥替换许可证服务器的密钥,他们可以解密您的内容。
有关如何打包内容的更多信息,请参阅 [使用Adobe Primetime DRM SDK保护内容](https://helpx.adobe.com/content/dam/help/en/primetime/drm/drm_protecting_content.pdf).
|
from abc import ABC, abstractmethod
from datetime import datetime
from typing import List
from application.domain.entities.income import Income
class IncomeUseCase(ABC):
@abstractmethod
def create_income(self, timestamp: datetime, description: str, amount: float) -> Income:
"""Create a new income object and return the created income entity."""
pass
@abstractmethod
def get_incomes(self) -> List[Income]:
"""Retrieve all expenses and return the corresponding expense entities."""
pass
@abstractmethod
def get_income(self, income_id: str) -> Income:
"""Retrieve an expense by its ID and return the corresponding expense entity."""
pass
@abstractmethod
def update_income(self, income_id: str, timestamp: datetime, description: str, amount: float) -> Income:
"""Update an existing expense and return the updated expense entity."""
pass
@abstractmethod
def delete_income(self, income_id: str):
"""Delete an expense by its ID."""
pass
@abstractmethod
def delete_incomes(self):
"""Deletes all expenses."""
pass
|
/** @format */
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import {
MockedProvider,
InMemoryCache,
MockLink,
} from '@teamhub/apollo-config';
import { DepartmentProvider } from '../../components/departmentContext';
import { MuiThemeProvider } from '@material-ui/core/styles';
import theme from '../../utils/theme';
function TestContextProvider({ children, apolloProps = {}, routerProps = {} }) {
const cache = new InMemoryCache();
return (
<MockedProvider cache={cache} addTypename={true} {...apolloProps}>
<MuiThemeProvider theme={theme}>
<DepartmentProvider>
<MemoryRouter {...routerProps}>{children}</MemoryRouter>
</DepartmentProvider>
</MuiThemeProvider>
</MockedProvider>
);
}
export default function createProvider({
apolloProps = {},
routerProps = {},
} = {}) {
function TestContextProviderWrapper(props) {
return (
<TestContextProvider
apolloProps={apolloProps}
routerProps={routerProps}
{...props}
>
{props.children}
</TestContextProvider>
);
}
return TestContextProviderWrapper;
}
|
import { test, expect } from '@playwright/test'
import assertionManager from '../managers/assertionManager'
import LoginManager from '../managers/loginManager';
import { users, urls } from '../testdata/testdata'
import { HomePage } from '../pageobjects/HomePage'
import { LoginPage } from '../pageobjects/loginpage';
test.describe('Login/Logout Flow', () => {
let loginPage: LoginPage
let homePage: HomePage
let loginManager: LoginManager
test.beforeEach(async ({ page }) => {
loginPage = new LoginPage(page)
homePage = new HomePage(page)
loginManager = new LoginManager(loginPage, homePage);
await page.goto(urls.baseUrl)
})
test("Verify the user can Login with correct username and password", async ({ page }) => {
await loginManager.login(users.user.username, users.user.password, page);
await assertionManager.assertUserIsLoggedIn(loginPage.userMenu, homePage.myProfileButton)
})
test("Verify the user can Logout", async ({ page }) => {
await loginManager.login(users.user.username, users.user.password, page);
await loginManager.logout()
await expect(page).toHaveURL(urls.baseUrl + urls.index)
})
test("Verify the user cannot Login with incorrect password", async ({ page }) => {
await loginManager.login(users.wrongPass.username, users.wrongPass.password, page);
await assertionManager.assertElementContainsText(loginPage.errorMessage, loginPage.errorMessageText);
})
test("Verify the user cannot Login with incorrect user", async ({ page }) => {
await loginManager.login(users.wrongUser.username, users.wrongUser.password, page);
await assertionManager.assertElementContainsText(loginPage.errorMessage, loginPage.errorMessageText);
})
test("Verify the user cannot Login with incorrect user and password", async ({ page }) => {
await loginManager.login(users.wrong.username, users.wrong.password, page);
await assertionManager.assertElementContainsText(loginPage.errorMessage, loginPage.errorMessageText);
})
})
|
import 'package:flutter/material.dart';
class BudgetFilteringStatusWidget extends StatelessWidget {
final String title;
final Color? backgroundColor;
final Color? textColor;
final FontWeight? fontWeight;
const BudgetFilteringStatusWidget({
Key? key,
required this.title,
this.backgroundColor,
this.textColor,
this.fontWeight,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(
horizontal: 25,
vertical: 5,
),
margin: const EdgeInsets.only(right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: backgroundColor,
),
child: Text(
title,
style: TextStyle(
fontSize: 18,
fontFamily: 'Poppins',
color: textColor,
fontWeight: fontWeight,
),
),
);
}
}
|
<!--markdown syntax-->
# `My Readme Template`
### `Normal text & new line`
<P>Hey Lambo, I need you the most. <br>
Have to be a billionaire.</P>
---
### `Heading Style`
# Tech World
## Tech World2
### Tech World3
#### Tech World4
##### Tech World5
###### Tech World6
---
## `Text Style`
<p>It is my target to full fill it within 4 months to be a Web Developer</p>
_Italic_
**It is bold line**<br>
**hellow**
**LaMBORGHINI**
~~delete something~~
---
### `Inline or Multiple line code block`
`# Basic Website Element (HTML)`
```html
<html>
<head></head>
<title>Technology</title>
<body>
World
</body>
</html>
```
<br>
`# Basic Website Element (CSS)`
```css
head {
background-color: "indigo";
color: "yellow";
}
```
`# Basic Website Element (JavaScript)`
```javascript
console.log("Tech Legacy");
```
---
### `List Item`
### Order list
1. html
1.html5
2. css
2.css3
3. javascript
3.js
4. react
### Un order list
- Lambo
- Ferarry
- Ducati Panegali V4R
- Kawasaki
### task list
- [x] finished1
- [x] finished2
- [] not finish
---
### `Link`
Automatic Link
https://www.google.com
Disabled link
`https://www.twitter.com`
Markdown link syntax
[Facebook](https://www.facebook.com)
[Instagram](https://www.instagram.com)
[LinkedIn][url]
---
<!--Link info-->
[url]: https://www.linkedin.com
### `Image Syntax`
<!--  -->
<img src="https://r1.ilikewallpaper.net/ipad-wallpapers/download/2359/Lamborghini-Gallardo-ipad-wallpaper-ilikewallpaper_com.jpg" width="130rem" title="Lambo"/>
---
### `Emoji`
😊❤️
---
### `Table Syntax`
<!-- | Name | Information |
| ------- | ------------ |
| Gaffar | Self-learner |
| |
| Lambo | Most liked |
| ------- | --------- | -->
| Name | Information |
| ------------ | ------------ |
| Abdul Gaffar | Self-learner |
| |
| Lambo | Most liked |
| |
|
package jamule
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import jamule.ec.packet.PacketParserTest
import jamule.model.AmuleCategory
import jamule.model.DownloadCommand
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.testcontainers.containers.GenericContainer
import org.testcontainers.containers.output.Slf4jLogConsumer
import org.testcontainers.images.builder.ImageFromDockerfile
import org.testcontainers.images.builder.dockerfile.DockerfileBuilder
import kotlin.math.roundToLong
class AmuleClientTest : FunSpec({
val logger: Logger = LoggerFactory.getLogger(PacketParserTest::class.java)
val amule = GenericContainer(
ImageFromDockerfile()
.withDockerfileFromBuilder { builder: DockerfileBuilder ->
builder
.from("m4dfry/amule-adunanza")
.expose(4712)
.build()
})
.withExposedPorts(4712)
.withLogConsumer(Slf4jLogConsumer(logger))
val amuleClient = AmuleClient(amule.host, 4712, "amule", logger = logger)
test("should get server stats") {
amuleClient.getStats().isSuccess shouldBe true
}
test("should search for a file") {
amuleClient.searchAsync("test").isSuccess shouldBe true
}
test("should get search status") {
amuleClient.searchAsync("linux").isSuccess shouldBe true
amuleClient.searchStatus().isSuccess shouldBe true
}
test("should get search results") {
amuleClient.searchSync("linux").isSuccess shouldBe true
amuleClient.searchResults().isSuccess shouldBe true
}
test("should stop searches") {
amuleClient.searchAsync("linux").isSuccess shouldBe true
amuleClient.searchStop().isSuccess shouldBe true
}
test("should get download queue") {
val files = amuleClient.getDownloadQueue()
files.isSuccess shouldBe true
logger.info("Download queue: $files")
}
test("should get shared files list") {
val files = amuleClient.getSharedFiles()
files.isSuccess shouldBe true
logger.info("Shared files found ${files.getOrNull()!!.size}")
}
test("should create category") {
val category =
AmuleCategory((Math.random() * Int.MAX_VALUE).roundToLong(), "test", "/finished", "Some Comment", 1, 10)
val result = amuleClient.createCategory(category)
result.isSuccess shouldBe true
}
test("should get list of categories") {
val categories = amuleClient.getCategories().getOrThrow()
logger.info("Categories found ${categories.size}")
}
test("should download then pause then delete") {
val toDownload = amuleClient.searchSync("linux").getOrThrow().files.first()
amuleClient.downloadSearchResult(toDownload.hash).getOrThrow()
amuleClient.sendDownloadCommand(toDownload.hash, DownloadCommand.PAUSE).getOrThrow()
amuleClient.sendDownloadCommand(toDownload.hash, DownloadCommand.DELETE).getOrThrow()
}
})
|
#include "StringUtils.h"
#include "ProfilerCore.h"
namespace spt::lib
{
String StringUtils::ToHexString(const Byte* data, SizeType size)
{
SPT_PROFILER_FUNCTION();
static constexpr char dictionary[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
const SizeType stringSize = size * 2;
lib::String result;
result.reserve(stringSize);
for (SizeType i = 0; i < size; ++i)
{
const SizeType dictIdx1 = static_cast<SizeType>(data[i] & Byte(0x0f));
const SizeType dictIdx2 = static_cast<SizeType>((data[i] >> 4) & Byte(0x0f));
result += dictionary[dictIdx1];
result += dictionary[dictIdx2];
}
return result;
}
WString StringUtils::ToWideString(lib::StringView view)
{
SPT_PROFILER_FUNCTION();
WString wideString(view.size() + 1, L'\0'); // add 1 to create slot for '\0' character
SizeType converted = 0;
mbstowcs_s(&converted, wideString.data(), wideString.size(), view.data(), view.size());
return wideString;
}
String StringUtils::ToMultibyteString(lib::WStringView view)
{
String mutlibyteString(view.size() + 1, '\0');
SizeType converted = 0;
wcstombs_s(&converted, mutlibyteString.data(), mutlibyteString.size(), view.data(), view.size());
return mutlibyteString;
}
} // spt::lib
|
//
// MaximumFrequencyStack.swift
// SwiftChallenges
//
// Created by KyleLearnedThis on 6/28/22.
// https://leetcode.com/problems/maximum-frequency-stack/
import Foundation
class MaximumFrequencyStack {
var numFrequency: [Int:Int]
var stack: [Int]
init() {
numFrequency = [Int:Int]()
stack = [Int]()
}
func push(_ val: Int) {
let count = numFrequency[val, default: 0] + 1
numFrequency[val] = count
stack.append(val)
}
func push(_ input: [Int]) {
for i in input {
push(i)
}
}
func pop() -> Int {
let entries = numFrequency.sorted { $0.1 > $1.1 }
let maxFreq = entries[0].value
let maxEntries = entries.filter{ $0.value == maxFreq }
var cur = 0
if maxEntries.count > 1 {
let keys = maxEntries.map {$0.key}
cur = lastIntersection(array1: keys, array2: stack)
} else {
cur = entries[0].key
}
let entry = maxEntries.filter{$0.key == cur}.first!
let key = entry.key
let freq = entry.value
if freq == 1 {
numFrequency.removeValue(forKey: key)
} else if freq > 1 {
numFrequency[key] = freq - 1
}
let n = stack.count
for (i, value) in stack.reversed().enumerated() {
if value == cur {
stack.remove(at: n - i - 1)
break
}
}
return key
}
func lastIntersection(array1: [Int], array2: [Int]) -> Int {
let a = NSMutableOrderedSet(array: array1)
let b = NSMutableOrderedSet(array: array2)
b.intersect(a)
let result = b.lastObject as! Int
return result
}
func printAll() {
for num in stack {
print("\(num)", terminator: " ")
}
print()
}
func printFrequency() {
let entries = numFrequency.sorted { $0.1 > $1.1 }
for entry in entries {
let key = entry.key
let value = entry.value
print("[\(key) : \(value)]", terminator: " ")
}
print()
}
}
class MaximumFrequencyStackV2 {
private var numFreq: [Int: Int]
private var freqNums: [Int: [Int]]
private var maxFreq: Int
init() {
self.numFreq = [Int: Int]()
self.freqNums = [Int: [Int]]()
self.maxFreq = 0
}
func push(_ x: Int) {
let freq = numFreq[x, default: 0] + 1
numFreq[x] = freq
var array = freqNums[freq, default: [Int]()]
array.append(x)
maxFreq = max(maxFreq, freq)
}
func pop() -> Int {
let num = freqNums[maxFreq, default: [Int]()].removeLast()
numFreq[num, default: Int(0)] -= 1
if freqNums[maxFreq, default: [Int]()].isEmpty {
maxFreq -= 1
}
return num
}
}
|
import React from 'react';
import './generic-card.scss';
export interface GenericCardProps {
width: number;
height?: number;
backgroundImg?: string;
elements: JSX.Element[];
}
export function GenericCard({ width, height, backgroundImg, elements }: GenericCardProps) {
const cardStyle = {
backgroundImage: backgroundImg ? `url(${backgroundImg})` : undefined,
backgroundSize: 'cover',
backgroundPosition: 'center',
maxWidth: width,
height: height
};
return (
<div className="generic-card-content" style={cardStyle}>
{elements}
</div>
);
}
|
import { useContext } from "react";
import { CartContext } from "../context/CartContext";
import PropTypes from "prop-types";
const Product = ({ product }: any) => {
const { id, image, category, title, price } = product;
const { addToCart }: any = useContext(CartContext);
return (
<div className="border border-[#e4e4e4] h-[400px] p-5">
<div className="h-[300px]">
<div className="my-4 relative overflow-hidden group transition">
<div className="w-full h-full flex items-center">
<div className="w-[250px] mx-auto flex justify-center items-center">
<img className="max-h-[160px]" src={image} alt="" />
</div>
</div>
</div>
<div>
<h1 className="font-b font-semibold">{title}</h1>
<p>{category}</p>
</div>
</div>
<div className="py-2 flex justify-between items-end">
<p className="font-semibold">$ {price}</p>
<button
onClick={() => addToCart(product, id)}
className="bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border border-gray-400 rounded shadow"
>
Add To Cart
</button>
</div>
</div>
);
};
Product.propTypes = {
product: PropTypes.object,
};
export default Product;
|
import { FlattenSimpleInterpolation } from 'styled-components'
import styled, { css, DefaultTheme } from 'styled-components/native'
export type BoxVariants = 'danger' | 'primary' | 'secondary' | 'success'
type Props = {
variant?: BoxVariants
}
const getVariantStyles = (theme: DefaultTheme, variant: BoxVariants) => {
const variantStyles: Record<BoxVariants, FlattenSimpleInterpolation> = {
danger: css`
background-color: ${theme.colors['red-light']};
border-color: ${theme.colors['red-light']};
`,
primary: css`
background-color: ${theme.colors['gray-600']};
border-color: ${theme.colors['gray-600']};
`,
secondary: css`
border-color: ${theme.colors['gray-500']};
`,
success: css`
background-color: ${theme.colors['green-light']};
border-color: ${theme.colors['green-light']};
`,
}
return variantStyles[variant]
}
export const Container = styled.View<Props>`
${({ theme, variant = 'primary' }) => css`
padding: 16px;
border-radius: 8px;
border-width: 1px;
border-color: transparent;
${getVariantStyles(theme, variant)}
`}
`
|
// SyncObjectManager.h
// This class wil hold and manage the vulkan sync objects
#ifndef SyncObjectManagerIncluded
#define SyncObjectManagerIncluded
// File includes
#include "../../Includes//VulkanIncludes.h"
// Standard library includes
#include <vector>
namespace D3D
{
class SyncObjectManager final
{
public:
// Delete default constructor
SyncObjectManager() = delete;
// Constructor
// Parameters:
// device: handle of the VkDevice
// maxFrames: the maximum amount of frames in flight
SyncObjectManager(VkDevice device, uint32_t maxFrames);
// Default destructor
~SyncObjectManager() = default;
// Delete copy and move functions
SyncObjectManager(SyncObjectManager& other) = delete;
SyncObjectManager(SyncObjectManager&& other) = delete;
SyncObjectManager& operator=(SyncObjectManager& other) = delete;
SyncObjectManager& operator=(SyncObjectManager&& other) = delete;
// Clean up allocated objects
void Cleanup(VkDevice device);
// Get the requested image available semaphore
// Parameters:
// frame: current frame and index of the semaphore
VkSemaphore& GetImageAvailableSemaphore(uint32_t frame) { return m_ImageAvailableSemaphores[frame]; }
// Get the requested render finished semaphore
// Parameters:
// frame: current frame and index of the semaphore
VkSemaphore& GetRenderFinishedSemaphore(uint32_t frame) { return m_RenderFinishedSemaphores[frame]; }
// Get the requested in flight fence
// Parameters:
// frame: current frame and index of the fence
VkFence& GetInFlightFence(uint32_t frame) { return m_InFlightFences[frame]; }
private:
// Vector of image available semaphores
std::vector<VkSemaphore> m_ImageAvailableSemaphores{};
// Vector of render finished semaphores
std::vector<VkSemaphore> m_RenderFinishedSemaphores{};
// Vector of in flight fences
std::vector<VkFence> m_InFlightFences{};
// Initialize the sync objects
// Paramters:
// device: handle of the VkDevice
// maxFrames: the max amount of frames in fligh
void CreateSyncObjects(VkDevice device, uint32_t maxFrames);
};
}
#endif // !SyncObjectManagerIncluded
|
# mdnspp
Multicast DNS (mDNS) is a zero configuration service for resolving hostnames to IP addresses on (small) networks without a local name server.
This library is a cross-platform C++20 wrapper for the C library [mjansson/mdns](https://github.com/mjansson/mdns), which provides am implementation of the networking, serialization and deserialization of packets according to [RFC 6762](https://datatracker.ietf.org/doc/html/rfc6762) and [RFC 6763](https://datatracker.ietf.org/doc/html/rfc6763).
The use of [mjansson/mdns](https://github.com/mjansson/mdns) as implemented in _mdnspp_ is a C++ification of the examples in C provided with the original library, along with a simple logger/sink system so that printouts can be redirected or disabled entirely.
## Features
* **Services** \
Resolve hostname to ipv4 and ipv6 addresses, and provides text resources. (PTR, A, AAAA, SRV and TXT).
* **Service discovery**\
Zero configuration service discovery using mDNS.
* **Query**\
Send queries to resolve hostnames (A and AAAA) or for resources provided by specific services.
* **Observation**\
Continuous monitoring of mDNS traffic.
## Examples
Check `examples/` for a full description of how to use this wrapper library. To build them, pass `-DMDNSPP_BUILD_EXAMPLES=ON` to CMake.
### Service servers
Setting up a service requires a hostname (e.g. "audhumbla"), a service name (e.g. "_mdnspp-service._udp.local."), and any text (TXT) resources. TXT records can have a key and value, or just a key.
```cpp
mdnspp::service_server s("audhumbla", "_mdnspp-service._udp.local.");
s.serve({
{"Odin", std::nullopt},
{"Thor", "Balder"}
}
);
```
### Service discovery
The following will print the discovered services to stdout,
```cpp
mdnspp::service_discovery d;
d.discover();
```
which can produce the following.
```txt
[debug] Local IPv4 address: 192.168.1.169
[debug] Local IPv6 address: fd94:d3e2:96a1:40ee:fd2b:443d:311d:2542
[debug] Opened 2 client sockets
[info] 192.168.1.169:5353: ANSWER PTR _services._dns-sd._udp.local._mdnspp-service._udp.local. rclass 0x1 ttl 10 length 23
[info] [fe80::6bc8:6f04:b59c:b2ad%enp4s0]:5353: ANSWER PTR _services._dns-sd._udp.local._mdnspp-service._udp.local. rclass 0x1 ttl 10 length 23
[info] [fe80::10d5:beaf:7d72:6ebf%enp4s0]:5353: ANSWER PTR _services._dns-sd._udp.local._airplay._tcp.local. rclass 0x1 ttl 10 length 11
[info] 192.168.1.73:5353: ANSWER PTR _services._dns-sd._udp.local._airplay._tcp.local. rclass 0x1 ttl 10 length 11
[debug] Closed 2 sockets
```
Instead of printing any received record to stdout, a callback can be provided and each record type can be handled individually (or discarded if not relevant).
```cpp
mdnspp::service_discovery d(
[](std::unique_ptr<mdnspp::record_t> record)
{
if(record->rtype == MDNS_RECORDTYPE_SRV)
std::cout << mdnspp::record_as<mdnspp::record_srv_t>(*record);
}
);
d.discover();
```
### Queries
Queries can be used to resolve specific hostnames ("audhumbla.local.") to ipv4 or ipv6 addresses without using discovery, or to retrieve service pointers.
```cpp
mdnspp::querier d;
d.inquire(
{
"audhumbla.local.",
MDNS_RECORDTYPE_A
});
```
The above produces the following output when the service example is running.
```txt
[debug] Local IPv4 address: 192.168.1.169
[debug] Local IPv6 address: fd94:d3e2:96a1:40ee:fd2b:443d:311d:2542
[debug] Opened 2 client sockets
[debug] Query audhumbla.local. for A records
[debug] Listening for mDNS query responses
[info] 192.168.1.169:5353: ANSWER A audhumbla.local.192.168.1.169 rclass 0x1 ttl 10 length 4
[info] 192.168.1.169:5353: ADDITIONAL AAAA audhumbla.local.fd94:d3e2:96a1:40ee:fd2b:443d:311d:2542 rclass 0x1 ttl 10 length 16
[info] 192.168.1.169:5353: ADDITIONAL TXT Odin rclass 0x1 ttl 10 length 18
[info] 192.168.1.169:5353: ADDITIONAL TXT Thor=Balder rclass 0x1 ttl 10 length 18
[info] [fe80::6bc8:6f04:b59c:b2ad%enp4s0]:5353: ANSWER A audhumbla.local.192.168.1.169 rclass 0x1 ttl 10 length 4
[info] [fe80::6bc8:6f04:b59c:b2ad%enp4s0]:5353: ADDITIONAL AAAA audhumbla.local.fd94:d3e2:96a1:40ee:fd2b:443d:311d:2542 rclass 0x1 ttl 10 length 16
[info] [fe80::6bc8:6f04:b59c:b2ad%enp4s0]:5353: ADDITIONAL TXT Odin rclass 0x1 ttl 10 length 18
[info] [fe80::6bc8:6f04:b59c:b2ad%enp4s0]:5353: ADDITIONAL TXT Thor=Balder rclass 0x1 ttl 10 length 18
[debug] Closed 2 sockets
```
### Logging
Implement a custom log sink to handle log messages if prints to stdout is not desired.
```cpp
class example_sink : public mdnspp::log_sink
{
public:
~example_sink() override = default;
void log(log_level level, const std::string &string) noexcept override
{
// print to stdout and omit the log level.
std::cout << string << std::endl;
}
};
mdnspp::querier d(std::make_shared<example_sink>());
d.inquire(
{
"audhumbla._mdnspp-service._udp.local.",
MDNS_RECORDTYPE_TXT
});
```
```txt
Local IPv4 address: 192.168.1.169
Local IPv6 address: fd94:d3e2:96a1:40ee:fd2b:443d:311d:2542
Opened 2 client sockets
Query audhumbla._mdnspp-service._udp.local. for TXT records
Listening for mDNS query responses
192.168.1.169:5353: ANSWER TXT Odin rclass 0x1 ttl 10 length 18
192.168.1.169:5353: ANSWER TXT Thor=Balder rclass 0x1 ttl 10 length 18
[fe80::6bc8:6f04:b59c:b2ad%enp4s0]:5353: ANSWER TXT Odin rclass 0x1 ttl 10 length 18
[fe80::6bc8:6f04:b59c:b2ad%enp4s0]:5353: ANSWER TXT Thor=Balder rclass 0x1 ttl 10 length 18
Closed 2 sockets
```
### Sending log messages from custom types
If deriving a class from `mdns_base`, log messages can be sent with various log levels as shown below. These methods return a logger instance which builds the log message string using streams, and `log_sink::log()` is invoked when the logger instance is destroyed.
```cpp
trace() << "This is a trace message";
{
auto debug_logger = debug();
debug_logger << "This is the first part of the message. ";
if(some_condition)
debug_logger << "some_condition was true. ";
else
debug_logger << "some_condition was false. ";
debug_logger << "This is the last part of the message. This scope exits now, and the logger is destroyed.";
}
```
## Limitations
These limitations are related to _mdnspp_ and not the original C library.
While the original C library provides an implementation according to the RFC's, users of the library must utilize it correctly.
Specifically, mDNS requests must be handled and responded to correctly, and records must be constructed correctly.
There could be bugs related to the construction of records and responses performed by this library, which has not been extensively tested against 3rd party implementations.
For example, there has been no systematic testing against Avahi or Apple's Bonjour, however, 3rd party services are discovered on the network (such as Apple devices).
The test coverage of this library is currently NIL.
Lastly, related to `service_server`
* A and AAAA records are only made for the first adapter encountered in each family (ipv4 and ipv6). This will be fixed.
* Services automatically serve A and AAAA records on the first network interface in each family, and does not facilitate to specify individual interfaces to use (or not use).
|
import BackgroundAnimation from "@/components/Background";
import Projects from "@/components/Projects";
import { motion } from "framer-motion";
import Image from "next/image";
import { TypeAnimation } from 'react-type-animation';
import React from "react";
import HomeStyles from "@/styles/Home.module.css";
import Footer from "@/components/Footer";
export default function Home() {
return (
<>
<motion.div
className={HomeStyles.home}
exit="exit"
variants={{
exit: {
y: "100vw",
transition: { ease: "easeInOut" },
},
}}
>
<div className={HomeStyles.photo}>
<Image
alt={"A large laptop with a girl sitting on it with her own laptop on her legs. "}
src={"/computer.png"}
width={400}
height={400}
style={{
float: "right",
opacity: 0.8
}}
/>
</div>
<div className={HomeStyles.introtext}>
<motion.h1
animate={{ scale: 1, opacity: 1, y: "0" }}
transition={{
delay: 0.25,
duration: 0.75,
type: "spring",
stiffness: 190,
}}
initial={{ scale: 0, opacity: 0, y: "-100vh" }}
>
Sarah Gerrard
<TypeAnimation
sequence={['Full-Stack Software Developer', 1000, 'Freelancer', 1000, 'Tech Aficionado', 1000]}
style={{
fontSize: '.4em' }}
repeat={Infinity}
/>
</motion.h1>
<motion.p
animate={{ scale: 1, opacity: 1 }}
transition={{ delay: 0.5, duration: 0.75 }}
initial={{ scale: 0, opacity: 0 }}
>
Utilizing my skills in both front and back-end development to create and implement web applications that are both functional and visually appealing.
</motion.p>
</div>
<BackgroundAnimation />
</motion.div>
<Projects />
<Footer />
</>
)
}
|
import dash
from dash import dcc, html
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
import numpy as np
# 2 - Data loading and app creation
#BS = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
BS = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
# good options: JOURNAL, SIMPLEX,
app = dash.Dash(__name__, use_pages=True, external_stylesheets=[dbc.themes.SIMPLEX, dbc.icons.FONT_AWESOME], suppress_callback_exceptions=True)
# 3 - Creating the HTML sections with their components (dcc)
iconos = ["fa-solid fa-upload", "fa-solid fa-minimize", "fa-sharp fa-solid fa-chart-line", "fa-regular fa-face-smile"]
navbar = dbc.NavbarSimple(
[
dbc.Row(
[
dbc.Col(html.I(className=iconos[i]), width=2), # valores ajustados manualmente para que quede bien
dbc.Col(dbc.NavLink(page["name"], href=page["path"]), width=1)
],
align="center",
)
for i, page in enumerate(dash.page_registry.values())
if page["module"] != "pages.not_found_404"
],
brand="Dataset Inspector",
color="primary",
dark=True,
className="mb-2",
)
app.layout = html.Div([
navbar,
dash.page_container,
dcc.Store(id='store', data={})])
if __name__ == '__main__':
app.run_server(debug=True)
|
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Swipe between maps</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.css' rel='stylesheet' />
<!-- JS and CSS for the swipe plugin -->
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.css' type='text/css' />
<style>
body { margin:0; padding:0;overflow: hidden;}
body * {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.mapboxgl-popup-content {
background-color: black;
color: white;
}
</style>
</head>
<body>
<div id="comparison-container">
<div id='owners' class='map'></div> <!-- div for owners map div -->
<div id='renters' class='map'></div> <!-- div for renters map div -->
</div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiY2FsZWJ5YW5ueSIsImEiOiJjbGg5ZjZ1YTEwNm9xM25vYXlmcTZocjVyIn0.VNdWm9VuMV5xPkG8Jlmf-w';
var ownerMap = new mapboxgl.Map({
container: 'owners', // owners map div
style: 'mapbox://styles/mapbox/dark-v10', // Mapbox dark style
center: [-122.6784,45.5152],
zoom: 10
});
ownerMap.on('load', function() {
// the rest of the owner data code will go in here
ownerMap.addLayer({
id: 'Owner Data',
type: "fill",
source: {
type: 'vector',
url: 'mapbox://calebyanny.6cg3yny2' //input your tileset ID url e.g. 'mapbox://jomerson.6ykhlovc'
},
'source-layer': 'Owner-Renter-Pop-c1tkhp', //input your source layer name e.g. 'Owner-Renter-Pop-ca08iw'
paint: {
'fill-color':
["step",
["get", "Own"],
"hsl(360, 100%, 97%)",
17.0,
"hsl(303, 47%, 82%)",
22.0,
"hsl(302, 57%, 63%)",
27.0,
"hsl(310, 60%, 45%)",
32.0,
"hsl(310, 90%, 32%)"],
"fill-opacity": 0.7
}
});
});
var renterMap = new mapboxgl.Map({
container: 'renters', // owners map div
style: 'mapbox://styles/mapbox/dark-v10', // Mapbox light style so we can observe the swipe
center: [-122.6784,45.5152],// Use the same center as your other map so that they are perfectly aligned
zoom: 10
});
renterMap.on('load', function() {
renterMap.addLayer({
id: 'Renter Data',
type: "fill",
source: {
type: 'vector',
url: 'mapbox://calebyanny.6cg3yny2' //input your tileset ID URL
},
'source-layer': 'Owner-Renter-Pop-c1tkhp', //input your source layer name e.g. Owner-Renter-Pop-dr7310
paint: {
'fill-color':
["step",
["get", "Rent"],
"hsl(360, 100%, 97%)",
17.0,
"hsl(303, 47%, 82%)",
22.0,
"hsl(302, 57%, 63%)",
27.0,
"hsl(310, 60%, 45%)",
32.0,
"hsl(310, 90%, 32%)"],
"fill-opacity": 0.7 ,
}
}); });
//POPUPS
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
renterMap.on('mousemove', 'Renter Data', function (e) {
// Change the cursor style as a UI indicator.
renterMap.getCanvas().style.cursor = 'crosshair';
var coordinates = e.lngLat;
var description = e.features[0].properties.Rent;
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(coordinates)
.setHTML("Renters: " + description + "%")
.addTo(renterMap);
});
renterMap.on('mouseleave', 'Renter Data', function () {
renterMap.getCanvas().style.cursor = '';
popup.remove();
});
ownerMap.on('mousemove', 'Owner Data', function (e) {
// Change the cursor style as a UI indicator.
ownerMap.getCanvas().style.cursor = 'crosshair';
var coordinates = e.lngLat;
var description = e.features[0].properties.Own;
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(coordinates)
.setHTML(" Owners: " + description + "%")
.addTo(ownerMap);
});
ownerMap.on('mouseleave', 'Owner Data', function () {
ownerMap.getCanvas().style.cursor = '';
popup.remove();
});
// A selector or reference to HTML element
var container = '#comparison-container';
var map = new mapboxgl.Compare(ownerMap, renterMap, container, {
})
</script>
</body>
</html>
|
/*
Problem Statement -
There are n children who want to go to a Ferris wheel, and your task is to find a gondola for each child.
Each gondola may have one or two children in it, and in addition, the total weight in a gondola may not exceed x. You know the weight of every child.
What is the minimum number of gondolas needed for the children?
Input
The first input line contains two integers n and x: the number of children and the maximum allowed weight.
The next line contains n integers p_1,p_2,...,p_n: the weight of each child.
Output
Print one integer: the minimum number of gondolas.
Constraints
1 <= n \<= 2.10^5
1 \<= x \<= 10^9
1 \<= p_i \<= x
*/
#include <bits/stdc++.h>
#define wl ll t;cin>>t;while(t--)
#define endl "\n"
#define ll long long int
#define ld long double
#define ull unsigned long long
#define li long int
#define ul unsigned long int
#define fast std::ios::sync_with_stdio(false); cin.tie(NULL);
const ll mod = 1e9 + 7;
const ll N = 1e6 + 5;
using namespace std;
void solve(){
int n, x;
cin>>n>>x;
vector<int> child(n);
for(int i = 0; i < n; i++){
cin>>child[i];
}
sort(begin(child), end(child));
int ans = 0;
int left = 0, right = n-1;
while(left <= right){
if(left != right){
if(child[left] + child[right] > x){
right --;
}
else{
left++;
right--;
}
ans++;
}
else{
ans ++;
left++;
right--;
}
}
cout<<ans;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
fast
solve();
return 0;
}
|
package e2_Directed_DFS;
//@author - Eleanor Ezimah
import e1_Digraph.Digraph;
import external_package.Bag;
import external_package.In;
import external_package.StdOut;
public class DirectedDFS {
private boolean[] marked; // marked[v] = true iff v is reachable from source(s)
private int count; // number of vertices reachable from source(s)
public DirectedDFS(Digraph G, int s) {
marked = new boolean[G.V()];
validateVertex(s);
dfs(G, s);
}
public DirectedDFS(Digraph G, Iterable<Integer> sources) {
marked = new boolean[G.V()];
validateVertices(sources);
for (int v : sources) {
if (!marked[v]) dfs(G, v);
}
}
private void dfs(Digraph G, int v) {
count++;
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) dfs(G, w);
}
}
public boolean marked(int v) {
validateVertex(v);
return marked[v];
}
public int count() {
return count;
}
// throw an IllegalArgumentException unless {@code 0 <= v < V}
private void validateVertex(int v) {
int V = marked.length;
if (v < 0 || v >= V)
throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
}
// throw an IllegalArgumentException unless {@code 0 <= v < V}
private void validateVertices(Iterable<Integer> vertices) {
if (vertices == null) {
throw new IllegalArgumentException("argument is null");
}
int V = marked.length;
for (int v : vertices) {
if (v < 0 || v >= V) {
throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
}
}
}
public static void main(String[] args) {
// read in digraph from command-line argument
In in = new In(args[0]);
Digraph G = new Digraph(in);
// read in sources from command-line arguments
Bag<Integer> sources = new Bag<Integer>();
for (int i = 1; i < args.length; i++) {
int s = Integer.parseInt(args[i]);
sources.add(s);
}
// multiple-source reachability
DirectedDFS dfs = new DirectedDFS(G, sources);
// print out vertices reachable from sources
for (int v = 0; v < G.V(); v++) {
if (dfs.marked(v)) StdOut.print(v + " ");
}
StdOut.println();
}
}
|
import css from "@styles/chat/navbar/glowMenu.module.css";
import { Dispatch, FC, SetStateAction } from "react";
export type OptionsGlowMenu = Array<{
name: string;
action: () => void;
}>;
type GlowMenuType = {
style: string;
options: OptionsGlowMenu;
view: Dispatch<SetStateAction<boolean>>;
};
export const GlowMenu: FC<GlowMenuType> = ({ style, options, view }) => {
return (
<>
<div onClick={() => view((prev) => !prev)} className={`${css.background}`} />
<section className={`${style} ${css.view}`}>
{options.map((select) => {
return (
<button key={select.name} onClick={select.action}>
{select.name}
</button>
);
})}
</section>
</>
);
};
|
#pragma once
#ifndef UTILS_STRING_HELPER_H_
#define UTILS_STRING_HELPER_H_
#include <cstdarg>
#include <iostream>
#include <map>
#include <string>
#include <sstream>
#include <unordered_map>
#include <vector>
using std::map;
using std::string;
using std::unordered_map;
using std::vector;
using std::ostringstream;
namespace simple {
class String {
public:
static String Digits;
static String CapitalLetters;
static String SmallLetters;
static String Letters;
static String Normal;
static String Printable;
static String WhiteSpace;
static String Random(size_t length, const String& chars);
static String Random(size_t length);
String();
String(size_t size);
String(const char* str);
String(const char* str, size_t length);
String(const string& str);
String(const String& str);
String& Vsnprintf(size_t size, const char* fmt, va_list args);
String& Snprintf(size_t size, const char* fmt, ...);
String& Sprintf(const char* fmt, ...);
String& Format(size_t size, const char* fmt, ...);
String& Format(const char* fmt, ...);
String& Assign(const char* str);
String& Assign(const string& str);
String& Assign(const String& str);
String& Append(const char* str);
String& Append(const string& str);
String& Append(const String& str);
template<class _ElementType>
String Join(const vector<_ElementType>& values) const {
if (values.empty())
return String();
ostringstream oss;
bool first_element = true;
for (auto& it : values) {
if (first_element) {
first_element = false;
} else {
oss << value_;
}
oss << it;
}
return String(oss.str());
}
template<class _Map>
String Join(const _Map& values, const string& assign_key) const {
if (values.empty())
return String();
std::ostringstream oss;
auto it = values.begin();
for (;;) {
oss << it->first << assign_key << it->second;
if (++it == values.end())
break;
oss << value_;
}
return String(oss.str());
}
String Center(size_t length, char fill = ' ') const;
String StripLeft(const String& chars) const;
String StripLeft() const;
String StripRight(const String& chars) const;
String StripRight() const;
String Strip(const String& chars) const;
String Strip() const;
String SubStr(int start, int end = -1) const;
String RemovePrefix(const String& str) const;
String RemoveSuffix(const String& str) const;
String Replace(const String& old, const String& str) const;
vector<String> Split(const String& sep, size_t maxsplit = -1) const;
unordered_map<String, String> Split(const String& sep, const string& assign_key) const;
String CamelToUnderscore() const;
String UnderscoreToCamel(bool little = true) const;
String Translate(const unordered_map<char, char>& table) const;
String ToUpper() const;
String ToLower() const;
bool IsDigit() const;
bool StartsWith(const String& prefix) const;
bool EndsWith(const String& suffix) const;
int Find(const String& sub) const;
int ToInt() const;
int64_t ToInt64() const;
String& resize(size_t new_size, const char fill = (char)0);
char& operator[](int index);
char operator[](int index) const;
string str() const;
char const * c_str() const;
size_t length() const;
size_t size() const;
operator int() const;
operator char const* () const;
operator string const& () const;
String& operator=(const char* str);
String& operator=(const string& str);
String& operator=(const String& str);
String& operator+=(const char* str);
String& operator+=(const string& str);
String& operator+=(const String& str);
friend bool operator<(const char* left, const String& right);
friend bool operator<(const String& left, const char* right);
friend bool operator<(const string& left, const String& right);
friend bool operator<(const String& left, const string& right);
friend bool operator<(const String& left, const String& right);
friend bool operator==(const char* left, const String& right);
friend bool operator==(const String& left, const char* right);
friend bool operator==(const string& left, const String& right);
friend bool operator==(const String& left, const string& right);
friend bool operator==(const String& left, const String& right);
friend bool operator>(const char* left, const String& right);
friend bool operator>(const String& left, const char* right);
friend bool operator>(const string& left, const String& right);
friend bool operator>(const String& left, const string& right);
friend bool operator>(const String& left, const String& right);
friend bool operator!=(const char* left, const String& right);
friend bool operator!=(const String& left, const char* right);
friend bool operator!=(const string& left, const String& right);
friend bool operator!=(const String& left, const string& right);
friend bool operator!=(const String& left, const String& right);
friend bool operator<=(const char* left, const String& right);
friend bool operator<=(const String& left, const char* right);
friend bool operator<=(const string& left, const String& right);
friend bool operator<=(const String& left, const string& right);
friend bool operator<=(const String& left, const String& right);
friend bool operator>=(const char* left, const String& right);
friend bool operator>=(const String& left, const char* right);
friend bool operator>=(const string& left, const String& right);
friend bool operator>=(const String& left, const string& right);
friend bool operator>=(const String& left, const String& right);
friend std::ostream& operator<<(std::ostream& stream, const String& str);
private:
string value_;
};
String operator+(String left, const char* right);
String operator+(String left, const string& right);
String operator+(String left, const String& right);
String operator+(const char* left, const String& right);
String operator+(const string& left, const String& right);
} // namespace simple
template<>
struct std::hash<simple::String> {
std::size_t operator()(const simple::String& s) const noexcept {
return std::hash<std::string>{}(s.str());
}
};
#endif // UTILS_STRING_HELPER_H_
|
/*
Given a search criteria object whose values will only be
primitives (ints, strings, booleans) and a list of objects.
return any object that matches all the key value pairs in the search
criteria object.
Bonus: write a 2nd solution using build in methods to practice functional
programming.
*/
const users = [
{ firstName: "Bob", lastName: "Bobbert", age: 31 },
{ firstName: "John", lastName: "Smith", age: 25 },
{ firstName: "Bob", lastName: "Smith", age: 27 },
{ firstName: "Bob", lastName: "White", age: 31 },
];
const searchCriteria1 = {
firstName: "Bob",
age: 31,
};
// const expected1 = [
// { firstName: "Bob", lastName: "Bobbert", age: 31 },
// { firstName: "Bob", lastName: "White", age: 31 },
// ];
const searchCriteria2 = {
lastName: "Smith",
};
// const expected2 = [
// { firstName: "John", lastName: "Smith", age: 25 },
// { firstName: "Bob", lastName: "Smith", age: 27 },
// ];
//function will find objects that match criteria
function findObjects(criteria, collection) {
let result = [];
//step 1: iterate through all the objects in collection
for (const objects of collection) {
let match = true;
//another loop for each key in the criteria
for (const key in criteria) {
//i'd say use hasOwn
if (Object.hasOwn(criteria, key) && objects[key] !== criteria[key]) {
match = false;
break; //lol
}
}
if (match) {
result.push(objects);
}
}
return result;
}
const functionalFindObjects = (criteria, collection) =>
collection.filter((item) =>
Object.keys(criteria).every((key) => item[key] === criteria[key])
);
/*
Given an id, an object that has keys with corresponding updated values, and an array of objects
Find the object by "id" key that matches the given id value and then update that object's
keys with the provided new values.
Return the updated object, or null if no object was found
*/
const students = [
{
id: 1,
name: "student1",
isLateToday: false,
lateCount: 15,
redBeltStatus: false,
},
{
id: 2,
name: "student2",
isLateToday: false,
lateCount: 1,
redBeltStatus: false,
},
{
id: 3,
name: "student3",
isLateToday: false,
lateCount: 0,
redBeltStatus: false,
},
];
const id1 = 3;
const updateData1 = { redBeltStatus: true, isLateToday: true };
/*const expected1 = {
id: 3,
name: "student3",
isLateToday: true,
lateCount: 0,
redBeltStatus: true,
};
*/
const id2 = 1;
const updateData2 = {
isLateToday: true,
lateCount: 16,
randomKey: "randomValue",
};
/*const expected2 = {
id: 1,
name: "student1",
isLateToday: true,
lateCount: 16,
redBeltStatus: false,
};
*/
/*
Explanation: In this implementation
randomKey was not added because it is not an existing key that can be updated
*/
const id3 = 5;
const updateData3 = {};
const expected3 = null;
function findByIdAndUpdate(id, updatedVals, collection) {
for (const eachItem of collection) {
if (eachItem.id == id) {
for (const key in updatedVals) {
if (eachItem.hasOwnProperty(key)) {
const value = updatedVals[key];
eachItem[key] = value;
}
}
return eachItem;
}
}
return null;
}
|
// import React from "react";
// import "../../../styles/product-card.css";
// import { Link } from "react-router-dom";
// import { useDispatch } from "react-redux";
// import { cartActions } from "../../../store/shopping-cart/cartSlice";
// const ProductCard = (props) => {
// const { id, title, image01, price } = props.item;
// const dispatch = useDispatch();
// const addToCart = () => {
// dispatch(
// cartActions.addItem({
// id,
// title,
// image01,
// price,
// })
// );
// };
// return (
// <div className="product__item">
// <div className="product__img">
// <img src={image01} alt="product-img" className="w-50" />
// </div>
// <div className="product__content">
// <h5>
// <Link to={`/foods/${id}`}>{title}</Link>
// </h5>
// <div className=" d-flex align-items-center justify-content-between ">
// <span className="product__price">${price}</span>
// <button className="addTOCart__btn" onClick={addToCart}>
// Add to Cart
// </button>
// </div>
// </div>
// </div>
// );
// };
// export default ProductCard;
import React, {useRef} from "react";
import "../../../styles/product-card.css";
import { Link } from "react-router-dom";
import { useDispatch } from "react-redux";
import { cartActions } from "../../../store/shopping-cart/cartSlice";
// import {
// setMenuList
// } from '../../../store/shopping-cart/menuStore';
import axios from "axios";
import { getJWT } from "../../../service/authService";
import { useNavigate } from "react-router-dom";
import { setRestaurantId } from '../../../store/shopping-cart/restaurantStore';
import ApiConstants from "../../../constants/apiConstants";
import { Toast } from 'primereact/toast';
const ProductCard = (props) => {
const { Id, Name, ImageURL } = props.item;
const toast = useRef(null);
const dispatch = useDispatch();
const apiConstants = new ApiConstants();
// "Id": 1,
// "Name": "Time Traveller",
// "City": "Bengaluru",
// "ImageURL": "https://media-cdn.tripadvisor.com/media/photo-l/14/96/fa/14/restaurant.jpg",
// "Email": "[email protected]",
// "Is_Closed": false,
// "Rating": "5.0",
// "createdAt": "2022-12-17T08:13:08.000Z",
// "updatedAt": "2022-12-17T08:13:08.000Z"
// }
// const addToCart = () => {
// dispatch(
// cartActions.addItem({
// id,
// title,
// image01,
// price,
// })
// );
// };
const navigate = useNavigate();
const getMenuList = () => {
console.log('IDvalue', Id);
dispatch(setRestaurantId(Id));
axios.get(apiConstants.SERVERLESS_OFFLINE+'/allmenuItems', {
params: {
restaurantId: Id,
},
headers: { "Authorization": `Bearer ${getJWT()}` } }).then((response) => {
console.log('response', response.data);
dispatch(cartActions.setMenuList(response.data));
navigate('/foods');
}).catch((e) => {
console.log('error getting the values', e);
toast.current.show({
severity: 'error',
summary: 'Something went wrong while getting all menuItems',
detail: e.response.data.message,
});
});
}
return (
<div className="product__item">
<div className="product__img">
<img src={ImageURL} alt="product-img" className="w-50" />
</div>
<div className="product__content">
<h5>
{ Name}
<button className="addTOCart__btn" onClick={getMenuList}>
Menu Items
</button>
{/* <Link to={`/foods/${Id}`}>{Name}</Link> */}
</h5>
{/* <div className=" d-flex align-items-center justify-content-between "> */}
{/* <span className="product__price">${price}</span> */}
{/* <button className="addTOCart__btn" onClick={addToCart}>
Add to Cart
</button> */}
{/* </div> */}
</div>
<Toast ref={toast}></Toast>
</div>
);
};
export default ProductCard;
|
export interface Movie {
adult: boolean
backdrop_path: string | null
belongs_to_collection: {} | null
budget: number
credits: MovieCredits
genres: MovieGenres[]
homepage: string | null
id: number
imdb_id: string | null
original_language: string
original_title: string
overview: string | null
popularity: number
poster_path: string | null
production_companies: MovieProductionCompanies[]
production_countries: MovieProductionCountries[]
release_date: string
revenue: string
runtime: string
spoken_languages: MovieSpokenLanguages[]
status: string
tagline: string | null
title: string
video: boolean
videos: {
results: MovieVideos[]
}
vote_average: number
vote_count: number
}
interface MovieCredits {
cast: MovieCast[]
crew: MovieCrew[]
}
interface MovieCast {
adult: boolean
cast_id: number
character: string
credit_id: string
gender: number
id: number
known_for_department: string
name: string
order: number
original_name: string
popularity: number
profile_path: string
}
interface MovieCrew {
adult: boolean
credit_id: number
department: string
gender: number
id: number
job: string
known_for_department: string
name: string
original_name: string
popularity: number
profile_path: string
}
interface MovieGenres {
id: number
name: string
}
interface MovieProductionCompanies {
name: string
id: number
logo_path: string | null
origin_country: string
}
interface MovieProductionCountries {
iso_3166_1: string
name: string
}
interface MovieSpokenLanguages {
iso_639_1: string
name: string
}
export interface MovieVideos {
id: string
iso_639_1: string
iso_3166_1: string
key: string
name: string
official: boolean
published_at: string
site: string
size: number
type: string
}
|
const redux = require('redux');
const counterReducer = (state = { counter: 0 }, action) => {
if (action.type === 'increment') {
return {
counter: state.counter + 1,
};
}
if (action.type === 'decrement') {
return {
counter: state.counter - 1,
};
}
return state;
};
const store = redux.createStore(counterReducer);
const counterSubscriber = () => {
const latestState = store.getState(); // 업데이트된 후의 최신상태 스냅샷 제공.
console.log(latestState);
};
// 리덕스가 구독함수를 인식하도록하고 상태 변경이 있을 때마다 구독함수를 실행하도록 한다.
store.subscribe(counterSubscriber);
// 액션 발송(상태 변경)
store.dispatch({ type: 'increment' });
store.dispatch({ type: 'decrement' });
|
import {
AllowNull,
AutoIncrement,
Column,
NotEmpty,
PrimaryKey,
Table,
Model
} from "sequelize-typescript";
import { DataTypes } from "sequelize";
@Table({
tableName: "patients",
timestamps: true,
})
export default class Patient extends Model {
@AutoIncrement
@PrimaryKey
@Column(DataTypes.INTEGER)
id?: number;
@AllowNull(false)
@NotEmpty
@Column(DataTypes.STRING)
first_name!: string;
@AllowNull(false)
@NotEmpty
@Column(DataTypes.STRING)
last_name!: string;
@AllowNull(false)
@NotEmpty
@Column(DataTypes.STRING)
mobile_number!: string;
@AllowNull(false)
@NotEmpty
@Column(DataTypes.STRING)
email!: string;
@AllowNull(false)
@NotEmpty
@Column(DataTypes.STRING)
password!: string;
@Column(DataTypes.STRING)
image?: string;
}
|
import { useCallback, useState } from "react";
import { addTodo } from "../../../../store/todos/actions";
import { v4 as uuidv4} from "uuid";
export default function AddTodo() {
const todoId =uuidv4();
const [todo, setTodo] = useState({
id: "",
text: "",
});
const handleChange = (e) => {
setTodo({
id: todoId,
text: e.target.value,
});
};
const handleSubmit = useCallback((e) => {
e.preventDefault();
if (todo.text === "") {
return alert("boş veri girme");
}
addTodo(todo);
setTodo({
id: "",
text: ""
});
},
[todo]
);
return (
<form onSubmit={handleSubmit} className="w-[90%] flex items-center justify-center">
<input type="text" onChange={handleChange} value={todo.text} className="w-[80%] h-[3rem] px-4 py-2 bg-transparent outline-none border-2 border-bg-pokemon-card rounded-l-3xl border-r-0 text-white"/>
<button className="border-2 border-bg-pokemon-card h-[3rem] px-4 py-2 font-bold text-white border-l-0 rounded-r-3xl relative hover:bg-bg-navbar transition-colors duration-300" type="submit">Submit</button>
</form>
);
}
|
/*
Freeware License, some rights reserved
Copyright (c) 2023 Iuliana Cosmina
Permission is hereby granted, free of charge, to anyone obtaining a copy
of this software and associated documentation files (the "Software"),
to work with the Software within the limits of freeware distribution and fair use.
This includes the rights to use, copy, and modify the Software for personal use.
Users are also allowed and encouraged to submit corrections and modifications
to the Software for the benefit of other users.
It is not allowed to reuse, modify, or redistribute the Software for
commercial use in any way, or for a user's educational materials such as books
or blog articles without prior permission from the copyright holder.
The above copyright notice and this permission notice need to be included
in all copies or substantial portions of the software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.apress.prospring6.six.repo
import com.apress.prospring6.six.plain.records.Singer
import com.apress.prospring6.six.repo.JdbcRepoTest.EmptyEmbeddedJdbcConfig
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType
import org.springframework.test.context.jdbc.Sql
import org.springframework.test.context.jdbc.SqlConfig
import org.springframework.test.context.jdbc.SqlGroup
import org.springframework.test.context.jdbc.SqlMergeMode
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig
import java.util.function.Consumer
import javax.sql.DataSource
/**
* Created by iuliana.cosmina on 13/05/2022
*/
@SqlMergeMode(SqlMergeMode.MergeMode.MERGE)
@Sql("classpath:h2/drop-schema.sql", "classpath:h2/create-schema.sql")
@SpringJUnitConfig(classes = [EmptyEmbeddedJdbcConfig::class, SingerJdbcRepo::class])
class JdbcRepoTest {
@Autowired
var singerRepo: SingerRepo? = null
@Test
@DisplayName("should return all singers")
@Sql(
value = ["classpath:h2/test-data.sql"],
config = SqlConfig(encoding = "utf-8", separator = ";", commentPrefix = "--"),
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD
)
fun testFindAllWithMappingSqlQuery() {
val singers = singerRepo!!.findAll()
Assertions.assertEquals(3, singers.size)
singers.forEach(Consumer { singer: Singer ->
LOGGER.info(
singer.toString()
)
})
}
@Test
@DisplayName("should return Chuck Berry")
/*@Sql(value = "classpath:h2/add-chuck.sql",
config = @SqlConfig(encoding = "utf-8", separator = ";", commentPrefix = "--"),
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)*/
/* @SqlGroup({
@Sql(value = "classpath:h2/add-chuck.sql",
config = @SqlConfig(encoding = "utf-8", separator = ";", commentPrefix = "--"),
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD),
@Sql(value = "classpath:h2/remove-chuck.sql",
config = @SqlConfig(encoding = "utf-8", separator = ";", commentPrefix = "--"),
executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
})*/
@SqlGroup(
Sql(
statements = arrayOf("insert into SINGER (first_name, last_name, birth_date) values ('Chuck', 'Berry', '1926-09-18')"),
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD
),
Sql(
statements = arrayOf("delete from SINGER where first_name = 'Chuck'"),
executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD
)
)
fun testFindByNameWithMappingSqlQuery() {
val singers = singerRepo!!.findByFirstName("Chuck")
Assertions.assertEquals(1, singers.size)
LOGGER.info("Result: {}", singers[0])
}
@Configuration
open class EmptyEmbeddedJdbcConfig {
@Bean
open fun dataSource(): DataSource? {
return try {
val dbBuilder = EmbeddedDatabaseBuilder()
dbBuilder.setType(EmbeddedDatabaseType.H2).setName("musicdb").build()
} catch (e: Exception) {
LOGGER.error("Embedded DataSource bean cannot be created!", e)
null
}
}
companion object {
private val LOGGER = LoggerFactory.getLogger(EmptyEmbeddedJdbcConfig::class.java)
}
}
companion object {
private val LOGGER = LoggerFactory.getLogger(RepoBeanTest::class.java)
}
}
|
<!-- Code by Brave Coder - https://youtube.com/BraveCoder -->
<?php
session_start();
if (isset($_SESSION['SESSION_EMAIL'])) {
header("Location: welcome.php");
die();
}
include 'config.php';
$msg = "";
if (isset($_GET['verification'])) {
if (mysqli_num_rows(mysqli_query($conn, "SELECT * FROM users WHERE code='{$_GET['verification']}'")) > 0) {
$query = mysqli_query($conn, "UPDATE users SET code='' WHERE code='{$_GET['verification']}'");
if ($query) {
$msg = "<div class='alert alert-success'>Account verification has been successfully completed. Please enter your email and password once again.</div>";
}
} else {
header("Location: index.php");
}
}
if (isset($_POST['submit'])) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, md5($_POST['password']));
$sql = "SELECT * FROM users WHERE email='{$email}' AND password='{$password}'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) === 1) {
$row = mysqli_fetch_assoc($result);
if (empty($row['code'])) {
// Validate reCAPTCHA
$recaptchaResponse = $_POST['g-recaptcha-response'];
$recaptchaSecretKey = '6LdVIc4oAAAAAFRImqezIKWk_SvYjsOkXt0zhP86';
// Verify reCAPTCHA
$recaptchaVerify = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$recaptchaSecretKey&response=$recaptchaResponse");
$recaptchaData = json_decode($recaptchaVerify);
if (!$recaptchaData->success) {
$msg = "<div class='alert alert-danger'>Please verify that you are not a robot.</div>";
} else {
// reCAPTCHA validation passed
$_SESSION['SESSION_EMAIL'] = $email;
header("Location: welcome.php");
}
} else {
$msg = "<div class='alert alert-info'>First verify your account and try again.</div>";
}
} else {
$msg = "<div class='alert alert-danger'>Email or password do not match.</div>";
}
}
?>
<!DOCTYPE html>
<html lang="zxx">
<head>
<title>Login</title>
<!-- Meta tag Keywords -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8" />
<meta name="keywords"
content="Login Form" />
<!-- //Meta tag Keywords -->
<link href="//fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
<!--/Style-CSS -->
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<!--//Style-CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/af562a2a63.js" crossorigin="anonymous"></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<!-- form section start -->
<section class="w3l-mockup-form">
<div class="container">
<!-- /form -->
<div class="workinghny-form-grid">
<div class="main-mockup">
<div class="w3l_form align-self">
<div class="left_grid_info">
<img src="images/image.svg" alt="">
</div>
</div>
<div class="content-wthree">
<h2>Login Now</h2>
<p>Website details... </p>
<?php echo $msg; ?>
<form action="" method="post">
<input type="email" class="email" name="email" placeholder="Enter Your Email" required>
<input type="password" class="password" name="password" placeholder="Enter Your Password" style="margin-bottom: 2px;" required>
<p><a href="forgot-password.php" style="margin-bottom: 15px; display: block; text-align: right;">Forgot Password?</a></p>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LdVIc4oAAAAAGnHXfdAGUf7cu_JVi-eO3iiJc7X"></div>
</div>
<button id="login" name="submit" class="btn" type="submit">Login</button>
</form>
<div class="social-icons">
<p>Create Account! <a href="register.php">Register</a>.</p>
</div>
</div>
</div>
</div>
<!-- //form -->
</div>
</section>
<!-- //form section start -->
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function (c) {
$('.alert-close').on('click', function (c) {
$('.main-mockup').fadeOut('slow', function (c) {
$('.main-mockup').remove();
});
});
});
</script>
</body>
</html>
|
import React from 'react';
import { Typography, IconButton, MenuItem, Menu, Avatar } from '@material-ui/core';
import MoreIcon from '@material-ui/icons/MoreHorizOutlined';
import styles from './Comment.module.scss';
import { ResponseUserTypes } from '../../utils/api/types';
import { Api } from '../../utils/api';
interface CommentPostProps {
user: ResponseUserTypes;
text: string;
createdAt: string;
userId: number;
id: number;
onRemove: (id: number) => void;
}
export const Comment: React.FC<CommentPostProps> = ({ id, user, text, createdAt, userId, onRemove }) => {
const [anchorEl, setAnchorEl] = React.useState(null);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const onCommentRemove = async () => {
if (window.confirm()) {
try {
await Api().comment.remove(id)
onRemove(id);
} catch (err) {
console.warn('Comment remove error', err);
alert('Не удалось удалить комментарий');
} finally {
handleClose();
}
}
}
return (
<div className={styles.comment}>
<div className={styles.userInfo}>
<Avatar className="mr-15">{user.fullName[0]}</Avatar>
<b>{user.fullName}</b>
<span>{createdAt}</span>
</div>
<Typography className={styles.text}>
{text}
</Typography>
<span className={styles.replyBtn}>Ответить</span>
{user.id === userId &&
<>
<IconButton onClick={handleClick}>
<MoreIcon />
</IconButton>
<Menu
anchorEl={anchorEl}
elevation={2}
open={Boolean(anchorEl)}
onClose={handleClose}
keepMounted>
<MenuItem onClick={onCommentRemove}>Удалить</MenuItem>
<MenuItem onClick={handleClose}>Редактировать</MenuItem>
</Menu></>}
</div>
);
};
|
import { createContext, useEffect, useState } from "react";
// type Theme = 'dark' | ''
interface appContextProps {
theme?: string
alterTheme?: () => void
}
export const appContext = createContext<appContextProps>({})
export function AppProvider(props: any) {
const [theme, setTheme] = useState('dark')
function alterTheme() {
const newTheme = theme === '' ? 'dark' : ''
setTheme(newTheme)
localStorage.setItem('theme', newTheme)
}
useEffect(() => {
const themeSaved = localStorage.getItem('theme')
setTheme(themeSaved!)
}, [])
return (
<appContext.Provider value={{
theme,
alterTheme
}}>
{props.children}
</appContext.Provider>
)
}
|
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int freq[MAX_SIZE];
int size, i, j, count;
/* Input size of array */
printf("Enter size of array: ");
scanf("%d", &size);
/* Input elements of array */
printf("Enter elements of array:\n");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
/* Initially initialize frequency of all elements to -1 */
freq[i] = -1;
}
/* Count frequency of each element */
for(i=0; i<size; i++)
{
count = 1;
for(j=i+1; j<size; j++)
{
if(arr[i] == arr[j])
{
count++;
/* Make sure not to count frequency of same element again */
freq[j] = 0;
}
}
/* If frequency of current element is not counted */
if(freq[i] != 0)
{
freq[i] = count;
}
}
/* Print frequency of each element */
printf("\nFrequency of each element in the array:\n");
for(i=0; i<size; i++)
{
if(freq[i] != 0)
{
printf("%d occurs %d times\n", arr[i], freq[i]);
}
}
return 0;
}
|
import { useState, useEffect } from 'react'
import Header from './components/Header'
import Form from './components/Form'
import PatientsList from './components/PatientsList'
function App() {
const [patients, setPatients] = useState(JSON.parse(localStorage.getItem('patients')) ?? [])
const [onePatient, setOnePatient] = useState({})
// For now i'm only using the local storage
// In a future update i need to delete this code to use a DB
useEffect(() => {
localStorage.setItem('patients', JSON.stringify(patients));
}, [patients]);
const deletePatient = id => {
const updatedPatients = patients.filter(patient => patient.id !== id);
setPatients(updatedPatients);
}
return (
<div className='container mx-auto mt-10'>
<Header />
<div className='mt-12 md:flex'>
<Form
onePatient={onePatient}
patients={patients}
setPatients={setPatients}
/>
<PatientsList
patients={patients}
setOnePatient={setOnePatient}
deletePatient={deletePatient}
/>
</div>
</div>
)
}
export default App
|
// Regular imports.
import AbstractEvent from './AbstractEvent'
import { setProto } from '../'
// Type imports.
import type { Client } from '../client'
import type { PlayerTagEvent } from '..'
/**
* BeAPI entered water event. Contains the logic
* for translating Minecraft event data to BeAPI
* wrapped data.
*/
export class EnteredWater extends AbstractEvent {
// Predefined in AbstractEvent.
protected readonly _logic = this.__logic.bind(this)
// Predefined in AbstractEvent.
protected readonly _client: Client
// Predefined in AbstractEvent.
protected _registered = false
// Predefined in AbstractEvent.
@setProto('EnteredWater')
public readonly name = 'EnteredWater'
// Predefined in AbstractEvent.
@setProto('custom')
public readonly iName = 'custom'
// Predefined in AbstractEvent.
public readonly alwaysCancel = false
/**
* BeAPI entered water event. Contains the logic
* for translating Minecraft event data to BeAPI
* wrapped data.
* @param client Client referece.
*/
public constructor(client: Client) {
super()
this._client = client
}
// Predefined in AbstractEvent.
public on(): void {
// If not already registered.
if (!this._registered) {
// Subscribe to Client event with needed logic
// And use bound _logic for the callback.
this._client.addListener('PlayerTag', this._logic)
// Set registered to true so this cannot be called
// Again before off being called.
this._registered = true
}
}
// Predefined in AbstractEvent.
public off(): void {
// If currently registered.
if (this._registered) {
// Remove Client event listener used
// With bound _logic callback.
this._client.removeListener('PlayerTag', this._logic)
// Set registered to false so this cannot be called
// Again before on being called.
this._registered = false
}
}
// Predefined in AbstractEvent.
protected __logic(data: PlayerTagEvent): void {
// If the beapi tag is not "in_water" return
if (data.tag !== 'in_water') return
// Set player isInWater to true.
data.player.isInWater(true)
// Emit in wator event.
this._client.emit(this.name, data.player)
}
}
|
import React, { useState, useEffect } from 'react'
// Helper
import { helpHttp } from '../helpers/helpHttp'
// Components
import CrudForm from './CrudForm'
import CrudTable from './CrudTable'
import Loader from './Loader'
import Message from './Message'
const Crud = () => {
const [databaseData, setDatabaseData] = useState(null);
const [editForm, setEditForm] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
let api = helpHttp(); // helper
let url = "http://localhost:5000/characters" // JSON-Server Endpoint (api)
useEffect(() => {
setLoading(true)
// api.get(url).then.... Instead helpHttp().get... // Causes an infinite bucle
// USING helpHttp (HELPER)
helpHttp().get(url).then((res) => {
// console.log(res)
if (!res.error) {
setDatabaseData(res)
setError(null)
} else {
setDatabaseData(null)
setError(res)
}
setLoading(false)
/*
NOT USING helpHttp (HELPER)
then(function (response) {
if (response.ok) {
response.json().then((res) => {
setDatabaseData(res)
setError(null)
})
} else {
let res = response.error
console.log('Respuesta de red OK pero respuesta HTTP no OK');
setDatabaseData(null)
setError(res)
}
})
setLoading(false)
*/
})
}, [url,]);
const addData = (data) => {
console.log("Sending data to API....", data)
setLoading(true)
const newItem = { id: Date.now(), name: data.name, team: data.team } // This item will be added
// Set options to Post method
let options = { headers: { "Content-type": "application/json" }, method: "POST", body: newItem }
api.post(url, options).then((res) => {
// console.log(res)
if (!res.error) {
setDatabaseData([...databaseData, newItem]) // Method #1
// setDatabaseData(databaseData.concat(newItem)) // Method #2
setError(null)
} else {
console.log(res)
setDatabaseData(null)
setError(res)
}
setLoading(false)
})
// console.log("Character added: ", databaseData)
}
const updateData = (data) => {
setLoading(true)
let newUrl = `${url}/${data.id} `
const updatedItem = data;
// Set options to Put method
let options = { headers: { "Content-type": "application/json" }, body: data, method: "PUT" }
api.put(newUrl, options).then((res) => {
// console.log(res)
if (!res.error) {
// This map returns a new Array with the updated item.
let newData = databaseData.map((item) => {
// item.id === updatedItem.id ? updatedItem : item Option #1
if (item.id === updatedItem.id) {
console.log(`Updating: ${item} to this: ${data} `)
return updatedItem
} else {
return item
}
})
setDatabaseData(newData) // Method #1
setError(null)
} else {
console.log(res)
setDatabaseData(null)
setError(res)
}
setLoading(false)
})
}
const removeData = (idItem) => {
setLoading(true)
let newUrl = `${url}/${idItem} `
// Set options to Put method
let options = { headers: { "Content-type": "application/json" }, method: "DELETE" }
api.del(newUrl, options).then((res) => {
if (!res.error) {
// If no errors, just filter the database excluding the clicked item through ID
console.log("Deleting this:", idItem)
// Filter "Database data" avoiding the clicked item
let newData = databaseData.filter((item) => item.id !== idItem)
setDatabaseData(newData);
setLoading(false)
} else {
setError(res)
}
})
}
return (
<div>
<h3>Crud API (Fetch)</h3>
<CrudForm addData={addData} updateData={updateData} editForm={editForm} setEditForm={setEditForm} />
{loading &&
<Loader />
}
{
error &&
<Message message={`Error code: ${error.status} for: ${error.statusText} `} bgColor={'red'} />
}
{
// Only show table if exist data
databaseData &&
<CrudTable data={databaseData} setEditForm={setEditForm} removeData={removeData} />
}
</div>
)
}
export default Crud
|
package com.schools.Schools.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
@ResponseStatus
public class GlobalExceptionHandler {
@ExceptionHandler(InstitutionNameExistsException.class)
public ResponseEntity<ErrorMessage> institutionNameExistsException(InstitutionNameExistsException exception, WebRequest request){
ErrorMessage message = new ErrorMessage(HttpStatus.CONFLICT, exception.getMessage());
return ResponseEntity.status(HttpStatus.CONFLICT).body(message);
}
@ExceptionHandler(InstitutionDoesNotExistException.class)
public ResponseEntity<ErrorMessage> institutionDoesNotExistException(InstitutionDoesNotExistException exception, WebRequest request){
ErrorMessage message = new ErrorMessage(HttpStatus.NOT_FOUND, exception.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(message);
}
@ExceptionHandler(CourseExistsException.class)
public ResponseEntity<ErrorMessage> courseExistsException(CourseExistsException exception, WebRequest request){
ErrorMessage message = new ErrorMessage(HttpStatus.CONFLICT, exception.getMessage());
return ResponseEntity.status(HttpStatus.CONFLICT).body(message);
}
@ExceptionHandler(CourseNotFoundException.class)
public ResponseEntity<ErrorMessage> courseNotFoundException(CourseNotFoundException exception, WebRequest request){
ErrorMessage message = new ErrorMessage(HttpStatus.NOT_FOUND, exception.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(message);
}
@ExceptionHandler(ForbiddenActionsException.class)
public ResponseEntity<ErrorMessage> forbiddenActionsException(ForbiddenActionsException exception, WebRequest request){
ErrorMessage message = new ErrorMessage(HttpStatus.FORBIDDEN, exception.getMessage());
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(message);
}
@ExceptionHandler(StudentNotFoundException.class)
public ResponseEntity<ErrorMessage> studentNotFoundException(StudentNotFoundException exception, WebRequest request){
ErrorMessage message = new ErrorMessage(HttpStatus.NOT_FOUND, exception.getMessage());
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(message);
}
}
|
import "./style.css";
import * as THREE from 'three.js';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({
canvas: document.querySelector('#bg'),
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
camera.position.setZ(30);
renderer.render(scene, camera);
const controls = new OrbitControls(camera, renderer.domElement);
//basic torus
const geometry = new THREE.TorusGeometry(10, 3, 16, 100);
const material = new THREE.MeshBasicMaterial({color: 0xFF6347, wireframe: true});
const torus = new THREE.Mesh(geometry, material);
torus.position.z -= 30;
torus.position.x -= 30;
//--------
//lightedTorus
const lightedMat = new THREE.MeshStandardMaterial({color: 0xFF6347});
const torus2 = new THREE.Mesh(geometry, lightedMat);
torus2.position.z -= 30;
torus2.position.x += 30;
//---------
//light
const pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(5,5,5);
const ambientLight = new THREE.AmbientLight(0xffffff);
const lightHelper = new THREE.PointLightHelper(pointLight);
//---------
const gridHelper = new THREE.GridHelper(200, 50);
const spaceImage =new THREE.TextureLoader().load('milky-way-starry-sky-night-sky-star-956981.jpeg');
scene.background = spaceImage;
scene.add(torus2);
scene.add(torus);
scene.add(pointLight, ambientLight, lightHelper);
scene.add(gridHelper);
function addStar() {
const geometry = new THREE.SphereGeometry(0.25, 24, 24);
const material = new THREE.MeshStandardMaterial({ color: 0xffffff});
const star = new THREE.Mesh(geometry, material);
const [x, y, z] = Array(3).fill().map(() => THREE.MathUtils.randFloatSpread(100));
star.position.set(x, y, z);
scene.add(star);
}
Array(200).fill().forEach(addStar);
function animate() {
requestAnimationFrame(animate);
torus.rotation.x += 0.01;
torus.rotation.y += 0.005;
torus.rotation.z += 0.01;
torus2.rotation.x += 0.01;
torus2.rotation.y += 0.005;
torus2.rotation.z += 0.01;
controls.update();
renderer.render(scene, camera);
}
animate()
|
import {
Injectable,
CanActivate,
ExecutionContext,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { PERMISSION_KEY } from './PermissionDecorator';
@Injectable()
export class PermissionGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredPermissions = this.reflector.getAllAndOverride<string[]>(
PERMISSION_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredPermissions) {
return true;
}
const { user } = context.switchToHttp().getRequest();
if (!user.emailVerified) {
throw new HttpException(
`User have not verified their email address`,
HttpStatus.FORBIDDEN,
);
}
const hasPermission = requiredPermissions.some((permissionScope) =>
user.permissions?.includes(permissionScope),
);
if (!hasPermission) {
throw new HttpException(
`Missing required permission: ${requiredPermissions.join(',')}`,
HttpStatus.FORBIDDEN,
);
}
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.