{ // 获取包含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":1093530,"cells":{"text":{"kind":"string","value":"where('phone_number',$admin_phone_number)->first();\n $this->actingAs($admin);\n return $admin;\n }\n /**\n * A basic feature test example.\n */\n public function test_city_web(): void\n { \n $out = \"test_city_web\";\n var_dump($out);\n $admin = $this->get_authenticated_user();\n $response = $this->get('/cities');\n $response->assertStatus(200);\n\n $dt_url = \"/ajax-get-city-data?_=1680244096377&columns%5B0%5D%5Bdata%5D=DT_RowIndex&columns%5B0%5D%5Bname%5D=id&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=name&columns%5B1%5D%5Bname%5D=name&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=action&columns%5B2%5D%5Bname%5D=action&columns%5B2%5D%5Bsearchable%5D=false&columns%5B2%5D%5Borderable%5D=false&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&draw=1&length=10&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&search=&start=0\";\n $response = $this->getJson($dt_url);\n $response->assertStatus(200)->assertJsonStructure([\n 'draw',\n 'recordsTotal',\n 'recordsFiltered',\n 'data' => [\n '*' => [\n 'id',\n 'name',\n 'created_at',\n 'updated_at',\n 'deleted_at',\n 'action',\n 'DT_RowIndex'\n ]\n ]\n\n ]);\n }\n\n public function test_get_create_city_web(): void\n {\n $out = \"test_get_create_city_web\";\n var_dump($out);\n $admin = $this->get_authenticated_user();\n \n $response = $this->get('/cities/create');\n $response->assertStatus(200);\n }\n\n public function test_store_create_city(): void\n {\n $out = \"test_store_create_city\";\n var_dump($out);\n $admin = $this->get_authenticated_user();\n\n $response = $this->post('/cities', [\n 'name' => $this->faker->name,\n ]);\n $response->assertStatus(302)\n ->assertRedirect('/cities');\n }\n\n public function test_city_detail_web(): void \n {\n $out = \"test_city_detail_web\";\n var_dump($out);\n $admin = $this->get_authenticated_user();\n\n $city_id = City::all()->random()->id;\n $response = $this->get('/cities/' . $city_id);\n $response->assertStatus(200);\n }\n\n public function test_update_city(): void\n {\n $out = \"test_update_city\";\n var_dump($out);\n $admin = $this->get_authenticated_user();\n\n $rand_city_id = City::all()->random()->id;\n $response = $this->put('/cities/' . $rand_city_id, [\n 'name' => $this->faker->name,\n ]);\n $response->assertStatus(302)\n ->assertRedirect('/cities/' . $rand_city_id);\n }\n\n public function test_delete_city(): void \n { \n $out = \"test_delete_city\";\n var_dump($out);\n $admin = $this->get_authenticated_user();\n\n $city_id = City::all()->random()->id;\n \n $response = $this->delete('/cities/' . $city_id);\n $response->assertStatus(302)\n ->assertRedirect('/cities');\n }\n}"}}},{"rowIdx":1093531,"cells":{"text":{"kind":"string","value":"package com.ohgiraffers.section02.set.run;\n\nimport java.util.*;\n\npublic class Application1 {\n public static void main(String[] args) {\n\n /*\n * Set 인터페이스를 구현한 Set 컬렉션 클래스의 특징\n * 1. 요소의 저장 순서를 유지하지 않는다.\n * 2. 같은 요소의 중복 저장을 허용하지 않는다. (null 값도 중복되지 않게 하나의 null만 저장)\n * */\n\n /*\n * HashSet 클래스\n * Set 컬렉션 클래스에서 가장 많이 사용되는 클래스 중 하나이다.\n * Hash-> 해시 알고리즘을 사용해서 검색 속도가 빠르다는 장점이 있다.\n * */\n\n HashSet hSet = new HashSet<>();\n// Set hset2 = new HashSet();\n// Collection hset3 = new HashSet();\n\n hSet.add(new String(\"java\"));\n hSet.add(\"oracle\");\n hSet.add(\"jdbc\");\n hSet.add(\"html\");\n hSet.add(\"css\");\n\n // 저장 순서는 유지되지 않는다.\n System.out.println(\"hset : \" + hSet);\n\n hSet.add(\"java\");\n\n // 중복을 허용하지 않는다.\n System.out.println(\"hset : \" + hSet);\n System.out.println(\"저장된 객체수 : \" + hSet.size());\n System.out.println(\"포함확인 : \" + hSet.contains(\"oracle\"));\n\n /*\n * 저장된 객체를 한개씩 꺼내는 기능이 없다.\n * 반복문을 이용해서 연속처리하는 방법\n * */\n\n // 1. toArray()배열로 바꾸고 for문 사용\n Object[] arr = hSet.toArray();\n for (int i = 0; i < arr.length; i++){\n System.out.println(i + \" : \" + arr[i]);\n }\n\n // 2. iterator()로 목록을 만들어서 연속 처리\n Iterator iter = hSet.iterator();\n\n while (iter.hasNext()){\n System.out.println(\"Iterator로 목록을 만들어 출력 = \" + iter.next());\n }\n\n Boolean result = hSet.remove(\"oracle\");\n System.out.println(\"지운 결과 : \" + result);\n System.out.println(\"hset = \" + hSet);\n\n hSet.clear();\n System.out.println(\"isEmpty : \" + hSet.isEmpty());\n System.out.println(\"hSet = \" + hSet);\n\n }\n}"}}},{"rowIdx":1093532,"cells":{"text":{"kind":"string","value":"import 'package:flutter/material.dart';\nimport 'package:flutter/widgets.dart';\n\nclass ButtonWidget extends StatelessWidget {\n final String text;\n final VoidCallback onClicked;\n\n const ButtonWidget({\n Key? key,\n required this.text,\n required this.onClicked,\n }) : super(key: key);\n\n @override\n Widget build(BuildContext context) => ElevatedButton(\n style: ElevatedButton.styleFrom(\n minimumSize: Size.fromHeight(50),\n shape: StadiumBorder(),\n backgroundColor: Color.fromARGB(135, 139, 75, 148),\n ),\n onPressed: onClicked,\n child: FittedBox(\n child:\n Text(text, style: TextStyle(fontSize: 18, color: Colors.white)),\n ),\n );\n}"}}},{"rowIdx":1093533,"cells":{"text":{"kind":"string","value":"package co.com.sofka.questions.model;\n\nimport javax.validation.constraints.NotBlank;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\n\n/**\n * QuestionDTO class.\n * DTO para la colección Question\n */\npublic class QuestionDTO {\n private String id;\n @NotBlank\n private String userId;\n @NotBlank(message = \"Debe existir el userName para este objeto\")\n private String userName;\n @NotBlank\n private String question;\n @NotBlank\n private String description;\n @NotBlank\n private String category;\n private List answers;\n\n public QuestionDTO() {\n\n }\n\n public QuestionDTO(String userId, String userName, String question, String description, String category) {\n this.userId = userId;\n this.userName = userName;\n this.question = question;\n this.description = description;\n this.category = category;\n }\n\n public QuestionDTO(String id, String userId, String userName, String question, String description, String category) {\n this.id = id;\n this.userId = userId;\n this.userName = userName;\n this.question = question;\n this.description = description;\n this.category = category;\n }\n\n public List getAnswers() {\n this.answers = Optional.ofNullable(answers).orElse(new ArrayList<>());\n return answers;\n }\n\n public void setAnswers(List answers) {\n this.answers = answers;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getUserId() {\n return userId;\n }\n\n public void setUserId(String userId) {\n this.userId = userId;\n }\n\n public String getQuestion() {\n return question;\n }\n\n public void setQuestion(String question) {\n this.question = question;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n @Override\n public String toString() {\n return \"QuestionDTO{\" +\n \"id='\" + id + '\\'' +\n \", userId='\" + userId + '\\'' +\n \", userName='\" + userName + '\\'' +\n \", question='\" + question + '\\'' +\n \", description='\" + description + '\\'' +\n \", category='\" + category + '\\'' +\n '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n QuestionDTO that = (QuestionDTO) o;\n return Objects.equals(id, that.id);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id);\n }\n}"}}},{"rowIdx":1093534,"cells":{"text":{"kind":"string","value":"\"use client\"\nimport { useThemeStore } from \"@/store\";\nimport { useTheme } from \"next-themes\";\nimport { themes } from \"@/config/thems\";\nimport { ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';\n\n\n\n\nconst PieChartWithPaddingAngle = ({ height = 300 }) => {\n const { theme: config, setTheme: setConfig } = useThemeStore();\n const { theme: mode } = useTheme();\n const theme = themes.find((theme) => theme.name === config);\n\n const data = [\n { name: 'Group A', value: 400 },\n { name: 'Group B', value: 300 },\n { name: 'Group C', value: 300 },\n { name: 'Group D', value: 200 },\n ];\n const COLORS = [\n `hsl(${theme?.cssVars[mode === \"dark\" ? \"dark\" : \"light\"].primary})`,\n `hsl(${theme?.cssVars[mode === \"dark\" ? \"dark\" : \"light\"].info})`,\n `hsl(${theme?.cssVars[mode === \"dark\" ? \"dark\" : \"light\"].warning})`,\n `hsl(${theme?.cssVars[mode === \"dark\" ? \"dark\" : \"light\"].success})`\n ];\n\n\n return (\n \n \n \n {data.map((entry, index) => (\n \n ))}\n \n \n {data.map((entry, index) => (\n \n ))}\n \n \n \n );\n};\n\nexport default PieChartWithPaddingAngle;"}}},{"rowIdx":1093535,"cells":{"text":{"kind":"string","value":"import sys\nimport os\n\n# Add the parent directory to the sys.path\nparent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\nsys.path.append(parent_dir)\n\nfrom solvers import Solver\nfrom rich import print\nimport random\nimport csv\nimport concurrent.futures\n\ndef run_thread(solver, user_choice_algorithm, initial_state, goal_state):\n try:\n solution, steps, cost_of_path, nodes_expanded, search_depth, running_time = solver.solve(user_choice_algorithm, initial_state, goal_state)\n solutions[user_choice_algorithm][initial_state] = [solution, cost_of_path, nodes_expanded, search_depth, running_time]\n if solution:\n print(f'Solution found for {initial_state}.')\n else:\n print(f'No solution found for {initial_state}.')\n except Exception as err:\n print(f'Error occurred while solving {initial_state}.')\n print(err)\n quit()\n\nif __name__ == '__main__':\n sample_size = int(input('Enter sample size: '))\n solutions = {'1': {},'2': {},'3': {},'4': {}}\n solver = Solver()\n test_cases = [x.strip() for x in open('tests.txt', 'r')]\n sample = random.sample(test_cases, sample_size)\n goal_state = '0123456780'\n\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=5000)\n for i, initial_state in enumerate(sample):\n executor.submit(run_thread, solver, '1', initial_state, goal_state)\n executor.submit(run_thread, solver, '2', initial_state, goal_state)\n executor.submit(run_thread, solver, '3', initial_state, goal_state)\n executor.submit(run_thread, solver, '4', initial_state, goal_state)\n print(i)\n executor.shutdown(wait=True)\n\n with open('results.csv', 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['Initial State'] + ['Solution', 'Steps', 'Nodes Expanded', 'Search Depth', 'Running Time'] * 4)\n for initial_state in solutions['1']:\n row = []\n row.append(initial_state)\n for algorithm in solutions:\n row.extend(solutions[algorithm][initial_state])\n writer.writerow(row)"}}},{"rowIdx":1093536,"cells":{"text":{"kind":"string","value":"## Usage\n\n**Want to suggest a new feature or chat with us?** [Join our Discord](https://deno.re/discord)\n\n### Minify Files\n\nWhen you request a `*.min.js`, `*.min.mjs` or `*.min.jsx` file and the release does not contain such a file, deno.re will automatically minify the file.\n\n```ts\n// Since deno-esbuild only comes with a mod.js file, deno.re will minify it for you.\nimport { build } from 'https://deno.re/esbuild/deno-esbuild@v0.20.0/mod.min.js'\n```\n\n### Import Latest Tag\n\n```ts\nimport { encodeHex } from 'https://deno.re/denoland/deno_std/encoding/hex.ts'\n```\n\n### Import Specific Commit\n\n```ts\nimport { encodeHex } from 'https://deno.re/denoland/deno_std@6cc097b6212eaba083634b0e826c0916a49a3148/encoding/hex.ts'\n```\n\n### Import Specific Tag\n\n```ts\nimport { encodeHex } from 'https://deno.re/denoland/deno_std@0.220.0/encoding/hex.ts'\n```\n\n### Omit Entry Point\n\n```ts\nimport { crypto } from 'https://deno.re/denoland/deno_std@0.221.0/crypto'\n// ↓\nimport { crypto } from 'https://deno.re/denoland/deno_std@0.221.0/crypto/mod.ts'\n```\n\nThe order of priority for file extensions can be found [here](https://github.com/boywithkeyboard/deno.re/blob/main/registry/get_entry_point.ts#L6).\n\n## Self-Hosting\n\nThere are two approaches you can take to deploy your custom instance of deno.re.\n\nYou can either\n\n1. use our [Docker image](https://github.com/boywithkeyboard/deno.re/pkgs/container/deno.re)\n2. or clone the repository and run `npm ci && npm run build` to build the server\n\nEither way, you need to set the below environment variables in order for the server to work:\n\n- `BASE_URL` *(The base URL for your custom instance, e.g. `https://foo.com`)*\n- `S3_HOSTNAME` *(The public hostname of your bucket, e.g. `bar.foo.com`)*\n- `S3_ACCESS_KEY_ID`\n- `S3_SECRET_ACCESS_KEY`\n- `S3_BUCKET` *(The name of your S3 bucket, e.g. `foo`)*\n- `S3_ENDPOINT` *(e.g. `https://.eu.r2.cloudflarestorage.com` for Cloudflare R2)*\n\n## Terms of Use\n\ndeno.re is designed to be a permanent caching layer for Deno modules stored on GitHub. If you decide to abuse our service in whatever way, we reserve the right to blacklist your GitHub account.\n\nNo guarantee of availability is assumed for this service."}}},{"rowIdx":1093537,"cells":{"text":{"kind":"string","value":"import { Component, OnInit } from '@angular/core';\nimport { Router, NavigationEnd } from '@angular/router';\nimport { SidebarService } from '../shared/sidebar/sidebar.service'\nimport { FormBuilder, Validators, FormGroup } from '@angular/forms';\nimport { ValidatorsService } from '../shared/services/validators.service';\nimport { AuthServiceService } from '../auth/services/auth-service.service';\n\nimport Swal from 'sweetalert2';\nimport { ProfileService } from './services/profile.service';\n\n@Component({\n selector: 'app-user-profile',\n templateUrl: './user-profile.component.html',\n styleUrls: ['./user-profile.component.scss']\n})\nexport class UserProfileComponent implements OnInit {\n\n FormReactive: FormGroup = this.fb.group({\n name: ['', [Validators.required, Validators.pattern(this.validatorsService.patternName), this.validatorsService.nameVacio]],\n lastName: ['', [Validators.required, Validators.pattern(this.validatorsService.patternName), this.validatorsService.nameVacio]],\n city: ['', [Validators.required, this.validatorsService.nameVacio]],\n phone: ['', [Validators.required, Validators.minLength(10), Validators.pattern(this.validatorsService.phonePattern), Validators.maxLength(10)]]\n });\n\n FormReactiveAgregar: FormGroup = this.fb.group({\n type: ['', [Validators.required, this.validatorsService.nameVacio]],\n city: ['', [Validators.required, this.validatorsService.nameVacio]],\n address: ['', [Validators.required, this.validatorsService.nameVacio]],\n price: ['', [Validators.required, ]],\n desc: ['', [Validators.required, this.validatorsService.nameVacio]],\n images: [[], [Validators.required]]\n });\n\n user:any;\n\n FormReactivePassword: FormGroup = this.fb.group({\n uid: [''],\n passwordA: ['', [Validators.required]],\n password: ['', [Validators.required, Validators.minLength(8)]],\n passwordv: ['', [Validators.required]]\n },\n {\n validators: [this.validatorsService.passwordActual('passwordA', 'uid'), this.validatorsService.passwordIguales('password', 'passwordv')]\n });\n\n hide = true;\n public imagenes: any;\n\n products: any;\n\n\n get nameMsg(): string {\n const errors = this.FormReactive.get('name').errors;\n\n if (errors['required'] || errors['vacio']){\n return 'El nombre es obligatorio.';\n }else if (errors['pattern']){\n return 'El nombre no peude contener caracteres numericos o especiales.';\n }\n\n return '';\n }\n\n get lastNameMsg(): string {\n const errors = this.FormReactive.get('lastName').errors;\n\n if (errors['required'] || errors['vacio']){\n return 'El apellido es obligatorio.';\n }else if (errors['pattern']){\n return 'El apellido no peude contener caracteres numericos o especiales.';\n }\n\n return '';\n }\n\n\n constructor(public sidebarservice: SidebarService,\n private router: Router,\n private fb: FormBuilder,\n private validatorsService: ValidatorsService,\n private authService: AuthServiceService,\n private profileService: ProfileService) { }\n\n toggleSidebar() {\n this.sidebarservice.setSidebarState(!this.sidebarservice.getSidebarState());\n}\n\ngetSideBarState() {\n return this.sidebarservice.getSidebarState();\n}\n\nhideSidebar() {\n this.sidebarservice.setSidebarState(true);\n}\n\nngOnInit() {\n this.router.events.subscribe((evt) => {\n if (!(evt instanceof NavigationEnd)) {\n return;\n }\n window.scrollTo(0, 0)\n });\n this.user = this.authService.user;\n console.log(this.user);\n\n this.FormReactive.get('name').setValue(this.user.name);\n this.FormReactive.get('phone').setValue(this.user.phone);\n this.FormReactive.get('city').setValue(this.user.city);\n this.FormReactive.get('lastName').setValue(this.user.lastName);\n\n this.FormReactivePassword.get('uid').setValue(this.user.uid);\n\n\n this.profileService.obtenerProductosDeUsuario(this.user.uid)\n .subscribe((resp)=>{\n this.products = resp.produts;\n });\n\n\n $.getScript('./assets/plugins/fancy-file-uploader/jquery.ui.widget.js');\n $.getScript('./assets/plugins/fancy-file-uploader/jquery.fileupload.js');\n $.getScript('./assets/plugins/fancy-file-uploader/jquery.iframe-transport.js');\n $.getScript('./assets/plugins/fancy-file-uploader/jquery.fancy-fileupload.js');\n $.getScript('./assets/plugins/Drag-And-Drop/imageuploadify.min.js');\n $.getScript('./assets/js/custom-file-upload.js');\n}\n\nonProductos(){\n this.router.navigateByUrl('profile/productos');\n}\n\n\ncampoValid(campo:string){\n return (this.FormReactive.get(campo).invalid\n && this.FormReactive.get(campo).touched);\n}\n\ncampoValidP(campo:string){\n return (this.FormReactivePassword.get(campo).invalid\n && this.FormReactivePassword.get(campo).touched);\n}\n\ncampoValidA(campo:string){\n return (this.FormReactiveAgregar.get(campo).invalid\n && this.FormReactiveAgregar.get(campo).touched);\n}\n\nupdateInfo(){\n const {name, lastName, city, phone} = this.FormReactive.value;\n\n const body ={\n name, lastName, city, phone\n }\n\n this.authService.updateUser(body, this.user.uid)\n .subscribe( ok =>{\n if(ok === true){\n console.log(ok);\n this.router.navigateByUrl('profile');\n window.location.reload();\n }else{\n Swal.fire('Error', ok, 'error');\n }\n});\n}\n\nonUpdatePassword(){\n\n const {password} = this.FormReactivePassword.value;\n const body = {\n password\n }\n\n this.authService.updateUser(body, this.user.uid)\n .subscribe( ok=>{\n if(ok === true){\n window.location.reload();\n }else{\n Swal.fire('Error', ok, 'error');\n }\n });\n\n}\nagregarHab(){\n const {type, city, address, price, desc} = this.FormReactiveAgregar.value;\n\n\n\n const body = new FormData();\n\n\n\n body.append('image', this.imagenes.file, this.imagenes.name);\n\n\n body.append('type', type);\n body.append('city', city);\n body.append('address', address);\n body.append('price', price);\n body.append('desc', desc);\n\n this.profileService.insertProduct(body)\n .subscribe(resp =>{\n if(resp.ok === true){\n window.location.reload();\n }else{\n Swal.fire('Error', resp, 'error');\n }\n })\n\n}\n\ncapturarFile(event){\n const [file] = event.target.files;\n this.imagenes = {\n file: file,\n name: file.name\n }\n\n}\n\n\ndeleteProduct(uid){\n\n this.profileService.deleteProduct(uid)\n .subscribe((resp)=>{\n if(resp.ok === true){\n console.log(resp);\n window.location.reload();\n }else{\n Swal.fire('Error', resp, 'error');\n }\n });\n\n}\n\n}"}}},{"rowIdx":1093538,"cells":{"text":{"kind":"string","value":"import React, {useRef, useState} from 'react';\nimport TextField from \"@material-ui/core/TextField\";\nimport Button from \"@material-ui/core/Button\";\nimport Avatar from \"@material-ui/core/Avatar\";\nimport IconButton from \"@material-ui/core/IconButton\";\nimport {useHistory} from 'react-router-dom'\nimport {makeStyles} from \"@material-ui/core\";\nimport {useFirebase, useFirebaseConnect} from \"react-redux-firebase\";\nimport { v4 as uuidv4 } from 'uuid';\nimport {useForm} from \"react-hook-form\";\nimport FormLoader from \"./FormLoader\";\nimport {useSelector} from \"react-redux\";\nconst DEFAULT_AVATAR = \"https://www.w3schools.com/howto/img_avatar.png\"\nconst useStyles = makeStyles(theme => ({\n textField: {\n marginTop: theme.spacing(1),\n marginBottom: theme.spacing(1),\n },\n avatarPicker: {\n alignSelf: 'center',\n justifyContent: \"center\",\n alignItems: \"center\",\n display: 'flex',\n '& > *': {\n margin: theme.spacing(1),\n },\n },\n inputFile: {\n display: \"none\",\n },\n avatarLarge: {\n width: theme.spacing(15),\n height: theme.spacing(15),\n borderColor: 'black',\n borderWidth: theme.spacing(1)\n },\n}))\n\nconst Form = () => {\n\n const classes = useStyles()\n const history = useHistory()\n useFirebaseConnect('users')\n const firebase = useFirebase()\n const users = useSelector((state) => state.firebase.ordered.users ? state.firebase.ordered.users : [])\n const form = useRef(null)\n const fileInput = useRef(null)\n\n const { register, handleSubmit, errors } = useForm({\n mode: 'onChange',\n reValidateMode: 'onChange',\n defaultValues: {\n email: '',\n name: '',\n phone: '',\n },\n });\n\n const [avatar, setAvatar] = useState(null)\n const [loading, setLoading] = useState(false)\n\n const onSubmit =async (data) => {\n setLoading(true)\n const formData = new FormData(form.current)\n let file = formData.get('avatar')\n let fileName = null;\n data.phone = parseInt(data.phone)\n if(file.size > 0){\n fileName = uuidv4() + '.' + file.name.split('.').pop()\n await firebase.uploadFile('/',file,null,{name: fileName} )\n }\n if(fileName) data.image = fileName\n firebase.ref('users').push(data, () => {\n setLoading(false)\n history.goBack()\n })\n\n\n }\n\n const onFileInputChange = () => {\n if(fileInput.current.files.length > 0){\n let file = fileInput.current.files[0]\n let reader = new FileReader()\n reader.onload = () => setAvatar(reader.result)\n reader.readAsDataURL(file)\n\n }\n }\n\n\n return (\n
\n
\n \n \n
\n {\n let existUser = users.find( user => user.value.name === value)\n return !existUser\n }\n })}\n />\n \n \n {\n loading && \n }\n \n \n \n );\n};\n\nexport default Form;"}}},{"rowIdx":1093539,"cells":{"text":{"kind":"string","value":"import 'package:audioplayers/audioplayers.dart';\nimport 'package:flutter/material.dart';\nimport 'package:flutter_markdown/flutter_markdown.dart';\nimport 'package:frontend/service/utils/sp_provider.dart';\nimport 'package:url_launcher/url_launcher.dart';\nimport 'package:markdown/markdown.dart' as md;\n\n///\n/// Custom chat message display [markdown] style\n/// - [CustomMarkdown]\n/// - [CustomAudioTagSyntax]\n/// - [CustomAudioBuilder]\n/// - [CustomSyntaxHighlighter]\n///\nclass CustomMarkdown extends StatelessWidget {\n CustomMarkdown(this.displayMsg, {super.key});\n\n final String displayMsg;\n final AudioPlayer player = AudioPlayer();\n\n @override\n Widget build(BuildContext context) {\n return MarkdownBody(\n data: displayMsg,\n selectable: true,\n fitContent: true,\n syntaxHighlighter: CustomSyntaxHighlighter(),\n styleSheet: MarkdownStyleSheet(\n codeblockDecoration: BoxDecoration(\n color: Colors.white70, borderRadius: BorderRadius.circular(8))),\n onTapLink: (String text, String? href, String title) {\n if (href == null || href.isEmpty) return;\n launchUrl(Uri.parse(href));\n },\n imageBuilder: (Uri uri, String? title, String? alt) {\n var header = {'Authorization': SpProvider().getString('token')};\n return Container(\n alignment: Alignment.topLeft,\n width: 128,\n height: 128,\n child: ClipRRect(\n borderRadius: const BorderRadius.all(Radius.circular(8)),\n child: Image.network(uri.toString(), headers: header)));\n },\n extensionSet: md.ExtensionSet(md.ExtensionSet.gitHubWeb.blockSyntaxes, [\n ...md.ExtensionSet.gitHubWeb.inlineSyntaxes,\n CustomAudioTagSyntax()\n ]),\n builders: {'audio': CustomAudioBuilder(player)},\n );\n }\n}\n\n///\n/// Custom audio tag syntax,\n/// to parse \n///\nclass CustomAudioTagSyntax extends md.InlineSyntax {\n CustomAudioTagSyntax() : super(r'\\s*
Subsets and Splits

No community queries yet

The top public SQL queries from the community will appear here once available.