{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \n \n \n \n \n "}}},{"rowIdx":1092508,"cells":{"text":{"kind":"string","value":"package com.example.jojosproject.Adapter\n\nimport android.graphics.Color\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.*\nimport androidx.recyclerview.widget.RecyclerView\nimport com.example.jojosproject.DataClass.Carte\nimport com.example.jojosproject.DataClass.Joueur\nimport com.example.jojosproject.R\nimport com.example.jojosproject.ViewHolder.ViewHolderJoueurPartie\n\nclass AdaptaterJoueurPartie (private val joueursEtCartes: Map) :\n RecyclerView.Adapter() {\n override fun onBindViewHolder(holder: ViewHolderJoueurPartie, position: Int) {\n val (joueur, carte) = joueursEtCartes.entries.elementAt(position)\n\n // Mettez à jour les vues du ViewHolder avec les données du joueur et de la carte\n holder.textViewNom.text = joueur.nom\n holder.textViewRôle.text = carte.nom\n holder.checkVivant.isChecked = false\n\n // Afficher/masquer et configurer les vues spécifiques en fonction du nom de la carte\n when (carte.nom) {\n \"Sorciere\" -> {\n holder.linearLayoutSpecificite.removeAllViews() // Supprimer les vues existantes\n\n val layoutParams = LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.WRAP_CONTENT,\n LinearLayout.LayoutParams.WRAP_CONTENT\n )\n\n // Créer et ajouter le TextView \"Vie\"\n val textViewVie = TextView(holder.linearLayoutSpecificite.context)\n textViewVie.text = \"Vie\"\n textViewVie.layoutParams = layoutParams\n textViewVie.setTextColor(Color.WHITE) // Changer la couleur du texte en blanc\n textViewVie.setBackgroundColor(Color.TRANSPARENT) // Définir un fond transparent\n holder.linearLayoutSpecificite.addView(textViewVie)\n\n // Créer et ajouter la CheckBox \"Vie\"\n val checkBoxVie = CheckBox(holder.linearLayoutSpecificite.context)\n checkBoxVie.layoutParams = layoutParams\n checkBoxVie.isChecked = true\n holder.linearLayoutSpecificite.addView(checkBoxVie)\n\n // Créer et ajouter le TextView \"Mort\"\n val textViewMort = TextView(holder.linearLayoutSpecificite.context)\n textViewMort.text = \"Mort\"\n textViewMort.layoutParams = layoutParams\n textViewMort.setTextColor(Color.WHITE) // Changer la couleur du texte en blanc\n textViewMort.setBackgroundColor(Color.TRANSPARENT) // Définir un fond transparent\n holder.linearLayoutSpecificite.addView(textViewMort)\n\n // Créer et ajouter la CheckBox \"Mort\"\n val checkBoxMort = CheckBox(holder.linearLayoutSpecificite.context)\n checkBoxMort.layoutParams = layoutParams\n checkBoxMort.isChecked = true\n holder.linearLayoutSpecificite.addView(checkBoxMort)\n }\n\n \"Cupidon\" -> {\n holder.linearLayoutSpecificite.removeAllViews() // Supprimer les vues existantes\n\n // Créer et ajouter les Spinners dynamiquement\n val spinnerJoueur1 = Spinner(holder.linearLayoutSpecificite.context)\n // Récupérer la liste des joueurs disponibles\n val listeJoueursDisponibles = joueursEtCartes.keys.map { it.nom }\n // Configurer les options du spinner en fonction des joueurs disponibles\n val joueurAdapter1 = ArrayAdapter(\n holder.linearLayoutSpecificite.context,\n android.R.layout.simple_spinner_item,\n listeJoueursDisponibles\n )\n spinnerJoueur1.adapter = joueurAdapter1\n spinnerJoueur1.setBackgroundColor(Color.WHITE) // Changer la couleur du fond en blanc\n holder.linearLayoutSpecificite.addView(spinnerJoueur1)\n\n // Créer et ajouter le cœur\n val heartTextView = TextView(holder.linearLayoutSpecificite.context)\n heartTextView.text = \"❤️\"\n holder.linearLayoutSpecificite.addView(heartTextView)\n\n val spinnerJoueur2 = Spinner(holder.linearLayoutSpecificite.context)\n // Configurer les options du spinner en fonction des joueurs disponibles\n val joueurAdapter2 = ArrayAdapter(\n holder.linearLayoutSpecificite.context,\n android.R.layout.simple_spinner_item,\n listeJoueursDisponibles\n )\n spinnerJoueur2.adapter = joueurAdapter2\n spinnerJoueur2.setBackgroundColor(Color.WHITE) // Changer la couleur du fond en blanc\n holder.linearLayoutSpecificite.addView(spinnerJoueur2)\n }\n else -> {\n // Pour les autres cartes, masquer le LinearLayout\n holder.linearLayoutSpecificite.visibility = View.INVISIBLE\n }\n }\n }\n\n\n override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderJoueurPartie {\n val view =\n LayoutInflater.from(parent.context).inflate(R.layout.joueur_en_partie, parent, false)\n return ViewHolderJoueurPartie(view)\n }\n\n override fun getItemCount(): Int {\n return joueursEtCartes.size\n }\n}"}}},{"rowIdx":1092509,"cells":{"text":{"kind":"string","value":"import * as express from 'express';\nimport { NextFunction, Request, Response } from 'express';\n\nimport { handleAsync } from '../common/helpers';\nimport { AuthController } from '../controllers/authController';\nimport {\n LoginDto,\n UpdatePasswordDto,\n UserRegistrationDto,\n} from '../dtos/user.dto';\nimport {\n userRegistrationSchema,\n loginSchema,\n updatePasswordSchema,\n} from '../schemas';\nimport { validateRequest } from '../middleware/validateInput';\nimport { jwtValidator } from '../middleware/jwtValidator';\nimport { TRequestWithToken } from '../common/types/user.types';\n\nconst authController = new AuthController();\nconst AuthRouter = express.Router();\n\nAuthRouter.post(\n '/auth/register',\n validateRequest(userRegistrationSchema),\n handleAsync(async (req: Request, res: Response, next: NextFunction) => {\n const data = req.body as UserRegistrationDto;\n const result = await authController.register(data);\n\n res.status(201).json(result);\n }),\n);\n\nAuthRouter.post(\n '/auth/login',\n validateRequest(loginSchema),\n handleAsync(async (req: Request, res: Response) => {\n const loginDto = req.body as LoginDto;\n const result = await authController.login(loginDto);\n res.status(200).json(result);\n }),\n);\n\nAuthRouter.put(\n '/auth/password',\n jwtValidator,\n validateRequest(updatePasswordSchema),\n handleAsync(\n async (req: TRequestWithToken, res: Response, next: NextFunction) => {\n const result = await authController.updatePassword(\n req.user.userId,\n req.body.oldPassword,\n req.body.newPassword,\n );\n const { password, ...data } = result;\n\n res.status(200).json(data);\n },\n ),\n);\n\nexport { AuthRouter };"}}},{"rowIdx":1092510,"cells":{"text":{"kind":"string","value":"package en.gregthegeek.gfactions.economy;\n\nimport java.util.HashMap;\n\nimport en.gregthegeek.gfactions.db.Datasource;\nimport en.gregthegeek.gfactions.faction.Faction;\nimport en.gregthegeek.util.Utils;\n\n/**\n * Represents an economy managed by gFactions.\n * \n * @author gregthegeek\n *\n */\npublic class IntegratedEconomy implements Economy {\n\tprivate final HashMap players = new HashMap(); // player name -> balance\n\tprivate final HashMap factions = new HashMap(); // faction id -> balance\n\n\t@Override\n\tpublic void initPlayer(String player) {\n\t\tif(!players.containsKey(player)) {\n\t\t\tplayers.put(player, Utils.plugin.getDataSource().getBalance(player));\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void initFaction(int id) {\n\t\tif(!factions.containsKey(id)) {\n\t\t\tfactions.put(id, Utils.plugin.getDataSource().getBalance(id));\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean modifyBalance(String player, int amount) {\n\t\tassert players.containsKey(player);\n\t\tint newAmt = players.get(player) + amount;\n\t\tif(newAmt >= 0) {\n\t\t\tplayers.put(player, newAmt);\n\t\t\tif(Utils.plugin.getConfig().getSaveInterval() < 0) {\n\t\t\t\tUtils.plugin.getDataSource().savePlayerBalances(players);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int getBalance(String player) {\n\t\tassert players.containsKey(player);\n\t\treturn players.get(player);\n\t}\n\n\t@Override\n\tpublic boolean modifyBalance(Faction fac, int amount) {\n\t\tint id = fac.getId();\n\t\tassert factions.containsKey(id);\n\t\tint newAmt = factions.get(id) + amount;\n\t\tif(newAmt >= 0) {\n\t\t\tfactions.put(id, newAmt);\n\t\t\tif(Utils.plugin.getConfig().getSaveInterval() < 0) {\n\t\t\t\tUtils.plugin.getDataSource().saveFactionBalances(factions);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int getBalance(Faction fac) {\n\t\tassert factions.containsKey(fac.getId());\n\t\treturn factions.get(fac.getId());\n\t}\n\t\n\t@Override\n\tpublic void save() {\n\t\tDatasource ds = Utils.plugin.getDataSource();\n\t\tds.savePlayerBalances(players);\n\t\tds.saveFactionBalances(factions);\n\t}\n}"}}},{"rowIdx":1092511,"cells":{"text":{"kind":"string","value":".gf-button {\n background: $colour-light-grey;\n text-align: center;\n align-items: center;\n justify-content: center;\n display: inline-flex;\n border-radius: $default-button-border-radius;\n text-transform: uppercase;\n cursor: pointer;\n box-sizing: border-box;\n border: none;\n font-family: $header-font;\n font-weight: 700;\n padding: 1em 3em;\n border: none;\n position: relative;\n margin-right: 5px;\n letter-spacing: 1px;\n box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);\n}\n\n// STATES\n\n.gf-button {\n &:focus {\n outline: 0;\n }\n &:hover {\n background: darken($colour-light-grey, 5%);\n box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);\n }\n &:active{\n outline: 0;\n box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);\n }\n}\n\n// COLOURS\n\n@each $name, $colour in $siteColours {\n .gf-button--#{$name} {\n background: $colour;\n\n @if $name == white {\n color: $colour-dark-grey;\n } @else if $name == 'light-grey' {\n color: $colour-dark-grey;\n } @else {\n color: $colour-white;\n }\n\n &:hover {\n background: darken($colour, 5%);\n }\n }\n}\n\n// SIZES\n\n@each $size, $value in $sizes {\n .gf-button--#{$size} {\n font-size: $value + em;\n }\n}\n\n// VARIATION\n\n.gf-button--hard {\n border-radius: 2px;\n}\n\n.gf-button--fluid {\n width: 100%;\n}\n\n// GRADIENTS\n\n@each $name, $colour in $siteColours {\n .gf-button--#{$name}-gradient {\n background: $colour;\n background: linear-gradient(to bottom, $colour 0%,darken($colour, 5%) 100%);\n filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=$colour, endColorstr=darken($colour, 5%),GradientType=0 );\n }\n}"}}},{"rowIdx":1092512,"cells":{"text":{"kind":"string","value":"import React, { useState, useEffect } from \"react\";\nimport axios from \"axios\";\nimport moment from \"moment\";\nimport { useParams } from \"react-router-dom\";\nimport StripeCheckout from \"react-stripe-checkout\";\nimport Swal from \"sweetalert2\";\nimport Loader from \"../components/Loader\";\nimport Error from \"../components/Error\";\nimport { api } from \"../api\";\n\nfunction Bookingscreen() {\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(\"\");\n const [room, setRoom] = useState({});\n const [totalAmount, setTotalAmount] = useState(0);\n const [totalDays, setTotalDays] = useState(0);\n\n const params = useParams();\n console.log(params);\n const fromdate = moment(params.fromdate, \"DD-MM-YYYY\");\n const todate = moment(params.todate, \"DD-MM-YYYY\");\n\n useEffect(() => {\n const user = JSON.parse(localStorage.getItem(\"currentUser\"));\n if (!user) {\n window.location.href = \"/login\";\n }\n async function fetchMyAPI() {\n try {\n setError(\"\");\n setLoading(true);\n const res = await axios.post(`${api}/api/rooms/getroombyid`, {\n roomid: params.roomid,\n });\n // console.log(res.data);\n setRoom(res.data);\n } catch (error) {\n // console.log(error);\n setError(error);\n }\n setLoading(false);\n }\n\n fetchMyAPI();\n }, []);\n\n useEffect(() => {\n const totaldays = moment.duration(todate.diff(fromdate)).asDays() + 1;\n setTotalDays(totaldays);\n setTotalAmount(totalDays * room.rentperday);\n }, [room]);\n\n const onToken = async (token) => {\n // console.log(token);\n const bookingDetails = {\n room,\n userid: JSON.parse(localStorage.getItem(\"currentUser\")).data._id,\n fromdate,\n todate,\n totalAmount,\n totaldays: totalDays,\n token,\n };\n\n try {\n setLoading(true);\n const result = await axios.post(`${api}/api/bookings/bookroom`, bookingDetails);\n // console.log(result);\n setLoading(false);\n Swal.fire(\n \"Congratulations\",\n \"Your Room Booked Successfully\",\n \"success\"\n ).then((result) => {\n window.location.href = \"/home\";\n });\n } catch (error) {\n setError(error);\n Swal.fire(\"Opps\", \"Error:\" + error, \"error\");\n }\n setLoading(false);\n };\n\n return (\n
\n {loading ? (\n \n ) : error.length > 0 ? (\n \n ) : (\n
\n
\n

{room.name}

\n \"\"\n
\n
\n \n

Booking Details

\n
\n \n

\n Name :{\" \"}\n {JSON.parse(localStorage.getItem(\"currentUser\")).data.name}\n

\n

\n Location : {room.locality}\n

\n

From Date : {params.fromdate}

\n

To Date : {params.todate}

\n

Max People Allowed : {room.maxcount}

\n
\n
\n \n

Amount

\n
\n \n

Total Days : {totalDays}

\n

Rent per day : {room.rentperday}

\n

Total Amount : {totalAmount}

\n
\n
\n\n
\n \n \n \n
\n
\n
\n )}\n
\n );\n}\n\nexport default Bookingscreen;"}}},{"rowIdx":1092513,"cells":{"text":{"kind":"string","value":"package cronies.meeting.user.service.impl;\n\nimport cronies.meeting.user.service.InviteService;\nimport cronies.meeting.user.service.CommonService;\nimport cronies.meeting.user.service.PushService;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Propagation;\nimport org.springframework.transaction.annotation.Transactional;\nimport select.spring.exquery.service.ExqueryService;\n\nimport java.util.HashMap;\nimport java.util.UUID;\n\n@Service(\"InviteService\")\n@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)\npublic class InviteServiceImpl implements InviteService {\n\n Logger log = LoggerFactory.getLogger(this.getClass());\n\n @Autowired\n private ExqueryService exqueryService;\n\n @Autowired\n private CommonService commonService;\n\n @Autowired\n private PushService pushService;\n\n\n @Transactional(propagation = Propagation.REQUIRED, readOnly = false)\n public HashMap getUserInviteCode(HashMap param) throws Exception {\n HashMap resultMap = new HashMap();\n param.put(\"userId\", param.get(\"ssUserId\"));\n\n resultMap = exqueryService.selectOne(\"cronies.app.invite.getUserInviteCode\", param);\n String nanoId = \"\";\n Boolean isExist = false;\n if(resultMap != null){\n isExist = true;\n resultMap.put(\"successYn\", \"Y\");\n }\n\n while(!isExist){\n // nanoId 생성\n nanoId = commonService.getNanoId(6);\n // nanoId 중복체크\n param.put(\"nanoId\", nanoId);\n if(checkNanoId(param) == null){\n try {\n exqueryService.insert(\"cronies.app.invite.insertInviteInfo\", param);\n resultMap = exqueryService.selectOne(\"cronies.app.invite.getUserInviteCode\", param);\n resultMap.put(\"successYn\", \"Y\");\n } catch (Exception e) {\n resultMap.put(\"successYn\", \"N\");\n resultMap.put(\"message\", \"초대코드 확인 중 오류가 발생하였습니다. 문의 부탁드립니다.\");\n }\n isExist = true;\n }\n }\n\n return resultMap;\n }\n\n @Transactional(propagation = Propagation.REQUIRED, readOnly = false)\n public HashMap saveTargetInviteCode(HashMap param) throws Exception {\n HashMap resultMap = new HashMap();\n param.put(\"userId\", param.get(\"ssUserId\"));\n\n // 초대코드 등록 여부 확인\n if(exqueryService.selectOne(\"cronies.app.invite.checkInviteHis\", param) == null){\n // 초대코드가 유효한지 확인\n resultMap = exqueryService.selectOne(\"cronies.app.invite.checkTargetUserInviteCode\", param);\n if(resultMap == null){\n resultMap = new HashMap();\n resultMap.put(\"successYn\", \"N\");\n resultMap.put(\"message\", \"유효하지 않은 상대방 코드입니다.\");\n } else {\n try {\n param.put(\"targetUserId\", resultMap.get(\"userId\"));\n param.put(\"inviteUserId\", param.get(\"userId\"));\n\n // 친구코드 등록\n exqueryService.insert(\"cronies.app.invite.insertInviteCode\", param);\n exqueryService.insert(\"cronies.app.invite.insertInvitePointHis\", param);\n exqueryService.update(\"cronies.app.invite.updateInvitePoint\", param);\n// exqueryService.update(\"cronies.app.invite.updateInvitePoint2\", param);\n resultMap = exqueryService.selectOne(\"cronies.app.invite.getUserInviteCode\", param);\n resultMap.put(\"successYn\", \"Y\");\n resultMap.put(\"message\", \"초대코드 등록에 성공하였습니다!\");\n } catch (Exception e) {\n resultMap.put(\"successYn\", \"N\");\n resultMap.put(\"message\", \"초대코드 등록 중 오류가 발생하였습니다. 문의 부탁드립니다.\");\n }\n }\n } else {\n resultMap.put(\"successYn\", \"N\");\n resultMap.put(\"message\", \"이미 초대코드를 등록하셨습니다.\");\n }\n\n return resultMap;\n }\n\n @Transactional(propagation = Propagation.REQUIRED, readOnly = false)\n public HashMap checkNanoId(HashMap param) throws Exception {\n HashMap resultMap = new HashMap();\n resultMap = exqueryService.selectOne(\"cronies.app.invite.checkNanoId\", param);\n return resultMap;\n }\n\n}"}}},{"rowIdx":1092514,"cells":{"text":{"kind":"string","value":"/***************************************************************************************\n*@file dnxNode.h\n*@author Steven D.Morrey (smorrey@ldschurch.org)\n*@c (c)2008 Intellectual Reserve, Inc.\n*\n* The purpose of this file is to define a worker node instrumentation class.\n***************************************************************************************/\n#include \"dnxTypes.h\"\n\n#ifndef DNXNODE\n#define DNXNODE\n\nenum\n{\n JOBS_DISPATCHED,\n JOBS_HANDLED,\n JOBS_REJECTED_OOM,\n JOBS_REJECTED_NO_NODES,\n JOBS_REQ_RECV,\n JOBS_REQ_EXP,\n HOSTNAME,\n AFFINITY_FLAGS\n\n};\n\n/** DnxNodes are more than just simple structs for keeping track of IP addresses\n* They are a linked list of worker nodes tied to relevant metrics\n*/\ntypedef struct DnxNode\n{\n\n struct DnxNode* next; //!< Next Node\n struct DnxNode* prev; //!< Previous Node\n char* address; //!< IP address or URL of worker\n char* hostname; //!< Hostname defined in dnxClient.cfg\n unsigned long long int flags; //!< Affinity flags assigned during init\n unsigned jobs_dispatched; //!< How many jobs have been sent to worker\n unsigned jobs_handled; //!< How many jobs have been handled\n unsigned jobs_rejected_oom; //!< How many jobs have been rejected due to memory\n unsigned jobs_rejected_no_nodes; //!< How many jobs have been rejected due to no available nodes\n unsigned jobs_req_recv; //!< How many job requests have been recieved from worker\n unsigned jobs_req_exp; //!< How many job requests have expired\n pthread_mutex_t mutex; //!< Thread locking control structure\n} DnxNode;\n\n\n/** Node Creation Function for DnxNodes\n* Create a new node and add it to the end of the list\n* @param address - IP address of the worker node\n* @param pTopDnxNode - Pointer to the node you want to add to\n* @return pDnxNode - Pointer to the newly created node\n*\n* NOTE: If a node already exists with that IP address, then\n* we return the existing node instead of creating a new node\n*/\nDnxNode* dnxNodeListCreateNode(char *address, char *hostname);\n\n/** Node Destruction Function\n* This function can be used to remove the entire list\n*/\nvoid dnxNodeListDestroy();\n\n\n/** Removal function for DnxNodes\n* Remove and delete a node.\n* Since all nodes are linked together in a list, this function will also heal the list\n* by pointing prev at next and vice versa\n* @param pDnxNode - A pointer to the node you want to remove\n* @return - A pointer to the next node in the list\n*/\nDnxNode* dnxNodeListRemoveNode(DnxNode* pDnxNode);\n\n/** Removal function for DnxNodes\n* Remove and delete all nodes.\n* Then recreate gTopNode\n*/\nvoid dnxNodeListReset();\n\n/** Return a pointer to the end node\n*/\nDnxNode* dnxNodeListEnd();\n\n/** Return a pointer to the beginning node\n*/\nDnxNode* dnxNodeListBegin();\n\n/** Find a node by it's IP address\n* @param address - The IP address of the node you want to find\n* @return - A pointer to the node if found, if not found it returns NULL\n*/\nDnxNode* dnxNodeListFindNode(char* address);\n\n/** Count the nodes\n*/\nint dnxNodeListCountNodes();\n\n\n/** Count a given member value from all nodes\n* Internal use function, use dnxNodeListCountX functions instead\n*/\nunsigned dnxNodeListCountValuesFromAllNodes(int member);\n\n/** Return a member value from a single node\n* Internal use function, use dnxNodeListCountX functions instead\n*/\nunsigned dnxNodeListGetMemberValue(DnxNode* pDnxNode, int member);\n\n/** Place holder function to determine if we want values from all nodes or just one\n* Internal use function, use dnxNodeListCountX functions instead\n*/\nunsigned dnxNodeListCount(char* address, int member);\n\nunsigned dnxNodeListIncrementNodeMember(char* address,int member);\n\nunsigned dnxNodeListSetNode(char* address, int member, void* value);\n\nstatic void * dnxStatsRequestListener(void *vptr_args);\n\n#endif"}}},{"rowIdx":1092515,"cells":{"text":{"kind":"string","value":"import React, { Component } from 'react';\nimport styles from './style.scss';\nimport { Router, Route, Link } from 'react-router'\nimport AppBar from 'material-ui/lib/app-bar';\nimport IconButton from 'material-ui/lib/icon-button';\nimport NavigationClose from 'material-ui/lib/svg-icons/navigation/close';\nimport IconMenu from 'material-ui/lib/menus/icon-menu';\nimport MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert';\nimport MenuItem from 'material-ui/lib/menus/menu-item';\nimport FlatButton from 'material-ui/lib/flat-button';\nimport RaisedButton from 'material-ui/lib/raised-button';\nimport Avatar from 'material-ui/lib/avatar';\nimport DropDownMenu from 'material-ui/lib/DropDownMenu';\nimport LeftNav from 'material-ui/lib/left-nav';\n\nimport withStyles from '../../../decorators/withStyles';\n@withStyles(styles)\nclass Header extends Component {\n constructor(props) {\n super(props);\n this.state = {\n showLeftNavigation: false\n };\n }\n showLeftNavigation = () => {\n this.setState({\n showLeftNavigation: true\n });\n };\n hideLeftNavigation = () => {\n this.setState({\n showLeftNavigation: false\n });\n };\n\n handleRequestChange = (open) => {\n this.setState({\n showLeftNavigation: open\n });\n };\n\n logout = async () => {\n window.location.href = '/#/';\n };\n\n render() {\n return (\n
\n }\n >\n \n \n \n :\n \n }\n />\n \n \n \n \n \n \n \n \n
\n );\n }\n}\n\nexport default Header;"}}},{"rowIdx":1092516,"cells":{"text":{"kind":"string","value":"@demo\nFeature: Search\n In order to see a word definition\n As a website user\n I need to be able to search for a word\n\n Scenario: Searching for a page that does exist\n Given I am on \"https://www.wikipedia.org/wiki/Main_Page\"\n When I fill in \"search\" with \"Behavior Driven Development\"\n And I press \"searchButton\"\n Then I should see \"agile software development\"\n Then I save screenshot\n\n Scenario: Searching for a page that does NOT exist\n Given I am on \"https://www.wikipedia.org/wiki/Main_Page\"\n When I fill in \"search\" with \"Glory Driven Development\"\n And I press \"searchButton\"\n Then I should see \"Search results\"\n Then I save screenshot"}}},{"rowIdx":1092517,"cells":{"text":{"kind":"string","value":"\n\n\n\n"}}},{"rowIdx":1092518,"cells":{"text":{"kind":"string","value":"import { BrowserModule } from \"@angular/platform-browser\";\nimport { NgModule } from \"@angular/core\";\n\nimport { AppRoutingModule } from \"./app-routing.module\";\nimport { AppComponent } from \"./app.component\";\nimport { LoginComponent } from \"./auth/login/login.component\";\nimport { RegisterComponent } from \"./auth/register/register.component\";\nimport { FormsModule, ReactiveFormsModule } from \"@angular/forms\";\nimport { HttpClientModule } from \"@angular/common/http\";\nimport { CommonModule } from \"@angular/common\";\nimport { InicioComponent } from \"./auth/inicio/inicio.component\";\nimport { HeaderComponent } from \"./auth/header/header.component\";\nimport { AngularFirestore } from \"angularfire2/firestore\";\nimport { AngularFireModule, FirebaseOptionsToken } from \"angularfire2\";\n\nimport { environment } from \"src/environments/environment\";\nimport { AngularFireAuth } from \"angularfire2/auth\";\nimport { AngularFirestoreModule } from \"angularfire2/firestore\";\nimport { AngularFireStorageModule } from \"angularfire2/storage\";\nimport { StoreModule } from \"@ngrx/store\";\nimport { ImagenesService } from \"./services/imagenes.service\";\nimport { PeliculasComponent } from './auth/peliculas/peliculas.component';\nimport { PipesImgPipe } from './pipes/pipes-img.pipe';\nimport { SeriesPipe } from './pipes/series.pipe';\n@NgModule({\n declarations: [\n AppComponent,\n LoginComponent,\n RegisterComponent,\n InicioComponent,\n HeaderComponent,\n PeliculasComponent,\n PipesImgPipe,\n SeriesPipe,\n ],\n imports: [\n BrowserModule,\n AppRoutingModule,\n FormsModule,\n HttpClientModule,\n CommonModule,\n ReactiveFormsModule,\n AngularFireModule,\n AngularFireModule.initializeApp(environment.firebase),\n AngularFireStorageModule,\n AngularFirestoreModule,\n StoreModule.forRoot({}),\n HttpClientModule,\n ],\n providers: [AngularFirestore, AngularFireAuth],\n bootstrap: [AppComponent],\n})\nexport class AppModule {}"}}},{"rowIdx":1092519,"cells":{"text":{"kind":"string","value":"import React, {useContext, useEffect, useState} from 'react'\nimport {FaArrowRight} from 'react-icons/fa'\nimport { SelectedInstancesContext } from '../App';\nimport { useNavigate } from 'react-router-dom';\nimport { LoadingComponent } from './LoadingComponent';\nimport { toast, ToastContainer } from 'react-toastify';\nimport \"react-toastify/dist/ReactToastify.css\";\nimport { CanteenApi } from '../Helpers/Service/CanteenService';\n\nexport const MenuComponent = () => {\n\n let navigate = useNavigate();\n\n const selectedInstancesContext = useContext(SelectedInstancesContext);\n\n const [loading, setLoading] = useState(true);\n const [categories, setCategories] = useState([]);\n\n useEffect(() => {\n CanteenApi.GetAllCategoriesWithPictures()\n .then(res => setCategories(res))\n .then(() => setLoading(false))\n .catch(() => toast.error('S-a produs o eroare!'));\n }, [])\n\n return (\n
\n {loading === true && \n \n }\n {loading === false &&\n <>\n

Meniu

\n
\n {categories.map(category => (\n
{\n selectedInstancesContext.setSelectedCategoryName(category.categoryName);\n selectedInstancesContext.setSelectedCategoryId(category.id);\n navigate('/canteenId=' + selectedInstancesContext.selectedCanteenId + '/' + category.categoryName.toLowerCase());\n }}\n >\n

{category.categoryName}

\n
\n
\n \n
\n
\n
\n ))}\n
\n \n }\n\n \n\n
\n )\n}"}}},{"rowIdx":1092520,"cells":{"text":{"kind":"string","value":"//\n// HomeViewController.swift\n// EMovie\n//\n// Created by Nizar Elhraiech on 15/1/2022.\n//\n\nimport UIKit\nimport Combine\n\n@available(iOS 13.0, *)\nclass HomeViewController: UIViewController {\n \n // MARK: Outlets \n @IBOutlet weak var passwordTextField: UITextField!\n @IBOutlet weak var emailTextField: UITextField!\n // MARK: Variable\n var user : User?\n var viewModel = HomeViewModel()\n var bag = Set()\n // MARK: Life cycle\n override func viewDidLoad() {\n super.viewDidLoad()\n // Do any additional setup after loading the view.\n setViewModel(viewModel)\n bindViewModel()\n }\n \n override func viewDidDisappear(_ animated: Bool) {\n super.viewDidDisappear(true)\n }\n \n private func setViewModel(_ viewModel: HomeViewModel) {\n self.viewModel = viewModel\n }\n \n private func bindViewModel() {\n viewModel.errorFromServer.sink(receiveValue: {\n isError in\n if isError {\n showError(errorDescription: NSLocalizedString(\"ErrorServer\", comment: \"\"))\n }\n \n }).store(in: &bag)\n viewModel.connexion.sink(receiveValue: {\n isError in\n if isError {\n showError(errorDescription: NSLocalizedString(\"NoConnection\", comment: \"\"))\n }\n \n }).store(in: &bag)\n viewModel.user.sink(receiveValue: {\n user in\n self.user = user\n print(user)\n }).store(in: &bag)\n }\n \n // MARK: navigation Method\n override func prepare(for segue: UIStoryboardSegue, sender: Any?) {\n }\n \n \n @IBAction func connectionAction(_ sender: Any) {\n guard let email = emailTextField.text else {\n return\n }\n guard let psswd = passwordTextField.text else {\n return\n }\n viewModel.email.send(email)\n viewModel.password.send(psswd)\n viewModel.login()\n }\n \n}"}}},{"rowIdx":1092521,"cells":{"text":{"kind":"string","value":"\n\n \n \n\n\n
\n
\n
\n Awesome chat app\n
\n
\n
\n
\n {{message.text}}\n
\n
\n
\n
\n
\n \n \n
\n
\n
\n
\n\n \n \n\n"}}},{"rowIdx":1092522,"cells":{"text":{"kind":"string","value":"\n\n\n \n \n Document\n\n \n\n\n\n
xxx
\n\n\n\n"}}},{"rowIdx":1092523,"cells":{"text":{"kind":"string","value":"/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n vector postorderTraversal(TreeNode* root) {\n stack st;\n vector arr;\n TreeNode* node = root;\n TreeNode* prev = nullptr;\n TreeNode* tmp;\n\n while(node || !st.empty())\n {\n while(node)\n {\n st.push(node);\n node = node->left;\n }\n\n tmp = st.top();\n if(tmp->right == nullptr || tmp->right == prev)\n {\n arr.push_back(tmp->val);\n st.pop();\n prev = tmp;\n }\n else\n node = tmp->right;\n\n\n }\n\n return arr;\n }\n};"}}},{"rowIdx":1092524,"cells":{"text":{"kind":"string","value":"import React, { Component } from 'react'\n\nimport { BACKEND } from '../config'\nimport cookie from 'react-cookies'\nimport { Link } from 'react-router-dom'\n\nimport './header.css'\n\nclass Header extends Component {\n\n constructor( props ) {\n super( props );\n this.state = {\n id : cookie.load('user_id'),\n username : '',\n login : '',\n logout : ''\n };\n this.logout = this.logout.bind( this );\n }\n\n componentDidMount() {\n if ( this.state.id ) {\n let url = BACKEND + 'user/' + this.state.id;\n fetch( url ).then( res => {\n return res.json();\n }).then( data => {\n this.setState( { username : data.username, logout : 'notShow', login : 'show' } );\n });\n } else {\n this.setState( { username : '', login : 'notShow', logout : 'show' } );\n }\n }\n\n logout = function() {\n cookie.remove( 'user_id', { path : '/' } );\n this.setState( { username : '', login : 'notShow', logout : 'show' } );\n };\n\n render() {\n return (\n
\n
\n
\n TEAM \n
\n\n
\n PLAYER \n
\n\n
\n GAME \n
\n
\n
\n
{ this.state.username }
\n
logout
\n
login
\n\n
\n
\n )\n }\n}\n\nexport default Header;"}}},{"rowIdx":1092525,"cells":{"text":{"kind":"string","value":"import { CListGroup, CListGroupItem } from \"@coreui/react\";\nimport { React, useState } from \"react\";\nimport { useHistory } from \"react-router-dom\";\nimport Slider1 from \"./slider\";\nimport { userApi } from \"../../../api/userApi\";\nimport toast from \"react-hot-toast\";\nimport bg1 from '../../../images/background/bg1.jpg';\n// day la component tren dau day \nfunction OnlineCourses() {\n const history = useHistory();\n const [listCategory, setListCategory] = useState([]);\n const [listSubject, setListSubject] = useState([]);\n const getListCategory = async () => {\n try {\n const response = await userApi.getListCategoryPost();\n setListCategory(response);\n } catch (responseError) {\n toast.error(responseError?.data?.message, {\n duration: 2000,\n });\n }\n };\n\n const getAllSubject = async () => {\n try {\n const response = await userApi.getListAllSubject();\n setListSubject(response.splice(0, 7))\n } catch (responseError) {\n toast.error(responseError?.data?.message, {\n duration: 2000,\n });\n }\n };\n if (listCategory?.length === 0) {\n getListCategory();\n }\n if (listSubject?.length === 0) {\n getAllSubject();\n }\n\n let marginRoot = window.innerHeight - 80 - 445 - 60 >= 20 ? (window.innerHeight - 80 - 445 - 60) / 2 : 10;\n\n\n\n return (\n
\n
\n
\n
\n \n \n \n
\n Kiến thức\n
\n \n
\n
\n
    \n {listCategory.map((category) => {\n return (\n
  • \n {\n history.push(\"/blog\", {\n category: category.setting_id,\n });\n }}\n >\n {\" \"}\n {category.setting_title}\n
\n \n );\n })}\n \n \n {\n window.location.href = \"/products\";\n }}\n >\n
Tất cả khóa học
\n \n {\n window.location.href = \"/combo\";\n }}\n >\n
Combo
\n \n {\n window.location.href = \"/lecturers\";\n }}\n >\n
Giảng viên
\n \n {listSubject.map((elment) => {\n return (\n {\n history.push(\"/products\", {\n category: elment?.id,\n });\n }}\n >\n
{elment?.name}
\n \n );\n })}\n \n
\n
\n
\n \n
\n
\n \n \n );\n}\n\nexport default OnlineCourses;"}}},{"rowIdx":1092526,"cells":{"text":{"kind":"string","value":"package dev.alexanastasyev.nirbackend.model;\n\nimport dev.alexanastasyev.nirbackend.util.lambda.DoubleGetter;\nimport dev.alexanastasyev.nirbackend.util.lambda.DoubleSetter;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Objects;\n\npublic class CustomerClusteringModel {\n\n private static final int EMPTY_VALUE = -1;\n\n /**\n * Идентификатор\n */\n private long id;\n\n /**\n * Год рождения\n */\n private double birthYear;\n\n /**\n * Образование\n */\n private double education;\n\n /**\n * Семейный статус\n */\n private double maritalStatus;\n\n /**\n * Доход\n */\n private double income;\n\n /**\n * Количество детей\n */\n private double childrenAmount;\n\n /**\n * Дата привлечения в компанию\n */\n private double enrollmentDate;\n\n /**\n * Количество дней с момента последней покупки\n */\n private double recency;\n\n /**\n * Есть ли жалобы за последние 2 года\n */\n private double complains;\n\n /**\n * Потрачено на вино за последние 2 года\n */\n private double wineAmount;\n\n /**\n * Потрачено на фрукты за последние 2 года\n */\n private double fruitsAmount;\n\n /**\n * Потрачено на мясо за последние 2 года\n */\n private double meatAmount;\n\n /**\n * Потрачено на рыбу за последние 2 года\n */\n private double fishAmount;\n\n /**\n * Потрачено на сладкое за последние 2 года\n */\n private double sweetAmount;\n\n /**\n * Потрачено на золото за последние 2 года\n */\n private double goldAmount;\n\n /**\n * Покупок по скидкам\n */\n private double discountPurchasesAmount;\n\n /**\n * Количество принятых рекламных кампаний\n */\n private double acceptedCampaignsAmount;\n\n /**\n * Количество покупок через сайт\n */\n private double webPurchasesAmount;\n\n /**\n * Количество покупок с помощью каталога\n */\n private double catalogPurchasesAmount;\n\n /**\n * Количество покупок непосредственно в магазине\n */\n private double storePurchasesAmount;\n\n /**\n * Посещений веб-сайта за последний месяц\n */\n private double websiteVisitsAmount;\n\n public CustomerClusteringModel() {\n }\n\n public CustomerClusteringModel(CustomerCSVModel csvModel) {\n extractId(csvModel.getId());\n extractBirthYear(csvModel.getBirthYear());\n extractEducation(csvModel.getEducation());\n extractMaritalStatus(csvModel.getMaritalStatus());\n extractIncome(csvModel.getIncome());\n extractChildrenAmount(csvModel.getKidsAmount(), csvModel.getTeensAmount());\n extractEnrollmentDate(csvModel.getEnrollmentDate());\n extractRecency(csvModel.getRecency());\n extractComplains(csvModel.getComplains());\n extractWineAmount(csvModel.getWineAmount());\n extractFruitsAmount(csvModel.getFruitsAmount());\n extractMeatAmount(csvModel.getMeatAmount());\n extractFishAmount(csvModel.getFishAmount());\n extractSweetAmount(csvModel.getSweetAmount());\n extractGoldAmount(csvModel.getGoldAmount());\n extractDiscountPurchasesAmount(csvModel.getDiscountPurchasesAmount());\n extractAcceptedCampaignsAmount(csvModel.getAcceptedCampaign1(), csvModel.getAcceptedCampaign2(),\n csvModel.getAcceptedCampaign3(), csvModel.getAcceptedCampaign4(), csvModel.getAcceptedCampaign5(),\n csvModel.getResponse());\n extractWebPurchasesAmount(csvModel.getWebPurchasesAmount());\n extractCatalogPurchasesAmount(csvModel.getCatalogPurchasesAmount());\n extractStorePurchasesAmount(csvModel.getStorePurchasesAmount());\n extractWebsiteVisitsAmount(csvModel.getVisitsAmount());\n }\n\n public CustomerClusteringModel(CustomerClusteringModel clusteringModel) {\n this.id = clusteringModel.getId();\n this.birthYear = clusteringModel.getBirthYear();\n this.education = clusteringModel.getEducation();\n this.maritalStatus = clusteringModel.getMaritalStatus();\n this.income = clusteringModel.getIncome();\n this.childrenAmount = clusteringModel.getChildrenAmount();\n this.enrollmentDate = clusteringModel.getEnrollmentDate();\n this.recency = clusteringModel.getRecency();\n this.complains = clusteringModel.getComplains();\n this.wineAmount = clusteringModel.getWineAmount();\n this.fruitsAmount = clusteringModel.getFruitsAmount();\n this.meatAmount = clusteringModel.getMeatAmount();\n this.fishAmount = clusteringModel.getFishAmount();\n this.sweetAmount = clusteringModel.getSweetAmount();\n this.goldAmount = clusteringModel.getGoldAmount();\n this.discountPurchasesAmount = clusteringModel.getDiscountPurchasesAmount();\n this.acceptedCampaignsAmount = clusteringModel.getAcceptedCampaignsAmount();\n this.webPurchasesAmount = clusteringModel.getWebPurchasesAmount();\n this.catalogPurchasesAmount = clusteringModel.getCatalogPurchasesAmount();\n this.storePurchasesAmount = clusteringModel.getStorePurchasesAmount();\n this.websiteVisitsAmount = clusteringModel.getWebsiteVisitsAmount();\n }\n\n public long getId() {\n return id;\n }\n\n public double getBirthYear() {\n return birthYear;\n }\n\n public void setBirthYear(double birthYear) {\n this.birthYear = birthYear;\n }\n\n public double getEducation() {\n return education;\n }\n\n public void setEducation(double education) {\n this.education = education;\n }\n\n public double getMaritalStatus() {\n return maritalStatus;\n }\n\n public void setMaritalStatus(double maritalStatus) {\n this.maritalStatus = maritalStatus;\n }\n\n public double getIncome() {\n return income;\n }\n\n public void setIncome(double income) {\n this.income = income;\n }\n\n public double getChildrenAmount() {\n return childrenAmount;\n }\n\n public void setChildrenAmount(double childrenAmount) {\n this.childrenAmount = childrenAmount;\n }\n\n public double getEnrollmentDate() {\n return enrollmentDate;\n }\n\n public void setEnrollmentDate(double enrollmentDate) {\n this.enrollmentDate = enrollmentDate;\n }\n\n public double getRecency() {\n return recency;\n }\n\n public void setRecency(double recency) {\n this.recency = recency;\n }\n\n public double getComplains() {\n return complains;\n }\n\n public void setComplains(double complains) {\n this.complains = complains;\n }\n\n public double getWineAmount() {\n return wineAmount;\n }\n\n public void setWineAmount(double wineAmount) {\n this.wineAmount = wineAmount;\n }\n\n public double getFruitsAmount() {\n return fruitsAmount;\n }\n\n public void setFruitsAmount(double fruitsAmount) {\n this.fruitsAmount = fruitsAmount;\n }\n\n public double getMeatAmount() {\n return meatAmount;\n }\n\n public void setMeatAmount(double meatAmount) {\n this.meatAmount = meatAmount;\n }\n\n public double getFishAmount() {\n return fishAmount;\n }\n\n public void setFishAmount(double fishAmount) {\n this.fishAmount = fishAmount;\n }\n\n public double getSweetAmount() {\n return sweetAmount;\n }\n\n public void setSweetAmount(double sweetAmount) {\n this.sweetAmount = sweetAmount;\n }\n\n public double getGoldAmount() {\n return goldAmount;\n }\n\n public void setGoldAmount(double goldAmount) {\n this.goldAmount = goldAmount;\n }\n\n public double getDiscountPurchasesAmount() {\n return discountPurchasesAmount;\n }\n\n public void setDiscountPurchasesAmount(double discountPurchasesAmount) {\n this.discountPurchasesAmount = discountPurchasesAmount;\n }\n\n public double getAcceptedCampaignsAmount() {\n return acceptedCampaignsAmount;\n }\n\n public void setAcceptedCampaignsAmount(double acceptedCampaignsAmount) {\n this.acceptedCampaignsAmount = acceptedCampaignsAmount;\n }\n\n public double getWebPurchasesAmount() {\n return webPurchasesAmount;\n }\n\n public void setWebPurchasesAmount(double webPurchasesAmount) {\n this.webPurchasesAmount = webPurchasesAmount;\n }\n\n public double getCatalogPurchasesAmount() {\n return catalogPurchasesAmount;\n }\n\n public void setCatalogPurchasesAmount(double catalogPurchasesAmount) {\n this.catalogPurchasesAmount = catalogPurchasesAmount;\n }\n\n public double getStorePurchasesAmount() {\n return storePurchasesAmount;\n }\n\n public void setStorePurchasesAmount(double storePurchasesAmount) {\n this.storePurchasesAmount = storePurchasesAmount;\n }\n\n public double getWebsiteVisitsAmount() {\n return websiteVisitsAmount;\n }\n\n public void setWebsiteVisitsAmount(double websiteVisitsAmount) {\n this.websiteVisitsAmount = websiteVisitsAmount;\n }\n\n @Override\n public String toString() {\n return \"CustomerClusteringModel{\" +\n \"id=\" + id +\n \", birthYear=\" + birthYear +\n \", education=\" + education +\n \", maritalStatus=\" + maritalStatus +\n \", income=\" + income +\n \", childrenAmount=\" + childrenAmount +\n \", enrollmentDate=\" + enrollmentDate +\n \", recency=\" + recency +\n \", complains=\" + complains +\n \", wineAmount=\" + wineAmount +\n \", fruitsAmount=\" + fruitsAmount +\n \", meatAmount=\" + meatAmount +\n \", fishAmount=\" + fishAmount +\n \", sweetAmount=\" + sweetAmount +\n \", goldAmount=\" + goldAmount +\n \", discountPurchasesAmount=\" + discountPurchasesAmount +\n \", acceptedCampaignsAmount=\" + acceptedCampaignsAmount +\n \", webPurchasesAmount=\" + webPurchasesAmount +\n \", catalogPurchasesAmount=\" + catalogPurchasesAmount +\n \", storePurchasesAmount=\" + storePurchasesAmount +\n \", websiteVisitsAmount=\" + websiteVisitsAmount +\n '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n CustomerClusteringModel that = (CustomerClusteringModel) o;\n return id == that.id && Double.compare(that.birthYear, birthYear) == 0 && Double.compare(that.education, education) == 0 && Double.compare(that.maritalStatus, maritalStatus) == 0 && Double.compare(that.income, income) == 0 && Double.compare(that.childrenAmount, childrenAmount) == 0 && Double.compare(that.enrollmentDate, enrollmentDate) == 0 && Double.compare(that.recency, recency) == 0 && Double.compare(that.complains, complains) == 0 && Double.compare(that.wineAmount, wineAmount) == 0 && Double.compare(that.fruitsAmount, fruitsAmount) == 0 && Double.compare(that.meatAmount, meatAmount) == 0 && Double.compare(that.fishAmount, fishAmount) == 0 && Double.compare(that.sweetAmount, sweetAmount) == 0 && Double.compare(that.goldAmount, goldAmount) == 0 && Double.compare(that.discountPurchasesAmount, discountPurchasesAmount) == 0 && Double.compare(that.acceptedCampaignsAmount, acceptedCampaignsAmount) == 0 && Double.compare(that.webPurchasesAmount, webPurchasesAmount) == 0 && Double.compare(that.catalogPurchasesAmount, catalogPurchasesAmount) == 0 && Double.compare(that.storePurchasesAmount, storePurchasesAmount) == 0 && Double.compare(that.websiteVisitsAmount, websiteVisitsAmount) == 0;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, birthYear, education, maritalStatus, income, childrenAmount, enrollmentDate, recency, complains, wineAmount, fruitsAmount, meatAmount, fishAmount, sweetAmount, goldAmount, discountPurchasesAmount, acceptedCampaignsAmount, webPurchasesAmount, catalogPurchasesAmount, storePurchasesAmount, websiteVisitsAmount);\n }\n\n public CustomerClusteringModel copy() {\n return new CustomerClusteringModel(this);\n }\n\n public void replaceEmptyFieldsWithAverage(CustomerClusteringModel average) {\n replaceIfEmpty(this::getBirthYear, this::setBirthYear, average.getBirthYear());\n replaceIfEmpty(this::getEducation, this::setEducation, average.getEducation());\n replaceIfEmpty(this::getMaritalStatus, this::setMaritalStatus, average.getMaritalStatus());\n replaceIfEmpty(this::getIncome, this::setIncome, average.getIncome());\n replaceIfEmpty(this::getChildrenAmount, this::setChildrenAmount, average.getChildrenAmount());\n replaceIfEmpty(this::getEnrollmentDate, this::setEnrollmentDate, average.getEnrollmentDate());\n replaceIfEmpty(this::getRecency, this::setRecency, average.getRecency());\n replaceIfEmpty(this::getComplains, this::setComplains, average.getComplains());\n replaceIfEmpty(this::getWineAmount, this::setWineAmount, average.getWineAmount());\n replaceIfEmpty(this::getFruitsAmount, this::setFruitsAmount, average.getFruitsAmount());\n replaceIfEmpty(this::getMeatAmount, this::setMeatAmount, average.getMeatAmount());\n replaceIfEmpty(this::getFishAmount, this::setFishAmount, average.getFishAmount());\n replaceIfEmpty(this::getSweetAmount, this::setSweetAmount, average.getSweetAmount());\n replaceIfEmpty(this::getGoldAmount, this::setGoldAmount, average.getGoldAmount());\n replaceIfEmpty(this::getDiscountPurchasesAmount, this::setDiscountPurchasesAmount, average.getDiscountPurchasesAmount());\n replaceIfEmpty(this::getAcceptedCampaignsAmount, this::setAcceptedCampaignsAmount, average.getAcceptedCampaignsAmount());\n replaceIfEmpty(this::getWebPurchasesAmount, this::setWebPurchasesAmount, average.getWebPurchasesAmount());\n replaceIfEmpty(this::getCatalogPurchasesAmount, this::setCatalogPurchasesAmount, average.getCatalogPurchasesAmount());\n replaceIfEmpty(this::getStorePurchasesAmount, this::setStorePurchasesAmount, average.getStorePurchasesAmount());\n replaceIfEmpty(this::getWebsiteVisitsAmount, this::setWebsiteVisitsAmount, average.getWebsiteVisitsAmount());\n }\n\n private void replaceIfEmpty(DoubleGetter getter, DoubleSetter setter, double value) {\n if (getter.getValue() == EMPTY_VALUE) {\n setter.setValue(value);\n }\n }\n\n private void extractId(String id) {\n if (id == null || id.isEmpty()) {\n this.id = EMPTY_VALUE;\n } else {\n this.id = Integer.parseInt(id);\n }\n }\n\n private void extractBirthYear(String birthYear) {\n extractDoubleValue(birthYear, this::setBirthYear);\n }\n\n private void extractEducation(String education) {\n if (\"Graduation\".equals(education)) {\n this.education = 0.5;\n } else if (\"Basic\".equals(education) || \"2n Cycle\".equals(education)) {\n this.education = 0;\n } else if (\"Master\".equals(education) || \"PhD\".equals(education)) {\n this.education = 1;\n } else {\n this.education = EMPTY_VALUE;\n }\n }\n\n private void extractMaritalStatus(String maritalStatus) {\n if (\"YOLO\".equals(maritalStatus) || \"Absurd\".equals(maritalStatus)\n || \"Alone\".equals(maritalStatus) || \"Widow\".equals(maritalStatus)\n || \"Divorced\".equals(maritalStatus)) {\n this.maritalStatus = 0;\n } else if (\"Together\".equals(maritalStatus) || \"Married\".equals(maritalStatus)) {\n this.maritalStatus = 1;\n } else {\n this.maritalStatus = EMPTY_VALUE;\n }\n }\n\n private void extractIncome(String income) {\n extractDoubleValue(income, this::setIncome);\n }\n\n private void extractChildrenAmount(String kidsAmount, String teensAmount) {\n if (kidsAmount == null || kidsAmount.isEmpty() || teensAmount == null || teensAmount.isEmpty()) {\n this.childrenAmount = EMPTY_VALUE;\n } else {\n this.childrenAmount = Double.parseDouble(kidsAmount) + Double.parseDouble(teensAmount);\n }\n }\n\n private void extractEnrollmentDate(String enrollmentDate) {\n try {\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"dd-MM-yyyy\");\n Date parsedDate = dateFormat.parse(enrollmentDate);\n this.enrollmentDate = parsedDate.getTime();\n } catch (Exception e) {\n this.enrollmentDate = EMPTY_VALUE;\n }\n }\n\n private void extractRecency(String recency) {\n extractDoubleValue(recency, this::setRecency);\n }\n\n private void extractComplains(String complains) {\n extractDoubleValue(complains, this::setComplains);\n }\n\n private void extractWineAmount(String wineAmount) {\n extractDoubleValue(wineAmount, this::setWineAmount);\n }\n\n private void extractFruitsAmount(String fruitsAmount) {\n extractDoubleValue(fruitsAmount, this::setFruitsAmount);\n }\n\n private void extractMeatAmount(String meatAmount) {\n extractDoubleValue(meatAmount, this::setMeatAmount);\n }\n\n private void extractFishAmount(String fishAmount) {\n extractDoubleValue(fishAmount, this::setFishAmount);\n }\n\n private void extractSweetAmount(String sweetAmount) {\n extractDoubleValue(sweetAmount, this::setSweetAmount);\n }\n\n private void extractGoldAmount(String goldAmount) {\n extractDoubleValue(goldAmount, this::setGoldAmount);\n }\n\n private void extractDiscountPurchasesAmount(String discountPurchasesAmount) {\n extractDoubleValue(discountPurchasesAmount, this::setDiscountPurchasesAmount);\n }\n\n private void extractAcceptedCampaignsAmount(String... acceptedCampaigns) {\n boolean valid = true;\n for (String campaign : acceptedCampaigns) {\n if (campaign == null || campaign.isEmpty()) {\n valid = false;\n break;\n }\n }\n if (valid) {\n double result = 0;\n for (String campaign : acceptedCampaigns) {\n result += Double.parseDouble(campaign);\n }\n this.acceptedCampaignsAmount = result;\n } else {\n this.acceptedCampaignsAmount = EMPTY_VALUE;\n }\n }\n\n private void extractWebPurchasesAmount(String webPurchasesAmount) {\n extractDoubleValue(webPurchasesAmount, this::setWebPurchasesAmount);\n }\n\n private void extractCatalogPurchasesAmount(String catalogPurchasesAmount) {\n extractDoubleValue(catalogPurchasesAmount, this::setCatalogPurchasesAmount);\n }\n\n private void extractStorePurchasesAmount(String storePurchasesAmount) {\n extractDoubleValue(storePurchasesAmount, this::setStorePurchasesAmount);\n }\n\n private void extractWebsiteVisitsAmount(String websiteVisitsAmount) {\n extractDoubleValue(websiteVisitsAmount, this::setWebsiteVisitsAmount);\n }\n\n private void extractDoubleValue(String value, DoubleSetter setter) {\n if (value == null || value.isEmpty()) {\n setter.setValue(EMPTY_VALUE);\n } else {\n setter.setValue(Double.parseDouble(value));\n }\n }\n}"}}},{"rowIdx":1092527,"cells":{"text":{"kind":"string","value":"import { doc, getDoc } from \"firebase/firestore\";\nimport { db } from \"../../firebaseConfig\";\n\n// This is an asynchronous function that fetches a specific node ID for a given store in a specific mall from Firebase Firestore.\n// Parameters:\n// currentMall - The name of the mall where the store is located.\n// storeName - The name of the store for which the node ID is to be fetched.\nexport default async function fetchNodeId(currentMall, storeName) {\n // Format the store name to create a node identifier (lowercase, spaces replaced with dashes, appended with '-node').\n const formattedStoreName = `${storeName\n .replace(/[^\\w\\s]/g, \"\")\n .replace(/\\s/g, \"-\")\n .toLowerCase()}-node`;\n\n // Create a document ID by concatenating the lowercase mall ID and the formatted store name.\n const documentID = `${currentMall.toLowerCase()}-${formattedStoreName}`;\n\n // Get a reference to the specific document (node) in the Firestore collection.\n const docRef = doc(db, \"malls\", currentMall, \"nodes\", documentID);\n\n // Fetch the document.\n const docSnap = await getDoc(docRef);\n\n // If the document exists, return the document ID. This is the node ID for the specified store.\n if (docSnap.exists()) {\n return docSnap.id;\n }\n\n // If the document does not exist (i.e., if the store name is invalid), throw an error.\n throw new Error(\"Invalid Store Name\");\n}"}}},{"rowIdx":1092528,"cells":{"text":{"kind":"string","value":"# JavaScript ES6 - let, const, arrow functions e template literals\n\n#### Conteúdo\nNeste bloco e no próximo, você vai aprender sobre a mais nova versão do *JavaScript*, conhecida como *ES6*, *ECMAScript 6* ou *ES2015*.\nEsses vários nomes podem gerar alguma dúvida, mas na verdade todos fazem referência à mesma linguagem. *JavaScript* é como nós chamamos a linguagem, só que esse nome é um **trademark** da Oracle. O nome oficial da linguagem é *ECMAScript*, e *ES* é apenas a abreviação (**E**CMA**S**cript).\nEssa nova versão possui alguns objetivos:\n* Ser uma linguagem melhor para construir aplicações complexas;\n* Resolver problemas antigos do JavaScript;\n* Facilitar o desenvolvimento de libraries.\nHoje você vai aprender quatro `features` do *ES6* que são muito importantes para que seu código fique limpo e bem escrito, além de resolverem alguns problemas da linguagem.\n* `let`;\n* `const`;\n* `arrow functions`;\n* `template literals`.\n\n#### Objetivo\n* Utilizar corretamente `let`;\n* Utilizar corretamente `const`;\n* Simplificar seu código com `arrow functions`;\n* Simplificar a construção de strings com `template literals`."}}},{"rowIdx":1092529,"cells":{"text":{"kind":"string","value":"import { Box, Button, Container, TextField, Typography } from \"@mui/material\";\nimport { Link, useNavigate } from \"react-router-dom\";\nimport styles from \"./style.module.css\";\nimport { getApiUrl } from \"utils/getApiUrl\";\nimport axios from \"axios\";\nimport { getAuthorizedOptions } from \"utils/getAuthorizedOptions\";\nimport { useState } from \"react\";\n\nconst API_ENDPOINT = `${getApiUrl()}/user-auth/verify-otp`;\n\nexport const ResetPasswordOtp = () => {\n const [isError, setError] = useState(false);\n const navigate = useNavigate();\n const handleSubmit = async (event) => {\n event.preventDefault();\n const formData = new FormData(event.currentTarget);\n if (!localStorage.getItem(\"email\")) {\n navigate(\"/\");\n }\n if(!formData.get(\"otp\")){\n setError(true)\n return\n }\n const otp = formData.get(\"otp\").toString();\n const data = {\n email: localStorage.getItem(\"email\"),\n otp_input: otp,\n };\n await axios\n .post(API_ENDPOINT, data)\n .then((res) => {\n setError(false);\n console.log(res);\n navigate(\"/reset-password\");\n })\n .catch((err) => {\n console.error(err);\n if(err.response.data === \"OTP is not valid\"){\n setError(true);\n }\n else {\n navigate(\"/\");\n }\n });\n };\n\n return (\n \n \n Reset Password\n \n We've sent you the OTP code. Insert your OTP code here\n \n \n
\n \n
\n \n
\n );\n};"}}},{"rowIdx":1092530,"cells":{"text":{"kind":"string","value":"Dot = class('Dot')\n\nfunction Dot:initialize(x, y, angle, speed, mass, directions, super, gigantic, repel)\n\tself.x = x\n\tself.y = y\n\tself.super = super or false -- if true, a large, immobile object\n\tself.gigantic = gigantic or false -- if true for a super object, then it is even larger\n\tself.directions = directions or 0 -- 0 means no restriction on angle of movement\n\tself.repel = repel or false\n\t\n\tself.lastX = x\n\tself.lastY = y\n\t\n\tif mass == 0 then\n\t\tlocal sizeFactor = math.random(1, 500)\n\t\tself.size = math.floor(sizeFactor/50)+5 * 2\n\t\tself.mass = mass or sizeFactor\n\telseif self.super then\n\t\tif gigantic then\n\t\t\tlocal sizeFactor = math.random(20000, 1000000)\n\t\t\tself.size = math.sqrt(math.floor(sizeFactor/100)) * 2\n\t\t\tself.mass = mass or sizeFactor\n\t\telse\n\t\t\tlocal sizeFactor = math.random(5000, 10000)\n\t\t\tself.size = (math.floor(sizeFactor/100)+5) * 2\n\t\t\tself.mass = mass or sizeFactor\n\t\tend\n\telse\n\t\tlocal sizeFactor = math.random(1, 2000)\n\t\tself.size = (math.floor(sizeFactor/150)+5) * 2\n\t\tself.mass = mass or sizeFactor\n\tend\n\t\n\tself.gx = 0\n\tself.gy = 0\n\tself.vx = 0\n\tself.vy = 0\n\t\n\tif not super then\n\t\tself.angle = angle\n\t\tself.speed = speed/50\n\t\t\n\t\tself.vx = math.cos(self.angle)*self.speed\n\t\tself.vy = math.sin(self.angle)*self.speed\n\tend\n\t\n\tself.color = {math.random(255), math.random(255), math.random(255)}\n\t\n\tif self.super then -- a super object has translucency\n\t\tself.color[4] = 150\n\tend\n\t\n\tself.destroy = false\nend\n\nfunction Dot:update(dt)\n\tself.vx = self.vx + self.gx\n\tself.vy = self.vy + self.gy\n\t\n\tself.angle = math.angle(0, 0, self.vx, self.vy)\n\tself.speed = math.sqrt(self.vx^2 + self.vy^2)\n\t\n\tif self.directions > 0 then -- calculate angle if limited\n\t\tself.angle = math.floor((self.angle/math.rad(360/self.directions)) + .5)*math.rad(360/self.directions)\n\tend\n\t\n\t-- used to disconnect the variables\n\tlocal lastX = self.x\n\tlocal lastY = self.y\n\t\n\tself.lastX = lastX\n\tself.lastY = lastY\n\t\n\tif not self.super then -- super objects will not move\n\t\tself.x = self.x + math.cos(self.angle)*self.speed\n\t\tself.y = self.y + math.sin(self.angle)*self.speed\n\tend\nend\n\nfunction Dot:draw()\n\tlocal alpha = 150\n\tif self.mass == 0 or self.gigantic then alpha = 255 end\n\tlove.graphics.setColor(self.color[1], self.color[2], self.color[3], alpha)\n\t\n\tif self.super then\n\t\tlove.graphics.circle('fill', self.x, self.y, self.size)\n\tend\n\t\n\tif self.angle then\n\t\tif not self.super then\n\t\t\tlocal w = self.size\n\t\t\tlocal h = self.speed -- the faster it is moving, the taller the object will be\n\t\t\tlove.graphics.polygon('fill', self.x + math.cos(self.angle - math.rad(90))*w, self.y + math.sin(self.angle - math.rad(90))*w, \n\t\t\t\t\t\t\t\t\t\t\t\t self.x + math.cos(self.angle + math.rad(90))*w, self.y + math.sin(self.angle + math.rad(90))*w,\n\t\t\t\t\t\t\t\t\t\t\t\t self.x + math.cos(self.angle)*h, self.y + math.sin(self.angle)*h)\n\t\tend\n\tend\nend"}}},{"rowIdx":1092531,"cells":{"text":{"kind":"string","value":"

\n\n

Solution

\n \n ``` c++ \n \n // Time Complexity of everything O(N)\n struct Node {\n Node* links[26];\n int cntPrefix=0;\n int cntEndsWith=0;\n \n bool containsKey(char ch)\n {\n return links[ch-'a']!=NULL;\n }\n\n void put(char ch,Node* node){\n links[ch-'a']=node;\n }\n Node* get(char ch)\n {\n return links[ch-'a'];\n }\n //for checking if the word is completed or not\n void increaseWordCnt()\n {\n cntEndsWith++;\n }\n void increasePrefix(){\n cntPrefix++;\n }\n void deleteWord(){\n cntEndsWith--;\n }\n void reducePrefixCnt(){\n cntPrefix--;\n }\n };\nclass Trie{\n Node* root;\n public:\n\n Trie(){\n root= new Node();\n }\n\n void insert(string &word){\n Node* node =root;\n \n for(int i=0;icontainsKey(word[i]))\n {\n node->put(word[i],new Node());\n }\n node =node->get(word[i]);\n node->increasePrefix();\n \n }\n node->increaseWordCnt();\n }\n\n int countWordsEqualTo(string &word){\n Node* node =root;\n \n for(int i=0;icontainsKey(word[i]))\n {\n node = node->get(word[i]);\n }\n else\n {\n return 0;\n }\n }\n return node->cntEndsWith;\n }\n\n int countWordsStartingWith(string &word){\n Node* node =root;\n for(int i=0;icontainsKey(word[i]))\n {\n node = node->get(word[i]);\n }\n else\n {\n return 0;\n }\n }\n return node->cntPrefix;\n }\n\n void erase(string &word){\n Node* node =root;\n for(int i=0;i containsKey(word[i])){\n node = node -> get(word[i]);\n node -> reducePrefixCnt();\n }else{\n return;\n }\n }\n node->deleteWord();\n }\n};\n\n ```\n"}}},{"rowIdx":1092532,"cells":{"text":{"kind":"string","value":"import { useContext, useState } from 'react';\nimport { Alert, Image, StyleSheet, View } from 'react-native';\nimport { launchCameraAsync, useCameraPermissions, PermissionStatus } from 'expo-image-picker';\nimport { GlobalContext } from '../../store/GlobalProvider';\nimport { globalStyles } from '../../theme';\nimport { Button } from '../Buttons';\nimport { Text } from '../Text';\n\nexport const ImagePicker = () => {\n const { theme } = useContext(GlobalContext);\n const [cameraPermissionInfo, requestPermission] = useCameraPermissions();\n const [pickedImage, setPickedImage] = useState(null);\n\n const verifyPermission = async () => {\n if (cameraPermissionInfo.status === PermissionStatus.UNDETERMINED) {\n const permissionRes = await requestPermission();\n\n return permissionRes.granted;\n }\n\n if (cameraPermissionInfo.status === PermissionStatus.DENIED) {\n Alert.alert('Insufficient Permissions!', 'You need to grant camera permissions to use this app.');\n\n return false;\n }\n\n return true;\n };\n\n const takeImageHandler = async () => {\n const hasPermission = await verifyPermission();\n\n if (!hasPermission) {\n return;\n }\n\n const image = await launchCameraAsync({\n allowsEditing: true,\n aspect: [16, 9],\n quality: 0.5,\n });\n\n setPickedImage(image);\n };\n\n return (\n <>\n \n {!pickedImage?.uri ? (\n No image taken yet.\n ) : (\n \n )}\n \n\n \n \n );\n};\n\nconst styles = StyleSheet.create({\n imagePreview: {\n width: '100%',\n height: 200,\n marginVertical: 8,\n justifyContent: 'center',\n alignItems: 'center',\n borderRadius: globalStyles.borderRadius,\n overflow: 'hidden',\n },\n image: {\n width: '100%',\n height: '100%',\n },\n});"}}},{"rowIdx":1092533,"cells":{"text":{"kind":"string","value":"import React from \"react\";\nimport s from './Post.module.css';\nimport userPhoto from \"../../../../assets/img/user.png\";\nimport {Button, Col, Divider, Row, Typography} from \"antd\";\nimport {LikeOutlined, LikeFilled, CloseOutlined} from \"@ant-design/icons\";\n\nconst {Text} = Typography\n\ntype PropsType = {\n setLiked: (postId: number) => void\n setUnLiked: (postId: number) => void\n deletePost: (postId: number) => void\n message: string\n likesCount: number\n isLiked: boolean\n id: number\n}\n\nconst Post: React.FC = (props) => {\n return
\n \n \n \"\"/\n \n \n
\n {props.message}\n
\n
\n {props.isLiked ? \n : }\n
\n \n \n props.deletePost(props.id)}/>\n \n
\n \n
\n}\n\nexport default Post;"}}},{"rowIdx":1092534,"cells":{"text":{"kind":"string","value":"14154\nwww.ics.uci.edu/~dock/manuals/oechem/cplusprog/node41.html\n4.4.3 Use of the conformers as first-class objects OEChem - C++ Theory Manual Version 1.3.1 Previous: 4.4.2 Use of the Up: 4.4 Properties of Multi-Conformer Next: 5. Traversing the Atoms, 4.4.3 Use of the conformers as first-class objects Alternatively, a programmer may wish to use the conformers as first class objects rather than via the state of the OEMCMolBase. This allows one to have multiple conformation objects at once and to treat the OEMCMolBase as a container of single-conformer molecules. The example below shows the use of the conformers as first class objects. Each conformer is represented by an OEConfBase which inherits from the OEMolBase object. Thus, each conformer can be treated as an independent molecule with respect to its coordinates as shown in the example code below. #include \"oechem.h\"\n#include \n\nusing namespace OEChem;\nusing namespace OESystem;\nusing namespace std;\n\nfloat GetMaxX(const OEMolBase &mol)\n{\n OEIter atom;\n float xyz[3];\n float maxX = 0.0f;\n bool first = true;\n for(atom = mol.GetAtoms();atom;++atom)\n {\n mol.GetCoords(atom,xyz);\n if(first)\n {\n maxX = xyz[0];\n first = false;\n }\n else\n if(xyz[0] > maxX)\n maxX = xyz[0];\n }\n return maxX;\n}\n\nint main(int, char ** argv)\n{\n OEIter mol;\n OEIter conf;\n\n oemolistream ims(argv[1]);\n\n std::string maxconf;\n float tmpx = 0.0f, maxX = 0.0f;\n\n for (mol=ims.GetMCMolBases(); mol; ++mol)\n {\n for(conf = mol->GetConfs(); conf; ++conf)\n {\n tmpx = GetMaxX(*conf);\n if(tmpx > maxX)\n {\n if(!maxconf.empty())\n {\n cerr << conf->GetTitle() << \" has a larger value of x than \" <<\n maxconf << endl;\n }\n maxconf = conf->GetTitle();\n maxX = tmpx;\n }\n }\n }\n\n return 0;\n}\n Download as text. In the listing above, the function GetMaxX returns the maximum x-coordinate of a molecule. The main routine loops over all of the conformers of each molecule and compares the maximum x-coordinate to a running maximum of the x-coordinate of every conformer. If there is a new maximum, the associated conformer is stored and the user is notified via cerr. OEChem - C++ Theory Manual Version 1.3.1 Previous: 4.4.2 Use of the Up: 4.4 Properties of Multi-Conformer Next: 5. Traversing the Atoms, Documentation released on July 30, 2004."}}},{"rowIdx":1092535,"cells":{"text":{"kind":"string","value":"//jshint esversion:6\n\nconst express = require('express');\nconst bodyParser = require('body-parser');\nconst ejs = require('ejs');\nconst mongoose = require('mongoose');\n\n\nconst app = new express();\napp.use(express.static(\"public\"));\napp.use(bodyParser.urlencoded({extended:true}));\n\nmongoose.connect(\"mongodb://localhost:27017/userDB\");\n\nconst userSchema = {\n \"email\": String,\n \"password\": String\n}\n\nconst User = mongoose.model(\"User\",userSchema);\n\napp.set('view engine', 'ejs');\n\napp.get('/',function(req,res){\n res.render('home');\n})\n\napp.get('/register',function(req,res){\n res.render('register');\n})\n\napp.get('/login',function(req,res){\n res.render('login');\n})\n\napp.post('/register', function(req,res){\n const email1 = req.body.username;\n const password1 = req.body.password;\n // console.log(email);\n // console.log(password);\n\n const newUser = new User({\n email: email1,\n password : password1\n })\n\n newUser.save(function(err){\n if(err){\n console.log(err);\n }\n else{\n res.render(\"secrets\");\n }\n }) \n\n})\n\napp.post('/login', function(req,res){\n const email1 = req.body.username;\n const password1 = req.body.password;\n // console.log(email);\n // console.log(password);\n \n User.findOne({email:email1},function(err,foundUser){\n if(err){\n console.log(err);\n }\n if(foundUser){\n if(foundUser.password === password1){\n res.render(\"secrets\");\n }\n else{\n res.render(\"Wrong-pass\");\n }\n }\n }) \n\n})\n\n\napp.listen(3000,function(){\n console.log(\"Server is running on port 3000\");\n})"}}},{"rowIdx":1092536,"cells":{"text":{"kind":"string","value":"\n\n\n \n \n \n \n Administration\n\n\n \n\n
\n
\n
\n\n
\n \n
\n

User edit:

\n
\n \n
\n \n
\n
\n\n
\n \n
\n \n
\n
\n\n
\n \n
\n \n
\n
\n\n
\n \n
\n \n
\n
\n\n
\n \n
\n \n
\n
\n\n
\n \n
\n \n
\n
\n\n
\n \n
\n \n
\n
\n\n
\n \n
\n \n \n \n
\n
\n\n
\n \n
\n
\n
\n\n\n
\n
\n
\n\n \n \n\n"}}},{"rowIdx":1092537,"cells":{"text":{"kind":"string","value":"import { cn } from '@/utils';\nimport { TouchableOpacity, View } from 'react-native';\nimport { Text } from './Text';\nimport { MaterialCommunityIcons } from '@expo/vector-icons';\nimport React from 'react';\n\ninterface TableProps extends React.ComponentPropsWithoutRef {\n header?: string;\n headerClassName?: string;\n children: React.ReactNode | React.ReactNode[];\n}\n\nconst Table = ({\n children,\n className,\n headerClassName,\n ...props\n}: TableProps) => {\n const enhancedChildren = React.Children.map(children, (child, i) => {\n const isLastChild = i === React.Children.count(children) - 1;\n if (React.isValidElement(child)) {\n return React.cloneElement(child, {\n // @ts-ignore\n isLastChild,\n });\n }\n return child;\n });\n return (\n <>\n {props.header && (\n \n {props.header}\n \n )}\n\n \n {enhancedChildren}\n \n \n );\n};\n\n// create type for TableRow omiting children and adding the following props: title, elementLeft, elementRight, description\n\ninterface TableRowProps\n extends React.ComponentPropsWithoutRef {\n title: string;\n elementLeft?: React.ReactNode;\n elementRight?: React.ReactNode;\n description?: string;\n isLastChild?: boolean;\n}\nconst TableRow = ({ className, isLastChild, ...props }: TableRowProps) => {\n return (\n \n {props.elementLeft && {props.elementLeft}}\n \n \n \n {props.title}\n \n \n {props.description && (\n \n \n {props.description}\n \n \n )}\n \n {props.elementRight ? (\n {props.elementRight}\n ) : (\n \n \n \n )}\n \n );\n};\n\nexport { Table, TableRow };"}}},{"rowIdx":1092538,"cells":{"text":{"kind":"string","value":"use axum::{http::StatusCode, response::IntoResponse};\nuse derive_more::From;\n\npub type Result = core::result::Result;\n\n#[derive(Debug, From)]\npub enum Error {\n #[from]\n Custom(String),\n\n #[from]\n Zoho(crate::zoho::Error),\n\n // -- Externals\n #[from]\n Io(std::io::Error), // as example\n\n #[from]\n Config(config::ConfigError),\n\n #[from]\n Sqlx(sqlx::Error),\n\n #[from]\n Reqwest(reqwest::Error),\n\n #[from]\n Chrono(chrono::ParseError),\n\n #[from]\n SerdeJson(serde_json::Error),\n}\n\n// region: --- Custom\n\nimpl Error {\n pub fn custom(val: impl std::fmt::Display) -> Self {\n Self::Custom(val.to_string())\n }\n}\n\nimpl From<&str> for Error {\n fn from(val: &str) -> Self {\n Self::Custom(val.to_string())\n }\n}\n\nimpl IntoResponse for Error {\n fn into_response(self) -> axum::response::Response {\n tracing::error!(\"{self:?}\");\n tracing::error!(\"<-- 500\");\n\n (StatusCode::INTERNAL_SERVER_ERROR, \"Internal Server Error\").into_response()\n }\n}\n\n// endregion: --- Custom\n\n// region: --- Error Boilerplate\n\nimpl core::fmt::Display for Error {\n fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {\n write!(fmt, \"{self:?}\")\n }\n}\n\nimpl std::error::Error for Error {}\n\n// endregion: --- Error Boilerplate"}}},{"rowIdx":1092539,"cells":{"text":{"kind":"string","value":"format();\n }\n\n if ($identifier instanceof FileExtension) {\n return $identifier->format();\n }\n\n try {\n $format = MediaType::from(strtolower($identifier))->format();\n } catch (Error) {\n try {\n $format = FileExtension::from(strtolower($identifier))->format();\n } catch (Error) {\n throw new NotSupportedException('Unable to create format from \"' . $identifier . '\".');\n }\n }\n\n return $format;\n }\n\n /**\n * Return the possible media (MIME) types for the current format\n *\n * @return array\n */\n public function mediaTypes(): array\n {\n return array_filter(MediaType::cases(), function ($mediaType) {\n return $mediaType->format() === $this;\n });\n }\n\n /**\n * Return the possible file extension for the current format\n *\n * @return array\n */\n public function fileExtensions(): array\n {\n return array_filter(FileExtension::cases(), function ($fileExtension) {\n return $fileExtension->format() === $this;\n });\n }\n\n /**\n * Create an encoder instance that matches the format\n *\n * @param array $options\n * @return EncoderInterface\n */\n public function encoder(mixed ...$options): EncoderInterface\n {\n return match ($this) {\n self::AVIF => new AvifEncoder(...$options),\n self::BMP => new BmpEncoder(...$options),\n self::GIF => new GifEncoder(...$options),\n self::HEIC => new HeicEncoder(...$options),\n self::JP2 => new Jpeg2000Encoder(...$options),\n self::JPEG => new JpegEncoder(...$options),\n self::PNG => new PngEncoder(...$options),\n self::TIFF => new TiffEncoder(...$options),\n self::WEBP => new WebpEncoder(...$options),\n };\n }\n}"}}},{"rowIdx":1092540,"cells":{"text":{"kind":"string","value":"import { screen, render } from '@testing-library/react';\nimport { rest } from 'msw';\nimport { setupServer } from 'msw/node';\nimport { MemoryRouter, Routes, Route } from 'react-router-dom';\nimport Detail from './';\n\ndescribe('Detail component', () => {\n it('Should render the container', () => {\n render(\n \n \n \n );\n\n const container = screen.getByTestId('detail');\n expect(container).toBeInTheDocument();\n });\n\n it('Should display the loading wheel when loading', () => {\n render(\n \n \n \n );\n\n const loadingWheel = screen.getByTestId('loading-wheel');\n expect(loadingWheel).toBeInTheDocument();\n });\n\n it('Should display an error message if there is API error', async () => {\n const server = setupServer(\n rest.get('http://localhost:3001/books/test', (req, res, ctx) => {\n return res(ctx.status(400));\n })\n );\n\n server.listen();\n\n render(\n \n \n } />\n \n \n );\n\n const error = await screen.findByText(/Failed to load book/);\n expect(error).toBeInTheDocument();\n\n server.close();\n });\n\n it('Should display API detail card information when API response is successful', async () => {\n const server = setupServer(\n rest.get('http://localhost:3001/books/test', (req, res, ctx) => {\n return res(ctx.json({\n author: 'test author',\n publisher: 'test publisher',\n city: 'test city',\n format: 'test format',\n year: 'test year', \n isbn: 'test isbn',\n title: 'test title',\n type: 'fiction',\n }));\n }),\n );\n\n server.listen();\n\n render(\n \n \n } />\n \n \n );\n\n const details = await screen.findAllByRole('heading');\n\n expect(details[0]).toHaveTextContent('test title');\n\n expect(details[1]).toHaveTextContent('AUTHOR');\n expect(details[2]).toHaveTextContent('test author');\n\n expect(details[3]).toHaveTextContent('PUBLISHER');\n expect(details[4]).toHaveTextContent('test publisher');\n\n expect(details[5]).toHaveTextContent('CITY');\n expect(details[6]).toHaveTextContent('test city');\n\n expect(details[7]).toHaveTextContent('FORMAT');\n expect(details[8]).toHaveTextContent('test format');\n\n expect(details[9]).toHaveTextContent('YEAR');\n expect(details[10]).toHaveTextContent('test year');\n\n expect(details[11]).toHaveTextContent('ISBN');\n expect(details[12]).toHaveTextContent('test isbn');\n\n server.close()\n });\n});"}}},{"rowIdx":1092541,"cells":{"text":{"kind":"string","value":"\"\"\"online_judge URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.urls import path,include\nfrom django.views.generic.base import TemplateView\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('problem/',include('problem.urls')),\n path('submission/',include('submissions.urls')),\n ### provides signup\n path('accounts/',include('accounts.urls')), \n ### provides login,logout\n path('accounts/',include('django.contrib.auth.urls')), \n ### profile links added\n path('profile/', include('profiles.urls')),\n ### home page for the time being\n path('',TemplateView.as_view(template_name='registration/home.html'),name='home'),\n \n\n]\nif settings.DEBUG : \n urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)"}}},{"rowIdx":1092542,"cells":{"text":{"kind":"string","value":"from django.db import models\n\n\nclass Bb(models.Model):\n title = models.CharField(max_length=50)\n content = models.TextField(null=True, blank=True)\n price = models.FloatField(null=True, blank=True)\n published = models.DateTimeField(auto_now_add=True, db_index=True)\n rubric = models.ForeignKey('Rubric', null=True, on_delete=models.PROTECT, verbose_name='Рубрика')\n\n class Meta:\n verbose_name_plural = 'Объявления'\n verbose_name = 'Объявление'\n ordering = ['-published']\n\n\nclass Rubric(models.Model):\n name = models.CharField(max_length=20, db_index=True,\n verbose_name='Название')\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = 'Рубрики'\n verbose_name = 'Рубрика'\n ordering = ['name']"}}},{"rowIdx":1092543,"cells":{"text":{"kind":"string","value":"'use strict';\n\nclass Node {\n constructor(value) {\n this.value = value;\n this.next = null;\n }\n}\n\nclass LinkedList {\n constructor() {\n this.head = null;\n }\n append(value) {\n const node = new Node(value);\n if (!this.head) {\n this.head = node;\n return;\n }\n let current = this.head;\n while (current.next) {\n current = current.next;\n }\n current.next = node;\n }\n\n values() {\n let values = [];\n let current = this.head;\n while (current) {\n values.push(current.value);\n current = current.next;\n }\n return values;\n }\n}\n\nclass Hashmap {\n constructor(size) {\n this.size = size;\n this.map = new Array(size);\n }\n\n set(key, value) {\n const asciiCodeSum = key.split(\"\").reduce((sum, element) => {\n return sum + element.charCodeAt();\n }, 0);\n const multiPrime = asciiCodeSum * 599;\n const index = multiPrime % this.size;\n // return index;\n if (!this.map[index]) {\n this.map[index] = new LinkedList();\n }\n this.map[index].append({\n [key]: value\n });\n }\n\n get(key) {\n const idx = this.hash(key);\n const bucket = this.map[idx];\n // console.log(bucket);\n if (bucket) {\n let current = bucket.head;\n while (current) {\n if (current.value[key]) {\n // console.log(current.value[key]);\n return current.value[key];\n }\n current = current.next;\n }\n return null;\n } else {\n return null;\n }\n }\n\n contains(key) {\n const idx = this.hash(key);\n const bucket = this.map[idx];\n if (bucket) {\n let current = bucket.head;\n while (current) {\n if (current.value[key]) {\n // console.log(current.value[key]);\n return true;\n }\n current = current.next;\n }\n return false;\n } else {\n return false;\n }\n }\n\n keys() {\n let keys = [];\n this.map.map((e) => {\n let current = e.head;\n while (current) {\n keys.push(Object.keys(current.value));\n current = current.next;\n }\n });\n return keys;\n }\n\n hash(key) {\n const asciicodeSum = key.split('').reduce((acc, cur) => {\n return acc + cur.charCodeAt(0);\n }, 0);\n const multiPrime = asciicodeSum * 599;\n const index = multiPrime % this.size;\n // console.log(index);\n return index;\n }\n}\n\nconst myhashmap = new Hashmap(10);\nmyhashmap.set('esam', '401d15 student');\nmyhashmap.set('ahmad', '401d15 student');\nmyhashmap.set('mohamad', '401d15 student');\nmyhashmap.set('samah', '401d15 student');\nmyhashmap.set('laith', '401d15 student');\nmyhashmap.set('shihab', '401d15 student');\n\nmyhashmap.get('esam');\nmyhashmap.get('laith');\nmyhashmap.get('eee');\n\nconsole.log(myhashmap.contains('laith'));\nconsole.log(myhashmap.contains('eee'));\n\nconsole.log('ppppppppppppppppp', myhashmap.get('esam'));\n\nconsole.log('jjjjjjjjjjjjj', myhashmap.keys());\n\n// console.log(myhashmap.map[8]);\n// console.log(myhashmap.map[8].head.next);\n\n// console.log(myhashmap);\n// myhashmap.map.forEach((ll) => {\n// console.log(ll.values());\n// });\n\nmodule.exports = Hashmap;"}}},{"rowIdx":1092544,"cells":{"text":{"kind":"string","value":"// Submit this file with other files you created.\n// Do not touch port declarations of the module 'CPU'.\n\n// Guidelines\n// 1. It is highly recommened to `define opcodes and something useful.\n// 2. You can modify modules (except InstMemory, DataMemory, and RegisterFile)\n// (e.g., port declarations, remove modules, define new modules, ...)\n// 3. You might need to describe combinational logics to drive them into the module (e.g., mux, and, or, ...)\n// 4. `include files if required\n\nmodule CPU(input reset, // positive reset signal\n input clk, // clock signal\n output is_halted); // Whehther to finish simulation\n /***** Wire declarations *****/\n wire [31:0] next_pc;\n wire [31:0] current_pc;\n wire [31:0] inst;\n wire [31:0] rd_din;\n wire [31:0] rs1_dout;\n wire [31:0] rs2_dout;\n wire [31:0] imm_gen_out;\n wire [31:0] alu_result;\n wire [31:0] mem_dout;\n wire alu_bcond; // TODO: will be used at control flow instruction feature\n wire reg_write;\n wire mem_read;\n wire mem_write;\n wire mem_to_reg;\n wire pc_to_reg; // TODO: will be used at control flow instruction feature\n wire is_ecall;\n wire [3:0] alu_op;\n wire alu_src;\n wire stall;\n wire [1:0] forward_a;\n wire [1:0] forward_b;\n wire [31:0] forwarded_rs2_data;\n wire [31:0] alu_in_1;\n wire [31:0] alu_in_2;\n /***** Register declarations *****/\n // You need to modify the width of registers\n // In addition, \n // 1. You might need other pipeline registers that are not described below\n // 2. You might not need registers described below\n /***** IF/ID pipeline registers *****/\n reg [31:0] IF_ID_inst; // will be used in ID stage\n /***** ID/EX pipeline registers *****/\n // From the control unit\n reg ID_EX_alu_src; // will be used in EX stage\n reg ID_EX_mem_write; // will be used in MEM stage\n reg ID_EX_mem_read; // will be used in MEM stage\n reg ID_EX_mem_to_reg; // will be used in WB stage\n reg ID_EX_reg_write; // will be used in WB stage\n reg ID_EX_halt_cpu; // will be used in WB stage\n // From others\n reg [31:0] ID_EX_rs1_data;\n reg [31:0] ID_EX_rs2_data;\n reg [31:0] ID_EX_imm;\n reg [31:0] ID_EX_ALU_ctrl_unit_input;\n reg [4:0] ID_EX_rs1;\n reg [4:0] ID_EX_rs2;\n reg [4:0] ID_EX_rd;\n\n /***** EX/MEM pipeline registers *****/\n // From the control unit\n reg EX_MEM_mem_write; // will be used in MEM stage\n reg EX_MEM_mem_read; // will be used in MEM stage\n reg EX_MEM_mem_to_reg; // will be used in WB stage\n reg EX_MEM_reg_write; // will be used in WB stage\n reg EX_MEM_halt_cpu; // will be used in WB stage\n // From others\n reg [31:0] EX_MEM_alu_out;\n reg [31:0] EX_MEM_dmem_data;\n reg [4:0] EX_MEM_rd;\n\n /***** MEM/WB pipeline registers *****/\n // From the control unit\n reg MEM_WB_mem_to_reg; // will be used in WB stage\n reg MEM_WB_reg_write; // will be used in WB stage\n reg MEM_WB_halt_cpu; // will be used in WB stage\n // From others\n reg [31:0] MEM_WB_mem_to_reg_src_1;\n reg [31:0] MEM_WB_mem_to_reg_src_2;\n reg [4:0] MEM_WB_rd;\n\n // TODO: should be change when control flow instruction implemented\n Adder pc_adder (\n .in1(current_pc),\n .in2(32'd4),\n .dout(next_pc)\n );\n\n // ---------- Update program counter ----------\n // PC must be updated on the rising edge (positive edge) of the clock. \n PC pc(\n .reset(reset), // input (Use reset to initialize PC. Initial value must be 0)\n .clk(clk), // input\n .pc_write(!stall), // input\n .next_pc(next_pc), // input\n .current_pc(current_pc) // output\n );\n\n // ---------- Instruction Memory ----------\n InstMemory imem(\n .reset(reset), // input\n .clk(clk), // input\n .addr(current_pc), // input\n .dout(inst) // output\n );\n\n // Update IF/ID pipeline registers here\n always @(posedge clk) begin\n if (reset) begin\n IF_ID_inst <= 0;\n end\n else begin\n if (!stall) begin\n IF_ID_inst <= inst;\n end\n end\n end\n\n // ---------- Hazard Detection Unit ----------\n HazardDetectionUnit hazard_detection_unit (\n .reg_write_ex (ID_EX_reg_write), // input\n .reg_write_mem (EX_MEM_reg_write), // input\n .mem_read_ex (ID_EX_mem_read), // input\n .opcode_id (IF_ID_inst[6:0]), // input\n .rs1_id (is_ecall ? 5'b10001 : IF_ID_inst[19:15]), // input\n .rs2_id (IF_ID_inst[24:20]), // input\n .rd_ex (ID_EX_rd), // input\n .rd_mem (EX_MEM_rd), // input\n .stall (stall) // output\n );\n\n // ---------- Register File ----------\n RegisterFile reg_file (\n .reset (reset), // input\n .clk (clk), // input\n .rs1 (is_ecall ? 5'b10001 : IF_ID_inst[19:15]), // input\n .rs2 (IF_ID_inst[24:20]), // input\n .rd (MEM_WB_rd), // input\n .rd_din (rd_din), // input\n .write_enable (MEM_WB_reg_write), // input\n .rs1_dout (rs1_dout), // output\n .rs2_dout (rs2_dout) // output\n );\n\n\n // ---------- Control Unit ----------\n ControlUnit ctrl_unit (\n .part_of_inst(IF_ID_inst[6:0]), // input\n .mem_read(mem_read), // output\n .mem_to_reg(mem_to_reg), // output\n .mem_write(mem_write), // output\n .alu_src(alu_src), // output\n .write_enable(reg_write), // output\n .pc_to_reg(pc_to_reg), // output\n .is_ecall(is_ecall) // output (ecall inst)\n );\n\n // ---------- Immediate Generator ----------\n ImmediateGenerator imm_gen(\n .inst(IF_ID_inst), // input\n .imm_gen_out(imm_gen_out) // output\n );\n\n // Update ID/EX pipeline registers here\n always @(posedge clk) begin\n if (reset) begin\n ID_EX_alu_src <= 0;\n ID_EX_mem_write <= 0;\n ID_EX_mem_read <= 0;\n ID_EX_mem_to_reg <= 0;\n ID_EX_reg_write <= 0;\n ID_EX_halt_cpu <= 0;\n\n ID_EX_rs1_data <= 0;\n ID_EX_rs2_data <= 0;\n ID_EX_imm <= 0;\n ID_EX_ALU_ctrl_unit_input <= 0;\n ID_EX_rd <= 0;\n end\n else begin\n ID_EX_alu_src <= alu_src;\n ID_EX_mem_write <= stall ? 0 : mem_write;\n ID_EX_mem_read <= mem_read;\n ID_EX_mem_to_reg <= mem_to_reg;\n ID_EX_reg_write <= stall ? 0 : reg_write;\n ID_EX_halt_cpu <= stall ? 0 : (is_ecall && rs1_dout == 10);\n\n ID_EX_rs1_data <= rs1_dout;\n ID_EX_rs2_data <= rs2_dout;\n ID_EX_imm <= imm_gen_out;\n ID_EX_ALU_ctrl_unit_input <= IF_ID_inst;\n ID_EX_rs1 <= IF_ID_inst[19:15];\n ID_EX_rs2 <= IF_ID_inst[24:20];\n ID_EX_rd <= IF_ID_inst[11:7];\n end\n end\n\n // Mux for alu_in_2\n Mux2To1 alu_in_2_mux(\n .din0(forwarded_rs2_data),\n .din1(ID_EX_imm),\n .sel(ID_EX_alu_src),\n .dout(alu_in_2)\n );\n\n // Mux for rs1 data forwarding\n Mux4To1 rs1_data_forward_mux(\n .din0 (ID_EX_rs1_data),\n .din1 (EX_MEM_alu_out),\n .din2 (rd_din),\n .din3 (32'b0),\n .sel (forward_a),\n .dout (alu_in_1)\n );\n\n // Mux for rs2 data forwarding\n Mux4To1 rs2_data_forward_mux(\n .din0 (ID_EX_rs2_data),\n .din1 (EX_MEM_alu_out),\n .din2 (rd_din),\n .din3 (32'b0),\n .sel (forward_b),\n .dout (forwarded_rs2_data)\n );\n\n ForwardingUnit forwarding_unit (\n .reg_write_mem (EX_MEM_reg_write), // input\n .reg_write_wb (MEM_WB_reg_write), // input\n .rs1_ex (ID_EX_rs1), // input\n .rs2_ex (ID_EX_rs2), // input\n .rd_mem (EX_MEM_rd), // input\n .rd_wb (MEM_WB_rd), // input\n .forward_a (forward_a), // output\n .forward_b (forward_b) // output\n );\n\n // ---------- ALU Control Unit ----------\n ALUControlUnit alu_ctrl_unit (\n .inst(ID_EX_ALU_ctrl_unit_input), // input\n .alu_op(alu_op) // output\n );\n\n // ---------- ALU ----------\n ALU alu (\n .alu_op(alu_op), // input\n .alu_in_1(alu_in_1), // input \n .alu_in_2(alu_in_2), // input\n .alu_result(alu_result), // output\n .alu_bcond(alu_bcond) // output\n );\n\n // Update EX/MEM pipeline registers here\n always @(posedge clk) begin\n if (reset) begin\n EX_MEM_mem_write <= 0;\n EX_MEM_mem_read <= 0;\n EX_MEM_mem_to_reg <= 0;\n EX_MEM_reg_write <= 0;\n EX_MEM_halt_cpu <= 0;\n\n EX_MEM_alu_out <= 0;\n EX_MEM_dmem_data <= 0;\n EX_MEM_rd <= 0;\n end\n else begin\n EX_MEM_mem_write <= ID_EX_mem_write;\n EX_MEM_mem_read <= ID_EX_mem_read;\n EX_MEM_mem_to_reg <= ID_EX_mem_to_reg;\n EX_MEM_reg_write <= ID_EX_reg_write;\n EX_MEM_halt_cpu <= ID_EX_halt_cpu;\n\n EX_MEM_alu_out <= alu_result;\n EX_MEM_dmem_data <= forwarded_rs2_data;\n EX_MEM_rd <= ID_EX_rd;\n end\n end\n\n // ---------- Data Memory ----------\n DataMemory dmem(\n .reset (reset), // input\n .clk (clk), // input\n .addr (EX_MEM_alu_out), // input\n .din (EX_MEM_dmem_data), // input\n .mem_read (EX_MEM_mem_read), // input\n .mem_write (EX_MEM_mem_write), // input\n .dout (mem_dout) // output\n );\n\n // Update MEM/WB pipeline registers here\n always @(posedge clk) begin\n if (reset) begin\n MEM_WB_mem_to_reg <= 0;\n MEM_WB_reg_write <= 0;\n MEM_WB_halt_cpu <= 0;\n\n MEM_WB_mem_to_reg_src_1 <= 0;\n MEM_WB_mem_to_reg_src_2 <= 0;\n MEM_WB_rd <= 0;\n end\n else begin\n MEM_WB_mem_to_reg <= EX_MEM_mem_to_reg;\n MEM_WB_reg_write <= EX_MEM_reg_write;\n MEM_WB_halt_cpu <= EX_MEM_halt_cpu;\n\n MEM_WB_mem_to_reg_src_1 <= EX_MEM_alu_out;\n MEM_WB_mem_to_reg_src_2 <= mem_dout;\n MEM_WB_rd <= EX_MEM_rd;\n end\n end\n\n // Mux for mem_to_reg\n Mux2To1 mem_to_reg_mux(\n .din0(MEM_WB_mem_to_reg_src_1),\n .din1(MEM_WB_mem_to_reg_src_2),\n .sel(MEM_WB_mem_to_reg),\n .dout(rd_din)\n );\n\n assign is_halted = MEM_WB_halt_cpu;\n \nendmodule"}}},{"rowIdx":1092545,"cells":{"text":{"kind":"string","value":"import Link from 'next/link';\nimport { useState } from 'react';\nimport styles from './styles.module.scss';\nimport Image from 'next/image';\nimport registerImage from '../../../public/register-customer.jpg';\nimport Head from 'next/head';\nimport { fetchFromApi } from '../../lib/axios';\nimport { useRouter } from 'next/router';\nimport ValidateUsername from '../../components/ValidateUsername';\nimport ValidatePassword from '../../components/ValidatePassword';\n\n\nexport default function Register() {\n const [user, setUser] = useState('');\n const [password, setPassword] = useState('');\n const router = useRouter();\n\n const handleSubmit = async (e: React.FormEvent) => {\n e.preventDefault();\n try {\n const { data } = await fetchFromApi.post('/register', {\n name: user,\n password: password,\n });\n\n if (data.token) {\n await fetch('/api/login', {\n method: 'post',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data),\n });\n router.push('/');\n }\n } catch (error) {\n console.error(error);\n } finally {\n setPassword('');\n setUser('');\n }\n };\n\n return (\n <>\n \n Registre-se | Faça a sua conta!\n \n
\n \n
\n

Crie sua conta

\n

Adicione um usuario e uma senha!

\n
\n setUser(e.target.value)}\n />\n \n setPassword(e.target.value)}\n />\n \n \n \n

\n Já tem uma conta cadastrada?\n

\n Conecte-se\n
\n
\n \n );\n}"}}},{"rowIdx":1092546,"cells":{"text":{"kind":"string","value":"/** @format */\n\nimport React from \"react\";\nimport CustomerList from \"../components/customer/CustomerList\";\nimport EventList from \"../components/rentalEvent/EventList\";\nimport VehiclesList from \"../components/vehicle/VehiclesList\";\nimport { Switch, Route, Link } from \"react-router-dom\";\nimport Button from \"react-bootstrap/Button\";\nimport VehicleAdding from \"../components/vehicle/VehicleAdding\";\nimport CustomerAdding from \"../components/customer/CustomerAdding\";\nimport \"./content.css\";\nimport EventAdding from \"../components/rentalEvent/EventAdding\";\nexport default function Content() {\n return (\n
\n

\n Lorem ipsum dolor, sit amet consectetur adipisicing elit. Deserunt porro\n sit iure culpa distinctio, vitae aliquid recusandae odio numquam\n sapiente maxime adipisci laudantium dolor quisquam quis. Nobis\n voluptates distinctio, impedit officia expedita ab maxime cum tenetur\n itaque veritatis quibusdam qui eum dolorem unde corporis praesentium\n eveniet, sunt reprehenderit? Asperiores hic delectus incidunt autem\n explicabo mollitia ipsa qui voluptate totam voluptatem voluptatibus in,\n minima quo maxime consequatur ipsam quaerat veritatis fuga rem\n repudiandae, tempore odit, sequi officiis. Consectetur, eius ipsum qui\n harum illo velit dolor facilis amet soluta dolorum assumenda delectus\n iure repellendus architecto magni fugit tempora! Maxime, libero.\n Molestias, incidunt!\n

\n
\n \n {\" \"}\n \n \n {\" \"}\n \n \n \n \n
\n \n \n \n \n \n \n \n \n
\n );\n}"}}},{"rowIdx":1092547,"cells":{"text":{"kind":"string","value":"syntax = \"proto3\";\n\npackage library;\n\n\nmessage Library {\n string id = 1;\n string title = 2;\n string description = 3;\n\n}\n\n\n\nmessage GetLibraryRequest {\n string library_id = 1;\n}\n\nmessage GetLibraryResponse {\n Library library = 1;\n}\n\nmessage SearchLibrarysRequest {\n string query = 1;\n}\n\nmessage SearchLibrarysResponse {\n repeated Library librarys = 1;\n}\n\nmessage CreateLibraryRequest {\n string library_id = 1;\n string title = 2;\n string description = 3;\n}\n\nmessage CreateLibraryResponse {\n Library library = 1;\n}\n\nservice LibraryService {\n rpc GetLibrary(GetLibraryRequest) returns (GetLibraryResponse);\n rpc SearchLibrarys(SearchLibrarysRequest) returns (SearchLibrarysResponse);\n rpc CreateLibrary(CreateLibraryRequest) returns (CreateLibraryResponse);\n}"}}},{"rowIdx":1092548,"cells":{"text":{"kind":"string","value":"import 'dart:math';\n\nimport 'package:flutter/cupertino.dart';\nimport 'package:flutter/material.dart';\nimport 'package:flutter/services.dart';\nimport 'package:google_fonts/google_fonts.dart';\nimport 'package:google_mobile_ads/google_mobile_ads.dart';\n\nimport '../AdHelper/adshelper.dart';\n\nclass HomeScreen extends StatefulWidget {\n const HomeScreen({Key? key}) : super(key: key);\n\n @override\n State createState() => _HomeScreenState();\n}\n\nclass _HomeScreenState extends State {\n\n var count = 1;\n var random_dice_no_1 = Random();\n var random_dice_no_2 = Random();\n var random_dice_no_3 = Random();\n var random_dice_no_4 = Random();\n var random_dice_no_5 = Random();\n var random_dice_no_6 = Random();\n\n var rnd_1 = 1;\n var rnd_2 = 1;\n var rnd_3 = 1;\n var rnd_4 = 1;\n var rnd_5 = 1;\n var rnd_6 = 1;\n\n var back = Colors.blue.shade100;\n\n Future? _launched;\n\n late BannerAd _bannerAd;\n\n bool _isBannerAdReady = false;\n\n @override\n void initState() {\n // TODO: implement initState\n super.initState();\n _bannerAd = BannerAd(\n adUnitId: AdHelper.bannerAdUnitIdOfHomeScreen,\n request: AdRequest(),\n size: AdSize.banner,\n listener: BannerAdListener(\n onAdLoaded: (_) {\n setState(() {\n _isBannerAdReady = true;\n });\n },\n onAdFailedToLoad: (ad, err) {\n print('Failed to load a banner ad: ${err.message}');\n _isBannerAdReady = false;\n ad.dispose();\n },\n ),\n );\n _bannerAd.load();\n }\n\n\n @override\n void dispose() {\n super.dispose();\n _bannerAd.dispose();\n }\n\n @override\n Widget build(BuildContext context) {\n\n SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(\n statusBarColor: Colors.transparent,\n ));\n\n\n return GestureDetector(\n onTap: () {\n // back = Color((random_dice_no_1.nextDouble() * 0x00FFFFFF).toInt()).withOpacity(1);\n\n setState(() {\n rnd_1 = random_dice_no_1.nextInt(6)+1;\n rnd_2 = random_dice_no_2.nextInt(6)+1;\n rnd_3 = random_dice_no_3.nextInt(6)+1;\n rnd_4 = random_dice_no_4.nextInt(6)+1;\n rnd_5 = random_dice_no_5.nextInt(6)+1;\n rnd_6 = random_dice_no_6.nextInt(6)+1;\n\n });\n },\n child: Scaffold(\n backgroundColor: Colors.white,\n body: Padding(\n padding: const EdgeInsets.all(8.0),\n child: Column(\n children: [\n SizedBox(height: 20.0,),\n\n Expanded(\n flex: 1,\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceAround,\n children: [\n\n count > 1 ? GestureDetector(\n onTap: (){\n if(count >= 2)\n {\n count_minus();\n }\n },\n child: const Padding(\n padding: EdgeInsets.all(8.0),\n child: Icon(Icons.indeterminate_check_box_outlined,size: 60,),\n ),\n ) : Container(),\n Padding(\n padding: const EdgeInsets.all(8.0),\n child: Text(\n \"${count} Dice\",\n textAlign: TextAlign.center,\n style: GoogleFonts.mochiyPopOne(textStyle: TextStyle(fontSize: 50,color: Colors.black,fontWeight: FontWeight.w600,))\n\n ),\n ),\n GestureDetector(\n onTap: (){\n if(count < 6)\n {\n count_add();\n }\n },\n child: const Padding(\n padding: EdgeInsets.all(8.0),\n child: Icon(Icons.add_box_outlined,size: 60,),\n ),\n ),\n ],\n ),\n ),\n\n if (count == 1) ...[\n Expanded(\n flex: 3,\n child: Center(\n child: Image.asset('assets/images/$rnd_1-dice.png',\n height: 280,\n width: 280,\n alignment: Alignment.center,),\n ),\n ),\n ]\n else if (count == 2) ...[\n Expanded(\n flex: 3,\n child: Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Center(\n child: Image.asset('assets/images/$rnd_1-dice.png',\n height: 180,\n width: 180,\n alignment: Alignment.center,),\n ),\n Center(\n child: Image.asset('assets/images/$rnd_2-dice.png',\n height: 180,\n width: 180,\n alignment: Alignment.center,),\n ),\n\n ],\n ),\n ),\n ]\n else if (count == 3) ...[\n Expanded(\n flex: 3,\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Center(\n child: Image.asset('assets/images/$rnd_1-dice.png',\n height: 180,\n width: 180,\n alignment: Alignment.center,),\n ),\n Center(\n child: Image.asset('assets/images/$rnd_2-dice.png',\n height: 180,\n width: 180,\n alignment: Alignment.center,),\n ),\n\n ],\n ),\n Center(\n child: Image.asset('assets/images/$rnd_3-dice.png',\n height: 180,\n width: 180,\n alignment: Alignment.center,),\n ),\n ],\n ),\n ),\n ]\n else if (count == 4) ...[\n Expanded(\n flex: 3,\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Center(\n child: Image.asset('assets/images/$rnd_1-dice.png',\n height: 180,\n width: 180,\n alignment: Alignment.center,),\n ),\n Center(\n child: Image.asset('assets/images/$rnd_2-dice.png',\n height: 180,\n width: 180,\n alignment: Alignment.center,),\n ),\n\n ],\n ),\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n\n children: [\n Center(\n child: Image.asset('assets/images/$rnd_3-dice.png',\n height: 180,\n width: 180,\n alignment: Alignment.center,),\n ),\n Center(\n child: Image.asset('assets/images/$rnd_4-dice.png',\n height: 180,\n width: 180,\n alignment: Alignment.center,),\n ),\n\n ],\n ),\n ],\n ),\n ),\n ]\n else if (count == 5) ...[\n Expanded(\n flex: 3,\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Center(\n child: Image.asset('assets/images/$rnd_1-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n Center(\n child: Image.asset('assets/images/$rnd_2-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n\n ],\n ),\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n\n children: [\n Center(\n child: Image.asset('assets/images/$rnd_3-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n Center(\n child: Image.asset('assets/images/$rnd_4-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n\n ],\n ),\n Center(\n child: Image.asset('assets/images/$rnd_5-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n\n ],\n ),\n ),\n ]\n else if (count == 6) ...[\n Expanded(\n flex: 3,\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Center(\n child: Image.asset('assets/images/$rnd_1-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n Center(\n child: Image.asset('assets/images/$rnd_2-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n\n ],\n ),\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n\n children: [\n Center(\n child: Image.asset('assets/images/$rnd_3-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n Center(\n child: Image.asset('assets/images/$rnd_4-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n\n ],\n ),\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Center(\n child: Image.asset('assets/images/$rnd_5-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n Center(\n child: Image.asset('assets/images/$rnd_6-dice.png',\n height: 150,\n width: 150,\n alignment: Alignment.center,),\n ),\n ],\n ),\n\n ],\n ),\n ),\n ],\n\n SizedBox(height: 10,),\n Text(\n \"Tap to Roll..\",\n textAlign: TextAlign.center,\n style: GoogleFonts.mochiyPopOne(textStyle: TextStyle(fontSize: 40,color: Colors.black,fontWeight: FontWeight.w600,))\n\n ),\n SizedBox(height: 30,),\n\n ],\n ),\n ),\n bottomNavigationBar: Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n if (_isBannerAdReady)\n Container(\n width: _bannerAd.size.width.toDouble(),\n height: _bannerAd.size.height.toDouble(),\n child: AdWidget(ad: _bannerAd),\n ),\n ],\n ),\n\n ),\n );\n }\n\n\n void count_add() {\n\n setState(() {\n\n count = count + 1;\n\n });\n }\n\n void count_minus() {\n\n setState(() {\n count = count - 1;\n\n });\n }\n}"}}},{"rowIdx":1092549,"cells":{"text":{"kind":"string","value":"var current_unit_index = 0;\nfunction generate_new_unit_id(){\n current_unit_index++;\n return current_unit_index;\n}\n/*\nvar unit = {\n defense: 1, // used to determine how much damage this unit can sustain before expiring\n attack: 1, // used to determine how much damage to apply when attacking\n\n move_range: 1, // used to determine how many tiles in a direction a unit can move\n attack_range: 1, // used to determine how many tiles this unit can attack in\n\n model: 0, // used to instaniate the visual aspect of this unit\n unit_id: -1 // used to have a common referencable id between clients\n}\n*/\n\n\n\n// CHARACTER MODEL INDICIES //\n\n\nconst unit_worker = 0;\nconst unit_soldier = 1;\nconst unit_sniper = 2;\nconst unit_tower = 3;\n\nconst worker_cost = 75;\nconst soldier_cost = 125;\nconst sniper_cost = 225;\nconst tower_cost = 500;\n// for now just add 125 to the cost\nconst worker_resort_cost = 200;\nconst soldier_resort_cost = 250;\nconst sniper_resort_cost = 350;\nconst tower_resort_cost = 625;\n\nfunction SERVER_CREATE_UNIT(type, position, player_id){\n let new_unit = init_new_unit_object(type, position, player_id);\n new_unit.unit_id = generate_new_unit_id();\n return new_unit;\n}\n\n\n\n// CHARACTER STATS GENERATION //\n\n\nfunction init_new_unit_object(type, position, owning_player_id){\n let n_unit = stats_for_unit(type);\n n_unit.pos = position;\n n_unit.type = type;\n n_unit.owner = owning_player_id;\n return n_unit;\n}\nfunction stats_for_unit(type){\n if (type == unit_worker) return create_worker();\n else if (type == unit_soldier) return create_soldier();\n else if (type == unit_sniper) return create_sniper();\n else if (type == unit_tower) return create_tower();\n \n return -1;\n}\nfunction create_soldier(){\n return {\n defense: 3, \n attack: 2, \n \n move_range: 3, \n attack_range: 3,\n vision_range: 3\n };\n}\nfunction create_worker(){\n return {\n defense: 2, \n attack: 2, \n \n move_range: 2, \n attack_range: 2,\n vision_range: 4\n };\n}\nfunction create_sniper(){\n return {\n defense: 2, \n attack: 1, \n \n move_range: 2, \n attack_range: 5,\n vision_range: 7\n };\n}\nfunction create_tower(){\n return {\n defense: 10, \n attack: 5, \n \n move_range: 1, \n attack_range: 3,\n vision_range: 4\n };\n}"}}},{"rowIdx":1092550,"cells":{"text":{"kind":"string","value":"#include\n#include\n#include\n#include\n\nint main()\n{\n\t// 参数一:IP 地址类型; AF_INET -> IPv4 AF_INET6 -> IPv6\n\t// 参数二:数据传输方式; SOCK_STREAM 流格式,面向连接 -> TCP ,数据报格式,无连接 -> UPD\n\t// 参数三:协议; 0 表示根据前面的两个参数自动推导协议类型:TCP/UDP\n\tint sockfd = socket(AF_INET,SOCK_STREAM,0);\n\t// 将套接字绑定到一个 IP 地址和端口上 \n\tstruct sockaddr_in serv_addr;\n\tbzero(&serv_addr,sizeof(serv_addr));\n\tserv_addr.sin_family= AF_INET;\n\tserv_addr.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n\tserv_addr.sin_port = htons(8888);\n\t// 将 socket 地址与文件描述符绑定\n\tbind(sockfd, (sockaddr*)&serv_addr , sizeof(serv_addr));\n // 监听 socket 端口;参数二:最大监听队列长度\n\tlisten(sockfd, SOMAXCONN);\n\n\tstruct sockaddr_in clnt_addr;\n\tsocklen_t clnt_addr_len = sizeof(clnt_addr);\n\tbzero(&clnt_addr,sizeof(clnt_addr));\n\t// 接受客户端连接,accept 函数会阻塞当前程序,直到有一个客户端 socket 被接受程序后才会往下运行\n\tint clnt_sockfd = accept(sockfd,(sockaddr*)&clnt_addr,&clnt_addr_len);\n\tprintf(\"new client fd %d! IP: %s Port: %d\\n\",clnt_sockfd, inet_ntoa(clnt_addr.sin_addr),ntohs(clnt_addr.sin_port));\n\treturn 0;\n}"}}},{"rowIdx":1092551,"cells":{"text":{"kind":"string","value":"import React, { useCallback } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport Typography from '@mui/material/Typography';\nimport Box from '@mui/material/Box';\nimport Grid from '@mui/material/Grid';\nimport CloseIcon from '@mui/icons-material/Close';\n\nimport warningAnimation from 'assets/warning.gif';\n\nimport { Button, Modal } from 'shared';\n\nimport useModal from 'hooks/useModal';\n\nimport useStyles from 'modules/Admin/components/Campaign/Modal/EditModal/styled.editModal';\n\nfunction EditModal() {\n const classes = useStyles();\n const [state, setState] = useModal();\n const navigate = useNavigate();\n\n const handleExit = useCallback(() => {\n setState({ ...state, modalName: '' });\n navigate('/admin/campaign/view/:id');\n }, [state]);\n\n const handleClose = useCallback(() => {\n setState({ ...state, modalName: '' });\n }, [state]);\n\n const handleEdit = useCallback(() => {\n navigate('/admin/campaign/add-new');\n });\n\n return (\n \n \n \n \n \n \n \n \n Are you sure you want to Edit!\n \n You are about to edit the details of a campaign This changes the\n campaign details.\n \n \n \n \n \n \n \n \n \n \n \n \n \n );\n}\nexport default EditModal;"}}},{"rowIdx":1092552,"cells":{"text":{"kind":"string","value":"---\ntitle: Diseño de Páginas Web para Centros de Estética en Castellón de la Plana\ndate: '2023-10-04'\ntags: ['Diseño web', 'Centros de Estética', 'Castellón de la Plana']\ndraft: false\nbanner : diseño_paginas_web_centrosdeestética\nfondoBanner : diseño_pagina_web_castellóndelaplana\nsummary: El diseño de páginas web para centros de estética en Castellón de la Plana es esencial para destacar en un sector tan competitivo. En un mundo cada vez más digitalizado, contar con una presencia online efectiva es clave para atraer a nuevos clientes y mantenerse relevante en el mercado.\n---\nimport Cta from \"../../../components/Cta.astro\";\nimport CtaBot from \"../../../components/CtaBot.astro\";\nimport GifSeo from \"../../../components/GifSeo.astro\";\nimport Gmaps from \"../../../components/Gmaps.astro\";\nimport Video from \"../../../components/Video.astro\";\n\n## Diseño de Páginas Web para Centros de Estética en Castellón de la Plana\n\nEl diseño de páginas web para centros de estética en Castellón de la Plana es esencial para destacar en un sector tan competitivo. En un mundo cada vez más digitalizado, contar con una presencia online efectiva es clave para atraer a nuevos clientes y mantenerse relevante en el mercado.\n\n### Motivos por los que necesitan una página web en su profesión y en su ciudad:\n\n1. **Aumentar la visibilidad:** Una página web optimizada les permitirá ser encontrados fácilmente por personas que buscan servicios de estética en Castellón de la Plana.\n\n2. **Diferenciarse de la competencia:** Con una página web profesional y atractiva, podrán destacar entre otros centros de estética en la ciudad, mostrando su estilo único y los servicios que ofrecen.\n\n3. **Mostrar su experiencia y servicios:** Una página web les brinda la oportunidad de presentar su experiencia en el sector, así como los diferentes servicios que ofrecen a sus clientes.\n\n4. **Generar confianza:** Una página web bien diseñada y con contenido de calidad transmitirá profesionalidad y confianza a los visitantes, motivándolos a elegir su centro de estética.\n\n### Beneficios del diseño web para su profesión y su ciudad:\n\n1. **Mayor alcance:** Una página web les permitirá llegar a un público más amplio, incluso más allá de Castellón de la Plana. Podrán atraer a nuevos clientes de otras ciudades que estén buscando servicios de estética en la zona.\n\n2. **Información actualizada:** A través de su página web, podrán mantener a sus clientes informados sobre las últimas novedades, promociones y servicios que ofrecen en su centro de estética.\n\n3. **Facilidad de contacto:** Una página web les brinda la oportunidad de incluir formularios de contacto, facilitando a los visitantes el poder solicitar información o reservar citas sin tener que llamar por teléfono.\n\n4. **Exposición de opiniones y testimonios:** Integrar reseñas y testimonios de clientes satisfechos en su página web ayudará a generar confianza en los visitantes y aumentar las posibilidades de que elijan su centro de estética.\n\n5. **Aprovechar el crecimiento del sector:** El mercado de la estética en Castellón de la Plana está en constante crecimiento. Tener una presencia online sólida les permitirá aprovechar al máximo esta tendencia y atraer a más clientes interesados en sus servicios.\n\nCon un diseño web efectivo diseñado por Élite Webs, su centro de estética en Castellón de la Plana podrá destacar y convertir las visitas en ventas. No pierdan la oportunidad de contar con una presencia online de calidad que los diferencie y les permita atraer a más clientes en esta ciudad tan cosmopolita y turística.\n\n\n\n\n\n## Diseño de Página Web para Centros de Estética en Castellón de la Plana\n\nEn Élite Webs, somos expertos en el diseño y desarrollo de páginas web para centros de estética en Castellón de la Plana. Nuestro enfoque se centra en convertir las visitas en ventas, brindándote una presencia en línea atractiva y efectiva que impulse el crecimiento de tu negocio. A continuación, te explicamos los elementos clave que consideramos para lograr un diseño web exitoso y cómo nuestro servicio puede ayudarte.\n\n## Elementos clave del diseño web exitoso\n\n- **Diseño atractivo y profesional**: Creamos páginas web con un diseño visualmente atractivo y profesional, que refleje la estética y la imagen de tu centro. Utilizamos colores, tipografías y elementos gráficos que transmitan confianza y sofisticación.\n\n- **Funcionalidad y navegación intuitiva**: Nos aseguramos de que tu página web sea fácil de usar y navegar. Implementamos una estructura clara de menús y submenús, junto con enlaces internos y externos relevantes, para facilitar la exploración de tus servicios y promociones.\n\n- **Optimización para dispositivos móviles**: Dado que cada vez más personas acceden a internet desde sus teléfonos móviles, aseguramos que tu página web tenga un diseño y una experiencia de usuario adaptada a dispositivos móviles. Esto garantiza que tus clientes potenciales puedan visitarte y contactarte sin problemas desde sus smartphones.\n\n- **Contenido relevante y persuasivo**: Creamos contenido persuasivo y relevante para captar la atención de tus visitantes. Destacamos los beneficios de tus servicios, compartimos testimonios de clientes satisfechos y te ayudamos a transmitir tus valores y ventajas competitivas.\n\n- **Integración de herramientas de reserva y contacto**: Facilitamos a tus clientes potenciales la solicitud de citas, con la integración de herramientas de reserva en línea y formularios de contacto. Esto permite una comunicación fluida y rápida entre tu centro de estética y tus clientes.\n\n## Cómo nuestro servicio de diseño web puede ayudar\n\nNuestro servicio de diseño web para centros de estética en Castellón de la Plana te brinda una solución completa para impulsar tu negocio en línea. Al elegirnos, beneficiarás de:\n\n- Una página web personalizada y atractiva que refuerce tu imagen de marca.\n\n- Un diseño web optimizado para SEO, lo que aumentará tu visibilidad en los motores de búsqueda y te ayudará a atraer más tráfico orgánico.\n\n- La integración de herramientas de reserva en línea y formularios de contacto, lo que facilitará la comunicación con tus clientes potenciales.\n\n- Un diseño responsive que se adapta a dispositivos móviles, para llegar a un público más amplio y mejorar la experiencia de usuario.\n\n- Soporte técnico y actualizaciones regulares para mantener tu página web funcionando sin problemas y al día con las últimas tendencias del diseño web.\n\n## Conclusión: Tu página web de calidad, nuestra especialidad\n\nEn el mundo digital de hoy, es fundamental para los centros de estética en Castellón de la Plana tener una página web de calidad. Una presencia en línea efectiva te ayudará a destacar entre tu competencia y atraer a más clientes. En Élite Webs, nos especializamos en el diseño y desarrollo de páginas web que convierten visitas en ventas. Nuestro enfoque en los elementos clave del diseño web exitoso y en ofrecer un servicio personalizado nos diferencia de la competencia.\n\nNo pierdas la oportunidad de llevar tu centro de estética al siguiente nivel. Contáctanos hoy mismo para discutir tus necesidades y descubre cómo podemos ayudarte a alcanzar el éxito en línea.\n\n