{ // 获取包含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"}}},{"rowIdx":625,"cells":{"text":{"kind":"string","value":"import UIKit\n\nclass CommentBottomTextView: UITextView {\n \n // MARK: - Properties\n let placeholderLabel: UILabel = {\n let label = UILabel()\n label.font = UIFont.systemFont(ofSize: 16)\n //label.font = UIFont(name: \"NanumMuGungHwa\", size: 25)\n label.textColor = .darkGray\n label.text = \"댓글을 적어주세요\"\n return label\n }()\n \n\n // MARK: - LifeCycle\n \n \n override init(frame: CGRect, textContainer: NSTextContainer?) {\n super.init(frame: frame, textContainer: textContainer)\n \n configure()\n \n }\n \n required init?(coder: NSCoder) {\n fatalError(\"init(coder:) has not been implemented\")\n }\n \n func configure() {\n \n \n \n self.backgroundColor = .white\n font = UIFont.systemFont(ofSize: 16)\n //self.font = UIFont(name: \"NanumMuGungHwa\", size: 25)\n self.isScrollEnabled = true\n //heightAnchor.constraint(equalToConstant: 600).isActive = true\n //heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height).isActive = true\n \n self.addSubview(self.placeholderLabel)\n self.placeholderLabel.translatesAutoresizingMaskIntoConstraints = false\n \n \n NSLayoutConstraint.activate([\n self.placeholderLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 8),\n self.placeholderLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 4),\n \n //placeholderLabel.anchor(top:topAnchor, left: leftAnchor, paddingTop:8, paddingLeft:4)\n ])\n \n \n \n \n }\n \n \n // MARK: - Selectors\n @objc func handleTextInputChange() {\n placeholderLabel.isHidden = !text.isEmpty\n \n // 텍스트의 위치에 레이블을 따라 움직이도록 코드를 추가\n // 이동 레이블 (placeholderLabel)을 입력한 텍스트의 위치에 맞게 조정\n let topOffset: CGFloat = text.isEmpty ? 8 : 0\n let leadingOffset: CGFloat = text.isEmpty ? 4 : 0\n \n UIView.animate(withDuration: 0.2) {\n self.placeholderLabel.transform = CGAffineTransform(translationX: leadingOffset, y: topOffset)\n }\n \n }\n \n func validateText() -> Bool {\n guard let text = self.text else { return false }\n let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // 텍스트 길이를 180자로 제한\n guard trimmedText.count <= 180 else { return false }\n \n // 최소 10자 이상이어야 함\n return trimmedText.count >= 10\n }\n\n \n func showAlert(message: String) {\n let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)\n alertController.addAction(UIAlertAction(title: \"확인\", style: .default, handler: nil))\n \n if let viewController = self.findViewController() {\n viewController.present(alertController, animated: true, completion: nil)\n }\n }\n \n \n}\n\n\nextension UIResponder {\n\n func findViewController() -> UIViewController? {\n if let viewController = self as? UIViewController {\n return viewController\n } else if let next = self.next {\n return next.findViewController()\n } else {\n return nil\n }\n }\n}"}}},{"rowIdx":626,"cells":{"text":{"kind":"string","value":"import Link from \"next/link\";\n\ntype Props = {\n title: String;\n description: String;\n date: String;\n slug: String;\n tags: String[];\n};\n\nfunction SinglePost(props: Props) {\n const { title, description, date, slug, tags } = props;\n return (\n \n
\n
\n
{date}
\n
    \n {tags.map((tag, index) => (\n \n {tag}\n \n ))}\n
\n

{title}

\n
\n

{description}

\n \n );\n}\n\nexport default SinglePost;"}}},{"rowIdx":627,"cells":{"text":{"kind":"string","value":"/*\n * Copyright (C) 2022 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.android.server.wearable;\n\nimport android.annotation.NonNull;\nimport android.app.wearable.WearableSensingManager;\nimport android.content.ComponentName;\nimport android.os.Binder;\nimport android.os.ParcelFileDescriptor;\nimport android.os.PersistableBundle;\nimport android.os.RemoteCallback;\nimport android.os.ShellCommand;\nimport android.util.Slog;\n\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.time.Duration;\n\nfinal class WearableSensingShellCommand extends ShellCommand {\n private static final String TAG = WearableSensingShellCommand.class.getSimpleName();\n\n static final TestableCallbackInternal sTestableCallbackInternal =\n new TestableCallbackInternal();\n\n @NonNull\n private final WearableSensingManagerService mService;\n\n private static ParcelFileDescriptor[] sPipe;\n\n WearableSensingShellCommand(@NonNull WearableSensingManagerService service) {\n mService = service;\n }\n\n /** Callbacks for WearableSensingService results used internally for testing. */\n static class TestableCallbackInternal {\n private int mLastStatus;\n\n public int getLastStatus() {\n return mLastStatus;\n }\n\n @NonNull\n private RemoteCallback createRemoteStatusCallback() {\n return new RemoteCallback(result -> {\n int status = result.getInt(WearableSensingManager.STATUS_RESPONSE_BUNDLE_KEY);\n final long token = Binder.clearCallingIdentity();\n try {\n mLastStatus = status;\n } finally {\n Binder.restoreCallingIdentity(token);\n }\n });\n }\n }\n\n @Override\n public int onCommand(String cmd) {\n if (cmd == null) {\n return handleDefaultCommands(cmd);\n }\n\n switch (cmd) {\n case \"create-data-stream\":\n return createDataStream();\n case \"destroy-data-stream\":\n return destroyDataStream();\n case \"provide-data-stream\":\n return provideDataStream();\n case \"write-to-data-stream\":\n return writeToDataStream();\n case \"provide-data\":\n return provideData();\n case \"get-last-status-code\":\n return getLastStatusCode();\n case \"get-bound-package\":\n return getBoundPackageName();\n case \"set-temporary-service\":\n return setTemporaryService();\n case \"set-data-request-rate-limit-window-size\":\n return setDataRequestRateLimitWindowSize();\n default:\n return handleDefaultCommands(cmd);\n }\n }\n\n @Override\n public void onHelp() {\n PrintWriter pw = getOutPrintWriter();\n pw.println(\"WearableSensingCommands commands: \");\n pw.println(\" help\");\n pw.println(\" Print this help text.\");\n pw.println();\n pw.println(\" create-data-stream: Creates a data stream to be provided.\");\n pw.println(\" destroy-data-stream: Destroys a data stream if one was previously created.\");\n pw.println(\" provide-data-stream USER_ID: \"\n + \"Provides data stream to WearableSensingService.\");\n pw.println(\" write-to-data-stream STRING: writes string to data stream.\");\n pw.println(\" provide-data USER_ID KEY INTEGER: provide integer as data with key.\");\n pw.println(\" get-last-status-code: Prints the latest request status code.\");\n pw.println(\" get-bound-package USER_ID:\"\n + \" Print the bound package that implements the service.\");\n pw.println(\" set-temporary-service USER_ID [PACKAGE_NAME] [COMPONENT_NAME DURATION]\");\n pw.println(\" Temporarily (for DURATION ms) changes the service implementation.\");\n pw.println(\" To reset, call with just the USER_ID argument.\");\n pw.println(\" set-data-request-rate-limit-window-size WINDOW_SIZE\");\n pw.println(\" Set the window size used in data request rate limiting to WINDOW_SIZE\"\n + \" seconds.\");\n pw.println(\" positive WINDOW_SIZE smaller than 20 will be automatically set to 20.\");\n pw.println(\" To reset, call with 0 or a negative WINDOW_SIZE.\");\n }\n\n private int createDataStream() {\n Slog.d(TAG, \"createDataStream\");\n try {\n sPipe = ParcelFileDescriptor.createPipe();\n } catch (IOException e) {\n Slog.d(TAG, \"Failed to createDataStream.\", e);\n }\n return 0;\n }\n\n private int destroyDataStream() {\n Slog.d(TAG, \"destroyDataStream\");\n try {\n if (sPipe != null) {\n sPipe[0].close();\n sPipe[1].close();\n }\n } catch (IOException e) {\n Slog.d(TAG, \"Failed to destroyDataStream.\", e);\n }\n return 0;\n }\n\n private int provideDataStream() {\n Slog.d(TAG, \"provideDataStream\");\n if (sPipe != null) {\n final int userId = Integer.parseInt(getNextArgRequired());\n mService.provideDataStream(userId, sPipe[0],\n sTestableCallbackInternal.createRemoteStatusCallback());\n }\n return 0;\n }\n\n private int writeToDataStream() {\n Slog.d(TAG, \"writeToDataStream\");\n if (sPipe != null) {\n final String value = getNextArgRequired();\n try {\n ParcelFileDescriptor writePipe = sPipe[1].dup();\n OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(writePipe);\n os.write(value.getBytes());\n } catch (IOException e) {\n Slog.d(TAG, \"Failed to writeToDataStream.\", e);\n }\n }\n return 0;\n }\n\n private int provideData() {\n Slog.d(TAG, \"provideData\");\n final int userId = Integer.parseInt(getNextArgRequired());\n final String key = getNextArgRequired();\n final int value = Integer.parseInt(getNextArgRequired());\n PersistableBundle data = new PersistableBundle();\n data.putInt(key, value);\n\n mService.provideData(userId, data, null,\n sTestableCallbackInternal.createRemoteStatusCallback());\n return 0;\n }\n\n private int getLastStatusCode() {\n Slog.d(TAG, \"getLastStatusCode\");\n final PrintWriter resultPrinter = getOutPrintWriter();\n int lastStatus = sTestableCallbackInternal.getLastStatus();\n resultPrinter.println(lastStatus);\n return 0;\n }\n\n private int setTemporaryService() {\n final PrintWriter out = getOutPrintWriter();\n final int userId = Integer.parseInt(getNextArgRequired());\n final String serviceName = getNextArg();\n if (serviceName == null) {\n mService.resetTemporaryService(userId);\n out.println(\"WearableSensingManagerService temporary reset. \");\n return 0;\n }\n\n final int duration = Integer.parseInt(getNextArgRequired());\n mService.setTemporaryService(userId, serviceName, duration);\n out.println(\"WearableSensingService temporarily set to \" + serviceName\n + \" for \" + duration + \"ms\");\n return 0;\n }\n\n private int getBoundPackageName() {\n final PrintWriter resultPrinter = getOutPrintWriter();\n final int userId = Integer.parseInt(getNextArgRequired());\n final ComponentName componentName = mService.getComponentName(userId);\n resultPrinter.println(componentName == null ? \"\" : componentName.getPackageName());\n return 0;\n }\n\n private int setDataRequestRateLimitWindowSize() {\n Slog.d(TAG, \"setDataRequestRateLimitWindowSize\");\n int windowSizeSeconds = Integer.parseInt(getNextArgRequired());\n if (windowSizeSeconds <= 0) {\n mService.resetDataRequestRateLimitWindowSize();\n } else {\n // 20 is the minimum window size supported by the rate limiter.\n // It is defined by com.android.server.utils.quota.QuotaTracker#MIN_WINDOW_SIZE_MS\n if (windowSizeSeconds < 20) {\n windowSizeSeconds = 20;\n }\n mService.setDataRequestRateLimitWindowSize(Duration.ofSeconds(windowSizeSeconds));\n }\n return 0;\n }\n}"}}},{"rowIdx":628,"cells":{"text":{"kind":"string","value":"import {\n Body,\n Controller,\n Delete,\n Get,\n Param,\n Post,\n Query,\n UploadedFiles,\n UseInterceptors,\n} from '@nestjs/common';\nimport { FileFieldsInterceptor } from '@nestjs/platform-express';\nimport { ObjectId } from 'mongoose';\nimport { AlbumService } from './album.service';\nimport { CreateAlbumDto } from './dto/create-album.dto';\n\n@Controller('/albums')\nexport class AlbumController {\n constructor(private albumService: AlbumService) {}\n\n @Post()\n @UseInterceptors(FileFieldsInterceptor([{ name: 'picture', maxCount: 1 }]))\n create(@UploadedFiles() files, @Body() dto: CreateAlbumDto) {\n const { picture } = files;\n return this.albumService.create(dto, picture[0]);\n }\n\n @Post('/update/:id')\n @UseInterceptors(FileFieldsInterceptor([{ name: 'picture', maxCount: 1 }]))\n update(\n @Param('id') id: ObjectId,\n @UploadedFiles() files,\n @Body() dto: CreateAlbumDto,\n ) {\n let { picture } = files || {};\n picture = !picture ? [] : picture;\n return this.albumService.updateAlbum(id, dto, picture[0]);\n }\n\n @Get()\n getAll(@Query('count') count: number, @Query('offset') offset: number) {\n return this.albumService.getAll(count, offset);\n }\n\n @Get('/search')\n search(@Query('query') query: string) {\n return this.albumService.search(query);\n }\n\n @Get(':id')\n getOne(@Param('id') id: ObjectId) {\n return this.albumService.getOne(id);\n }\n\n @Delete(':id')\n delete(@Param('id') id: ObjectId) {\n return this.albumService.delete(id);\n }\n}"}}},{"rowIdx":629,"cells":{"text":{"kind":"string","value":"\"use client\"\n\nimport React from \"react\"\nimport { zodResolver } from \"@hookform/resolvers/zod\"\nimport { useForm } from \"react-hook-form\"\nimport * as z from \"zod\"\n\nimport { newsletter } from \"@/lib/airtable\"\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n Form,\n FormControl,\n FormField,\n FormItem,\n FormMessage,\n} from \"@/components/ui/form\"\nimport Heading from \"@/components/ui/heading\"\nimport { Input } from \"@/components/ui/input\"\n\nimport { Icons } from \"./icons\"\n\nconst formSchema = z.object({\n email: z.string().email().min(2, {\n message: \"Username must be at least 2 characters.\",\n }),\n})\n\nconst NewsLetter = () => {\n const [isLoading, setIsLoading] = React.useState(false)\n const [isError, setIsError] = React.useState(false)\n const [isSuccess, setIsSuccess] = React.useState(false)\n\n const form = useForm>({\n resolver: zodResolver(formSchema),\n defaultValues: {\n email: \"\",\n },\n })\n async function onSubmit(values: z.infer) {\n setIsLoading(true)\n setIsError(false)\n setIsSuccess(false)\n\n try {\n const response = await newsletter.create([\n {\n fields: {\n Email: values.email,\n },\n },\n ])\n setIsSuccess(true)\n setIsLoading(false)\n form.reset()\n console.log(response)\n\n return response\n } catch (error) {\n setIsLoading(false)\n console.log(error)\n form.reset()\n setIsError(true)\n }\n }\n\n return (\n
\n
\n
\n
\n \n Join Our Newsletter &nbsp;\n {/* todo: add icn like 📨 */}\n \n

\n Never miss a beat and be the first to receive exciting updates,\n exclusive offers, and insider content—join our newsletter today\n and stay connected with us!\n

\n
\n
\n \n (\n \n \n \n \n \n \n {isLoading ? (\n <>\n Submitting...{\" \"}\n \n \n ) : (\n Subscribe\n )}\n \n
\n {/* Enter your country here */}\n \n \n )}\n />\n {/* Alert */}\n {(isError || isSuccess) && (\n \n

\n {isError && \"Something went wrong! 😕\"}\n {isSuccess && \"Thanks! your message has been sent 🎊\"}\n

\n
\n )}\n \n \n
\n
\n \n )\n}\n\nexport default NewsLetter"}}},{"rowIdx":630,"cells":{"text":{"kind":"string","value":"document.addEventListener('DOMContentLoaded', () => {\n const chatDisplay = document.getElementById('chat-display');\n const messageForm = document.getElementById('message-form');\n const messageInput = document.getElementById('message');\n\n const termsModal = document.getElementById('terms-modal');\n const agreeCheckbox = document.getElementById('agree-checkbox');\n\n // Show the terms modal on page load\n termsModal.style.display = 'block';\n\n // Function to close the terms modal\n window.closeTermsModal = function () {\n if (agreeCheckbox.checked) {\n // If the user agrees, hide the modal and proceed\n termsModal.style.display = 'none';\n } else {\n // If the user doesn't agree, you might want to handle this case (e.g., display an error message)\n alert('You must agree to the Terms and Conditions to continue.');\n }\n };\n\n const socket = io();\n\n messageForm.addEventListener('submit', function (event) {\n event.preventDefault();\n const messageText = messageInput.value.trim();\n if (messageText !== '') {\n socket.emit('chat message', messageText);\n messageInput.value = '';\n }\n });\n\n socket.on('chat message', function (message) {\n displayMessage(message);\n });\n\n function displayMessage(message) {\n const messageElement = document.createElement('div');\n messageElement.classList.add('message-entry');\n messageElement.textContent = `> ${message}`;\n chatDisplay.appendChild(messageElement);\n chatDisplay.scrollTop = chatDisplay.scrollHeight;\n }\n\n function displayMessages() {\n // Clear the chat display\n chatDisplay.innerHTML = '';\n \n // Get the current timestamp\n const currentTime = new Date().getTime();\n \n // Display messages from the last hour\n const lastHourMessages = messages.filter(\n msg => currentTime - msg.timestamp < 60 * 60 * 1000\n );\n \n lastHourMessages.forEach(({ message }) => {\n const messageElement = document.createElement('div');\n messageElement.classList.add('message-entry');\n messageElement.textContent = `> ${message}`;\n chatDisplay.appendChild(messageElement);\n \n // Trigger reflow before applying animation\n void messageElement.offsetWidth;\n \n // Apply animation only to the newly added message\n messageElement.style.animation = 'fadeIn 0.5s ease-in-out forwards';\n });\n \n // Scroll to the bottom of the chat display\n chatDisplay.scrollTop = chatDisplay.scrollHeight;\n }\n \n \n});"}}},{"rowIdx":631,"cells":{"text":{"kind":"string","value":"import * as RadixCollapsible from \"@radix-ui/react-collapsible\";\nimport { useCallback, useState } from \"react\";\n\nimport { collapsibleContentAnimation } from \"./styles.css\";\n\nimport type { ReactNode } from \"react\";\n\nexport type CollapsibleProps = {\n /**\n * Dialog content\n */\n children: ReactNode | Array;\n\n /**\n * Allow collapsible to act as a controlled component\n */\n isOpen?: boolean;\n\n /**\n * Function called with new state when state changes.\n */\n onOpenChange?: (openState: boolean) => void;\n\n /**\n * Element to use as Dialog trigger. Note: Must accept a ref.\n */\n triggerNode: ReactNode;\n};\n\n/**\n * An unstyled, primitive component for creating a collapsible UI element.\n */\nexport function Collapsible({ children, isOpen, onOpenChange, triggerNode }: CollapsibleProps) {\n const [localOpenState, setLocalOpenState] = useState(isOpen);\n\n const handleOpenChange = useCallback(\n (openState: boolean) => {\n setLocalOpenState(openState);\n\n if (onOpenChange) {\n onOpenChange(openState);\n }\n },\n [onOpenChange]\n );\n\n return (\n \n {/**\n * Allow custom trigger node. Must accept a ref.\n * ToDo: Figure out a tidy way to require triggerNode to accept ref,\n * or to wrap triggerNode so it is always able to accept a ref.\n */}\n {triggerNode}\n\n \n {children}\n \n \n );\n}"}}},{"rowIdx":632,"cells":{"text":{"kind":"string","value":"using System.Collections.Generic;\nusing UnityEngine;\nusing System;\nusing UnityEditor;\nusing AstralCandle.Entity;\nusing System.Linq;\nusing AstralCandle.Animation;\nusing UnityEngine.Events;\n\n/*\n--- This code has has been written by Joshua Thompson (https://joshgames.co.uk) ---\n --- Copyright ©️ 2024-2025 AstralCandle Games. All Rights Reserved. ---\n*/\n\npublic class GameLoop : MonoBehaviour{ \n public static GameLoop instance;\n [HideInInspector] public List playerStructures = new();\n [HideInInspector] public List allEntities = new();\n \n #region EDITOR VARIABLES\n [SerializeField] bool showDebug;\n [SerializeField] Transform map;\n [SerializeField] Settings settings;\n [SerializeField] WaveProfile[] waves;\n [SerializeField] EntityCharacter humanEntity;\n [SerializeField] int humansToStartWith = 2;\n [SerializeField] bool startOnPlay;\n [SerializeField] UnityEvent Win, Lose;\n \n #endregion\n #region COSMETIC\n Vector3 previousScale, targetScale;\n \n #endregion\n #region PRIVATE VARIABLES\n const int NUMBER_OF_SPAWN_DIRECTIONS = 4; // UP, DOWN, LEFT, RIGHT\n readonly int[] RESOURCE_NODE_DIRECTIONS = new int[4]{0, 90, 180, 270};\n int _wave = -1;\n \n float _mapScale, previousMapScale; \n\n [SerializeField] Pause pauseState;\n [HideInInspector] public WinLose state;\n #endregion\n \n public float MapScale{\n get => _mapScale;\n private set{\n if(value == _mapScale){ return; }\n _mapScale = value;\n settings.scaleAnimation.ResetTime();\n previousScale = targetScale;\n targetScale = new(value, map.localScale.y, value);\n } \n }\n \n /// \n /// The concurrent wave we are on\n /// \n public int Wave{\n get => _wave;\n private set{\n if(value == _wave){ return; }\n _wave = value; \n }\n }\n \n /// \n /// The current wave we are playing on\n /// \n public Game CurrentGame{\n get;\n private set;\n }\n \n //--- FUNCTIONS\n\n /// \n /// Scales the map in size to match the 'TargetScale' vector\n /// \n void PlayMapAnimation(){\n float value = settings.scaleAnimation.Play();\n map.localScale = Vector3.LerpUnclamped(previousScale, targetScale, value);\n }\n\n public List CalculateResourceSpawnLocations(){\n // Calculate resource spawning locations\n HashSet resourceSpawnLocations = new();\n int maxMapSize = (int)Grid.RoundToGrid(MapScale / 2, settings.cellSize) - settings.cellSize;\n int minMapSize = (int)Grid.RoundToGrid(previousMapScale / 2, settings.cellSize);\n for(int i = minMapSize; i < maxMapSize; i += settings.cellSize){\n for(int x = -i; x < i; x+= settings.cellSize){\n resourceSpawnLocations.Add(new(x, 0, i));\n resourceSpawnLocations.Add(new(-x, 0, -i));\n }\n for(int z = -i; z < i; z+= settings.cellSize){\n resourceSpawnLocations.Add(new(i, 0, z));\n resourceSpawnLocations.Add(new(-i, 0, z));\n }\n }\n System.Random random = new();\n return resourceSpawnLocations.OrderBy(e => random.NextDouble()).ToList(); // Shuffles list\n }\n\n public void SpawnEntities(ref List spawnPositions, params Entity[] entities){\n Transform parentFolder = GameObject.Find(\"_GAME_RESOURCES_\").transform;\n spawnPositions ??= CalculateResourceSpawnLocations();\n\n foreach(Entity e in entities){\n if(spawnPositions.Count <= 0){ continue; }\n\n Vector3 position = spawnPositions[0];\n spawnPositions.RemoveAt(0);\n\n Entity newE = Instantiate(e, position, Quaternion.identity, parentFolder);\n PlayerControls.instance.entities.SubscribeToEntities(newE);\n Collider col = newE.GetComponent();\n\n Vector3 newPos = position;\n newPos.y = (map.localScale.y /2) + col.bounds.extents.y;\n newE.transform.position = newPos;\n\n Vector3 euler = newE.transform.eulerAngles;\n euler.y = RESOURCE_NODE_DIRECTIONS[UnityEngine.Random.Range(0, RESOURCE_NODE_DIRECTIONS.Length-1)];\n newE.transform.eulerAngles = euler;\n }\n }\n\n public void SpawnEntities(ref List spawnPositions, params ResourceSettings[] settings){\n spawnPositions ??= CalculateResourceSpawnLocations();\n\n for(int i = 0; i < settings.Length; i++){\n ResourceSettings r = settings[i];\n int fillAmount = Mathf.FloorToInt(spawnPositions.Count * r.resourcePopulation);\n\n for(int x = 0; x < fillAmount && x < spawnPositions.Count; x++){\n SpawnEntities(ref spawnPositions, r.resourceNode);\n }\n }\n }\n\n public void NewGame(){ \n Wave++;\n\n MapScale = Utilities.Remap(Wave + 1, 0, waves.Length, settings.mapSize.min, settings.mapSize.max);\n CurrentGame = new Game(waves[Wave], map.position, MapScale, (Wave + 1).ToString());\n\n // Spawn resources\n Transform parentFolder = GameObject.Find(\"_GAME_RESOURCES_\").transform;\n List rLocations = CalculateResourceSpawnLocations();\n SpawnEntities(ref rLocations, settings.resources);\n\n // Spawn starting humans\n if(Wave == 0){\n for(int i = 0; i < humansToStartWith; i++){\n SpawnEntities(ref rLocations, humanEntity);\n }\n }\n }\n\n // RUNS ALL ENTITIES\n private void FixedUpdate() {\n if(state != WinLose.In_Game || PlayerControls.instance.Paused){ return; }\n for(int i = allEntities.Count-1; i > -1; i--){ allEntities[i].Run(state); }\n }\n\n void Awake() => instance = this;\n\n /// \n /// Initiates this script\n /// \n void Start(){ \n MapScale = Utilities.Remap(Wave + 1, 0, waves.Length, settings.mapSize.min, settings.mapSize.max);\n previousMapScale = Grid.RoundToGrid((float)settings.mapSize.min * settings.resourceSpawnSubtractMin, settings.cellSize);\n if(startOnPlay){ NewGame(); }\n pauseState.Initiate();\n }\n private void Update() {\n PlayMapAnimation();\n pauseState.OnPause(PlayerControls.instance?.Paused == true);\n if(PlayerControls.instance?.Paused == true){ \n return;\n }\n if((state == WinLose.Win || state == WinLose.Lose) && (Tutorial.instance.CompletedWave || startOnPlay)){ return; }\n\n Keep keepInstance = Keep.instance;\n bool keepExists = keepInstance;\n bool hasOccupants = false; // Should check all structures\n List s = PlayerControls.instance?.entities.GetAllOfType(Keep.instance as EntityStructure);\n foreach(Entity structure in s){\n EntityStructure thisS = structure as EntityStructure;\n if(!thisS){ continue; } \n\n if(thisS.GetOccupants() >0){\n hasOccupants = true;\n break;\n }\n }\n bool hasHumansOnField = PlayerControls.instance?.entities.GetAllOfType(humanEntity).Count > 0;\n \n state = (keepExists && (hasOccupants || hasHumansOnField))? WinLose.In_Game : WinLose.Lose; // If keep exists and we either have occupants OR occupants on field\n \n if(Wave >= waves.Length-1 && CurrentGame.CalculateProgress() >= 1){ \n state = WinLose.Win; \n Win?.Invoke();\n return;\n }\n else if(state == WinLose.Lose && (Tutorial.instance.CompletedWave || startOnPlay)){\n Lose?.Invoke();\n return;\n }\n\n\n \n\n // Ensures the game is always running\n if(CurrentGame != null && CurrentGame.Run() && Wave < waves.Length-1 && state == WinLose.In_Game){ \n previousMapScale = MapScale;\n NewGame();\n return;\n }\n }\n\n private void OnDrawGizmos() {\n #if UNITY_EDITOR\n if(!showDebug || !map){ return; }\n Handles.DrawWireCube(map.position, new Vector3(settings.mapSize.min, map.localScale.y, settings.mapSize.min));\n Handles.DrawWireCube(map.position, new Vector3(settings.mapSize.max, map.localScale.y, settings.mapSize.max));\n #endif\n }\n\n public enum GameState{\n Init,\n Break,\n Wave\n }\n\n public enum WinLose{\n In_Game,\n Win,\n Lose\n }\n\n /// \n /// Used to setup each wave\n /// \n public class Game{\n #region CLASS_VARIABLES\n GameState _state;\n public GameState State{\n get => _state;\n private set{\n if(value == _state){ return; }\n _state = value;\n ProgressBar.instance.UpdateState(State.ToString());\n ProgressBar.instance.UpdateColour((value == GameState.Break)? wave.intermissionColour : wave.waveColour);\n if(value == GameState.Wave){ \n ProgressBar.instance.UpdateValue(waveName);\n ProgressBar.instance.UpdateTarget(0); \n }\n }\n }\n\n Vector3 position;\n float scale;\n string waveName;\n\n float intermission;\n\n /// \n /// Shows how long the intermission is\n /// \n \n WaveProfile wave;\n\n #region ENTITY COUNTERS\n /// \n /// IDs of the characters\n /// \n public HashSet aliveEntities{\n get;\n private set;\n }\n\n /// \n /// The entities remaining for this wave\n /// \n int totalEntities;\n \n int _entitiesCleared;\n /// \n /// The number of entities cleared in this wave. | UPDATES THE PROGRESS BAR WHEN SET\n /// \n int EntitiesCleared{\n get => _entitiesCleared;\n set{\n _entitiesCleared = value;\n ProgressBar.instance.UpdateTarget(CalculateProgress());\n }\n }\n #endregion\n \n int spawnGroupIndex;\n float elapsedSpawnDelay;\n #endregion\n\n /// \n /// Constructor to create a new game\n /// \n /// Information about this wave\n /// The base position of the map\n /// The map scale so we can spawn the entities on the edges\n public Game(WaveProfile waveData, Vector3 position, float scale, string waveName = null){\n this.wave = waveData;\n\n aliveEntities = new();\n this.intermission = waveData.intermission;\n this.totalEntities = waveData.CalculateEntities();\n this.spawnGroupIndex = 0;\n this.EntitiesCleared = 0;\n\n this.position = position;\n this.scale = scale; \n \n waveName ??= waveData.name;\n this.waveName = waveName;\n }\n\n /// \n /// Returns the group data of the given index for this wave\n /// \n WaveProfile.SpawnGroupData GetWaveGroup() => wave.waveData[Mathf.Clamp(spawnGroupIndex, 0, wave.waveData.Length-1)];\n\n /// \n /// Calculates a position on the edge of the map to spawn an entity\n /// \n /// The position we should spawn an entity at\n Vector3 CalculatePosition(){\n int spawnDirection = (int)GetWaveGroup().spawnDirection;\n bool isHorizontal = spawnDirection == 1 || spawnDirection == 3;\n float angle = Utilities.CalculateRadianAngle(spawnDirection, NUMBER_OF_SPAWN_DIRECTIONS);\n\n Vector3 offset = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * (scale/2);\n\n float rndValue = UnityEngine.Random.Range(-1f, 1f);\n float offsetf = rndValue * scale/3;\n offset.x = (isHorizontal)? offsetf: offset.x; // Left/Right\n offset.y = 1.25f;\n offset.z = (!isHorizontal)? offsetf: offset.z; // Up/Down\n return position + offset;\n }\n \n /// \n /// Spawns an entity on the edge of the map on a given direction\n /// \n /// The entity we wish to spawn\n void SpawnEntity(EntityCharacter character){\n // Spawns the character and adds it to alive entities list\n aliveEntities.Add(\n Instantiate(\n character, \n CalculatePosition(), \n Quaternion.identity, \n GameObject.Find(\"_GAME_RESOURCES_\").transform\n ).GetInstanceID()\n );\n } \n\n /// \n /// Attempts to remove the entity from the 'aliveEntities' hashSet so we can see how complete the wave is\n /// \n /// The transform ID of the entity\n public void RemoveEntity(int id){\n if(!aliveEntities.Contains(id)){ return; }\n aliveEntities.Remove(id);\n EntitiesCleared++;\n }\n \n /// \n /// Calculates wave progression \n /// \n /// Value between 0-1\n public float CalculateProgress() => Mathf.Clamp01((float)EntitiesCleared / totalEntities);\n\n /// \n /// Runs this wave; Spawning entities\n /// \n public bool Run(){\n if(CalculateProgress() >= 1){ return true; } // Completed wave!\n\n intermission -= Time.deltaTime;\n State = (intermission >0)? GameState.Break : GameState.Wave;\n \n switch(State){\n case GameState.Break: \n ProgressBar.instance.UpdateValue(Mathf.Ceil(intermission).ToString());\n ProgressBar.instance.UpdateTarget(intermission / wave.intermission);\n break;\n case GameState.Wave:\n // Spawning\n WaveProfile.SpawnGroupData groupData = GetWaveGroup();\n elapsedSpawnDelay -= (elapsedSpawnDelay >0)? Time.deltaTime : 0;\n if(elapsedSpawnDelay <= 0 && spawnGroupIndex <= wave.waveData.Length-1){\n for(int i = 0; i < groupData.quantity; i++){\n foreach(IWave _char in groupData.group.entities.Cast()){\n if(_char == null){ continue; } // Stops any non-'IWave' entites from being spawned\n SpawnEntity(_char as EntityCharacter);\n }\n }\n elapsedSpawnDelay = groupData.spawnDelay;\n spawnGroupIndex++;\n }\n break;\n } \n return false;\n }\n }\n\n /// \n /// The settings which controls this game loop\n /// \n [Serializable] public class Settings{\n public AnimationInterpolation scaleAnimation;\n public Utilities.MinMax mapSize = new(15, 100);\n [Tooltip(\"The distance up to the min map scale where we will start to spawn resources\"), Range(0, 1)]public float resourceSpawnSubtractMin;\n public ResourceSettings[] resources;\n public int cellSize = 1;\n }\n\n [Serializable] public class ResourceSettings{\n [Tooltip(\"The resource we want to spawn\")] public EntityResourceNode resourceNode;\n [Tooltip(\"The % quantity of this resource which will spawn\"), Range(0, 1)] public float resourcePopulation = 0.05f;\n }\n\n /// \n /// Maps positions to a grid\n /// \n public static class Grid{\n public static float RoundToGrid(float value, int cellSize) => Mathf.RoundToInt(value / cellSize) * cellSize; \n public static Vector3 RoundToGrid(Vector3 value, int cellSize) => new Vector3(RoundToGrid(value.x, cellSize), RoundToGrid(value.y, cellSize), RoundToGrid(value.z, cellSize)); \n public static float FloorToGrid(float value, int cellSize) => Mathf.FloorToInt(value / cellSize) * cellSize; \n public static Vector3 FloorToGrid(Vector3 value, int cellSize) => new Vector3(FloorToGrid(value.x, cellSize), FloorToGrid(value.y, cellSize), FloorToGrid(value.z, cellSize)); \n }\n [Serializable] public class Pause{\n [Header(\"SFX Settings\")]\n public AudioSource source;\n [Range(0, 1)] public float onPauseVolume = 0.05f;\n [Range(0, 1)] public float onPausePitch = 0.65f;\n\n public AnimationInterpolation transitionSettings;\n [HideInInspector] public float defaultVolume;\n [HideInInspector] public float defaultPitch;\n\n public void Initiate(){\n defaultVolume = source.volume;\n defaultPitch = source.pitch;\n } \n public void OnPause(bool isPaused){\n float value = transitionSettings.Play(!isPaused);\n\n source.volume = Mathf.LerpUnclamped(defaultVolume, onPauseVolume, value);\n source.pitch = Mathf.LerpUnclamped(defaultPitch, onPausePitch, value);\n }\n }\n [Serializable] public class AudioSettings{\n public AudioClip[] type;\n public Utilities.MinMaxF cooldown;\n public Utilities.MinMaxF pitch = new Utilities.MinMaxF(1, 1);\n public float ActualCooldown{ get; set; }\n\n public void PlaySound(AudioSource s){\n if(ActualCooldown > 0 || type.Length <= 0 || !s) { return; }\n ActualCooldown = UnityEngine.Random.Range(cooldown.min, cooldown.max);\n s.clip = type[UnityEngine.Random.Range(0, type.Length)];\n s.pitch = UnityEngine.Random.Range(pitch.min, pitch.max);\n s.Play();\n }\n\n \n public void PlaySoundWithIncrease(AudioSource s, float value, float step = -1){\n if(ActualCooldown > 0 || type.Length <= 0 || !s) { return; }\n ActualCooldown = UnityEngine.Random.Range(cooldown.min, cooldown.max);\n s.clip = type[UnityEngine.Random.Range(0, type.Length)];\n \n float val = Utilities.Remap(Mathf.Clamp01(value), 0, 1, pitch.min, pitch.max);\n s.pitch = (step > 0)? (float)Math.Round(val / step, 1) * step : val;\n s.Play();\n }\n }\n}"}}},{"rowIdx":633,"cells":{"text":{"kind":"string","value":"import React from 'react';\n\nimport { \n CarContainer, \n HeaderContainer, \n LogoContainer, \n Menu, \n MenuOpenUser \n} from './style/HeaderStyle';\n\nimport Logo from '../../assets/logo/logo.svg';\nimport Burger from '../../assets/header/burger.svg';\n\nimport { Link } from 'react-router-dom';\n\nimport { GlobalContext } from '../../Context/GlobalContext';\n\nimport Car from './ComponentsInHeader/Car/Car';\nimport LoginAndRegisterContainer from './ComponentsInHeader/LoginAndRegisterContainer/LoginAndRegisterContainer';\n\nconst Header = () => {\n\n const { \n bag, \n car, setCar,\n carUserOpen, setCarUserOpen,\n localizationContainer,\n openLoginAndRegisterContainer, setOpenLoginAndRegisterContainer,\n setLogin,\n setRegister,\n setNameRegister,\n setEmailRegister,\n setEnderecoRegister,\n setComplementoRegister,\n setBairroRegister,\n setCepRegister,\n setTelefoneRegister,\n setEmail,\n setPassword\n } = React.useContext(GlobalContext);\n\n \n const [ numberItems, setNumberItems ] = React.useState('');\n\n \n\n React.useEffect(()=>{\n\n if(bag.length >= 1){\n setCar(true);\n\n const totalValuesInArray = [];\n\n for(let i = 0; i position !== undefined);\n\n const total = filterTotalValues.reduce((acc, value) => acc + value, 0);\n\n setNumberItems(total);\n\n }\n\n }, [bag, setCar]);\n\n const textLoginButton = React.useRef();\n\n function textChange(){\n if(textLoginButton.current){\n textLoginButton.current.textContent = \"Click to enter\";\n }\n }\n\n function openCarUser(){\n\n setCarUserOpen(!carUserOpen);\n\n }\n\n function textChangeReverse(){\n if(textLoginButton.current){\n textLoginButton.current.textContent = \"Login\";\n }\n }\n\n\n function moveToLocalizacao(){\n if(localizationContainer.current){\n window.scroll({\n top: localizationContainer.current.offsetTop,\n behavior: \"smooth\"\n })\n }\n }\n\n\n function openLoginOrRegister(event){\n setCarUserOpen(false);\n setOpenLoginAndRegisterContainer(true);\n\n const textCliqued = event.target.textContent;\n\n if(textCliqued === \"Cadastre-se Aqui!\"){\n setLogin(false);\n setRegister(true);\n setNameRegister(\"\")\n setEmailRegister(\"\")\n setEnderecoRegister(\"\")\n setComplementoRegister(\"\")\n setBairroRegister(\"\")\n setCepRegister(\"\")\n setTelefoneRegister(\"\")\n setEmail(\"\")\n setPassword(\"\")\n }\n else{\n setRegister(false);\n setLogin(true);\n setNameRegister(\"\")\n setEmailRegister(\"\")\n setEnderecoRegister(\"\")\n setComplementoRegister(\"\")\n setBairroRegister(\"\")\n setCepRegister(\"\")\n setTelefoneRegister(\"\")\n setEmail(\"\")\n setPassword(\"\")\n }\n }\n\n return (\n \n\n
\n\n \n\n \"Logo_Image\"\n\n \n\n\n \n\n
\n\n \n\n
\n Cadastre-se Aqui!\n
\n\n {\n openLoginAndRegisterContainer && (\n\n \n\n )\n }\n\n\n
\n\n\n \n\n \"My_Burger_Icons\"\n\n {\n car && bag.length >=1 && (\n\n
\n\n

{numberItems}

\n\n
\n )\n }\n\n {\n carUserOpen && bag.length >= 1 && (\n <>\n\n
\n\n
\n\n \n\n \n )\n }\n\n
\n\n\n \n\n
    \n\n \n\n
  • Cardápio
  • \n\n \n\n\n \n\n
  • Restaurente de Lanche Gourmet
  • \n\n \n\n\n \n\n
  • Localização
  • \n\n \n\n\n \n\n
  • Contato
  • \n\n \n\n
\n\n
\n\n\n
\n\n
\n\n
\n )\n}\n\nexport default Header;"}}},{"rowIdx":634,"cells":{"text":{"kind":"string","value":"// Copyright 2022 - 2023 Wenmeng See the COPYRIGHT\n// file at the top-level directory of this distribution.\n// \n// Licensed under the Apache License, Version 2.0 , at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n// \n// Author: tickbh\n// -----\n// Created Date: 2023/09/14 09:42:25\n\nuse std::{\n any::{Any, TypeId},\n net::SocketAddr,\n time::Duration, future::poll_fn,\n};\n\nuse tokio::{\n io::{AsyncRead, AsyncWrite},\n net::{TcpStream},\n};\nuse webparse::{http::http2::frame::StreamIdentifier, Binary, Request, Response, Serialize, Version, BinaryMut};\n\nuse crate::{\n ProtError, ProtResult, RecvRequest, RecvStream, ServerH2Connection, TimeoutLayer, OperateTrait, Middleware,\n};\nuse super::http1::ServerH1Connection;\n\npub struct Builder {\n inner: ServerOption,\n}\n\nimpl Builder {\n pub fn new() -> Self {\n Self {\n inner: ServerOption::default(),\n }\n }\n\n pub fn connect_timeout(mut self, connect_timeout: Duration) -> Self {\n if self.inner.timeout.is_none() {\n self.inner.timeout = Some(TimeoutLayer::new());\n }\n self.inner.timeout.as_mut().unwrap().connect_timeout = Some(connect_timeout);\n self\n }\n\n pub fn ka_timeout(mut self, ka_timeout: Duration) -> Self {\n if self.inner.timeout.is_none() {\n self.inner.timeout = Some(TimeoutLayer::new());\n }\n self.inner.timeout.as_mut().unwrap().ka_timeout = Some(ka_timeout);\n self\n }\n\n pub fn read_timeout(mut self, read_timeout: Duration) -> Self {\n if self.inner.timeout.is_none() {\n self.inner.timeout = Some(TimeoutLayer::new());\n }\n self.inner.timeout.as_mut().unwrap().read_timeout = Some(read_timeout);\n self\n }\n\n pub fn write_timeout(mut self, write_timeout: Duration) -> Self {\n if self.inner.timeout.is_none() {\n self.inner.timeout = Some(TimeoutLayer::new());\n }\n self.inner.timeout.as_mut().unwrap().write_timeout = Some(write_timeout);\n self\n }\n\n pub fn timeout(mut self, timeout: Duration) -> Self {\n if self.inner.timeout.is_none() {\n self.inner.timeout = Some(TimeoutLayer::new());\n }\n self.inner.timeout.as_mut().unwrap().timeout = Some(timeout);\n self\n }\n\n pub fn timeout_layer(mut self, timeout: Option) -> Self {\n self.inner.timeout = timeout;\n self\n }\n\n pub fn addr(mut self, addr: SocketAddr) -> Self {\n self.inner.addr = Some(addr);\n self\n }\n\n pub fn value(self) -> ServerOption {\n self.inner\n }\n\n pub fn middle(mut self, middle: M) -> Self {\n self.inner.middles.push(Box::new(middle));\n self\n }\n\n pub fn stream(self, stream: T) -> Server\n where\n T: AsyncRead + AsyncWrite + Unpin,\n {\n let mut server = Server::new(stream, self.inner.addr);\n server.set_timeout_layer(self.inner.timeout.clone());\n server\n }\n}\n\n#[derive(Default)]\npub struct ServerOption {\n addr: Option,\n timeout: Option,\n middles: Vec>,\n}\n\npub struct Server\nwhere\n T: AsyncRead + AsyncWrite + Unpin + Sized,\n{\n http1: Option>,\n http2: Option>,\n middles: Vec>,\n addr: Option,\n timeout: Option,\n req_num: usize,\n max_req_num: usize,\n}\n\nimpl Server {\n pub fn builder() -> Builder {\n Builder::new()\n }\n}\n\nimpl Server\nwhere\n T: AsyncRead + AsyncWrite + Unpin,\n{\n pub fn new(io: T, addr: Option) -> Self {\n Self {\n http1: Some(ServerH1Connection::new(io)),\n http2: None,\n middles: vec![],\n addr,\n\n timeout: None,\n req_num: 0,\n max_req_num: usize::MAX,\n }\n }\n}\n\nimpl Server\nwhere\n T: AsyncRead + AsyncWrite + Unpin\n{\n pub fn new_by_cache(io: T, addr: Option, binary: BinaryMut) -> Self {\n Self {\n http1: Some(ServerH1Connection::new_by_cache(io, binary)),\n http2: None,\n addr,\n middles: vec![],\n timeout: None,\n req_num: 0,\n max_req_num: usize::MAX,\n }\n }\n\n pub fn into_io(self) -> T {\n if self.http1.is_some() {\n self.http1.unwrap().into_io()\n } else {\n self.http2.unwrap().into_io()\n }\n }\n\n pub fn set_read_timeout(&mut self, read_timeout: Option) {\n if self.timeout.is_none() {\n self.timeout = Some(TimeoutLayer::new());\n }\n self.timeout\n .as_mut()\n .unwrap()\n .set_read_timeout(read_timeout);\n if let Some(http) = &mut self.http1 {\n http.set_read_timeout(read_timeout);\n } else if let Some(http) = &mut self.http2 {\n http.set_read_timeout(read_timeout);\n }\n }\n\n pub fn set_write_timeout(&mut self, write_timeout: Option) {\n if self.timeout.is_none() {\n self.timeout = Some(TimeoutLayer::new());\n }\n self.timeout\n .as_mut()\n .unwrap()\n .set_write_timeout(write_timeout);\n if let Some(http) = &mut self.http1 {\n http.set_write_timeout(write_timeout);\n } else if let Some(http) = &mut self.http2 {\n http.set_write_timeout(write_timeout);\n }\n }\n\n pub fn set_timeout(&mut self, timeout: Option) {\n if self.timeout.is_none() {\n self.timeout = Some(TimeoutLayer::new());\n }\n self.timeout.as_mut().unwrap().set_timeout(timeout);\n if let Some(http) = &mut self.http1 {\n http.set_timeout(timeout);\n } else if let Some(http) = &mut self.http2 {\n http.set_timeout(timeout);\n }\n }\n\n pub fn set_ka_timeout(&mut self, timeout: Option) {\n if self.timeout.is_none() {\n self.timeout = Some(TimeoutLayer::new());\n }\n self.timeout.as_mut().unwrap().set_ka_timeout(timeout);\n if let Some(http) = &mut self.http1 {\n http.set_ka_timeout(timeout);\n } else if let Some(http) = &mut self.http2 {\n http.set_ka_timeout(timeout);\n }\n }\n\n pub fn set_timeout_layer(&mut self, timeout: Option) {\n self.timeout = timeout.clone();\n if let Some(http) = &mut self.http1 {\n http.set_timeout_layer(timeout);\n } else if let Some(http) = &mut self.http2 {\n http.set_timeout_layer(timeout);\n }\n }\n \n pub fn middle(&mut self, middle: M) {\n self.middles.push(Box::new(middle));\n }\n\n pub fn get_req_num(&self) -> usize {\n self.req_num\n }\n\n pub async fn send_response(\n &mut self,\n res: Response,\n stream_id: Option,\n ) -> ProtResult<()>\n where\n RecvStream: From,\n R: Serialize,\n {\n let _result = if let Some(h1) = &mut self.http1 {\n h1.send_response(res.into_type::()).await?;\n } else if let Some(h2) = &mut self.http2 {\n if let Some(stream_id) = stream_id {\n let _recv = RecvStream::only(Binary::new());\n let res = res.into_type::();\n h2.send_response(res, stream_id).await?;\n }\n };\n\n Ok(())\n }\n\n pub async fn req_into_type(mut r: RecvRequest) -> Request\n where\n Req: From,\n Req: Serialize + Any,\n {\n if TypeId::of::() == TypeId::of::() {\n r.into_type::()\n } else {\n if !r.body().is_end() {\n let _ = r.body_mut().wait_all().await;\n }\n r.into_type::()\n }\n }\n\n pub async fn try_wait_req(r: &mut RecvRequest) -> ProtResult<()>\n where\n Req: From,\n Req: Serialize,\n {\n if !r.body().is_end() {\n let _ = r.body_mut().wait_all().await;\n }\n Ok(())\n }\n\n pub async fn incoming(&mut self, mut f: F) -> ProtResult>\n where\n F: OperateTrait + Send,\n {\n loop {\n let result = if let Some(h1) = &mut self.http1 {\n h1.incoming(&mut f, &self.addr, &mut self.middles).await\n } else if let Some(h2) = &mut self.http2 {\n h2.incoming(&mut f, &self.addr, &mut self.middles).await\n } else {\n Ok(Some(true))\n };\n match result {\n Ok(None) | Ok(Some(false)) => {\n self.req_num = self.req_num.wrapping_add(1);\n }\n Err(ProtError::ServerUpgradeHttp2(b, r)) => {\n if self.http1.is_some() {\n self.http2 = Some(self.http1.take().unwrap().into_h2(b));\n if let Some(r) = r {\n self.http2\n .as_mut()\n .unwrap()\n .handle_request(&self.addr, r, &mut f, &mut self.middles)\n .await?;\n\n self.req_num = self.req_num.wrapping_add(1);\n }\n } else {\n return Err(ProtError::ServerUpgradeHttp2(b, r));\n }\n }\n Err(e) => {\n for i in 0usize .. self.middles.len() {\n self.middles[i].process_error(None, &e).await;\n }\n return Err(e);\n }\n Ok(Some(true)) => return Ok(Some(true)),\n };\n if self.req_num >= self.max_req_num {\n self.flush().await?;\n return Ok(Some(true))\n }\n }\n }\n\n \n pub async fn flush(&mut self) -> ProtResult<()>\n {\n if let Some(h1) = &mut self.http1 {\n let _ = poll_fn(|cx| {\n h1.poll_write(cx)\n }).await;\n } else if let Some(h2) = &mut self.http2 {\n let _ = poll_fn(|cx| {\n h2.poll_write(cx)\n }).await;\n };\n return Ok(())\n }\n\n pub fn set_max_req(&mut self, num: usize) {\n self.max_req_num = num;\n }\n}"}}},{"rowIdx":635,"cells":{"text":{"kind":"string","value":"import 'package:flutter/material.dart';\n\nimport '../common/mask_layer.dart';\n\n/// 遮罩层\nclass MaskLayerWidget extends StatelessWidget {\n const MaskLayerWidget({\n super.key,\n required this.maskLayer,\n });\n\n final MaskLayer maskLayer;\n\n @override\n Widget build(BuildContext context) {\n return InkWell(\n onTap: maskLayer.onTap,\n child: LayoutBuilder(builder: _builderWidget),\n );\n }\n\n Widget _builderWidget(BuildContext context, BoxConstraints constraints) {\n double width = constraints.maxWidth * maskLayer.percent;\n double height = constraints.maxHeight;\n\n return SizedBox(\n width: width,\n height: height,\n child: maskLayer.widget ?? Container(\n decoration: const BoxDecoration(\n gradient: LinearGradient(\n begin: Alignment.topLeft,\n end: Alignment.bottomRight,\n colors: [Color(0xFFf7f373), Color(0xFFc5b9ab)],\n ),\n ),\n ),\n );\n }\n}"}}},{"rowIdx":636,"cells":{"text":{"kind":"string","value":"---\ntitle: การจัดการภาพ\nlinktitle: การจัดการภาพ\nsecond_title: Aspose.Page .NET API\ndescription: ค้นพบพลังของ Aspose.Page สำหรับ .NET ผ่านบทช่วยสอนการจัดการรูปภาพของเรา ครอบตัดและปรับขนาดภาพ EPS ได้อย่างง่ายดายเพื่อผลลัพธ์ที่น่าทึ่งและแม่นยำ\ntype: docs\nweight: 26\nurl: /th/net/image-manipulation/\n---\n## การแนะนำ\n\nคุณพร้อมที่จะยกระดับทักษะการจัดการภาพ EPS ใน .NET แล้วหรือยัง? เจาะลึกบทช่วยสอนการจัดการรูปภาพที่ครอบคลุมของเราด้วย Aspose.Page สำหรับ .NET ซึ่งเราจะแนะนำคุณตลอดกระบวนการครอบตัดและปรับขนาดรูปภาพ EPS อย่างราบรื่น\n\n## ครอบตัดรูปภาพ EPS ด้วย Aspose.Page สำหรับ .NET\nคุณเบื่อกับการดิ้นรนกับเครื่องมือครอบตัดรูปภาพที่ซับซ้อนหรือไม่? ไม่ต้องมองอีกต่อไป! บทช่วยสอนของเราเกี่ยวกับ \"ครอบตัดรูปภาพ EPS ด้วย Aspose.Page สำหรับ .NET\" ให้คำแนะนำทีละขั้นตอนเกี่ยวกับวิธีการสำรวจโลกอันทรงพลังของ Aspose.Page เพื่อครอบตัดรูปภาพ EPS ได้อย่างง่ายดาย\n\n### ปลดปล่อยศักยภาพ\nAspose.Page สำหรับ .NET ปลดล็อกโลกแห่งความเป็นไปได้ที่ราบรื่น ช่วยให้คุณสามารถครอบตัดรูปภาพ EPS ได้อย่างแม่นยำ ไม่ว่าคุณจะเป็นมือใหม่หรือนักพัฒนาที่มีประสบการณ์ บทช่วยสอนของเรารองรับทุกระดับทักษะ บอกลากระบวนการที่น่าเบื่อ และพบกับผลลัพธ์อันน่าทึ่ง!\n\n### การปรับขนาดได้อย่างง่ายดาย\nนำทางกระบวนการปรับขนาดได้อย่างง่ายดายด้วย Aspose.Page เราแนะนำคุณในการบรรลุความแม่นยำในระดับจุด นิ้ว มิลลิเมตร และเปอร์เซ็นต์ บอกลาการบิดเบือนและพบกับภาพ EPS ที่มีขนาดสมบูรณ์แบบซึ่งตรงตามข้อกำหนดของโครงการของคุณ\n\n### เห็นภาพการเปลี่ยนแปลง\nบทช่วยสอนของเราไม่เพียงแค่สอนเท่านั้น แต่ยังแสดงภาพการเปลี่ยนแปลงอีกด้วย มีส่วนร่วมกับคำอธิบายโดยละเอียด รูปภาพ และตัวอย่างที่ทำให้กระบวนการครอบตัดมีชีวิต ดูผลกระทบของแต่ละขั้นตอนและเพิ่มความมั่นใจในทักษะการจัดการภาพของคุณ\n\n### เพิ่มขั้นตอนการพัฒนาของคุณ\n Aspose.Page สำหรับ .NET ไม่ได้เป็นเพียงเครื่องมือเท่านั้น มันเป็นตัวเปลี่ยนเกมสำหรับขั้นตอนการพัฒนาของคุณ เรียนรู้วิธีบูรณาการการจัดการภาพอย่างราบรื่น ประหยัดเวลาและความพยายาม ยกระดับโครงการของคุณด้วยภาพ EPS ที่น่าดึงดูดและครอบตัดอย่างแม่นยำ[อ่านเพิ่มเติม](./crop-eps-images/)\n\n## ปรับขนาดภาพ EPS ด้วย Aspose.Page สำหรับ .NET\nพร้อมที่จะควบคุมขนาดภาพ EPS ของคุณใน .NET แล้วหรือยัง? บทช่วยสอนของเราเกี่ยวกับ \"การปรับขนาดรูปภาพ EPS ด้วย Aspose.Page สำหรับ .NET\" ช่วยให้คุณสามารถปรับขนาดรูปภาพได้อย่างแม่นยำ ซึ่งตอบสนองความต้องการเฉพาะของโปรเจ็กต์ของคุณ\n\n### แม่นยำในทุกมิติ\nAspose.Page สำหรับ .NET รับประกันความแม่นยำในทุกมิติ ไม่ว่าคุณจะทำงานกับจุด นิ้ว มิลลิเมตร หรือเปอร์เซ็นต์ บทช่วยสอนของเราจะให้ข้อมูลเชิงลึกโดยละเอียดเกี่ยวกับการปรับขนาดที่สมบูรณ์แบบ ไม่มีการคาดเดาอีกต่อไป มีเพียงผลลัพธ์ที่แม่นยำเท่านั้น\n\n### บูรณาการอย่างราบรื่น\n เรียนรู้วิธีผสานรวม Aspose.Page เข้ากับโปรเจ็กต์ .NET ของคุณได้อย่างราบรื่นเพื่อการปรับขนาดรูปภาพอย่างมีประสิทธิภาพ คำแนะนำทีละขั้นตอนของเราทำให้กระบวนการง่ายขึ้น ทำให้นักพัฒนาทุกระดับสามารถเข้าถึงได้ ยกระดับโปรเจ็กต์ของคุณด้วยรูปภาพที่เข้ากับการออกแบบของคุณได้อย่างลงตัว[อ่านเพิ่มเติม](./resize-eps-images/)\n\nสำรวจโลกของ Aspose.Page สำหรับ .NET ด้วยบทช่วยสอนการจัดการรูปภาพของเรา และเปลี่ยนทักษะการจัดการรูปภาพ EPS ของคุณวันนี้!\n## บทช่วยสอนการจัดการรูปภาพ\n### [ครอบตัดรูปภาพ EPS ด้วย Aspose.Page สำหรับ .NET](./crop-eps-images/)\nสำรวจโลกที่ไร้รอยต่อของการจัดการภาพ EPS ใน .NET ด้วย Aspose.Page ครอบตัดและปรับขนาดรูปภาพได้อย่างง่ายดายเพื่อผลลัพธ์ที่น่าทึ่ง\n### [ปรับขนาดภาพ EPS ด้วย Aspose.Page สำหรับ .NET](./resize-eps-images/)\nสำรวจกระบวนการปรับขนาดอิมเมจ EPS ใน .NET ได้อย่างราบรื่นโดยใช้ Aspose.Page ให้ความแม่นยำในระดับจุด นิ้ว มิลลิเมตร และเปอร์เซ็นต์ได้อย่างง่ายดาย"}}},{"rowIdx":637,"cells":{"text":{"kind":"string","value":"import java.util.Scanner;\nabstract class shape__{\n final double pi=3.14;\n Scanner sn=new Scanner(System.in);\n abstract void findArea();\n\n}\nclass Rectangle__ extends shape__{\n int l,b;\n Rectangle__(){\n System.out.print(\"Enter length and breadth : \");\n l=sn.nextInt();\n b=sn.nextInt();\n }\n void findArea(){\n System.out.print(\"\\nArea of Rectangle : \"+(l*b));\n }\n}\nclass Circle__ extends shape__{\n double r;\n Circle__(){\n System.out.print(\"Enter radius : \");\n r=sn.nextDouble();\n }\n void findArea(){\n System.out.print(\"\\nArea of Circle : \"+(pi*r*r));\n }\n}\nclass Square__ extends shape__{\n int a;\n Square__(){\n System.out.print(\"Enter side : \");\n a=sn.nextInt();\n }\n void findArea(){\n System.out.print(\"\\nArea of the Square : \"+(a*a)+\"\\n\\n\");\n }\n}\n\npublic class ShapeAbstract {\n public static void main(String args[]){\n System.out.println(\"Area of Shapes\");\n Rectangle__ re=new Rectangle__();\n Circle__ ci=new Circle__();\n Square__ sq=new Square__();\n System.out.println(\"\\n_____________RECTANGLE______________\");\n re.findArea();\n System.out.println(\"\\n\\n_____________CIRCLE______________\");\n ci.findArea();\n System.out.println(\"\\n\\n_____________SQUARE______________\");\n sq.findArea();\n } \n}"}}},{"rowIdx":638,"cells":{"text":{"kind":"string","value":"# Retail Example\n\nAs a result of having to invest in omnichannel capabilities during the \npandemic, the retail industry should be better placed to integrate \nGAI into existing digital platforms. Such integration could be \nparticularly important as companies look for new ways to \ndifferentiate and personalise products, while remaining cost-competitive\n\n![Sector deep-dive: Retail and Customer Services](https://raw.githubusercontent.com/rohit-lakhanpal/build-your-own-copilot/main/docs/img/retail-and-customer-services.png)\n\nReferences: [Australia’s Generative AI opportunity Research paper | TechCouncil of Australia](https://techcouncil.com.au/wp-content/uploads/2023/07/230714-Australias-Gen-AI-Opportunity-Final-report-vF4.pdf).\n\n\n| | |\n| -: | :- |\n| Industry | Retail |\n| Use case | Key feature summarisation and product descriptions to present most relevant content in concise form |\n| WHO | Retail product mangers |\n| WHAT | AOAI takes a very long product description and summarizes it into one sentence. |\n| WOW | Significantly reduces the time for product owners and marketers to produce content. |\n\n## Stage 1\n| | |\n| -: | :- |\n| Overview | Summarise product description |\n| Techniques | Prompt Engineering - zero shot example |\n| Model | GPT 35 Turbo (0613) |\n| Weights | TopP:0.95; Temp:0.7 |\n\n**System Prompt**\n\n```text\nYou are an AI assistant that summarises product descriptions. The summary should be limited to one sentence. \n```\n\n**User Prompt**\n```text\nFor one person \nUse on up to 5 devices simultaneously \nWorks on PC, Mac, iPhone, iPad, and Android phones and tablets \n1 TB (1,000 GB) of secure cloud storage \nWord, Excel, PowerPoint, and OneNote with offline access and premium features \nMicrosoft Defender advanced security for your personal data and devices \nOneDrive ransomware protection for your files and photos \nOutlook ad-free secure email \nMicrosoft Editor advanced spelling, grammar, and writing assistance \nClipchamp video editor with premium filters and effects \nPremium, customizable templates \nExpanded content library of high-quality photos, icons, fonts, videos, and audio \nContact support via chat or email to get help when you need it\n```\n\n**Output**\n\n```text\nGet the ultimate productivity package with Microsoft 365 Personal, including 1TB cloud storage, advanced security features, and premium software for all your devices!\n```\n\n## Stage 2\n\n| | |\n| -: | :- |\n| Overview | Summarise product description in the voice of the customer |\n| Techniques | Prompt Engineering - few shot example |\n| Model | GPT 35 Turbo (0613) |\n| Weights | TopP:0.95; Temp:0.7 |\n\n\n**System Prompt**\n\n```text\nYou are an AI assistant that summarises product descriptions. The summary should be limited to one sentence. \n\nYou can only respond in JSON in the format of {\"product description\":summarised description}\n```\n\n**User Prompt**\n```text\nFor one person \nUse on up to 5 devices simultaneously \nWorks on PC, Mac, iPhone, iPad, and Android phones and tablets \n1 TB (1,000 GB) of secure cloud storage \nWord, Excel, PowerPoint, and OneNote with offline access and premium features \nMicrosoft Defender advanced security for your personal data and devices \nOneDrive ransomware protection for your files and photos \nOutlook ad-free secure email \nMicrosoft Editor advanced spelling, grammar, and writing assistance \nClipchamp video editor with premium filters and effects \nPremium, customizable templates \nExpanded content library of high-quality photos, icons, fonts, videos, and audio \nContact support via chat or email to get help when you need it\n```\n\n**Output**\n\n```text\n\n{\n\"product description\": \"Microsoft 365 Personal includes 1 TB of secure cloud storage, premium features for Word, Excel, PowerPoint, and OneNote, advanced security for personal data and devices, ad-free secure email, advanced spelling and grammar assistance, and access to a content library of high-quality photos, icons, fonts, videos, and audio.\"\n}\n```"}}},{"rowIdx":639,"cells":{"text":{"kind":"string","value":"/**\n * https://leetcode-cn.com/problems/sort-colors/\n * 颜色分类\n */\n\n/**\n * 【冒泡排序】\n * ① 从头开始比较每一对相邻元素,如果第1个比第2个大,就交换它们的位置\n * 执行完一轮后,最未尾那个元素就是最大的元素\n * ② 忽略①中曾经找到的最大元素,重复执行步骤①,直到全部元素有序\n */\nlet sortColors = function sortColors(nums: number[]): void {\n for (let i = 0; i < nums.length; i++)\n for (let j = nums.length - 1; j > i; j--)\n if (nums[j] < nums[j - 1])\n [nums[j], nums[j - 1]] = [nums[j - 1], nums[j]]\n}\n\n/**\n * 【选择排序】\n * ① 从序列中找出最大的那个元素,然后与最未尾的元素交换位置\n * 执行完一轮后,最未尾的那个元素就是最大的元素\n * ② 忽略①中曾经找到的最大元素,重复执行步骤①\n */\nsortColors = function sortColors(nums: number[]): void {\n for (let i = nums.length - 1; i > 0; i--) {\n let max = 0 // 最大元素的下标\n for (let j = 0; j <= i; j++)\n max = (nums[max] < nums[j]) ? j : max;\n [nums[max], nums[i]] = [nums[i], nums[max]]\n }\n}\n\n/**\n * 【插入排序】\n * ① 在执行过程中,插入排序会将序列分为 2 部分\n * 头部是已经排好序的,尾部是待排序的\n * ② 从头开始扫描每一个元素\n * 每当扫描到一个元素,就将它插入到头部合适的位置,使得头部数据依然保持有序\n */\nsortColors = function sortColors(nums: number[]): void {\n for (let i = 0; i < nums.length; i++) {\n let cur = i;\n while (cur > 0 && nums[cur] > nums[cur - 1]) {\n [nums[cur], nums[cur - 1]] = [nums[cur - 1], nums[cur]]\n cur--\n }\n }\n}\n\n/**\n * 一次遍历\n */\nsortColors = function sortColors(nums: number[]): void {\n let left = 0, right = nums.length - 1\n // left 指向第一个非 0 的数\n while (nums[left] == 0) left++;\n // right 指向从后往前第一个非 2 的数\n while (nums[right] == 2) right--;\n\n let i = left\n while (i <= right && left <= right) {\n if (nums[i] == 0) {\n [nums[left], nums[i]] = [nums[i], nums[left]]\n left++\n i++\n } else if (nums[i] == 2) {\n [nums[right], nums[i]] = [nums[i], nums[right]]\n right--\n } else i++\n }\n}"}}},{"rowIdx":640,"cells":{"text":{"kind":"string","value":"import React, { Component } from \"react\";\nimport { Switch, Route, Redirect } from \"react-router-dom\";\nimport { connect } from \"react-redux\";\n\nimport { HomePage } from \"../pages/homepage\";\nimport { ShopPage } from \"../pages/shop\";\nimport { SignInAndSignUpPage } from \"../pages/SignIn_and_SignUp\";\nimport { Header } from \"../components/Header\";\n\nimport { auth, createUserProfileDocument } from \"../firebase/firebase.utils\";\nimport { setCurrentUser } from \"../redux/user/user.actions\";\n\nimport \"./App.scss\";\n\nclass App extends Component {\n // state = {\n // currentUser: null\n // };\n unsubscribeFromAuth = null;\n componentDidMount() {\n const { setCurrentUser } = this.props;\n this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {\n if (userAuth) {\n const userRef = await createUserProfileDocument(userAuth);\n userRef.onSnapshot(snapshot => {\n setCurrentUser({\n id: snapshot.id,\n ...snapshot.data()\n });\n });\n }\n setCurrentUser(userAuth);\n });\n }\n componentWillUnmount() {\n this.unsubscribeFromAuth();\n }\n render() {\n return (\n
\n
\n \n \n \n \n this.props.currentUser ? (\n \n ) : (\n \n )\n }\n />\n \n
\n );\n }\n}\n\nconst mapStateToProps = ({ user }) => ({\n currentUser: user.currentUser\n});\n\nconst mapDispatchToProps = dispatch => ({\n setCurrentUser: user => dispatch(setCurrentUser(user))\n});\n\nexport default connect(\n mapStateToProps,\n mapDispatchToProps\n)(App);"}}},{"rowIdx":641,"cells":{"text":{"kind":"string","value":"/* eslint-disable key-spacing */\nimport { AggregateRoot } from '@nestjs/cqrs';\nimport { LiteralObject, Utils } from '@aurorajs.dev/core';\nimport {\n IamRoleId,\n IamRoleName,\n IamRoleIsMaster,\n IamRolePermissionIds,\n IamRoleAccountIds,\n IamRoleCreatedAt,\n IamRoleUpdatedAt,\n IamRoleDeletedAt,\n} from './value-objects';\nimport { IamCreatedRoleEvent } from '../application/events/iam-created-role.event';\nimport { IamUpdatedRoleEvent } from '../application/events/iam-updated-role.event';\nimport { IamDeletedRoleEvent } from '../application/events/iam-deleted-role.event';\nimport { IamPermission } from '@app/iam/permission';\nimport { IamAccount } from '@app/iam/account';\n\nexport class IamRole extends AggregateRoot\n{\n id: IamRoleId;\n name: IamRoleName;\n isMaster: IamRoleIsMaster;\n permissionIds: IamRolePermissionIds;\n accountIds: IamRoleAccountIds;\n createdAt: IamRoleCreatedAt;\n updatedAt: IamRoleUpdatedAt;\n deletedAt: IamRoleDeletedAt;\n\n // eager relationship\n permissions: IamPermission[];\n accounts: IamAccount[];\n\n constructor(\n id: IamRoleId,\n name: IamRoleName,\n isMaster: IamRoleIsMaster,\n permissionIds: IamRolePermissionIds,\n accountIds: IamRoleAccountIds,\n createdAt: IamRoleCreatedAt,\n updatedAt: IamRoleUpdatedAt,\n deletedAt: IamRoleDeletedAt,\n\n permissions?: IamPermission[],\n accounts?: IamAccount[],\n )\n {\n super();\n this.id = id;\n this.name = name;\n this.isMaster = isMaster;\n this.permissionIds = permissionIds;\n this.accountIds = accountIds;\n this.createdAt = createdAt;\n this.updatedAt = updatedAt;\n this.deletedAt = deletedAt;\n\n // eager relationship\n this.permissions = permissions;\n this.accounts = accounts;\n }\n\n static register (\n id: IamRoleId,\n name: IamRoleName,\n isMaster: IamRoleIsMaster,\n permissionIds: IamRolePermissionIds,\n accountIds: IamRoleAccountIds,\n createdAt: IamRoleCreatedAt,\n updatedAt: IamRoleUpdatedAt,\n deletedAt: IamRoleDeletedAt,\n\n permissions?: IamPermission[],\n accounts?: IamAccount[],\n ): IamRole\n {\n return new IamRole(\n id,\n name,\n isMaster,\n permissionIds,\n accountIds,\n createdAt,\n updatedAt,\n deletedAt,\n\n permissions,\n accounts,\n );\n }\n\n created(role: IamRole): void\n {\n this.apply(\n new IamCreatedRoleEvent(\n role.id.value,\n role.name.value,\n role.isMaster.value,\n role.permissionIds?.value,\n role.accountIds?.value,\n role.createdAt?.value,\n role.updatedAt?.value,\n role.deletedAt?.value,\n ),\n );\n }\n\n updated(role: IamRole): void\n {\n this.apply(\n new IamUpdatedRoleEvent(\n role.id?.value,\n role.name?.value,\n role.isMaster?.value,\n role.permissionIds?.value,\n role.accountIds?.value,\n role.createdAt?.value,\n role.updatedAt?.value,\n role.deletedAt?.value,\n ),\n );\n }\n\n deleted(role: IamRole): void\n {\n this.apply(\n new IamDeletedRoleEvent(\n role.id.value,\n role.name.value,\n role.isMaster.value,\n role.permissionIds?.value,\n role.accountIds?.value,\n role.createdAt?.value,\n role.updatedAt?.value,\n role.deletedAt?.value,\n ),\n );\n }\n\n toDTO(): LiteralObject\n {\n return {\n id: this.id.value,\n name: this.name.value,\n isMaster: this.isMaster.value,\n permissionIds: this.permissionIds?.value,\n accountIds: this.accountIds?.value,\n createdAt: this.createdAt?.value,\n updatedAt: this.updatedAt?.value,\n deletedAt: this.deletedAt?.value,\n\n // eager relationship\n permissions: this.permissions?.map(item => item.toDTO()),\n accounts: this.accounts?.map(item => item.toDTO()),\n };\n }\n\n // function called to get data for repository side effect methods\n toRepository(): LiteralObject\n {\n return {\n id: this.id.value,\n name: this.name.value,\n isMaster: this.isMaster.value,\n permissionIds: this.permissionIds?.value,\n accountIds: this.accountIds?.value,\n createdAt: this.createdAt?.value,\n updatedAt: this.updatedAt?.value,\n deletedAt: this.deletedAt?.value,\n\n // eager relationship\n permissions: this.permissions?.map(item => item.toDTO()),\n accounts: this.accounts?.map(item => item.toDTO()),\n };\n }\n}"}}},{"rowIdx":642,"cells":{"text":{"kind":"string","value":"//\n// Copyright 2020 Electronic Arts Inc.\n//\n// TiberianDawn.DLL and RedAlert.dll and corresponding source code is free \n// software: you can redistribute it and/or modify it under the terms of \n// the GNU General Public License as published by the Free Software Foundation, \n// either version 3 of the License, or (at your option) any later version.\n\n// TiberianDawn.DLL and RedAlert.dll and corresponding source code is distributed \n// in the hope that it will be useful, but with permitted additional restrictions \n// under Section 7 of the GPL. See the GNU General Public License in LICENSE.TXT \n// distributed with this program. You should have received a copy of the \n// GNU General Public License along with permitted additional restrictions \n// with this program. If not, see https://github.com/electronicarts/CnC_Remastered_Collection\n\n/* $Header: /CounterStrike/BAR.H 1 3/03/97 10:24a Joe_bostic $ */\n/***********************************************************************************************\n *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***\n ***********************************************************************************************\n * *\n * Project Name : Command & Conquer *\n * *\n * File Name : BAR.H *\n * *\n * Programmer : Joe L. Bostic *\n * *\n * Start Date : 08/16/96 *\n * *\n * Last Update : August 16, 1996 [JLB] *\n * *\n *---------------------------------------------------------------------------------------------*\n * Functions: *\n * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */\n\n#ifndef BAR_H\n#define BAR_H\n\n/*\n**\tThe \"bool\" integral type was defined by the C++ committee in\n**\tNovember of '94. Until the compiler supports this, use the following\n**\tdefinition.\n*/\n#ifndef __BORLANDC__\n#ifndef TRUE_FALSE_DEFINED\n#define TRUE_FALSE_DEFINED\nenum {false=0,true=1};\ntypedef int bool;\n#endif\n#endif\n\n#include \"fixed.h\"\n\n\n/*\n**\tThis is a manager for a progress (or other) bargraph. Such a graph consists of a fill\n**\tand a background region. The fill percentage of the bargraph is controlled by an\n**\tupdate value. The bargraph can be optionally outlined.\n*/\nclass ProgressBarClass\n{\n\tpublic:\n\t\tProgressBarClass(int x, int y, int width, int height, int forecolor, int backcolor, int bordercolor=0);\n\n\t\tbool Update(fixed value);\n\t\tvoid Redraw(void) const;\n\n\tprivate:\n\n\t\tvoid Outline(void) const;\n\t\tbool Is_Horizontal(void) const;\n\t\tbool Is_Outlined(void) const {return(BorderColor != 0);}\n\n\t\t/*\n\t\t**\tThis is the upper left coordinates of the bargraph.\n\t\t*/\n\t\tint X,Y;\n\n\t\t/*\n\t\t**\tThis is the dimensions of the bargraph.\n\t\t*/\n\t\tint Width, Height;\n\n\t\t/*\n\t\t**\tThese are the colors to use when drawing the progress bar.\n\t\t*/\n\t\tint BarColor;\n\t\tint BackColor;\n\t\tint BorderColor;\n\n\t\t/*\n\t\t**\tThis is the current value of the bargraph.\n\t\t*/\n\t\tfixed CurrentValue;\n\n\t\t/*\n\t\t**\tThis is the current value as of the last time the bargraph was rendered.\n\t\t*/\n\t\tfixed LastDisplayCurrent;\n\n\t\t/*\n\t\t**\tIf the bargraph has been drawn at least once, then this flag will\n\t\t**\tbe true.\n\t\t*/\n\t\tunsigned IsDrawn:1;\n};\n\n\n#endif"}}},{"rowIdx":643,"cells":{"text":{"kind":"string","value":"import { v4 as uuidv4 } from 'uuid';\nimport { comparing, hashing } from '../utils/bcrypto';\nimport { IUser, IUserUpdate } from '../types/user.type';\nimport { User } from '../entities/User';\n\nexport class UserService {\n async findAll(): Promise {\n return User.find();\n }\n\n async delete(id: string): Promise {\n const deletedUser = await User.findOne({ where: { id } });\n if (deletedUser) {\n await User.delete(id);\n return deletedUser;\n }\n return null;\n }\n\n async findByEmail(email: string): Promise {\n return User.findOne({ where: { email } });\n }\n\n public async createUser({ username, password, email }: IUser) {\n const existingUser = await this.findByEmail(email);\n if (existingUser) {\n return {\n status: 400,\n data: null,\n error: null,\n message: 'User with this email already exists'\n };\n }\n\n const passwordHash = await hashing(password);\n const token = await hashing(uuidv4());\n\n const encodedToken = Buffer.from(token).toString('base64');\n\n const newUser = User.create({\n username,\n password: passwordHash,\n email,\n confirmationToken: token\n });\n await newUser.save();\n\n return {\n status: 200,\n data: { email, confirmationToken: encodedToken },\n error: null,\n message: 'User successfully registered'\n };\n }\n\n public async loginUser({ password, email }: IUser) {\n const existingUser = await this.findByEmail(email);\n if (!existingUser) {\n return {\n status: 400,\n data: null,\n error: null,\n message: 'User not exist'\n };\n }\n\n const passwordMatched = await comparing(password, existingUser.password);\n\n if (!passwordMatched) {\n return {\n status: 400,\n data: null,\n message: 'Invalid password or email'\n };\n }\n return {\n status: 200,\n data: null,\n error: null,\n message: 'User successfully login',\n id: existingUser.id\n };\n }\n\n public userLogout() {\n try {\n return {\n status: 200,\n data: null,\n error: null,\n message: 'User successfully logged out'\n };\n } catch (error) {\n return {\n status: 500,\n data: null,\n error: 'Server error',\n message: `We got this error ${error}`\n };\n }\n }\n\n public async changePassword(email: string, { oldPassword, newPassword }: IUserUpdate) {\n const user = await this.findByEmail(email);\n if (!user || user === null) {\n return {\n status: 404,\n data: null,\n error: null,\n message: 'User not found'\n };\n }\n\n const passwordMatched = await comparing(oldPassword, user.password);\n if (!passwordMatched) {\n return {\n status: 400,\n data: null,\n error: null,\n message: 'Invalid password'\n };\n }\n\n const passwordHash = await hashing(newPassword);\n const updatedUser = await User.update({ id: user.id }, { password: passwordHash });\n\n return {\n status: 200,\n data: updatedUser,\n error: null,\n message: 'Password changed successfully'\n };\n }\n\n public async requestResetPassword(email: string) {\n const user = await this.findByEmail(email);\n if (!user || user === null) {\n return {\n status: 404,\n data: null,\n error: null,\n message: 'User not found'\n };\n }\n\n const resetToken = await hashing(uuidv4());\n\n const encodedToken = Buffer.from(resetToken).toString('base64');\n\n user.resetPasswordToken = resetToken;\n await user.save();\n return {\n status: 200,\n data: { email: user.email, resetPasswordToken: encodedToken },\n error: null,\n message: 'Password reset token sent successfully'\n };\n }\n\n public async resetPassword(resetPasswordToken: string, newPassword: string) {\n const decodedToken = Buffer.from(resetPasswordToken, 'base64').toString('ascii');\n\n const user = await User.findOne({ where: { resetPasswordToken: decodedToken } });\n if (!user) {\n return {\n status: 404,\n data: null,\n error: null,\n message: 'User not found'\n };\n }\n const passwordHash = await hashing(newPassword);\n user.password = passwordHash;\n user.resetPasswordToken = '';\n await user.save();\n return {\n status: 200,\n data: null,\n error: null,\n message: 'Password change successfully'\n };\n }\n\n public async confirmEmail(confirmationToken: string) {\n try {\n const decodedToken1 = Buffer.from(confirmationToken, 'base64').toString('ascii');\n const user = await User.findOne({ where: { confirmationToken: decodedToken1 } });\n if (!user) {\n return {\n status: 404,\n data: null,\n error: 'User not found',\n message: 'User not found'\n };\n }\n\n user.isEmailConfirmed = true;\n user.confirmationToken = '';\n await user.save();\n\n return {\n status: 200,\n data: user,\n error: null,\n message: 'Email successfully confirmed'\n };\n } catch (error) {\n return {\n status: 400,\n data: null,\n error: 'Invalid confirmation token',\n message: 'Invalid confirmation token'\n };\n }\n }\n\n public async checkAuth() {\n return {\n status: 200,\n data: { isAuthenticated: true },\n error: null,\n message: 'Authentication succes'\n };\n }\n}"}}},{"rowIdx":644,"cells":{"text":{"kind":"string","value":"package cn.lzj66.service;\n\nimport cn.lzj66.dao.ClassesDao;\nimport cn.lzj66.dao.StudentDao;\nimport cn.lzj66.dao.SubjectDao;\nimport cn.lzj66.dao.TaskDao;\nimport cn.lzj66.dao.TaskItemDao;\nimport cn.lzj66.dao.TeacherClassesDao;\nimport cn.lzj66.dao.TeacherDao;\nimport cn.lzj66.entity.Classes;\nimport cn.lzj66.entity.Student;\nimport cn.lzj66.entity.Task;\nimport cn.lzj66.entity.TaskItem;\nimport cn.lzj66.entity.Teacher;\nimport cn.lzj66.request.ListQuestion;\nimport cn.lzj66.request.Subject;\nimport cn.lzj66.response.Question;\nimport cn.lzj66.dao.*;\nimport cn.lzj66.entity.*;\nimport cn.lzj66.request.CreateTask;\nimport cn.lzj66.util.CalculateExp;\nimport cn.lzj66.util.Create;\nimport cn.lzj66.util.InviteCode;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\n@Service\npublic class TeacherService {\n\n @Autowired\n private ClassesDao classesDao;\n @Autowired\n private TeacherClassesDao teacherClassesDao;\n @Autowired\n private TaskDao taskDao;\n @Autowired\n private TaskItemDao taskItemDao;\n @Autowired\n private TeacherDao teacherDao;\n @Autowired\n private SubjectDao subjectDao;\n @Autowired\n private StudentDao studentDao;\n /**\n * 根据用户名获取账号密码\n * @param username String\n * @return Class\n */\n public Teacher getTeacherByUserName(String username){\n return teacherDao.getTeacherByName(username);\n }\n\n /**\n * 根据教师id获取班级列表\n * @param teacherId int\n * @return List\n */\n public List getClassList(int teacherId){\n return classesDao.getClassByTeacherAndId(teacherId);\n }\n\n /**\n * 根据班级id获取全部同学\n * @param classId int\n * @return List\n */\n public List getAllStudentByClassId(int classId){\n return studentDao.getSameStudent(classId);\n }\n /**\n * 增加一个老师账号\n * @param teacher Class\n * @return\n */\n public int addTeacher(Teacher teacher){\n return teacherDao.addTeacher(teacher);\n }\n\n /**\n * 增加一个Subject\n * @param subject\n * @return\n */\n public int addSubject(Subject subject) {\n return subjectDao.addSubject(subject);\n }\n\n /**\n * 添加一个班级\n * @param teacherId int 教师id\n * @param name string 班级名字\n * @param desc string 班级描述\n * @return\n */\n @Transactional\n public boolean addClass(int teacherId,String name,String desc){\n String uuid = InviteCode.build();//生成一个邀请码\n Classes classes = new Classes();\n classes.setName(name);\n classes.setRemark(desc);\n classes.setUuid(uuid);\n classesDao.addClass(classes);\n int classId = classes.getId();\n System.out.println(classes.getId());\n int res = teacherClassesDao.add(teacherId,classId);\n if(res >= 1){\n return true;\n }else{\n return false;\n }\n }\n\n @Transactional\n public boolean addTask(int teacherId , CreateTask question, ListQuestion listQuestion){\n Task task = new Task();\n task.setClassId(question.getClassId());\n task.setTeacherId(teacherId);\n task.setTitle(question.getTitle());\n task.setCount(question.getCount());\n task.setDescription(question.getDescription().trim());\n task.setEndTime(question.getEndTime());\n\n int row = taskDao.addTask(task);\n int taskId = task.getId();\n List items = new ArrayList<>();\n TaskItem taskItem;\n for (int i = 0; i < listQuestion.getQuestion().size(); i++) {\n taskItem = new TaskItem();\n taskItem.setQuestion(listQuestion.getQuestion().get(i));\n taskItem.setAnswer(listQuestion.getAnswer().get(i));\n taskItem.setTaskId(taskId);\n items.add(taskItem);\n }\n int res = taskItemDao.addBatchItem(items);\n if(res >= 1){\n return true;\n }else{\n return false;\n }\n }\n public List getTaskList(int teacherId){\n return taskDao.getListTaskByTeacherId(teacherId);\n }\n\n /**\n * 创建题目\n * @param difficult 难度\n * @param type 题目类型\n * @param count 数量\n * @return List\n */\n public List createQuestion(int difficult, int type, int count){\n List list = new ArrayList<>();\n switch (type){\n case 1:\n CalculateExp calculateExp = new CalculateExp();\n Map> map = calculateExp.build(count, Create.getMaxNumberByDifficult(difficult),Create.getDifficultBySelf(difficult));\n List ques = map.get(\"question\");\n List answer = map.get(\"answer\");\n Question question ;\n for (int i = 0; i < ques.size(); i++) {\n question = new Question();\n question.setId(i + 1);\n question.setQuestion(ques.get(i));\n question.setAnswer(answer.get(i));\n list.add(question);\n }\n break;\n case 2:\n list = subjectDao.getSubjectByDifficult(difficult,count);\n break;\n default:\n break;\n }\n return list;\n }\n}"}}},{"rowIdx":645,"cells":{"text":{"kind":"string","value":"import { lz, lzc } from 'lazy-init'\nimport type { LazyOptions } from '../src/options'\n\nconst satisfiesOptions = (a: object, b: object, options: LazyOptions) => {\n const { cache = false, freeze = false } = options\n\n expect(Object.isFrozen(a)).toBe(freeze)\n expect(Object.isFrozen(b)).toBe(freeze)\n\n if (cache) {\n expect(a).toBe(b)\n } else {\n expect(a).not.toBe(b)\n }\n}\n\ndescribe('correct \"lazyOptions\" are applied by \"lz()\" method', () => {\n test('`{ cache: false, freeze: false }` [default]', () => {\n const expectedOptions = { cache: false, freeze: false }\n\n satisfiesOptions(\n lz({ foo: 'bar' }, undefined),\n lz({ foo: 'bar' }, undefined),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, false),\n lz({ foo: 'bar' }, false),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, {}),\n lz({ foo: 'bar' }, {}),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, { cache: false }),\n lz({ foo: 'bar' }, { cache: false }),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, { freeze: false }),\n lz({ foo: 'bar' }, { freeze: false }),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, { cache: false, freeze: false }),\n lz({ foo: 'bar' }, { cache: false, freeze: false }),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, { cache: undefined, freeze: undefined }),\n lz({ foo: 'bar' }, { cache: undefined, freeze: undefined }),\n expectedOptions\n )\n })\n test('`{ cache: true, freeze: false }`', () => {\n const expectedOptions = { cache: true, freeze: false }\n\n satisfiesOptions(\n lz({ foo: 'bar' }, { cache: true, freeze: false }),\n lz({ foo: 'bar' }, { cache: true, freeze: false }),\n expectedOptions\n )\n })\n test('`{ cache: false, freeze: true }`', () => {\n const expectedOptions = { cache: false, freeze: true }\n\n satisfiesOptions(\n lz({ foo: 'bar' }, true),\n lz({ foo: 'bar' }, true),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, { freeze: true }),\n lz({ foo: 'bar' }, { freeze: true }),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, { cache: false, freeze: true }),\n lz({ foo: 'bar' }, { cache: false, freeze: true }),\n expectedOptions\n )\n })\n test('`{ cache: true, freeze: true }`', () => {\n const expectedOptions = { cache: true, freeze: true }\n\n satisfiesOptions(\n lz({ foo: 'bar' }, { cache: true }),\n lz({ foo: 'bar' }, { cache: true }),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, { cache: true, freeze: undefined }),\n lz({ foo: 'bar' }, { cache: true, freeze: undefined }),\n expectedOptions\n )\n satisfiesOptions(\n lz({ foo: 'bar' }, { cache: true, freeze: true }),\n lz({ foo: 'bar' }, { cache: true, freeze: true }),\n expectedOptions\n )\n })\n})\n\ndescribe('correct \"lazyOptions\" are applied by \"lzc()\" method', () => {\n test('`{ cache: false, freeze: false }`', () => {\n const expectedOptions = { cache: false, freeze: false }\n\n satisfiesOptions(\n lzc({ foo: 'bar' }, { cache: false }),\n lzc({ foo: 'bar' }, { cache: false }),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, { cache: false, freeze: false }),\n lzc({ foo: 'bar' }, { cache: false, freeze: false }),\n expectedOptions\n )\n })\n test('`{ cache: true, freeze: false }`', () => {\n const expectedOptions = { cache: true, freeze: false }\n\n satisfiesOptions(\n lzc({ foo: 'bar' }, false),\n lzc({ foo: 'bar' }, false),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, { freeze: false }),\n lzc({ foo: 'bar' }, { freeze: false }),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, { cache: undefined, freeze: false }),\n lzc({ foo: 'bar' }, { cache: undefined, freeze: false }),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, { cache: true, freeze: false }),\n lzc({ foo: 'bar' }, { cache: true, freeze: false }),\n expectedOptions\n )\n })\n test('`{ cache: false, freeze: true }`', () => {\n const expectedOptions = { cache: false, freeze: true }\n\n satisfiesOptions(\n lzc({ foo: 'bar' }, { cache: false, freeze: true }),\n lzc({ foo: 'bar' }, { cache: false, freeze: true }),\n expectedOptions\n )\n })\n test('`{ cache: true, freeze: true } [default]`', () => {\n const expectedOptions = { cache: true, freeze: true }\n\n satisfiesOptions(\n lzc({ foo: 'bar' }, undefined),\n lzc({ foo: 'bar' }, undefined),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, true),\n lzc({ foo: 'bar' }, true),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, {}),\n lzc({ foo: 'bar' }, {}),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, { cache: true }),\n lzc({ foo: 'bar' }, { cache: true }),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, { freeze: true }),\n lzc({ foo: 'bar' }, { freeze: true }),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, { cache: undefined, freeze: undefined }),\n lzc({ foo: 'bar' }, { cache: undefined, freeze: undefined }),\n expectedOptions\n )\n satisfiesOptions(\n lzc({ foo: 'bar' }, { cache: true, freeze: true }),\n lzc({ foo: 'bar' }, { cache: true, freeze: true }),\n expectedOptions\n )\n })\n})"}}},{"rowIdx":646,"cells":{"text":{"kind":"string","value":"const routes = [\n {\n path: '/',\n component: () => import('layouts/MainLayout.vue'),\n children: [\n { path: '', component: () => import('pages/IndexPage.vue'), name: 'index', meta: { requiresAuth: true } },\n { path: '/item', component: () => import('pages/ItemsPage.vue'), name: 'items', meta: { requiresAuth: true } },\n { path: '/login', component: () => import('pages/LoginPage.vue'), name: 'login', meta: { guest: true } },\n { path: '/settings', component: () => import('pages/SettingsPage.vue'), name: 'settings', meta: { requiresAuth: true } },\n { path: '/item/:id', component: () => import('pages/ItemDetailsPage.vue'), name: 'item-details', meta: { requiresAuth: true } },\n { path: '/item/:id/edit', component: () => import('pages/EditItemPage.vue'), name: 'edit-item', meta: { requiresAuth: true } },\n { path: '/item/create', component: () => import('pages/CreateItemPage.vue'), name: 'create-item', meta: { requiresAuth: true } },\n { path: '/order/:id', component: () => import('pages/OrderDetailsPage.vue'), name: 'order-details', meta: { requiresAuth: true } },\n { path: '/round/:id', component: () => import('pages/RoundDetailsPage.vue'), name: 'round-details' },\n { path: '/round/:id/payment-methods', component: () => import('pages/RoundPaymentMethodsPage.vue'), name: 'round-payments' },\n { path: '/order', component: () => import('pages/OrdersPage.vue'), name: 'orders', meta: { requiresAuth: true } },\n { path: '/round', component: () => import('pages/RoundsPage.vue'), name: 'rounds', meta: { requiresAuth: true } },\n { path: '/payments', component: () => import('pages/PaymentsPage.vue'), name: 'payments', meta: { requiresAuth: true } },\n { path: '/payment/create', component: () => import('pages/CreatePaymentPage.vue'), name: 'create-payment', meta: { requiresAuth: true } },\n { path: '/payemnt/:id/edit', component: () => import('pages/EditPaymentPage.vue'), name: 'edit-payment', meta: { requiresAuth: true } },\n { path: '/change-password', component: () => import('pages/ChangePasswordPage.vue'), name: 'change-password', meta: { requiresAuth: true } },\n { path: '/telegram-bot', component: () => import('pages/TelegramBotSettingPage.vue'), name: 'telegram-bot', meta: { requiresAuth: true } },\n { path: '/users', component: () => import('pages/UsersPage.vue'), name: 'users', meta: { requiresAuth: true } },\n ]\n },\n\n // Always leave this as last one,\n // but you can also remove it\n {\n path: '/:catchAll(.*)*',\n component: () => import('pages/ErrorNotFound.vue')\n }\n]\n\nexport default routes"}}},{"rowIdx":647,"cells":{"text":{"kind":"string","value":"
\n \n\n # 𝙼𝚒𝚗𝚒𝚖𝚊𝚕 𝙻𝚊𝚗𝚐𝚞𝚊𝚐𝚎\n 𝙰 𝚗𝚎𝚠 𝚠𝚊𝚢 𝚝𝚘 𝚝𝚑𝚒𝚗𝚔 𝚊𝚋𝚘𝚞𝚝 𝚙𝚛𝚘𝚐𝚛𝚊𝚖𝚖𝚒𝚗𝚐.\n
\n\n> #### 𝚀𝚞𝚒𝚌𝚔 𝙰𝚍𝚟𝚒𝚌𝚎\n> The language is under heavy development, and you can help us develop it!
\n> Join our [Discord server](https://discord.gg/F3Uh9W4g), and apply to be a developer (there is a channel explaining how).\n\n### 𝙼𝚎𝚖𝚋𝚎𝚛𝚜\n
\n\n**Creators:** [@pandasoli](https://github.com/pandasoli) and\n[@JuniorBecari10](https://github.com/juniorbecari10)\n\n
\n\n
\n\n## 𝙰𝚋𝚘𝚞𝚝\n\n**𝙼𝚒𝚗𝚒𝚖𝚊𝚕** is a compiled, general-purpose programming language with high-level syntax, but low-level control and speed.
\nThe compiler writes the minimum amount of Assembly instructions possible, so that the language reaches the peak of its speed.\n\nThe language is also very customizable, you can create your own statements or expression nodes, by doing this the code will be more readable and easier to develop and debug.\n\n**𝙼𝚒𝚗𝚒𝚖𝚊𝚕** can be changed though plugins that are able to mimic any programming language syntax.
\nThey make possible even the creation of a transpiler from any language to **𝙼𝚒𝚗𝚒𝚖𝚊𝚕**, only with a plugin (for example you can mimic the entire Go or Rust syntax through them).\n\n
\n\n## 𝚃𝚑𝚎 𝙲𝚘𝚖𝚙𝚒𝚕𝚎𝚛\n\nThe **𝙼𝚒𝚗𝚒𝚖𝚊𝚕** compiler is very fast and its error messages are very helpful.
\nWith **𝙼𝚒𝚗𝚒𝚖𝚊𝚕**, solving compiling errors is easy!
\n\nTom will be your best friend in this journey.\n\n\n### 𝙼𝚎𝚎𝚝 𝚃𝚘𝚖\nTom will be your best friend while programming in **𝙼𝚒𝚗𝚒𝚖𝚊𝚕**.
\nHe will always help you developing your programs.\n\n```\n /\\_/\\\n( o.o ) Hello!\n > ^ <\n```\n\nHe will always be present while creating your **𝙼𝚒𝚗𝚒𝚖𝚊𝚕** project, inside the language's intuitive setup.
\nAlso he will help you solving the compiling errors, giving hints of how to solve them.\n\n## 𝚂𝚢𝚗𝚝𝚊𝚡\n\nLike said before, **𝙼𝚒𝚗𝚒𝚖𝚊𝚕** has a high-level and easy to understand syntax.
\nThe keywords are short, but easily readable.\n\nExample of a Hello World program:\n```rust\nfn main {\n println(\"Hello, World!\")\n}\n```\n\nFor more information about the syntax or anything related to the language, check out our [Docs](https://github.com/minimal-lang/docs)!
\n_(they aren't boring long lines of text)._"}}},{"rowIdx":648,"cells":{"text":{"kind":"string","value":"import 'package:hydrated_bloc/hydrated_bloc.dart';\nimport 'package:lets_go_with_me/core/util/network_Info.dart';\nimport 'package:lets_go_with_me/core/util/shared_preference_util.dart';\nimport 'package:lets_go_with_me/data/repositories/auth_repo.dart';\n\nimport '../../core/util/user_preferences.dart';\n\npart 'auth_state.dart';\n\nclass AuthCubit extends Cubit {\n\n AuthCubit({required this.authRepo, required this.networkInfo})\n : super(AuthInitial());\n\n final AuthRepo authRepo;\n final NetworkInfo networkInfo;\n\n Future requestLoginOtp(String mobNo) async {\n if (mobNo.length != 10) {\n emit(AuthError(message: \"Kindly enter 10 digit valid mobile number.\"));\n return;\n }\n\n final internetAvailable = await networkInfo.isConnected;\n if (!internetAvailable) {\n emit(AuthError(message: \"No active internet connection.\"));\n return;\n }\n\n emit(RequestOtpInProgress());\n final failureOrOtpRequestResponseModel = await authRepo.requestOtp(mobNo);\n\n emit(failureOrOtpRequestResponseModel.fold((failure) {\n return RequestOtpFailure();\n }, (otpRequestResponseModel) {\n print(\"lgfjg OTP ${otpRequestResponseModel.otp.toString()}\");\n SharedPreferenceUtil.instance.setBooleanPreferencesValue(SharedPreferenceUtil.instance.isNewUser, otpRequestResponseModel.isNewUser);\n SharedPreferenceUtil.instance.setStringPreferenceValue(SharedPreferenceUtil.instance.loginOtp, otpRequestResponseModel.otp.toString());\n if (otpRequestResponseModel.userid != null) {\n SharedPreferenceUtil.instance.setStringPreferenceValue(SharedPreferenceUtil.instance.userId, otpRequestResponseModel.userid!);\n }\n return RequestOtpSuccess();\n }));\n }\n\n Future verifyLoginOtp(String otp) async {\n emit(VerifyOtpInProgress());\n\n final verifyOtpSuccess = await authRepo.verifyOtp(otp);\n if (verifyOtpSuccess) {\n emit(VerifyOtpSuccess());\n } else {\n emit(VerifyOtpFailure());\n }\n }\n}"}}},{"rowIdx":649,"cells":{"text":{"kind":"string","value":"\n\n"}}},{"rowIdx":650,"cells":{"text":{"kind":"string","value":"import React, { useState } from \"react\";\nimport axios from \"axios\";\nimport { Link, useNavigate } from \"react-router-dom\";\n\nexport default function AddStaff() {\n let navigate = useNavigate();\n\n const [staff, setStaff] = useState({\n first_name: \"\",\n last_name: \"\",\n phone_number: \"\",\n email: \"\",\n role: \"\",\n description: \"\",\n });\n\n const { first_name, last_name, phone_number, email, role, description } =\n staff;\n\n const onInputChange = (e) => {\n setStaff({ ...staff, [e.target.name]: e.target.value });\n };\n\n const onSubmit = async (e) => {\n e.preventDefault();\n await axios.post(\"http://localhost:8080/staff\", staff); //To POST info into the data base by using axios\n navigate(\"/allstaff\"); //To redirect to home page\n };\n\n return (\n
\n
\n
\n

Edit Staff

\n
onSubmit(e)}>\n
\n \n onInputChange(e)}\n />\n
\n
\n \n onInputChange(e)}\n />\n
\n
\n \n onInputChange(e)}\n />\n
\n
\n \n onInputChange(e)}\n />\n
\n
\n \n onInputChange(e)}\n />\n
\n
\n \n onInputChange(e)}\n />\n
\n \n \n Cancel\n \n
\n
\n
\n
\n );\n}"}}},{"rowIdx":651,"cells":{"text":{"kind":"string","value":"import React, { useEffect, useState } from 'react';\nimport { fetchUser, fetchTrips } from \"../api.js\";\nimport { Link, useNavigate } from \"react-router-dom\";\nimport Navbar from \"../components/Navbar/Navbar.jsx\";\nimport Footer from \"../components/Footer/Footer.jsx\";\nimport TrajetProfil from '../components/Trajets/TrajetProfil.jsx';\nimport './style/Profil.css';\n\nfunction Profil() {\n\n const [auth, setAuth] = useState(false);\n const [email, setEmail] = useState('');\n\n //Tableau des trajets de l'utilisateur\n const [trips, setTrips] = useState([]);\n\n useEffect(() => {\n fetchUser()\n .then(res => {\n \n if(res.data.Status === \"Success\") {\n setAuth(true);\n setEmail(res.data.email);\n // navigate('/');\n\n //Afficher les trajets de l'utilisateur connecté\n fetchTrips()\n .then(res => {\n setTrips(res.data);\n console.log(res.data);\n })\n .then(err => console.log(err));\n\n } else {\n setAuth(false);\n setMessage(res.data.Error);\n }\n })\n .then(err => console.log(err));\n }, []);\n\n return (\n
\n \n
\n
\n
\n
\n

Infos personnelles

\n
\n
\n

Océane H.

\n

Session : CDA31 23-01

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

Biographie

\n
\n
\n

Bonjour, moi c’est Laura. Je recherche une ou plusieurs personnes pour faire du covoiturage depuis Blagnac.

\n \n
\n
\n
\n
\n

Mes trajets

\n
\n {\n trips.length > 0 ?\n
    \n {trips.map(trip => (\n \n ))}\n
\n :\n

Vous n'avez aucun trajet

\n }\n
\n
\n
\n

Mes badges

\n \n
\n\n {/*

Bonjour {name}

\n

Votre mail : {email}

\n {\n trips.length > 0 ?\n
    \n {trips.map(trip => (\n
  • \n

    Adresse de départ : {trip.adresse_depart}

    \n

    Adresse d'arrivée : {trip.adresse_arrivee}

    \n

    Date : {trip.date}

    \n

    Nombre de places : {trip.number_place}

    \n
  • \n ))}\n
\n :\n

Vous n'avez aucun trajet

\n } */}\n
\n \n {/* Déconnexion */}\n
\n
\n \n
\n
\n )\n}\n\nexport default Profil"}}},{"rowIdx":652,"cells":{"text":{"kind":"string","value":"// ArduinoJson - https://arduinojson.org\n// Copyright © 2014-2024, Benoit BLANCHON\n// MIT License\n\n#include \n#include \n\n#include \n\n#define SHOULD_WORK(expression) REQUIRE(DeserializationError::Ok == expression);\n#define SHOULD_FAIL(expression) \\\n REQUIRE(DeserializationError::TooDeep == expression);\n\nTEST_CASE(\"JsonDeserializer nesting\") {\n JsonDocument doc;\n\n SECTION(\"Input = const char*\") {\n SECTION(\"limit = 0\") {\n DeserializationOption::NestingLimit nesting(0);\n SHOULD_WORK(deserializeMsgPack(doc, \"\\xA1H\", nesting)); // \"H\"\n SHOULD_FAIL(deserializeMsgPack(doc, \"\\x90\", nesting)); // []\n SHOULD_FAIL(deserializeMsgPack(doc, \"\\x80\", nesting)); // {}\n }\n\n SECTION(\"limit = 1\") {\n DeserializationOption::NestingLimit nesting(1);\n SHOULD_WORK(deserializeMsgPack(doc, \"\\x90\", nesting)); // {}\n SHOULD_WORK(deserializeMsgPack(doc, \"\\x80\", nesting)); // []\n SHOULD_FAIL(deserializeMsgPack(doc, \"\\x81\\xA1H\\x80\", nesting)); // {H:{}}\n SHOULD_FAIL(deserializeMsgPack(doc, \"\\x91\\x90\", nesting)); // [[]]\n }\n }\n\n SECTION(\"char* and size_t\") {\n SECTION(\"limit = 0\") {\n DeserializationOption::NestingLimit nesting(0);\n SHOULD_WORK(deserializeMsgPack(doc, \"\\xA1H\", 2, nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, \"\\x90\", 1, nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, \"\\x80\", 1, nesting));\n }\n\n SECTION(\"limit = 1\") {\n DeserializationOption::NestingLimit nesting(1);\n SHOULD_WORK(deserializeMsgPack(doc, \"\\x90\", 1, nesting));\n SHOULD_WORK(deserializeMsgPack(doc, \"\\x80\", 1, nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, \"\\x81\\xA1H\\x80\", 4, nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, \"\\x91\\x90\", 2, nesting));\n }\n }\n\n SECTION(\"Input = std::string\") {\n using std::string;\n\n SECTION(\"limit = 0\") {\n DeserializationOption::NestingLimit nesting(0);\n SHOULD_WORK(deserializeMsgPack(doc, string(\"\\xA1H\"), nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, string(\"\\x90\"), nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, string(\"\\x80\"), nesting));\n }\n\n SECTION(\"limit = 1\") {\n DeserializationOption::NestingLimit nesting(1);\n SHOULD_WORK(deserializeMsgPack(doc, string(\"\\x90\"), nesting));\n SHOULD_WORK(deserializeMsgPack(doc, string(\"\\x80\"), nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, string(\"\\x81\\xA1H\\x80\"), nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, string(\"\\x91\\x90\"), nesting));\n }\n }\n\n SECTION(\"Input = std::istream\") {\n SECTION(\"limit = 0\") {\n DeserializationOption::NestingLimit nesting(0);\n std::istringstream good(\"\\xA1H\"); // \"H\"\n std::istringstream bad(\"\\x90\"); // []\n SHOULD_WORK(deserializeMsgPack(doc, good, nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, bad, nesting));\n }\n\n SECTION(\"limit = 1\") {\n DeserializationOption::NestingLimit nesting(1);\n std::istringstream good(\"\\x90\"); // []\n std::istringstream bad(\"\\x91\\x90\"); // [[]]\n SHOULD_WORK(deserializeMsgPack(doc, good, nesting));\n SHOULD_FAIL(deserializeMsgPack(doc, bad, nesting));\n }\n }\n}"}}},{"rowIdx":653,"cells":{"text":{"kind":"string","value":"# KaziNasi\n\nKaziNasi is a web application designed to connect individuals seeking casual labor with available workers in their local area. The platform aims to simplify the process of finding and hiring workers for short-term tasks such as cleaning, gardening, moving, and more.\n\n## Table of Contents\n\n- [Introduction](#introduction)\n- [Features](#features)\n- [Technologies Used](#technologies-used)\n- [Installation](#installation)\n- [Usage](#usage)\n- [Deployment](#deployment)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Introduction\n\nFinding reliable and available help for short-term tasks can be challenging. KaziNasi bridges this gap by providing a platform where individuals can easily find workers for their specific needs. Whether you're a homeowner looking for someone to help with yard work or a business owner in need of extra hands for a one-time project, KaziNasi can help you find the right person for the job.\n\n## Features\n\n- **User Authentication**: Users can create accounts, log in, and manage their profiles.\n- **Worker Profiles**: Workers can create detailed profiles showcasing their skills, experience, availability, and rates.\n- **Client Profiles**: Clients can create profiles and post job listings detailing the tasks they need help with.\n- **Job Matching**: KaziNasi uses a matching algorithm to connect workers with relevant job listings based on their skills and availability.\n- **Messaging System**: Users can communicate with each other through a built-in messaging system to discuss job details, negotiate terms, and more.\n- **Rating and Review System**: Clients can rate workers based on their performance, and workers can rate clients based on their experience, helping to build trust within the community.\n- **Geolocation**: The platform utilizes geolocation to show users nearby workers and job listings, making it easier to find local opportunities.\n- **Notifications**: Users receive notifications for new messages, job matches, and other relevant updates.\n\n## Technologies Used\n\n- **Frontend**: The frontend of KaziNasi is built using Flutter, a cross-platform framework for building native interfaces for iOS, Android, and the web.\n- **Backend**: The backend is powered by Node.js, a JavaScript runtime built on Chrome's V8 JavaScript engine.\n- **Database**: MySQL is used as the database to store user profiles, job listings, messages, and reviews.\n- **Web Server**: Nginx is used as the web server to serve the Flutter web app and handle incoming requests.\n- **Authentication**: Firebase Authentication is used to manage user authentication and authorization, ensuring that only authenticated users can access the platform.\n## Installation\n\nTo run KaziNasi locally, follow these steps:\n\n1. Clone the repository:\n\n ```sh\n git clone https://github.com/kelvinthuo999/KaziNasi\n ```\n\n2. Navigate to the project directory:\n\n ```sh\n cd KaziNasi\n ```\n\n3. Install dependencies:\n\n ```sh\n flutter pub get\n ```\n\n4. Set up the Node.js backend: Follow the instructions in the `backend/README.md` file to set up and run the Node.js backend.\n\n5. Run the app:\n\n ```sh\n flutter run -d chrome\n ```\n\n## Usage\n\nOnce the app is running, you can use it to:\n\n- Create a user account as a worker or client.\n- Fill out your profile with relevant information.\n- Browse job listings or create a new job listing if you're a client.\n- Apply for jobs if you're a worker.\n- Communicate with other users through the messaging system.\n- Rate and review other users based on your experience.\n\n## Deployment\nTo deploy KaziNasi to a live server, follow these steps:\n\n1. Set up a server: You'll need a server running Nginx, Node.js, and MySQL to deploy the backend of KaziNasi.\n2. Deploy the frontend: Use a web hosting service (e.g., Firebase Hosting, Netlify) to deploy the Flutter web app frontend.\n3. Configure the backend: Update the frontend configuration (e.g., API endpoints) to point to your deployed backend.\n4. Access the app: Once deployed, the KaziNasi web app will be accessible via any browser.\n\n## Contributing\n\nContributions to KaziNasi are welcome! If you'd like to contribute to the project, please fork the repository and submit a pull request with your changes."}}},{"rowIdx":654,"cells":{"text":{"kind":"string","value":"import { StyleSheet, View } from \"react-native\";\nimport Text from \"../utils/Text.jsx\";\nimport React from \"react\";\nimport theme from \"../../theme.js\";\nimport ReviewActions from \"./ReviewActions.jsx\";\n\nconst styles = StyleSheet.create({\n circle: {\n alignItems: \"center\",\n justifyContent: \"center\",\n borderRadius: 50 / 2,\n width: 50,\n height: 50,\n borderColor: theme.colors.primary,\n borderWidth: 2,\n },\n});\n\nconst ReviewItem = ({ review, currentUser }) => {\n return (\n \n \n \n \n {review.rating}\n \n \n \n \n \n {currentUser ? review.repository.fullName : review.user.username}\n \n \n {review.createdAt}\n \n \n \n {review.text}\n \n \n \n {currentUser ? : null}\n \n );\n};\n\nexport default ReviewItem;"}}},{"rowIdx":655,"cells":{"text":{"kind":"string","value":"const mangasData = require(\"../../infrastructure/mangas/data\");\nimport { IMangaRepository } from \"../../domain/repository/MangaRepository\";\nimport { Manga } from \"@/domain/entity/manga/model\";\n\nexport class Mangas {\n constructor(readonly mangaRepository: IMangaRepository) {}\n\n public async getAllMangas(): Promise {\n try {\n return await this.mangaRepository.getAllMangas();\n } catch (error) {\n return \"Erro ao buscar os mangas: \" + error;\n }\n }\n\n public async getManga(idManga: number): Promise {\n try {\n return await this.mangaRepository.getManga(idManga);\n } catch (error) {\n return \"Erro ao buscar o manga: \" + error;\n }\n }\n\n public async createManga(manga: Manga): Promise {\n try {\n return await this.mangaRepository.createManga(manga);\n } catch (error) {\n return \"Erro ao criar o manga: \" + error;\n }\n }\n\n public async updateManga(idManga: number, manga: Manga): Promise {\n try {\n return await this.mangaRepository.updateManga(idManga, manga);\n } catch (error) {\n return \"Erro ao atualizar o manga: \" + error;\n }\n }\n\n public async deleteManga(idManga: number): Promise {\n try {\n return await this.mangaRepository.deleteManga(idManga);\n } catch (error) {\n return \"Erro ao deletar o manga: \" + error;\n }\n }\n}"}}},{"rowIdx":656,"cells":{"text":{"kind":"string","value":"package com.study.security_bosung.web.controller.api;\n\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.core.io.InputStreamResource;\nimport org.springframework.core.io.Resource;\nimport org.springframework.http.ContentDisposition;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.study.security_bosung.service.notice.NoticeService;\nimport com.study.security_bosung.web.dto.CMRespDto;\nimport com.study.security_bosung.web.dto.notice.AddNoticeReqDto;\nimport com.study.security_bosung.web.dto.notice.GetNoticeListResponseDto;\nimport com.study.security_bosung.web.dto.notice.GetNoticeResponseDto;\n\nimport lombok.RequiredArgsConstructor;\nimport lombok.extern.slf4j.Slf4j;\n\n@RestController\n@RequestMapping(\"/api/v1/notice\")\n@Slf4j\n@RequiredArgsConstructor\npublic class NoticeRestController {\n\t\n\t// 파일의 경로를 변수처럼 사용할 수 있음\n\t@Value(\"${file.path}\")\n\tprivate String filePath;\n\t\n\tprivate final NoticeService noticeService; \n\t\n\t@GetMapping(\"/list/{page}\")\n\tpublic ResponseEntity getNoticeList(@PathVariable int page, @RequestParam String searchFlag, @RequestParam String searchValue) {\n\t\tList listDto = null;\n\t\ttry {\n\t\t\tlistDto = noticeService.getNoticeList(page, searchFlag, searchValue);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn ResponseEntity.internalServerError().body(new CMRespDto<>(-1, \"datavase error\", listDto));\n\t\t}\n\t\t\n\t\treturn ResponseEntity.ok(new CMRespDto<>(1, \"lookup successful\", listDto));\n\t}\n\t\n\t@PostMapping(\"\")\n\tpublic ResponseEntity addNotice(AddNoticeReqDto addNoticeReqDto) {\n\t\tlog.info(\">>>>>>{}\", addNoticeReqDto);\n\t\tlog.info(\">>>>>> fileName: {}\", addNoticeReqDto.getFile().get(0).getOriginalFilename());\n\t\t\n\t\tint noticeCode = 0;\n\n\t\ttry {\n\t\t\tnoticeCode = noticeService.addNotice(addNoticeReqDto);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn ResponseEntity.internalServerError().body(new CMRespDto<>(-1, \"Failed to write\", noticeCode));\n\t\t}\n\t\treturn ResponseEntity.ok(new CMRespDto<>(1, \"completing creation\", noticeCode));\n\t}\n\t\n\t@GetMapping(\"/{noticeCode}\")\n\tpublic ResponseEntity getNotice(@PathVariable int noticeCode) {\n\t\tGetNoticeResponseDto getNoticeResponseDto = null;\n\t\ttry {\n\t\t\tgetNoticeResponseDto = noticeService.getNotice(null, noticeCode);\n\t\t\tif(getNoticeResponseDto == null) {\n\t\t\t\treturn ResponseEntity.badRequest().body(new CMRespDto<>(-1, \"request failes\", null));\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn ResponseEntity.internalServerError().body(new CMRespDto<>(-1, \"database failes\", null));\n\t\t}\n\t\t\n\t\treturn ResponseEntity.ok().body(new CMRespDto<>(1, \"lookup successful\", getNoticeResponseDto));\n\t}\n\t\n\t@GetMapping(\"/{flag}/{noticeCode}\")\n\tpublic ResponseEntity geNotice(@PathVariable String flag, @PathVariable int noticeCode) {\n\t\tGetNoticeResponseDto getNoticeResponseDto = null;\n\t\tif (flag.equals(\"pre\") || flag.equals(\"next\")) {\n\t\t\ttry {\n\t\t\t\tgetNoticeResponseDto = noticeService.getNotice(flag, noticeCode);\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t\treturn ResponseEntity.internalServerError().body(new CMRespDto<>(-1, \"database failes\", null));\n\t\t\t}\n\t\t}else {\n\t\t\treturn ResponseEntity.badRequest().body(new CMRespDto<>(-1, \"request failes\", null));\n\t\t}\n\t\t\n\t\treturn ResponseEntity.ok().body(new CMRespDto<>(1, \"lookup successful\", getNoticeResponseDto));\n\t}\n\t\n\t@GetMapping(\"/file/download/{fileName}\")\n\tpublic ResponseEntity downloadFile(@PathVariable String fileName) throws IOException {\n\t\tPath path = Paths.get(filePath + \"notice/\" + fileName);\n\t\t\n\t\tString contentType = Files.probeContentType(path); // file의 MIME타입\n\t\t\n\t\tlog.info(\"contentType: {}\", contentType);\n\t\t\n\t\tHttpHeaders headers = new HttpHeaders();\n\t\theaders.setContentDisposition(ContentDisposition.builder(\"attachment\") // 한글 파일명 다운로드 할 수 있게 설정\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.filename(fileName, StandardCharsets.UTF_8)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.build());\n\t\t\n\t\theaders.add(HttpHeaders.CONTENT_TYPE, contentType); // header\n\t\t\n\t\tResource resource = new InputStreamResource(Files.newInputStream(path)); // body\n\t\t\n\t\treturn ResponseEntity.ok().headers(headers).body(resource);\n\t}\n}"}}},{"rowIdx":657,"cells":{"text":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage eu.fasten.analyzer.restapiplugin.mvn.api;\n\nimport eu.fasten.analyzer.restapiplugin.mvn.RestApplication;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.mockito.Mockito;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport java.util.List;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class CallableApiTest {\n\n private CallableApiService service;\n private CallableApi api;\n private final int offset = 0;\n private final int limit = Integer.parseInt(RestApplication.DEFAULT_PAGE_SIZE);\n\n @BeforeEach\n void setUp() {\n service = Mockito.mock(CallableApiService.class);\n api = new CallableApi(service);\n }\n\n @Test\n public void getPackageCallablesTest() {\n var packageName = \"pkg name\";\n var version = \"pkg version\";\n var response = new ResponseEntity<>(\"package binary callables\", HttpStatus.OK);\n Mockito.when(service.getPackageCallables(packageName, version, offset, limit, null, null)).thenReturn(response);\n var result = api.getPackageCallables(packageName, version, offset, limit, null, null);\n assertEquals(response, result);\n Mockito.verify(service).getPackageCallables(packageName, version, offset, limit, null, null);\n }\n\n @Test\n public void getCallableMetadataTest() {\n var packageName = \"pkg name\";\n var version = \"pkg version\";\n var callable = \"callable\";\n var response = new ResponseEntity<>(\"callable metadata\", HttpStatus.OK);\n Mockito.when(service.getCallableMetadata(packageName, version, callable, null, null)).thenReturn(response);\n var result = api.getCallableMetadata(packageName, version, callable, null, null);\n assertEquals(response, result);\n Mockito.verify(service).getCallableMetadata(packageName, version, callable, null, null);\n }\n\n @Test\n public void getCallablesTest() {\n var ids = List.of(1L, 2L, 3L);\n var response = new ResponseEntity<>(\"callables metadata map\", HttpStatus.OK);\n Mockito.when(service.getCallables(ids)).thenReturn(response);\n var result = api.getCallables(ids);\n assertEquals(response, result);\n Mockito.verify(service).getCallables(ids);\n }\n}"}}},{"rowIdx":658,"cells":{"text":{"kind":"string","value":"/* \n* AMRIT – Accessible Medical Records via Integrated Technology \n* Integrated EHR (Electronic Health Records) Solution \n*\n* Copyright (C) \"Piramal Swasthya Management and Research Institute\" \n*\n* This file is part of AMRIT.\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see https://www.gnu.org/licenses/.\n*/\n\n\nimport { Component, OnInit, DoCheck } from '@angular/core';\nimport { Router, ActivatedRoute } from '@angular/router';\nimport { BeneficiaryDetailsService } from '../../services/beneficiary-details.service';\nimport 'rxjs/Rx';\nimport { HttpServiceService } from 'app/app-modules/core/services/http-service.service';\nimport { SetLanguageComponent } from 'app/app-modules/core/components/set-language.component';\n\n@Component({\n selector: 'app-beneficiary-details',\n templateUrl: './beneficiary-details.component.html',\n styleUrls: ['./beneficiary-details.component.css']\n})\nexport class BeneficiaryDetailsComponent implements OnInit, DoCheck {\n\n beneficiary: any;\n today: any;\n beneficiaryDetailsSubscription: any;\n current_language_set: any;\n\n constructor(\n private router: Router,\n private route: ActivatedRoute,\n public httpServiceService: HttpServiceService,\n private beneficiaryDetailsService: BeneficiaryDetailsService\n ) { }\n\n ngOnInit() {\n this.assignSelectedLanguage();\n this.today = new Date();\n this.route.params.subscribe(param => {\n this.beneficiaryDetailsService.getBeneficiaryDetails(param['beneficiaryRegID'], localStorage.getItem('benFlowID'));\n this.beneficiaryDetailsSubscription = this.beneficiaryDetailsService.beneficiaryDetails$\n .subscribe(res => {\n if (res != null) {\n this.beneficiary = res;\n if (res.serviceDate) {\n this.today = res.serviceDate;\n }\n }\n });\n\n this.beneficiaryDetailsService.getBeneficiaryImage(param['beneficiaryRegID'])\n .subscribe(data => {\n if (data && data.benImage) {\n this.beneficiary.benImage = data.benImage;\n }\n });\n });\n }\n\n ngDoCheck() {\n this.assignSelectedLanguage();\n }\n assignSelectedLanguage() {\n const getLanguageJson = new SetLanguageComponent(this.httpServiceService);\n getLanguageJson.setLanguage();\n this.current_language_set = getLanguageJson.currentLanguageObject;\n }\n \n ngOnDestroy() {\n if (this.beneficiaryDetailsSubscription)\n this.beneficiaryDetailsSubscription.unsubscribe();\n }\n\n}"}}},{"rowIdx":659,"cells":{"text":{"kind":"string","value":"import * as React from 'react';\n\nimport { Slider } from '@miblanchard/react-native-slider';\nimport { Button, StyleSheet, Text, View } from 'react-native';\nimport { ExcludeSystemGestureAreaView } from '../../src';\nimport { NavigationContainer, useNavigation } from '@react-navigation/native';\nimport { createStackNavigator } from '@react-navigation/stack';\n\nconst Stack = createStackNavigator();\n\nexport default function App() {\n return (\n \n \n \n \n \n \n );\n}\n\nconst Home = () => {\n const { navigate } = useNavigation();\n return (\n \n {\n navigate('demo', {});\n }}\n />\n \n );\n};\n\nconst DemoComponent = () => {\n const [value, setValue] = React.useState(20);\n return (\n \n \n \n setValue(value as number)}\n />\n \n \n Value: {value}\n \n );\n};\nconst styles = StyleSheet.create({\n sliderContainer: {\n height: 50,\n width: '100%',\n marginLeft: 10,\n marginRight: 10,\n alignItems: 'stretch',\n justifyContent: 'center',\n // backgroundColor: 'green',\n },\n container: {\n flex: 1,\n alignItems: 'center',\n justifyContent: 'center',\n },\n box: {\n width: 60,\n height: 60,\n marginVertical: 20,\n },\n});"}}},{"rowIdx":660,"cells":{"text":{"kind":"string","value":"/*\n * This code is released under Creative Commons Attribution 4.0 International\n * (CC BY 4.0) license, http://creativecommons.org/licenses/by/4.0/legalcode .\n * That means:\n * \n * You are free to:\n * \n * Share — copy and redistribute the material in any medium or format\n * Adapt — remix, transform, and build upon the material\n * for any purpose, even commercially.\n * \n * The licensor cannot revoke these freedoms as long as you follow the\n * license terms.\n * \n * Under the following terms:\n * \n * Attribution — You must give appropriate credit, provide a link to the\n * license, and indicate if changes were made. You may do so in any\n * reasonable manner, but not in any way that suggests the licensor endorses\n * you or your use.\n * \n * No additional restrictions — You may not apply legal terms or technological\n * measures that legally restrict others from doing anything the license\n * permits.\n * \n *\n * 2019 Aeonium Software Systems, Robert Rohm.\n */\npackage java8.teil06.streams.terminal;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.OptionalInt;\nimport java.util.function.BinaryOperator;\nimport java.util.function.IntBinaryOperator;\nimport java.util.stream.IntStream;\n\n/**\n * Beispiel zu Reduce-Operationen: Endergebnis des reduce-Vorgangs ist immer ein\n * Optional, parametrisiert mit dem Ergebnistyp. Die Reduzierung erfolgt immer\n * mit einem BinaryOperator\n *\n * @author Robert Rohm&lt;r.rohm@aeonium-systems.de&gt;\n */\npublic class Terminal04_reduce {\n\n public static void main(String[] args) {\n\n IntStream intStream = IntStream.of(1, 6, 4, 56, 68, 95, 266, 757, 668, 8865, 5);\n\n OptionalInt intMax = intStream.reduce(new IntBinaryOperator() {\n /**\n * Reduzierung zum Maximum:\n *\n * @param left Erster bzw. vorheriger Wert,\n * @param right nächster Wert\n * @return Maximum der beiden Werte\n */\n @Override\n public int applyAsInt(int left, int right) {\n return Math.max(left, right);\n }\n });\n System.out.println(\"intMax: \" + intMax.getAsInt());\n\n \n // Reduce mit komplexen Datenobjekten\n List personen = Person.createData();\n\n Optional reduced = personen.stream().reduce(new BinaryOperator() {\n /**\n *\n * @param t Erstes Element - oder Return-Wert des vorherigen Durchlaufs\n * @param u Nächstes Element\n * @return Zwischenergebnis\n */\n @Override\n public Person apply(Person t, Person u) {\n System.out.println(\"t: \" + t);\n System.out.println(\"u: \" + u);\n System.out.println(\"------------------\");\n return t;\n }\n });\n\n System.out.println(\"result: \" + reduced.get());\n }\n}"}}},{"rowIdx":661,"cells":{"text":{"kind":"string","value":"from transformers import AutoTokenizer, AutoModelForCausalLM,BitsAndBytesConfig,StoppingCriteriaList\nimport transformers\nimport torch\nfrom typing import Dict,List,Tuple\nfrom byzerllm.utils import (generate_instruction_from_history,\ncompute_max_new_tokens,tokenize_stopping_sequences,StopSequencesCriteria)\n\nfrom typing import Dict, Any,List,Generator\nfrom pyjava.storage import streaming_tar as STar\nfrom pyjava import RayContext\nfrom pyjava.api.mlsql import DataServer\nfrom byzerllm import BlockRow\nimport os\nimport time\n\ndef stream_chat(self,tokenizer,ins:str, his:List[Dict[str,str]]=[], \n max_length:int=4090, \n top_p:float=0.95,\n temperature:float=0.1,**kwargs):\n \n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") \n timeout_s = float(kwargs.get(\"timeout_s\",60*5)) \n skip_check_min_length = int(kwargs.get(\"stopping_sequences_skip_check_min_length\",0)) \n \n role_mapping = { \n \"user\":\"User\", \n \"assistant\":\"Assistant\",\n }\n \n fin_ins = generate_instruction_from_history(ins,his,role_mapping=role_mapping) \n\n tokens = tokenizer(fin_ins, return_token_type_ids=False,return_tensors=\"pt\").to(device)\n\n stopping_criteria = None\n \n if \"stopping_sequences\" in kwargs: \n stopping_sequences = [torch.tensor(word).to(device) for word in tokenize_stopping_sequences(tokenizer,kwargs[\"stopping_sequences\"].split(\",\"))] \n input_length = tokens[\"input_ids\"].shape[1]\n stopping_criteria=StoppingCriteriaList([StopSequencesCriteria(\n tokenizer=tokenizer,\n stops=stopping_sequences,\n input_start=input_length,\n skip_check_min_length=skip_check_min_length\n )])\n \n max_new_tokens = compute_max_new_tokens(tokens,max_length) \n \n start_time = time.monotonic() \n response = self.generate(\n input_ids=tokens[\"input_ids\"],\n max_new_tokens= max_new_tokens,\n repetition_penalty=1.05,\n temperature=temperature,\n attention_mask=tokens.attention_mask,\n eos_token_id=tokenizer.eos_token_id,\n pad_token_id=tokenizer.eos_token_id,\n bos_token_id=tokenizer.bos_token_id,\n early_stopping=True,\n max_time=timeout_s,\n stopping_criteria=stopping_criteria,\n ) \n time_taken = time.monotonic() - start_time \n new_tokens = response[0][tokens[\"input_ids\"].shape[1]:]\n print(f\"generate took {time_taken} s to complete. tokens/s:{len(new_tokens)/time_taken}\",flush=True)\n answer = tokenizer.decode(new_tokens, skip_special_tokens=True)\n return [(answer,\"\")]\n\n\ndef init_model(model_dir,infer_params:Dict[str,str]={},sys_conf:Dict[str,str]={}):\n longContextMode = infer_params.get(\"longContextMode\",\"true\") == \"true\" \n if longContextMode:\n old_init = transformers.models.llama.modeling_llama.LlamaRotaryEmbedding.__init__\n def ntk_scaled_init(self, dim, max_position_embeddings=4096, base=10000, device=None):\n\n #The method is just these three lines\n max_position_embeddings = 16384\n a = 8 #Alpha value\n base = base * a ** (dim / (dim-2)) #Base change formula\n\n old_init(self, dim, max_position_embeddings, base, device) \n \n transformers.models.llama.modeling_llama.LlamaRotaryEmbedding.__init__ = ntk_scaled_init\n\n pretrained_model_dir = os.path.join(model_dir,\"pretrained_model\")\n adaptor_model_dir = model_dir\n is_adaptor_model = os.path.exists(pretrained_model_dir)\n\n if not is_adaptor_model: \n pretrained_model_dir = model_dir\n\n tokenizer = AutoTokenizer.from_pretrained(pretrained_model_dir,trust_remote_code=True)\n tokenizer.padding_side=\"right\"\n tokenizer.pad_token_id=0\n tokenizer.bos_token_id = 1\n\n print(f\"longContextMode:{longContextMode}\", flush=True)\n\n quatization = infer_params.get(\"quatization\", \"false\")\n\n if quatization in [\"4\", \"8\", \"true\"]:\n print(f\"enable [{quatization}] quatization.\", flush=True)\n load_in_8bit = quatization == \"8\"\n # default using int4\n quantization_config = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_quant_type=\"nf4\",\n bnb_4bit_use_double_quant=False,\n bnb_4bit_compute_dtype=torch.bfloat16,\n )\n if load_in_8bit:\n llm_int8_threshold = infer_params.get(\"llm_int8_threshold\", 6.0)\n quantization_config = BitsAndBytesConfig(\n load_in_8bit=True,\n llm_int8_threshold=llm_int8_threshold,\n llm_int8_skip_modules=None,\n llm_int8_enable_fp32_cpu_offload=False,\n llm_int8_has_fp16_weight=False,\n )\n model = AutoModelForCausalLM.from_pretrained(\n pretrained_model_dir,\n trust_remote_code=True,\n device_map=\"auto\",\n quantization_config=quantization_config,\n )\n else:\n model = AutoModelForCausalLM.from_pretrained(pretrained_model_dir,trust_remote_code=True,\n device_map='auto', \n torch_dtype=torch.bfloat16 \n )\n if is_adaptor_model:\n from peft import PeftModel\n model = PeftModel.from_pretrained(model, adaptor_model_dir)\n\n model.eval() \n if quatization:\n model = torch.compile(model) \n\n model = model.to_bettertransformer() \n import types\n model.stream_chat = types.MethodType(stream_chat, model) \n return (model,tokenizer)\n\n\n\ndef sft_train(data_refs:List[DataServer],\n train_params:Dict[str,str],\n conf: Dict[str, str])->Generator[BlockRow,Any,Any]:\n from ..utils.sft import sft_train as common_sft_train\n return common_sft_train(data_refs,train_params,conf) \n\n\ndef sfft_train(data_refs:List[DataServer],\n train_params:Dict[str,str],\n conf: Dict[str, str])->Generator[BlockRow,Any,Any]:\n from ..utils.fulltune.pretrain import sfft_train as common_sfft_train\n return common_sfft_train(data_refs,train_params,conf)"}}},{"rowIdx":662,"cells":{"text":{"kind":"string","value":"import { Injectable, OnDestroy } from '@angular/core';\nimport { webSocket, WebSocketSubject } from 'rxjs/webSocket';\nimport { Observable } from 'rxjs';\nimport { environment } from 'src/environments/environment';\nimport { WsEchoService } from './echo-ws.service';\nimport { Logger } from 'src/app/core/logger';\n\n/*\n Example service for websocket backend connection.\n Works in pair with either:\n - python echo backend server. See .md file in digitalpanda-study/web-socket-and-worker for setup at \"ws://localhost:9998/echo\"\n - digitalpanda-backend text-based bidirectoninal WebSocket controller at `${environment.wsApiEndpoint}/ui/websocket/echo`\n*/\n@Injectable({\n providedIn: 'root'\n})\nexport class EchoNativeWebSocketService implements OnDestroy, WsEchoService{\n \n private echoEndpoint: string = environment.wsApiEndpoint + \"/ws/echo\" //\"ws://localhost:9998/echo\"\n private socket$: WebSocketSubject;\n \n public connect(): void {\n if (!this.socket$ || this.socket$.closed) {\n Logger.debug(\"[EchoSocketService].connect() : new WebSocketSubject connection\")\n this.socket$ = webSocket({\n url: this.echoEndpoint\n , deserializer : e => String(e.data)\n , serializer : e => e\n , openObserver : { next: () => Logger.debug(\"[EchoSocketService]: server connection opened\")}\n , closeObserver : { next: () => Logger.debug(\"[EchoSocketService]: server connection closed\")}\n });\n }\n}\n\n sendMessage(message: string) {\n this.connect();\n this.socket$.next(message);\n }\n\n getInputStream(): Observable {\n this.connect();\n return this.socket$.asObservable();\n }\n\n ngOnDestroy(): void {\n this.close();\n }\n\n close() {\n this.socket$.complete();\n }\n}"}}},{"rowIdx":663,"cells":{"text":{"kind":"string","value":"#[starknet::interface]\ntrait IHelloWorld {\n fn read_hello_world(self: @IContractState) -> felt252;\n\n fn write_hello_world(ref self: IContractState, new_message: felt252);\n}\n\n#[starknet::contract]\nmod contract {\n #[storage]\n struct Storage {\n hello_world: felt252,\n }\n\n #[constructor]\n fn constructor(ref self: ContractState) {\n self.hello_world.write('Hello Encode!');\n }\n\n #[external(v0)]\n impl HelloWorldInterface of super::IHelloWorld {\n fn read_hello_world(self: @ContractState) -> felt252 {\n self.hello_world.read()\n }\n\n fn write_hello_world(ref self: ContractState, new_message: felt252) {\n self.hello_world.write(new_message);\n }\n }\n}"}}},{"rowIdx":664,"cells":{"text":{"kind":"string","value":"\n\n\n….\n\n\n\n\nStore the details of 5 teachers who are having qualification as NET.\n*/ \n\n// format one use simplexml_load_string()\n\n// xml string\n/*\n$xmlstr=\"\"; // called as root\n$xml= simplexml_load_string($xmlstr);\n*/\n\nclass teach{\n public $tname,$sub,$exp;\n public function __construct($t,$s,$e){\n $this->tname=$t;\n $this->sub=$s;\n $this->exp=$e;\n }\n\n public function create_xml(SimpleXMLElement $xml){\n $cs_obj=$xml->addChild(\"Computer Science\"); //parent\n $tname_obj=$cs_obj->addChild(\"Teacher Name\",\"$this->tname\"); // child \n $qual=$cs_obj->addChild(\"Qualification\",\"UGC-NET\");\n $sub_obj=$cs_obj->addChild(\"Subject Taught\",\"$this->sub\");\n $exp_obj=$cs_obj->addChild(\"Experience\",\"$this->exp\");\n }\n}\n\n// using SimpleXMLElement class :\n// $xml=new SimpleXMLElement(\"\"); // root\n// $cs=$xml->addChild(\"Computer Science\"); //parent \n// $tname=$cs->addChild(\"Teacher Name\",\"prajwal\"); // child\n// $qual=$cs->addChild(\"Qualification\",\"UGC-NET\"); // child\n// $sub=$cs->addChild(\"Subject Taught\",\"PHP_LAB\"); // child\n// $sub=$cs->addChild(\"Subject Taught\",\"PYTHON_LAB\"); // child\n// $sub=$cs->addChild(\"Subject Taught\",\"CPP_LAB\"); // child\n// $exp=$cs->addChild(\"Experience\",\"1year\"); // child\n// $xml->asXML(\"Teacher.xml\");\n\n$obj[0]=new teach(\"teach1\",\"php\",1);\n$obj[1]=new teach(\"teach2\",\"cpp\",2);\n$obj[2]=new teach(\"teach3\",\"python\",3);\n$obj[3]=new teach(\"teach4\",\"EVS\",4);\n$obj[5]=new teach(\"teach5\",\"english\",5);\n\n$xml=new SimpleXMLElement(\"\"); // root\nforeach($obj as $t){\n $t->create_xml($xml);\n}\n$xml->asXML(\"Teacher.xml\");\necho \"

XML Doc created Successful.

\".\"
\";\n\n/*\n \n// Adding child named \"institution\" \n// and valued \"geeksforgeeks\" \n\n$xml->addChild(\"institution\", \"geeksforgeeks\"); \n\n \n// Adding attribute named \"type\" and value \n// \"educational\" in institution element. \n\n$xml->institution->addAttribute(\"type\", \"educational\"); \n\n \n\n\n*/\n?>"}}},{"rowIdx":665,"cells":{"text":{"kind":"string","value":"/**\n * 상태 : (offsetX, offsetY, size) = 좌표 (offsetX, offsetY)에서 시작하여 가로 길이와 세로 길이가 size인 정사각형을 압축했을 때 남아 있는 0과 1의 개수\n * 종료 조건 : 상태가 나타내는 범위의 크기와 관계없이 범위 안 원소들이 모두 0이거나 1이면 하나의 수자로 압축\n * - 0의 개수가 zero, 1의 개수가 one 이라면\n * {0 : 1, 1 : 0} -> 모든 원소가 0\n * {0 : 0, 1 : 1} -> 모든 원소가 1\n * 점화식 : (offsetX, offsetY, size) = (offsetX, offsetY, size/2) + (offsetX + size/2, offsetY, size/2)\n * + (offsetX, offsetY + size/2, size/2) + (offsetX + size/2, offsetY + size/2, size/2)\n */\nclass Solution {\n public int[] solution(int[][] arr) {\n Count count = count(0, 0, arr.length, arr);\n return new int[]{count.zero, count.one};\n }\n\n private Count count(int offsetX, int offsetY, int size, int[][] arr) {\n int h = size / 2;\n for (int x = offsetX; x < offsetX + size; x++) { //모든 원소가 같은 값을 같는지 순회(검사)\n for (int y = offsetY; y < offsetY + size; y++) {\n if (arr[y][x] != arr[offsetY][offsetX]) {\n return count(offsetX, offsetY, h, arr) //모든 결과 합해서 반환\n .add(count(offsetX + h, offsetY, h, arr))\n .add(count(offsetX, offsetY + h, h, arr))\n .add(count(offsetX + h, offsetY + h, h, arr));\n }\n }\n }\n //다른 값을 가진 원소가 있다면 종료 조건에 해당하지 않고 점화식에 따라 반환값 구하기\n if (arr[offsetY][offsetX] == 1) { //해당 원소가 1인지 0인지에 따라 알맞은 개수를 갖는 Count 객체 반환\n return new Count(0, 1);\n }\n return new Count(1, 0);\n }\n\n private static class Count {\n public final int zero;\n public final int one;\n\n public Count(int zero, int one) {\n this.zero = zero;\n this.one = one;\n }\n\n public Count add(Count other) { //원소가 섞여있다면 재귀 메서드를 사용하여 점화식에 따라 부분 문제를 해결해야 함\n // 4개의 작은 정사각형 결과 합을 구해야 함\n return new Count(zero + other.zero, one + other.one);\n }\n }\n}"}}},{"rowIdx":666,"cells":{"text":{"kind":"string","value":"import { useState } from \"react\";\nimport Bookings from \"./Bookings/Bookings\";\nimport Restaurant from \"../../assets/images/restaurant.jpg\";\nimport SeasoningDish from \"../../assets/images/seasoning-dish.jpg\";\nimport WarningIcon from \"../../assets/icons/warning.png\";\nimport AsteriskIcon from \"../../assets/icons/asterisk.png\";\n\nimport \"./BookingForm.css\";\n\nexport const getInitialDate = () => {\n const initialDate = new Date().toLocaleDateString(\"en-IN\", {\n day: \"2-digit\",\n month: \"2-digit\",\n year: \"numeric\",\n });\n\n const formattedDate = initialDate.split(\"/\").reverse().join(\"-\");\n return formattedDate;\n};\n\nconst BookingForm = ({ availableTimes, dispatch, submitForm }) => {\n const [date, setDate] = useState({\n value: getInitialDate(),\n isValid: true,\n });\n\n const [time, setTime] = useState(\"17:00\");\n\n const [guests, setGuests] = useState({\n value: \"1\",\n isValid: true,\n });\n\n const [occasion, setOccasion] = useState(\"Birthday\");\n\n const isFormValid = date.isValid && guests.isValid;\n\n const validateDateInput = (selectedDate) => {\n if (!selectedDate) {\n setDate({ value: \"\", isValid: false });\n return false;\n }\n\n return true;\n };\n\n const handleDateChange = (e) => {\n const selectedDate = e.target.value;\n\n const isValidDate = validateDateInput(selectedDate);\n\n if (isValidDate) {\n setDate({\n value: selectedDate,\n isValid: true,\n });\n dispatch({ type: \"date_change\", payload: selectedDate });\n }\n };\n\n const handleTimeChange = (e) => {\n setTime(e.target.value);\n };\n\n const validateGuestsInput = (enteredGuests) => {\n if (!enteredGuests) {\n setGuests({ value: \"\", isValid: false });\n return false;\n }\n\n if (+enteredGuests < 1 || +enteredGuests > 10) {\n setGuests({ value: enteredGuests, isValid: false });\n return false;\n }\n\n return true;\n };\n\n const handleGuestsChange = (e) => {\n const enteredGuests = e.target.value;\n\n const isValidGuests = validateGuestsInput(enteredGuests);\n\n if (isValidGuests) setGuests({ value: enteredGuests, isValid: true });\n };\n\n const handleOccasionChange = (e) => {\n setOccasion(e.target.value);\n };\n\n const handleSubmit = (e) => {\n e.preventDefault();\n\n if (!isFormValid) return;\n\n const formData = {\n date: date.value,\n time: time,\n guests: guests.value,\n occasion: occasion,\n };\n\n submitForm(formData);\n };\n\n return (\n
\n
\n

Book a table

\n

Find a table for any occasion

\n
\n \"restaurant\n \"adrian\n
\n
\n
\n
\n \n \"asteriskindicates required fields.\n \n
\n
\n
\n \n \n {!date.isValid && (\n
\n \"warning\n

Please select a date.

\n
\n )}\n
\n
\n \n \n \n \n
\n
\n \n \n {!guests.isValid && (\n
\n \"warning\n

Please enter a number between 1 and 10.

\n
\n )}\n
\n
\n \n \n \n \n \n
\n \n \n
\n
\n );\n};\n\nexport default BookingForm;"}}},{"rowIdx":667,"cells":{"text":{"kind":"string","value":"import React, { useEffect, useState } from \"react\";\n// import { useDispatch, useSelector } from \"react-redux\";\nimport { useDispatch, useSelector } from \"react-redux\";\n\nimport Footer from \"./Foot\";\nimport \"../index.css\";\nimport { getTodos, handleCompleted, removeToDo } from \"./TodoSlice\";\n\nfunction ToDoList() {\n const dispatch = useDispatch();\n useEffect(() => {\n console.log(\"dispatched\");\n\n const newTodos = getTodos();\n dispatch(newTodos);\n }, [dispatch]);\n\n const { data, error, loading } = useSelector((state) => state);\n console.log(data);\n const [filter, setfilter] = useState < string > (\"all\");\n const handleFilter = (selectedFilter) => {\n setfilter(selectedFilter);\n };\n\n const filteredTodos = data.filter((todo) => {\n if (filter === \"active\") {\n return !todo.completed;\n } else if (filter === \"completed\") {\n return todo.completed;\n } else {\n return true;\n }\n });\n console.log(data);\n const handle = (todo) => {\n dispatch(handleCompleted(todo));\n };\n return (\n <>\n
    \n {filteredTodos &&\n filteredTodos.map((todo) =>\n todo.completed ? (\n
  • \n
    \n handle(todo)}\n className=\"toggle\"\n checked={todo.completed}\n type=\"checkbox\"\n />\n \n dispatch(removeToDo(todo))}\n className=\"destroy\"\n >\n
    \n
  • \n ) : (\n
  • \n
    \n handle(todo)}\n />\n \n dispatch(removeToDo(todo))}\n className=\"destroy\"\n >\n
    \n
  • \n )\n )}\n
\n