text
stringlengths 184
4.48M
|
---|
/*
* Copyright 2017-2022 University of Padua, Italy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.unipd.dei.dards.index;
import com.univocity.parsers.tsv.TsvParser;
import com.univocity.parsers.tsv.TsvParserSettings;
import it.unipd.dei.dards.parse.DocumentParser;
import it.unipd.dei.dards.parse.ParsedDocument;
import it.unipd.dei.dards.parse.LongEvalParser;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.LowerCaseFilterFactory;
import org.apache.lucene.analysis.core.StopFilterFactory;
import org.apache.lucene.analysis.custom.CustomAnalyzer;
import org.apache.lucene.analysis.en.KStemFilterFactory;
import org.apache.lucene.analysis.standard.StandardTokenizerFactory;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.*;
import org.apache.lucene.search.similarities.*;
import org.apache.lucene.store.FSDirectory;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.List;
/**
* Indexes documents processing a whole directory tree.
*
* @author DARDS
* @version 1.00
* @since 1.00
*/
public class DirectoryIndexer {
/**
* One megabyte
*/
private static final int MBYTE = 1024 * 1024;
/**
* The index writer.
*/
private final IndexWriter writer;
/**
* The class of the {@code DocumentParser} to be used.
*/
private final Class<? extends DocumentParser> dpCls;
/**
* The directory (and sub-directories) where documents are stored.
*/
private final Path docsDir;
/**
* The extension of the files to be indexed.
*/
private final String extension;
/**
* The charset used for encoding documents.
*/
private final Charset cs;
/**
* The total number of documents expected to be indexed.
*/
private final long expectedDocs;
/**
* The start instant of the indexing.
*/
private final long start;
/**
* The total number of indexed files.
*/
private long filesCount;
/**
* The total number of indexed documents.
*/
private long docsCount;
/**
* The total number of indexed bytes
*/
private long bytesCount;
/**
* The path of the file containng the urls.
*/
private final String urlFile;
/**
* Creates a new indexer.
*
* @param analyzer the {@code Analyzer} to be used.
* @param similarity the {@code Similarity} to be used.
* @param ramBufferSizeMB the size in megabytes of the RAM buffer for indexing documents.
* @param indexPath the directory where to store the index.
* @param docsPath the directory from which documents have to be read.
* @param extension the extension of the files to be indexed.
* @param charsetName the name of the charset used for encoding documents.
* @param expectedDocs the total number of documents expected to be indexed
* @param dpCls the class of the {@code DocumentParser} to be used.
* @param urlFile the path of the file containing the document id-url pairs.
* @throws NullPointerException if any of the parameters is {@code null}.
* @throws IllegalArgumentException if any of the parameters assumes invalid values.
*/
public DirectoryIndexer(final Analyzer analyzer, final Similarity similarity, final int ramBufferSizeMB,
final String indexPath, final String docsPath,final String urlFile, final String extension,
final String charsetName, final long expectedDocs,
final Class<? extends DocumentParser> dpCls) {
if (dpCls == null) {
throw new NullPointerException("Document parser class cannot be null.");
}
this.dpCls = dpCls;
if (analyzer == null) {
throw new NullPointerException("Analyzer cannot be null.");
}
if (similarity == null) {
throw new NullPointerException("Similarity cannot be null.");
}
if (ramBufferSizeMB <= 0) {
throw new IllegalArgumentException("RAM buffer size cannot be less than or equal to zero.");
}
final IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
iwc.setSimilarity(similarity);
iwc.setRAMBufferSizeMB(ramBufferSizeMB);
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
iwc.setCommitOnClose(true);
iwc.setUseCompoundFile(true);
if (indexPath == null) {
throw new NullPointerException("Index path cannot be null.");
}
if (indexPath.isEmpty()) {
throw new IllegalArgumentException("Index path cannot be empty.");
}
final Path indexDir = Paths.get(indexPath);
// if the directory does not already exist, create it
if (Files.notExists(indexDir)) {
try {
Files.createDirectory(indexDir);
} catch (Exception e) {
throw new IllegalArgumentException(
String.format("Unable to create directory %s: %s.", indexDir.toAbsolutePath().toString(),
e.getMessage()), e);
}
}
if (!Files.isWritable(indexDir)) {
throw new IllegalArgumentException(
String.format("Index directory %s cannot be written.", indexDir.toAbsolutePath().toString()));
}
if (!Files.isDirectory(indexDir)) {
throw new IllegalArgumentException(String.format("%s expected to be a directory where to write the index.",
indexDir.toAbsolutePath().toString()));
}
if (docsPath == null) {
throw new NullPointerException("Documents path cannot be null.");
}
if (docsPath.isEmpty()) {
throw new IllegalArgumentException("Documents path cannot be empty.");
}
final Path docsDir = Paths.get(docsPath);
if (!Files.isReadable(docsDir)) {
throw new IllegalArgumentException(
String.format("Documents directory %s cannot be read.", docsDir.toAbsolutePath().toString()));
}
if (!Files.isDirectory(docsDir)) {
throw new IllegalArgumentException(
String.format("%s expected to be a directory of documents.", docsDir.toAbsolutePath().toString()));
}
this.docsDir = docsDir;
if (urlFile == null) {
throw new NullPointerException("Url file path cannot be null.");
}
this.urlFile=urlFile;
if (extension == null) {
throw new NullPointerException("File extension cannot be null.");
}
if (extension.isEmpty()) {
throw new IllegalArgumentException("File extension cannot be empty.");
}
this.extension = extension;
if (charsetName == null) {
throw new NullPointerException("Charset name cannot be null.");
}
if (charsetName.isEmpty()) {
throw new IllegalArgumentException("Charset name cannot be empty.");
}
try {
cs = Charset.forName(charsetName);
} catch (Exception e) {
throw new IllegalArgumentException(
String.format("Unable to create the charset %s: %s.", charsetName, e.getMessage()), e);
}
if (expectedDocs <= 0) {
throw new IllegalArgumentException(
"The expected number of documents to be indexed cannot be less than or equal to zero.");
}
this.expectedDocs = expectedDocs;
this.docsCount = 0;
this.bytesCount = 0;
this.filesCount = 0;
try {
writer = new IndexWriter(FSDirectory.open(indexDir), iwc);
} catch (IOException e) {
throw new IllegalArgumentException(String.format("Unable to create the index writer in directory %s: %s.",
indexDir.toAbsolutePath().toString(), e.getMessage()), e);
}
this.start = System.currentTimeMillis();
}
/**
* Creates a new indexer.
*
* @param analyzer the {@code Analyzer} to be used.
* @param similarity the {@code Similarity} to be used.
* @param ramBufferSizeMB the size in megabytes of the RAM buffer for indexing documents.
* @param indexPath the directory where to store the index.
* @param expectedDocs the total number of documents expected to be indexed
* @throws NullPointerException if any of the parameters is {@code null}.
* @throws IllegalArgumentException if any of the parameters assumes invalid values.
*/
public DirectoryIndexer(final Analyzer analyzer, final Similarity similarity, final int ramBufferSizeMB,
final String indexPath, final long expectedDocs) {
if (analyzer == null) {
throw new NullPointerException("Analyzer cannot be null.");
}
if (similarity == null) {
throw new NullPointerException("Similarity cannot be null.");
}
if (ramBufferSizeMB <= 0) {
throw new IllegalArgumentException("RAM buffer size cannot be less than or equal to zero.");
}
final IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
iwc.setSimilarity(similarity);
iwc.setRAMBufferSizeMB(ramBufferSizeMB);
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
iwc.setCommitOnClose(true);
iwc.setUseCompoundFile(true);
if (indexPath == null) {
throw new NullPointerException("Index path cannot be null.");
}
if (indexPath.isEmpty()) {
throw new IllegalArgumentException("Index path cannot be empty.");
}
final Path indexDir = Paths.get(indexPath);
// if the directory does not already exist, create it
if (Files.notExists(indexDir)) {
try {
Files.createDirectory(indexDir);
} catch (Exception e) {
throw new IllegalArgumentException(
String.format("Unable to create directory %s: %s.", indexDir.toAbsolutePath().toString(),
e.getMessage()), e);
}
}
if (!Files.isWritable(indexDir)) {
throw new IllegalArgumentException(
String.format("Index directory %s cannot be written.", indexDir.toAbsolutePath().toString()));
}
if (!Files.isDirectory(indexDir)) {
throw new IllegalArgumentException(String.format("%s expected to be a directory where to write the index.",
indexDir.toAbsolutePath().toString()));
}
if (expectedDocs <= 0) {
throw new IllegalArgumentException(
"The expected number of documents to be indexed cannot be less than or equal to zero.");
}
this.expectedDocs = expectedDocs;
this.docsCount = 0;
this.bytesCount = 0;
this.filesCount = 0;
try {
writer = new IndexWriter(FSDirectory.open(indexDir), iwc);
} catch (IOException e) {
throw new IllegalArgumentException(String.format("Unable to create the index writer in directory %s: %s.",
indexDir.toAbsolutePath().toString(), e.getMessage()), e);
}
this.start = System.currentTimeMillis();
this.dpCls=null;
this.docsDir=null;
this.extension=null;
this.cs=null;
this.urlFile=null;
}
/**
* Indexes the documents.
*
* @throws IOException if something goes wrong while indexing.
*/
public void index() throws IOException {
System.out.printf("%n#### Start indexing ####%n");
TsvParserSettings settings = new TsvParserSettings();
settings.getFormat().setLineSeparator("\n");
TsvParser parser = new TsvParser(settings);
List<String[]> urlList = parser.parseAll(new File(urlFile));
HashMap<String,String> urlMap=new HashMap<>();
for(String[] pair:urlList){
urlMap.put(pair[0],pair[1]);
}
Files.walkFileTree(docsDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.getFileName().toString().endsWith(extension)) {
DocumentParser dp = DocumentParser.create(dpCls, Files.newBufferedReader(file, cs),urlMap);
bytesCount += Files.size(file);
filesCount += 1;
Document doc = null;
for (ParsedDocument pd : dp) {
doc = new Document();
// add the document identifier
doc.add(new StringField(ParsedDocument.FIELDS.ID, pd.getIdentifier(), Field.Store.YES));
// add the document body
doc.add(new BodyField(pd.getBody()));
//System.out.println(pd.getIdentifier());
//System.out.println(pd.getBody());
//add the document url
doc.add(new UrlField(pd.getUrl()));
writer.addDocument(doc);
docsCount++;
// print progress every 10000 indexed documents
if (docsCount % 10000 == 0) {
System.out.printf("%d document(s) (%d files, %d Mbytes) indexed in %d seconds.%n",
docsCount, filesCount, bytesCount / MBYTE,
(System.currentTimeMillis() - start) / 1000);
}
}
}
return FileVisitResult.CONTINUE;
}
});
writer.commit();
writer.close();
if (docsCount != expectedDocs) {
System.out.printf("Expected to index %d documents; %d indexed instead.%n", expectedDocs, docsCount);
}
System.out.printf("%d document(s) (%d files, %d Mbytes) indexed in %d seconds.%n", docsCount, filesCount,
bytesCount / MBYTE, (System.currentTimeMillis() - start) / 1000);
System.out.printf("#### Indexing complete ####%n");
}
/**
* Indexes the documents.
* @param docs the list of document to index
* @throws IOException if something goes wrong while indexing.
*/
public void index(List<Document> docs) throws IOException {
System.out.printf("%n#### Start re-indexing from documents ####%n");
docsCount=0;
for(Document d: docs){
writer.addDocument(d);
docsCount++;
if (docsCount % 10000 == 0) {
System.out.printf("%d document(s) (%d files, %d Mbytes) re-indexed in %d seconds.%n",
docsCount, filesCount, bytesCount / MBYTE,
(System.currentTimeMillis() - start) / 1000);
}
}
writer.commit();
writer.close();
if (docsCount != expectedDocs) {
System.out.printf("Expected to index %d documents; %d indexed instead.%n", expectedDocs, docsCount);
}
System.out.printf("%d document(s) (%d files, %d Mbytes) re-indexed in %d seconds.%n", docsCount, filesCount,
bytesCount / MBYTE, (System.currentTimeMillis() - start) / 1000);
System.out.printf("#### Re-Indexing complete ####%n");
}
/**
* Main method of the class. Just for testing purposes.
*
* @param args command line arguments.
* @throws Exception if something goes wrong while indexing.
*/
public static void main(String[] args) throws Exception {
final int ramBuffer = 256;
final String docsPath = "./input/English/Documents/Trec";
final String indexPath = "experiment/index-stop-stem";
final String urlFile = "./input/French/urls.txt";
final String extension = "txt";
final int expectedDocs = 1570734;
final String charsetName = StandardCharsets.UTF_8.name();
final Analyzer a = CustomAnalyzer.builder().withTokenizer(StandardTokenizerFactory.class).addTokenFilter(
LowerCaseFilterFactory.class).addTokenFilter(StopFilterFactory.class).addTokenFilter(KStemFilterFactory.class).build();
//final Similarity sim = new MultiSimilarity(new Similarity[]{new BM25Similarity(), new DFRSimilarity(new BasicModelIne(), new AfterEffectL(), new NormalizationH2(0.9F))});
final Similarity sim = new BM25Similarity();
DirectoryIndexer i = new DirectoryIndexer(a, sim, ramBuffer, indexPath, docsPath,urlFile, extension,
charsetName, expectedDocs, LongEvalParser.class);
i.index();
}
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>第十二课 建造圣殿</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<link rel="stylesheet" type="text/css" href="page_styles.css"/>
<link href="calibreHtmlOutBasicCss.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="calibreMeta">
<div class="calibreMetaTitle">
<h1>
<a href="../w4lf8-w8n1g.html">2264 圣经之旅
</a>
</h1>
</div>
<div class="calibreMetaAuthor">
台湾福音书房
</div>
</div>
<div class="calibreMain">
<div class="calibreEbookContent">
<div class="calibreEbNavTop">
<a href="19-11.htm" class="calibreAPrev">previous page
</a>
<a href="19-13.htm" class="calibreANext">next page
</a>
</div>
<a name="top" class="calibre5" id="top"></a><h2 class="calibre6" id="calibre_pb_0">第十二课 建造圣殿</h2>
<div class="nav"><a href="19-11.htm" class="calibre3">上一篇</a> <a href="19.htm" class="calibre3">回目录</a> <a href="19-13.htm" class="calibre3">下一篇</a></div>
<hr class="calibre4"/>
<h3 class="calibre8">课文范围</h3>
<p class="calibre7">撒母耳记下七章,二十四章十八至二十五节。</p>
<h3 class="calibre8">目标</h3>
<p class="calibre7">一 从旧约大卫、所罗门建造圣殿的预表,看出神心中的喜悦是召会的建造。</p>
<p class="calibre7">二 从所罗门献殿的祷告,看见正确的祷告该是为着神的权益而祷告。</p>
<h3 class="calibre8">负担及研讨重点</h3>
<p class="calibre7">一 认识关于建造圣殿一些重要的属灵意义。</p>
<p class="calibre7">引题:一起唱补充本诗歌六百零三首,谈谈每人摸着什么?今天实际的圣殿是在那里?</p>
<p class="calibre7">开启:‘从建造圣殿的过程中,我们可以学得许多教训。读时,我们最好和历代志上、下所记关乎建殿的事一起读。</p>
<p class="calibre7">1. 建造圣殿,不是一件随便的事,必须先有神的旨意。大卫有心愿、有准备、有力量、有材料,可是神并不拣选他。神的旨意是定规所罗门为祂的名建造圣殿。’</p>
<p class="calibre7">2. 建造圣殿有一个主要的目的,就是‘为耶和华神的名’,大卫和所罗门都能够看到建殿乃是为着祂的名。今天召会和基督徒都是属灵的殿。今天召会的存在,信徒的生活,是否真是为着见证和传扬祂的名呢?</p>
<p class="calibre7">3. 圣殿是建造在阿珥楠的禾场上,因为那块地包含这样的故事-审判罪恶、悔改和认罪、献祭、赎罪、公义得到满足。今天神的殿,不管是有形或是无形的,都必须建造在这样的地基上。…</p>
<p class="calibre7">4. 王上五章十七节是讲到殿的根基-那些又大又宝贵的石头。我们也知道在那些石头中,有一块顶大的石头,是经过试验的,它作了根基的头块房角石,这就是预表新约时代圣殿的头块房角石是基督,而其余的根基石是使徒和申言者。这是一个严重的问题:我们的工程是不是建造在基督和使徒、申言者的根基上?</p>
<p class="calibre7">5. 建造圣殿的材料是金、银、铜、铁、木、石等。它们都是出于泥土的,它们的本相都是污秽、丑陋的。有的材料是重价买回来的,有的是从仇敌手中掳来的,也有的是甘心奉献的;可是都经过神分别为圣。</p>
<p class="calibre7">6. 圣殿的图样,必须出乎神。所罗门建造圣殿,不是凭着自己的聪明智慧,乃是凭着神的灵所启示的,和神的手所画出的图样,正像摩西建造会幕是完全依照山上的样式。</p>
<p class="calibre7">7. 让我们记得圣殿是所罗门一人所建造的,也是千万工人所建造的,正像召会是基督一人所建立的,也是千万个基督徒所共同有分的。(圣经提要第一卷,101~103页。)</p>
<p class="calibre7">应用:在聚会中积极尽功用-申言、祷告、赞美、带人、财物奉献…,并操练实际的服事-整洁、饼杯、招待、文书…。</p>
<p class="calibre7">二 正确的祷告乃是为着神的权益祷告,向着圣地、圣城和圣殿,也就是向着基督、神的国和神的家。</p>
<p class="calibre7">引题:所罗门献殿的祷告有那些特点?你如何祷告呢?</p>
<p class="calibre7">开启:‘关于神垂听祂选民祷告的七种情形,末了一种强调三件事:圣地,预表基督是分给众信徒的分;圣城,表征在基督里之神的国;以及圣殿,表征神在地上的家,就是召会。这三项-圣地、圣城和圣殿,是有关神经纶的三个重要项目。以色列人被掳到巴比伦时,但以理打开窗户,面向耶路撒冷,一日三次为圣地、圣城和圣殿祷告。这指明我们的祷告,必须向着基督、神的国和神的家,就是神永远经纶的目标,这样神必垂听我们的祷告。圣地、圣城和圣殿,都是基督的预表。基督是我们的美地;基督是我们的城,我们的国;基督也是殿,神的居所。今天,我们的祷告该对准圣地、圣城和圣殿。这就是说,我们的祷告该对准神在地上的权益,就是基督与召会。神权益的属灵意义,就是基督自己。这指明无论我们为谁祷告,我们的祷告必须对准基督,就是神的权益。我们需要为圣徒祷告,但我们的祷告不该对准他们。一面我们为他们祷告,另一面我们是因着神的权益为他们祷告。倘若我们的祷告只对准我们所代祷的人,这会带进仇敌的攻击。这是属灵争战中的属灵战略。…我们的祷告该全然为着神的权益,以完成神的经纶。’(列王纪生命读经,46~47页。)</p>
<p class="calibre7">应用:为着主今时代的行动祷告:福音的广传、推广神圣的真理、海外开展…。</p>
<h3 class="calibre8">辅助活动-交通主今时代的行动</h3>
<p class="calibre7">请召会中的父老,或由服事者向青少年讲述主今日在地上的行动:福音的广传、推广神圣的真理、海外开展…等等,同时播放‘敞开的窗户’片段,以加深青少年对主今日行动之扩展的印象,最后并一同为着神在地上的权益祷告。</p>
<h3 class="calibre8">福音的应用</h3>
<p class="calibre7">神的目标是建造召会作基督的身体,终极完成于新耶路撒冷。这伟大的事业乃是整个宇宙的意义。从神的建造的神圣启示来看,我们应问自己一些关键的问题:神为什么造我?我在地上作什么?我该如何计划此生?我想成就什么?我能帮助建造神所要建造的么?还是我建造自己所要的,而这会被神的审判丢入火湖呢?我是要为自己和自己的目标而活,还是为神和神的目标而活?神建造的本质是团体的,由成千上万的信徒所组成。为这建造,我们需要从疏离、单独和个人主义蒙拯救。我们受造不是要成为一个疏离的个人,而是要在基督里被建造成为神的家。为此,我们需要蒙拯救,不只脱离罪和悖逆,更要撇弃我们自私的独立和个人主义。同时,我们要蒙拯救脱离虚浮、空洞的生活,一种只专注追求属世成就,与神无关的生活。神拯救我们为着一个目的-建造召会作神的殿。</p>
<hr class="calibre4"/>
<div class="nav"><a href="19-11.htm" class="calibre3">上一篇</a> <a href="#top" class="calibre3">回页首</a> <a href="19.htm" class="calibre3">回目录</a> <a href="19-13.htm" class="calibre3">下一篇</a></div>
</div>
<div class="calibreToc">
<h2><a href="../w4lf8-w8n1g.html">Table of contents
</a></h2>
<div>
<ul>
<li>
<a href="01.htm">圣经之旅(一)蒙拣选的族类</a>
</li>
<li>
<a href="02.htm">圣经之旅(二)神圣别的子民</a>
</li>
<li>
<a href="03.htm">圣经之旅(三)据有享受美地</a>
</li>
<li>
<a href="04.htm">圣经之旅(四)建立神的国度</a>
</li>
<li>
<a href="05.htm">圣经之旅(五)殿与城的恢复</a>
</li>
<li>
<a href="06.htm">圣经之旅(六)爱、生命与建造</a>
</li>
<li>
<a href="07.htm">圣经之旅(七)有一婴孩为我们而生</a>
</li>
<li>
<a href="08.htm">圣经之旅(八)往荣耀里去的路径</a>
</li>
<li>
<a href="09.htm">圣经之旅(九)一粒麦子的繁殖与扩增</a>
</li>
<li>
<a href="10.htm">圣经之旅(十)满有荣光与卓越的职事</a>
</li>
<li>
<a href="11.htm">圣经之旅(十一)启示的基督、建造的召会</a>
</li>
<li>
<a href="12.htm">圣经之旅(十二)至宝的基督、荣耀的盼望</a>
</li>
<li>
<a href="13.htm">圣经之旅(十三)敬虔的奥秘、更美的新约</a>
</li>
<li>
<a href="14.htm">圣经之旅(十四)神圣的供备、生命的交通</a>
</li>
<li>
<a href="15.htm">圣经之旅(十五)终极的显出-新耶路撒冷</a>
</li>
<li>
<a href="16.htm">圣经之旅(一)服事者手册</a>
</li>
<li>
<a href="17.htm">圣经之旅(二)服事者手册</a>
</li>
<li>
<a href="18.htm">圣经之旅(三)服事者手册</a>
</li>
<li>
<a href="19.htm">圣经之旅(四)服事者手册</a>
</li>
<li>
<a href="20.htm">圣经之旅(五)服事者手册</a>
</li>
<li>
<a href="21.htm">圣经之旅(六)服事者手册</a>
</li>
<li>
<a href="22.htm">圣经之旅(七)服事者手册</a>
</li>
<li>
<a href="23.htm">圣经之旅(八)服事者手册</a>
</li>
<li>
<a href="24.htm">圣经之旅(九)服事者手册</a>
</li>
<li>
<a href="25.htm">圣经之旅(十)服事者手册</a>
</li>
<li>
<a href="26.htm">圣经之旅(十一)服事者手册</a>
</li>
<li>
<a href="27.htm">圣经之旅(十二)服事者手册</a>
</li>
<li>
<a href="28.htm">圣经之旅(十三)服事者手册</a>
</li>
<li>
<a href="29.htm">圣经之旅(十四)服事者手册</a>
</li>
<li>
<a href="30.htm">圣经之旅(十五)服事者手册</a>
</li>
<li>
<a href="index.htm">回书目</a>
</li>
<li>
<a href="01-00.htm">前言</a>
</li>
<li>
<a href="01-01.htm">‘圣经之旅’使用说明</a>
</li>
<li>
<a href="01-02.htm">神起初的创造</a>
</li>
<li>
<a href="01-03.htm">神的恢复与进一步的创造</a>
</li>
<li>
<a href="01-04.htm">神创造的中心-人</a>
</li>
<li>
<a href="01-05.htm">生命的园子和宇宙的对偶</a>
</li>
<li>
<a href="01-06.htm">宇宙的悲剧</a>
</li>
<li>
<a href="01-07.htm">神对人的拯救</a>
</li>
<li>
<a href="01-08.htm">该隐与亚伯</a>
</li>
<li>
<a href="01-09.htm">挪亚改变时代的生活与工作</a>
</li>
<li>
<a href="01-10.htm">在复活里的生活</a>
</li>
<li>
<a href="01-11.htm">亚伯拉罕-蒙召族类之父</a>
</li>
<li>
<a href="01-12.htm">亚伯拉罕在迦南</a>
</li>
<li>
<a href="01-13.htm">亚伯拉罕与神的交通</a>
</li>
<li>
<a href="01-14.htm">罗得-一个失败的义人</a>
</li>
<li>
<a href="01-15.htm">以撒-承受恩典的人</a>
</li>
<li>
<a href="01-16.htm">雅各-蒙神拣选的人</a>
</li>
<li>
<a href="01-17.htm">雅各的被变化</a>
</li>
<li>
<a href="01-18.htm">约瑟-在生命中作王</a>
</li>
</ul>
</div>
</div>
<div class="calibreEbNav">
<a href="19-11.htm" class="calibreAPrev">previous page
</a>
<a href="../w4lf8-w8n1g.html" class="calibreAHome">start
</a>
<a href="19-13.htm" class="calibreANext">next page
</a>
</div>
</div>
</body>
</html>
|
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'Product.dart';
import 'Cart_page.dart'; // Import de la nouvelle page du panier
class ShopPage extends StatefulWidget {
@override
_ShopPageState createState() => _ShopPageState();
}
class _ShopPageState extends State<ShopPage> {
late List<Product> products;
final String baseURL = 'http://localhost:8080';
int cartItemCount = 0; // Nombre d'articles dans le panier
int? cartId; // ID du panier
@override
void initState() {
super.initState();
fetchProducts();
}
Future<void> fetchProducts() async {
final response = await http.get(Uri.parse('$baseURL/product'));
if (response.statusCode == 200) {
List<dynamic> data = json.decode(response.body);
setState(() {
products = data.map((json) => Product(
id: json['id_product'],
title: json['product_title'],
description: json['product_description'],
price: json['product_price'],
image: '$baseURL/uploads/${json['product_img']}',
)).toList();
});
} else {
throw Exception('Failed to load products');
}
}
Future<int?> _getUserIdFromToken() async {
final prefs = await SharedPreferences.getInstance();
final token = prefs.getString('token');
if (token != null) {
final jwtPayload = json.decode(
ascii.decode(base64.decode(base64.normalize(token.split(".")[1]))));
final userId = jwtPayload['id'];
return userId;
} else {
return null;
}
}
Future<void> fetchCartId() async {
print('Fetching cart ID');
final userId = await _getUserIdFromToken();
print('User ID: $userId');
if (userId != null) {
final response = await http.get(Uri.parse('$baseURL/cart/get/$userId'));
if (response.statusCode == 200) {
print('Cart ID response: ${response.body}');
final cartData = json.decode(response.body);
if (cartData.isNotEmpty) {
setState(() {
cartId = cartData[0]['id_cart']; // Mettre à jour l'ID du panier
});
}
}
}
}
Future<void> addToCart(int productId) async {
print('Product ID: $cartId');
await fetchCartId(); // Récupérer l'ID du panier si ce n'est pas encore fait
if (cartId != null) {
try {
final Map<String, dynamic> requestData = {
'id_product': productId,
'id_cart': cartId,
'item_quantity': 1
};
final response = await http.post(
Uri.parse('$baseURL/cart/add'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(requestData),
);
if (response.statusCode == 200) {
print('Produit ajouté au panier avec succès');
} else {
print('Échec de l\'ajout au panier');
}
} catch (error) {
print('Erreur lors de l\'ajout au panier: $error');
}
} else {
print('ID du panier non trouvé');
}
}
void _navigateToCartPage() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CartPage()),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Boutique'),
actions: [
Stack(
children: [
IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: _navigateToCartPage, // Naviguer vers la page du panier
),
cartItemCount > 0
? Positioned(
right: 8,
top: 8,
child: CircleAvatar(
backgroundColor: Colors.red,
radius: 8,
child: Text(
'$cartItemCount',
style: TextStyle(
fontSize: 8,
color: Colors.white,
),
),
),
)
: SizedBox.shrink(),
],
),
],
),
body: products != null
? ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
final product = products[index];
return Padding(
padding: EdgeInsets.all(8.0),
child: Card(
elevation: 3,
child: InkWell(
onTap: () {
// Mettez ici ce que vous voulez faire au clic sur le produit
},
child: Row(
children: [
Container(
width: 100,
height: 100,
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.network(
product.image,
fit: BoxFit.cover,
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
product.title,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
Text(product.description),
Text(
'${product.price}\ points',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
],
),
),
),
Padding(
padding: EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {
addToCart(product.id);
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.blue),
),
child: Icon(Icons.add_shopping_cart),
),
),
],
),
),
),
);
},
)
: Center(
child: CircularProgressIndicator(),
),
);
}
}
|
import Image from "next/image"
import { invalidateQuery, useMutation, useQuery } from "@blitzjs/rpc"
import { FC, useEffect, useRef, useState } from "react"
import {
Button,
Flex,
Text,
Box,
Input,
Modal,
ModalContent,
ModalHeader,
ModalBody,
ModalCloseButton,
ModalOverlay,
ModalProps,
HStack,
} from "@chakra-ui/react"
import { Camera, Edit, Trash } from "react-feather"
import { isValidPhoneNumber } from "react-phone-number-input"
import { UserImage } from "@prisma/client"
import { useCurrentUser } from "app/core/hooks/useCurrentUser"
import { EditUser } from "app/users/validations"
import editUser from "app/users/mutations/editUser"
import getCurrentUser from "app/users/queries/getCurrentUser"
import getUser from "app/users/queries/getUser"
import { numberWithCommas } from "helpers/number"
import Gem from "app/core/icons/Gem"
import removePictures from "app/users/mutations/removePictures"
import sendOTP from "app/auth/mutations/sendOTP"
import ConfirmModal from "app/core/components/ConfirmModal"
import AddPictureModal from "./AddPictureModal"
import LabeledTextField from "app/core/components/LabeledTextField"
import Form, { FORM_ERROR } from "app/core/components/Form"
import PinField from "../../PinField"
import useMenu from "app/core/hooks/useMenu"
import { gemsToDollar } from "helpers/price"
import getUserCountry from "app/users/queries/getUserCountry"
import PhoneField from "../../PhoneField"
interface EditProfileProps {
user: NonNullable<ReturnType<typeof useCurrentUser>>
focusOnMount?: boolean
}
const EditPhoneModal = ({
isPhone,
...props
}: Omit<ModalProps, "children"> & { isPhone?: boolean }) => {
const [userCountry] = useQuery(getUserCountry, null, {
suspense: false,
useErrorBoundary: false,
keepPreviousData: true,
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
retryOnMount: false,
// 12 hours cache time,
staleTime: 1000 * 60 * 60 * 12,
})
const [sendOTPMutation, { isSuccess, isLoading, error }] = useMutation(sendOTP)
const [editUserMutation] = useMutation(editUser, {
onSuccess: async () => {
await invalidateQuery(getCurrentUser)
props.onClose()
},
})
return (
<Modal isCentered {...props}>
<ModalOverlay />
<ModalContent
justifyItems="center"
backgroundColor="black"
background="linear-gradient(180deg, rgba(255, 255, 255, 0.05) 46.4%, rgba(10, 7, 12, 0.05) 200%)"
>
<ModalHeader>Edit {isPhone ? "Phone Number" : "Email"}</ModalHeader>
<ModalCloseButton />
<ModalBody p="2rem">
{!isSuccess}
<Form
submitText={isSuccess ? "Save" : undefined}
onSubmit={async (values) => {
if (!values.code) return
try {
await editUserMutation({
code: values.code,
...(isPhone
? {
phone: values.phone,
}
: {
email: values.email,
}),
})
} catch (error) {
if (error.code === "P2002") {
// This error comes from Prisma
if (error.meta?.target?.includes("phone")) {
return { phone: "This phone is already being used" }
} else if (error.meta?.target?.includes("email")) {
return { phone: "This email is already being used" }
}
}
return {
[FORM_ERROR]: error.message,
}
}
}}
schema={EditUser}
>
{({ values, handleSubmit }) => (
<>
{isPhone ? (
<PhoneField name="phone" defaultCountryCode={userCountry?.countryCode} />
) : (
<LabeledTextField
name="email"
label="Email"
type="email"
placeholder="Email"
required
/>
)}
{error && <Text color="red.500">{(error as Error).message}</Text>}
{!isSuccess ? (
<Button
isLoading={isLoading}
onClick={() =>
sendOTPMutation(isPhone ? { phone: values.phone! } : { email: values.email! })
}
disabled={
isPhone
? !values.phone ||
!isValidPhoneNumber(values.phone, userCountry?.countryCode)
: !values.email
}
bg="white"
color="black"
w="full"
borderRadius="2xl"
>
Send code
</Button>
) : (
<HStack justifyContent="center">
<PinField name="code" onComplete={() => handleSubmit()} />
</HStack>
)}
</>
)}
</Form>
</ModalBody>
</ModalContent>
</Modal>
)
}
const EditProfile: FC<EditProfileProps> = ({ user, focusOnMount }) => {
const { dispatch } = useMenu()
const inputRef = useRef<HTMLInputElement | null>(null)
const [image, setImage] = useState<File | null>(null)
const [showRemovePictureModal, setShowRemovePictureModal] = useState(false)
const [editMode, setEditMode] = useState<"email" | "phone" | null>(null)
const refetchUser = async () =>
await Promise.all([
invalidateQuery(getCurrentUser),
invalidateQuery(getUser, { username: user.username }),
])
const [removePicturesMutation] = useMutation(removePictures, {
onSuccess: refetchUser,
})
const [editUserMutation] = useMutation(editUser, {
onSuccess: refetchUser,
})
useEffect(() => {
if (focusOnMount && inputRef.current) {
inputRef.current.focus()
inputRef.current.click()
}
}, [inputRef, focusOnMount])
const [pictureToBeRemoved, setPictureToBeRemoved] = useState<UserImage | null>(null)
return (
<Flex flexDir="column" mt="1.5rem">
{editMode !== null && (
<EditPhoneModal isOpen onClose={() => setEditMode(null)} isPhone={editMode === "phone"} />
)}
<ConfirmModal
title="Are you sure to remove picture?"
isOpen={showRemovePictureModal}
onClose={() => {
setShowRemovePictureModal(false)
setPictureToBeRemoved(null)
}}
onConfirm={() => {
if (pictureToBeRemoved) {
removePicturesMutation({
id: pictureToBeRemoved.id,
imageUrl: pictureToBeRemoved.url,
})
setShowRemovePictureModal(false)
}
}}
>
<Flex flexDir="column" alignItems="center">
<Box borderRadius="xl" overflow="hidden" position="relative" w="10rem" h="11.5rem">
{pictureToBeRemoved && (
<Image
alt="thumbnail"
objectFit="cover"
objectPosition="center center"
src={pictureToBeRemoved.url}
layout="fill"
//placeholder="blur"
//blurDataURL={user.imageUrl}
/>
)}
</Box>
</Flex>
</ConfirmModal>
{image && (
<AddPictureModal
isOpen
onClose={() => setImage(null)}
refetchUser={refetchUser}
image={image}
/>
)}
<Flex
flexDir="column"
h="100%"
gridGap={{
base: "1rem",
md: "2rem",
}}
>
<Box
overflowX="auto"
h="100%"
sx={{
paddingBottom: "7px",
"&::-webkit-scrollbar": {
borderRadius: "100px",
height: "4px",
width: "40px",
backgroundColor: `rgba(255,255,255, 0.05)`,
},
"&::-webkit-scrollbar-thumb": {
backgroundColor: `rgba(255,255,255, 0.05)`,
},
}}
>
<Flex flexDir="row" gridGap="1rem" w="fit-content">
{user.images.length < 10 && (
<Flex
bg="rgba(10, 7, 12, 0.25)"
border="1px dashed rgba(255, 255, 255, 0.35)"
cursor="pointer"
_hover={{
bg: "rgba(255, 255, 255, 0.2)",
}}
borderRadius="xl"
overflow="hidden"
position="relative"
w="6rem"
h="7.5rem"
alignItems="center"
justifyContent="center"
onClick={() => inputRef.current?.click()}
>
<Input
type="file"
display="none"
ref={inputRef}
accept="image/*"
onChange={(evt) => setImage(evt.target.files?.[0] || null)}
/>
<Box
border="1px solid #B026FF"
borderRadius="full"
p="1rem"
w="fit-content"
h="fit-content"
>
<Camera color="#B026FF" />
</Box>
</Flex>
)}
{user.images.map((image) => (
<Box
borderRadius="xl"
overflow="hidden"
position="relative"
w="6rem"
h="7.5rem"
key={image.id}
>
<Box
position="absolute"
right={0}
top={0}
bg="rgba(10, 7, 13, 0.5)"
backdropFilter="blur(20px)"
borderRadius="full"
p=".4rem"
m=".3rem"
zIndex="1"
cursor="pointer"
onClick={() => {
setPictureToBeRemoved(image)
setShowRemovePictureModal(true)
}}
>
<Trash width={18} height={18} color="white" />
</Box>
<Box pos="relative" sx={{ aspectRatio: "4 / 5" }}>
<Image
alt="thumbnail"
objectFit="cover"
objectPosition="center center"
src={image.url}
layout="fill"
//placeholder="blur"
//blurDataURL={user.imageUrl}
/>
</Box>
</Box>
))}
</Flex>
</Box>
<Flex flexDir="column" h="100%" mt=".5rem">
<Form
style={{ height: "100%" }}
schema={EditUser}
initialValues={{
name: user.name,
price: user.price,
phone: user.phone || undefined,
email: user.email || undefined,
}}
onSubmit={async (values) => {
try {
await editUserMutation({
name: values.name || null,
price: values.price || 0,
email: values.email !== user.email ? values.email || null : undefined,
})
} catch (error) {
if (error.code === "P2002") {
// This error comes from Prisma
if (error.meta?.target?.includes("phone")) {
return { phone: "This phone is already being used" }
} else if (error.meta?.target?.includes("email")) {
return { email: "This email is already being used" }
}
} else {
return { [FORM_ERROR]: error.toString() }
}
}
}}
>
{({ submitting, values }) => (
<Flex flexDir="column" justifyContent="space-between" h="100%" gridGap="1rem">
<Flex flexDir="column" gridGap="1rem">
<Flex
flexDir="column"
gridGap=".5rem"
mb="0.5rem"
onClick={() => {
if (user.role !== "CREATOR") {
dispatch({
type: "SET_PAGE",
payload: {
page: "EARN",
},
})
}
}}
>
<LabeledTextField
name="price"
label="Price per second"
placeholder="Price"
type="number"
fontSize="1rem"
paddingBottom="0.1rem"
inputLeftElement={<Gem boxSize={5} />}
/>
<Text fontWeight="medium" ml=".5rem" opacity=".75">
{values.price ? (
<>$ {numberWithCommas(gemsToDollar(values.price ?? 0))} / second</>
) : (
<>Free</>
)}
</Text>
</Flex>
<LabeledTextField name="name" label="Name" placeholder="Name" fontSize="1rem" />
<LabeledTextField
name="email"
label="Email"
placeholder="[email protected]"
disabled={user.email}
fontSize="1rem"
inputRightElement={
<Edit cursor="pointer" onClick={() => setEditMode("email")} />
}
/>
<LabeledTextField
disabled
name="phone"
label="Phone"
placeholder="(555) 123-4567"
type="phone"
fontSize="1rem"
inputRightElement={
<Edit cursor="pointer" onClick={() => setEditMode("phone")} />
}
/>
</Flex>
<Button
variant="outline"
w="100%"
py="1.5rem"
type="submit"
isLoading={submitting}
disabled={submitting}
>
Save changes
</Button>
</Flex>
)}
</Form>
</Flex>
</Flex>
</Flex>
)
}
export default EditProfile
|
<template>
<div>
<b-alert :show="export_alert" variant="success" @dismissed="export_alert = false">
<h6 class="alert-heading">Export request sent</h6>
<h6> A CSV file will download shortly. </h6>
</b-alert>
<div style="max-height: 75vh; display: block; overflow-x: auto;">
<div v-for="list in lists" class="dash">
<coloumn :title="list"></coloumn>
</div>
<div style="display: inline-block; margin: 80px;">
<h3 style="margin-bottom: 30px;"> Make a new List!</h3>
<b-button variant="primary" @click="newList">Create List</b-button>
</div>
</div>
<b-modal id="list-modal" title="Create a new List" @ok="createList" v-b-modal.modal-center>
<b-form ref="listForm" @submit.stop.prevent="submitList">
<b-form-group label="List Name" label-for="list-name">
<b-form-input id="list-name" v-model="listName" :state="listName" required></b-form-input>
</b-form-group>
</b-form>
</b-modal>
</div>
</template>
<script>
import Coloumn from "./coloumn.vue";
export default {
name: "Dashboard",
data() {
return {
lists: this.getLists(),
listName: null,
export_alert: false,
}
},
components: {
coloumn: Coloumn,
},
methods: {
getLists() {
fetch("http://localhost:5000/get/lists", {
method: "GET",
headers: {
"Content-Type": "application/json",
"AUTHENTICATION-TOKEN": localStorage.getItem("token")
}
}).then(res => res.json())
.then(data => {
if(data.lists.length != 0) {
this.lists = data.lists;
} else {
this.lists = []
}
})
.catch(err => alert(err));
},
updateLists() {
this.lists = this.getLists();
},
newList() {
this.$bvModal.show("list-modal");
},
createList(bvModalEvent) {
bvModalEvent.preventDefault();
this.submitList();
},
submitList() {
// Check form is valid
if (!this.$refs.listForm.checkValidity()) {
return;
}
// Form is valid, so lets create the list
fetch("http://localhost:5000/create/list", {
method: "POST",
headers: {
"Content-Type": "application/json",
"AUTHENTICATION-TOKEN": localStorage.getItem("token")
},
body: JSON.stringify({
title: this.listName,
}),
}).then((res) => res.json())
.then((data) => {
console.log(data);
if(data.status == "success") {
this.lists.push(this.listName);
this.listName = null;
this.$bvModal.hide("list-modal");
} else {
alert(data.error);
}
})
.catch((err) => {
alert(err);
});
},
triggerExportAlert() {
this.export_alert = 5;
}
}
};
</script>
<style scoped>
.dash {
height: 75vh;
width: 25%;
display: flex;
float: left;
}
</style>
|
package com.example.m015_room
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.m015_room.databinding.ActivityMainBinding
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel: MainViewModel by viewModels{
object : ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val wordDao = (application as App).db.wordDao()
return MainViewModel(wordDao) as T
}
}
}
private var previousWords: List<Word> = emptyList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
binding.inputTextField.doOnTextChanged {text, _, _, _ ->
if (text.isNullOrEmpty()) {
binding.btnAdd.isEnabled = false
}else {
binding.btnAdd.isEnabled = true
}
}
binding.btnAdd.setOnClickListener {
var wordText = binding.inputTextField.text.toString()
val regex = "^[а-яА-Яa-zA-Z-]+$".toRegex()
if (wordText.isEmpty() || !regex.matches(wordText)) {
Toast.makeText(this, getString(R.string.wrong_input), Toast.LENGTH_SHORT).show()
// Удаляем все недопустимые символы
wordText = wordText.filter { it.isLetter() || it == '-' }
binding.inputTextField.setText(wordText) // Обновляем текст в EditText
} else {
viewModel.addWord(wordText)
binding.inputTextField.text?.clear()
}
}
binding.btnDelete.setOnClickListener { viewModel.deleteAll() }
lifecycleScope.launch{
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.firstWords
.collect{words ->
if (words != previousWords) {
previousWords = words
binding.txtDb.text = words.joinToString(separator = "\r\n")
}
}
}
}
}
}
|
import { expect, test } from "@playwright/test";
import {
LOGIN_DATA,
SAUCE_DEMO_URL,
} from "../../../utils/fixtures/sauce-demo/constants";
import { LoginPage } from "../../../utils/fixtures/sauce-demo/pages/loginPage";
let loginPage;
test("should block images on sauce-demo.com", async ({ page }) => {
loginPage = new LoginPage(page);
await page.route("**/*.{png,jpg,jpeg,svg}", (route) => {
if (route.request().resourceType() === "image") {
route.abort();
} else {
route.continue();
}
});
await page.goto(SAUCE_DEMO_URL);
await loginPage.login(LOGIN_DATA.validUserName, LOGIN_DATA.validPassword);
await expect(page.getByText("Swag Labs")).toBeVisible();
await page.on('pageerror', pageError => {
console.log(`Page errors: "${pageError}"`);
})
await page.on('requestfailed', requestFailed => {
console.log(`Request fails: "${requestFailed.url()}"`);
})
});
|
#include "search_algos.h"
/**
* linear_search - function that searches for a value in an
* array of integers using the Linear search algorithm
* @array: pointer to the first element of the array to search in
* @size: the number of elements in array
* @value: value to search for
*
* Return: Index where the value is found, or -1 if not found
*/
int linear_search(int *array, size_t size, int value)
{
size_t i = 0;
if (array == NULL)
return (-1);
/**for (size_t i = 0; i < size; i++)**/
while (i < size)
{
printf("Value checked array[%lu] = [%d]\n", i, *(array + i));
if (array[i] == value)
return (i);
i++;
}
return (-1);
}
|
const axios = require('axios');
const { Client } = require('@elastic/elasticsearch');
const User = require('../models/userModel');
const config = require('../../config/config');
const client = new Client({ node: config.elasticsearchHost });
const syncEmails = async (userId) => {
try {
const user = await User.findById(userId);
console.log("🚀 ~ file: emailService.js:12 ~ syncEmails ~ user:", user);
if (!user) {
throw new Error('User not found');
}
const response = await axios.get('https://graph.microsoft.com/v1.0/me/mailfolders/inbox/messages', {
headers: {
Authorization: `Bearer ${user.accessToken}`,
},
});
const emails = response.data.value;
console.log("🚀 ~ file: emailService.js:24 ~ syncEmails ~ emails:", emails);
for (const email of emails) {
await client.index({
index: 'emails',
body: {
userId: userId,
emailId: email.id,
subject: email.subject,
from: email.from.emailAddress.address,
receivedDateTime: email.receivedDateTime,
},
});
}
console.log('Emails synchronized successfully');
} catch (error) {
console.error('Error synchronizing emails:', error.message);
}
};
const getEmailsForUser = async (userId) => {
try {
const body = await client.search({
index: 'emails',
body: {
query: {
match: { userId }
}
}
});
console.log("🚀 ~ file: emailService.js:48 ~ getEmailsForUser ~ body:", body)
return body.hits.hits.map(hit => hit._source);
} catch (error) {
console.log("🚀 ~ file: emailService.js:48 ~ getEmailsForUser ~ body:", error);
}
};
module.exports = { syncEmails, getEmailsForUser };
|
import React from "react";
import "./App.css";
import Navigation from "./Navbar/Navigation";
import TweetList from "./Tweets/TweetList";
import Trending from "./Trending/Trending";
import { Container} from "react-bootstrap";
const mockTweets = [
{
id: 1,
avatar:
"https://avatars1.githubusercontent.com/u/53025782?s=400&u=f1ffa8eaccb8545222b7c642532161f11e74a03d&v=4",
author: "John Doe",
twitteruser: "@mr zein",
posttime: "1h",
content: "Just had a great day at the beach! ☀️🏖️ #summertime",
retweet: true,
commentscount: 29,
retweetscount: 8,
likecount: 37,
},
{
id: 2,
avatar:
"https://avatars1.githubusercontent.com/u/53025782?s=400&u=f1ffa8eaccb8545222b7c642532161f11e74a03d&v=4",
author: "Jane Doe",
twitteruser: "@mr zein",
posttime: "2h",
content: "I'm so excited to start my new job at Twitter! 🐦",
retweet: false,
commentscount: 2,
retweetscount: 10,
likecount: 4,
},
// add more mock tweets as needed
];
function App() {
const [tweets] = React.useState(mockTweets);
return (
<Container className="container">
<Navigation />
<TweetList tweets={tweets} />
<Trending />
</Container>
);
}
export default App;
|
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthserviceService } from '../../services/authservice.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
loginForm!: FormGroup;
users: any[] = [];
type: string = 'students';
constructor(
private build: FormBuilder,
private router: Router,
private authService: AuthserviceService
) {}
ngOnInit(): void {
this.createForm();
this.getUsers();
}
createForm() {
this.loginForm = this.build.group({
email: ['', [Validators.email, Validators.required]],
password: ['', [Validators.required]],
type: [this.type],
});
}
getUsers() {
this.authService.getUsers(this.type).subscribe((res: any) => {
this.users = res;
});
}
getRole(event: any) {
this.type = event.value;
this.getUsers();
}
submit() {
let index = this.users.findIndex(
(item) =>
item.email == this.loginForm.value.email &&
item.password == this.loginForm.value.password
);
if (index !== -1) {
const model = {
username: this.users[index].userName,
role: this.type,
userId: this.users[index].id,
};
this.authService.login(model).subscribe((res: any) => {
this.authService.user.next(res);
this.router.navigate(['/subjects']);
});
} else {
alert(' الايميل او كلمه السر غير صحيح');
}
}
}
|
package nottodo.api.config.security.jwt
import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import io.jsonwebtoken.security.Keys
import nottodo.api.config.security.jwt.dto.EmailAndSocialType
import nottodo.persistence.rdb.domain.user.entity.SocialType
import org.springframework.stereotype.Component
import java.nio.charset.StandardCharsets
import java.util.*
@Component
class JwtTokenProvider(
private val jwtProperties: JwtProperties
) {
private val accessSecretKey = Keys.hmacShaKeyFor(jwtProperties.accessSecret.toByteArray(StandardCharsets.UTF_8))
fun generateAccessToken(email: String, socialType: SocialType): String {
val claims = Jwts.claims()
claims["email"] = email
claims["socialType"] = socialType.name
val now = Date()
val expiration = Date(now.time + jwtProperties.accessExpireLength)
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(Date())
.setExpiration(expiration)
.signWith(accessSecretKey, SignatureAlgorithm.HS256)
.compact()
}
fun extractUserFromAccessToken(token: String): EmailAndSocialType {
val claims = extractAllClaimsFromAccessToken(token)
val email = claims.get("email", String::class.java)
val socialType = SocialType.valueOf(claims.get("socialType", String::class.java))
return EmailAndSocialType(email, socialType)
}
private fun extractAllClaimsFromAccessToken(accessToken: String): Claims {
return Jwts.parserBuilder()
.setSigningKey(accessSecretKey)
.build()
.parseClaimsJws(accessToken)
.body
}
}
|
import { CartService } from './../cart/cart.service';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { tap, take } from 'rxjs/operators';
import jwt_decode from 'jwt-decode';
import { BehaviorSubject } from 'rxjs';
import { User } from '../shared/user.model';
export interface IAuthResponse {
token: string;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
configUrl = 'http://localhost:3000';
user = new BehaviorSubject<User>(null);
tokenExpirationTimer: any;
constructor(private http: HttpClient, private router: Router, private cartService: CartService) { }
registerUser(userData: Object) {
return this.http.post<IAuthResponse>(this.configUrl + '/users/register', userData)
.pipe(
tap(resData => {
console.log(resData);
this.handleAuthentication(resData.token);
})
)
}
loginUser(username: string, password: string) {
return this.http.post<IAuthResponse>(this.configUrl + '/users/login', {
username,
password
})
.pipe(
tap(resData => {
console.log(resData);
this.handleAuthentication(resData.token);
})
)
}
autoLogin() {
const token = localStorage.getItem('token');
const tokenExpirationDate = +localStorage.getItem('tokenExpirationDate');
if(!token || !tokenExpirationDate) {
console.log('no token info');
return;
}
const currentTime = Date.now();
if(currentTime > tokenExpirationDate) {
console.log('token expired');
return;
}
const tokenExpiresIn = tokenExpirationDate - Date.now();
console.log(tokenExpiresIn);
const decodedToken: any = jwt_decode(token);
const user = new User(
decodedToken._id,
decodedToken.firstName,
decodedToken.lastName,
decodedToken.city,
decodedToken.address,
decodedToken.postalCode,
decodedToken.email,
decodedToken.username,
// decodedToken.password,
token,
tokenExpirationDate
);
this.user.next(user);
this.autoLogout(tokenExpiresIn);
// this.cartService.initialCart(token);
}
logout() {
this.user.next(null);
localStorage.removeItem('token');
localStorage.removeItem('tokenExpirationDate');
this.router.navigate(['/home']);
if(this.tokenExpirationTimer) {
clearTimeout(this.tokenExpirationTimer);
}
this.tokenExpirationTimer = null;
}
autoLogout(tokenExpiresIn: number) {
this.tokenExpirationTimer = setTimeout(() => {
this.logout();
console.log('auto logout');
}, tokenExpiresIn);
}
private handleAuthentication(token: string) {
const decodedToken: any = jwt_decode(token);
const tokenExpirationDate = Date.now() + decodedToken.tokenExpiresIn * 1000;
const tokenExpiresIn = decodedToken.tokenExpiresIn * 1000;
const user = new User(
decodedToken._id,
decodedToken.firstName,
decodedToken.lastName,
decodedToken.city,
decodedToken.address,
decodedToken.postalCode,
decodedToken.email,
decodedToken.username,
// decodedToken.password,
token,
tokenExpirationDate
);
this.user.next(user);
this.autoLogout(tokenExpiresIn);
localStorage.setItem('token', token);
localStorage.setItem('tokenExpirationDate', JSON.stringify(tokenExpirationDate));
this.router.navigate(['/products']);
}
}
|
package poo.PrimeiraProva;
import java.util.Scanner;
public class SistemaHotelPedro {
static int quartosCriados = 0;
static int idClientesCriados = 0;
static Hotel hotelPedro = new Hotel("Pedro-Hotel", null, null);
public static void main(String[] args) {
Scanner entradaTeclado = new Scanner(System.in);
int opcao = 0;
do {
System.out.println("Menu:");
System.out.println("[1] - Cadastrar quarto");
System.out.println("[2] - Cadastrar cliente");
System.out.println("[3] - Listar Quartos");
System.out.println("[4] - Listar clientes");
System.out.println("[5] - Fazer reserva de quarto");
System.out.println("[6] - Realizar chek-in do hóspede");
System.out.println("[7] - Sair");
System.out.print("Escolha uma opção: ");
opcao = entradaTeclado.nextInt();
switch (opcao) {
case 1:
hotelPedro.setQuartos(cadastrarQuarto());
break;
case 2:
hotelPedro.setClientes(cadastrarCliente(entradaTeclado));
break;
case 3:
listaQuartos(hotelPedro);
break;
case 4:
listaClientes(hotelPedro);
break;
case 5:
reservaQuarto(hotelPedro, entradaTeclado);
break;
case 6:
fazerCheckIn(hotelPedro, entradaTeclado);
break;
case 7:
System.out.println("Saindo...");
default:
System.out.println("Opção inválida. Tente novamente.");
}
} while (opcao != 7);
}
public static void fazerCheckIn(Hotel hotel, Scanner entradaTeclado) {
int idClienteInformado = 0;
System.out.println("\nInforme o id do cliente\n: ");
idClienteInformado = entradaTeclado.nextInt();
for (Quarto item : hotel.getQuartos()) {
if (item.getCliente().getIdCliente() == idClienteInformado){
System.out.println("Este cliente está ospedado no quarto Nº: "+item.getNumQuarto());
}
}
}
public static void reservaQuarto(Hotel hotel, Scanner entradaTeclado) {
int idClienteInformado = 0;
int numQuartoInformado = 0;
System.out.println("Listando clientes cadastrados...");
hotel.listaClientes();
System.out.println("\nInforme o id do cliente\n: ");
idClienteInformado = entradaTeclado.nextInt();
System.out.println("Listando quartos para reserva...");
hotel.listaQuartos();
System.out.println("\n");
System.out.println("Informe o quarto a ser reservado: ");
numQuartoInformado = entradaTeclado.nextInt();
for (Quarto item : hotel.getQuartos()) {
if (item.getNumQuarto() == numQuartoInformado) {
for (Cliente item2 : hotel.getClientes()) {
if (item2.getIdCliente() == idClienteInformado) {
item.setOcupado(true);
item.setCliente(item2);
item2.setQuartoCliente(item);
System.out.println("\n");
}
}
item.infosQuarto();
System.out.println("\n");
}
}
}
public static Quarto cadastrarQuarto() {
quartosCriados += 1;
Quarto novoQuarto = new Quarto(quartosCriados, false, new Cliente(null, null, null, 0));
System.out.println("quarto numero: " + quartosCriados + "º criado com sucesso");
return novoQuarto;
}
public static void listaQuartos(Hotel hotel) {
hotel.listaQuartos();
}
public static void listaClientes(Hotel hotel) {
hotel.listaClientes();
}
public static Cliente cadastrarCliente(Scanner entradaTeclado) {
idClientesCriados += 1;
Cliente novoCliente = new Cliente(null, null, null, null);
novoCliente.setIdCliente(idClientesCriados);
System.out.println("Informe o nome do cliente: ");
novoCliente.setNome(entradaTeclado.next());
System.out.println("Informe o cpf do cliente: ");
novoCliente.setCpf(entradaTeclado.next());
novoCliente.clienteCriado();
return novoCliente;
}
}
|
const puppeteer = require('puppeteer');
const cheerio = require('cheerio');
const fs = require('fs');
require("dotenv").config();
// Log in to LinkedIn
async function login(page) {
await page.goto('https://www.linkedin.com/login');
await page.waitForSelector('#username');
// Enter the user's email address and password
await page.type('#username', process.env.EMAIL);
await page.type('#password', process.env.PASSWORD);
// Click the login button
await page.click('button[type="submit"]');
// Wait for the login process to complete
await page.waitForNavigation();
// Pause execution and wait for manual security checks
console.log('Please complete any necessary security checks manually.');
await new Promise((resolve) => setTimeout(resolve, 15000)); // Wait for 15 seconds
}
async function scrapeLinkedInProfile(html, urlToScrape) {
try {
// Use Cheerio to parse the HTML and extract the desired data
const $ = cheerio.load(html);
const linkedInUrl = urlToScrape;
// Extract name, connections count, description, location, experience, education, skills, and recent posts from the profile
const name = $('.text-heading-xlarge').text().trim();
const description = $('.text-body-medium').text().trim();
// Extract connections count
const connectionsElement = $('li.text-body-small').last();
let connections = connectionsElement.text().trim();
//remove connections from the string
connections = connections.replace('connections', '').trim();
// Extract Location
const locationElement = $('span.text-body-small.inline.t-black--light.break-words');
const location = locationElement.text().trim();
// Extract the professional experiences
const experience = [];
const experienceSection = $('section').find('div#experience').parent();
experienceSection.find('.pvs-entity--padded').each((index, element) => {
const jobTitle = $(element).find('.t-bold').find('[aria-hidden="true"]').first().text().trim();
// Extract company and job type from the combined string
const combinedText = $(element).find('.t-14.t-normal').find('[aria-hidden="true"]').first().text().trim();
const regex = /^(.+) · (.+)$/; // Regular expression to separate company and job type
//if . not present in the regex then it set company as whole string
if (combinedText.includes('·')) {
var match = combinedText.match(regex);
var company = match ? match[1] : '';
var jobType = match ? match[2] : '';
}
else {
var company = combinedText;
var jobType = '';
}
// Extract the job description
const jobDescriptionElement = $(element).find('.pv-shared-text-with-see-more');
let jobDescription = jobDescriptionElement.find('.inline-show-more-text').find('span.visually-hidden').first().text().trim();
//if jobDescription starts with Skills then it is not a jobDescription
if (jobDescription.startsWith('Skills')) {
jobDescription = '';
}
// Remove the "see more" button text
const seeMoreText = jobDescriptionElement.find('.inline-show-more-text__button').text().trim();
jobDescription = jobDescription.replace(seeMoreText, '');
// Remove unnecessary newlines and extra whitespaces with new lines
jobDescription = jobDescription.replace(/\n/g, ', ');
// Extract the skills
const skills = [];
const skillElement = $(element).find('.pv-shared-text-with-see-more');
let skill = skillElement.find('.inline-show-more-text').find('span.visually-hidden').last().text().trim();
if (skill.startsWith('Skills:')) {
skill = skill.replace('Skills:', '').trim();
skill = skill.split('·');
skill.forEach(element => {
skills.push(element.trim());
}
);
}
// Extract the duration
const durationString = $(element).find('.t-14.t-normal.t-black--light').find('[aria-hidden="true"]').first().text().trim();
const [startDateString, endDateAndDuration] = durationString.split(" - ");
// Check if endDateAndDuration exists and is not undefined
let [endDateString, durationText] = endDateAndDuration ? endDateAndDuration.split(" · ") : ['', ''];
// Check if the end date is "Present"
const isPresent = endDateString && endDateString.includes("Present");
if (isPresent) {
// Replace "Present" with the current date in the format "Month Year"
const currentDate = new Date();
const currentMonth = currentDate.toLocaleString("default", { month: "short" });
const currentYear = currentDate.getFullYear();
endDateString = `${currentMonth} ${currentYear}`;
}
// Convert start and end dates to date strings in the format day/month/year
const startDateParts = startDateString.trim().split(" ");
const startMonth = startDateParts[0];
const startYear = parseInt(startDateParts[1], 10);
let startDate = new Date(startYear, new Date(Date.parse(`${startMonth} 1, ${startYear}`)).getMonth(), 1);
const endDateParts = endDateString && endDateString.trim().split(" ");
const endMonth = endDateParts ? endDateParts[0] : '';
const endYear = endDateParts ? parseInt(endDateParts[1], 10) : '';
const lastDayOfMonth = new Date(endYear, new Date(Date.parse(`${endMonth} 1, ${endYear}`)).getMonth() + 1, 0).getDate();
let endDate = endMonth && endYear ? new Date(endYear, new Date(Date.parse(`${endMonth} 1, ${endYear}`)).getMonth(), lastDayOfMonth) : '';
if (startDate) {
startDate = startDate.toLocaleString().split(',')[0];
}
if (endDate) {
endDate = endDate.toLocaleString().split(',')[0];
}
const durationRegex = /(\d+)\s*mos/i;
const durationInMonths = durationText.match(durationRegex) ? parseInt(durationText.match(durationRegex)[1]) : 0;
const location = $(element).find('.t-14.t-normal.t-black--light').eq(1).find('[aria-hidden="true"]').first().text().trim();
const companyUrl = $(element).find('a.optional-action-target-wrapper').first().attr('href');
if (isPresent) {
endDate = 'Present';
}
experience.push({ jobTitle, company, jobType, jobDescription, skills, startDate, endDate, durationInMonths, location, companyUrl });
});
// Extract the education details
const education = [];
// Find the section with id="education"
const educationSection = $('section').find('div#education').parent();
educationSection.find('.pvs-entity--padded').each((index, element) => {
const institutionElement = $(element).find('.t-14.t-normal').find('[aria-hidden="true"]').first();
const institution = $(element).find('.t-bold').find('[aria-hidden="true"]').first().text().trim();
const institutionLink = institutionElement.closest('a').attr('href');
const degreeElement = $(element).find('.t-14.t-normal').find('[aria-hidden="true"]').first();
const degree = degreeElement.text().trim();
const duration = $(element).find('.t-14.t-normal.t-black--light').find('[aria-hidden="true"]').first().text().trim();
const [startYear, endYear] = duration.split(" - ");
education.push({ institution, institutionLink, degree, startYear, endYear });
});
// Extract the skills
const skillsSection = $('section').find('div#skills').parent();
const skills = [];
skillsSection.find('.pvs-list__item--one-column').each((index, element) => {
const skillTopic = $(element).find('.t-bold').find('[aria-hidden="true"]').text().trim();
if (skillTopic.length > 0) {
skills.push(skillTopic);
}
});
// Extract the about
const aboutSection = $('section').find('div#about').parent();
const aboutElement = aboutSection.find('.pv-shared-text-with-see-more');
let about = aboutElement.text().trim();
// Remove the "see more" button text
const seeMoreText = aboutElement.find('.inline-show-more-text__button').text().trim();
about = about.replace(seeMoreText, '');
// Remove unnecessary newlines and extra whitespaces with new lines
about = about.replace(/\n\s+/g, ' ');
// Extract the recent posts
const content_collectionsSection = $('section').find('div#content_collections').parent();
const recentPosts = [];
content_collectionsSection.find('.profile-creator-shared-feed-update__mini-container').each((index, element) => {
const postLink = $(element).find('a[aria-label^="View full post."]').attr('href');
let postContent = $(element).find('.inline-show-more-text').text().trim().replace(/\n\s+/g, ' ').trim();
postContent = postContent.replace('…show more', ''); // Remove the "…show more" part
recentPosts.push({
link: postLink,
content: postContent,
});
});
// Format the data into an object
const profileData = {
name,
linkedInUrl,
description,
connections,
location,
about,
professionalExperience: experience,
education,
skills,
recentPosts,
};
return profileData;
} catch (error) {
console.error('Error occurred while scraping the page:', error);
return null;
}
}
async function performLinkedInScraping(page, urlToScrape) {
//Uncomment the below line if you want to login to LinkedIn without using cookies and comment the above code
// await login(page);
// Navigate to the URL
await page.goto(urlToScrape, { waitUntil: 'domcontentloaded' });
// Wait for any lazy-loaded content to load (if applicable)
await page.waitForTimeout(2000);
// Get the whole HTML data of the page
const html = await page.content();
try {
const profileData = await scrapeLinkedInProfile(html, urlToScrape);
// Save as JSON file
if (!fs.existsSync('Output')) {
fs.mkdirSync('Output');
}
// fs.writeFile('Output/profileData.json', JSON.stringify(profileData, null, 2), (err) => {
// if (err) {
// console.error('Error saving data to profileData.json:', err);
// } else {
// console.log('Data saved to profileData.json!');
// }
// });
return profileData;
} catch (error) {
console.error(error.message);
}
}
module.exports = {
performLinkedInScraping
}
|
/*
* Covid19-Simple-Graphs
* Copyright (C) 2020 aleskandro
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Injectable } from '@angular/core';
import * as Papa from 'papaparse';
import { Line } from './models/line';
import { PackedData } from './models/packed-data';
import { LocationModel } from './models/location';
// const confirmedUrl = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv";
const confirmedUrl = ' https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv';
// const deathsUrl = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv";
const deathsUrl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv';
// const recoveredUrl ="https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv";
const recoveredUrl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/0bba23f925700fe934849e6d27a4da295ee58419/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv';
const italyPcUrl = 'https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv';
@Injectable({
providedIn: 'root'
})
export class CsvPollerService {
time: string[];
confirmed: Line[];
deaths: Line[];
recovered: Line[];
statesCountries: Map<string, string[]>;
initialized = false;
initCounter = 2;
constructor() {
this.time = new Array<string>();
this.confirmed = new Array<Line>();
this.deaths = new Array<Line>();
this.recovered = new Array<Line>();
this.parse(confirmedUrl, 'confirmed');
this.parse(recoveredUrl, 'recovered');
this.parse(deathsUrl, 'deaths');
}
parseItaly() {
const stateMapsConf = new Map<string, Line>();
const stateMapsDeaths = new Map<string, Line>();
const stateMapsRec = new Map<string, Line>();
const raw = new Map<string, any>();
const comparator = (a, b) => {
if (a.t < b.t) {
return -1;
}
if (a.t > b.t) {
return 1;
}
return 0;
};
const f = (v, i, a) => v.country !== 'Italy';
Papa.parse(italyPcUrl, {
header: true,
skipEmptyLines: true,
download: true,
dynamicTyping: true,
complete: (result) => {
result.data.forEach((e) => {
const state = e.denominazione_regione;
if (!raw.has(state)) {
raw.set(state, []);
stateMapsConf.set(state, new Line(
'Italy', state, 0, 0,
new Array(33).fill(0)));
stateMapsRec.set(state, new Line(
'Italy', state, 0, 0,
new Array(33).fill(0)));
stateMapsDeaths.set(state, new Line(
'Italy', state, 0, 0,
new Array(33).fill(0)));
}
raw.get(state).push({
t: e.data,
confirmed: e.totale_casi,
deaths: e.deceduti,
recovered: e.dimessi_guariti
});
});
this.confirmed = this.confirmed.filter(f);
this.deaths = this.deaths.filter(f);
this.recovered = this.recovered.filter(f);
Array.from(raw.keys()).forEach(k => {
raw.get(k).sort(comparator);
raw.get(k).forEach((e, i) => {
stateMapsConf.get(k)
.data.push(e.confirmed);
stateMapsDeaths.get(k)
.data.push(e.deaths);
stateMapsRec.get(k)
.data.push(e.recovered);
});
this.confirmed.push(stateMapsConf.get(k));
this.deaths.push(stateMapsDeaths.get(k));
this.recovered.push(stateMapsRec.get(k));
});
this._setStatesCountries();
this.initialized = true;
}
});
}
parse(url: string, key: string) {
Papa.parse(url, {
header: true,
skipEmptyLines: true,
download: true,
dynamicTyping: true,
complete: (result) => {
const time = result.meta.fields.slice(4);
result.data.forEach((e) => {
const ts = [];
time.forEach((t) => {
ts.push(e[t]);
});
this[key].push(new Line(
e.country, e.state,
e.lat, e.long,
ts
));
});
if (!this.initialized) {
if (this.initCounter <= 0) {
this.time = time;
this.parseItaly();
} else {
this.initCounter--;
}
}
},
transformHeader: (header) => {
if (header === 'Province/State') {
return 'state';
}
if (header === 'Country/Region') {
return 'country';
}
if (header.split('/').length == 3) {
const t = header.split('/');
return '20' + t[2] +
('0' + t[0]).slice(-2) +
('0' + t[1]).slice(-2);
}
return header;
}
});
}
noopReducer = o => true;
sumReducer = (cur, ret) => {
for (let i = 0; i < ret.data.length; i++) {
ret.data[i] += cur.data[i];
}
return ret;
}
getStateData(country: string, state: string, displacement: number) {
const filter = o => o.state == state && o.country == country;
return this._getData(country, state, filter, this.noopReducer, displacement);
}
getCountryData(country: String, displacement: number) {
const filter = o => o.country == country;
return this._getData(country, null, filter, this.sumReducer, displacement);
}
getWorldData(displacement: number) {
return this._getData('World', null, this.noopReducer, this.sumReducer, displacement);
}
_getData(country: String, state: String, filter, reducer, displacement: number) {
const c = JSON.parse(JSON.stringify(this.confirmed)).filter(filter).reduce(reducer);
const d = JSON.parse(JSON.stringify(this.deaths)).filter(filter).reduce(reducer);
const r = JSON.parse(JSON.stringify(this.recovered)).filter(filter).reduce(reducer);
c.country = country;
c.state = state;
c.data = this._displace(c.data, displacement);
d.country = country;
d.state = state;
d.data = this._displace(d.data, displacement);
r.country = country;
r.state = state;
r.data = this._displace(r.data, displacement);
this._filterNaN(c.data);
this._filterNaN(d.data);
this._filterNaN(r.data);
const ret = new PackedData(c, r, d, this.time);
return ret;
}
_filterNaN(a) {
if (isNaN(a[a.length - 1])) {
a.splice(-1);
}
}
_displace(a, displacement) {
if (displacement > 0) {
const d = displacement;
return (new Array(d).fill(0)).concat(a).slice(0, -d);
} else {
const d = -displacement;
return a.concat((new Array(d).fill(a[a.length - 1]))).slice(d);
}
}
_setStatesCountries() {
const hmap = new Map<string, string[]>();
this.confirmed
.forEach(
(e) => {
if (e.state === null && !hmap.has(e.country)) {
hmap.set(e.country, []);
} else {
if (hmap.has(e.country)) {
hmap.get(e.country).push(e.state);
}
else {
hmap.set(e.country, [e.state]);
}
}
}
);
this.statesCountries = hmap;
}
getCountries() {
return Array.from(this.statesCountries.keys());
}
getStatesOfCountry(country: string) {
return this.statesCountries.get(country);
}
}
|
interface TextInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
name: string;
label?: string;
}
const TextInput = (props: TextInputProps) => {
const { label, name, ...rest } = props;
return (
<div className="flex flex-col">
{label ?? <label htmlFor={name}>{label}</label>}
<input name={name} {...rest} className="form-field" />
</div>
);
};
export default TextInput;
|
import {
Image,
ImageSourcePropType,
StyleProp,
Text,
TouchableHighlight,
View,
ViewStyle,
} from 'react-native';
import {commonstyle} from '../../../styles/common-style';
import {ImagePathMain} from '../../../utils/ImagePath';
import * as React from 'react';
import {commoncolor} from '../../../styles/common-color';
import {RouterScreen} from '../../../router';
interface MainTabItemProps {
type: RouterScreen;
isCheck: boolean;
}
class MainTabItemState {
icon: ImageSourcePropType = ImagePathMain.image_tab_home_grey;
text: string = '首页';
}
const MainTabItemView = (props: MainTabItemProps) => {
const [itemState, setItemState] = React.useState(new MainTabItemState());
React.useEffect(() => {
let status: MainTabItemState = new MainTabItemState();
switch (props.type) {
case RouterScreen.HOME:
status.icon = props.isCheck
? ImagePathMain.image_tab_home_light
: ImagePathMain.image_tab_home_grey;
status.text = '首页';
break;
case RouterScreen.PROFILE:
status.icon = props.isCheck
? ImagePathMain.image_tab_profile_light
: ImagePathMain.image_tab_profile_grey;
status.text = '看点';
break;
case RouterScreen.MINE:
status.icon = props.isCheck
? ImagePathMain.image_tab_mine_light
: ImagePathMain.image_tab_mine_grey;
status.text = '我的';
break;
}
setItemState(status);
}, [props.isCheck, props.type]);
return (
<View
style={[commonstyle.flex_v, commonstyle.flex_center, commonstyle.flex_1]}>
<Image source={itemState.icon} style={[commonstyle.image_wh_tab]} />
<Text
style={[
commonstyle.font_size_body_min,
commonstyle.font_color_8a8a8a,
props.isCheck
? commonstyle.font_color_main
: commonstyle.font_color_8a8a8a,
]}>
{itemState.text}
</Text>
</View>
);
};
interface MainTabProps {
style: StyleProp<ViewStyle> | undefined;
onClickTab: (page: RouterScreen) => void;
}
const MainTabView = (_props: MainTabProps) => {
const [mainTabList] = React.useState([
{type: RouterScreen.HOME, isCheck: true},
{type: RouterScreen.PROFILE, isCheck: false},
{type: RouterScreen.MINE, isCheck: false},
]);
const [currentPage, setCurrentPage] = React.useState(RouterScreen.HOME);
const itemClick = (item: MainTabItemProps, index: number) => {
if (currentPage === item.type) {
return;
}
setCurrentPage(item.type);
mainTabList.forEach(value => {
value.isCheck = false;
});
mainTabList[index].isCheck = true;
_props.onClickTab(item.type);
};
const getMainTabListView = mainTabList.map((item, index) => {
return (
<TouchableHighlight
underlayColor={commoncolor.white}
style={[commonstyle.flex_1]}
key={item.type}
onPress={() => itemClick(item, index)}>
<MainTabItemView type={item.type} isCheck={item.isCheck} />
</TouchableHighlight>
);
});
return (
<View
style={[
commonstyle.height_main_tab,
commonstyle.width_100,
commonstyle.background_white,
commonstyle.flex_h,
]}>
{getMainTabListView}
</View>
);
};
export default MainTabView;
|
<div class="mx-4 grid mt-5">
<div class="col-12 sm:col-12 md:col-12 lg:col-9 xl:col-9">
<p-card header="Listado de Gastos" styleClass="p-2">
<p-table [value]="gastos" [paginator]="true" [rows]="5" [showCurrentPageReport]="true" [scrollable]="true"
scrollHeight="flex" [tableStyle]="{ 'min-width': '50rem' }"
currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} registros."
[rowsPerPageOptions]="[5, 8, 12, 16]"
styleClass="p-datatable-lg">
<ng-template pTemplate="header">
<tr>
<th>Descripción</th>
<th>Monto</th>
<th>Tipo Saldo</th>
<th>
<gasto-add-component [tipoGastos]="tipoGastos"
(onIsGastoAdd)="getIsGastoAdd( $event )"></gasto-add-component>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-gasto>
<tr>
<td>{{ gasto.descripcion }}</td>
<td>{{ gasto.monto | currency:"$ "}}</td>
<td>{{ gasto.tipoGasto.descripcion }}</td>
<td>
<button pButton pRipple icon="pi pi-trash" (click)="onDeleteSaldo(gasto.id)"
class="p-button-raised p-button-danger mr-2"></button>
<gasto-update-component [tipoGastos]="tipoGastos"
(onIsGastoUpdate)="getIsSaldoUpdate( $event )" [gasto]="gasto"></gasto-update-component>
</td>
</tr>
</ng-template>
</p-table>
</p-card>
<!-- manejo de mensajes para eliminar.-->
<p-toast></p-toast>
<p-confirmDialog [style]="{width: '50vw'}"></p-confirmDialog>
</div>
<div class="col-12 sm:col-12 md:col-12 lg:col-3 xl:col-3">
<div class="grid">
<div class="col-12">
<p-card header="Saldo Actual">
<p class="m-0 text-5xl text-center">
<span class="font-bold">{{ 20232.434 | currency:"$ "}}</span>
</p>
</p-card>
</div>
<div class="col-12">
<p-card header="Gasto Total">
<p class="m-0 text-5xl text-center">
<span class="font-bold">{{ 20232.434 | currency:"$ "}}</span>
</p>
</p-card>
</div>
</div>
</div>
</div>
|
const Agents = require("../models/Agent");
const Redeem = require("../models/Redeem");
const User = require("../models/User");
const UserSpendTransactionHistory = require("../models/UserSpendTransactionHistory");
const ApiFeatures = require("../utils/ApiFeatures");
const { giveresponse, asyncHandler } = require("../utils/res_help");
const App = require("../models/App");
const Agent = require("../models/Agent");
const HostLiveStreamTrack = require("../models/HostLiveStreamTrack");
const NotificationPackagename = require("../models/NotificationPackagename");
const moment = require("moment-timezone");
const { ObjectId } = require("mongodb");
exports.getRedeemById = asyncHandler(async (req, res, next) => {
const redeem = await Redeem.findOne({ _id: req.body._id }).populate("user");
const app = App.findOne();
if (!redeem) giveresponse(res, 404, false, "Redeem not found");
redeem.total_amount = redeem.diamond * app.amount_per_diamond;
return giveresponse(res, 200, true, "Redeem detail get success", redeem);
});
exports.fetchRedeems = asyncHandler(async (req, res, next) => {
const { request_status } = req.body;
const apiFeature = new ApiFeatures(Redeem.find({ request_status: request_status }).populate({ path: "user", select: "fullName" }), req.body).search().sort().pagination();
const redeems = await apiFeature.query;
apiFeature.totalRecord = await Redeem.countDocuments({ request_status: request_status });
const result = await App.findOne({ type: 1 }).select("amount_per_diamond");
return giveresponse(res, 200, true, "Rejected Redeems get success.", { totalRecord: apiFeature.totalRecord, totalPage: apiFeature.totalPage, redeems, amount_per_diamond: result.amount_per_diamond });
});
exports.fetchAllRedeems = asyncHandler(async (req, res, next) => {
const { agent_id, request_status } = req.body;
let query = { request_status: request_status || 0 };
if (request_status == 0) {
const agent = await Agent.find();
const agentHost = await User.find({ agent_id: agent_id ? agent_id : agent[0]?._id, is_block: 0 })
.sort({ _id: "desc" })
.select("_id");
const userIdsArray = agentHost.map((user) => user._id);
query.user_id = { $in: userIdsArray };
}
const apiFeature = new ApiFeatures(Redeem.find(query).populate({ path: "user", select: "fullName" }), req.body?.options).search().sort().pagination();
const redeemData = await apiFeature.query;
apiFeature.totalRecord = await Redeem.countDocuments(query);
const data = [];
for (const redeem of redeemData) {
let pay_amount = 0;
try {
pay_amount = (redeem.diamond / redeem.coins) * redeem.coins_rate;
} catch (e) {
pay_amount = 0;
}
const Stream_Payable = redeem.stream_days * redeem.stream_rate;
const final_amount = Math.round(pay_amount) + Stream_Payable;
data.push({ fullName: redeem.user?.fullName, package_name: redeem.package_name, stream_days: redeem.stream_days, stream_payable: Stream_Payable, coin: redeem.diamond, coin_payable: Math.round(pay_amount), final_amount });
}
return giveresponse(res, 200, true, "redeems fetch success", { data: request_status == 0 ? data : redeemData, totalRecord: apiFeature.totalRecord, totalPage: apiFeature.totalPage });
});
exports.rejectRedeem = asyncHandler(async (req, res, next) => {
const redeem = await Redeem.updateOne({ _id: req.body._id }, { $set: { request_status: 2 } }, { new: true });
if (!redeem) return giveresponse(res, 404, false, "Redeem request not found");
const user_diomand = await User.findOne({ _id: redeem.user_id }).select("diamond");
const diomand = user_diomand.diamond + redeem.diamond;
const result = await User.updateOne({ _id: redeem.user_id }, { diamond: diomand });
if (result) return giveresponse(res, 200, true, "Reject redeem success.", redeem.user_id);
});
exports.completeRedeem = asyncHandler(async (req, res, next) => {
const result = await Redeem.updateOne({ _id: req.body._id }, { $set: { amount_paid: req.body.amount_paid, request_status: 1, completed_at: new Date() } });
return giveresponse(res, 200, true, "amount request approved");
});
//------------------------- android api route ------------------
exports.fetchRedeemRequests = asyncHandler(async (req, res, next) => {
const { user_id, start, limit } = req.body;
const user = await User.findOne({ _id: user_id });
if (!user) return giveresponse(res, 404, false, "User doesn't exist!");
const redeem = await Redeem.find({ user_id: user_id }).sort({ _id: -1 }).skip(parseInt(start)).limit(parseInt(limit));
return giveresponse(res, 200, true, "Redeem Request get successfully!", redeem);
});
exports.placeRedeemRequest = asyncHandler(async (req, res, next) => {
placeRedeem(req, res);
return giveresponse(res, 200, true, "Redeem Request added successfully!");
});
exports.placeRedeemRequestAll = asyncHandler(async (req, res, next) => {
const agents = await Agents.find({ status: 1, is_deleted: 0 });
for (const agent of agents) {
const hosts = await User.find({ agent_id: agent._id, is_host: 2, is_block: 0 });
for (const host of hosts) {
const hostStatus = await UserSpendTransactionHistory.countDocuments({ received_by: host._id, type: 2, createdAt: { $gt: moment().subtract(14, "days").toDate() } });
if (hostStatus > 0) {
(req.body.user_id = host._id), (req.body.account_info = "1"), (req.body.payment_getway_title = "1"), (req.body.agent_id = agent._id), await placeRedeem(req, res);
} else {
await User.findOneAndUpdate({ _id: host._id }, { is_block: 1 }, { new: true });
}
}
}
return giveresponse(res, 200, true, "Reedem Request processed successfully!");
});
const placeRedeem = asyncHandler(async (req, res) => {
const { user_id, account_info, payment_getway_title, agent_id, diamond } = req.body;
const user = await User.findOne({ _id: user_id });
if (!user) return giveresponse(res, 404, false, "User doesn't exist");
const packageNames = await NotificationPackagename.find();
let itrate = 0;
for (const package of packageNames) {
const DaysAgo = moment().subtract(15, "days");
// redeem means to convert diamond worth into cash
const dimnodRedeem = await UserSpendTransactionHistory.aggregate([{ $match: { received_by: new ObjectId(user_id), package_name: package.package_name, host_paided: 1, createdAt: { $lte: DaysAgo.toDate() } } }, { $group: { _id: null, diamond: { $sum: "$diamond" } } }]);
await UserSpendTransactionHistory.updateMany({ received_by: user_id, package_name: package.package_name, host_paided: 1, createdAt: { $lte: DaysAgo.toDate() } }, { $set: { host_paided: 2 } });
if (itrate === 0) {
itrate = 1;
const agents = await Agents.findOne({ _id: agent_id });
const stream_minits = agents.stream_minits;
const stream_rate = agents.stream_rate;
const coins = agents.coins;
const coins_rate = agents.coins_rate;
const streamTracks = await HostLiveStreamTrack.aggregate([{ $match: { host_id: user_id, start: { $gte: DaysAgo.toDate() } } }, { $group: { _id: { host_id: "$host_id", date: { $dateToString: { format: "%Y-%m-%d", date: "$start" } } }, count: { $sum: 1 }, time_diff: { $sum: { $divide: [{ $subtract: ["$end", "$start"] }, 60000] } } } }, { $match: { time_diff: { $gt: stream_minits * 60 } } }]);
const myRandomString = "DIM" + Math.random().toString(36).substring(7).toUpperCase();
const redeem = new Redeem({ user_id, account_info, diamond: dimnodRedeem[0]?.diamond || 0, payment_getway_title, redeem_token: myRandomString, stream_days: streamTracks.length, stream_minits, stream_rate, coins, coins_rate, package_name: package.package_name });
await redeem.save();
} else {
const myRandomString = "DIM" + Math.random().toString(36).substring(7).toUpperCase();
const redeem = new Redeem({ user_id, account_info, diamond: dimnodRedeem[0]?.diamond || 0, payment_getway_title, redeem_token: myRandomString, package_name: package.package_name });
await redeem.save();
}
if (user.diamond < diamond) return giveresponse(res, 400, false, "Insufficient balance to redeem!");
user.diamond -= dimnodRedeem[0]?.diamond || 0;
await user.save();
}
});
|
import numpy as np
import matplotlib.pyplot as plt
def simpleaxis(ax):
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
omega_0 = 100
def draw_pulse(S, scale_type='time'):
"""
Draw field pulse.
.. image:: https://placekitten.com/200/139
:param S:
:param frame_id:
:param scale_type:
:return:
"""
# def delta(t):
# delta = np.ones_like(t)
# if scale_type == 'time':
# delta[t/S < 0.4] = 0
# delta[t/S > 0.6] = 2
# return delta * 120
# elif scale_type == 'value':
# delta[t < 0.4] = 0
# delta[t > 0.6] = 2
# return S * delta * 120
def phaseshift(t):
pt = np.zeros_like(t)
slope = 70
if scale_type == 'time':
mask = np.logical_and(t/S > 0, t/S < 0.4)
pt[mask] = t[mask]/S*slope
mask = np.logical_and(t/S >= 0.4, t/S < 0.6)
pt[mask] = 0.4*slope
mask = np.logical_and(t/S >= 0.6, t/S < 1)
pt[mask] = 0.4*slope - (t[mask]/S - 0.6)*slope
else:
mask = np.logical_and(t > 0, t < 0.4)
pt[mask] = t[mask]*slope
mask = np.logical_and(t >= 0.4, t < 0.6)
pt[mask] = 0.4*slope
mask = np.logical_and(t >= 0.6, t < 1)
pt[mask] = 0.4*slope - (t[mask] - 0.6)*slope
return pt
# def E(t):
# return 1 + 0.1*t
def E(t):
if scale_type == 'time':
return gaussian(t/S, 0.5, 0.15)
elif scale_type == 'value':
return S * gaussian(t, 0.5, 0.15)
ts = np.linspace(0, 1.5, 5000)
dt = ts[1] - ts[0]
phase = 0
phases = []
# phaseshifts = []
# for i in range(ts.shape[0]):
# phase = omega_0*dt + phaseshift(ts[i])
# phases.append(phase)
# # phaseshifts.append(phase - omega)
# phases = np.array(phases)
phases = omega_0*ts + phaseshift(ts)
signal = E(ts) * np.sin(phases)
return ts, signal, E(ts), phaseshift(ts)
# plt.show()
figsizefactor = 0.8
fig, axarr = plt.subplots(2, 1, gridspec_kw={'height_ratios': [2, 1]}, sharex=True, figsize=(11*figsizefactor,4.7*figsizefactor))
def add_plots(S = 1.5, color = 'C0', scale_type='time', label=None):
ts, signal, Es, phaseshifts = draw_pulse(S, scale_type=scale_type)
ax = axarr[0]
# ax.set_title(f'Scale factor: {S:.3f}')
ax.plot(ts, signal, color=color, alpha=0.5, label=label)
ax.plot(ts, Es, '--', color=color)
ax.set_ylabel('Field strength\n, a.u.')
ax.set_ylim(-1.6, 1.6)
# ax.legend()
ax = axarr[1]
if scale_type == 'time':
ax.plot(ts, phaseshifts, color=color, linewidth=2 if color == 'black' else 2,
zorder=10 if color == 'black' else 5,
alpha=1 if color == 'black' else 0.7)
else:
ax.plot(ts, phaseshifts, color=color, linewidth=2 if color == 'black' else 6,
zorder=10 if color == 'black' else 5,
alpha=1 if color == 'black' else 0.7)
add_plots(S=1, color='black', scale_type='time', label='Input pulse')
add_plots(S=1.5, color='C0', scale_type='time')
add_plots(S=1.5, color='C2', scale_type='value')
ax = axarr[1]
ax.set_xlabel('Time, a.u.')
ax.set_ylabel('Phase shift,\n rad.')
ax.set_ylim(0, 33)
ax.set_xlim(0, 1.55)
for ax in axarr:
simpleaxis(ax)
axarr[0].spines['bottom'].set_visible(False)
axarr[0].tick_params(bottom=False)
# axarr[0].legend()
plt.tight_layout()
fig.savefig('tests/qubits/figures/for_si_figure_noborders.png', dpi=300)
plt.show()
# fig.savefig(f'tests/qubits/figures/frames_{scale_type}/{frame_id:08d}.png', dpi=300)
# plt.close(fig)
# # def delta(t):
# # return 600*t**2
# for frame, S in enumerate(np.linspace(1,1.5, 100)):
# print(f'Rendering frame {frame}')
# draw_pulse(S, frame, scale_type='time')
|
import React, { useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { useNavigate } from "react-router-dom";
import { Link } from "react-router-dom";
import { auth, sendPasswordReset } from "../../Firebase/Config";
import "./Reset.css";
function Reset() {
const [email, setEmail] = useState("");
const [user, loading, error] = useAuthState(auth);
const navigate = useNavigate();
useEffect(() => {
if (loading) return;
if (user) return;
}, [user, loading]);
// conditionally render "Register" and "Login" divs
const renderAuthLinks = () => {
if (!user) {
return (
<>
<div>
Don't have an account? <Link to="/register">Register</Link> now.
</div>
<div>
Or, try <Link to="/">logging in</Link>.
</div>
</>
);
}
return null;
};
return (
<div className="reset">
<div className="reset__container">
<input
type="text"
className="reset__textBox"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="E-mail Address"
/>
<button
className="reset__btn"
onClick={() => sendPasswordReset(email)}
>
Send password reset email
</button>
{renderAuthLinks()}
</div>
</div>
);
}
export default Reset;
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router'; // Import RouterModule and Routes
import { Assignment1Component } from './assignment1/assignment1.component';
import { Assignment2Component } from './assignment2/assignment2.component';
import { CountriesComponent } from './countries/countries.component';
import { LoginComponent } from './login/login.component';
import { SignupComponent } from './signup/signup.component';
import { ContactlistComponent } from './contactlist/contactlist.component';
import { Q1Component } from './questions/q1/q1.component';
import { Q2Component } from './questions/q2/q2.component';
import { Q3Component } from './questions/q3/q3.component';
import { Q4Component } from './questions/q4/q4.component';
import { Q5Component } from './questions/q5/q5.component';
import { Q6Component } from './questions/q6/q6.component';
import { Q7Component } from './questions/q7/q7.component';
import { Q8Component } from './questions/q8/q8.component';
import { Q9Component } from './questions/q9/q9.component';
const routes: Routes = [
{ path: 'assignment1', component: Assignment1Component },
{ path: 'assignment2', component: Assignment2Component },
{ path: 'countries', component: CountriesComponent },
{ path: '', redirectTo: 'assignment1', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'contactlist', component: ContactlistComponent },
{ path: 'assignment1/q1', component: Q1Component },
{ path: 'assignment1/q2', component: Q2Component },
{ path: 'assignment1/q3', component: Q3Component },
{ path: 'assignment1/q4', component: Q4Component },
{ path: 'assignment1/q5', component: Q5Component },
{ path: 'assignment1/q6', component: Q6Component },
{ path: 'assignment1/q7', component: Q7Component },
{ path: 'assignment1/q8', component: Q8Component },
{ path: 'assignment1/q9', component: Q9Component },
{ path: 'assignment2/part1', component: CountriesComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)], // Use RouterModule.forRoot() to configure your routes
exports: [RouterModule], // Export RouterModule for use in other parts of your application
})
export class AppRoutingModule { }
|
import { IsEmail, IsEnum, IsString } from "class-validator";
import { Role } from "../enum/role.enum";
import { ApiProperty } from "@nestjs/swagger";
export class UserSignin {
@ApiProperty({ default: '[email protected]' })
@IsEmail()
email: string;
@ApiProperty({ default: 'test' })
@IsString()
password: string;
}
export class UserSignup {
@ApiProperty({ default: '[email protected]' })
@IsEmail()
email: string;
@ApiProperty({ default: 'test' })
@IsString()
password: string;
@ApiProperty({ default: 'abc user'})
@IsString()
username: string;
@ApiProperty({default: 'admin'})
@IsEnum(Role)
role: Role;
}
|
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package uk.co.inhealthcare.open.itk.transport.HTTP;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import uk.co.inhealthcare.open.itk.infrastructure.ITKCommsException;
import uk.co.inhealthcare.open.itk.infrastructure.ITKMessagingException;
import uk.co.inhealthcare.open.itk.infrastructure.ITKTransportTimeoutException;
import uk.co.inhealthcare.open.itk.infrastructure.ITKUnavailableException;
import uk.co.inhealthcare.open.itk.payload.ITKMessage;
import uk.co.inhealthcare.open.itk.transport.ITKTransportRoute;
import uk.co.inhealthcare.open.itk.transport.ITKTransportSender;
import uk.co.inhealthcare.open.itk.transport.WS.ITKSOAPException;
import uk.co.inhealthcare.open.itk.util.xml.DomUtils;
/**
* The Class HTTPSender.
*
* @author Nick Jones
*/
public class ITKTransportSenderHTTPImpl implements ITKTransportSender {
private final static Logger logger = LoggerFactory.getLogger(ITKTransportSenderHTTPImpl.class);
/**
* Transport send.
*
* @param message The ITKMessage object
* @param destination the destination
* @return the document
* @throws ITKMessagingException the iTK messaging exception
*/
public Document transportSend(ITKMessage message, ITKTransportRoute destination, Map<String, String> httpProperties)
throws ITKMessagingException {
Document responseDoc = null;
// The following code allows test certificates where the CN name does not match the hostname
// Consider if there is a more elegant way of achieving this.
String allowLocalHost = System.getProperty("JSAT.OverrideHostnameVerification");
if (allowLocalHost.equalsIgnoreCase("Y")) {
logger.warn("JSAT configured to override hostname verification. Do not use this setting in Live");
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
new javax.net.ssl.HostnameVerifier(){
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
logger.warn("Hostname is:"+hostname);
return true;
}
});
}
// Post the msg
String serviceEndpoint = destination.getPhysicalAddress();
try {
URLConnection urlConnection = new URL(serviceEndpoint).openConnection();
HttpURLConnection conn = (HttpURLConnection) urlConnection;
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type","text/xml");
conn.setRequestProperty("accept-charset","UTF-8");
for (Map.Entry<String, String> entry : httpProperties.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
conn.setConnectTimeout(destination.getTransportTimeout());
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.write(message.getFullMessage());
pw.close();
int responseCode = conn.getResponseCode();
logger.trace("HTTP Response Code:"+responseCode);
if (responseCode == HttpURLConnection.HTTP_ACCEPTED){
logger.trace("SIMPLE HTTP ACCEPT (202)");
} else if (responseCode == HttpURLConnection.HTTP_OK) {
logger.trace("HTTP 200");
String responseString = readInput(conn.getInputStream());
responseDoc = DomUtils.parse(responseString);
} else if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
logger.error("HTTP 503");
throw new ITKUnavailableException("HTTP Unavailable Response / ITK Busy Tone");
} else if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
logger.error("HTTP 500");
String responseString = readInput(conn.getErrorStream());
//Understand why an error has occurred - do we have a SOAP fault?
if (responseString != null && responseString.contains("http://www.w3.org/2005/08/addressing/fault")) {
//SOAP fault
throw ITKSOAPException.parseSOAPFault(responseString);
} else {
throw new ITKCommsException("HTTP Internal server error");
}
} else {
logger.error("Unrecognized HTTP response code:"+responseCode);
throw new ITKCommsException("Unrecognized HTTP response code:"+responseCode);
}
} catch (MalformedURLException mue) {
logger.error("MalformedURLException on WS-CALL", mue);
throw new ITKCommsException("Configuration error sending ITK Message");
} catch (SocketTimeoutException ste) {
logger.error("Timeout on WS-CALL", ste);
throw new ITKTransportTimeoutException("Transport timeout sending ITK Message");
} catch (IOException ioe) {
logger.error("IOException on WS-CALL", ioe);
throw new ITKCommsException("Transport error sending ITK Message");
} catch (SAXException se) {
logger.error("SAXException processing response from WS-CALL", se);
throw new ITKCommsException("XML Error Processing ITK Response");
} catch (ParserConfigurationException pce) {
logger.error("ParseConfigurationException on WS-CALL", pce);
throw new ITKCommsException("XML Configuration Error Processing ITK Response");
}
return responseDoc;
}
/**
* Read input from a stream
*
* @param is the is
* @return the string
* @throws IOException Signals that an I/O exception has occurred.
*/
private String readInput(InputStream is) throws IOException {
BufferedInputStream bis = new BufferedInputStream(is);
byte[] contents = new byte[1024];
int bytesRead = 0;
String responseString = "";
while ((bytesRead = bis.read(contents)) != -1) {
responseString = responseString + new String(contents, 0, bytesRead);
}
logger.trace("Response was:"+responseString);
bis.close();
return responseString ;
}
}
|
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
contract GovernorEvents {
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, bytes[] calldatas, uint startBlock, uint endBlock, string name, string description);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
/// @notice An event emitted when the voting period is set
event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCasted(address indexed voter, uint proposalId, bool support, uint votes);
/// @notice An event emitted when a principal approve a proposal
event ProposalApproved(address indexed approver, uint proposalId);
}
contract QDAOGovernorDelegatorStorage {
/// @notice Administrator for this contract
address public admin;
address public pendingImplementation;
/// @notice Active implementation of Governor
address public implementation;
/// @notice Multisig with addresses of principals who approve proposals in crisis sutuation
QDAOMultisigInterface public multisig;
mapping (address => bool) changeHasApproved;
}
/**
* @title Storage for Governor Delegator
*/
contract QDAOGovernorDelegateStorageV1 is QDAOGovernorDelegatorStorage {
/// @notice The duration of voting on a proposal, in blocks
uint public votingPeriod;
/// @notice The total number of proposals
uint public proposalCount;
/// @notice Voting delay
uint public votingDelay;
/// @notice The address of the Timelock contract
QDAOTimelockInterface public timelock;
/// @notice The address of the QDAO token
QDAOTokenInterface public token;
/// @notice The record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
bool queued;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
/// @notice Approvals from principals
mapping(address => bool) hasApproved;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal
bool support;
/// @notice The number of votes the voter had, which were cast
uint256 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
NoQuorum,
Succeeded,
Queued,
Executed
}
/// @notice Quorum numerator
uint public quorumNumerator;
}
interface QDAOTimelockInterface {
function delay() external view returns (uint);
function contractAddress() external view returns (address);
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface QDAOTokenInterface {
function getPastVotes(address account, uint blockNumber) external view returns (uint96);
function totalSupply() external view returns (uint256);
}
interface QDAOMultisigInterface {
function getPrincipals() external view returns (address[] memory);
function requiredApprovals() external view returns (uint);
function addPrincipal(address _principal, uint8 _requiredApprovals) external;
}
|
import * as Yup from "yup";
import {
ActionFormProps,
ActionRenderers,
BaseEventStateType,
EventComponents,
EventMeta,
EventTypeInfo,
} from "../../types";
import {
ArrayField,
Field,
RandomUUIDField,
SegmentedSelectField,
SelectField,
} from "../../formFields";
import { useFormikContext } from "formik";
import { RenderClock } from "../../components/Clock";
import { Mark, Stack, Title, Text, Table, Button } from "@mantine/core";
import { IconPencil } from "@tabler/icons";
import { ReactNode } from "react";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import {
clockTimeAt,
formatMMSSMS,
startClockAt,
stopClockAt,
UpwardClock,
UpwardClockType,
} from "../../clock";
import {
Action,
ActionPayloadValidators,
ActionValidChecks,
} from "../../types";
import { wrapAction } from "../../eventStateHelpers";
const playerSchema = Yup.object({
id: Yup.string().uuid().required(),
name: Yup.string().required(),
number: Yup.string()
.required()
.matches(/^[0-9]*$/, "must be a number"),
});
type PlayerType = Yup.InferType<typeof playerSchema>;
export interface State extends BaseEventStateType {
players: {
home: PlayerType[];
away: PlayerType[];
};
halves: Array<{
stoppageTime: number;
goals: Array<{
side: "home" | "away";
player: string | null;
time: number;
}>;
}>;
clock: UpwardClockType;
scoreHome: number;
scoreAway: number;
ruleset: keyof typeof RULESETS;
}
interface Ruleset {
halfDurationMs: number;
extraTimeDurationMs: number;
}
const RULESETS = {
_default: {
halfDurationMs: 45 * 60 * 1000,
extraTimeDurationMs: 15 * 60 * 1000,
},
sixtyMinutes: {
halfDurationMs: 30 * 60 * 1000,
extraTimeDurationMs: 15 * 60 * 1000,
},
};
const MAX_HALVES_WITHOUT_EXTRA_TIME = 2;
const slice = createSlice({
name: "football",
initialState: {
id: "",
type: "football",
name: "",
startTime: "2022-04-29T09:00:00+01:00",
worthPoints: 0,
players: {
home: [],
away: [],
},
halves: [],
clock: {
type: "upward",
state: "stopped",
timeLastStartedOrStopped: 0,
wallClockLastStarted: 0,
},
scoreHome: 0,
scoreAway: 0,
ruleset: "_default",
} as State,
reducers: {
goal: {
reducer(
state,
action: Action<{ side: "home" | "away"; player: string | null }>
) {
if (action.payload.side === "home") {
state.scoreHome++;
} else {
state.scoreAway++;
}
state.halves[state.halves.length - 1].goals.push({
side: action.payload.side,
player: action.payload.player,
time: clockTimeAt(state.clock, action.meta.ts),
});
},
prepare(payload: { side: "home" | "away"; player: string | null }) {
return wrapAction({ payload });
},
},
startHalf: {
reducer(state, action: Action) {
const halfDuration =
RULESETS[state.ruleset ?? "_default"].halfDurationMs;
const extraTimeDuration =
RULESETS[state.ruleset ?? "_default"].extraTimeDurationMs;
state.halves.push({
goals: [],
stoppageTime: 0,
});
if (state.halves.length <= MAX_HALVES_WITHOUT_EXTRA_TIME) {
state.clock.timeLastStartedOrStopped =
halfDuration * (state.halves.length - 1);
} else {
state.clock.timeLastStartedOrStopped =
halfDuration * MAX_HALVES_WITHOUT_EXTRA_TIME +
extraTimeDuration *
(state.halves.length - MAX_HALVES_WITHOUT_EXTRA_TIME - 1);
}
startClockAt(state.clock, action.meta.ts);
},
prepare() {
return wrapAction({ payload: {} });
},
},
resumeCurrentHalf: {
reducer(state, action: Action) {
startClockAt(state.clock, action.meta.ts);
},
prepare() {
return wrapAction({ payload: {} });
},
},
endHalf: {
reducer(state, action: Action) {
stopClockAt(state.clock, action.meta.ts);
},
prepare() {
return wrapAction({ payload: {} });
},
},
addStoppageTime(state, action: PayloadAction<{ minutes: number }>) {
state.halves[state.halves.length - 1].stoppageTime =
action.payload.minutes;
},
},
});
export const reducer = slice.reducer;
export const actions = slice.actions;
export const schema: Yup.SchemaOf<State> = Yup.object().shape({
scoreHome: Yup.number().default(0),
scoreAway: Yup.number().default(0),
clock: UpwardClock,
halves: Yup.array()
.of(
Yup.object({
stoppageTime: Yup.number().default(0),
goals: Yup.array().of(
Yup.object({
side: Yup.mixed<"home" | "away">()
.oneOf(["home", "away"])
.required(),
player: Yup.string().nullable(),
time: Yup.number().required(),
})
),
})
)
.default([]),
players: Yup.object({
home: Yup.array().of(playerSchema).required().default([]),
away: Yup.array().of(playerSchema).required().default([]),
}),
ruleset: Yup.mixed<keyof typeof RULESETS>()
.oneOf(["_default", "sixtyMinutes"])
.required()
.default("_default"),
});
export const actionPayloadValidators: ActionPayloadValidators<
typeof slice["actions"]
> = {
goal: Yup.object({
side: Yup.mixed<"home" | "away">().oneOf(["home", "away"]).required(),
player: Yup.string().uuid().nullable().default(null),
}),
startHalf: Yup.object({}),
// pauseClock: Yup.object({}),
resumeCurrentHalf: Yup.object({}),
endHalf: Yup.object({}),
addStoppageTime: Yup.object({
minutes: Yup.number().required().min(0),
}),
};
export const actionValidChecks: ActionValidChecks<
State,
typeof slice["actions"]
> = {
goal: (state) => state.halves.length > 0,
startHalf: (state) => state.clock.state === "stopped",
resumeCurrentHalf: (state) =>
state.halves.length > 0 && state.clock.state === "stopped",
addStoppageTime: (state) => state.halves.length > 0,
endHalf: (state) =>
state.halves.length > 0 && state.clock.state === "running",
};
export const actionRenderers: ActionRenderers<
typeof actions,
typeof slice["caseReducers"],
State
> = {
goal: ({ action, state, meta }) => {
const goal = action.payload;
const teamName =
action.payload.side === "home" ? meta.homeTeam.name : meta.awayTeam.name;
const player =
goal.player &&
state.players[goal.side].find(
(x: Yup.InferType<typeof playerSchema>) => x.id === goal.player
);
const tag = player
? `${player.name} (${
player.number ? player.number + ", " : ""
}${teamName})`
: teamName;
const time = clockTimeAt(state.clock, action.meta.ts);
return (
<span>
{tag} at {Math.floor(time / 60 / 1000).toFixed(0)} minutes
</span>
);
},
resumeCurrentHalf: ({ action, state }) => {
return <span>Half resumed</span>;
},
startHalf: () => <span>Started next half</span>,
endHalf: () => <span>Half finished</span>,
addStoppageTime: ({ action }) => (
<span>Stoppage time: {action.payload.minutes} minutes</span>
),
};
export function GoalForm(props: ActionFormProps<State>) {
const { values } =
useFormikContext<Yup.InferType<typeof actionPayloadValidators["goal"]>>();
const players =
values.side === "home"
? props.currentState.players.home
: values.side === "away"
? props.currentState.players.away
: [];
return (
<div>
<SegmentedSelectField
name="side"
title="Side"
values={[
["home", props.meta.homeTeam.name],
["away", props.meta.awayTeam.name],
]}
/>
<SelectField
name="player"
title="Player"
// @ts-expect-error typing here is funky
values={[[null, "Unknown"]].concat(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
players!.map((player) => [
player.id,
`${player.name} (${player.number})`,
])
)}
/>
</div>
);
}
export function StoppageTimeForm() {
return (
<>
<Field name="minutes" title="Minutes" type="number" independent />
</>
);
}
export function EditForm(props: { meta: EventMeta }) {
return (
<>
<Field name="name" title="Name" independent />
<SelectField
name="ruleset"
title="Ruleset"
values={[
["_default", "Standard Rules"],
["sixtyMinutes", "60 Minute Matches"],
]}
/>
<fieldset>
<Title order={3}>{props.meta.homeTeam?.name ?? "Home Side"}</Title>
<ArrayField
name="players.home"
title="Players"
initialChildValue={{ name: "", number: "" }}
renderChild={({ namespace }) => (
<div>
<RandomUUIDField name={namespace + "id"} />
<Field name={namespace + "name"} title="Name" independent />
<Field name={namespace + "number"} title="Number" independent />
</div>
)}
/>
</fieldset>
<fieldset>
<Title order={3}>{props.meta.awayTeam?.name ?? "Away Side"}</Title>
<ArrayField
name="players.away"
title="Players"
initialChildValue={{ name: "", number: "" }}
renderChild={({ namespace }) => (
<div>
<RandomUUIDField name={namespace + "id"} />
<Field name={namespace + "name"} title="Name" independent />
<Field name={namespace + "number"} title="Number" independent />
</div>
)}
/>
</fieldset>
</>
);
}
export function RenderScore(props: { state: State; meta: EventMeta }) {
const currentHalf =
props.state.halves.length > 0
? props.state.halves[props.state.halves.length - 1]
: null;
return (
<Stack align={"center"}>
<Title>
{props.meta.homeTeam.name} {props.state.scoreHome} -{" "}
{props.meta.awayTeam.name} {props.state.scoreAway}
</Title>
<div>
<RenderClock
key={
props.state.clock.state + props.state.clock.timeLastStartedOrStopped
}
clock={props.state.clock}
precisionMs={0}
precisionHigh={2}
/>
{(currentHalf?.stoppageTime || 0) > 0 && (
<span>+{currentHalf?.stoppageTime}</span>
)}
</div>
</Stack>
);
}
export const typeInfo: EventTypeInfo<State, typeof actions> = {
reducer,
stateSchema: schema,
actionCreators: actions,
actionPayloadValidators,
actionRenderers,
actionValidChecks,
};
export const components: EventComponents<typeof actions, State> = {
EditForm,
RenderScore,
actionForms: {
goal: GoalForm,
addStoppageTime: StoppageTimeForm,
},
};
|
import 'package:flutter/material.dart';
class SecondaryButton extends StatelessWidget {
const SecondaryButton(
{super.key, required this.onPressed, required this.text});
final Function() onPressed;
final String text;
@override
Widget build(BuildContext context) {
return OutlinedButton(
onPressed: onPressed,
style: ButtonStyle(
side: MaterialStateProperty.all(const BorderSide(
color: Colors.transparent,
width: 1.0,
strokeAlign: BorderSide.strokeAlignInside)),
backgroundColor: MaterialStateProperty.all(const Color(0xFFD7D7D7))),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Text(text,
style: TextStyle(
color: const Color(0xFF07020D),
fontFamily: Theme.of(context).textTheme.bodyMedium!.fontFamily,
fontSize: Theme.of(context).textTheme.bodyMedium!.fontSize,
fontWeight:
Theme.of(context).textTheme.bodyMedium!.fontWeight)),
),
);
}
}
|
import { NextResponse } from "next/server"
import OpenAI from "openai"
export async function POST(req) {
try {
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
})
const payload = await req.json()
console.log({ payload })
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: `Explain this topic like I am 5 years old in 100 words.`,
},
{
role: "user",
content: `${payload.title}`,
},
],
temperature: 0.7,
max_tokens: 256,
top_p: 1,
})
return NextResponse.json({ response }, { status: 201 })
} catch (error) {
console.error("Error fetching explanation:", error)
NextResponse.json("OpenAIError")
}
}
|
@extends('layouts.frontend')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">
{{ trans('global.create') }} {{ trans('cruds.transaction.title_singular') }}
</div>
<div class="card-body">
<form method="POST" action="{{ route("frontend.transactions.store") }}" enctype="multipart/form-data">
@method('POST')
@csrf
<div class="form-group">
<label class="required" for="narration">{{ trans('cruds.transaction.fields.narration') }}</label>
<input class="form-control" type="text" name="narration" id="narration" value="{{ old('narration', '') }}" required>
@if($errors->has('narration'))
<div class="invalid-feedback">
{{ $errors->first('narration') }}
</div>
@endif
<span class="help-block">{{ trans('cruds.transaction.fields.narration_helper') }}</span>
</div>
<div class="form-group">
<label for="description">{{ trans('cruds.transaction.fields.description') }}</label>
<textarea class="form-control" name="description" id="description">{{ old('description') }}</textarea>
@if($errors->has('description'))
<div class="invalid-feedback">
{{ $errors->first('description') }}
</div>
@endif
<span class="help-block">{{ trans('cruds.transaction.fields.description_helper') }}</span>
</div>
<div class="form-group">
<label class="required" for="date">{{ trans('cruds.transaction.fields.date') }}</label>
<input class="form-control date" type="text" name="date" id="date" value="{{ old('date') }}" required>
@if($errors->has('date'))
<div class="invalid-feedback">
{{ $errors->first('date') }}
</div>
@endif
<span class="help-block">{{ trans('cruds.transaction.fields.date_helper') }}</span>
</div>
<div class="form-group">
<label class="required" for="amount">{{ trans('cruds.transaction.fields.amount') }}</label>
<input class="form-control" type="number" name="amount" id="amount" value="{{ old('amount', '') }}" step="0.01" required>
@if($errors->has('amount'))
<div class="invalid-feedback">
{{ $errors->first('amount') }}
</div>
@endif
<span class="help-block">{{ trans('cruds.transaction.fields.amount_helper') }}</span>
</div>
<div class="form-group">
<label class="required" for="transactionable_type">{{ trans('cruds.transaction.fields.transactionable_type') }}</label>
<input class="form-control" type="text" name="transactionable_type" id="transactionable_type" value="{{ old('transactionable_type', '') }}" required>
@if($errors->has('transactionable_type'))
<div class="invalid-feedback">
{{ $errors->first('transactionable_type') }}
</div>
@endif
<span class="help-block">{{ trans('cruds.transaction.fields.transactionable_type_helper') }}</span>
</div>
<div class="form-group">
<label for="status">{{ trans('cruds.transaction.fields.status') }}</label>
<input class="form-control" type="text" name="status" id="status" value="{{ old('status', '') }}">
@if($errors->has('status'))
<div class="invalid-feedback">
{{ $errors->first('status') }}
</div>
@endif
<span class="help-block">{{ trans('cruds.transaction.fields.status_helper') }}</span>
</div>
<div class="form-group">
<label for="remarks">{{ trans('cruds.transaction.fields.remarks') }}</label>
<textarea class="form-control" name="remarks" id="remarks">{{ old('remarks') }}</textarea>
@if($errors->has('remarks'))
<div class="invalid-feedback">
{{ $errors->first('remarks') }}
</div>
@endif
<span class="help-block">{{ trans('cruds.transaction.fields.remarks_helper') }}</span>
</div>
<div class="form-group">
<label class="required" for="type_id">{{ trans('cruds.transaction.fields.type') }}</label>
<select class="form-control select2" name="type_id" id="type_id" required>
@foreach($types as $id => $entry)
<option value="{{ $id }}" {{ old('type_id') == $id ? 'selected' : '' }}>{{ $entry }}</option>
@endforeach
</select>
@if($errors->has('type'))
<div class="invalid-feedback">
{{ $errors->first('type') }}
</div>
@endif
<span class="help-block">{{ trans('cruds.transaction.fields.type_helper') }}</span>
</div>
<div class="form-group">
<label class="required" for="transactionable_id">{{ trans('cruds.transaction.fields.transactionable') }}</label>
<select class="form-control select2" name="transactionable_id" id="transactionable_id" required>
@foreach($transactionables as $id => $entry)
<option value="{{ $id }}" {{ old('transactionable_id') == $id ? 'selected' : '' }}>{{ $entry }}</option>
@endforeach
</select>
@if($errors->has('transactionable'))
<div class="invalid-feedback">
{{ $errors->first('transactionable') }}
</div>
@endif
<span class="help-block">{{ trans('cruds.transaction.fields.transactionable_helper') }}</span>
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
{{ trans('global.save') }}
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
|
import { useContext, useState } from "react";
import "../css/Login.css";
import { Login_Error } from "../../../Util";
import { Login_S } from "../../../service";
import { useAxios } from "../../../Hook";
import { useNavigate } from "react-router-dom";
import { contextLogin } from "../../../Hook/Context/Context_Login";
import { toast } from "react-toastify";
const Client_Id = "330b6c67acca4d537d39";
// Client_Id lay trong github nha
function Login({ Value }) {
const [state, dispatch] = useAxios();
const Navigate = useNavigate();
const { state_Login, dispatch_Login } = useContext(contextLogin);
const [ValueError, setValueError] = useState({});
const [FormLogin, setFormLogin] = useState({
Email: "",
Pass: "",
});
const Change_Value_Login = (value) => {
setFormLogin({ ...FormLogin, ...value });
};
const LoginSubmitForm = (e) => {
e.preventDefault();
setValueError(Login_Error(FormLogin).Detail_Error);
if (!Login_Error(FormLogin).is_Error) {
dispatch({ type: "REQUEST" });
Login_S(FormLogin)
.then((res) => {
if (res.status === 200) {
localStorage.setItem("Access_Token", res.data.Access_Token);
dispatch_Login({
type: "CHANGE",
payload: { ...res.data, is_Login: true },
});
toast.success("Login Complete");
Navigate("/");
} else {
toast.error("Login Fail");
}
dispatch({ type: "SUCCESS" });
})
.catch((err) => {
dispatch({ type: "ERROR", payload: { Error: err } });
});
} else {
const Error_Value = Login_Error(FormLogin).Detail_Error;
let Arraykey = Object.keys(Error_Value);
Arraykey.map((key) => toast.error(Error_Value[key]));
}
};
return (
<div className={`FromLS LoginForm ${Value.ChangeForm ? "active" : ""}`}>
<form onSubmit={LoginSubmitForm}>
<h1>Login</h1>
<div className="inputText">
<label htmlFor="Email"> Email</label>
<input
type="text"
required
value={FormLogin.Email}
onChange={(e) => Change_Value_Login({ Email: e.target.value })}
/>
<div className="toastInput"></div>
</div>
<div className="inputText">
<label htmlFor="Pass">Password</label>
<input
type="password"
required
value={FormLogin.Pass}
onChange={(e) => Change_Value_Login({ Pass: e.target.value })}
/>
<div className="toastInput"></div>
</div>
<div className="selection">
<div className="remeber">
<input type="checkbox" name="" />
<p>Remember</p>
</div>
<p>Forgot Password</p>
</div>
<button className="Loginbtn" type="submit">
Login
</button>
</form>
<div className="otherOptions">
<div className="titleOther">Or</div>
<button className="optionLogin ">Github</button>
<button className="optionLogin ">Twitter</button>
</div>
<div className="btnLink mt-20U ">
<p>
Don't have an account
<span
style={{ color: "#fff", cursor: "pointer" }}
onClick={Value.HandleChangeForm}
>
Register
</span>
</p>
</div>
</div>
);
}
export default Login;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="{{url_for('index')}}">Home</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{url_for('puppies.add')}}">Add Pup</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{url_for('puppies.list')}}">List Pups</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{url_for('puppies.delete')}}">Remove Pup</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{url_for('owners.add')}}">Add Owner</a>
</li>
</ul>
</div>
</div>
</nav>
{% block content %}
{% endblock %}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
|
**PROJECT 1: Variational Autoencoder (VAE) Implemented on VAE 10000**
**Project Overview**
**Objective:** Implement a VAE for feature learning and image generation using 5K skin lesion images from the HAM10000 dataset.
**Architecture:** The VAE comprises an encoder and decoder. The encoder transforms input images into a lower-dimensional latent space representation, while the decoder reconstructs the original images from the latent space.
**Training Process**
**Reparameterization Trick:** VAE utilizes a reparameterization trick for efficient sampling of latent space representations.
**Forward Pass:** Input images are encoded into a latent space representation by the encoder, and then sampled using the reparameterization trick. The decoder reconstructs the input images from the sampled latent space representations.
**Results**
**Hyperparameters:** After experimenting with different hyperparameters, the best reconstruction results by using 5K which is half of the original dataset, we achieved:
- Latent dimension: 120
- Batch size: 32
- Learning rate: 1e-3
- Number of epochs: 100
**Performance:** While the results are not perfect, the VAE showed significant improvement with optimized hyperparameters and the reconstructed image shows the main characteristics of the original image and it is visible that the reconstruction is for a skin lesion image.
---
**PROJECT 2: Anomaly detection: Generation Approach Autoencoder**
**Project Overview**
**Objective:** Implement anomaly detection on the full HAM10000 dataset consisting of 10,000 skin lesion images. The dataset contains 7 classes of skin lesions, with cancerous ones categorized as "abnormal" and the remaining 4 classes considered as "normal".
0: 'nv' - Melanocytic nevus, 1: 'mel' - Melanoma, 2: 'bkl' - Benign keratosis, 3: 'bcc' - Basal cell carcinoma, 4: 'akiec' - Actinic keratosis, 5: 'vasc' - Vascular lesion, 6: 'df' - Dermatofibroma.
Abnormal Classes = [1, 3, 4]
Normal Classes = [0, 2, 5, 6]
**Architecture:** The architecture employed for anomaly detection consisted of an Autoencoder (AE) model. The AE model comprised an encoder and a decoder, each consisting of multiple fully connected layers with ReLU activation functions. The encoder reduced the input image dimensionality to a lower-dimensional latent space, while the decoder attempted to reconstruct the original image from this latent representation.
**Training Process**: The training process involves the following steps:
1. **Model Training Setup**:
- The model was set to training mode using `model.train()` to enable dropout and batch normalization layers.
- The training loop iterated over epochs, with each epoch consisting of multiple batches.
2. **Loss Calculation and Optimization**:
- For each batch in the training DataLoader, the model reconstructed the input data and computed the mean squared error (MSE) loss between the input and reconstructed samples.
- Gradients of the loss with respect to model parameters were computed using backpropagation, and the model parameters were updated using the optimizer.
**Evaluation**: The evaluation process includes the following steps:
1. **Model Evaluation Setup**:
- The model was set to evaluation mode using `model.eval()` to disable dropout and batch normalization layers.
2. **Loss Calculation**:
- For each batch in the test DataLoader, the model reconstructed the input data.
- MSE loss was calculated between the input data and reconstructed samples, and the loss distribution was flattened.
3. **Loss Distribution and Labels**:
- The loss distribution and corresponding labels were collected for further analysis.
4. **Evaluation Metrics**:
- Evaluation metrics such as precision, recall, and F1-score were calculated using the loss distribution and labels for anomaly detection.
**Results**: When checking the Loss distribution of the data we can see that the Anomalies have a normal distribution, however, the Normal does not have a good distribution at all and this is due to the class imbalance of the original dataset.
**Performance:** Overall, the model did not perform well when reconstructing the image, however, after changing the hyper-parameters it did improve, which is the main objective rather than having a perfect model, plus, we learnt a lot!
**Future Improvements:** Future improvements for this model include incorporating convolutional neural networks (CNNs) to capture more intricate patterns in the images. Additionally, proper normalization of the images and addressing class imbalance issues, possibly by utilizing techniques such as Variational Autoencoders (VAEs), could enhance the model's performance.
**Note**: Both projects utilized the HAM10000 dataset. However, during the loading process, the pixel values were extracted in tabular form. This approach may have introduced a discrepancy, as the visualization of the images revealed a decrease in quality. Addressing this issue is essential to ensure accurate representation and analysis of the dataset.
Thanks for checking this repo out :)
|
package com.dovisen.dblog.controller;
import com.dovisen.dblog.domain.post.Post;
import com.dovisen.dblog.domain.post.PostDTO;
import com.dovisen.dblog.domain.post.PostService;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/posts")
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
@PostMapping
public ResponseEntity<Object> savePost(@RequestBody @Valid PostDTO postDTO){
Post savedPost;
try{
savedPost = postService.save(postDTO);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedPost.getId())
.toUri();
return ResponseEntity.created(location).body(savedPost);
}
@GetMapping
@PermitAll
public ResponseEntity<List<Post>> getTopNPosts(@RequestParam(defaultValue = "10") int limit){
List<Post> posts = postService.findAll();
return ResponseEntity.status(HttpStatus.OK).body(posts);
}
@GetMapping("/{id}")
public ResponseEntity<Object> getOnePost(@PathVariable(value = "id") UUID id){
Post post;
try{
post = postService.findById(id);
} catch (NullPointerException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
}
return ResponseEntity.status(HttpStatus.OK).body(post);
}
@GetMapping("/{parentId}/comments")
public ResponseEntity<List<Post>> getComments(@PathVariable(value="parentId") UUID parentId){
List<Post> comments = this.postService.findComments(parentId);
return ResponseEntity.status(HttpStatus.OK).body(comments);
}
@PostMapping("/{id}/like")
public ResponseEntity<Post> changeLike(@PathVariable(value="id") UUID id){
Post post = this.postService.changeLike(id);
return ResponseEntity.status(HttpStatus.OK).body(post);
}
@DeleteMapping("/{id}")
public ResponseEntity<Object> deletePost(@PathVariable(value = "id") UUID id){
try {
postService.delete(id);
} catch (NullPointerException e){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e);
}
return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Post não encontrado");
}
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2023 Google Research (main, core work; original source)
# Copyright 2023 Emanuele Ballarin <[email protected]> (minor edits; maintainance)
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of the Lion optimizer."""
from collections.abc import Callable
from typing import Optional
from typing import Tuple
import torch
from torch.optim.optimizer import Optimizer
class Lion(Optimizer):
r"""Implements Lion algorithm."""
def __init__(
self,
params,
lr: float = 1e-4,
betas: Tuple[float, float] = (0.9, 0.99),
weight_decay: float = 0.0,
):
"""Initialize the hyperparameters.
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float, optional): learning rate (default: 1e-4)
betas (Tuple[float, float], optional): coefficients used for computing
running averages of gradient and its square (default: (0.9, 0.99))
weight_decay (float, optional): weight decay coefficient (default: 0)
"""
if lr < 0.0:
raise ValueError(f"Invalid learning rate: {lr}")
if not 0.0 <= betas[0] < 1.0:
raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
if not 0.0 <= betas[1] < 1.0:
raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
defaults = dict(lr=lr, betas=betas, weight_decay=weight_decay)
super().__init__(params, defaults)
@torch.no_grad()
def step(self, closure: Optional[Callable] = None):
"""Performs a single optimization step.
Args:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
Returns:
loss
"""
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
for p in group["params"]:
if p.grad is None:
continue
p.data.mul_(1 - group["lr"] * group["weight_decay"])
grad = p.grad
state = self.state[p]
# State initialization
if len(state) == 0:
state["exp_avg"] = torch.zeros_like(p)
exp_avg = state["exp_avg"]
beta1, beta2 = group["betas"]
update = exp_avg * beta1 + grad * (1 - beta1)
p.add_(torch.sign(update), alpha=-group["lr"])
exp_avg.mul_(beta2).add_(grad, alpha=1 - beta2)
return loss
|
package cells_test
import (
"context"
"strconv"
"testing"
"github.com/brendoncarroll/go-state/cells"
"github.com/brendoncarroll/go-state/cells/celltest"
)
func TestDerived(t *testing.T) {
celltest.TestCell(t, func(t testing.TB) cells.Cell[uint64] {
c1 := cells.NewMem[string](cells.DefaultEquals[string], cells.DefaultCopy[string])
c2 := cells.NewDerived(cells.DerivedParams[string, uint64]{
Inner: c1,
Forward: func(ctx context.Context, dst *uint64, src string) (err error) {
if src == "" {
*dst = 0
return nil
}
*dst, err = strconv.ParseUint(src, 10, 64)
return err
},
Inverse: func(ctx context.Context, dst *string, src uint64) error {
*dst = strconv.FormatUint(src, 10)
return nil
},
Equals: cells.DefaultEquals[uint64],
Copy: cells.DefaultCopy[uint64],
})
return c2
})
}
|
% Sin/Cos iteracynie/rekursywnie
clear all; close all;
% Wartości parametrów
x0 = 0; % 0, pi/4;
dx = pi/10;
N = 100;
% Odniesienie
n = 0:N-1;
x = x0 + n*dx;
y1 = sin( x );
% Metoda iteracyjna #1
y(1) = sin( x0 - 2*dx );
y(2) = sin( x0 - dx );
a = 2*cos(dx);
for n = 3 : N+2
y(n) = a*y(n-1) - y(n-2);
end
y2 = y(3:end);
figure; plot(x,y1,'ro-',x,y2,'go-'); grid; title('y=sin(x)')
legend('Sinus','Rekursywnie'); pause
% Metoda iteracyjna #2
u(1) = cos( dx/2 );
v(1) = 0;
b = 2*sin( dx/2 );
for n = 2 : N
u(n) = u(n-1) - b*v(n-1);
v(n) = v(n-1) + b*u(n);
end
y3a = u(1:end); y3b = v(1:end);
figure; plot(x,y1,'r',x,y3a,'go-',x,y3b,'bo-'); grid; title('y=sin(x)')
legend('Sinus','Magic u','Magic v'); pause
|
import 'package:flutter/material.dart';
import 'package:fourscore/Component/FirebasePicture.dart';
import 'package:fourscore/Component/PhotoProfile.dart';
import 'package:fourscore/Component/Text/MyText.dart';
import 'package:fourscore/Component/myDialog.dart';
import 'package:fourscore/Student/Profile/ProfilePage.dart';
import 'package:fourscore/main.dart';
import 'package:hexcolor/hexcolor.dart';
class StudentAppBar extends StatelessWidget {
const StudentAppBar({
super.key,
required this.picture,
});
final String picture;
@override
Widget build(BuildContext context) {
return Positioned(
top: 10,
child: Container(
width: width(context),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
onTap: () {
myDialog(context, "Coming soon");
},
child: Container(
height: 50,
width: 50,
decoration: BoxDecoration(
color: HexColor("#2D2F3A"),
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.4),
blurRadius: 10,
offset: Offset(1, 1),
),
]),
child: Icon(
Icons.notifications_outlined,
color: Colors.white,
)),
),
MyText(
text: "4Score",
fontSize: 27,
color: Colors.white,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
PageRouteBuilder(
// transitionDuration: Duration(milliseconds: 100),
pageBuilder: (context, animation, secondaryAnimation) {
return ProfilePage();
},
transitionsBuilder:
(context, animation, secondaryAnimation, child) {
return FadeTransition(
opacity: animation,
child: child,
);
},
),
);
},
child: Hero(
tag: 'pp',
child: PhotoProfile(
picture: picture,
size: 50,
),
),
)
],
),
),
);
}
}
|
package com.ltl.opencartadminstrationback.controller;
import at.favre.lib.crypto.bcrypt.BCrypt;
import com.github.pagehelper.Page;
import com.ltl.opencartadminstrationback.constant.ClientExceptionConstant;
import com.ltl.opencartadminstrationback.dto.in.*;
import com.ltl.opencartadminstrationback.dto.out.*;
import com.ltl.opencartadminstrationback.enumeration.AdministratorStatus;
import com.ltl.opencartadminstrationback.exception.ClientException;
import com.ltl.opencartadminstrationback.po.Administrator;
import com.ltl.opencartadminstrationback.service.AdministratorService;
import com.ltl.opencartadminstrationback.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import javax.xml.bind.DatatypeConverter;
import java.security.SecureRandom;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/administrator")
public class AdministratorController {
@Autowired
private AdministratorService administratorService;
@Autowired
private JWTUtil jwtUtil;
@Autowired
private SecureRandom secureRandom;
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String fromEmail;
private Map<String, String> emailPwdResetCodeMap = new HashMap<>();
/** @Author ltl
* @Description //TODO
* @Date 10:18 2020/3/1
* @Param [administratorLoginInDTO]
* @return com.ltl.opencartadminstrationback.dto.out.AdministratorLoginOutDTO
**/
@GetMapping("/login")
public AdministratorLoginOutDTO login(AdministratorLoginInDTO administratorLoginInDTO) throws ClientException {
Administrator administrator = administratorService.getByUsername(administratorLoginInDTO.getUsername());
if (administrator == null){
throw new ClientException(ClientExceptionConstant.ADMINISTRATOR_USERNAME_NOT_EXIST_ERRCODE, ClientExceptionConstant.ADMINISTRATOR_USERNAME_NOT_EXIST_ERRMSG);
}
String encPwdDB = administrator.getEncryptedPassword();
BCrypt.Result result = BCrypt.verifyer().verify(administratorLoginInDTO.getPassword().toCharArray(), encPwdDB);
if (result.verified) {
AdministratorLoginOutDTO administratorLoginOutDTO = jwtUtil.issueToken(administrator);
return administratorLoginOutDTO;
}else {
throw new ClientException(ClientExceptionConstant.ADMINISTRATOR_PASSWORD_INVALID_ERRMSG, ClientExceptionConstant.ADMINISTRATOR_PASSWORD_INVALID_ERRMSG);
}
}
/** @Author ltl
* @Description //TODO
* @Date 10:19 2020/3/1
* @Param [adminstratorId]
* @return com.ltl.opencartadminstrationback.dto.out.AdministratorGetProfileOutDTO
**/
@GetMapping("/getProfile")
public AdministratorGetProfileOutDTO getProfile(@RequestParam(required = false) Integer adminstratorId){
Administrator administrator = administratorService.getById(adminstratorId);
AdministratorGetProfileOutDTO administratorGetProfileOutDTO = new AdministratorGetProfileOutDTO();
administratorGetProfileOutDTO.setAdministratorId(administrator.getAdministratorId());
administratorGetProfileOutDTO.setUsername(administrator.getUsername());
administratorGetProfileOutDTO.setRealName(administrator.getRealName());
administratorGetProfileOutDTO.setEmail(administrator.getEmail());
administratorGetProfileOutDTO.setAvatarUrl(administrator.getAvatarUrl());
administratorGetProfileOutDTO.setCreateTimestamp(administrator.getCreateTime().getTime());
return administratorGetProfileOutDTO;
}
/** @Author ltl
* @Description //TODO
* @Date 10:21 2020/3/1
* @Param [administratorUpdateProfileInDTO, administratorId]
* @return void
**/
@PostMapping("/updateProfile")
public void updateProfile(@RequestBody AdministratorUpdateProfileInDTO administratorUpdateProfileInDTO
,@RequestAttribute Integer administratorId){
Administrator administrator = new Administrator();
administrator.setAdministratorId(administratorId);
administrator.setRealName(administratorUpdateProfileInDTO.getRealName());
administrator.setEmail(administratorUpdateProfileInDTO.getEmail());
administrator.setAvatarUrl(administratorUpdateProfileInDTO.getAvatarUrl());
administratorService.update(administrator);
}
/** @Author ltl
* @Description //TODO
* @Date 16:36 2020/2/25
* @Param [email]
* @return java.lang.String
**/
@GetMapping("/getPwdResetCode")
public void getPwdResetCode(@RequestParam String email) throws ClientException {
Administrator administrator = administratorService.getByEmail(email);
if (administrator == null){
throw new ClientException(ClientExceptionConstant.ADMINISTRATOR_EMAIL_NOT_EXIST_ERRCODE, ClientExceptionConstant.ADMINISTRATOR_EMAIL_NOT_EXIST_ERRMSG);
}
byte[] bytes = secureRandom.generateSeed(3);
String hex = DatatypeConverter.printHexBinary(bytes);
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromEmail);
message.setTo(email);
message.setSubject("opencart管理端管理员密码重置");
message.setText(hex);
mailSender.send(message);
emailPwdResetCodeMap.put(email, hex);
}
/** @Author ltl
* @Description //TODO
* @Date 16:37 2020/2/25
* @Param [administratorResetPwdInDTO]
* @return void
**/
@PostMapping("/resetPwd")
public void resetPwd(@RequestBody AdministratorResetPwdInDTO administratorResetPwdInDTO){
}
/** @Author ltl
* @Description //TODO
* @Date 18:26 2020/3/2
* @Param [pageNum]
* @return com.ltl.opencartadminstrationback.dto.out.PageOutDTO<com.ltl.opencartadminstrationback.dto.out.AdministratorListOutDTO>
**/
@GetMapping("/getList")
public PageOutDTO<AdministratorListOutDTO> getList(@RequestParam(required = false, defaultValue = "1") Integer pageNum){
Page<Administrator> page = administratorService.getList(pageNum);
List<AdministratorListOutDTO> administratorListOutDTOS = page.stream().map(administrator -> {
AdministratorListOutDTO administratorListOutDTO = new AdministratorListOutDTO();
administratorListOutDTO.setAdministratorId(administrator.getAdministratorId());
administratorListOutDTO.setUsername(administrator.getUsername());
administratorListOutDTO.setRealName(administrator.getRealName());
administratorListOutDTO.setStatus(administrator.getStatus());
administratorListOutDTO.setCreateTimestamp(administrator.getCreateTime().getTime());
return administratorListOutDTO;
}).collect(Collectors.toList());
PageOutDTO<AdministratorListOutDTO> pageOutDTO = new PageOutDTO<>();
pageOutDTO.setTotal(page.getTotal());
pageOutDTO.setPageSize(page.getPageSize());
pageOutDTO.setPageNum(page.getPageNum());
pageOutDTO.setList(administratorListOutDTOS);
return pageOutDTO;
}
/** @Author ltl
* @Description //TODO
* @Date 18:26 2020/3/2
* @Param [administratorId]
* @return com.ltl.opencartadminstrationback.dto.out.AdministratorShowOutDTO
**/
@GetMapping("/getById")
public AdministratorShowOutDTO getById(@RequestParam Integer administratorId){
Administrator administrator = administratorService.getById(administratorId);
AdministratorShowOutDTO administratorShowOutDTO = new AdministratorShowOutDTO();
administratorShowOutDTO.setAdministratorId(administrator.getAdministratorId());
administratorShowOutDTO.setUsername(administrator.getUsername());
administratorShowOutDTO.setRealName(administrator.getRealName());
administratorShowOutDTO.setEmail(administrator.getEmail());
administratorShowOutDTO.setAvatarUrl(administrator.getAvatarUrl());
administratorShowOutDTO.setStatus(administrator.getStatus());
return administratorShowOutDTO;
}
/** @Author ltl
* @Description //TODO
* @Date 18:25 2020/3/2
* @Param [administratorCreateInDTO]
* @return java.lang.Integer
**/
@PostMapping("/create")
public Integer create(@RequestBody AdministratorCreateInDTO administratorCreateInDTO){
Administrator administrator = new Administrator();
administrator.setUsername(administratorCreateInDTO.getUsername());
administrator.setRealName(administratorCreateInDTO.getRealName());
administrator.setEmail(administratorCreateInDTO.getEmail());
administrator.setAvatarUrl(administratorCreateInDTO.getAvatarUrl());
administrator.setStatus((byte) AdministratorStatus.Enable.ordinal());
administrator.setCreateTime(new Date());
String bcryptHashString = BCrypt.withDefaults().hashToString(12, administratorCreateInDTO.getPassword().toCharArray());
administrator.setEncryptedPassword(bcryptHashString);
Integer administratorId = administratorService.create(administrator);
return administratorId;
}
/** @Author ltl
* @Description //TODO
* @Date 18:28 2020/3/2
* @Param [administratorUpdateInDTO]
* @return void
**/
@PostMapping("/update")
public void update(@RequestBody AdministratorUpdateInDTO administratorUpdateInDTO){
Administrator administrator = new Administrator();
administrator.setAdministratorId(administratorUpdateInDTO.getAdministratorId());
administrator.setRealName(administratorUpdateInDTO.getRealName());
administrator.setEmail(administratorUpdateInDTO.getEmail());
administrator.setAvatarUrl(administratorUpdateInDTO.getAvatarUrl());
administrator.setStatus(administratorUpdateInDTO.getStatus());
String password = administratorUpdateInDTO.getPassword();
if (password != null && !password.isEmpty()){
String bcryptHashString = BCrypt.withDefaults().hashToString(12, password.toCharArray());
administrator.setEncryptedPassword(bcryptHashString);
}
administratorService.update(administrator);
}
/** @Author ltl
* @Description //TODO
* @Date 18:29 2020/3/2
* @Param [adminstratorId]
* @return void
**/
@PostMapping("/delete")
public void delete(@RequestBody Integer adminstratorId){
administratorService.delete(adminstratorId);
}
/** @Author ltl
* @Description //TODO
* @Date 18:29 2020/3/2
* @Param [administratorIds]
* @return void
**/
@PostMapping("/batchDelete")
public void batchDelete(@RequestBody List<Integer> administratorIds){
administratorService.batchDelete(administratorIds);
}
}
|
import React from "react";
import { getUserLocalStorage } from "../../../../../../utils/getUserLocalStorage";
import {
IOpcionMultiple,
IReactivo,
OpcionesVerdaderoFalso,
OpcionFalsoVerdadero,
ReactivoBase,
} from "../../../../interfaces/reactivo.interface";
import { useReactivosContext } from "../../context/ReactivosContext";
const defaultOpcionFalsoVerdadero: OpcionesVerdaderoFalso = [
{ esCorrecto: false, puntos: 0, opcion: "Falso" },
{ esCorrecto: false, puntos: 0, opcion: "Verdadero" },
];
export const useReactivoForm = () => {
const {
reactivoRef,
pregunta,
setPregunta,
puntos,
setPuntos,
tipoReactivo,
setTipoReactivo,
opcionesMultiple,
setOpcionesMultiple,
opcionFalsoVerdadero,
setOpcionFalsoVerdadero,
opcionesVerdaderoFalso,
setOpcionesVerdaderoFalso,
descripcionOpcion,
setDescripcionOpcion,
puntoOpcion,
setPuntosOpcion,
valorTextualCorrecto,
setValorTextualCorrecto,
esOpcionCorrecta,
setEsOpcionCorrecta,
similitudValorTextual,
setSimilitudValorTextual,
valorNumericoCorrecto,
setValorNumericoCorrecto,
margenValorNumerico,
setMargenValorNumerico,
categoria,
setCategoria,
materia,
setMateria,
dificultad,
setDificultad,
estatusReactivo,
setEstatusReactivo,
esPrivado,
setEsPrivado,
mostrarPista,
setMostrarPista,
pista,
setPista,
tiempoMaximoRespuesta,
setTiempoMaximoRespuesta,
errorMessage,
setErrorMessage,
errorOpcionMultipleMessage,
setErrorOpcionMultipleMessage,
} = useReactivosContext();
const handleChangeOpcionFalsoVerdadero = (opcion: OpcionFalsoVerdadero) => {
const [opcionFalso, opcionVerdadero] = opcionesVerdaderoFalso;
const esCorrecto = opcion === "Verdadero";
setOpcionFalsoVerdadero(opcion);
setOpcionesVerdaderoFalso([
{ ...opcionFalso, esCorrecto: !esCorrecto, puntos: 0 },
{ ...opcionVerdadero, esCorrecto: esCorrecto, puntos: puntos },
]);
};
const _validateAddOpcionMultiple = () => {
if (descripcionOpcion.trim() === "") {
throw new Error("Ingrese descripcion opción");
}
if (esOpcionCorrecta && puntoOpcion === 0) {
throw new Error("Si la opción es correcta, ingrese puntos de opción");
}
};
const handleAddOpcionMultiple = () => {
try {
setErrorOpcionMultipleMessage("");
_validateAddOpcionMultiple();
const newOpcionMultiple: IOpcionMultiple = {
esCorrecto: esOpcionCorrecta,
puntos: esOpcionCorrecta ? puntoOpcion : 0,
opcion: descripcionOpcion,
};
const newOpcionesMulple: IOpcionMultiple[] = [
...opcionesMultiple,
newOpcionMultiple,
];
setOpcionesMultiple(newOpcionesMulple);
setDescripcionOpcion("");
setPuntosOpcion(0);
setEsOpcionCorrecta(false);
} catch (error: any) {
setErrorOpcionMultipleMessage(error.message);
}
};
const handleDeleteOpcionMultiple = (om: IOpcionMultiple) => {
const newOpcionesMulple = opcionesMultiple.filter(
(item) => item.opcion !== om.opcion
);
setOpcionesMultiple(newOpcionesMulple);
};
const _validateForm = () => {
if (pregunta.trim() === "") {
throw new Error("pregunta no puede ser vacia");
}
if (puntos === 0) {
throw new Error("Puntos de reactivo debe ser mayor a cero");
}
if (categoria.trim() === "") {
throw new Error("Ingrese Categoria");
}
if (materia.trim() === "") {
throw new Error("ingrese materia");
}
if (mostrarPista && pista.trim() === "") {
throw new Error(
"Si se va a mostrar pista, ingrese descripción de pista."
);
}
if (tipoReactivo === "OPCION_MULTIPLE") {
const puntosOM = opcionesMultiple
.map((om) => om.puntos)
.reduce((cur, ac) => ac + cur, 0);
if (opcionesMultiple.length < 2)
throw new Error("Deben de existir al menos 2 opciones multiple");
if (!opcionesMultiple.find((om) => om.esCorrecto)) {
throw new Error("Al menos una opción debe ser correcta");
}
if (puntosOM !== puntos) {
throw new Error(
"Los puntos de opcion multiple no coincien con los puntos de reactivo"
);
}
}
if (tipoReactivo === "FALSO_VERDADERO") {
if (!opcionesVerdaderoFalso.find((om) => om.esCorrecto)) {
throw new Error("Al menos una opción debe ser correcta");
}
}
if (
tipoReactivo === "VALOR_TEXTUAL" &&
valorTextualCorrecto.trim() === ""
) {
throw new Error("El valor textual no puede ser vacio");
}
};
const resetReactivoForm = () => {
setCategoria("");
setDificultad("MEDIA");
setEsPrivado(false);
setEstatusReactivo("ACTIVO");
setMargenValorNumerico(0);
setMateria("");
setMostrarPista(false);
setOpcionesMultiple([]);
setOpcionesVerdaderoFalso(defaultOpcionFalsoVerdadero);
setOpcionFalsoVerdadero(undefined);
setPista("");
setPregunta("");
setPuntos(0);
setSimilitudValorTextual(0);
setTiempoMaximoRespuesta(0);
setTipoReactivo("FALSO_VERDADERO");
setValorNumericoCorrecto(0);
setValorTextualCorrecto("");
};
const loadDefaultValues = () => {
resetReactivoForm();
setPregunta(reactivoRef.current?.pregunta!);
setTipoReactivo(reactivoRef.current?.tipoReactivo!);
setPuntos(reactivoRef.current?.puntos!);
setCategoria(reactivoRef.current?.categoria!);
setMateria(reactivoRef.current?.materia!);
setDificultad(reactivoRef.current?.dificultad!);
setEstatusReactivo(reactivoRef.current?.estatus!);
setEsPrivado(reactivoRef.current?.isPrivado!);
setMostrarPista(reactivoRef.current?.mostrarPista!);
setPista(reactivoRef.current?.pista!);
setTiempoMaximoRespuesta(reactivoRef.current?.tiempoMaximoRespuesta!);
// setOpcionesMultiple([]);
// setOpcionFalsoVerdadero(undefined);
// setOpcionesVerdaderoFalso(defaultOpcionFalsoVerdadero);
// setValorNumericoCorrecto(0);
// setSimilitudValorTextual(0);
// setValorNumericoCorrecto(0);
// setMargenValorNumerico(0);
if (reactivoRef.current?.tipoReactivo === "VALOR_TEXTUAL") {
setValorTextualCorrecto(reactivoRef.current?.valorTextualCorrecto || "");
setSimilitudValorTextual(reactivoRef.current?.similitudValorTextual || 0);
}
if (reactivoRef.current?.tipoReactivo === "FALSO_VERDADERO") {
setOpcionesVerdaderoFalso(
reactivoRef.current.opciones || opcionesVerdaderoFalso
);
setOpcionFalsoVerdadero(
reactivoRef.current!.opciones.find((o) => o.esCorrecto)?.opcion
);
}
if (reactivoRef.current?.tipoReactivo === "OPCION_MULTIPLE") {
setOpcionesMultiple(reactivoRef.current.opciones);
}
if (reactivoRef.current?.tipoReactivo === "VALOR_NUMERICO") {
setValorNumericoCorrecto(reactivoRef.current.valorNumericoCorrecto);
setMargenValorNumerico(reactivoRef.current.valorNumericoCorrecto);
}
};
const handleSubmit = (cb: (data: IReactivo) => void) => {
try {
const { idAccount, idUsuario, prefijo, idUsuarioConPrefijo } =
getUserLocalStorage()!;
setErrorMessage("");
setErrorOpcionMultipleMessage("");
_validateForm();
const reactivoBase: ReactivoBase = {
id: !reactivoRef.current
? "_" + Math.random().toString(36).substr(2, 9)
: reactivoRef.current.id,
type: "reactivo",
idAccount,
materia: materia,
categoria: categoria,
pregunta: pregunta,
puntos: puntos,
idUsuario: idUsuarioConPrefijo,
isPrivado: esPrivado,
dificultad: dificultad,
tiempoMaximoRespuesta: tiempoMaximoRespuesta,
pista: pista,
mostrarPista: mostrarPista,
tipoReactivo: tipoReactivo,
estatus: estatusReactivo,
};
if (tipoReactivo === "OPCION_MULTIPLE") {
const reactivo: IReactivo = {
...reactivoBase,
tipoReactivo: "OPCION_MULTIPLE",
opciones: opcionesMultiple,
};
cb(reactivo);
return;
}
if (tipoReactivo === "FALSO_VERDADERO") {
const reactivo: IReactivo = {
...reactivoBase,
tipoReactivo: "FALSO_VERDADERO",
opciones: opcionesVerdaderoFalso,
};
cb(reactivo);
return;
}
if (tipoReactivo === "VALOR_TEXTUAL") {
const reactivo: IReactivo = {
...reactivoBase,
tipoReactivo: "VALOR_TEXTUAL",
valorTextualCorrecto: valorTextualCorrecto,
similitudValorTextual: similitudValorTextual,
};
cb(reactivo);
return;
}
if (tipoReactivo === "VALOR_NUMERICO") {
const reactivo: IReactivo = {
...reactivoBase,
tipoReactivo: "VALOR_NUMERICO",
valorNumericoCorrecto: valorNumericoCorrecto,
margenValorNumerico: margenValorNumerico,
};
cb(reactivo);
return;
}
if (tipoReactivo === "ENSAYO") {
const reactivo: IReactivo = {
...reactivoBase,
tipoReactivo: "ENSAYO",
};
cb(reactivo);
}
} catch (error: any) {
setErrorMessage(error.message);
}
};
return {
setOpcionFalsoVerdadero,
handleChangeOpcionFalsoVerdadero,
handleAddOpcionMultiple,
handleDeleteOpcionMultiple,
loadDefaultValues,
resetReactivoForm,
handleSubmit,
};
};
|
package ilya.chistousov.countthefood.core.basefragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.IllegalArgumentException
abstract class BaseFragment<VB : ViewBinding>
(private val bindingInflater: (inflater: LayoutInflater) -> VB) : Fragment() {
private var _binding: VB? = null
val binding: VB
get() = _binding as VB
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = bindingInflater.invoke(inflater)
if (_binding == null) {
throw IllegalArgumentException("binding cannot be null")
}
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
import { useMutation, useQuery } from '@apollo/client';
import { Button } from 'semantic-ui-react';
import { FOLLOW_USER, IS_FOLLOWING, UNFOLLOW_USER } from '../../../gql/follow';
import { IsFollowingQuery, User } from '../../../interfaces';
import './profileHeader.scss';
interface Props {
user: User;
authUser: User | null;
handleModal: ( type: "avatar" | "settings" ) => void;
}
export const ProfileHeader = ( { user, authUser, handleModal }: Props ) => {
const [ followUser ] = useMutation( FOLLOW_USER );
const [ unfollowUser ] = useMutation( UNFOLLOW_USER );
const { data, loading, refetch } = useQuery<IsFollowingQuery>( IS_FOLLOWING, {
variables: {
username: user.username
}
} );
const followButton = () => {
if ( data?.isFollowing ) {
return (
<Button onClick={ onUnfollow } className="btn-danger">
Dejar de seguir
</Button>
);
}
return (
<Button onClick={ onFollow } className="btn-action">
Seguir
</Button>
);
};
const checkAuthUser = () => {
if ( authUser?.username === user?.username ) {
return (
<Button onClick={ () => handleModal( 'settings' ) }>
Ajustes
</Button>
);
}
return (
!loading && followButton()
);
};
const onFollow = async () => {
try {
await followUser( {
variables: {
username: user.username
}
} );
refetch();
} catch ( error ) {
console.log( error );
}
};
const onUnfollow = async () => {
try {
await unfollowUser( {
variables: {
username: user.username
}
} );
refetch();
} catch ( error ) {
console.log( error );
}
};
return (
<div className="profile-header">
<h2>{ user.username }</h2>
{
authUser
? checkAuthUser()
: <></>
}
</div>
);
};
|
# Creación de builders en clases TO
Para la creación de los builders que se debe seleccionar el nombre de la clase To con el botón derecho del mouse,
seleccionar la opción

# Microservicio ubicación
# Colección de postman
En la carpeta docs/postman, se encuentra la colección de postman con los ejemplos de uso del api rest para el microservicio ubicación.
> docs/postman/EXPEL.postman_collection.json
# Resolución de erroes
En el caso de tener el siguiente error:
```log
Name:dataSource, Connection:3, Time:8, Success:False
Type:Prepared, Batch:False, QuerySize:1, BatchSize:0
Query:["select paisentity0_.[id_pais] as id_pais1_1_, paisentity0_.[nacionalidad] as nacional2_1_, paisentity0_.[nombre_pais] as nombre_p3_1_ from [CLEX1].[pais] paisentity0_ where paisentity0_.[id_pais]=?"]
Params:[(ECU)]
2023-03-27 09:36:42 - SQL Error: 207, SQLState: S0001
2023-03-27 09:36:42 - El nombre de columna 'id_pais' no es válido.
2023-03-27 09:36:42 - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
com.microsoft.sqlserver.jdbc.SQLServerException: El nombre de columna 'id_pais' no es válido.
````
Se debe tener la siguiente configuración en el archivo application.yml, basada en los siguientes links:
* https://thorben-janssen.com/naming-strategies-in-hibernate-5/
* https://www.baeldung.com/hibernate-field-naming-spring-boot
```properties
spring=
jpa=
hibernate=
naming=
physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
dialect=org.hibernate.dialect.SQLServerDialect
properties=
hibernate=
default_schema='CLEX1'
globally_quoted_identifiers=true
physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
```
Agregar esa configuración en el archivo application.yml cambiará las estrategias de nomenclatura de Hibernate para que sean compatibles con JPA. La configuración que has establecido en el archivo application.yml hará lo siguiente:
* PhysicalNamingStrategyStandardImpl: Hibernate utilizará esta estrategia para convertir los nombres de las tablas y columnas en la base de datos a nombres de identificadores físicos (nombres reales de tablas y columnas en la base de datos) sin cambiarlos.
* ImplicitNamingStrategyJpaCompliantImpl: Hibernate utilizará esta estrategia para generar nombres de identificadores implícitos (cuando no se especifica un nombre explícito mediante anotaciones) de acuerdo con las reglas de JPA.
Si esta configuración ha resuelto el problema del error org.hibernate.AnnotationException: No identifier specified for entity, entonces significa que el problema estaba relacionado con las estrategias de nomenclatura en lugar de la configuración de la entidad. Esto puede suceder si Hibernate estaba utilizando una estrategia de nomenclatura diferente y no podía reconocer correctamente los identificadores de la entidad y sus atributos.
Con esta solución, la aplicación debe funcionar correctamente, y las entidades deben mapearse correctamente a las tablas y columnas de la base de datos.
# GIT
## Eliminar las carpetas y archivos que no deberían estar en el repositorio de Git
Para eliminar las carpetas y archivos que no deberían estar en el repositorio de Git y agregar un archivo .gitignore para evitar que vuelvan a subirse, sigue estos pasos:
Primero, crea un archivo .gitignore en la raíz de tu proyecto si aún no lo has hecho. Puedes hacerlo con un editor de texto o desde la línea de comandos, por ejemplo:
```bash
touch .gitignore
```
Abre el archivo .gitignore y agrega las carpetas y archivos que deseas ignorar. En tu caso, serían las siguientes:
```txt
target/
.idea/
*.iml
```
Guarda y cierra el archivo .gitignore.
Ahora, necesitas eliminar las carpetas y archivos del repositorio de Git sin eliminarlos de tu sistema local. Puedes hacer esto con el siguiente comando:
```bash
git rm -r --cached target/ .idea/ *.iml
```
A continuación, agrega el archivo .gitignore al repositorio y haz un commit con los cambios:
```bash
git add .gitignore
git commit -m "Eliminadas carpetas innecesarias y agregado .gitignore"
```
Por último, sube los cambios al repositorio remoto:
```bash
git push
```
Con estos pasos, habrás eliminado las carpetas y archivos innecesarios del repositorio de Git y asegurado que no se vuelvan a subir en el futuro gracias al archivo .gitignore.
|
using Microsoft.Build.Framework;
using Microsoft.Extensions.Logging;
using System.Collections;
using ILogger = Microsoft.Build.Framework.ILogger;
namespace Belp.Build.Testing.Loggers;
/// <summary>
/// Captures events from MSBuild as <see cref="Diagnostic"/>s.
/// </summary>
public sealed class MSBuildDiagnosticLogger : ILogger
{
private sealed class DiagnosticAggregateList : IReadOnlyList<Diagnostic>
{
private readonly IReadOnlyList<Diagnostic> _errors;
private readonly IReadOnlyList<Diagnostic> _warnings;
public Diagnostic this[int index]
{
get
{
return index < _errors.Count
? _errors[index]
: _warnings[index - _errors.Count]
;
}
}
public int Count => _errors.Count + _warnings.Count;
public DiagnosticAggregateList(MSBuildDiagnosticLogger logger)
{
_errors = logger._errors;
_warnings = logger._warnings;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<Diagnostic> GetEnumerator()
{
for (int i = 0; i < _errors.Count; i++)
{
yield return _errors[i];
}
for (int i = 0; i < _warnings.Count; i++)
{
yield return _warnings[i];
}
}
}
private IEventSource _eventSource = null!;
/// <inheritdoc />
string? ILogger.Parameters
{
get => null;
set
{
}
}
LoggerVerbosity ILogger.Verbosity
{
get => LogLevel.ToLoggerVerbosity();
set => LogLevel = value.ToLogLevel();
}
/// <summary>
/// Gets or sets the minimum level of logged messages.
/// </summary>
public LogLevel LogLevel { get; set; } = LogLevel.Information;
private readonly List<Diagnostic> _errors = [];
/// <summary>
/// Gets a list of errors catched by the logger.
/// </summary>
public IReadOnlyList<Diagnostic> Errors => _errors.AsReadOnly();
private readonly List<Diagnostic> _warnings = [];
/// <summary>
/// Gets a list of warnings catched by the logger.
/// </summary>
public IReadOnlyList<Diagnostic> Warnings => _warnings.AsReadOnly();
/// <summary>
/// Gets a list of diagnostics(errors, warnings, and messages) catched by the logger.
/// </summary>
public IReadOnlyList<Diagnostic> Diagnostics => new DiagnosticAggregateList(this);
/// <summary>
/// Raised when an error is captured by the logger.
/// </summary>
public event DiagnosticEventHandler? OnError;
/// <summary>
/// Raised when a warning is captured by the logger.
/// </summary>
public event DiagnosticEventHandler? OnWarning;
/// <summary>
/// Raised when a message is captured by the logger.
/// </summary>
public event DiagnosticEventHandler? OnMessage;
/// <summary>
/// Raised when any diagnostic is captured by the logger.
/// </summary>
public event DiagnosticEventHandler? OnDiagnostic;
/// <inheritdoc />
public void Initialize(IEventSource eventSource)
{
_eventSource = eventSource;
eventSource.ErrorRaised += OnErrorRaised;
eventSource.WarningRaised += OnWarningRaised;
eventSource.MessageRaised += OnMessageRaised;
}
/// <inheritdoc />
public void Shutdown()
{
_eventSource.ErrorRaised -= OnErrorRaised;
_eventSource.WarningRaised -= OnWarningRaised;
_eventSource.MessageRaised -= OnMessageRaised;
}
/// <summary>
/// Runs when an error is raised.
/// </summary>
/// <param name="sender">The error's sender.</param>
/// <param name="e">The raised error.</param>
private void OnErrorRaised(object sender, BuildErrorEventArgs e)
{
var diagnostic = new Diagnostic(
LogLevel.Error,
e.Code,
e.Message,
e.File,
new TextSpan(
new TextSpan.Position(e.LineNumber, e.ColumnNumber),
new TextSpan.Position(e.EndLineNumber, e.EndColumnNumber)
),
e.ProjectFile
);
_errors.Add(diagnostic);
OnError?.Invoke(diagnostic);
OnDiagnostic?.Invoke(diagnostic);
}
/// <summary>
/// Runs when a warning is raised.
/// </summary>
/// <param name="sender">The warning's sender.</param>
/// <param name="e">The raised warning.</param>
private void OnWarningRaised(object sender, BuildWarningEventArgs e)
{
var diagnostic = new Diagnostic(
LogLevel.Warning,
e.Code,
e.Message,
e.File,
new TextSpan(
new TextSpan.Position(e.LineNumber, e.ColumnNumber),
new TextSpan.Position(e.EndLineNumber, e.EndColumnNumber)
),
e.ProjectFile
);
_warnings.Add(diagnostic);
OnWarning?.Invoke(diagnostic);
OnDiagnostic?.Invoke(diagnostic);
}
/// <summary>
/// Runs when a message is raised.
/// </summary>
/// <param name="sender">The message's sender.</param>
/// <param name="e">The raised message.</param>
/// <exception cref="NotSupportedException">The message has an unsupported importance level.</exception>
private void OnMessageRaised(object sender, BuildMessageEventArgs e)
{
var diagnostic = new Diagnostic(
e.Importance switch
{
MessageImportance.High => LogLevel.Information,
MessageImportance.Normal => LogLevel.Debug,
MessageImportance.Low => LogLevel.Trace,
var importance => throw new NotSupportedException($"Unsupported importance level {importance}."),
},
e.Code,
e.Message,
e.File,
new TextSpan(
new TextSpan.Position(e.LineNumber, e.ColumnNumber),
new TextSpan.Position(e.EndLineNumber, e.EndColumnNumber)
),
e.ProjectFile
);
OnMessage?.Invoke(diagnostic);
OnDiagnostic?.Invoke(diagnostic);
}
}
|
package it.unibs.ingesw;
import java.util.ArrayList;
public class Network implements IDNameGiver{
private ArrayList<Location> locations;
private ArrayList<Transition> transitions;
private ArrayList<Link> netLinks;
private int netId;
private String name;
static int network_id = 0; //Variabile statica che fornisce un id diverso ogni qualvolta si crea una rete
private final int OFFSET = 10000; //Costante che viene sommata all'id di un node nel caso quest'ultimo sia una location
public Network (String name) {
locations = new ArrayList<Location>();
transitions = new ArrayList<Transition>();
netLinks = new ArrayList<Link>();
this.name = name;
this.netId = ++network_id;
}
public void addLocation (String name) {
locations.add(new Location(netId, locations.size()+OFFSET, name));
}
public void addTransition (String name) {
transitions.add(new Transition(netId, transitions.size(), name));
}
public void addLink (Link l) {
netLinks.add(l);
}
public ArrayList<Location> getLocations() {
return locations;
}
public Location getLocation(int i) {
return this.locations.get(i);
}
public void setLocations(ArrayList<Location> locations) {
this.locations = locations;
}
public ArrayList<Transition> getTransitions() {
return transitions;
}
public Transition getTransition(int i) {
return this.transitions.get(i);
}
public void setTransitions(ArrayList<Transition> transitions) {
this.transitions = transitions;
}
public ArrayList<Link> getNetLinks() {
return netLinks;
}
public void setNetLinks(ArrayList<Link> netLinks) {
this.netLinks = netLinks;
}
public int getId() {
return netId;
}
public void setNetId(int netId) {
this.netId = netId;
}
/**
* Produce in uscita la lista delle transizioni con associato un numero
* @return StringBuffer s
*/
public StringBuffer getTransitionsList() {
StringBuffer s = new StringBuffer("");
for (int i = 0; i<transitions.size(); i++) {
s.append(i + ")" + transitions.get(i).getName() + "\n");
}
return s;
}
/**
* Produce in uscita la lista dei posti con associato un numero
* @return StringBuffer s
*/
public StringBuffer getLocationsList() {
StringBuffer s = new StringBuffer("");
for (int i = 0; i<locations.size(); i++) {
s.append(i + ")" + locations.get(i).getName() + "\n");
}
return s;
}
/**
* Produce in uscita la lista dei link
* @return Stringbuffer s
*/
public StringBuffer getLinksList() {
StringBuffer s = new StringBuffer("");
for (int i = 0; i < netLinks.size(); i++) {
s.append(i + ")" + nodeNameFromID(netLinks.get(i).getOrigin()) + "---->" + nodeNameFromID(netLinks.get(i).getDestination())+ "\n");
}
return s;
}
public Transition getLastTransition() {
return transitions.get(transitions.size()-1);
}
public Location getLastLocation() {
return locations.get(locations.size()-1);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* produce in uscita il nome della location o transition associata all'ID fornito in ingresso al metodo
* @param int id
* @return String t.getName()
*/
public String nodeNameFromID(int id) {
for(Location l : locations) {
if(l.getId() == id)
return l.getName();
}
for(Transition t : transitions) {
if(t.getId() == id)
return t.getName();
}
return null;
}
}
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../localization/language_constrants.dart';
import '../../../../utill/color_resources.dart';
import '../../../../utill/custom_themes.dart';
import '../../../../utill/dimensions.dart';
import '../../../../view/basewidget/custom_expanded_app_bar.dart';
import '../../../../view/screen/support/add_ticket_screen.dart';
class IssueTypeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
List<String> issueTypeList = [getTranslated('Website_Problem', context), getTranslated('Partner_request', context), getTranslated('Complaint', context), getTranslated('Info_inquiry', context)];
return CustomExpandedAppBar(
title: getTranslated('support_ticket', context),
isGuestCheck: true,
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Padding(
padding: EdgeInsets.only(top: Dimensions.PADDING_SIZE_LARGE, left: Dimensions.PADDING_SIZE_LARGE),
child: Text(getTranslated('add_new_ticket', context), style: titilliumSemiBold.copyWith(fontSize: 20)),
),
Padding(
padding: EdgeInsets.only(left: Dimensions.PADDING_SIZE_LARGE, bottom: Dimensions.PADDING_SIZE_LARGE),
child: Text(getTranslated('select_your_category', context), style: titilliumRegular),
),
Expanded(child: ListView.builder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.symmetric(horizontal: Dimensions.PADDING_SIZE_LARGE, vertical: Dimensions.PADDING_SIZE_EXTRA_SMALL),
itemCount: issueTypeList.length,
itemBuilder: (context, index) {
return Container(
color: ColorResources.getLowGreen(context),
margin: EdgeInsets.only(bottom: Dimensions.PADDING_SIZE_SMALL),
child: ListTile(
leading: Icon(Icons.query_builder, color: ColorResources.getPrimary(context)),
title: Text(issueTypeList[index], style: robotoBold),
onTap: () {
Navigator.pushReplacement(context, CupertinoPageRoute(builder: (_) => AddTicketScreen(type: issueTypeList[index])));
},
),
);
},
)),
]),
);
}
}
|
package chaos.common.spell;
import chaos.board.Cell;
import chaos.board.World;
import chaos.common.AbstractGenerator;
import chaos.common.Actor;
import chaos.common.Castable;
import chaos.common.Caster;
import chaos.common.State;
import chaos.common.TargetFilter;
import chaos.common.wizard.Wizard;
import chaos.common.inanimate.MagicWood;
import chaos.util.CastUtils;
import chaos.util.CellEffectEvent;
import chaos.util.CellEffectType;
import chaos.util.PolycellEffectEvent;
import java.util.HashSet;
import java.util.Set;
/**
* Mass morph.
*
* @author Sean A. Irvine
* @author William S. Irvine
*/
public class MassMorph extends Castable implements TargetFilter {
@Override
public int getCastFlags() {
return CAST_LIVING | CAST_INANIMATE | CAST_GROWTH;
}
@Override
public int getCastRange() {
return MAX_CAST_RANGE;
}
@Override
public void cast(final World world, final Caster caster, final Cell cell, final Cell casterCell) {
if (world != null && cell != null && caster != null) {
// Need to compute the player number of the target. If this cannot be done
// then we silently exit, since it should not be possible to cast this
// spell on a non-actor.
final Actor target = cell.peek();
if (target != null) {
final int player = target.getOwner();
// Compute set of cells to be affected. This might or might not include
// the cell the user clicked when casting the spell.
final HashSet<Cell> affected = new HashSet<>();
for (int i = 0; i < world.size(); ++i) {
final Cell c = world.getCell(i);
final Actor a = c.peek();
if (a != null
&& !(a instanceof Wizard)
&& !(a instanceof AbstractGenerator)
&& a.getState() == State.ACTIVE
&& c.getMount() == null
&& c.peek().getOwner() == player) {
affected.add(c);
}
}
// Normally the inserted trees will belong to the player who originally
// owned the target. But sometimes that player could actually be dead,
// if a sleeping target was chosen. In this case, the new trees will
// belong to the caster. This fixes Bug#264.
final int castOwner = caster.getOwner();
final int newOwner;
if (player == Actor.OWNER_NONE) {
newOwner = castOwner;
} else {
final Wizard wizTarget = world.getWizardManager().getWizard(player);
newOwner = wizTarget != null && wizTarget.getState() != State.ACTIVE ? castOwner : player;
}
if (!affected.isEmpty()) {
// At least one candidate cell was found. Perform an effect on all
// selected cells and carry out the animation.
world.notify(new PolycellEffectEvent(affected, CellEffectType.TWIRL));
for (final Cell c : affected) {
// Bug#309 case of growths with things underneath, need to pop entire content
while (c.pop() != null) {
// do nothing
}
final MagicWood mw = new MagicWood();
mw.setOwner(newOwner);
c.push(mw);
}
// And redraw all the cells with the new forms.
world.notify(new PolycellEffectEvent(affected, CellEffectType.REDRAW_CELL));
} else if (casterCell != null) {
// Try to indicate spell failure in the case of no affected.
casterCell.notify(new CellEffectEvent(casterCell, CellEffectType.SPELL_FAILED));
}
}
}
}
@Override
public void filter(final Set<Cell> targets, final Caster caster, final World world) {
CastUtils.keepMostFrequentOwner(targets, world, world.getTeamInformation().getTeam(caster));
}
}
|
<?php
/**
* Plugin Name: Blockmania
* Description: A collection of editor blocks.
* Version: 0.1.0
* Author: Tyler Kowalchuk
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: tk-blockmania
*
* @package tk-blockmania
*/
/**
* Registers all block assets so that they can be enqueued through the block editor
* in the corresponding context.
*
* @see https://developer.wordpress.org/block-editor/tutorials/block-tutorial/applying-styles-with-stylesheets/
*/
function tk_blockmania_tk_blockmania_block_init() {
$dir = __DIR__;
$script_asset_path = "$dir/build/index.asset.php";
if ( ! file_exists( $script_asset_path ) ) {
throw new Error(
'You need to run `npm start` or `npm run build` for the "tk-blockmania/tk-blockmania" block first.'
);
}
$index_js = 'build/index.js';
$script_asset = require( $script_asset_path );
wp_register_script(
'tk-blockmania-tk-blockmania-block-editor',
plugins_url( $index_js, __FILE__ ),
$script_asset['dependencies'],
$script_asset['version']
);
wp_set_script_translations( 'tk-blockmania-tk-blockmania-block-editor', 'tk-blockmania' );
$editor_css = 'build/index.css';
wp_register_style(
'tk-blockmania-tk-blockmania-block-editor',
plugins_url( $editor_css, __FILE__ ),
array(),
filemtime( "$dir/$editor_css" )
);
$style_css = 'build/style-index.css';
wp_register_style(
'tk-blockmania-tk-blockmania-block',
plugins_url( $style_css, __FILE__ ),
array(),
filemtime( "$dir/$style_css" )
);
register_block_type(
'tk-blockmania/tk-blockmania',
array(
'editor_script' => 'tk-blockmania-tk-blockmania-block-editor',
'editor_style' => 'tk-blockmania-tk-blockmania-block-editor',
'style' => 'tk-blockmania-tk-blockmania-block',
)
);
}
add_action( 'init', 'tk_blockmania_tk_blockmania_block_init' );
|
import React, {useEffect, useRef, useState} from 'react';
import {useParams} from 'react-router-dom';
import {useClient} from "../hooks/useClient";
import ChatMessages from "../components/ChatMessages";
import Form, {FormRequestInput} from "../components/Form";
import BaseLayout from "./BaseLayout";
import {RoomResponse} from "../client/messages";
export default function ChatRoom() {
const {courier} = useClient();
const {id} = useParams();
const [text, setText] = useState<string>("");
const [room, setRoom] = useState<RoomResponse>();
const messagesEndRef: React.Ref<any> = useRef(null);
const scrollToBottom = (opts?: ScrollIntoViewOptions) => messagesEndRef.current?.scrollIntoView(opts);
const afterSubmit = async () => {
setText("");
};
useEffect(() => {
courier.rooms.get(id || "").then(room => setRoom(room))
}, [id]);
return (
<BaseLayout title={room?.name || ""}>
<div className={"Chat"}>
<div className={"chat-header"}>
<button onClick={async () => await navigator.share({
title: "GroupMe Clone",
text: "Chat with me in " + room?.name,
url: process.env.REACT_APP_DOMAIN + "/join" + room?.id
})}>
Share
</button>
</div>
<div className={"chat-top"}></div>
{
room ?
<ChatMessages scrollToBottom={scrollToBottom} room={room}/> :
<></>
}
<div ref={messagesEndRef} className={"chat-bottom"}></div>
<div className={"text-container"}>
<Form id={"message-input-" + id}
className={"message-form"}
action={"/message"}
method={"POST"}
inputs={[
{
displayName: "message",
name: "message",
type: "textarea",
value: text,
setValue: setText,
},
{
displayName: "roomId",
name: "roomId",
type: "hidden",
value: id || "",
}
]}
submit={(form: FormRequestInput) => courier.messages.send({
message: form['message'],
roomId: form['roomId']
})
}
afterSubmit={afterSubmit}/>
</div>
</div>
</BaseLayout>
)
}
|
/*
wdb - weather and water data storage
Copyright (C) 2012 met.no
Contact information:
Norwegian Meteorological Institute
Box 43 Blindern
0313 OSLO
NORWAY
E-mail: [email protected]
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA
*/
#ifndef STLOADERCONFIGURATION_H_
#define STLOADERCONFIGURATION_H_
// PROJECT INCLUDES
#include <wdbConfiguration.h>
// SYSTEM INCLUDES
#include <string>
#include <boost/program_options/positional_options.hpp>
namespace wdb { namespace load {
/**
* STLoaderConfiguration handles the options
* of the station laoder application.
*
* @see WdbConfiguration
*/
class STLoaderConfiguration : public WdbConfiguration
{
public:
// LIFECYCLE
/**
* Default Constructor
*/
explicit STLoaderConfiguration( const std::string & defaultDataProvider = "");
/**
* Default Destructor
*/
virtual ~STLoaderConfiguration();
/** Container for input options
*/
struct InputOptions
{
std::vector<std::string> file;
};
/** Container for output options
*/
struct OutputOptions
{
bool list;
};
/** Container for general loader options
*/
struct STLoadingOptions
{
// bool loadPlaceDefinition;
// std::string dataProvider; ///< The data provider name.
// /**
// * In case you use the LoaderDatabaseConnection, this value will be
// * chosen automatically if dataProvider is empty
// */
std::string defaultDataProvider;
std::string stdatabase; /// < station database name.
std::string sthost; /// < station database host.
std::string stuser; /// < station database user.
std::string stpass; /// < station database password.
int stport; /// < station database port.
// std::string placeName; /// < The place name.
// std::string referenceTime; /// < Reftime.
// std::string valueParameter; /// < Value Parameter.
// std::string levelParameter; /// < Level Parameter.
// int dataVersion; /// The Data Version
// int confidenceCode; /// Confidence Code
std::string nameSpace; /// what namespace to use
/**
* Generate and return a pq compatible database connection string using
* the options given for the program.
*/
std::string pqDatabaseConnection() const;
std::string psqlDatabaseConnection() const;
};
/** Get the input options
* @return The input options
*/
const InputOptions & input() const { return input_; }
/** Get the output options
* @return The output options
*/
const OutputOptions & output() const { return output_; }
/** Get the general loading options
*/
const STLoadingOptions & loading() const { return loading_; }
/** Get the positional options of the loader
* Used for returning the file name
* @return The positional options
*/
boost::program_options::positional_options_description & positionalOptions() { return positionalOptions_; }
protected:
using WdbConfiguration::parse_;
/**
* Parse arguments from a given file
* @param argc Number of command line arguments
* @param argv The actual command line arguments
*/
virtual void parse_( int argc, char ** argv );
/** Commands to be performed after parsing arguments
*/
// virtual void postParseHook();
/// Positional options
boost::program_options::positional_options_description positionalOptions_;
/// Input options
InputOptions input_;
/// Output options
OutputOptions output_;
/// loading options
STLoadingOptions loading_;
const std::string defaultDataProvider_;
};
} }
#endif /*STLOADERCONFIGURATION_H_*/
|
$(function(){
// 基于准备好的dom,初始化echarts实例
var echLeft=document.querySelector('.echarts_left')
var echRight=document.querySelector('.echarts_right')
var myChart = echarts.init(echLeft);
//销量的柱状图
// 指定图表的配置项和数据
var option = {
title: {
text: '2018年注册人数'
},
tooltip: {},
legend: {
data:['销量','人数'],
},
xAxis: {
data: ["1月","2月","3月","4月","5月","6月"],
data: ["1月","2月","3月","4月","5月","6月"]
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [175, 121, 256, 98, 167, 242]
},
{
name:'人数',
type:'bar',
data:[200,158,345,198,247,320]
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
//右边品牌的饼状图
// 指定图表的配置项和数据
var myChart2 = echarts.init(echRight);
var option2 = {
title : {
text: '热门品牌销售',
subtext: '2018年11月',
x:'center',
textStyle:{
}
},
tooltip : {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient: 'vertical',
left: 'left',
data: ['阿迪','耐克','新百伦','意尔康','回力']
},
series : [
{
name: '热门品牌',
type: 'pie',
radius : '55%',
center: ['50%', '60%'],
data:[
{value:335, name:'阿迪'},
{value:310, name:'耐克'},
{value:234, name:'新百伦'},
{value:135, name:'意尔康'},
{value:1548, name:'回力'}
],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart2.setOption(option2);
});
|
//
// WXBPropertyWrapper.swift
// WXBSwift
//
// Created by WeiXinbing on 2020/8/17.
// Copyright © 2020 bing. All rights reserved.
//
import UIKit
/// 将 String Int Double 解析为 String 的包装器
@propertyWrapper struct WXBString {
public var wrappedValue: String
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
var string: String
do {
string = try container.decode(String.self)
}
catch {
do {
string = String(try container.decode(Int.self))
}
catch {
do {
string = String(try container.decode(Double.self))
}
catch {
string = "" // 如果不想要 String? 可以在此处给 string 赋值 = “”
}
}
}
wrappedValue = string
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/template" id="main">
<div id="box" :class="box">
<p>这是我的{{name}},很高兴认识你!</p>
</div>
</script>
<div id="app">
<!--<component :is="role"></component>-->
<admin :role="name"></admin>
<!-- <span>111</span>-->
<p>{{name}}</p>
<!-- <span>22</span>-->
</div>
<script src="../vue.js"></script>
<script type="text/template" id="child">
<div id="c2">
<h2>child组件</h2>
</div>
</script>
<script>
Vue.component("admin",{
template:"<h2>admin组件</h2>"
})
let vm = new Vue({
el: "#app",
//template: "#main",
data() {
return {
name:"tinaluo",
role:"admin",
r3:"R3"
}
},
components:{
admin:{
props:['role','inner-content'],
template:"<h2>{{role}}</h2>"
}
}
})
</script>
</body>
</html>
|
@import url("https://fonts.googleapis.com/css?family=Raleway:300,500,700");
@import './constants';
/* Global */
* {
box-sizing: border-box;
}
body {
color: #090b08;
margin: 0;
font-family: "Raleway", sans-serif;
font-weight: 300;
background-color: #ecffe9;
}
h1 {
font-size: 1.7em;
font-weight: 700;
line-height: 1.5em;
text-transform: uppercase;
}
h2 {
text-transform: uppercase;
}
h4 {
font-size: 0.8em;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 1px;
}
h6 {
font-weight: 500;
}
a {
text-decoration: none;
color: #090b08;
}
ul {
list-style: none;
}
.btn {
display: inline-block;
padding: 0.5em 1.5em;
border: solid 1px #000;
transition: all 0.3s ease-in;
}
.btn:hover,
.btn:focus {
transform: translate(0px, -2px);
-webkit-box-shadow: 0px 10px 7px -9px rgba(0, 0, 0, 0.75);
-moz-box-shadow: 0px 10px 7px -9px rgba(0, 0, 0, 0.75);
box-shadow: 0px 10px 7px -9px rgba(0, 0, 0, 0.75);
transition: all 0.3s ease-out;
}
form {
display: flex;
}
form input:first-child {
flex: 1 0 80%;
background-color: transparent;
}
form input:last-child {
flex: 1 0 20%;
border-left: 0;
cursor: pointer;
background-color: #c0eea9;
transition: all 0.25s ease;
}
#submit:hover {
background-color: #000;
color: #fff;
transition: all 0.25s ease;
-webkit-box-shadow: 0px 10px 7px -9px rgba(0, 0, 0, 0.75);
-moz-box-shadow: 0px 10px 7px -9px rgba(0, 0, 0, 0.75);
box-shadow: 0px 10px 7px -9px rgba(0, 0, 0, 0.75);
}
input {
padding: 10px;
border: 1px solid #000;
}
/* Pas alleen de onderstaande regels aan */
/* Header */
header {
display: flex;
justify-content: space-around;
position: fixed;
width: 100%;
z-index: 1;
padding: $StandaardPadding;
background-color: $HeaderBackground;
height: 120px;
-webkit-box-shadow: 0px 10px 7px -9px rgba(0, 0, 0, 0.75);
-moz-box-shadow: 0px 10px 7px -9px rgba(0, 0, 0, 0.75);
box-shadow: 0px 10px 7px -9px rgba(0, 0, 0, 0.75);
.brand-logo img {
width: auto;
padding-top: $StandaardPadding;
height: 7.5em;
}
.title {
display: flex;
align-items: center;
text-transform: uppercase;
letter-spacing: 1px;
padding-bottom: 1em;
}
.title.title-right {
justify-content: flex-end;
}
.line {
width: 3em;
height: 1px;
background-color: $HeaderLine;
margin-right: 1em;
}
.line.line-right {
order: 2;
margin-right: 0;
margin-left: 1em;
}
}
/* Hero Section */
.hero {
padding: $StandaardPadding;
display: flex;
height: 100vh;
align-items: center;
background: $BackgroundColor;
.hero-img img {
display: block;
height: auto;
width: 15.5em;
}
.hero-text {
@include Text()
}
}
/* Featured Section */
.featured {
padding: 20px;
.featured .wrapper {
display: flex;
flex-wrap: wrap;
}
#featured .image img {
width: 300px;
}
.text-featured {
@include Text()
}
.text-featured p {
text-align: justify;
padding: $StandaardPadding;
line-height: 1.4em;
}
}
/* About Section */
.about {
background-color: $BackgroundColor;
padding: $StandaardPadding;
.text-about {
@include Text()
}
.text-about p {
text-align: justify;
padding-bottom: 1em;
line-height: 1.4em;
}
.about .wrapper {
display: flex;
}
.video-wrapper {
position: relative;
padding-bottom: 33.25%;
overflow: hidden;
align-self: center;
flex: 2 0 55%;
margin: 1.4em 0;
}
.video-wrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}
/* Contact Section */
.contact {
padding: $StandaardPadding;
.wrapper .contact {
display: flex;
flex-wrap: wrap;
}
.form-wrapper,
.contact-wrapper {
padding: $StandaardPadding;
}
.copy-wrapper {
padding-left: $StandaardPadding;
}
}
|
Machine learning is a field of artificial intelligence that focuses on developing algorithms and models that allow computers to learn from data and make predictions or decisions without being explicitly programmed.
### Key Concepts
- **Training Data**: Algorithms learn from a dataset called training data, which consists of input features and corresponding target outcomes.
- **Learning Process**: Machine learning algorithms identify patterns, relationships, and trends in training data to create predictive models or make decisions.
- **[[generalization]]**: Trained models apply learned patterns to new, unseen data, making predictions or decisions based on this generalization.
### Types of Machine Learning
- **Supervised Learning**: Involves training algorithms on labeled data, where inputs are paired with correct outputs. Common tasks include regression (predicting a continuous value) and classification (assigning labels to categories).
- **Unsupervised Learning**: Algorithms learn from unlabeled data, discovering patterns and structures within the data. Clustering and dimensionality reduction are examples.
- **Semi-Supervised Learning**: Combines labeled and unlabeled data to improve learning efficiency and model accuracy.
- **Reinforcement Learning**: Involves training agents to interact with an environment and learn optimal strategies through rewards and penalties.
## Resources
- [ML cheatsheet glossary](https://ml-cheatsheet.readthedocs.io/en/latest/glossary.html)
- [Google Machine Learning glossary](https://developers.google.com/machine-learning/glossary)
|
import {MdLocationOn} from 'react-icons/md'
import {HiCalendar, HiLogout, HiMinus, HiPlus,HiSearch} from 'react-icons/hi'
import { useEffect, useRef, useState } from 'react'
import useOutsideClick from '../hooks/useOutsideClick'
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { DateRange } from 'react-date-range';
import { format } from 'date-fns';
import { createSearchParams, json, useNavigate, useSearchParams } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux'
import { logout } from '../features/AuthSlice';
import Modal from './Modal';
import {HeartIcon, TrashIcon} from '@heroicons/react/24/outline'
import { getAsyncFavorites ,removeAsyncFavorites} from '../features/FavoriteSlice';
export default function Header(){
const[searchParams,setSearchParams]=useSearchParams()
const[destination,setDestination] = useState(searchParams.get("destination") || "")
const[openOptions,setOpenOptions] = useState(false)
const[options,setOptions] = useState({adult:2,children:1,room:1})
const [date,setDate]= useState([{
startDate: new Date(),
endDate: new Date(),
key: 'selection'
}])
const[openDate,setOpenDate] = useState(false)
const[open,setOpen] = useState(false)
const navigate = useNavigate()
function handleSearch(){
// setSearchParams({date,options,destinaton})
const encodedParams= createSearchParams({
date:JSON.stringify(date),
destination,
options:JSON.stringify(options)
})
setSearchParams(encodedParams)
navigate({
pathname:"/hotels",
search:encodedParams.toString()
})
}
function handleOptions(name,operation){
return(
setOptions((prev)=>{
return(
{
...prev,
[name] : operation== 'inc' ? options[name] + 1 : options[name] - 1
}
)
})
)
}
const { loading, error, users ,isAuthenticated } = useSelector((state) => state.auth)
const dispatch = useDispatch()
const {favorites} = useSelector((state) => state.favorites)
useEffect(()=>{
dispatch(getAsyncFavorites())
},[])
function removeFavorite(item){
dispatch(removeAsyncFavorites(item))
}
const logoutHandler =()=>{
dispatch(logout())
console.log(isAuthenticated);
}
return (
<div className="header">
<Modal title="title" open={open} onOpen={setOpen}>
{favorites && favorites.map((fav)=>{
return (
<div className="list__item" key={fav.id}>
<img src={fav.picture_url.url} />
<h3 className="name">{fav.name}</h3>
<div className="list-item__info info">€ {fav.price} <span>night</span></div>
<button><TrashIcon className='icon red'
onClick={()=> removeFavorite(fav.id)}/>
</button>
</div>
)
})}
</Modal>
<div>
<button className="heart" onClick={()=> setOpen(open => !open)}>
<HeartIcon className='icon' />
<span className='badge'>{favorites.length}</span>
</button>
</div>
<div className="headerSearch">
<div className="headerSearchItem">
<MdLocationOn className='headerIcon locationIcon'/>
<input type='text' placeholder='where to go?' className='headerSearchInput textField'
value={destination} onChange={(e)=> setDestination(e.target.value)}
id='destination' name='destination'
/>
<span className="seperator"></span>
</div>
<div className="headerSearchItem">
<HiCalendar className='headerIcon dateIcon'/>
<div className="dateDropDown" onClick={()=>setOpenDate(!openDate)}>
{`${format(date[0].startDate, "yyyy-MM-dd")} to ${format(date[0].endDate, "yyyy-MM-dd")}` }
</div>
{openDate && <DateRange className='date' minDate={new Date()}
ranges={date} onChange={(item)=>setDate([item.selection])} />}
<span className="seperator"></span>
</div>
<div className="headerSearchItem">
<div id='optionDropDown' onClick={()=> setOpenOptions(!openOptions)}>{options.adult} adult • {options.children} children •{options.room}room</div>
{openOptions && <GuestOptionList options={options} setOpenOptions={setOpenOptions} handleOptions={handleOptions}/>}
<span className="seperator"></span>
</div>
<div className="headerSearchItem">
<button className='headerSearchBtn' onClick={handleSearch}>
<HiSearch className='headerIcon'/>
</button>
</div>
</div>
{isAuthenticated ?(
<div className='logout'>
<span>log out</span>
<button onClick={logoutHandler}><HiLogout className='icon' /></button>
</div>
) : (
<button onClick={()=> navigate('/signup')}>sign up </button>
)
}
</div>
)
}
export function GuestOptionList({options , handleOptions , setOpenOptions}){
const optionsRef = useRef()
useOutsideClick(optionsRef, "optionDropDown" ,()=> setOpenOptions(false))
return(
<div className='guestOptions' ref={optionsRef}>
<OptionItem type="adult" options={options} minLimit={1} handleOptions={handleOptions}/>
<OptionItem type="children" options={options} minLimit={0} handleOptions={handleOptions}/>
<OptionItem type="room" options={options} minLimit={1} handleOptions={handleOptions}/>
</div>
)
}
export function OptionItem({options, type , minLimit , handleOptions}){
return(
<div className='guestOptionItem'>
<span className='optionText'>{type}</span>
<div className='optionCounter'>
<button className='optionCounterBtn' disabled={options[type] <= minLimit}
onClick={()=> handleOptions(type, 'dec')}>
<HiMinus className='icon'/>
</button>
<span className='optionCounterNumber'>{options[type]}</span>
<button className='optionCounterBtn' onClick={()=> handleOptions(type, 'inc')} >
<HiPlus className='icon'/>
</button>
</div>
</div>
)
}
|
import { useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import LoginLight from "../../../assets/images/loginLight.jpg";
import {
AiOutlineMail,
AiOutlineEyeInvisible,
AiOutlineEye,
AiOutlineLock,
AiOutlineMobile
} from "react-icons/ai";
import authService from "../../../services/auth.service";
import LoadingScreen from "../../../assets/LoadingScreen"; // Adjust the path as necessary
import { toast } from "react-toastify";
function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState("");
const fuelUser = authService.getCurrentFuelStation();
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
if (fuelUser) {
navigate('/seller/')
}
}, [fuelUser])
useEffect(() => {
// Simulate a loading delay
const timer = setTimeout(() => {
setIsLoading(false);
}, 2000); // Adjust the timeout as needed
return () => clearTimeout(timer);
}, []);
const handleLogin = async (e) => {
e.preventDefault();
try {
await authService.fuelStationLogin(email, password).then(
(response) => {
toast.success("Login Successful")
navigate("/seller/")
},
(error) => {
toast.error(error.response.data.message);
}
);
} catch (err) {
console.log(err);
}
}
return (
<>
{isLoading ? (
<LoadingScreen />
) : (
<div className="w-screen h-screen flex justify-center items-center bg-cover bg-center"
style={{ backgroundImage: `url(${LoginLight})` }}>
<div className="bg-black bg-opacity-75 p-10 rounded-lg">
<div className="header">
<h1 className="text-center text-[54px]">Seller Login</h1>
<p className="text-center text-[14px]">Login with your email and password</p><br></br><br></br>
</div>
<form className="w-full max-w-sm" onSubmit={handleLogin}>
<div className="md:flex md:items-center mb-6">
<div className="md:w-1/3">
<label
className="block text-white font-bold md:text-right mb-1 md:mb-0 pr-4"
htmlFor="inline-full-name"
>
Email
</label>
</div>
<div className="md:w-2/3">
<input
className="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500"
id="inline-full-name"
type="email"
value={email}
required
onChange={(e) => {
setEmail(e.target.value)
}}
placeholder="[email protected]"
/>
</div>
</div>
<div className="md:flex md:items-center mb-6">
<div className="md:w-1/3">
<label
className="block text-white font-bold md:text-right mb-1 md:mb-0 pr-4"
htmlFor="inline-password"
>
Password
</label>
</div>
<div className="md:w-2/3 relative flex flex-row">
<input
className="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 pr-7 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500"
id="inline-password"
type={`${(showPassword) ? "text" : "password"}`}
placeholder="******************"
minLength={8}
required
onChange={(e) => {
setPassword(e.target.value)
}}
/>
{showPassword ? (
<AiOutlineEyeInvisible className="absolute top-3 right-2 text-xl text-black"
onClick={() => {
setShowPassword(false)
}}/>
) : (
<AiOutlineEye className="absolute top-3 right-2 text-xl text-black"
onClick={() => {
setShowPassword(true)
}}/>
)
}
</div>
</div>
<div className="actions w-full flex flex-col gap-4">
<button
className="bg-[#fe6f2b] hover:bg-[#F59337] text-white font-bold py-2 px-4 rounded-full"
>
Login
</button>
<button
className="bg-transparent border border-[#fe6f2b] hover:bg-[#F59337] text-white font-bold py-2 px-4 rounded-full"
onClick={((e) => {
e.preventDefault();
navigate('../register')
})}
>
Sign Up
</button>
<button
className="bg-transparent mb-5 border border-[#fe6f2b] hover:bg-[#F59337] text-white font-bold py-2 px-4 rounded-full"
onClick={((e) => {
e.preventDefault();
navigate('/user/')
})}
>
User
</button>
</div>
</form>
</div>
</div>
)}
</>
);
}
export default Login;
|
#include <SFML/Graphics.hpp>
#include <iostream>
#include <fstream>
#include <memory>
class DShape
{
public:
std::shared_ptr<sf::Shape> shape;
float x = 0.0f, y = 0.0f;
float speedX = 0.0f, speedY = 0.0f;
sf::Text text;
DShape(float x, float y, float speedX, float speedY)
: x(x) ,y(y)
, speedX(speedX) , speedY(speedY)
{
}
};
int main()
{
// List of all shapes
std::vector<DShape> shapes;
// Load in from config file
std::ifstream fin("config.txt");
std::string configType;
// Get window parameters from the config file
int wWidth = 400;
int wHeight = 400;
if (fin >> configType)
{
fin >> wWidth >> wHeight;
}
else
{
std::cerr << "Could not load text from config.txt" << std::endl;
exit(-1);
}
// Set up window with parameters
sf::RenderWindow window(sf::VideoMode(wWidth, wHeight), "My Window");
window.setVerticalSyncEnabled(true);
window.setFramerateLimit(60);
// Get text parameters from config file
std::string fontFilePath;
int fontSize = 0, fontR = 0, fontG = 0, fontB = 0;
if (fin >> configType)
{
fin >> fontFilePath >> fontSize >> fontR >> fontG >> fontB;
}
// Apply parameters to font
sf::Font font;
if (!font.loadFromFile(fontFilePath))
{
std::cerr << "Could not load font from file" << std::endl;
exit(-1);
}
sf::Color fontColor = sf::Color(fontR, fontG, fontB);
// Load in all the shapes from the config file
while (fin >> configType)
{
std::string name = "";
float x = 0.0f, y = 0.0f;
float speedX = 0.0f, speedY = 0.0f;
int r = 0, g = 0, b = 0;
if (configType == "Rectangle")
{
float width = 0.0f, height = 0.0f;
fin >> name >> x >> y >> speedX >> speedY >> r >> g >> b >> width >> height;
DShape rectangle(x, y, speedX, speedY);
rectangle.shape = std::make_shared<sf::RectangleShape>(sf::Vector2f(width, height));
rectangle.shape->setFillColor(sf::Color(r, g, b));
// initialize text and set its color
sf::Text text = sf::Text(name, font, fontSize);
text.setFillColor(fontColor);
// move the origin of the text to the center to make my life easier
sf::FloatRect textBounds = text.getLocalBounds();
text.setOrigin(sf::Vector2f(textBounds.left + textBounds.width / 2,
textBounds.top + textBounds.height / 2));
rectangle.text = text;
shapes.push_back(rectangle);
}
else if (configType == "Circle")
{
float radius;
fin >> name >> x >> y >> speedX >> speedY >> r >> g >> b >> radius;
DShape circle(x, y, speedX, speedY);
circle.shape = std::make_shared<sf::CircleShape>(radius);
circle.shape->setFillColor(sf::Color(r, g, b));
// initialize text and set its color
sf::Text text = sf::Text(name, font, fontSize);
text.setFillColor(fontColor);
// move the origin of the text to the center to make my life easier
sf::FloatRect textBounds = text.getLocalBounds();
text.setOrigin(sf::Vector2f(textBounds.left + textBounds.width / 2,
textBounds.top + textBounds.height / 2));
circle.text = text;
shapes.push_back(circle);
}
}
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered
// since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
{
window.close();
return 0;
}
}
// update shapes and text
for (auto& shape : shapes)
{
sf::FloatRect bounds = shape.shape->getLocalBounds();
// move
shape.x += shape.speedX;
shape.y += shape.speedY;
// bounce
if (shape.x < 0 || shape.x + bounds.width > wWidth)
{
shape.speedX *= -1;
}
if (shape.y < 0 || shape.y + bounds.height > wHeight)
{
shape.speedY *= -1;
}
shape.shape->setPosition(sf::Vector2f(shape.x, shape.y));
// update text position after moving the shape
shape.text.setPosition(sf::Vector2f(shape.x + bounds.width / 2, shape.y + bounds.height / 2));
}
// clear the window with black color
window.clear(sf::Color::Black);
// draw everything here
for (auto& shape : shapes)
{
window.draw(*shape.shape);
window.draw(shape.text);
}
// end the current frame
window.display();
}
return 0;
}
|
const { Form, Button , Container, Row, Col, Table, ToggleButton, ToggleButtonGroup, Card, Alert} = ReactBootstrap;
const maxEnergy = 2000;
const minEnergy = 250
function PeriodicTablePage() {
const [selectedElement, setSelectedElement] = React.useState(" ");
return(
<div>
<PeriodicTable selectedElement={selectedElement} setSelectedElement={setSelectedElement}/>
{/* <br></br>
<Filters /> */}
<br></br>
<EdgeInfo element={selectedElement}/>
</div>
);
}
function PeriodicTable({selectedElement, setSelectedElement}) {
const handleClick = (symbol) => {
setSelectedElement(symbol);
};
return (
<div>
<link rel="stylesheet" href="./periodicTable.css" type="text/css"/>
<div className="grid-container">
{elements.map((element, index) => {
var classInfo = "element element-"+element.z
classInfo += element.availability == "fullK" ? ' availabilityKFull' : ''
classInfo += element.availability == "fullL" ? ' availabilityLFull' : ''
classInfo += element.availability == "fullM" ? ' availabilityMFull' : ''
classInfo += element.availability == "partialK" ? ' availabilityPartialK' : ''
classInfo += element.availability == "partialL" ? ' availabilityPartialL' : ''
classInfo += element.availability == "partialM" ? ' availabilityPartialM' : ''
classInfo += selectedElement == element.symbol ? ' selectedElement' : ''
return (
<div className={classInfo} key={element.z} onClick={() => handleClick(element.symbol)} >{element.symbol}</div>
)
})}
</div>
</div>
);
}
function Filters() {
const [value, setValue] = React.useState(["K", "L2","L3"]);
const handleChange = (val) => setValue(val);
return (
<div>
{/* <ToggleButton id="tbg-btn-1" value={"K"}> K </ToggleButton> */}
<ToggleButtonGroup type="checkbox" value={value} onChange={handleChange}>
<ToggleButton id="tbg-btn-1" variant="outline-primary" value={"K"}> K </ToggleButton>
</ToggleButtonGroup>
<ToggleButtonGroup type="checkbox" value={value} onChange={handleChange}>
<ToggleButton id="tbg-btn-2" variant="outline-primary" value={"L1"}> L1 </ToggleButton>
<ToggleButton id="tbg-btn-3" variant="outline-primary" value={"L2"}> L2 </ToggleButton>
<ToggleButton id="tbg-btn-4" variant="outline-primary" value={"L3"}> L3 </ToggleButton>
</ToggleButtonGroup>
</div>
);
}
function EdgeInfo( {element} ) {
const kEdges = edges.filter(item => (item.element==element) && (item.edge.startsWith('K')));
const lEdges = edges.filter(item => (item.element==element) && (item.edge.startsWith('L')));
const mEdges = edges.filter(item => (item.element==element) && (item.edge.startsWith('M')));
return (
<Container>
<Row>
{kEdges.length >0 ? <Col md={4} xs={12}><EdgeTable selectedEdges={kEdges} /></Col> : null }
{lEdges.length >0 ? <Col md={4} xs={12}><EdgeTable selectedEdges={lEdges} /></Col> : null }
{mEdges.length >0 ? <Col md={4} xs={12}><EdgeTable selectedEdges={mEdges} /></Col> : null }
</Row>
</Container>
);
}
function EdgeTable( {selectedEdges} ) {
const minEnergyCP = 380;
const minEnergyLH = 250;
const minEnergyLV = 500;
const maxEnergyCP = 2000;
const maxEnergyLH = 2000;
const maxEnergyLV = 2000;
return (
<div>
<Table striped bordered hover size="sm">
<thead>
<tr>
<th style={{width: "33%"}}>Edge</th>
<th style={{width: "33%"}}>Energy</th>
<th style={{width: "33%"}}>Availability</th>
</tr>
</thead>
<tbody>
{selectedEdges.map((edge, index) => {
var availability = "";
availability += ((edge.energy >= minEnergyCP) & (edge.energy <= maxEnergyCP)) ? "CP " : ""
availability += ((edge.energy >= minEnergyLH) & (edge.energy <= maxEnergyLH)) ? "LH " : ""
availability += ((edge.energy >= minEnergyLV) & (edge.energy <= maxEnergyLV)) ? "LV " : ""
return (
<tr key={index} >
<td> {edge.element} {edge.edge} </td>
<td> {edge.energy} eV </td>
<td> {availability} </td>
</tr>
)
})}
</tbody>
</Table>
</div>
);
}
|
<div class="d-none" id="docs-npm">
<h1>NPM</h1>
<p><span class="fw-bold">npm</span> is two things: it is an online repository for publishing open-source Node.js projects. It is also a command-line utility for interacting with repositories that helps in package installation, version management, and dependency management. A large amount of Node.js libraries and applications are published on npm. These applications can be searched for on <a href="https://www.npmjs.com/" target="_blank">https://www.npmjs.com/</a>. Once you have a package you want to install, it can be installed with a single command-line command. <span class="fw-bold">npm install {package-name}</span></p>
<br>
<p>For example let's install the express framework. To do so we run <span class="fw-bold">npm install express</span>. The specified module will be installed in the <span class="fw-bold">./node_modules/</span> folder. Once installed to your <span class="fw-bold">node_modules</span> folder, you'll be able to use <span class="fw-bold">require()</span> on them just like any other module.</p>
<br>
<p>Let's look at an example of a global install. All we need to to is add a <span class="fw-bold">-g</span> flag to the command. <span class="fw-bold">npm install express -g</span> This will install the program globally on your system, which means you can access it whitin everywhere in your system.</p>
<br>
<p>Another important use for npm is dependency management. When you have a node project with a package.json file, you can run <span class="fw-bold">npm install</span> from the project root and npm will install all the dependencies listed in the package.json. This makes for example installing a Node.js project from a git repo easier.</p>
<br>
<p>Example:</p>
<div class="code-example">
<pre>git clone https://github.com/cloudhead/vows.git<br>cd vows<br>npm install</pre>
</div>
<br>
<p>After running those commands, you will see a <span class="fw-bold">node_modules</span> folder containing all of the project dependencies specified in the package.json.</p>
<br><br>
</div>
|
// Write your code here
import {Component} from 'react'
import './index.css'
class CoinToss extends Component {
state = {
Total: 0,
Heads: 0,
Tails: 0,
imageURL: 'https://assets.ccbp.in/frontend/react-js/heads-img.png',
}
getHeadOrTail = () => {
const tossResult = Math.floor(Math.random() * 2)
if (tossResult === 0) {
this.setState(prevState => ({
Total: prevState.Total + 1,
Heads: prevState.Heads + 1,
imageURL: 'https://assets.ccbp.in/frontend/react-js/heads-img.png',
}))
} else {
this.setState(prevState => ({
Total: prevState.Total + 1,
Tails: prevState.Tails + 1,
imageURL: 'https://assets.ccbp.in/frontend/react-js/tails-img.png',
}))
}
}
render() {
const headOrTail = this.state
const {Total, Heads, Tails, imageURL} = headOrTail
return (
<div className="bg-container1">
<div className="bg-container2">
<h1 className="heading">Coin Toss Game</h1>
<p className="para">Heads (or) Tails</p>
<img src={imageURL} alt="..." className="coin-img" />
<button type="button" onClick={this.getHeadOrTail}>
Toss Coin
</button>
<div className="THT-container">
<p>Total: {Total}</p>
<p>Heads: {Heads}</p>
<p>Tail: {Tails}</p>
</div>
</div>
</div>
)
}
}
export default CoinToss
|
package controller
import (
"fmt"
"github.com/deanchristt/order-service/dto"
"github.com/deanchristt/order-service/entity"
"github.com/deanchristt/order-service/helper"
"github.com/deanchristt/order-service/service"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
type ProductController interface {
All(context *gin.Context)
FindById(context *gin.Context)
Insert(context *gin.Context)
Update(context *gin.Context)
Delete(context *gin.Context)
}
type productController struct {
productService service.ProductService
jwtService service.JwtService
}
func (p *productController) getCustomerIdByToken(token string) string {
aToken, err := p.jwtService.ValidateToken(token)
if err != nil {
panic(err.Error())
}
claims := aToken.Claims.(jwt.MapClaims)
id := fmt.Sprintf("%v", claims["user_id"])
return id
}
func (p productController) All(context *gin.Context) {
var products = p.productService.All()
res := helper.BuildResponse(true, "OK", products)
context.JSON(http.StatusOK, res)
}
func (p productController) FindById(context *gin.Context) {
id, err := strconv.Atoi(context.Param("id"))
if err != nil {
res := helper.BuildErrorResponse("Param id was not found", err.Error(), helper.EmptyObj{})
context.AbortWithStatusJSON(http.StatusBadRequest, res)
return
}
var product = p.productService.FindById(id)
if (product == entity.Product{}) {
res := helper.BuildErrorResponse("Data not found", "No data with given id", helper.EmptyObj{})
context.JSON(http.StatusNotFound, res)
} else {
res := helper.BuildResponse(true, "OK", product)
context.JSON(http.StatusOK, res)
}
}
func (p productController) Insert(context *gin.Context) {
var productCreatDto dto.ProductCreateDto
errDto := context.ShouldBind(&productCreatDto)
if errDto != nil {
res := helper.BuildErrorResponse("Failed to process request", errDto.Error(), helper.EmptyObj{})
context.JSON(http.StatusBadRequest, res)
} else {
authHeader := context.GetHeader("Authorization")
customerId := p.getCustomerIdByToken(authHeader)
convertCustomerId, err := strconv.Atoi(customerId)
if err == nil {
productCreatDto.CustomerId = convertCustomerId
}
result := p.productService.Insert(productCreatDto)
response := helper.BuildResponse(true, "OK", result)
context.JSON(http.StatusCreated, response)
}
}
func (p productController) Update(context *gin.Context) {
var productUpdateDto dto.ProductUpdateDto
errDto := context.ShouldBind(&productUpdateDto)
if errDto != nil {
res := helper.BuildErrorResponse("Failed to process request", errDto.Error(), helper.EmptyObj{})
context.JSON(http.StatusBadRequest, res)
return
}
authHeader := context.GetHeader("Authorization")
token, errToken := p.jwtService.ValidateToken(authHeader)
if errToken != nil {
panic(errToken.Error())
}
claims := token.Claims.(jwt.MapClaims)
customerId := fmt.Sprintf("%v", claims["user_id"])
path := context.Param("id")
productId, _ := strconv.Atoi(path)
if p.productService.IsAllowedToEdit(customerId, productId) {
id, errID := strconv.Atoi(customerId)
if errID == nil {
productUpdateDto.ID = productId
productUpdateDto.CustomerId = id
}
result := p.productService.Update(productUpdateDto)
response := helper.BuildResponse(true, "OK", result)
context.JSON(http.StatusOK, response)
} else {
response := helper.BuildErrorResponse("You dont have permission", "You are not the owner", helper.EmptyObj{})
context.JSON(http.StatusForbidden, response)
}
}
func (p productController) Delete(context *gin.Context) {
//TODO implement me
var product entity.Product
id, err := strconv.Atoi(context.Param("id"))
if err != nil {
response := helper.BuildErrorResponse("Failed tou get id", "No param id were found", helper.EmptyObj{})
context.JSON(http.StatusBadRequest, response)
}
product.ID = id
authHeader := context.GetHeader("Authorization")
token, errToken := p.jwtService.ValidateToken(authHeader)
if errToken != nil {
panic(errToken.Error())
}
claims := token.Claims.(jwt.MapClaims)
userID := fmt.Sprintf("%v", claims["user_id"])
if p.productService.IsAllowedToEdit(userID, product.ID) {
p.productService.Delete(product)
res := helper.BuildResponse(true, "Deleted", helper.EmptyObj{})
context.JSON(http.StatusOK, res)
} else {
response := helper.BuildErrorResponse("You dont have permission", "You are not the owner", helper.EmptyObj{})
context.JSON(http.StatusForbidden, response)
}
}
func NewProductController(productService service.ProductService, jwtService service.JwtService) ProductController {
return &productController{
productService: productService,
jwtService: jwtService,
}
}
|
'use client';
import Link from 'next/link';
import MenuIcon from '@mui/icons-material/Menu';
import { useEffect, useState } from 'react';
import ShoppingBasketIcon from '@mui/icons-material/ShoppingBasket';
import '@/styles/nav.css'
function Nav() {
const [showMenu, setShowMenu] = useState(false);
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
setIsAdmin(JSON.parse(window.localStorage.getItem('user'))?.admin);
}, []);
return (
<div className="headerContainer">
<div className="basketContainer">
<Link href="/cart" className="linkForCart">
<ShoppingBasketIcon className="shoppingBasketIcon"/>
</Link>
</div>
<button className="navBarMenuButton" onClick={() => setShowMenu(!showMenu)} onMouseEnter={() => setShowMenu(true)}>
<MenuIcon className="menuIcon"/>
</button>
<div className={`menuOptions ${showMenu ? 'visible' : ''}`} onClick={() => setShowMenu(false)} onMouseLeave={() => setShowMenu(false)}>
<Link href="/" className="link">Home</Link>
<Link href="/shop" className="link">Shop</Link>
<Link href="/aboutUs" className="link">About Us</Link>
<Link href="/contactUs" className="link">Contact Us</Link>
{isAdmin && <Link href="/adminPanel" className="link">Admin</Link>}
</div>
</div>
);
}
export default Nav;
|
<template>
<view class="login page bg__white">
<view class="page__bd page__bd_spacing">
<view class="weui-cells__tips">请绑定接收信息手机号</view>
<form bindsubmit="loginBtnClick">
<view class="weui-cells__title">手机号</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input h4">
<view class="weui-cell__bd">
<input type="number" placeholder="请输入手机号" value="{{phone}}" name="phone" bindinput="getNameInput" />
</view>
</view>
</view>
<view class="weui-cells__title">验证码</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input weui-cell_vcode h4">
<view class="weui-cell__bd">
<input type="number" placeholder="请输入短信验证码" name="yzm" bindinput="getYzmInput" />
</view>
<view class="weui-cell__ft">
<button class="weui-btn h4 yzm-btn" type="primary" disabled="{{yzmBtn.isShow}}" @tap="yzmClick">{{yzmBtn.msg}}</button>
</view>
</view>
</view>
<!-- <view class="item-input">
<input type="number" placeholder="请输入手机号" value="{{phone}}" name="phone" bindinput="getNameInput" />
</view>
<view class="weui-flex item-input">
<input type="number" placeholder="请输入短信验证码" name="yzm" bindinput="getYzmInput" />
<button class="weui-btn yzm-btn" type="primary" plain="true" disabled="{{yzmBtn.isShow}}" @tap="yzmClick">{{yzmBtn.msg}}</button>
</view> -->
<view class="weui-btn-area">
<button class="weui-btn" type="primary" formType="submit">绑定</button>
</view>
<!-- <view class="item-input">
<button class="weui-btn" type="primary" formType="submit">绑定</button>
</view> -->
</form>
</view>
</view>
</template>
<script>
import wepy from 'wepy'
import base from '../../mixins/base'
import http from '../../utils/Http'
import {
__getApi
} from '../../config.js'
export default class CheckPhone extends wepy.page {
mixins = [base]
config = {
navigationBarTitleText: '绑定手机号'
}
data = {
token_access: '',
phone: '',
yzm: '',
yzmBtn: {
isShow: false,
msg: '获取验证码'
}
}
timeCountdown(time) {
const _self = this
let oTime = time
if (oTime === 0) {
_self.yzmBtn.isShow = false
_self.yzmBtn.msg = '获取验证码'
_self.$apply()
} else {
_self.yzmBtn.isShow = true
_self.yzmBtn.msg = oTime + 's'
_self.$apply()
oTime--
setTimeout(function() {
_self.timeCountdown(oTime)
}, 1000)
}
}
methods = {
getNameInput(e) {
this.phone = e.detail.value
},
getYzmInput(e) {
this.yzm = e.detail.value
},
async yzmClick() {
if (!this.isPhone(this.phone)) {
this.$alert('温馨提示', '请先填写正确的手机号')
return
}
const res = await http.get(__getApi._getCustomMadetelRegist, {
phone: this.phone,
token_access: this.token_access
})
if (res.false) return
this.timeCountdown(60)
},
loginBtnClick(e) {
const that = this
if (that.required(e.detail.value.phone) && that.required(e.detail.value.yzm)) {
http.post(__getApi._getCustomMadetelBind, {
token_access: that.token_access,
phone: e.detail.value.phone,
smsVeriCode: e.detail.value.yzm
})
wx.showToast({
title: '绑定成功',
icon: 'success',
duration: 1000
})
setTimeout(function() {
wx.navigateBack()
}, 1000)
} else {
that.$alert('温馨提示', '请绑定手机号')
}
}
}
onLoad(options) {
this.token_access = options.token_access
this.phone = options.phone ? options.phone : ''
}
}
</script>
<style lang="less">
.page {
height: 100vh;
}
.weui-cell {
background: #F9F9F9;
border-radius: 4px;
}
.weui-cells__title {
margin-top: 0;
padding-top: 0.77em;
color: #1E1E1E;
font-size: 32rpx;
}
.weui-btn-area {
margin-top: 80rpx;
}
.weui-other {
margin-top: 40rpx;
}
.weui-cells:after,
.weui-cells:before {
border: none;
}
.weui-phone {
width: 100%;
position: fixed;
left: 0;
bottom: 80rpx;
}
.weui-index image {
width: 100rpx;
height: 100rpx;
position: fixed;
right: 80rpx;
bottom: 160rpx;
}
.yzm-btn {
width: 196rpx;
line-height: 60rpx;
}
.phone {
width: 18px;
height: 14px;
vertical-align: middle;
margin-right: 10rpx;
}
</style>
|
Package in Java is a mechanism to encapsulate
a group of classes, sub packages and interfaces.
Packages are used for:
* Preventing naming conflicts. For example there can be two
classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee
* Making searching/locating and usage of classes, interfaces,
enumerations and annotations easier
* Providing controlled access: protected
and default have package level access control.
A protected member is accessible by classes in the same package and its
subclasses. A default member (without any access specifier) is accessible
by classes in the same package only.
* Packages can be considered as data encapsulation (or data-hiding).
|
#include "dog.h"
#include <stdio.h>
#include <stdlib.h>
/**
*init_dog - function that initialize a variable of type struct dog
*
*@d: pointer to struct dog
*@name: pointer to the var name
*@age: pointer the to age
*@owner: pointer the to owner
*/
void init_dog(struct dog *d, char *name, float age, char *owner)
{
if (d != NULL)
{
(*d).name = name;
(*d).age = age;
(*d).owner = owner;
}
}
|
#Script from class exercise
test4 <- read.csv("~/Documents/Dropbox/NASCAR Drive/Courses/EPSY 6220/test4.csv")
View(test4)
library(psych)
#now that we have the psych package available, we can ask it to compute the reliability
#of the data in test4.csv
alpha(test4)
#The next thing we would like to do is examine the factor structure of the data.
#We can do this first with a principal components analysis in psych
pc<-principal(test4, rotate="varimax")
#then call the result
pc
#We would like to examine the possibilty of more than 1 component or factor.
#To do this, we would run a principal axis factor analysis, like this...
pa<-fa(test4,fm="pa",rotate="varimax")
pa
#the result is pretty much what we just got with the PCA.
#To run a 2 factor solution, we need to specify it:
pa2<-fa(test4,nfactors=2,fm="pa",rotate="varimax")
pa2
|
create table customer (
id int primary key,
first_name varchar(100) not null,
last_name varchar(100) not null,
city varchar(100),
country varchar(100),
phone varchar(100)
);
create table supplier (
id int primary key,
company_name varchar(100) not null,
contact_name varchar(100),
contact_title varchar(100),
city varchar(100),
country varchar(100),
phone varchar(100),
fax varchar(100)
);
create table product (
id int primary key,
product_name varchar(100) not null,
unit_price decimal(12,2) default 0,
package varchar(100),
is_discontinued boolean default false,
supplier_id int references supplier(id) not null
);
create table orders (
id int primary key,
order_date timestamp default now(),
order_number varchar(100),
total_amount decimal(12,2) default 0,
customer_id int references customer(id) not null
);
create table order_item (
id int primary key,
unit_price decimal(12,2) default 0,
quantity int default 1,
order_id int references orders(id) not null,
product_id int references product(id) not null
);
select * from supplier;
select * from product;
select * from orders;
select * from order_item;
select * from customer;
--1
select *from customer where country in ('Canada');
--2
select country from customer;
--3
select count(*)from orders;
--4
select max( total_amount )from orders;
--5
select sum(id)from orders;
--6------------------------------------------------
select sum(total_amount)from orders where order_date>to_timestamp('Dec 31 2013 ', 'MON DD YYYY');
--7
SELECT AVG(total_amount) FROM orders;
--8
select orders.customer_id,avg(orders.total_amount)from customer,orders group by customer.first_name,orders.id;
--9
select *from customer where country in('Spain','Brazil');
--10
select * from orders where order_date>to_timestamp('Dec 31 2012 ', 'MON DD YYYY') AND total_amount<100;
--11
select *from customer where country in ('Spain','France','Germany','Italy') order by country asc ;
--12
select*from customer,supplier where supplier.country=customer.country;
--13
select *from customer where first_name LIKE 'Jo%';
--14
select *from customer where first_name LIKE '___a';
--14
select sum(quantity), sum(unit_price)from order_item ;
--15
SELECT COUNT(customer.id), Country FROM customer GROUP BY Country;
--16
SELECT COUNT(customer.id), Country FROM customer GROUP BY Country ORDER BY COUNT(customer.id) DESC;
--17
select first_name,sum(total_amount),count(quantity)from orders join customer
c on orders.customer_id = c.id join order_item oi on orders.id = oi.order_id
group by first_name order by sum(total_amount);
--18
select first_name,sum(total_amount),count(quantity)from orders join customer
c on orders.customer_id = c.id join order_item oi on orders.id = oi.order_id
group by first_name having count (quantity)>20;
|
<a name="readme-top"></a>
<!-- PROJECT SHIELDS -->
<!--
*** I'm using markdown "reference style" links for readability.
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
*** See the bottom of this document for the declaration of the reference variables
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
-->
[![Contributors][contributors-shield]][contributors-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![MIT License][license-shield]][license-url]
<!-- PROJECT LOGO -->
<br />
<div align="center">
<h3 align="center">ARGames - IoT</h3>
<p align="center">
Epitech ESP ARGames project
</p>
[](https://sonarcloud.io/summary/new_code?id=ArGame-Epitech_IoT)
</div>
<!-- TABLE OF CONTENTS -->
<details>
<summary>Table of Contents</summary>
<ol>
<li>
<a href="#about-the-project">A propos du projet</a>
<ul>
<li><a href="#built-with">Techo, Frameworks et librairies</a></li>
</ul>
</li>
<li>
<a href="#getting-started">Guide de démarrage</a>
<ul>
<li><a href="#prerequisites">Prérequis</a></li>
<li><a href="#installation">Développement</a></li>
</ul>
</li>
<li><a href="#usage">Usage</a></li>
<li><a href="#roadmap">Roadmap</a></li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#license">License</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#acknowledgments">Acknowledgments</a></li>
</ol>
</details>
<!-- ABOUT THE PROJECT -->
## A propos du projet
[![Product Name Screen Shot][product-screenshot]](https://example.com)
There are many great README templates available on GitHub; however, I didn't find one that really suited my needs so I created this enhanced one. I want to create a README template so amazing that it'll be the last one you ever need -- I think this is it.
Here's why:
* Your time should be focused on creating something amazing. A project that solves a problem and helps others
* You shouldn't be doing the same tasks over and over like creating a README from scratch
* You should implement DRY principles to the rest of your life :smile:
Of course, no one template will serve all projects since your needs may be different. So I'll be adding more in the near future. You may also suggest changes by forking this repo and creating a pull request or opening an issue. Thanks to all the people have contributed to expanding this template!
Use the `BLANK_README.md` to get started.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
### Techo, Frameworks et librairies
Ce projet à été développer a l'aide de ces technologies/frameworks/librairies:
* [![PlatformIO][PlatformIO]][PlatformIO-url]
* [![Github Actions][Github-actions]][Github-actions-url]
* [![Sonarcloud][Sonarcloud]][Sonarcloud-url]
* [![Taskfile][Taskfile]][Taskfile-url]
* [![Esp32][Esp-32]][Esp-32-url]
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- GETTING STARTED -->
## Guide de démarrage
Cette section est un guide pour vous aider à démarrer a développer sur le projet.
### Prérequis
Nous utilisons Taskfile pour gérer les tâches de développement. Vous devez donc l'installer sur votre machine.
* Taskfile
```sh
sh -c "$(curl --location https://taskfile.dev/install.sh)" -- -d -b ~/.local/bin
```
plus d'info sur la documentation officiel de [Taskfile](https://taskfile.dev/#/installation)
PlatformIO est également requis pour compiler et flasher le code sur la carte ESP32 et également pour unifier l'environnement de développement de tous les développeurs.
- PlatformIO CLI
```sh
curl -fsSL -o get-platformio.py https://raw.githubusercontent.com/platformio/platformio-core-installer/master/get-platformio.py
python3 get-platformio.py
```
vous avez également la possibilité d'installer PlatformIO [directement dans votre IDE](https://platformio.org/platformio-ide) (VSCode, Atom, CLion, etc...)
plus d'info sur la documentation officiel de [PlatformIO](https://docs.platformio.org/en/latest/core/installation.html)
### Développement
Toutes les tâches de développement sont gérées par Taskfile. Vous pouvez voir toutes les tâches disponibles avec la commande suivante:
```sh
task -l
```
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- USAGE EXAMPLES -->
## Usage
Use this space to show useful examples of how a project can be used. Additional screenshots, code examples and demos work well in this space. You may also link to more resources.
_For more examples, please refer to the [Documentation](https://example.com)_
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- ROADMAP -->
## Roadmap
- [x] Add Changelog
- [x] Add back to top links
- [ ] Add Additional Templates w/ Examples
- [ ] Add "components" document to easily copy & paste sections of the readme
- [ ] Multi-language Support
- [ ] Chinese
- [ ] Spanish
See the [open issues](https://github.com/othneildrew/Best-README-Template/issues) for a full list of proposed features (and known issues).
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- LICENSE -->
## License
Distributed under the MIT License. See `LICENSE.txt` for more information.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- CONTACT -->
## Contact
Your Name - [@your_twitter](https://twitter.com/your_username) - [email protected]
Project Link: [https://github.com/your_username/repo_name](https://github.com/your_username/repo_name)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- ACKNOWLEDGMENTS -->
## Acknowledgments
Use this space to list resources you find helpful and would like to give credit to. I've included a few of my favorites to kick things off!
* [Choose an Open Source License](https://choosealicense.com)
* [GitHub Emoji Cheat Sheet](https://www.webpagefx.com/tools/emoji-cheat-sheet)
* [Malven's Flexbox Cheatsheet](https://flexbox.malven.co/)
* [Malven's Grid Cheatsheet](https://grid.malven.co/)
* [Img Shields](https://shields.io)
* [GitHub Pages](https://pages.github.com)
* [Font Awesome](https://fontawesome.com)
* [React Icons](https://react-icons.github.io/react-icons/search)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[contributors-shield]: https://img.shields.io/github/contributors/ArGame-Epitech/IoT.svg?style=for-the-badge
[contributors-url]: https://github.com/ArGame-Epitech/IoT/graphs/contributors
[stars-shield]: https://img.shields.io/github/stars/ArGame-Epitech/IoT.svg?style=for-the-badge
[stars-url]: https://github.com/ArGame-Epitech/IoT/stargazers
[issues-shield]: https://img.shields.io/github/issues/ArGame-Epitech/IoT.svg?style=for-the-badge
[issues-url]: https://github.com/ArGame-Epitech/IoT/issues
[license-shield]: https://img.shields.io/github/license/ArGame-Epitech/IoT.svg?style=for-the-badge
[license-url]: https://github.com/ArGame-Epitech/IoT/blob/master/LICENSE.txt
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555
[linkedin-url]: https://linkedin.com/in/othneildrew
[product-screenshot]: images/screenshot.png
[Next.js]: https://img.shields.io/badge/next.js-000000?style=for-the-badge&logo=nextdotjs&logoColor=white
[Next-url]: https://nextjs.org/
[React.js]: https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB
[React-url]: https://reactjs.org/
[Vue.js]: https://img.shields.io/badge/Vue.js-35495E?style=for-the-badge&logo=vuedotjs&logoColor=4FC08D
[Vue-url]: https://vuejs.org/
[Angular.io]: https://img.shields.io/badge/Angular-DD0031?style=for-the-badge&logo=angular&logoColor=white
[Angular-url]: https://angular.io/
[Svelte.dev]: https://img.shields.io/badge/Svelte-4A4A55?style=for-the-badge&logo=svelte&logoColor=FF3E00
[Svelte-url]: https://svelte.dev/
[Laravel.com]: https://img.shields.io/badge/Laravel-FF2D20?style=for-the-badge&logo=laravel&logoColor=white
[Laravel-url]: https://laravel.com
[Bootstrap.com]: https://img.shields.io/badge/Bootstrap-563D7C?style=for-the-badge&logo=bootstrap&logoColor=white
[Bootstrap-url]: https://getbootstrap.com
[JQuery.com]: https://img.shields.io/badge/jQuery-0769AD?style=for-the-badge&logo=jquery&logoColor=white
[JQuery-url]: https://jquery.com
[PlatformIO]: https://img.shields.io/badge/PlatformIO-000000?style=for-the-badge&logo=platformio&logoColor=white
[PlatformIO-url]: https://platformio.org/
[Github-actions]: https://img.shields.io/badge/GitHub_Actions-2088FF?style=for-the-badge&logo=github-actions&logoColor=white
[Github-actions-url]: https://github.com
[Sonarcloud]: https://img.shields.io/badge/SonarCloud-4E9BCD?style=for-the-badge&logo=sonarcloud&logoColor=white
[Sonarcloud-url]: https://sonarcloud.io/
[Taskfile]: https://img.shields.io/badge/Taskfile-00C4B4?style=for-the-badge&logo=go&logoColor=white
[Taskfile-url]: https://taskfile.dev/#/
[Esp-32]: https://img.shields.io/badge/ESP32-000000?style=for-the-badge&logo=espressif&logoColor=white
[Esp-32-url]: https://www.espressif.com/en/products/socs/esp32
[QA-gate]: https://sonarcloud.io/api/project_badges/quality_gate?project=ArGame-Epitech_IoT
[QA-gate-url]: https://sonarcloud.io/summary/new_code?id=ArGame-Epitech_IoT
|
package com.poli.meets.mentorship.web.rest;
import com.poli.meets.mentorship.domain.MeetingSlot;
import com.poli.meets.mentorship.service.dto.MeetingSlotDTO;
import com.poli.meets.mentorship.service.MeetingSlotService;
import com.poli.meets.mentorship.service.dto.MeetingSlotPostDTO;
import com.poli.meets.mentorship.service.dto.PagedResponse;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
/**
* REST controller for managing {@link MeetingSlot}.
*/
@Slf4j
@RestController
@RequestMapping("/api")
@AllArgsConstructor
public class MeetingSlotResource {
private final MeetingSlotService meetingSlotService;
@DeleteMapping("/meeting-slots/current-user/{id}")
public ResponseEntity<Void> deleteMeetingSlot(
@RequestHeader("Authorization") String token,
@PathVariable Long id) {
meetingSlotService.delete(token, id);
return ResponseEntity.noContent().build();
}
@GetMapping("/meeting-slots/current-user/free")
public ResponseEntity<List<MeetingSlotDTO>> getAllMeetingSlotsForCurrentMentor(
@RequestHeader("Authorization") String token) {
return ResponseEntity.ok().body(meetingSlotService.findFreeSlots(token));
}
@GetMapping("/meeting-slots")
public ResponseEntity<List<MeetingSlotDTO>> getAllMeetingSlotsForMentor(
@RequestParam Long mentorId) {
return ResponseEntity.ok().body(meetingSlotService.findFreeSlots(mentorId));
}
@PostMapping("/meeting-slots/current-user")
public ResponseEntity<MeetingSlotDTO> createMeetingSlot(
@RequestHeader("Authorization") String token,
@RequestBody MeetingSlotPostDTO meetingSlotDTO) {
return ResponseEntity.ok().body(meetingSlotService.save(token, meetingSlotDTO));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BookShopOnline.Core.Enums
{
public enum VoucherType
{
COUPONS = 0,
DELIVERY = 1,
}
/// <summary>
/// Tình trạng đơn hàng
/// </summary>
public enum OrderStatus
{
/// <summary>
/// Chờ xác nhận
/// </summary>
WAIT_FOR_CONFIRMATION = 0,
/// <summary>
/// Đã xác nhận
/// </summary>
CONFIRMED = 1,
/// <summary>
/// Đang xử lý
/// </summary>
PROCESSING = 2,
/// <summary>
/// Hoàn thành
/// </summary>
COMPLETE = 3,
/// <summary>
/// Đã hủy
/// </summary>
CANCELLED = 4,
}
/// <summary>
/// Tình trạng giao hàng
/// </summary>
public enum DeliveryStatus
{
/// <summary>
/// Chưa giao hàng
/// </summary>
NOT_DELIVERY = 0,
/// Đang giao hàng
/// </summary>
BEING_TRANSPORTED = 1,
/// <summary>
/// Đã lấy hàng
/// </summary>
DELIVERIED = 2,
/// <summary>
/// Hủy
/// </summary>
CANCELLED = 3,
}
/// <summary>
/// Hình thức giao hàng
/// </summary>
public enum DeliveryMethod
{
/// <summary>
/// giao hàng tận nơi
/// </summary>
LOCAL_DELIVERY = 0,
}
/// <summary>
/// Phương thức thanh toán
/// </summary>
public enum PaymentMethod
{
COD = 0,
ZALOPAY_WALLTET = 1,
VNPAY = 2,
MONO_WALLET = 3,
SHOPPEPAY_WALLET = 4,
}
/// <summary>
/// Tình trạng thanh toán
/// </summary>
public enum PaymentStatus
{
UNPAID = 0,
WAIT_FOR_HANDLE = 1,
PAID = 2,
}
public enum SortType
{
/// <summary>
/// Sắp xếp tăng dần
/// </summary>
ASC = 1,
/// <summary>
/// Sắp xếp giảm dần
/// </summary>
DESC = 2,
/// <summary>
/// Không sắp xếp
/// </summary>
NULL = 0,
}
public enum AccountStatus {
/// <summary>
/// Ngừng hoạt động
/// </summary>
IN_ACTIVE = 0,
/// <summary>
/// Đang hoạt động
/// </summary>
ACTIVCE = 1,
}
public enum Gender
{
MALE = 0,
FEMALE = 1,
OTHER = 2,
}
}
|
import { NavScreen } from "../screens/NavScreen";
import { PreNavScreen } from "../screens/PreNavScreen";
import { PauseScreen } from "../screens/PauseScreen";
import { PreGameScreen } from "../screens/PreGameScreen";
import { VictoryScreen } from "../screens/VictoryScreen";
import { SplashScreen } from "../screens/SplashScreen";
import { GameplayScreen } from "../screens/GameplayScreen";
import { TutorialScreen } from "../screens/TutorialScreen";
import { AuthScreen } from "../screens/AuthScreen";
import { Screen } from "../screens/Screen";
import { UserManager } from "./UserManager";
import { Overlay } from "../screens/Overlay";
import { PassportScreen } from "../screens/PassportScreen";
import { Region } from "../components/Region";
export type OverlayEnum =
| "prenav"
| "pregame"
| "pause"
| "victory"
| "passport";
export type ScreenEnum =
| "splash"
| "map"
| "gameplay"
| "learning"
| "testing"
| "tutorial"
| "auth"
| OverlayEnum;
export class ScreenManager {
private static screenManager: ScreenManager;
public static get(): ScreenManager {
if (!this.screenManager) this.screenManager = new ScreenManager();
return this.screenManager;
}
public static readonly SPLASH: ScreenEnum = "splash";
public static readonly NAV: ScreenEnum = "map"; // URL reads /map, but it uses NavScreen
public static readonly PRENAV: ScreenEnum = "prenav";
public static readonly PREGAME: ScreenEnum = "pregame";
public static readonly PAUSE: ScreenEnum = "pause";
public static readonly GAMEPLAY: ScreenEnum = "gameplay";
public static readonly LEARNING: ScreenEnum = "learning";
public static readonly TESTING: ScreenEnum = "testing";
public static readonly VICTORY: ScreenEnum = "victory";
public static readonly TUTORIAL: ScreenEnum = "tutorial";
public static readonly PASSPORT: ScreenEnum = "passport";
public static readonly AUTH: ScreenEnum = "auth";
private screenMap: Object;
private loader: JQuery;
private mainContainer: JQuery;
private currentBaseScreen: Screen;
private currentBaseScreenEnum: ScreenEnum;
private currentOverlay: Overlay;
private currentOverlayEnum: OverlayEnum;
private region: Region;
private constructor() {
// Ideally, this should be a static Map<ScreenEnum, Screen>, but I couldn't pass a class itself to a map :(
this.screenMap = {};
this.screenMap[ScreenManager.SPLASH] = SplashScreen;
this.screenMap[ScreenManager.NAV] = NavScreen;
this.screenMap[ScreenManager.PRENAV] = PreNavScreen;
this.screenMap[ScreenManager.PREGAME] = PreGameScreen;
this.screenMap[ScreenManager.PAUSE] = PauseScreen;
this.screenMap[ScreenManager.GAMEPLAY] = GameplayScreen;
//TODO learningscreen
//TODO testingscreen
this.screenMap[ScreenManager.VICTORY] = VictoryScreen;
this.screenMap[ScreenManager.TUTORIAL] = TutorialScreen;
this.screenMap[ScreenManager.PASSPORT] = PassportScreen;
this.screenMap[ScreenManager.AUTH] = AuthScreen;
/**
* Popstate / Back Button
*/
$(window).on(
"popstate",
function (e: JQueryEventObject) {
if (history.state !== null) {
let queries: any = {};
for (let q in history.state) {
if (q != "screen" && q != "property") {
queries[q] = history.state[q];
}
}
this.switchScreens(history.state.screen, queries, false);
}
}.bind(this)
);
$(document).on(
"click",
"a",
function (e: JQueryEventObject) {
let href = $(e.currentTarget).attr("href");
// non-event and internal links only
if (
href &&
href.indexOf("#") == -1 &&
(href.indexOf(document.domain) > -1 || href.indexOf(":") === -1)
) {
e.preventDefault(); // prevent link from working normally
let url_components = href.split("?");
let path = url_components[0];
if (path[0] == "/") path = path.slice(1);
if (!(path in this.screenMap)) path = ScreenManager.SPLASH;
let queries: string;
if (url_components.length > 1) queries = url_components[1];
else queries = "";
this.switchScreens(path, new URLSearchParams(queries));
}
}.bind(this)
);
// loading indicator overlay*/
this.loader = $("#loading-overlay");
this.mainContainer = $("#main-container");
}
public setupInitScreen(): void {
// load and display the current screen
let screenSwitch: ScreenEnum = <ScreenEnum>(
window.location.pathname.split(/[\/?]/)[1]
);
this.currentBaseScreenEnum = this.screenMap[screenSwitch]
? screenSwitch
: ScreenManager.SPLASH;
this.currentBaseScreen = new this.screenMap[this.currentBaseScreenEnum](
new URLSearchParams(window.location.search)
);
// set initial state (for going back later)
history.replaceState(
{ screen: this.currentBaseScreen.name },
"",
window.location.pathname + window.location.search
);
console.log("Switch " + this.currentBaseScreenEnum);
this.currentBaseScreen.ready();
$("#loading-overlay").fadeOut("fast");
}
public switchScreens(
screen: ScreenEnum,
queries: URLSearchParams,
pushState = true
): void {
let newScreenEnum =
screen && screen in this.screenMap ? screen : ScreenManager.SPLASH;
let newScreen: Screen = new this.screenMap[newScreenEnum](queries);
if (!newScreen.overlay) this.loader.fadeIn("fast");
$(".material-tooltip").remove();
$.ajax({
method: "GET",
url: ScreenManager.generateURL(newScreen),
success: function (data: any, status: string, xhr: JQueryXHR) {
if (this.currentBaseScreen) this.currentBaseScreen.detachHandlers();
if (this.currentOverlay) this.currentOverlay.detachHandlers();
if (newScreen.overlay) {
if (this.currentOverlay && this.currentOverlay.overlayElement) {
this.currentOverlay.overlayElement.remove();
}
this.currentOverlay = <Overlay>newScreen;
this.currentOverlay.overlayElement = $(data).find(".screen-overlay");
this.currentOverlayEnum = <OverlayEnum>newScreenEnum;
this.mainContainer.prepend($(data).filter("#main-container").html());
this.currentOverlay.overlayElement =
this.mainContainer.find(".screen-overlay");
if (this.region) {
this.currentOverlay.dataLoaded(this.region);
this.region = null;
}
this.currentOverlay.ready();
} else {
if (this.currentBaseScreen) this.currentBaseScreen.onLeave();
this.currentBaseScreen = newScreen;
this.currentBaseScreenEnum = newScreenEnum;
if (this.currentOverlay) this.currentOverlay.onLeave();
this.currentOverlay = null;
this.mainContainer.fadeOut(
"fast",
function () {
this.mainContainer.html($(data).filter("#main-container").html());
this.mainContainer.fadeIn(
"fast",
function () {
document.title = $(data).filter("title").text();
this.loader.fadeOut("fast");
$("html, body").animate({ scrollTop: 0 }, "fast");
this.currentBaseScreen.ready();
}.bind(this)
);
}.bind(this)
);
if (pushState)
history.pushState(null, "", ScreenManager.generateURL(newScreen));
}
}.bind(this),
dataType: "html",
error: function (xhr: JQueryXHR, status: string, err: string) {
newScreen.error();
this.loader.fadeOut("fast");
}.bind(this),
});
}
public closeOverlay(): void {
if (this.currentOverlay) {
this.currentOverlay.detachHandlers();
if (this.currentOverlay.overlayElement)
this.currentOverlay.overlayElement.remove();
this.currentBaseScreen.reattachHandlers();
}
}
public passRegionToOverlay(region: Region): void {
if (this.currentOverlay) this.currentOverlay.dataLoaded(region);
else this.region = region;
}
/**
* Back button
* Same as browser button
*
* Screens user is not allowed to return to are
* not pushed to the history stack
*/
back(): void {
history.back();
}
public static generateURL(screen: Screen): string {
let url = screen.name == ScreenManager.SPLASH ? "/" : "/" + screen.name;
if (screen.queries) {
url += "?" + screen.queries.toString();
}
return url;
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PC Games Shop</title>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/reset.css">
<link href="https://unpkg.com/[email protected]/dist/aos.css" rel="stylesheet">
</head>
<body>
<header class="header">
<div class="container">
<div class="header-nav">
<nav class="nav">
<div class="logo-img"> <a href=""><img src="img/png/joystick.png" alt=""></a></div>
<ul class="nav-list">
<li class="nav-item"><a href="" class="nav-link">Головна</a></li>
<li class="nav-item"><a href="#catalog" class="nav-link">Каталог ігор</a></li>
<li class="nav-item"><a href="#about" class="nav-link">Про магазин</a></li>
<li class="nav-item"><a href="#footer" class="nav-link">Контакти</a></li>
<button id="open-cart"> <img src="img/svg/cart.svg" alt="" class="nav-cart"></button>
</ul>
</nav>
</div>
</div>
</header>
<section class="services" data-aos="fade-up">
<div class="container">
<h1 class="services-h1">Вас вітає магазин із продажу комп'ютерних ігор!</h1>
<div class="service-p">Чому саме ми?</div>
<div class="services-poslug">
<div class="services-row">
<div class="services-card"> <img src="img/svg/delivery.svg" alt="" class="img-service"> Швидка доставка ігор на пошту </div>
<div class="services-card"> <img src="img/svg/low-price.svg" alt="" class="img-service">Низькі ціни на ринку </div>
<div class="services-card"> <img src="img/svg/gamepad.svg" alt="" class="img-service"> Великий асортимент ігор </div>
</div>
</div>
<a href="#catalog"><div class="button-ctg"><button class="btn-catalog"> До каталогу</button></div></a>
</div>
</section>
<section class="catalog" id="catalog" data-aos="fade-down">
<div class="container">
<h1 class="catalog-h1">Каталог ігор</h1>
<div class="card-row">
<div class="service-card" data-id="01">
<img src="img/jpg/catalog games/1.jpg" alt="" class="ctg-img">
<p class="ctg-text">Mortal Kombat 11 для ПК (ключ)</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">999 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="02">
<img src="img/jpg/catalog games/2.jpg" alt="" class="ctg-img">
<p class="ctg-text">Grand Theft Auto 5 для ПК (ключ)</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">349 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="03">
<img src="img/jpg/catalog games/3.jpg" alt="" class="ctg-img">
<p class="ctg-text">FIFA 23 для ПК (ключ)</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">649 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="04">
<img src="img/jpg/catalog games/4.jpg" alt="" class="ctg-img">
<p class="ctg-text">Resident Evil 4 Deluxe для ПК (ключ)</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">1299 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="05">
<img src="img/jpg/catalog games/5.jpg" alt="" class="ctg-img">
<p class="ctg-text">Euro Truck Simulator 2 для ПК (ключ)</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">199 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="06">
<img src="img/jpg/catalog games/6.jpg" alt="" class="ctg-img">
<p class="ctg-text">Star Wars Jedi: Survivor для ПК (ключ)</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">1499 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="07">
<img src="img/jpg/catalog games/7.jpg" alt="" class="ctg-img">
<p class="ctg-text">Hogwarts Legacy для PS5</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">1749 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="08">
<img src="img/jpg/catalog games/8.jpg" alt="" class="ctg-img">
<p class="ctg-text">God of War Ragnarok для PS4</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">1199 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="09">
<img src="img/jpg/catalog games/9.jpg" alt="" class="ctg-img">
<p class="ctg-text">Minecraft. Playstation 4 Edition</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">1199 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="10">
<img src="img/jpg/catalog games/10.jpg" alt="" class="ctg-img">
<p class="ctg-text">NBA 2K23 для Xbox Series X</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">1349 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="11">
<img src="img/jpg/catalog games/11.jpg" alt="" class="ctg-img">
<p class="ctg-text">Red Dead Redemption 2 для Xbox One</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">799 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
<div class="service-card" data-id="12">
<img src="img/jpg/catalog games/12.jpg" alt="" class="ctg-img">
<p class="ctg-text">NFS: Unbound для XBOX Series X</p>
<div class="items counter-wrapper">
<div class="items__control" data-action="minus">-</div>
<div class="items__current" data-counter>1</div>
<div class="items__control" data-action="plus">+</div>
</div>
<p class="ctg-price">1149 грн</p>
<button class="ctg-btn" data-cart>Додати в кошик</button>
</div>
</div>
</div>
</section>
<div class="modal-add-cart" id="my-modal">
<div class="modal-box">
<button><img src="img/svg/close-button.svg" alt="" class="close-modal" id="close-btn"></button>
<p>Товар доданий в кошик!</p>
</div>
</div>
<div class="modal-cart" id="modal-cart">
<div class="modal-cart-box">
<button><img src="img/svg/close-button.svg" alt="" class="close-modal" id="close-btn-cart"></button>
<p class="cart-text" style="visibility: visible;">В кошику немає товарів.</p>
<p class="price-cart" style="display: none;"> 0 </p>
<button class="btn-cart" style="display: none;" id="buy-btn"> <p class="cart-btn-text">Замовити</p></button>
</div>
</div>
<div class="modal-cart-form" id="form-cart">
<div class="modal-form-box">
<button><img src="img/svg/close-button.svg" alt="" class="close-modal" id="form-close"></button>
<h2 class="modal-title">Оформити замовлення</h2> <br>
<form action="">
<p class="input-text">Ваш ПІБ</p>
<input type="text" class="input-modal" placeholder="">
<p class="input-text">Ваш номер телефону</p>
<input type="text" class="input-modal" placeholder=""> <br>
<p class="input-text">Ваш email</p>
<input type="text" class="input-modal" placeholder="">
</form>
<button class="modal-btn" id="btn-modal-finished">Оплатити</button>
</div>
</div>
<div class="modal-pay" id="modal-pay">
<div class="modal-pay-box">
<button><img src="img/svg/close-button.svg" alt="" class="close-modal" id="form-close-buy"></button>
<h2 class="modal-title">Оплата замовлення</h2> <br>
<p class="input-text">Ваш номер картки</p>
<input type="text" class="input-modal">
<p class="input-text">Строк придатності вашої картки</p>
<input type="text" class="input-modal">
<p class="input-text">Ваш CVV код</p>
<input type="text" class="input-modal">
<button class="modal-btn-pay" id="btn-modal-pay-finished">Оплатити</button>
</div>
</div>
<div class="modal-finished" id="modal-finished">
<div class="modal-finished-box">
<button><img src="img/svg/close-button.svg" alt="" class="close-modal" id="form-close-finished"></button>
<img src="img/png/galochka.png" alt="" class="galochka-img-modal">
<p class="finished-text">Замовлення оформлено!</p>
</div>
</div>
<section class="about" id="about" data-aos="zoom-in">
<div class="container">
<h1 class="about-h1">Про магазин</h1>
<p class="about-text">
Ласкаво просимо до нашого онлайн-магазину комп'ютерних ігор! <br> <br>
Ми - ваш надійний та зручний джерело найновіших комп'ютерних ігор. Наш інтернет-магазин пропонує широкий асортимент грифів, жанрів та платформ для всіх типів геймерів, незалежно від їхнього досвіду чи уподобань. <br> <br>
Особливості нашого магазину: <br> <br>
Величезний вибір ігор: Ми пропонуємо широкий асортимент ігор для всіх платформ, включаючи ПК, Xbox, PlayStation. Ви знайдете у нас найновіші релізи, популярні хіти, класичні ігри та незалежні проекти. <br><br>
Вигідні пропозиції та знижки: Ми постійно надаємо різноманітні знижки та акції, щоб зробити покупки в нашому магазині ще вигіднішими. Ви можете отримати доступ до ексклюзивних пропозицій. <br><br>
Швидка та надійна доставка: Ми розуміємо, що ви хочете насолоджуватися новими іграми якомога швидше. Тому ми пропонуємо швидку та надійну доставку на електронну пошту усіх замовлень, щоб ви могли швидко розпочати грати. <br><br>
Приєднуйтесь до нашого онлайн-магазину комп'ютерних ігор та дозвольте нам зробити ваше ігрове досвід ще більш захоплюючим!
</p>
</div>
</section>
<footer class="footer" id="footer" data-aos="fade-down">
<div class="container">
<h1 class="h1-contacts">Контакти</h1>
<p class="contacts-text">
Call Center - 0800378913 <br><br>
Графік роботи 09:00 - 20:00
</p>
<div class="row-contact-svg">
<a href="#!"><img src="img/svg/instagram.svg" alt="" class="contacts-svg"></a>
<a href="#!"><img src="img/svg/facebook.svg" alt="" class="contacts-svg"></a>
<a href="#!"><img src="img/svg/tiktok.svg" alt="" class="contacts-svg"></a>
</div>
</div>
</footer>
<script src="https://unpkg.com/[email protected]/dist/aos.js"></script>
<script src="js/script.js"></script>
<script src="js/counter.js"></script>
<script src="js/cart.js"></script>
<script src="js/calcCartPrice.js"></script>
<script src="js/toggleCartStatus.js"></script>
</body>
</html>
|
import React from 'react';
import { jobPositions } from '../jobPosition';
const Experience = () => {
const nameOfPositionStyle = `sm:text-xl text-lg font-bold mb-1`;
const nameOfCompanyStyle = `mr-5 font-bold text-base sm:text-md text-sky-500 tracking-tight`;
const period = ` text-slate-500 text-[10px] sm:text-[11px] pr-3`;
const icon = `sm:w-5 sm:h-5 w-3 h-3 mb-2 mt-2 sm:ml-[-10px] sm:mr-[5px] mt-[1px] sm:mt-[-1px] `;
const link = ` text-slate-500 sm:text-xs text-[8px]`;
return (
<section className=" sm:mt-[4rem]">
<h1 className="border-b-4 border-slate-500 pb-2 font-bold text-slate-500 mx-2 shadow-lg">
EXPERIENCE
</h1>
<div className="flex flex-col mx-5 ">
{jobPositions.map((position) => (
<div
key={position.id}
className="mt-3 border-b-2 border-slate-300 pb-2 shadow-sm"
>
<div className="flex flex-col items-start mb-2">
<h1 className={nameOfPositionStyle}>{position.position}</h1>
<div className="flex flex-col">
<h2 className={nameOfCompanyStyle}>{position.company}</h2>
</div>
{position.description && (
<p className="w-[90%] py-2 text-slate-500 text-xs">
{position.description}
</p>
)}
</div>
<div className="flex flex-row">
<div className="flex flex-row sm:mx-2">
<img
src="/assetsCv/calendar.png"
alt="Calendar Icon"
className={`${icon} `}
/>
<p className={period}>{position.date}</p>
</div>
<div className="flex flex-row ">
<img
src="/assetsCv/location.png"
alt="Location Icon"
className={`${icon} mt-[2px] sm:mt-[-2px]`}
/>
<p className={period}>{position.location}</p>
</div>
</div>
<div className="flex flex-row ">
<a className={link} target="a_blank" href={position.link}>
{position.link}
</a>
</div>
</div>
))}
</div>
</section>
);
};
export default Experience;
|
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import "languages.js" as JS
import BaseUI as UI
import TaskList
UI.AppStackPage {
id: root
title: qsTr("Settings")
padding: 0
Flickable {
contentHeight: settingsPane.implicitHeight
anchors.fill: parent
Pane {
id: settingsPane
anchors.fill: parent
padding: 0
ColumnLayout {
width: parent.width
spacing: 0
UI.SettingsSectionTitle { text: qsTr("Theme and colors") }
SettingsCheckItem {
title: qsTr("Dark Theme")
checkState: Settings.darkTheme ? Qt.Checked : Qt.Unchecked
onClicked: Settings.darkTheme = !Settings.darkTheme
Layout.fillWidth: true
}
UI.SettingsItem {
title: qsTr("Primary Color")
subtitle: colorDialog.getColorName(Settings.primaryColor)
onClicked: {
colorDialog.selectAccentColor = false
colorDialog.open()
}
}
UI.SettingsItem {
title: qsTr("Accent Color")
subtitle: colorDialog.getColorName(Settings.accentColor)
onClicked: {
colorDialog.selectAccentColor = true
colorDialog.open()
}
}
UI.SettingsSectionTitle { text: qsTr("Localization") }
UI.SettingsItem {
title: qsTr("Language")
subtitle: JS.getLanguageFromCode(Settings.language)
onClicked: languageDialog.open()
}
UI.SettingsItem {
property string name: JS.getCountryFromCode(Settings.country)
property string nativeName: JS.getCountryFromCode(Settings.country, "native")
title: qsTr("Country")
subtitle: nativeName + ((name !== nativeName) ? " (" + name + ")" : "")
onClicked: pageStack.push(Qt.resolvedUrl("SettingsContinentsPage.qml"))
}
UI.SettingsSectionTitle { text: qsTr("Task settings") }
SettingsCheckItem {
title: qsTr("Strikethrough completed tasks")
subtitle: qsTr("Add a strikethrough over the name of completed tasks in list view")
checkState: Settings.strikeCompleted ? Qt.Checked : Qt.Unchecked
onClicked: Settings.strikeCompleted = !Settings.strikeCompleted
Layout.fillWidth: true
}
SettingsCheckItem {
title: qsTr("Use AM/PM time selection")
subtitle: qsTr("The time is selected using AM/PM clock")
checkState: Settings.timeAMPM ? Qt.Checked : Qt.Unchecked
onClicked: Settings.timeAMPM = !Settings.timeAMPM
Layout.fillWidth: true
}
SettingsCheckItem {
title: qsTr("Use the tumbler time selector")
subtitle: qsTr("Select the time using a tumbler clock")
checkState: Settings.timeTumbler ? Qt.Checked : Qt.Unchecked
onClicked: Settings.timeTumbler = !Settings.timeTumbler
Layout.fillWidth: true
}
}
}
}
OptionsDialog {
id: colorDialog
property bool selectAccentColor: false
function getColorName(color) {
var filtered = colorDialog.model.filter((c) => {
return Material.color(c.bg) === color
})
return filtered.length ? filtered[0].name : ""
}
title: selectAccentColor ? qsTr("Choose accent color") : qsTr("Choose primary color")
model: [
{ name: "Material Red", bg: Material.Red },
{ name: "Material Pink", bg: Material.Pink },
{ name: "Material Purple", bg: Material.Purple },
{ name: "Material DeepPurple", bg: Material.DeepPurple },
{ name: "Material Indigo", bg: Material.Indigo },
{ name: "Material Blue", bg: Material.Blue },
{ name: "Material LightBlue", bg: Material.LightBlue },
{ name: "Material Cyan", bg: Material.Cyan },
{ name: "Material Teal", bg: Material.Teal },
{ name: "Material Green", bg: Material.Green },
{ name: "Material LightGreen", bg: Material.LightGreen },
{ name: "Material Lime", bg: Material.Lime },
{ name: "Material Yellow", bg: Material.Yellow },
{ name: "Material Amber", bg: Material.Amber },
{ name: "Material Orange", bg: Material.Orange },
{ name: "Material DeepOrange", bg: Material.DeepOrange },
{ name: "Material Brown", bg: Material.Brown },
{ name: "Material Grey", bg: Material.Grey },
{ name: "Material BlueGrey", bg: Material.BlueGrey }
]
delegate: RowLayout {
spacing: 0
Rectangle {
visible: colorDialog.selectAccentColor
color: UI.Style.primaryColor
Layout.margins: 0
Layout.leftMargin: 10
Layout.minimumWidth: 48
Layout.minimumHeight: 32
}
Rectangle {
color: Material.color(modelData.bg)
Layout.margins: 0
Layout.leftMargin: colorDialog.selectAccentColor ? 0 : 10
Layout.minimumWidth: 32
Layout.minimumHeight: 32
}
RadioButton {
checked: {
if (colorDialog.selectAccentColor)
Material.color(modelData.bg) === UI.Style.accentColor
else
Material.color(modelData.bg) === UI.Style.primaryColor
}
text: modelData.name
Layout.leftMargin: 4
onClicked: {
colorDialog.close()
if (colorDialog.selectAccentColor)
Settings.accentColor = Material.color(modelData.bg)
else
Settings.primaryColor = Material.color(modelData.bg)
}
}
}
}
OptionsDialog {
id: languageDialog
title: qsTr("Language")
model: System.translations()
delegate: RadioButton {
checked: modelData === Settings.language
text: JS.getLanguageFromCode(modelData)
onClicked: { languageDialog.close(); Settings.language = modelData }
}
}
}
|
package com.aurine.cloudx.open.api.inner.feign;
import com.aurine.cloudx.open.common.entity.base.OpenApiHeader;
import com.pig4cloud.pigx.common.core.util.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
/**
* 入云解绑
*
* @author : Qiu
* @date : 2021 12 24 16:35
*/
@FeignClient(contextId = "remoteCascadeCloudUnbind", value = "cloudx-open-biz")
public interface RemoteCascadeCloudUnbindService {
/**
* 申请入云解绑
* (边缘侧 -> 平台侧)
*
* @param header 请求头信息
* @param projectCode 项目第三方code
* @return R 返回结果
*/
@PutMapping("/v1/cascade/cloud-unbind/apply/{projectCode}")
R<Boolean> apply(@RequestBody OpenApiHeader header, @PathVariable("projectCode") String projectCode);
/**
* 撤销入云解绑
* (边缘侧 -> 平台侧)
*
* @param header 请求头信息
* @param projectCode 项目第三方code
* @return R 返回结果
*/
@PutMapping("/v1/cascade/cloud-unbind/revoke/{projectCode}")
R<Boolean> revoke(@RequestBody OpenApiHeader header, @PathVariable("projectCode") String projectCode);
/**
* 同意入云解绑
* (平台侧 -> 边缘侧)
*
* @param header 请求头信息
* @param projectCode 项目第三方code
* @return R 返回结果
*/
@PutMapping("/v1/cascade/cloud-unbind/accept/{projectCode}")
R<Boolean> accept(@RequestBody OpenApiHeader header, @PathVariable("projectCode") String projectCode);
/**
* 拒绝入云解绑
* (平台侧 -> 边缘侧)
*
* @param header 请求头信息
* @param projectCode 项目第三方code
* @return R 返回结果
*/
@PutMapping("/v1/cascade/cloud-unbind/reject/{projectCode}")
R<Boolean> reject(@RequestBody OpenApiHeader header, @PathVariable("projectCode") String projectCode);
}
|
/*******************************************************************************
* * $Id:: TermForm.java 293593 2017-09-29 16:36:45Z marinca $
* * . * .
* * * RRRR * Copyright © 2012 OHIM: Office for Harmonization
* * . RR R . in the Internal Market (trade marks and designs)
* * * RRR *
* * . RR RR . ALL RIGHTS RESERVED
* * * . _ . *
******************************************************************************/
package eu.ohim.sp.ui.tmefiling.form.terms;
import eu.ohim.sp.ui.tmefiling.form.json.ConceptForm;
import org.apache.commons.lang.builder.HashCodeBuilder;
import java.util.ArrayList;
import java.util.List;
/**
* This class holds a concept of Goods and Services term.
*/
public class TermForm implements java.io.Serializable, Comparable<TermForm> {
/**
* Serial version of the class.
*/
private static final long serialVersionUID = 1L;
/** The id class. */
private String idClass;
/** The description. */
private String description;
/** The scope availabilty. */
private boolean scopeAvailabilty;
/** The imported nice class heading. */
private boolean importedNiceClassHeading;
/** The parent ids. */
private List<ConceptForm> parentIds;
/** The error. */
private ErrorType error;
/** The related terms. */
private List<String> relatedTerms;
/** The harm concept. */
private String harmConcept;
/** The identifier. */
private String identifier;
/** The taxonomy path. */
private String taxonomyPath;
/** The generated. */
private boolean generated;
/**
* Instantiates a new term form.
*/
public TermForm() {
}
/**
* Creates a new term object with the given class id and description.
*
* @param idClass the class id to which this term is part of.
* @param description the wording of the term.
*/
public TermForm(String idClass, String description) {
this.idClass = idClass;
this.description = description;
}
/**
* Method that returns the idClass.
*
* @return the idClass
*/
public String getIdClass() {
return idClass;
}
/**
* Method that sets the idClass.
*
* @param idClass the idClass to set
*/
public void setIdClass(String idClass) {
this.idClass = idClass;
}
/**
* Method that returns the description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* The term is concept if it is false.
*
* @return false if the term is a concept
*/
public boolean isScopeAvailabilty() {
return scopeAvailabilty;
}
/**
* Sets the scope of the term.
*
* @param scopeAvailabilty the new scope availabilty
*/
public void setScopeAvailabilty(boolean scopeAvailabilty) {
this.scopeAvailabilty = scopeAvailabilty;
}
/**
* Method that sets the description.
*
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* It returns true if only the term is the same as on Nice Class Heading.
*
* @return true if only the term is the same as on Nice Class Heading
*/
public boolean isImportedNiceClassHeading() {
return importedNiceClassHeading;
}
/**
* This will be set as true if only the term is the same as on Nice Class Heading.
*
* @param importedNiceClassHeading the new imported nice class heading
*/
public void setImportedNiceClassHeading(boolean importedNiceClassHeading) {
this.importedNiceClassHeading = importedNiceClassHeading;
}
/**
* Gets the parent ids.
*
* @return the parent ids
*/
public List<ConceptForm> getParentIds() {
if (parentIds == null) {
parentIds = new ArrayList<ConceptForm>();
}
return parentIds;
}
/**
* Sets the parent ids.
*
* @param parentIds the new parent ids
*/
public void setParentIds(List<ConceptForm> parentIds) {
this.parentIds = parentIds;
}
/**
* Gets the related terms.
*
* @return the related terms
*/
public List<String> getRelatedTerms() {
return relatedTerms;
}
/**
* Sets the related terms.
*
* @param related the related terms to set
*/
public void setRelatedTerms(List<String> related) {
this.relatedTerms = related;
}
/**
* Gets the error.
*
* @return the error
*/
public ErrorType getError() {
return error;
}
/**
* Sets the error.
*
* @param error the error to set
*/
public void setError(ErrorType error) {
this.error = error;
}
/**
* If the term is in the Harmonized DB, this field is filled with its Harmonized Id.
* Check EuroClass documentation <a href=https://it.oami.europa.eu/wiki/EuroClass>here</a> and
* <a href=http://tm.itawiki.org/wiki/EuroClass_Main_Page>here</a>.
*
* @return the harmonized id of the concept if it is in the Harmonized DB. Null otherwise.
*/
public String getHarmConcept() {
return harmConcept;
}
/**
* Sets the Harmonized Id for the term if it is in the Harmonized DB.
* Check EuroClass documentation <a href=https://it.oami.europa.eu/wiki/EuroClass>here</a> and
* <a href=http://tm.itawiki.org/wiki/EuroClass_Main_Page>here</a>.
*
* @param externalReference the harmonized id of the concept if it is in the Harmonized DB.
*/
public void setHarmConcept(String externalReference) {
this.harmConcept = externalReference;
}
/**
* If the term is in the Harmonized DB, this field is filled with its taxonomy path.
* Check EuroClass documentation <a href=https://it.oami.europa.eu/wiki/EuroClass>here</a> and
* <a href=http://tm.itawiki.org/wiki/EuroClass_Main_Page>here</a>.
*
* @return the taxonomy path the concept if it is in the Harmonized DB. Null otherwise.
*/
public String getTaxonomyPath() {
return taxonomyPath;
}
/**
* Sets the taxonomy path for the term if it is in the Harmonized DB.
* Check EuroClass documentation <a href=https://it.oami.europa.eu/wiki/EuroClass>here</a> and
* <a href=http://tm.itawiki.org/wiki/EuroClass_Main_Page>here</a>.
*
* @param taxonomyPath the taxonomy path of the concept if it is in the Harmonized DB.
*/
public void setTaxonomyPath(String taxonomyPath) {
this.taxonomyPath = taxonomyPath;
}
/**
* Returns whether the term is a generated term or not.
*
* @return true, if is generated
*/
public boolean isGenerated() {
return generated;
}
/**
* Set if the term is generated or not.
*
* @param generated the new generated
*/
public void setGenerated(boolean generated) {
this.generated = generated;
}
/**
* Gets the term identifier.
*
* @return the identifier
*/
public String getIdentifier() {
return identifier;
}
/**
* Sets the term identifier.
*
* @param identifier the new identifier
*/
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return new HashCodeBuilder().append(description).append(idClass).toHashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TermForm other = (TermForm) obj;
if (description == null) {
if (other.description != null) {
return false;
}
} else if (!description.equals(other.description)) {
return false;
}
if (idClass == null) {
if (other.idClass != null) {
return false;
}
} else if (!idClass.equals(other.idClass)) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(TermForm o) {
if ((o!=null) && (this!=null)) {
return this.hashCode() - o.hashCode();
}
return 0;
}
}
|
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import {
Box,
Card,
CardActions,
CardContent,
Collapse,
CardMedia,
Button,
Typography,
Rating,
TextField,
useTheme,
} from "@mui/material";
import Header from "components/Header";
import { useGetBlogsQuery, useDeletePostMutation, useGetCustomersQuery } from "state/api";
import Addbutton from "components/Addbutton";
import Swal from "sweetalert2";
const Headerpage = () => {
const theme = useTheme();
const navigate = useNavigate();
const handleAddBlogClick = () => {
navigate("/blog/create");
};
const handleEditBlog = async (id) => {
navigate(`/blog/edit/${id}`);
};
const handleDelete = async (id) => {
try {
const result = await Swal.fire({
title: 'Are you sure?',
text: 'You will not be able to recover this blog!',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel',
reverseButtons: true,
});
if (result.isConfirmed) {
const { error } = await deletePost(id);
if (error) {
console.error('Error deleting blog:', error);
Swal.fire('Error!', 'An error occurred while deleting the blog.', 'error');
} else {
Swal.fire('Deleted!', 'The blog has been deleted.', 'success');
}
}
} catch (error) {
console.error('Error deleting blog:', error);
}
};
const [deletePost] = useDeletePostMutation();
const { data: blogs, isLoading, } = useGetBlogsQuery();
return (
<Box m="1.5rem 2.5rem">
<Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<Header title="Blog" subtitle="List of Customers" />
<Addbutton onClick={handleAddBlogClick} />
</Box>
<Box sx={{display: "flex", flexWrap: "wrap", justifyContent: "center"}}>
{isLoading ? (
<Typography>Loading blogs...</Typography>
) : (
<>
{blogs.map((blog) => (
<Box mt="3rem" key={blog._id} >
<Card sx={{ maxWidth: 370, marginRight: "2rem", bgcolor:theme.palette.mode === 'dark' ? '#2C2C2C' : '#FCFCFC' }} >
<CardMedia
component="img"
sx={{ height: 140 }}
image={blog.image}
title={blog.title}
/>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
{blog.title}
</Typography>
<Typography variant="body2" color="text.secondary">
{blog.description}
</Typography>
</CardContent>
<CardActions>
<Box
sx={{ display: "flex", justifyContent: "center", marginTop: "4rem", marginLeft: "5rem" }}>
<Button type="submit" variant="contained"
sx={{ width: "70px",
height: "40px",
fontSize: "15px",
marginRight: "1rem",
background: "#4153AC"
}}
onClick={() => handleEditBlog(blog._id)}>
Edit
</Button>
<Button type="submit" variant="contained"
sx={{ width: "70px",
height: "40px",
fontSize: "15px",
background: '#E25760' }}
onClick={() => handleDelete(blog._id)}>
Delete
</Button>
</Box>
</CardActions>
</Card>
</Box>
))}
</>
)}
</Box>
</Box>
);
};
export default Headerpage;
|
import React, {useState} from 'react';
import { Container, GithubLog, SearchForm } from './styles';
import { useNavigate } from 'react-router-dom';
import { ThemeName } from '../../styles/theme';
interface Props {
themeName: ThemeName;
setThemeName: (newName: ThemeName) => void;
}
const Header: React.FC<Props> = ({ themeName, setThemeName}) => {
const [search, setSearch] = useState('');
const navigate = useNavigate();
function handleSubmit(event: React.FormEvent) {
event.preventDefault();
navigate('/' + search.toLowerCase().trim());
}
function toggleTheme() {
setThemeName(themeName === 'light' ? 'dark' : 'light');
}
return (
<Container>
<GithubLog onClick={toggleTheme} />
<SearchForm onSubmit={handleSubmit} >
<input placeholder="Enter Username or Repo..." value={search}
onChange={e => setSearch(e.currentTarget.value)}
/>
</SearchForm>
</Container>
);
}
export default Header;
|
<template>
<div id="reg-model">
<el-card class="box-card">
<h3 class="center">{{ $t("auth.register.title") }}</h3>
<el-form autoComplete="on" ref="regForm" label-position="left" label-width="0px" class="card-box" :rules="rules" status-icon :model="form">
<el-form-item prop="username">
<el-input :placeholder="$t('auth.register.input-username')" v-model="form.username">
<i slot="prefix" class="mdl-icon-input material-icons el-input__icon">account_circle</i>
</el-input>
</el-form-item>
<el-form-item prop="email">
<el-input :placeholder="$t('auth.register.input-email')" v-model="form.email">
<i slot="prefix" class="mdl-icon-input material-icons el-input__icon">mail</i>
</el-input>
</el-form-item>
<el-form-item prop="password">
<el-input :placeholder="$t('auth.register.input-password')" type="password" v-model="form.password">
<i slot="prefix" class="mdl-icon-input material-icons el-input__icon">lock</i>
</el-input>
</el-form-item>
<el-form-item prop="inviteCode">
<el-input :placeholder="$t('auth.register.input-invite')" v-model="form.inviteCode">
<i slot="prefix" class="mdl-icon-input material-icons el-input__icon">record_voice_over</i>
</el-input>
</el-form-item>
<el-form-item class="center">
<el-button type="primary" :loading="this.loading" @click="registerTo">
{{ $t("auth.login.submit") }}
</el-button>
</el-form-item>
</el-form>
</el-card>
</div>
</template>
<script>
import { register as R } from '@/api/auth';
export default {
data() {
return {
form: {
username: '',
password: '',
email: '',
inviteCode: this.$route.params.id,
},
rules: {
username: [
{ required: true, message: this.$t('auth.error.non-input-username') },
],
email: [
{ required: true, message: this.$t('auth.error.non-input-email') },
],
password: [
{ required: true, message: this.$t('auth.error.non-input-password') },
],
inviteCode: [
{ required: true, message: this.$t('auth.error.non-input-invite') },
],
},
loading: false,
};
},
methods: {
registerTo() {
this.$refs.regForm.validate((valid) => {
if (valid) {
this.loginLoading = true;
R(this.form.email, this.form.password, this.form.username, this.form.inviteCode)
.then(() => {
this.loginLoading = false;
this.$notify.info({
title: this.$t('auth.register.register'),
message: this.$t('auth.register.register-success'),
});
setTimeout(() => {
this.$router.push({ name: 'Login' });
}, 2000);
}).catch((err) => {
this.loginLoading = false;
this.$notify.error({
title: this.$t('auth.register.register'),
message: err.response && err.response.data.error
? err.response.data.error
: err.message,
});
});
}
});
},
},
};
</script>
<style scoped>
#reg-model {
margin-top: 15vh;
height: 100px;
}
.center {
text-align: center;
}
</style>
<style>
.mdl-icon-input {
font-size: 16px;
padding-top: 2px;
}
</style>
|
/*
* DATAGERRY - OpenSource Enterprise CMDB
* Copyright (C) 2024 becon GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Component, OnDestroy, OnInit } from '@angular/core';
import { AbstractControl, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router} from '@angular/router';
import { HttpParams } from '@angular/common/http';
import { ReplaySubject, takeUntil } from 'rxjs';
import { SearchService } from './services/search.service';
import { SearchResultList } from './models/search-result';
import { PageLengthEntry } from '../../layout/table/components/table-page-size/table-page-size.component';
/* ------------------------------------------------------------------------------------------------------------------ */
@Component({
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit, OnDestroy {
// Get the form control of the input field
public get input(): AbstractControl {
return this.searchInputForm.get('input');
}
// Default page size
private readonly defaultLimit: number = 10;
private skip: number = 0;
public limit: number = this.defaultLimit;
public currentPage: number = 1;
// Max number of size for pagination truncate
public maxNumberOfSites: number[];
private initSearch: boolean = true;
private initFilter: boolean = true;
public searchInputForm: UntypedFormGroup;
// List of search results
public searchResultList: SearchResultList;
public publicIdResult;
public filterResultList: any[];
public queryParameters: any = [];
private subscriber: ReplaySubject<void> = new ReplaySubject<void>();
public readonly defaultResultSizeList: Array<PageLengthEntry> = [
{ label: '10', value: 10 },
{ label: '25', value: 25 },
{ label: '50', value: 50 },
{ label: '100', value: 100 },
{ label: '200', value: 200 }
];
// Page size select form group
public resultSizeForm: UntypedFormGroup = new UntypedFormGroup({
size: new UntypedFormControl(this.limit),
});
/* ------------------------------------------------------------------------------------------------------------------ */
/* LIFE CYCLE */
/* ------------------------------------------------------------------------------------------------------------------ */
constructor(private route: ActivatedRoute, private searchService: SearchService, private router: Router) {
this.searchInputForm = new UntypedFormGroup({
input: new UntypedFormControl('', Validators.required)
});
}
public ngOnInit(): void {
this.route.queryParamMap.pipe(takeUntil(this.subscriber)).subscribe(params => {
this.queryParameters = params.get('query');
if (params.has('limit')) {
this.limit = (+JSON.parse(params.get('limit')));
this.resultSizeForm.get('size').setValue(this.limit);
}
if (params.has('page')) {
this.currentPage = (+JSON.parse(params.get('page')));
} else {
this.currentPage = 1;
}
if (params.has('skip')) {
this.skip = (+JSON.parse(params.get('skip')));
} else {
this.skip = 0;
}
this.initSearch = true;
this.initFilter = (window.history.state.load || window.history.state.load === undefined);
this.onSearch();
});
this.resultLength.valueChanges.pipe(takeUntil(this.subscriber))
.subscribe((size: number) => {
this.limit = size;
this.router.navigate(
[],
{
relativeTo: this.route,
queryParams: { limit: this.limit },
queryParamsHandling: 'merge'
}).then();
this.onSearch();
});
}
public ngOnDestroy(): void {
this.subscriber.next();
this.subscriber.complete();
}
/* ------------------------------------------------ HELPER FUNCTIONS ------------------------------------------------ */
/**
* Get the form control of the size selection
*/
public get resultLength(): UntypedFormControl {
return this.resultSizeForm.get('size') as UntypedFormControl;
}
/**
* Triggers the actual search api call
*/
public onSearch(): void {
this.publicIdResult = undefined;
let params = new HttpParams();
params = params.set('limit', this.limit.toString());
params = params.set('skip', this.skip.toString());
this.searchService.postSearch(this.queryParameters, params).pipe(
takeUntil(this.subscriber)).subscribe((results: SearchResultList) => {
this.searchResultList = results;
this.filterResultList = this.initFilter && results !== null ? results.groups : this.filterResultList;
if (this.initSearch) {
this.maxNumberOfSites = Array.from({ length: (this.searchResultList.total_results) }, (v, k) => k + 1);
this.initSearch = false;
this.initFilter = false;
}
}
);
let localParameters = JSON.parse(this.queryParameters);
if (localParameters.length === 1) {
localParameters[0].searchForm = 'publicID';
localParameters = JSON.stringify(localParameters);
this.searchService.postSearch(localParameters, params).pipe(takeUntil(this.subscriber))
.subscribe((results: SearchResultList) => {
if (results !== null && results.results.length > 0) {
this.publicIdResult = results.results[0];
}
}
);
}
}
/**
* Pagination page was changed.
* @param event: Data from the change event.
*/
public onChangePage(event): void {
this.currentPage = event;
this.skip = (this.currentPage - 1) * this.limit;
this.setPageParam(this.currentPage);
this.onSearch();
}
private setPageParam(page): void {
this.router.navigate(
[],
{
relativeTo: this.route,
queryParams: { page, skip: this.skip, query: this.queryParameters },
queryParamsHandling: 'merge'
}
).then();
}
}
|
"""untangledstrings URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
from untangled import views
urlpatterns = [
path('', include('untangled.urls')),
# path('untangled/', include('untangled.urls')),
path('admin/', include('untangledStringsAdmin.urls')),
path('admin/', admin.site.urls),
path('ckeditor/', include('ckeditor_uploader.urls')),
path('login', auth_views.LoginView.as_view(), name='login'),
path('oauth/', include('social_django.urls', namespace='social')),
path('users/', include('django.contrib.auth.urls')),
path('ckeditor/', include('ckeditor_uploader.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/View/navBar.dart';
class Splash extends StatefulWidget {
const Splash({Key? key});
@override
State<Splash> createState() => _SplashState();
}
class _SplashState extends State<Splash> {
double _scale = 1.0;
@override
void initState() {
super.initState();
_startAnimation();
}
void _startAnimation() {
Timer.periodic(Duration(milliseconds: 1000), (timer) {
setState(() {
_scale = _scale == 1.0 ? 1.1 : 1.0;
});
});
}
@override
Widget build(BuildContext context) {
double myHeight = MediaQuery.of(context).size.height;
double myWidth = MediaQuery.of(context).size.width;
return SafeArea(
child: Scaffold(
backgroundColor: Colors.white,
body: Container(
height: myHeight,
width: myWidth,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
AnimatedContainer(
duration: Duration(milliseconds: 1000),
curve: Curves.easeInOut,
height: myHeight * 0.3 * _scale,
child: Image.asset('assets/image/logo.png'),
),
Column(
children: [
Text(
'Safe Car Rental',
style: TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
),
Text(
'Rent a car with us',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.normal,
color: Colors.grey),
),
Text(
' and enjoy your trip!',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.normal,
color: Colors.grey),
),
],
),
Padding(
padding: EdgeInsets.symmetric(horizontal: myWidth * .14),
child: GestureDetector(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => NavBar()));
},
child: Container(
decoration: BoxDecoration(
color: Color(0xFF9C27B0),
borderRadius: BorderRadius.circular(50)),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: myWidth * .05, vertical: myHeight * .013),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Get Started',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.normal,
color: Colors.white),
),
],
),
),
),
),
)
],
),
),
),
);
}
}
|
import React, { ChangeEvent, ReactElement } from "react";
import {
CartItemType,
ReducerAction,
ReducerActionType,
} from "../context/CartProvider";
type PropsType = {
item: CartItemType;
dispatch: React.Dispatch<ReducerAction>;
REDUCER_ACTIONS: ReducerActionType;
};
const CartItem = ({ item, dispatch, REDUCER_ACTIONS }: PropsType) => {
const img: string = new URL(`../images/${item.sku}.jpg`, import.meta.url)
.href;
const lineTotal: number = item.qty * item.price;
const highestQty: number = 20 > item.qty ? 20 : item.qty;
const optionValues: number[] = [...Array(highestQty).keys()].map(i => i + 1)
const options: ReactElement[] = optionValues.map((value) => {
return <option key={`opt${value}`} value={value}>{value}</option>;
});
const changeQty = (e: ChangeEvent<HTMLSelectElement>) => {
dispatch({
type: REDUCER_ACTIONS.QUANTITY,
payload: { ...item, qty: Number(e.target.value) },
});
};
const removeItem = () => {
return dispatch({ type: REDUCER_ACTIONS.REMOVE, payload: item });
};
const content = (
<li className="grid grid-cols-cart-item-sm md:grid-cols-cart-item-md gap-2 mb-[0.5em]">
<img src={img} alt={item.name} className="hidden md:block min-w-[68px]" />
<div aria-label="Item Name">{item.name}</div>
<div aria-label="Price Per Item">
{new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(item.price)}
</div>
<label htmlFor="itemQty" className="absolute left-[-10000px]">
Item Quantity
</label>
<select
name="itemQty"
id="itemQty"
className="max-h-[48px]"
value={item.qty}
aria-label="Item Quantity"
onChange={changeQty}
>
{options}
</select>
<div className="hidden md:block text-center" aria-label="Line Item Subtotal">
{new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(lineTotal)}
</div>
<button
className="max-h-[48px] justify-self-end"
aria-label="Remove Item From Cart"
title="Remove Item From Cart"
onClick={removeItem}
>
❌
</button>
</li>
);
return content;
};
export default CartItem;
|
/*
* The MIT License (MIT) Copyright (c) 2014 Ordinastie Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions: The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.malisis.core.client.gui.component.interaction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.malisis.core.client.gui.GuiRenderer;
import net.malisis.core.client.gui.MalisisGui;
import net.malisis.core.client.gui.component.IGuiText;
import net.malisis.core.client.gui.component.UIComponent;
import net.malisis.core.client.gui.element.SimpleGuiShape;
import net.malisis.core.client.gui.event.ComponentEvent.ValueChange;
import net.malisis.core.client.gui.icon.GuiIcon;
import net.malisis.core.renderer.RenderParameters;
import net.malisis.core.renderer.font.FontRenderOptions;
import net.malisis.core.renderer.font.MalisisFont;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.opengl.GL11;
/**
* @author Ordinastie
*
*/
public class UIRadioButton extends UIComponent<UIRadioButton> implements IGuiText<UIRadioButton> {
private static HashMap<String, List<UIRadioButton>> radioButtons = new HashMap<>();
protected GuiIcon bgIcon;
protected GuiIcon bgIconDisabled;
protected GuiIcon rbDisabled;
protected GuiIcon rbChecked;
protected GuiIcon rbHovered;
/** The {@link MalisisFont} to use for this {@link UIRadioButton}. */
protected MalisisFont font = MalisisFont.minecraftFont;
/** The {@link FontRenderOptions} to use for this {@link UIRadioButton}. */
protected FontRenderOptions fro = new FontRenderOptions();
private String name;
private String text;
private boolean selected;
public UIRadioButton(MalisisGui gui, String name, String text) {
super(gui);
this.name = name;
setText(text);
fro.color = 0x444444;
shape = new SimpleGuiShape();
bgIcon = gui.getGuiTexture().getIcon(200, 54, 8, 8);
bgIconDisabled = gui.getGuiTexture().getIcon(200, 62, 8, 8);
rbDisabled = gui.getGuiTexture().getIcon(208, 54, 6, 6);
rbChecked = gui.getGuiTexture().getIcon(214, 54, 6, 6);
rbHovered = gui.getGuiTexture().getIcon(220, 54, 6, 6);
addRadioButton(this);
}
public UIRadioButton(MalisisGui gui, String name) {
this(gui, name, null);
}
// #region Getters/Setters
@Override
public MalisisFont getFont() {
return font;
}
@Override
public UIRadioButton setFont(MalisisFont font) {
this.font = font;
calculateSize();
return this;
}
@Override
public FontRenderOptions getFontRenderOptions() {
return fro;
}
@Override
public UIRadioButton setFontRenderOptions(FontRenderOptions fro) {
this.fro = fro;
calculateSize();
return this;
}
/**
* Sets the text for this {@link UIRadioButton}.
*
* @param text the new text
*/
public UIRadioButton setText(String text) {
this.text = text;
calculateSize();
return this;
}
/**
* Gets the text for this {@link UICheckBox}.
*
* @return the text
*/
public String getText() {
return text;
}
/**
* Checks if this {@link UIRadioButton} is selected.
*
* @return true, if is selected
*/
public boolean isSelected() {
return selected;
}
/**
* Sets state of this {@link UIRadioButton} to selected.<br>
* If a radiobutton with the same name is currently selected, unselects it.<br>
* Does not fire {@link SelectEvent}.
*
* @return the UI radio button
*/
public UIRadioButton setSelected() {
UIRadioButton rb = getSelected(name);
if (rb != null) rb.selected = false;
selected = true;
return this;
}
// #end Getters/Setters
/**
* Calculates the size for this {@link UIRadioButton}.
*/
private void calculateSize() {
int w = StringUtils.isEmpty(text) ? 0 : (int) font.getStringWidth(text, fro);
setSize(w + 11, 10);
}
@Override
public void drawBackground(GuiRenderer renderer, int mouseX, int mouseY, float partialTick) {
shape.resetState();
shape.setSize(8, 8);
shape.translate(1, 0, 0);
rp.icon.set(isDisabled() ? bgIconDisabled : bgIcon);
renderer.drawShape(shape, rp);
renderer.next();
// draw the white shade over the slot
if (hovered) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_ALPHA_TEST);
renderer.enableBlending();
rp = new RenderParameters();
rp.colorMultiplier.set(0xFFFFFF);
rp.alpha.set(80);
rp.useTexture.set(false);
shape.resetState();
shape.setSize(6, 6);
shape.setPosition(2, 1);
renderer.drawShape(shape, rp);
renderer.next();
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
if (text != null) renderer.drawText(font, text, 12, 0, 0, fro);
}
@Override
public void drawForeground(GuiRenderer renderer, int mouseX, int mouseY, float partialTick) {
if (selected) {
GL11.glEnable(GL11.GL_BLEND);
rp.reset();
shape.resetState();
shape.setSize(6, 6);
shape.setPosition(2, 1);
rp.icon.set(isDisabled() ? rbDisabled : (isHovered() ? rbHovered : rbChecked));
renderer.drawShape(shape, rp);
}
}
@Override
public boolean onClick(int x, int y) {
if (fireEvent(new UIRadioButton.SelectEvent(this))) setSelected();
return true;
}
public static void addRadioButton(UIRadioButton rb) {
List<UIRadioButton> listRb = radioButtons.get(rb.name);
if (listRb == null) listRb = new ArrayList<>();
listRb.add(rb);
radioButtons.put(rb.name, listRb);
}
public static UIRadioButton getSelected(String name) {
List<UIRadioButton> listRb = radioButtons.get(name);
if (listRb == null) return null;
for (UIRadioButton rb : listRb) if (rb.selected) return rb;
return null;
}
public static UIRadioButton getSelected(UIRadioButton rb) {
return getSelected(rb.name);
}
/**
* Event fired when a {@link UIRadioButton} changes its selection.<br>
* When catching the event, the state is not applied to the {@code UIRadioButton} yet.<br>
* Cancelling the event will prevent the value to be changed.
*/
public static class SelectEvent extends ValueChange<UIRadioButton, UIRadioButton> {
public SelectEvent(UIRadioButton component) {
super(component, getSelected(component), component);
}
}
}
|
import request from "supertest";
import { Types } from "mongoose";
import app from "../../app";
import { natsClient } from "../../NatsClient";
import { Subjects } from "@nftickets/common";
import { Ticket } from "../../models";
const createTicket = (cookie: string[]) =>
request(app).post("/api/tickets").set("Cookie", cookie).send({
title: "Some stuff",
price: 10,
});
const updateTicket = (id: string, cookie: string[], newTicket: object) =>
request(app).put(`/api/tickets/${id}`).set("Cookie", cookie).send(newTicket);
it("Return 404 if the provided id doesn't exists", async () => {
const id = new Types.ObjectId().toHexString();
await request(app)
.put(`/api/tickets/${id}`)
.set("Cookie", global.signin())
.send({
title: "Some stuff",
price: 10,
})
.expect(404);
});
it("Return 401 if the user is not signed in", async () => {
const id = new Types.ObjectId().toHexString();
await request(app)
.put(`/api/tickets/${id}`)
.send({
title: "Some stuff",
price: 10,
})
.expect(401);
});
it("Return 401 if the user doesn't own the ticket", async () => {
const response = await createTicket(global.signin());
await request(app)
.put(`/api/tickets/${response.body.id}`)
.set("Cookie", global.signin())
.send({
title: "New some stuff",
price: 3000,
})
.expect(401);
});
it("Return 400 if the user provided invalid title or price", async () => {
const cookie = global.signin();
const response = await createTicket(cookie);
await updateTicket(response.body.id, cookie, { title: "", price: 20 }).expect(
400
);
await updateTicket(response.body.id, cookie, {
title: "New some stuff",
price: -20,
}).expect(400);
});
it("Update if the ticket provided valid inputs", async () => {
const cookie = global.signin();
const newTicket = { title: "New some stuff", price: 100 };
const response = await createTicket(cookie);
await updateTicket(response.body.id, cookie, newTicket).expect(200);
const ticketResponse = await request(app)
.get(`/api/tickets/${response.body.id}`)
.send();
expect(ticketResponse.body.title).toEqual(newTicket.title);
expect(ticketResponse.body.price).toEqual(newTicket.price);
});
it("Publishes an event", async () => {
const cookie = global.signin();
const newTicket = { title: "New some stuff", price: 100 };
const response = await createTicket(cookie);
await updateTicket(response.body.id, cookie, newTicket).expect(200);
expect(natsClient.client.publish).toHaveBeenLastCalledWith(
Subjects.TicketUpdated,
expect.anything(),
expect.anything()
);
});
it("Rejects updates if the ticket is reserved", async () => {
const cookie = global.signin();
const newTicket = { title: "New some stuff", price: 100 };
const { body } = await createTicket(cookie);
const ticket = await Ticket.findById(body.id);
await ticket!.set({ orderId: Types.ObjectId().toHexString() }).save();
await updateTicket(body.id, cookie, newTicket).expect(400);
});
|
package com.soa.filter;
import com.soa.dto.FilterQueryDto;
import com.soa.exception.NotValidParamsException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
@AllArgsConstructor
public class FilterService {
public static void isValidRequestParams(FilterQueryDto dto) {
if (dto.getId() != null) {
checkNumberIsPositive("Id", dto.getId());
}
if (dto.getName() != null) {
checkValidName(dto.getName());
}
if (dto.getSort() != null) {
checkSortParams(dto.getSort());
}
if (dto.getMinEnginePower() != null) {
checkValidEnginePower(dto.getMinEnginePower());
}
if (dto.getMaxEnginePower() != null) {
checkValidEnginePower(dto.getMaxEnginePower());
}
if (dto.getMaxEnginePower() != null && dto.getMinEnginePower() != null) {
checkMinEnginePowerIsSmallerThanMaxEnginePower(dto.getMinEnginePower(), dto.getMaxEnginePower());
}
if (dto.getLimit() != null) {
checkNumberIsPositive("Limit", dto.getLimit());
}
if (dto.getOffset() != null) {
checkNumberIsPositive("Offset", dto.getOffset());
}
}
public static void checkValidName(String name) {
checkEmpty(name);
if (name.length() < 3) {
throw new NotValidParamsException("Длина имени должна быть больше 3");
}
}
public static void checkSortParams(String sort) {
checkEmpty(sort);
if (!(sort.equals("asc") || sort.equals("desc"))) {
throw new NotValidParamsException("Неверный параметр сортировки");
}
}
public static void checkNumberIsPositive(String nameOfField, Integer number) {
if (number <= 0) {
throw new NotValidParamsException(nameOfField + " должен быть больше 0");
}
}
public static void checkMinEnginePowerIsSmallerThanMaxEnginePower(BigDecimal min, BigDecimal max) {
if (max.compareTo(min) < 0) {
throw new NotValidParamsException("Максимальное значение мощности должно быть меньше минимального");
}
}
public static void checkValidEnginePower(BigDecimal enginePower) {
if (enginePower.compareTo(BigDecimal.valueOf(0L)) < 0) {
throw new NotValidParamsException("Сила двигателя должна быть больше 0");
}
}
public static void checkEmpty(String value) {
if (value == null || value.isBlank()) {
throw new NotValidParamsException("Поля не должны быть пустыми");
}
}
}
|
import React, {useEffect, useRef, useState} from "react";
import Header from "./header";
import {Route, Routes} from "react-router-dom";
import Home from "../pages/home";
import Products from "../pages/products/products";
import Footer from "./footer";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../assets/css/App.css'
import AboutUs from "../pages/about-us";
import SeasonalPlants from "../pages/products/seasonal-plants";
import LivePlants from "../pages/products/live-plants";
import Seeds from "../pages/products/seeds";
import Tools from "../pages/products/tools";
import {isMobile} from "react-device-detect";
function Fulllayout() {
const [isLoaded, set_isLoaded] = useState(false);
// if (!isLoaded) {
// return <div style={{marginTop: '15%'}}><LoaderSpinner/></div>
// } else {
return (
<div>
<Header/>
<div className={isMobile ? 'mobile_view container-fluid' : 'body_view container-fluid'}>
<Routes>
<Route index path="/" element={<Home/>}/>
<Route path="/products" element={<Products/>}/>
<Route path="/seasonal-variety" element={<SeasonalPlants/>}/>
<Route path="/live-plants" element={<LivePlants/>}/>
<Route path="/pots-tools" element={<Tools/>}/>
<Route path="/seeds" element={<Seeds/>}/>
<Route path="/About-Us" element={<AboutUs/>}/>
{/*<Route path="*" element={<NoPage />} />*/}
</Routes>
</div>
<Footer/>
</div>
)
}
export default Fulllayout;
|
import {
FocusEventHandler,
InputHTMLAttributes,
forwardRef,
useState,
} from "react";
import { ErrorMessage } from "./ErrorMessage";
import { v1 } from "uuid";
type InputProps = {
label: string;
errorMessage: string | undefined;
} & InputHTMLAttributes<HTMLInputElement>;
export const InputField = forwardRef<HTMLInputElement, InputProps>(
({ label, errorMessage, ...otherProps }, ref) => {
const [isLabelOnTop, setIsLabelOnTop] = useState(false);
const onBlurHandler: FocusEventHandler<HTMLInputElement> = (e) => {
const value = e.currentTarget.value;
setIsLabelOnTop(value.trim() !== "");
};
const onFocusHandler = () => setIsLabelOnTop(true);
const id = v1();
return (
<div className="relative flex flex-col gap-1">
<input
{...otherProps}
className={`relative ${errorMessage && "shadow-[0_0px_2px_2px_rgba(0,0,0,0.3)] shadow-red-500"} border border-slate-300 px-3 py-3 shadow-lg placeholder:text-sm placeholder:uppercase focus:outline-none`}
ref={ref}
onBlur={onBlurHandler}
onFocus={onFocusHandler}
id={id}
/>
<label
htmlFor={id}
className={`absolute select-none ${isLabelOnTop ? "-top-5 left-0.5" : "left-3 top-3.5"} text-sm uppercase text-slate-500 transition-all duration-200`}
>
{label}
</label>
<ErrorMessage message={errorMessage} />
</div>
);
},
);
|
<a name="readme-top"></a>
<div align="center">
<img src="logo.svg" alt="logo" width="240" height="auto" />
<br/>
<h3><b>Lendsqr_fe_test README </b></h3>
</div>
# 📗 Table of Contents
- [📗 Table of Contents](#-table-of-contents)
- [📖 Lendqsr\_fe\_test ](#-lendqsr_fe_test-)
- [🛠 Built With Typescript React and SCSS](#-built-with--typescript-react-and-scss)
- [Tech Stack ](#tech-stack-)
- [Key Features ](#key-features-)
- [🚀 Live Demo ](#-live-demo-)
- [💻 Getting Started ](#-getting-started-)
- [Prerequisites](#prerequisites)
- [Setup](#setup)
- [Install](#install)
- [Usage](#usage)
- [Deployment : Deploy this project using npm run build](#deployment--deploy-this-project-using-npm--run-build)
- [`npm run build`](#npm-run-build)
- [👥 Author ](#-author-)
- [❓ FAQ ](#-faq-)
- [📝 License ](#-license-)
# 📖 Lendqsr_fe_test <a name="about-project"></a>
## 🛠 Built With <a name="built-with"> Typescript React and SCSS</a>
### Tech Stack <a name="tech-stack"></a>
<details>
<summary>Client</summary>
<ul>
<li><a href="https://www.typescriptlang.org/">Typescript React</a></li>
<li><a href="https://sass-lang.com/">SCSS</a></li>
</ul>
</details>
<details>
<summary>Server</summary>
<ul>
<li><a href="https://www.google.com/url?q=https://6270020422c706a0ae70b72c.mockapi.io/lendsqr/api/v1/users&sa=D&source=editors&ust=1674066247745072&usg=AOvVaw1oWbP6U5D2-NEE4ATlj0b0">Supplied Endpoints</a></li>
</ul>
</details>
### Key Features <a name="key-features"></a>
- **Login :** Users are able to login using their registered email with their BVN as password.
- **View Users :** The user_table shows the summary of all users
- **View User Details :** From the user_table, clicking "view details" on a user will take take you to the user's dashboard with full details of the user
- **NOTE :** You need to be logged in to access the full app. Check Frequently Asked Questions below for details.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
## 🚀 Live Demo <a name="live-demo"></a>
- [Live Demo Link](https://onoja-victor-lendsqr-fe-test.netlify.app/)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
## 💻 Getting Started <a name="getting-started"></a>
To get a local copy up and running, follow these steps.
### Prerequisites
In order to run this project you need: `Node Package Manager (npm)`
### Setup
Clone this repository to your desired folder:
Example commands:
cd my-folder
git clone https://github.com/jsvoo/Onoja-Victor-Lendsqr-fe-test.git
### Install
Install this project with: `npm install`
### Usage
To run the project, execute the following command: `npm start`
This runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
## Deployment : Deploy this project using npm run build
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
## 👥 Author <a name="authors"></a>
👤 **Onoja Victor**
- GitHub: [@jsvoo](https://github.com/jsvoo)
- LinkedIn: [@jsvoo](linkedin.com/in/victor-ojogbane-onoja-52a077145)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
## ❓ FAQ <a name="faq"></a>
- **What details can I use to login on the app?**
- You can access the app by logging in with any of the users from this enpoint https://6270020422c706a0ae70b72c.mockapi.io/lendsqr/api/v1/users. Use the user's email for the email field, and their BVN as password.
- **Can I use the app without logging in?**
- No. you need to login to access other parts of the application
<p align="right">(<a href="#readme-top">back to top</a>)</p>
## 📝 License <a name="license"></a>
This project is [MIT](./LICENSE) licensed.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
const DonatedItem = ({ donation }) => {
const { id, picture, title, price, category } = donation;
return (
<div>
<div className="card rounded-lg card-side bg-base-100 shadow-xl flex gap-3 items-center" style={{ background: donation.card_bg }}>
<figure className='h-full w-1/2'><img src={picture} alt="Photos" /></figure>
<div className="card-body space-y-2 py-2">
<button className='px-1 font-medium rounded' style={{ backgroundColor: donation.card_bg, color: donation.text_color }}>{category}</button>
<h2 className="card-title text-xl font-semibold" style={{ color: donation.category_bg }} >{title}</h2>
<p className='font-semibold' style={{ color: donation.category_bg }}>{price}</p>
<div className="card-actions justify-end">
</div>
<Link to={`/donation/${id}`}>
<button className="btn px-4 py-2 rounded text-white font-semibold" style={{ background: donation.category_bg }}>View Details</button>
</Link>
</div>
</div>
</div>
);
};
export default DonatedItem;
DonatedItem.propTypes = {
donation: PropTypes.object,
}
|
import { FileImageOutlined, MoreOutlined, SendOutlined, SmileOutlined } from "@ant-design/icons";
import { Avatar, Card, Col, Form, List, Row, Skeleton, Space, Input, Button, Select, Typography, theme, Tooltip, FormInstance } from "antd";
import { useEffect, useRef, useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";
import { useMutation, useQuery } from "react-query";
import { io } from "socket.io-client";
import { useAppSelector } from "src/shared/hooks/useRedux";
import { messageService } from "../servers/message.service";
import { conversationService } from "../servers/conversation.service";
import { arrangeListMessage, validateTime } from "../utils/formValidator";
import { userService } from "../servers/user.service";
import { IMessageNew } from "../typeDef/message.type";
import { useDispatch } from "react-redux";
import { setCurrentConversationIdChat } from "../store/appSlice";
import { setCookie } from "cookies-next";
import data from '@emoji-mart/data'
import Picker from '@emoji-mart/react'
interface Props{
currentUserIdChat: number
}
const BoxChat = ({currentUserIdChat}: Props) => {
const [form] = Form.useForm();
const listRef = useRef<any>(null);
const [emoji, setEmoji] = useState(null);
const [trigger, setTrigger] = useState(false);
const [socket, setSocket] = useState(io(`${process.env.NEXT_PUBLIC_BACKEND_BASE_URL_DEFAULT}`,{ transports : ['websocket']}));
const [messages, setMessages] = useState<string[]>([]);
const [isChanged, setIsChanged] = useState<boolean>(false)
const {dataUser, currentConversationIdChat} = useAppSelector((state) => state.appSlice)
const { token } = theme.useToken();
const dataUserChat: any = messages.find((item:any) => item.user.id !== dataUser?.id)
const dispatch = useDispatch()
const handleSelectEmoji = (e:any) => {
setEmoji(e.native);
setTrigger(!trigger)
};
const suffix = (
<Row gutter={16} align="middle">
<Col style={{ height: 48, display: "flex", alignItems: "center" }}>
<Tooltip open={trigger} color={"transparent"} title={ <Picker previewPosition={top} data={data} onEmojiSelect={(e:any) => handleSelectEmoji(e)} /> }>
<SmileOutlined onClick={() => setTrigger(!trigger)} style={{fontSize: 16, color: '#1890ff'}}/>
</Tooltip>
</Col>
<Col style={{ height: 48, display: "flex", alignItems: "center" }}>
<FileImageOutlined style={{fontSize: 16, color: '#1890ff'}}/>
</Col>
<Col style={{ height: 48, display: "flex", alignItems: "center" }}>
<Button htmlType="submit" style={{ borderStyle: "none", textAlign: "center"}}>
<SendOutlined style={{ fontSize: 16, color: '#1890ff'}}/>
</Button>
</Col>
</Row>
);
// const [conversationIdGet, setConversationIdGet] = useState<number>()
// useQuery(["conversation", roomId], () => conversationService.getConversation({conversationId: roomId}), {
// select(data:any) {
// return data.data.participants
// },
// onSuccess(data) {
// const filterUser = data.find((item:any) => item.user.name !== dataUser?.name)
// setUserConversation(filterUser.conversationId)
// },
// })
// console.log(userConversation)
const { data: dataMessCurrent } = useQuery(["dataMessCurrent", currentUserIdChat], () => messageService.getMessage({senderId: dataUser?.id!}), {
select(data:any) {
return data.data
}
})
const { data: messageSend } = useQuery(["messageSend", currentUserIdChat], () => messageService.getMessage({senderId: currentUserIdChat!}), {
select(data:any) {
return data.data
},
onSuccess(data) {
const messageSend: any = data.filter((innerArray:any) => {
const conversationCurrent = dataMessCurrent.find((item:any) => item.conversationId === innerArray.conversationId)
return conversationCurrent
})
const conversationId = messageSend.find((item:any) => item.conversationId)
const currentConversationIdChat = dispatch(setCurrentConversationIdChat(conversationId.conversationId))
setCookie("currentConversationIdChat", currentConversationIdChat)
setMessages((prevMessages) => [
...prevMessages,
...messageSend.map((mes:any) => {
return {
message: mes.body,
time: mes.createdAt,
user: mes.sender
}
})])
},
enabled: !!currentUserIdChat && !!dataMessCurrent
})
const { data: messageGet } = useQuery(["messageGet", currentUserIdChat], () => messageService.getMessage({senderId: dataUser?.id!}), {
select(data:any) {
return data.data
},
onSuccess(data) {
if(messageSend){
const messageGet: any = data.filter((innerArray:any) => {
const conversationCurrent = messageSend.find((item:any) => item.conversationId === innerArray.conversationId)
return conversationCurrent
})
setMessages((prevMessages) => [
...prevMessages,
...messageGet.map((mes:any) => {
return {
message: mes.body,
time: mes.createdAt,
user: mes.sender
}
})])}
},
enabled: !!currentUserIdChat && !!messageSend
})
const createMutation = useMutation({
mutationKey: ['createMessage'],
mutationFn: (body: IMessageNew) => messageService.newMessage(body),
})
const loadMoreData = () => {
return
}
useEffect(() => {
setMessages([])
socket.on("new message", message => {
setMessages((prevMessages) => [...prevMessages, message]);
});
return () => {
socket.off('new message');
};
}, [currentUserIdChat]);
const handleMessage = (value:{message: string}) => {
const formCreate = {
newMessage: value.message as string,
conversationId: currentConversationIdChat,
senderId: dataUser?.id as number
}
createMutation.mutate(formCreate)
setIsChanged(false)
socket.emit("send message", {message: value.message, user: dataUser});
form.resetFields();
listRef.current?.scrollIntoView({ behavior: 'smooth' });
};
return (
<>
<Form style={{minHeight: "600px", backgroundColor: token.colorBgLayout, position: "relative", borderRadius: 10}}
form={form}
onFinish={handleMessage}
autoComplete="off"
name="basic"
scrollToFirstError={true}
>
<Card style={{position: "absolute", top: 0, left:0, width: "100%", opacity: 0.7, backdropFilter: "blur(10px)", zIndex: "10", backgroundBlendMode: "lighten"}}>
<div className="text-2xl flex items-center justify-start">
<Avatar className="block m-2 max-w-[32px] max-h-[32px] rounded-[50px]" alt="userIcon" src={`${dataUserChat?.user.image}`} />
<Typography>{dataUserChat?.user.username}</Typography>
<MoreOutlined style={{fontSize: "18px", position: "absolute", right: 10}} />
</div>
</Card>
{
messages && messageGet && messageSend &&
<>
<div id="scrollableDiv" style={{height: 450, overflow: 'auto', padding: '0 16px'}}>
<InfiniteScroll
ref={listRef}
dataLength={messages.length}
next={loadMoreData}
hasMore={messages.length < 50}
loader={isChanged && <Skeleton avatar paragraph={{ rows: 1 }} active />}
scrollableTarget="scrollableDiv"
>
<List
style={{marginTop: 120}}
grid={{column: 1}}
itemLayout="horizontal"
dataSource={arrangeListMessage(messages as [])}
renderItem={(item, index) => (
<List.Item style={{float: item?.user.username !== dataUser?.username ? "right" : "left", borderStyle: "none"}}>
<div style={{backgroundColor: item?.user.username !== dataUser?.username ? "#C0DBEA": token.colorBgContainer, borderRadius: 10, padding: "12px 24px"}}>
<Typography>{item?.message}</Typography>
</div>
<p style={{fontSize: "12px", float:"left", margin: "5px 10px"}}>{validateTime(item?.time).split("(")[0]}</p>
</List.Item>
)}
/>
</InfiniteScroll>
</div>
<Space.Compact
style={{
position: "absolute",
display: "flex",
alignItems: "center",
width: '100%',
height: "10%",
backgroundColor: "#fff",
bottom: 0,
}}>
<Form.Item style={{width: "100%",margin: 0}} name="message">
<Input onChange={() => setIsChanged(true)} size="large" bordered={false} maxLength={100} style={{ resize: 'none' }} allowClear suffix={suffix}/>
</Form.Item>
</Space.Compact>
</>
}
</Form>
</>
);
}
export default BoxChat;
|
- [[#2.1 Introduction|2.1 Introduction]]
- [[#2.2 The Landau-Ginzburg Hamiltonian|2.2 The Landau-Ginzburg Hamiltonian]]
- [[#2.3 Saddle point approximation,and mean-field theory|2.3 Saddle point approximation,and mean-field theory]]
## 2.1 Introduction
上一章中我们说到,临界点的热力学函数可以通过一系列临界指数$\{\alpha,\beta,\gamma,\cdots \}$进行表征. 实验上也表明了这些指数是普适的,即与所研究的材料无关,并且在某种程度上与相变的性质无关,比如$\text{CO}_2$的冷凝过程中共存边界的消失与蛋白质溶液相分离具有相同的奇异行为. 这种普适性需要解释.
我们还注意到,响应函数的发散以及通过散射实验对涨落的直接观察表明,涨落在临界点附近具有长波关联$\xi \gg a$. 这种关联的涨落涉及许多粒子,并且本着弹性理论的启发,粗粒化的方法可能适合它们的描述. 这里我们将构建这样一个*统计场论*.
我们首先关注磁性系统,它们的对称性更加透明. 考虑像铁这样的材料,实验上观察到在居里温度$T_c$以下其具有铁磁性. 磁性的微观起源是量子力学,涉及巡游电子、自旋和相互作用等元素,可以用一个微观哈密顿量$\mathcal{H}_{\text{mic}}$描述. 原则上,系统的所有热力学性质都可以从配分函数中得到,这样的配分函数可以通过对所有自由度求和而得到
$$
Z(T) = \mathrm{tr} \left[ e^{-\beta \mathcal{H}_{\text{mic}}} \right],\quad \text{with} \quad \beta = \frac{1}{k_B T}.
$$
实际上这个公式并不常用,因为微观哈密顿量和其自由度非常复杂,很难进行计算.
为了找出可能产生铁磁性的元素微观理论是必要的,然而考虑到存在磁行为,这样的理论不一定适用于描述热涨落导致的磁性消失. 为了解决后者,相互作用电子的量子统计理论是一个过于复杂的起点. 相反我们观察到**靠近居里点的重要自由度是自旋的长波长集体激发**(很像在低温下主导固体热容的长波长声子). 因此,关注这些最终导致相变的波动的统计特性更有意义.
为此,我们将焦点从微观尺度转移到比晶格间距大得多但比系统尺寸小得多的中间介观尺度. 以类似于图1.1中描述的粗粒化过程的方式,我们定义磁化场$\vec{m}(\mathbf{x})$ ,它表示点$\mathbf{x}$附近的自旋的平均值. 需要强调的是,虽然$\mathbf{x}$被视为连续变量,但函数$\vec{m}(\mathbf{x})$在晶格间距量级的距离上不表现出任何变化,即其傅里叶变换仅涉及小于某个上截断$\Lambda \sim 1/a$的波矢.
![[Pasted image 20240312151849.png|650]]
从原始自由度到场$\vec{m}(\mathbf{x})$的变换是变量的变化,这种映射是不可逆的,因为在平均的过程中丧失了很多微观细节(每一个场的构型对应着许多微观构型,将这些微观构型的权重加起来即可). 同样原则上可以通过变换由玻尔兹曼权重$e^{-\beta \mathcal{H}_{\text{mic}}}$产生的原始微观概率来得到场$\vec{m}(\mathbf{x})$的构型的相应概率. 新的配分函数可以写成
$$
Z(T) = \mathrm{tr} \left[ e^{-\beta \mathcal{H}_{\text{mic}}} \right] \equiv \int \mathcal{D} \vec{m}(\mathbf{x}) \mathcal{W} \left[ \vec{m}(\mathbf{x}) \right].
\tag{2.2}
$$
其中$\mathcal{D}\vec{m}(\mathbf{x})$表示对场所有允许的构型做积分,而每种构型的权重$\mathcal{W}(\vec{m}(\mathbf{x}))$是我们希望得到的.
得到$\mathcal{W}(\vec{m}(\mathbf{x}))$的精确形式并不比解决整个问题容易,但实际上可以用一些唯象参数来描述它(这类似于用几个弹性模量描述固体变形的能量成本). 在相变的背景下,朗道首先应用这种方法来描述氦中超流的出现. 实际上这种方法可以普遍的应用于经历相变的不同类型的系统,其中$\vec{m}(\mathbf{x})$描述相应的序参量场. 我们将这个问题一般化,考虑一个$d$维空间中的$n$分量场
$$
\mathbf{x} \equiv (x_1,x_2,\cdots,x_d) \in \Re^d \quad (\text{space}),\quad \vec{m} \equiv (m_1,m_2,\cdots,m_n) \in \Re^n \quad (\text{order parameter}).
$$
这个一般性的框架涵盖的具体例子包括:
$n=1$描述了气液相变、二元混合物以及单轴磁体;
$n=2$应用于超流、超导和平面磁铁;
$n = 3$对应与经典磁铁.
尽管大多数物理现象发生在三维空间($d=3$),在平面($d=2$)和线($d=1$)上. 相对论场论由类似的结构描述,但是$d=4$.
## 2.2 The Landau-Ginzburg Hamiltonian
使用2.2式中的粗粒化权重,我们可以定义一个有效哈密顿量
$$
\beta \mathcal{H}[\vec{m}(\mathbf{x})] \equiv - \ln \mathcal{W}[\vec{m}(\mathbf{x})],$$
它通过玻尔兹曼因子给出了场构型的概率. 类比上一章中的弹性理论,我们按照以下原则构造$\beta \mathcal{H}[\vec{m}(\mathbf{x})]$:
**局部性和均匀性:** 如果一个系统包含不相连的部分,整体的概率通过每一部分概率的乘积得到. (2.3)式中的哈密顿量分解为每个部分的贡献之和,转变为在连续表示下的积分
$$
\beta \mathcal{H} = \int d^d \mathbf{x} \Phi[\vec{m}(\mathbf{x}),\mathbf{x}].
$$
这里$\Phi$是能量密度,原则上它在不同位置可以具有不同的函数形式. 对于空间中均匀的材料,不同的位置$\mathbf{x}$是等价的,因此可以将$\Phi$中对于$\mathbf{x}$的依赖移除. 但当系统处于外部势或者有额外的杂质时这是不成立的. 我们对更复杂的系统感兴趣,在这些系统中,由于相互作用,系统的不同部分之间存在一些耦合,为此我们在上式中包含了场的梯度
$$
\beta \mathcal{H} = \int d^d \mathbf{x} \Phi[\vec{m}(\mathbf{x}),\nabla \vec{m},\nabla^2 \vec{m},\cdots].
$$
一般的非局部相互作用可以通过包括许多导数来描述,当仅包含少数导数即可获得良好的描述时,“局部”是有用的. 这是短程相互作用的情况(甚至包括气液混合物中的范德瓦尔斯相互作用),但对于长程相互作用(如库伦)失败.
**解析性和多项式展开:** 接下来将$\Phi$的函数形式写为$\vec{m}(\mathbf{x})$的幂及其梯度的展开式. 为了证明这种展开的合理性,让我们再次检查独立自由度集合(例如自旋)的简单示例. 微观层面的概率分布可能比较复杂,例如自旋可以被限制为固定大小,或者被量化为特定值. 在介观尺度上,场$\vec{m}(\mathbf{x})$是通过对许多这样的自旋进行平均而获得的. 平均过程通常会简化概率分布. 在大多数情况下,中心极限定理意味着总和的概率分布接近高斯形式. 在构建统计场论时,我们实际上正在寻找中心极限定理的概括,以描述相互作用的自由度. 关键在于,从微观尺度到介观尺度,与微观自由度相关的非解析性被洗掉,粗粒场的概率分布是通过$\vec{m}$次方的解析展开得到的. 当然,宏观尺度上存在与相变相关的非解析性. 然而,这种奇点涉及无穷大(宏观数)的自由度. 通过关注介观尺度,我们从而避免了短尺度和长尺度上可能出现的奇点!
![[Pasted image 20240312153856.png|550]]
**对称性:** 一个在平均过程中存活的元素是潜在的微观对称性. 这种对称性限制了有效哈密顿量的可能形式和展开. 比如在不存在外加磁场时,所有磁化方向都是等价的,因此$\mathcal{H}[R_n \vec{m}(\mathbf{x})] = \mathcal{H}[\vec{m}(\mathbf{x})]$,其中$R_n$是$n$维序参量空间的一个旋转. $\vec{m}$的线性项与这个对称性是不符合的,因此展开的第一项正比于$m^2(\mathbf{x})$
$$
m^2(\mathbf{x}) \equiv \vec{m}(\mathbf{x}) \cdot \vec{m}(\mathbf{x}) \equiv \sum_i^n m_i(\mathbf{x}) m_i(\mathbf{x}),$$
其中$\{m_i\}$是矢量场的分量. 更高阶项由$4$次方$m^4(\mathbf{x})$、$6$次方$m^6(\mathbf{x})$给出.
在构造涉及矢量场梯度的项时,我们应该记住系统的空间对称性. 在*各向同性*系统中,空间中的所有方向都是等效的,我们应该使用在空间旋转下不变的导数组合. 最简单的项为:
$$
(\nabla \vec{m})^2 \equiv \sum_{i=1}^{n} \sum_{\alpha = 1}^d \partial_{\alpha} m_i \partial_{\alpha} m_i,$$
$\partial_{\alpha}$代表沿着空间的$\alpha$方向做偏导. 如果不同方向是不等价的,更多的项会包括进来. 比如在三角晶格上的二维磁铁,$\partial_1 m_i \partial_1 m_i$和$\partial_2 m_i \partial_2 m_i$的系数可以是不同的. 然而,通过适当地重新缩放坐标,梯度项可以再次更改为(2.7)的形式. 各向同性系统中的四阶梯度项是:
$$
(\nabla^2 \vec{m})^2 \equiv \sum_{i=1}^{n} \sum_{\alpha = 1}^d \sum_{\beta = 1}^d (\partial_{\alpha} \partial_{\alpha} m_i)(\partial_{\beta} \partial_{\beta} m_i),$$
并且一个可能的四次项为:
$$
m^2 (\nabla^2 \vec{m})^2 \equiv \sum_{i=1}^{n} \sum_{j = 1}^n \sum_{\alpha = 1}^d m_i m_i \partial_{\alpha} m_j \partial_{\alpha} m_j.
$$
各向异性再次导致高阶项,通常无法通过简单的重新缩放来消除.
我们将很快证明,为了描述磁系统,事实上大多数转变,只包含几项就足够了,从而产生所谓的*Landau-Ginzburg*哈密顿量:
$$
\beta \mathcal{H} = \beta F_0 + \int d^d \mathbf{x} \left[ \frac{t}{2} m^2(\mathbf{x}) + u m^4(\mathbf{x}) + \frac{K}{2} (\nabla m)^2 + \cdots - \vec{h} \cdot \vec{m}(\mathbf{x}) \right].
$$
在短尺度上对磁性和非磁性自由度的积分也会生成一个总体常数$F_0$. 这种对总自由能的贡献是解析的(如前所述),并且大部分会被忽略. 方程(2.8)还包括磁功$\vec{B}·\vec{m}$对哈密顿量的贡献,其中$\vec{h} \equiv \beta \vec{B}$,$\vec{B}$是磁场. 磁场还可能产生高阶项,例如$m^2 \vec{m}· \vec{h}$,与上面的项相比它们更次要一些.
**稳定性:** 由于LG哈密顿量源于一个良定义的物理问题,粗粒化的玻尔兹曼权重不能导致任何非物理的场的构型. 特别的,对于无限大的$\vec{m}$,概率不能是发散的. 这个条件表明$\vec{m}$的高阶幂的系数必须是正的. 对涉及梯度的项的符号有相关的限制,以避免振荡不稳定.
Landau-Ginzburg哈密顿量依赖于一系列的唯象参数$\{ t,u,K,\cdots \}$,这些参数是微观相互作用以及外部参数如温度、压强的非普适函数. 必须充分理解这一点,这可能是造成混乱的根源. 虽然场的特定构型的概率由玻尔兹曼权重$\exp\{ -\beta \mathcal{H}[\vec{m}(\mathbf{x})] \}$给出,但这并不意味着指数中的所有项都与$(k_BT)^{-1}$成比例. 这种依赖性仅适用于真正的微观哈密顿量. 更准确地说,Landau-Ginzburg哈密顿量是通过对微观自由度进行积分(粗粒化)而获得的有效自由能,同时将其平均值限制为$\vec{m}(\mathbf{x})$. 正是由于执行这样的第一性原理程序的困难,我们才仅在对称性的基础上假设所产生的有效自由能的形式. 付出的代价是唯象参数对原始微观参数以及温度等外部约束具有未知的函数依赖性(因为我们必须考虑粗粒度过程中丢失的短程涨落的熵). 对这些函数形式的约束来自对称性、解析性和稳定性,正如在构造$\Phi[\vec{m}]$的函数形式的上下文中所讨论的那样. 值得注意的是,这些介观系数将是外部参数的解析函数,例如可表示为温度$T$的幂级数.
## 2.3 Saddle point approximation,and mean-field theory
通过仅关注粗粒化场,我们大大简化了原始问题. 现在应该从配分函数中获得各种热力学函数以及奇异行为
$$
Z = \int \mathcal{D} \vec{m}(\mathbf{x}) \exp \{ -\beta \mathcal{H}[\vec{m}(\mathbf{x})] \},\tag{2.9}
$$
对应于之前定义的Landau-Ginzburg哈密顿量. 在实际,泛函积分是作为离散积分的极限而获得的:连续坐标$\mathbf{x} ≡ (x_1,x_2,\cdots x_d)$首先被离散化为点$\mathbf{i} ≡ (i_1,i_2,\cdots,i_d)$的格,格距为$a$;将各种导数替换为适当的差分,得到泛函积分为:
$$
\int \mathcal{D} \vec{m}(\mathbf{x}) \mathcal{F}\left[\vec{m}(\mathbf{x}),\frac{\partial \vec{m}}{\partial x_\alpha},\cdots\right] \equiv \lim _{\mathcal{N} \rightarrow \infty} \prod_{i=1}^{\mathcal{N}} \mathrm{d} \vec{m}_i \mathcal{F}\left[\vec{m}_i,\frac{\vec{m}_{i_\alpha+1}-\vec{m}_{i_\alpha}}{a},\cdots\right] .
$$
事实上,关于泛函积分的存在性有许多数学问题. 这些问题主要与短距离内的自由度过多有关,从而导致函数表现相当糟糕. 这些问题不需要我们关心因为我们知道这些潜在的问题有一个良定义的晶格间距,这限制和控制了短距离行为.
即使经过所有这些简化,计算式(2.9)中的 Landau-Ginzburg 配分函数仍然不容易. 下面我们进行鞍点近似,其中方程中的积分被被积函数的最大值替代,对应于场$\vec{m}(\mathbf{x})$的最可能构型. 磁体中相互作用的自然趋势是保持磁化矢量平行,因此我们期望方程中的参数$K$为正. $\vec{m}(\mathbf{x})$的大小或方向的任何变化都会导致方程 (2.8) 中$K(\nabla \vec{m})^2$项的“能量损失”. 因此,场在其最可能的配置中是均匀的,并且将积分限制到该子空间我们得到:
$$
Z \approx Z_{\text{sp}} = e^{-\beta F_0} \int d \vec{m} \exp \left[-V \left( \frac{t}{2} m^2 + um^4 + \cdots - \vec{h} \cdot \vec{m} \right) \right],\tag{2.10}
$$
其中$V$是系统体积. 在极限$V \rightarrow \infty$时积分被鞍点$\vec{m}$主导,相应的鞍点自由能为:
$$
\beta F_{\text{sp}} = - \ln Z_{\text{sp}} \approx \beta F_0 + V \min \{ \Psi(\vec{m}) \}_{\vec{m}},\tag{2.11}
$$
其中
$$
\Psi(\vec{m}) \equiv \frac{t}{2} \vec{m}^2 + u(\vec{m}^2)^2 + \cdots - \vec{h} \cdot \vec{m}.
$$
最有可能的磁化强度将与外部磁场对齐,即$\vec{m}(\mathbf{x}) = \overline{m} \hat{h}$ . 为了得到具体的数值我们要得到上式的最值.
$$
\Psi'(\overline{m}) = t \overline{m} + 4u \overline{m}^3 + \cdots - h = 0.
\tag{2.13}
$$
令人惊讶的是这个简单的方程捕捉了相变的定性行为.
虽然函数$\Psi(m)$是解析函数并且没有奇点,但鞍点自由能为方程式(2.11)很可能是非解析的. 这是因为最小化运算不是一个解析过程,并且会引入奇点,正如我们将很快演示的那样. $V \rightarrow \infty$的热力学极限证明了方程(2.10)鞍点近似的合理性. 对于有限的$V$,积分是完美解析的. 在临界点附近,磁化强度很小,因此在$\Psi(\vec{m})$的展开中仅保留最低幂次是合理的. (我们稍后可以自洽地检查展开式中省略的项确实是小的修正)$\Psi(m)$的行为很大程度上取决于参数$t$的符号.
(1) 对于$t \gt 0$,四次项对于稳定性不是必需的,可以忽略. (2.13)式的解是$\overline{m} = h/t$,描述了顺磁行为. 最可能的磁化是沿着磁场方向,并且在$\vec{h} \rightarrow 0$时消失. 磁化率为$\chi = 1/t$,随着$t \rightarrow 0$发散.
![[Pasted image 20240311223154.png|660]]
(2) 对于$t \lt 0$,需要$u$为正值来保证稳定性. 函数$\Psi(m)$现在有两个局部最小值,全局最小值处自旋与磁场对其. 当$\vec{h} \rightarrow 0$时全局最小值向非零值移动,表明自发磁化. 即使在$\vec{h} = 0$时也是如此,如铁磁体. $h = 0$时$\vec{m}$的方向由系统的历史决定,并且可以通过外部场$\vec{h}$重新调整.
![[Pasted image 20240311224807.png|650]]
最可能磁化强度$\overline{m}(h)$的结果曲线与图1.4中的曲线非常相似. 因此,Landau-Ginzburg 配分函数的鞍点评估会导致$t>0$时产生顺磁行为,$t<0$时产生铁磁行为,相变线终止于点$t = h = 0$.
![[Pasted image 20240311224843.png|800]]
参数$(t,u,K,\cdots)$是温度的解析方程,可以在临界点$T = T_c$附近进行展开.
$$
\left\{\begin{array}{l}
t(T,\cdots)=a_0+a_1\left(T-T_c\right)+\mathcal{O}\left(T-T_c\right)^2,\\
u(T,\cdots)=u+u_1\left(T-T_c\right)+\mathcal{O}\left(T-T_c\right)^2,\\
K(T,\cdots)=K+K_1\left(T-T_c\right)+\mathcal{O}\left(T-T_c\right)^2 .
\end{array}\right.
$$
展开系数可以看作唯象参数,可以通过与实验对比确定. 特别的,为了让图1.4和图2.3匹配,我们要求$t$是一个关于温度的单调函数并且在$T_c$时为$0$,这就要求$a_0=0$以及$a_1 = a \gt 0$. 在相变点附近的铁磁相的稳定性要求$u$和$K$是正的. 将磁体的实验相图与从鞍点获得的相图相匹配的最小条件集是
$$
t = a(T - T_c)^2 + \mathcal{O}(T-T_c)^2,\quad \text{with} \quad (a,u,K) \gt 0.
\tag{2.15}
$$
当然可以在扩展中设置附加项,例如$a$或$u$为零,并通过适当选择高阶项来保持相图和稳定性. 然而,这样的选择不是通用的,没有理由施加比实验绝对要求更多的限制.
使用式(2.15)我们可以我们可以量化式(2.11)-(2.13)中自由能的鞍点评估所预测的奇异行为.
下面计算鞍点近似给出的临界指数.
* **磁化:** 在零场时(2.13)简化为$\partial \Psi / \partial m = t \overline{m} + 4 u \overline{m}^3 = \overline{m}(t + 4 u \overline{m}^3) = 0$,我们得到
$$
\overline{m}(h=0)= \begin{cases}0 & \text { for } t>0,\\ \sqrt{\frac{-t}{4 u}}=\sqrt{\frac{a}{4 u}}\left(T_c-T\right)^{1 / 2} & \text { for } t<0 .\end{cases}
\tag{2.16}
$$
![[Pasted image 20240312134209.png|700]]
对于$t<0$,非磁化解$\overline{m} = 0$是$\Psi(m)$的最大值,并且存在自发磁化,普适指数$\beta = 1/2$. 总振幅是非普适的并且取决于材料.
通过(2.13),当$t=0$时可以计算出
$$
\overline{m}(t = 0) = \left( \frac{h}{4u} \right)^{1/3},$$
可以得到$\delta = 3$.
* **磁化率:** 其大小$t \overline{m} + 4u \overline{m}^3 = h$的解给. 幅度的变化由*纵向磁化率*$\chi_l$控制,其倒数很容易获得为:
$$
\chi_{\ell}^{-1}=\left.\frac{\partial h}{\partial \overline{m}}\right|_{h=0}=t+12 u \overline{m}^2= \begin{cases}t & \text { for } t>0,\text { and } h=0,\\ -2 t & \text { for } t<0,\text { and } h=0 .\end{cases}
\tag{2.18}
$$
从两侧接近相变点时,零场磁化率按照$\chi_{\pm} \sim A_{\pm} |t|^{-\gamma_{\pm}}$发散且$\gamma_{+} = \gamma_{-} = 1$. 尽管振幅$A_{\pm}$是依赖于材料的,式$(2.18)$预测它们的比值$A_{+} / A_{-} = 2$是普适的. (我们很快就会遇到横向磁化率$\chi_t$,它描述了磁化强度垂直于它的磁场的变化的响应. 当$h = 0$时,磁化相中的$\chi_t$始终为无穷)
![[Pasted image 20240312141129.png|650]]
* **热容:** $h=0$时的自由能为
$$
\beta F=\beta F_0+V \Psi(\bar{m})=\beta F_0+V \begin{cases}0 & \text { for } t>0,\\ -\frac{t^2}{16 u} & \text { for } t<0 .\end{cases}
\tag{2.19}
$$
由于$t = a(T-T_c) + \cdots$,只保留$(T-T_c)$的领头阶我们可以得到$\partial/\partial T \sim a \partial / \partial t$. 因此我们可以得到在零场时热容的行为为:
$$
C(h=0)=-T \frac{\partial^2 F}{\partial T^2} \approx-T_c a^2 \frac{\partial^2}{\partial t^2}\left(k_{\mathrm{B}} T_c \beta F\right)=C_0+V k_{\mathrm{B}} a^2 T_c^2 \times \begin{cases}0 & \text { for } t>0,\\ \frac{1}{8 u} & \text { for } t<0 .\end{cases}
$$
鞍点近似预测了一个不连续性而不是发散. 如果我们坚持使用幂律$t^{- \alpha}$来描述这个奇异性,我们只能选择$\alpha = 0$.
![[Pasted image 20240312141733.png|650]]
## 2.4 Continuous symmetry breaking and Goldstone modes
对于零外场的情况,虽然微观哈密顿量具有完全的旋转对称性,但是低温相却没有. 当 $n$ 空间中一个特定方向被选作净磁化 $\vec{M}$ 的方向时,*自发对称性破缺*就发生了,同时对应的*长程序*也建立起来,其中系统的大多数自旋沿 $\vec{M}$ 方向. 原始的对称性在全局范围内仍然存在,在某种意义上,如果所有的局域自旋同时旋转(即场变换为 $\vec{m}(\mathbf{x}) \mapsto \mathfrak{R} \vec{m}(\mathbf{x})$ ),能量不会改变. 这样的旋转将一个有序态转化为另一个等价的态.
由于均匀的旋转不耗费能量,因此通过连续性,我们期望一个在空间中缓慢变化的旋转(即 $\vec{m}(\mathbf{x}) \mapsto \Re(\mathbf{x}) \vec{m}(\mathbf{x})$ ,其中 $\Re(\mathbf{x})$ 仅有长波长的变化)耗费很小的能量. 这样的低能激发称为Goldstone模式. 这样的集体模式出现在任何连续对称破缺的系统中. $^5$ 固体中的声子提供一个 Goldstone 模式熟悉的例子,此时由于晶体结构的存在,平移对称性和旋转对称性被破坏.
出现在不同系统中堵塞Goldstone模式有某些共同的特征. 下面我们探讨*超流*中Goldstone模式的起源和行为. 类似于玻色凝聚,超流相在单个量子基态上有着宏观量级的占据数,序参量 :
$$
\psi(\mathbf{x}) \equiv \psi_{\Re}(\mathbf{x})+\mathrm{i} \psi_{\Im}(\mathbf{x}) \equiv|\psi(\mathbf{x})| \mathrm{e}^{\mathrm{i} \theta(\mathbf{x})}
$$
可以粗略地视为在$\mathbf{x}$附近真实波函数的基态分量.$^6$ 波函数的相位不是可观测量,不应该出现在物理可测概率中. 这一观察限制了有效粗粒化哈密顿量的形式,给出展开
$$
\beta \mathcal{H}=\beta F_0+\int \mathrm{d}^d \mathbf{x}\left[\frac{K}{2}|\nabla \psi|^2+\frac{t}{2}|\psi|^2+u|\psi|^4+\cdots\right] .
\tag{2.22}
$$
> $^5$打破离散对称性不会产生 Goldstone 模式,因为此时不可能产生从一个态到另一个等价态缓慢变化的变换.
> $^6$一个更严格的推导通过相互作用玻色子哈密顿量的二次量子化形式进行,这超出了我们目前的范围.
方程$(2.22)$事实上等价于$n=2$的Landau-Ginzburg哈密顿量,这可以通过将变量转化为两分量场$\vec{m}(\mathbf{x}) \equiv\left(\psi_{\Re}(\mathbf{x}),\psi_{\Im}(\mathbf{x})\right)$看出. $t<0$时有限大小$\psi$的出现标志着超流相变的发生. $t<0$时均匀$\psi$对应的Landau-Ginzburg哈密顿量呈酒瓶或墨西哥帽的形状.
最小化这个函数给出了$\psi$的大小,但并不限制其相位$\theta$. 现在,考虑一个相位缓慢变化的态$\psi(\mathbf{x}) = \bar{\psi} \mathrm{e}^{\mathrm{i} \theta(\mathrm{x})}$,代入哈密顿量给出:
$$
\beta \mathcal{H}=\beta \mathcal{H}_0+\frac{\bar{K}}{2} \int \mathrm{d}^d \mathbf{x}(\nabla \theta)^2,
\tag{2.23}
$$
- $\beta H_0=\beta F_0+\int d^d \mathbf{x}\left[\frac{t}{2} \bar{\psi}^2+u \bar{\psi}^4\right]$
- $\bar{K}=K \bar{\psi}^2$
就像声子的情况一样,我们能通过能量函数在均匀旋转下的不变性猜测:因为变换 $\theta(\mathbf{x}) \mapsto \theta(\mathbf{x})+\theta_0$ 不改变能量,能量密度只能依赖于 $\theta(\mathbf{x})$ 的导数,展开式的第一项给出 $(2.23)$ 式. 基于对称性的推理并没有给出*stiffness参数*的值. 从包含正常相和超流相的Landau-Ginzburg形式出发,我们发现 $\bar{K}$ 正比于序参量的平方,即 $\bar{K} \propto \bar{\psi}^2 \propto t ,$ 并在临界点消失.
我们可以将序参量相位的变化分解为独立的简正模式(在一个体积为 $V$ 的区域内):
$$
\theta(\mathbf{x})=\frac{1}{\sqrt{V}} \sum_{\mathbf{q}} \mathrm{e}^{\mathrm{i} \mathbf{q} \cdot \mathbf{x}} \theta_{\mathbf{q}}.
\tag{2.24}
$$
利用平移对称性,(2.23)给出
$$
\beta \mathcal{H} = \beta \mathcal{H}_0 + \frac{\overline{K}}{2} \sum_{\mathbf{q}} q^2 |\theta(\mathbf{q})|^2.
$$
我们可以看到,与声子的情况类似,波数为$\mathbf{q}$的Goldstone模式的能量正比于$q^2$,在长波处变得非常小.
## 2.5 Discrete symmetry breaking and domain walls
对单分量的场 (标量场),有序相的磁化强度有两个可能的取值. 虽然这两个可能的态有相同的能量,但是将一个态连续形变为另一个态是不可能的. 在这种情况,以及其他离散对称性破缺的系统,同一样品中不同的态被清晰的畴壁分隔. 为证明这一点,考虑 Landau-Ginzburg哈密顿量在$t<0$,$h=0$时的标量场. 强制让系统两侧处于不同的状态可以引入畴壁,例如,要求 $m(x \rightarrow-\infty)=-\bar{m},m(x \rightarrow$ $+\infty)=+\bar{m}_{\text {. }}$ 其中,通过最小化能量可以得到最可能的场构型 :
$$
\frac{\mathrm{d}^2 m_w(x)}{\mathrm{d} x^2}=t m_w(x)+4 u m_w(x)^3
$$
> [!NOTE]
> $\frac{\mathrm{d}^2 m_w(x)}{\mathrm{d} x^2} \rightarrow K \frac{d^2 m_\omega(x)}{d x^2}$ 应为原文笔误
上述方程可通过对
$$
\begin{aligned}
H & =\int d^d \mathbf{x}\left(\frac{t}{2} m^2+u m^4+\frac{K}{2}\left(\frac{d m}{d x}\right)^2\right) \\
& =\mathcal{A} \int d x\left(\frac{t}{2} m^2+u m^4+\frac{K}{2}\left(\frac{d m}{d x}\right)^2\right)
\end{aligned}
$$
- 考虑系统在垂直 $x$ 轴方向上的平移不变性,即 $m$ 仅依赖于 $x$
- $\mathcal{A}$ 为垂直 $x$ 轴方向上截面的大小
- 上述 $d$ 重积分可转化为一维积分
求泛函极值得到 :
$$
t m+4 u m^3=\frac{K}{2} \frac{d}{d x}\left(2 \frac{d m}{d x}\right)=K \frac{d^2 m}{d x^2}
$$
利用恒等式 $\frac{d^2 \tanh (a x)}{\mathrm{d} x^2}=2 a^2 \tanh (a x)\left[1-\tanh ^2(a x)\right]$,可以很轻松地验证
$$
m_w(x)=\bar{m} \tanh \left[\frac{x-x_0}{w}\right],$$
是上述非线性方程的解,其中
$$
w=\sqrt{\frac{2 K}{-t}},\quad \text { and } \quad \bar{m}=\sqrt{\frac{-t}{4 u}} .
$$
上述解将磁化率接近 $\pm \bar{m}$ 两个可能取值的区域分开. 两个区域间的畴壁位于任意位置 $x_0$,宽度为 $\omega_{\circ}$ 在接近相变点 $t=0$ 时,畴壁宽度以 $\left(T_c-T\right)^{-1 / 2}$ 的方式发散. 宽度 $\omega$ 实际上正比于系统的关联长度,关联长度的计算将在下章进行.
系统产生畴壁所耗费的自由能可通过计算与均匀磁化下自由能的差值得到:
$$
\begin{aligned}
\beta F_w & =\int \mathrm{d}^d \mathbf{x}\left[\frac{K}{2}\left(\frac{\mathrm{d} m_w}{\mathrm{~d} x}\right)^2+\frac{t}{2}\left(m_w^2-\bar{m}^2\right)+u\left(m_w^4-\bar{m}^4\right)\right] \\
& =-\frac{2}{3} t \bar{m}^2 \omega \mathcal{A}
\end{aligned}
$$
- $\mathcal{A}$ 为系统垂直于 $x$ 方向的截面积. 单位面积的自由能正比于体能量密度乘以畴壁宽度. 在接近相变时,上述计算预测界面自由能以$(T_c - T)^{3/2}$的方式消失.
|
---
type: story
layout: ../../layouts/StoryLayout.astro
title: "Who builds a blog in 2022? Me"
excerpt: I have no intention of making this story sound profound, leaving me with quite the herculean task—considering the profound journey it took to get to this point..
tag: non-technical
draft: false
pages: 0
author: Favour Felix
cover: "https://firebasestorage.googleapis.com/v0/b/favour-portfolio.appspot.com/o/stories%2Fwho-builds-a-blog-cover.webp?alt=media&token=d93809d7-947c-4b38-a9d2-68815f29c4da"
banner: "https://firebasestorage.googleapis.com/v0/b/favour-portfolio.appspot.com/o/stories%2Fwho-builds-a-blog-cover.webp?alt=media&token=d93809d7-947c-4b38-a9d2-68815f29c4da"
readTime: 4 mins
year: 2023
date: September 27, 2023
updatedAt: September 27, 2023 2:00 AM
---
A bunch of people have asked how I built my blog, **[favourfelix.com](http://favourfelix.com/)**, more times than I expected. I thought it might be interesting to turn the process into a story.
Let me be clear: I have no intention of making this story sound profound, leaving me with quite the herculean task—considering the profound journey it took to get to this point. And you might wonder—what’s so special about building a blog? Absolutely nothing; it’s the story that precedes it that holds the most substance.
We live in an age where very few people get excited about reading. No one seems interested if it’s not audio-visual content or a short tweet. Amid all this chaos, there’s me. The one with an inexplicable desire to do things differently than everyone I encounter—this is why I still write.
Here’s a quick outline for the story I am about to tell:
- [The beginning](#the-beginning-2011---2015)
- [The middle](#the-middle-2016---2021)
- [There will be no end](#there-will-be-no-end-2022---forever)
- [The technical jargon and conclusion](#technical-jargon-and-conclusion)
- [Glossary](#glossary)

## The beginning (2011 - 2015)
As a young child, I never had an internet-enabled phone, yet I constantly sought ways to establish a presence online. You might wonder why. Well, it all stemmed from my childhood ambition of becoming a computer engineer. I eagerly seized any chance that seemed to validate that career path, even if it involved signing up for platforms like Facebook, Tumblr, and 2go, without actively engaging in any of them.
The goal to build a blog began with a simple Google search: “How to make a website” sometime in October 2011. The search result pages almost always led to something technical requiring a personal computer, which I did not have then. Hence, I went for a more accessible option: Microblogging sites. I could add my name or any word as a subdomain to personalize the website and make it feel like mine, so it felt perfect.
My first stop on the microblogging train was Blogger—arguably the most popular one in 2011, but I soon realized it wasn’t the best and switched tracks to WordPress. The WordPress track introduced me to even greater customizations and a less skeletal User Interface. So, I stuck with it for the longest.
**References**: [felixfavour.blogspot.com](http://felixfavour.blogspot.com), [felixfavour.wordpress.com](http://felixfavour.wordpress.com) (now discontinued)

## The middle (2016 - 2021)
The middle was exceptional; this season, I really began blogging even though the preliminary years involved me lifting content from the internet—in my defence, that was what blogging meant to me.
I and a long-time friend began a blogging group called [The Niclex](http://theniclex.wordpress.com/) (His first name is Nicholas, and my last name is Felix. Get it?). It grew to be one of my most significant achievements. The Niclex grew from a team of two to over ten authors and editors, and we wrote content that outlived our early tenacity. The blog was most active from 2018 to 2021 and was very prosperous by numerous standards.

Image showing all-time organic stats on [theniclex.wordpress.com](http://theniclex.wordpress.com) blog.
Thanks to Nicholas Onyeanakwe, Salim Oyinlola, Tobi Wesey, Ajibola Matthew, Inioluwa Adeniyi, Temi Adesanya, Daniel Okafor, Adeyemi Ayodeji, Bolu and everyone else who engaged and supported the cause.
**References**: [theniclex.wordpress.com](http://theniclex.wordpress.com), [crufftechnologies.wordpress.com](http://crufftechnologies.wordpress.com)

## There will be no end (2022 - forever)
Finally, 2020/2021 was a pivotal season for me, especially from a faith perspective. I was becoming an adult, a 9-5er, and I needed a personal outlet to share a few discoveries and thoughts aside from my notebook; that was how this blog came to life.
I wrote my first piece on the 17th of September, 2022, after teasing a launch in October 2021.
## Technical Jargon and Conclusion
This story has transcended from being a story about the technicalities of this blog to one of my early blogging experiences. Sharing how I designed and built this would fit better in its own article.
<section class="first">
. . .
</section>
To wrap things up, one of the key takeaways from this article, along with some context from previous posts on this blog, is my inclination always to start something. There was a time when I didn't particularly appreciate this aspect of myself because it seemed like I embarked on numerous endeavours without much tangible progress to showcase.
However, in hindsight, each of these experiences played a crucial role in preparing me for the unforeseen challenges that awaited me in my subsequent experiences. Moreso, the drive I displayed during those initial phases has proven to be an invaluable asset in my little achievements within the corporate world.
## Glossary
**Subdomain:** This is an additional word that might precede a domain name (facebook.com, twitter.com) to categorize a site’s content. For example, mobile.facebook.com is a subdomain of facebook.com, and it is used to serve users who visit facebook.com on their mobile phones.
**User Interface (UI)** - This is simply the components and design of a digital product that defines how a user can interact with it. For a website, this could be the colour, font, use of images, layout, and more.
**9-5er:** A person who works a mundane job that typically runs from 9 a.m. to 5 p.m.
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { GradoComponent } from './grado/grado.component';
import { RegistrarGradoComponent } from './registrar-grado/registrar-grado.component';
import { ActualizarGradoComponent } from './actualizar-grado/actualizar-grado.component';
const routes: Routes = [
{ path: 'grados', component: GradoComponent },
{ path: 'registrar-grado', component: RegistrarGradoComponent },
{ path: 'actualizar-grado/:id', component: ActualizarGradoComponent },
{ path: '', redirectTo: 'grados', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import unittest
from app.usecase.repo.user import create_account, authenticate
from app.usecase.repo.account import rp_deposit, rp_send_money, rp_withdraw
class TestUserAndAccountRepos(unittest.TestCase):
def test_all_handlers(self):
#Test Account Creation: Should be true when "Account Does Not Exists"
self.assertTrue( create_account("[email protected]", "Random User 0") )
self.assertTrue( create_account("[email protected]", "Random User 1") )
#Test Account Creation: Should be false when "Account Exists"
self.assertFalse( create_account("[email protected]", "Random Name") )
#Test Authenticate: Should be true when "Account Exists"
self.assertTrue( authenticate("[email protected]") )
#Test Authenticate: Should be false when "Account Does Not Exists"
self.assertFalse( authenticate("[email protected]") )
#Test Deposit Fund: Should be True when "Account Exists"
self.assertTrue( rp_deposit("[email protected]", 20) )
#Test Deposit Fund: Should be False when "Account Does Not Exists"
self.assertFalse( rp_deposit("[email protected]", 20) )
#Test Withdrawal: Should be True when "Fund Is Sufficient"
self.assertTrue( rp_withdraw("[email protected]", 5) )
#Test Withdrawal: Should be False when "Fund Is Insufficient"
self.assertFalse( rp_withdraw("[email protected]", 25) )
#Test Send Money: Should be True when "Fund Is Sufficient"
self.assertTrue( rp_send_money("[email protected]", 7.5, "[email protected]") )
#Test Send Money: Should be False when "Recipient Does Not Exist"
self.assertFalse( rp_send_money("[email protected]", 20, "[email protected]") )
#Test Send Money: Should be False when "Fund Is Insufficient"
self.assertFalse( rp_send_money("[email protected]", 20, "[email protected]") )
if __name__ == '__main__':
unittest.main()
|
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using React.Models;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace React.Controllers
{
public class HomeController : Controller
{
private static readonly IList<Comment> _commentList;
static HomeController()
{
_commentList = new List<Comment> {
new Comment
{
ID = 1,
Author = "Daniel Lo Nigro",
Text = "Hello ReactJS.NET World!"
},
new Comment
{
ID = 2,
Author = "Pete Hunt",
Text = "This is one comment"
},
new Comment
{
ID = 3,
Author = "Jordan Walke",
Text = "This is *another* comment"
}
};
}
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
[Route("comments")]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public ActionResult GetAllComments()
{
return Json(_commentList);
}
[Route("comments/new")]
[HttpPost]
public ActionResult AddComment(Comment comment)
{
// Create a fake ID for this comment
comment.ID = _commentList.Count + 1;
_commentList.Add(comment);
return Content("Success :)");
}
}
}
|
package chapter10.section01
import java.io.BufferedReader
import java.io.FileOutputStream
import java.io.FileReader
import java.io.PrintWriter
/*
코틀린 표준 라이브러리(6) - use()
- 보통 특정 객체가 사용된 후 닫아야 하는 경우가 생기는데 이때 use()를 사용하면
객체를 사용한 후 close() 등을 자동적으로 호출해 닫아 줄 수 있습니다.
- 표준 함수의 정의
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R
public inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R (JAVA 7 이후)
*/
fun main() {
PrintWriter(FileOutputStream("d:\\test\\output.txt")).use {
it.println("hello")
}
}
private fun readFirstLine(): String {
BufferedReader(FileReader("test.file")).use { return it.readLine() }
}
|
import { PlusIcon, MinusIcon } from "@heroicons/react/24/solid";
import { useCtx } from "../../../../context/Ctx";
import { AddPaymentMethod } from "./add-categories";
import { PaymentMethodsListingsItems } from "./payment-methods-listings";
import { COLLECTIONS } from "../../../../utils/firestore-collections";
import { useCollection } from "react-firebase-hooks/firestore";
import { collection, query, where } from "firebase/firestore";
import { db } from "../../../../config/@firebase";
import { formatCollectionData } from "../../../../utils/formatData";
import { Loading } from "../../../../components/loading";
const { categories } = COLLECTIONS;
export function PaymentMethods() {
const { updateModalStatus, authenticatedUser } = useCtx();
const [value, loading, error] = useCollection(
query(
collection(db, COLLECTIONS.paymentMethods),
where("branchId", "==", authenticatedUser.branchId)
),
{
snapshotListenOptions: { includeMetadataChanges: true },
}
);
const formattedData = formatCollectionData(value);
if (error)
return (
<h1 className="text-xl font-semibold">
Error fetching payment methods..
</h1>
);
if (loading)
return (
<div className="h-[40vh]">
<Loading />
</div>
);
return (
<div>
<div className="flex items-center justify-between py-4 ">
<h1 className="font-bold text-2xl">Payment Methods</h1>
<PlusIcon
onClick={() => updateModalStatus(true, <AddPaymentMethod />)}
className="h-8 w-8 font-bold text-gray-900"
/>
</div>
<div className="text-2xl">
{formattedData?.length > 0 &&
formattedData?.map((data) => (
<PaymentMethodsListingsItems key={data.slug} {...data} />
))}
{formattedData?.length === 0 && (
<div>
<h1 className="text-2xl font-normal">
No Payment Methods right now. Add a payment method to proceed.
</h1>
</div>
)}
</div>
</div>
);
}
|
<template>
<div>
<h1>Search Gif</h1>
<Search @gif-search="getGifs" />
<Loading v-if="loading" />
<div class="row">
<div v-for="gif in gifs" class="col-12 col-md-4 g-3" :key="gif.id">
<Card :gif="gif" />
</div>
</div>
</div>
</template>
<script>
import Card from "../components/Card.vue";
import Search from "../components/Search.vue";
import Loading from "../components/Loading.vue";
import swal from "sweetalert2";
export default {
components: { Card, Search, Loading },
data: () => ({
gifs: [],
loading: true,
}),
created() {
this.getGifs();
},
methods: {
async getGifs(busqueda = "pokemon") {
if (busqueda.trim() === "") {
swal.fire({
title: "Sin Busqueda",
icon: "error",
showConfirmButton: false,
showCloseButton: true,
timer: 3000,
timerProgressBar: true,
});
return;
}
this.loading = true;
this.gifs = [];
const gifsAll = await fetch(
`https://api.giphy.com/v1/gifs/search?api_key=9mGUXtcxrZPOzx4t05xd6TONPxHXNFDf&q=${busqueda}`
);
const { data } = await gifsAll.json();
this.gifs = data;
this.loading = false;
},
},
};
</script>
<style>
</style>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.