text
stringlengths 184
4.48M
|
|---|
import { useContext } from "react"
import styles from "./styles.module.scss"
import { AppContext } from "../../context/AppContext";
function Header() {
const {
setCurrentFilial,
currentFilial,
filiais,
user
} = useContext(AppContext);
const hrefToUser = user ? user.role === "user" ? "/#/profile" : "/#/profileemployee" : "/#/enter";
return (
<div className={styles.container}>
<a href="#/"><h1>MOVIEFLIX</h1></a>
<nav>
<p className={styles.selectFilial}>
Local: {currentFilial?.nome}
{
(!user || user.role === "user") && (
<div className={styles.listFiliais}>
{filiais.map((filial) => (
<p onClick={() => setCurrentFilial(filial)}>{filial.nome}</p>
))}
</div>
)
}
</p>
<a href="/#/movies">Filmes</a>
<a href="/#/products">Snacks</a>
<a href="/#/cart">Carrinho</a>
</nav>
<a className={styles.login} href={hrefToUser}>{user ? user.nome : "Entrar"}</a>
</div>
)
}
export { Header }
|
## Home Page Render
```
GET /
```
This API endpoint renders the home page of the application.
### Path Parameters
None
### Example Request
```javascript
fetch('/', {
method: 'GET',
})
.then(response => response.json())
.then(data => console.log(data));
```
### Example Response
```
HTML content of the home page
```
### Response Codes
**200**: The home page was successfully rendered.
**500**: An error occurred on the server while trying to render the home page.
<br />
## Google Authentication
```
GET /auth/google
```
This API endpoint is used to authenticate users via Google.
### Path Parameters
None
### Example Request
```javascript
fetch('/auth/google', {
method: 'GET',
})
.then(response => response.json())
.then(data => console.log(data));
```
### Example Response
The response will be dependent on the user's Google profile and the success of the authentication process.
### Response Codes
**200**: The request was successful and the user was authenticated.
**401**: Unauthorized. The user could not be authenticated.
<br />
## Google Authentication
```
GET /auth/google/secrets
```
This API endpoint is used to authenticate a user with Google. If the authentication is successful, the user is redirected to the '/secrets' page. If the authentication fails, the user is redirected to the '/login' page.
### Path Parameters
None
### Example Request
```javascript
fetch('/auth/google/secrets', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
});
```
### Example Response
This endpoint does not return a JSON response. It redirects the user to either the '/secrets' page or the '/login' page based on the success or failure of the authentication.
### Response Codes
**302**: This response code will be returned when the user is successfully authenticated and is being redirected to the '/secrets' page.
**401**: This response code will be returned when the user authentication fails and the user is being redirected to the '/login' page.
<br />
|
<?php
namespace App\Http\Controllers;
use App\Models\Book;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class BookViewController extends Controller
{
public function index()
{
$books = Book::all();
return view('books', compact("books"));
}
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\StoreBookRequest $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedBook = $request->validate([
'kode' => 'required|unique:books',
'judul' => 'required',
'penulis' => 'required|string',
'penulis_tambahan' => 'string',
'penerbit' => 'string',
'kelas' => 'string',
'rak' => 'required',
'jurusan' => 'string',
'tags' => 'string',
'abstrak' => 'string',
'tahun_terbit' => 'integer',
'cover' => 'file|image|mimes:jpeg,png,jpg|max:2048',
'kategori' => 'string',
]);
$validatedBook['kode_panggil'] = $validatedBook['rak'].'.'.$validatedBook['kode'];
if ($files = $request->file('cover')) {
$destinationPath = 'image/bookcover/'; // upload path
$coverImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$validatedBook['cover'] = $destinationPath."".$coverImage;
$files->move($destinationPath, $coverImage);
} else {
$validatedBook['cover']= "https://dummyimage.com/852x480/15748f/ffffff&text=".$validatedBook['judul'];
}
Book::create($validatedBook);
return response()->json($validatedBook, 201);
}
/**
* Display the specified resource.
*
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$book = Book::find($id);
if (is_null($book)) {
return response()->json([
'status' => 'success',
'message' => "$id book not found"
], 404);
}
return response()->json([
'status' => 'success',
'message' => "$book->kode book detail",
'data' => $book
]);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function edit(Book $book)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\UpdateBookRequest $request
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$book = Book::find($id);
if (is_null($book)) {
return response()->json([
'status' => 'success',
'message' => "$id book not found",
'data' => null
], 404);
}
$validatedBook = $request->validate([
'kode' => 'required|unique:books,kode,'.$book->id,
'judul' => 'required',
'penulis' => 'required|string',
'penulis_tambahan' => 'string',
'penerbit' => 'string',
'kelas' => 'string',
'rak' => 'required',
'jurusan' => 'string',
'tags' => 'string',
'abstrak' => 'string',
'tahun_terbit' => 'integer',
'cover' => 'file|image|mimes:jpeg,png,jpg|max:2048',
'kategori' => 'string',
]);
$validatedBook['kode_panggil'] = $validatedBook['rak'].'.'.$validatedBook['kode'];
if (!$book->cover) {
if ($files = $request->file('cover')) {
$destinationPath = 'image/bookcover/'; // upload path
$coverImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$validatedBook['cover'] = $destinationPath."".$coverImage;
$files->move($destinationPath, $coverImage);
} else {
$validatedBook['cover']= "https://dummyimage.com/852x480/15748f/ffffff&text=".$validatedBook['judul'];
}
}
Book::where('kode',$book->kode)->update($validatedBook);
return response()->json($validatedBook, 200);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$book = Book::find($id);
if (is_null($book)) {
return response()->json([
'status' => 'success',
'message' => "$id book not found",
], 404);
}
$book->delete();
return response()->json([
'status' => 'success',
'message' => "$book->kode has been deleted"
]);
}
}
|
#pragma once
#include "network.hpp"
#include "callable.h"
#include <unordered_map>
#include <memory>
#include <atomic>
enum class MsgType : uint32_t
{
Message,
};
class tokenizer;
class parser;
class interpreter;
class iNetHelper {
public:
iNetHelper(
uint16_t port,
std::shared_ptr<interpreter> interpreter,
bool bContinueOnError);
~iNetHelper(){}
uint16_t Port() { return m_port; }
std::any GetLastError() { return m_lastError; }
protected:
std::any InterpretMsgObject(std::vector<uint8_t> body);
std::mutex m_mutex;
bool m_bContinueOnError = false;
std::any m_lastError = nullptr;
uint16_t m_port{ 0 };
std::shared_ptr<tokenizer> m_tokenizer{ nullptr };
std::shared_ptr<parser> m_parser{ nullptr };
std::shared_ptr<interpreter> m_interpreter{ nullptr }, m_iContext{ nullptr };
};
class NetClient :
public net::client_interface<MsgType>,
public iNetHelper
{
public:
NetClient(const std::string& host,
uint16_t port, std::shared_ptr<callable> callback,
std::shared_ptr<interpreter> interpreter,
bool bContinueOnError = false,
bool bSuppressOutput = false);
~NetClient(){}
bool Start();
void Stop();
bool TryConnect();
void SendMessageData(std::vector<uint8_t>& msg);
std::string Host() { return m_host; }
private:
void EngineThread();
void CoreUpdate();
std::any DoCallback(std::shared_ptr<callable> callback, _args args);
std::shared_ptr<callable> m_callback;
std::string m_host;
// If anything sets this flag to false, the engine
// will attempt to shut down gracefully
static std::atomic<bool> bAtomActive;
};
class NetServer :
public net::server_interface<MsgType>,
public iNetHelper
{
public:
NetServer(uint16_t port,
std::shared_ptr<callable> onClientConnect,
std::shared_ptr<callable> onClientValidated,
std::shared_ptr<callable> onClientDisconnect,
std::shared_ptr<callable> onMessage,
std::shared_ptr<interpreter> interpreter,
bool bContinueOnError = false,
bool bSuppressOutput = false);
void SendMessageData(uint32_t clientId, std::vector<uint8_t>& msg);
void MessageAllFromData(std::vector<uint8_t>& msg, uint32_t except);
private:
std::any DoCallback(std::shared_ptr<callable> callback, _args args);
std::shared_ptr<callable> m_onClientConnect;
std::shared_ptr<callable> m_onClientValidated;
std::shared_ptr<callable> m_onClientDisconnect;
std::shared_ptr<callable> m_onMessage;
protected:
bool OnClientConnect(const std::string& host, uint16_t port);
void OnClientValidated(std::shared_ptr<net::connection<MsgType>> client);
void OnClientDisconnect(std::shared_ptr<net::connection<MsgType>> client);
void OnMessage(std::shared_ptr<net::connection<MsgType>> client, net::message<MsgType>& msg);
};
|
from os import getenv
from dotenv import load_dotenv
from langchain_openai import OpenAI
from langchain_openai.embeddings import OpenAIEmbeddings
from langchain_community.document_loaders import PDFMinerPDFasHTMLLoader
from bs4 import BeautifulSoup
import re
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.vectorstores import AstraDB
from flask import Flask, request, jsonify
import tiktoken
import threading
import requests
from langchain_core.documents import Document
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
from operator import itemgetter
from langchain_community.callbacks import get_openai_callback
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from langchain.memory import ConversationBufferMemory
app = Flask(__name__)
# Load openai key
load_dotenv()
llm = OpenAI(openai_api_key=getenv('OPENAI_API_KEY'), temperature=0)
model = "text-embedding-ada-002"
outputParser = StrOutputParser()
# Load AstraDB
embedding = OpenAIEmbeddings(model=model)
vstore = AstraDB(
embedding=embedding,
collection_name="astra_vector_demo3",
api_endpoint=getenv("ARTA_DB_API_ENDPOINT"),
token=getenv("ASTRA_DB_APPLICATION_TOKEN")
)
# Download file pdf
def download_pdf(file):
response = requests.get(file)
if response.status_code == 200:
pdf_data = response.content
return pdf_data
else:
return None
# Load pdf file
def load_pdf(file):
loaderPDFMiner = PDFMinerPDFasHTMLLoader(file)
data = loaderPDFMiner.load()[0]
soup = BeautifulSoup(data.page_content, 'html.parser')
content = soup.find_all()
return content
# Splitting data into 3 header
def splitting_data(content):
markdown_header = ""
for header in content:
style = header.get('style')
if style:
font_size = re.search(r'font-size:(\d+)px', style)
if font_size:
font_size = int(font_size.group(1))
text = header.get_text().strip()
if font_size > 20 and len(text) < 100:
text = f"# {text} " if not text.startswith("#") else text
elif 15 < font_size <= 20 and len(text) < 100:
text = f"## {text} " if not text.startswith("##") else text
elif 12 < font_size <= 15 and len(text) < 100:
text = f"### {text} " if not text.startswith("###") else text
markdown_header += text.replace('\n', '') + "\n"
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=250,
chunk_overlap=30,
length_function=len,
is_separator_regex=False
)
text_sections = text_splitter.split_text(markdown_header)
return text_sections
# Extract header for each chunk
def extract_headers(chunk):
headers = {"header1": None, "header2": None, "header3": None}
last_headers = {"header1": None, "header2": None,
"header3": None}
for line in chunk.split('\n'):
if line.startswith("#"):
if line:
if line.startswith("###"):
last_headers["header3"] = line.strip()[4:]
last_headers["header2"] = None
last_headers["header1"] = None
elif line.startswith("##"):
last_headers["header2"] = line.strip()[3:]
last_headers["header1"] = None
else:
last_headers["header1"] = line.strip()[2:]
headers.update({key: value for key, value in last_headers.items() if value})
return headers
# Create chunk
def process_chunks(chunks, file_name, file_id):
results = []
last_headers = {"header1": "", "header2": "", "header3": ""}
encoding = tiktoken.get_encoding("cl100k_base")
for chunk in chunks:
headers = extract_headers(chunk)
num_tokens = len(encoding.encode(chunk))
for key in headers:
if headers[key]:
last_headers[key] = headers[key]
else:
headers[key] = last_headers[key]
metadata = {
"header1": headers["header1"],
"header2": headers["header2"],
"header3": headers["header3"],
"document_name": file_name,
"document_id": file_id,
"tokens_embedded": num_tokens
}
document = Document(page_content=chunk, metadata=metadata)
results.append(document)
# print(results)
vstore.add_documents(results)
# Caclulate similarity chunk and answer
def calculate_similarity(chunk, answer):
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform([chunk, answer])
similarity_matrix = cosine_similarity(tfidf_matrix)
similarity_score = similarity_matrix[0, 1]
return similarity_score
# Retrieve data from document in AstraDB and generate the answer based on the question
def retriever(question, document_name, document_id, memory):
retrieved_docs = ''
retrieved_headers = []
retriever = vstore.as_retriever(search_type="similarity_score_threshold",
search_kwargs={"score_threshold": 0.95,
'filter': {'document_name': document_name,
'document_id': document_id}})
docs = retriever.get_relevant_documents(question)
for doc in docs:
retrieved_docs += doc.page_content
retrieved_headers.append(doc.metadata)
template = """
Before asking a question, please make sure it is related to the content of the document.
Only questions relevant to the document's topics will receive accurate responses.
Use the provided context as the basis for your answers and do not make up new reasoning paths - just mix-and-match what you are given.
Your answers should be short and to the point, and don't answer about other topics out of context.
Memory: take {memory} for reference the previous answer and relevant to the context, if not relevant please don't take context from outside
Context: {context}
Question: {question}
Answer: fill the answer that related to the existing context, if not please return 'The question does not fit the existing context' """
prompt = PromptTemplate(template=template, input_variables=["context", "question", "memory"])
chain = (
{"context": itemgetter("context"), "question": itemgetter("question"), "memory": itemgetter("memory")}
| prompt
| llm
| outputParser
)
with get_openai_callback() as cb:
result = chain.invoke({"context": retrieved_docs, "question": question, "memory": memory})
headers = retrieved_headers
return result, headers, cb, retrieved_docs
# Get header reference
def retrieve_header_ref(context_docs):
header_refs = []
for doc in context_docs:
h1 = doc['header1']
h2 = doc['header2']
h3 = doc['header3']
if h2 and h3:
header_ref = "-{}>{}>{}>{}".format(doc['document_name'], h1, h2, h3)
elif h2:
header_ref = "-{}>{}>{}".format(doc['document_name'], h1, h2)
elif h3:
header_ref = "-{}>{}>{}".format(doc['document_name'], h1, h3)
else:
header_ref = "-{}>{}".format(doc['document_name'], h1)
header_refs.append(header_ref)
return "\n".join(header_refs)
# Process generate answer based on the document
@app.route("/retriever_data", methods=['POST'])
def retriever_data():
question = request.json.get('question')
document_name = request.json.get('document_name')
document_id = request.json.get('document_id')
chat_history = request.json.get('chat_history')
memory = ConversationBufferMemory()
previous_context = ""
results = []
if chat_history != []:
for msg in chat_history:
if msg['type'] == 'Human':
results.append({"input": msg['content']})
elif msg['type'] == 'AI':
results.append({"output": msg['content']})
previous_context += msg['content'] + "\n"
for i in range(0, len(results), 2):
human_input = results[i]
ai_output = results[i + 1] if i + 1 < len(results) else None
memory.save_context(human_input, ai_output)
elif chat_history == []:
memory.save_context({"input": ""}, {"input": ""})
memory.chat_memory
if previous_context.strip():
combined_question = previous_context + question
else:
combined_question = question
result, headers, cb, docs = retriever(combined_question, document_name, document_id, memory)
header_ref = retrieve_header_ref(headers)
cleaned_result = result.strip()
# if cleaned_result == "The question does not fit the existing context.":
# header_ref = ''
similarity_score = calculate_similarity(docs, cleaned_result)
human = {'content': question, 'type': 'Human'}
ai = {'content': cleaned_result, 'header_ref': header_ref, 'type': 'AI'}
chat_history.append(human)
chat_history.append(ai)
response_data = {
"chat_history": chat_history,
"message": cleaned_result,
"tokens_in": cb.prompt_tokens,
"tokens_out": cb.completion_tokens
}
print(similarity_score)
return jsonify(response_data), 200
# Save document into AstraDB
@app.route("/process_data", methods=['POST'])
def process_data():
try:
file = request.json.get("file")
document_name = request.json.get("document_name")
document_id = request.json.get("document_id")
content = load_pdf(file)
threading.Thread(target=process_chunks, args=(splitting_data(content), document_name, document_id)).start()
return jsonify({"message": "File uploaded successfully"}), 200
except Exception as e:
print(f"An error occurred: {e}")
return jsonify({'error': str(e)}), 500
if __name__ == "__main__":
app.run(debug=True)
|
package com.example.listaelementos.adapters;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.listaelementos.R;
import com.example.listaelementos.models.Creature;
import java.util.List;
public class RecyclerDataAdapter extends RecyclerView.Adapter<RecyclerDataAdapter.RecyclerDataHolder> {
@NonNull
List<Creature> list;
private View.OnClickListener listener;
private OnItemClickListener itemListener;
public RecyclerDataAdapter(List<Creature> list, OnItemClickListener listener){
this.list = list;
this.itemListener = listener;
}
@Override
public RecyclerDataAdapter.RecyclerDataHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, null, false);
return new RecyclerDataHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerDataAdapter.RecyclerDataHolder holder, int position) {
holder.assignData(list.get(position), itemListener);
}
@Override
public int getItemCount() {
return list.size();
}
public class RecyclerDataHolder extends RecyclerView.ViewHolder {
TextView tw;
ImageView img;
public RecyclerDataHolder(@NonNull View itemView) {
super(itemView);
tw = itemView.findViewById(R.id.txtNameMain);
img = itemView.findViewById(R.id.imgRcvMain);
}
public void assignData(Creature p, OnItemClickListener onItemClickListener) {
tw.setText(p.name);
tw.setBackgroundColor(Color.parseColor("#"+p.colorNombre));
img.setImageResource(p.drawable);
itemView.setBackgroundColor(Color.parseColor("#"+p.colorImagen));
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.onItemClick(p,getItemCount());
}
});
}
}
public interface OnItemClickListener{
void onItemClick(Creature p, int position);
}
}
|
<template>
<!-- 展开全屏 -->
<music-full ref="MusicFullRef" v-model:musicFull="musicFull" :audio="(audio as HTMLAudioElement)" />
<!-- 底部播放栏 -->
<div class="music-play-bar" :class="setAnimationClass('animate__bounceInUp')">
<n-image
:src="getImgUrl(playMusic?.picUrl, '300y300')"
class="play-bar-img"
lazy
preview-disabled
@click="setMusicFull"
/>
<div class="music-content">
<div class="music-content-title">
<n-ellipsis class="text-ellipsis" line-clamp="1">
{{ playMusic.name }}
</n-ellipsis>
</div>
<div class="music-content-name">
<n-ellipsis class="text-ellipsis" line-clamp="1">
<span v-for="(item, index) in playMusic.song.artists" :key="index">
{{ item.name
}}{{ index < playMusic.song.artists.length - 1 ? ' / ' : '' }}
</span>
</n-ellipsis>
</div>
</div>
<div class="music-buttons">
<div @click="handlePrev">
<i class="iconfont icon-prev"></i>
</div>
<div class="music-buttons-play" @click="playMusicEvent">
<i class="iconfont icon" :class="play ? 'icon-stop' : 'icon-play'"></i>
</div>
<div @click="handleEnded">
<i class="iconfont icon-next"></i>
</div>
</div>
<div class="music-time">
<div class="time">{{ getNowTime }}</div>
<n-slider
v-model:value="timeSlider"
:step="0.05"
:tooltip="false"
></n-slider>
<div class="time">{{ getAllTime }}</div>
</div>
<div class="audio-volume">
<div>
<i class="iconfont icon-notificationfill"></i>
</div>
<n-slider
v-model:value="volumeSlider"
:step="0.01"
:tooltip="false"
></n-slider>
</div>
<div class="audio-button">
<n-tooltip trigger="hover">
<template #trigger>
<i class="iconfont icon-likefill"></i>
</template>
喜欢
</n-tooltip>
<n-tooltip trigger="hover">
<template #trigger>
<i class="iconfont icon-Play" @click="parsingMusic"></i>
</template>
解析播放
</n-tooltip>
<n-tooltip trigger="hover">
<template #trigger>
<i class="iconfont icon-full" @click="setMusicFull"></i>
</template>
歌词
</n-tooltip>
</div>
<!-- 播放音乐 -->
<audio ref="audio" :src="playMusicUrl" :autoplay="play"></audio>
</div>
</template>
<script lang="ts" setup>
import type { SongResult } from '@/type/music'
import { secondToMinute, getImgUrl } from '@/utils'
import { computed, onMounted, ref, watch } from 'vue'
import { useStore } from 'vuex'
import { setAnimationClass } from '@/utils'
import { getParsingMusicUrl } from '@/api/music'
import {
loadLrc,
nowTime,
allTime,
} from '@/hooks/MusicHook'
import MusicFull from './MusicFull.vue'
const store = useStore()
// 播放的音乐信息
const playMusic = computed(() => store.state.playMusic as SongResult)
// 是否播放
const play = computed(() => store.state.play as boolean)
// 播放链接
const ProxyUrl =
import.meta.env.VITE_API_PROXY + '' || 'http://110.42.251.190:9856'
const playMusicUrl = ref('')
watch(
() => store.state.playMusicUrl,
async (value, oldValue) => {
const isUrlHasMc = location.href.includes('mc.')
if (value && isUrlHasMc) {
let playMusicUrl1 = value as string
if (!ProxyUrl) {
playMusicUrl.value = playMusicUrl1
return
}
const url = new URL(playMusicUrl1)
const pathname = url.pathname
const subdomain = url.origin.split('.')[0].split('//')[1]
playMusicUrl1 = `${ProxyUrl}/mc?m=${subdomain}&url=${pathname}`
// console.log('playMusicUrl1', playMusicUrl1)
// // 获取音频文件
// const { data } = await axios.get(playMusicUrl1, {
// responseType: 'blob'
// })
// const musicUrl = URL.createObjectURL(data)
// console.log('musicUrl', musicUrl)
// playMusicUrl.value = musicUrl
playMusicUrl.value = playMusicUrl1
console.log('playMusicUrl1', playMusicUrl1)
setTimeout(() => {
onAudio()
store.commit('setPlayMusic', true)
}, 100)
} else {
playMusicUrl.value = value
}
loadLrc(playMusic.value.id)
},
{ immediate: true }
)
// 获取音乐播放Dom
onMounted(() => {
// 监听音乐是否播放
watch(
() => play.value,
(value, oldValue) => {
if (value && audio.value) {
audioPlay()
onAudio()
} else {
audioPause()
}
}
)
watch(
() => playMusicUrl.value,
(value, oldValue) => {
if (!value) {
parsingMusic()
}
}
)
// 抬起键盘按钮监听
document.onkeyup = (e) => {
switch (e.code) {
case 'Space':
playMusicEvent()
}
}
// 按下键盘按钮监听
document.onkeydown = (e) => {
switch (e.code) {
case 'Space':
return false
}
}
})
const audio = ref<HTMLAudioElement | null>(null)
const audioPlay = () => {
if (audio.value) {
audio.value.play()
}
}
const audioPause = () => {
if (audio.value) {
audio.value.pause()
}
}
// 计算属性 获取当前播放时间的进度
const timeSlider = computed({
get: () => (nowTime.value / allTime.value) * 100,
set: (value) => {
if (!audio.value) return
audio.value.currentTime = (value * allTime.value) / 100
audioPlay()
store.commit('setPlayMusic', true)
},
})
// 音量条
const audioVolume = ref(1)
const volumeSlider = computed({
get: () => audioVolume.value * 100,
set: (value) => {
if(!audio.value) return
audio.value.volume = value / 100
},
})
// 获取当前播放时间
const getNowTime = computed(() => {
return secondToMinute(nowTime.value)
})
// 获取总时间
const getAllTime = computed(() => {
return secondToMinute(allTime.value)
})
// 监听音乐播放 获取时间
const onAudio = () => {
if(audio.value){
audio.value.removeEventListener('timeupdate', handleGetAudioTime)
audio.value.removeEventListener('ended', handleEnded)
audio.value.addEventListener('timeupdate', handleGetAudioTime)
audio.value.addEventListener('ended', handleEnded)
}
}
function handleEnded() {
store.commit('nextPlay')
}
function handlePrev() {
store.commit('prevPlay')
}
const MusicFullRef = ref<any>(null)
function handleGetAudioTime(this: any) {
// 监听音频播放的实时时间事件
const audio = this as HTMLAudioElement
// 获取当前播放时间
nowTime.value = Math.floor(audio.currentTime)
// 获取总时间
allTime.value = audio.duration
// 获取音量
audioVolume.value = audio.volume
MusicFullRef.value?.lrcScroll()
}
// 播放暂停按钮事件
const playMusicEvent = async () => {
if (play.value) {
store.commit('setPlayMusic', false)
} else {
store.commit('setPlayMusic', true)
}
}
const musicFull = ref(false)
// 设置musicFull
const setMusicFull = () => {
musicFull.value = !musicFull.value
}
// 解析音乐
const parsingMusic = async () => {
const { data } = await getParsingMusicUrl(playMusic.value.id)
store.state.playMusicUrl = data.data.url
}
</script>
<style lang="scss" scoped>
.musicPage-enter-active {
animation: fadeInUp 0.4s ease-in-out;
}
.musicPage-leave-active {
animation: fadeOutDown 0.4s ease-in-out;
}
.text-ellipsis {
width: 100%;
}
.music-play-bar {
@apply h-20 w-full absolute bottom-0 left-0 flex items-center rounded-t-2xl overflow-hidden box-border px-6 py-2;
z-index: 99999999;
backdrop-filter: blur(20px);
background-color: rgba(0, 0, 0, 0.747);
.music-content {
width: 200px;
@apply ml-4;
&-title {
@apply text-base text-white;
}
&-name {
@apply text-xs mt-1;
@apply text-gray-400;
}
}
}
.play-bar-img {
@apply w-14 h-14 rounded-2xl;
}
.music-buttons {
@apply mx-6;
.iconfont {
@apply text-2xl hover:text-green-500 transition;
}
.icon {
@apply text-xl hover:text-white;
}
@apply flex items-center;
> div {
@apply cursor-pointer;
}
&-play {
@apply flex justify-center items-center w-12 h-12 rounded-full mx-4 hover:bg-green-500 transition;
background: #383838;
}
}
.music-time {
@apply flex flex-1 items-center;
.time {
@apply mx-4 mt-1;
}
}
.audio-volume {
width: 140px;
@apply flex items-center mx-4;
.iconfont {
@apply text-2xl hover:text-green-500 transition cursor-pointer mr-4;
}
}
.audio-button {
@apply flex items-center mx-4;
.iconfont {
@apply text-2xl hover:text-green-500 transition cursor-pointer m-4;
}
}
</style>
|
"""Unit tests for prime_numbers module."""
import unittest
from primunos import prime_numbers
class TestPrimeGenerator(unittest.TestCase):
def test_five(self):
"""Testing if prime numbers are correctly generated."""
self.assertEqual(prime_numbers(5), [2, 3, 5])
def test_prime_numbers(self):
"""Testing if prime numbers are correctly generated."""
self.assertEqual(prime_numbers(20), [2, 3, 5, 7, 11, 13, 17, 19])
def test_fifty(self):
"""Testing if prime numbers are correctly generated."""
self.assertEqual(prime_numbers(
50), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47])
def test_one_hundred(self):
"""Testing if prime numbers are correctly generated."""
self.assertEqual(prime_numbers(100),
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97])
def test_two_hundred(self):
"""Testing if prime numbers are correctly generated."""
self.assertEqual(prime_numbers(200),
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199])
def test_zero(self):
"""Testing if zero is correctly determined not to be prime."""
self.assertEqual(prime_numbers(
0), "You know '0' and '1' are not Prime numbers smh")
def test_one(self):
""""Testing if one is correctly determined not to be prime."""
self.assertEqual(prime_numbers(
1), "You know '0' and '1' are not Prime numbers smh")
def test_invalid_type_string_list(self):
"""Testing if error returned if input not integer."""
self.assertEqual(prime_numbers([]), "Integers are the only data types allowed.")
def test_invalid_type_string_set(self):
"""Testing if error returned if input not integer."""
self.assertEqual(prime_numbers(set()), "Integers are the only data types allowed.")
def test_only_positive(self):
"""Testing if error returned if negative integers input."""
self.assertEqual(
prime_numbers(-1), "Anything less than 2 is not possible to generate prime numbers.")
if __name__ == "__main__":
unittest.main()
|
<div class="container">
<div class="signup-container">
<img src="../../../../assets/logo-small.svg" class="logo" />
<mat-card class="signup-card" [attr.aria-busy]="waiting">
<mat-progress-bar
*ngIf="waiting"
mode="indeterminate"
class="progress-bar"
></mat-progress-bar>
<mat-card-header>
<mat-card-title>
<span class="signup-text">Join to Project Name!</span>
</mat-card-title>
</mat-card-header>
<mat-card-content>
<form
[formGroup]="credentials"
class="signup-form"
(keyup.enter)="submit()"
>
<mat-form-field hideRequiredMarker="true" appearance="outline">
<mat-label>Name</mat-label>
<input
matInput
type="text"
formControlName="name"
required
#focusInitial
/>
</mat-form-field>
<mat-form-field hideRequiredMarker="true" appearance="outline">
<mat-label>Surname</mat-label>
<input matInput type="text" formControlName="lastName" required />
</mat-form-field>
<mat-form-field hideRequiredMarker="true" appearance="outline">
<mat-label>Email Address</mat-label>
<input matInput type="email" formControlName="email" required />
<mat-icon
*ngIf="credentials.controls.email.hasError('uniqueEmail')"
matSuffix
class="error"
matTooltip="This email is already in use."
matTooltipPosition="after"
>error</mat-icon
>
<mat-icon
*ngIf="credentials.controls.email.valid"
matSuffix
class="success"
matTooltip="This email is not used available."
matTooltipPosition="after"
>done</mat-icon
>
<mat-hint *ngIf="credentials.controls.email.hasError('uniqueEmail')"
>Reset your account.</mat-hint
>
</mat-form-field>
<mat-form-field hideRequiredMarker="true" appearance="outline">
<mat-label>Username</mat-label>
<input matInput type="text" formControlName="username" required />
<mat-icon
*ngIf="credentials.controls.username.hasError('uniqueUsername')"
matSuffix
class="error"
matTooltip="This username is already taken."
matTooltipPosition="after"
>error</mat-icon
>
<mat-icon
*ngIf="credentials.controls.username.valid"
matSuffix
class="success"
matTooltip="This username is available."
matTooltipPosition="after"
>done</mat-icon
>
<mat-hint>You can use letters, numbers & hyphen(-).</mat-hint>
</mat-form-field>
<mat-form-field hideRequiredMarker="true" appearance="outline">
<mat-label>Password</mat-label>
<input
matInput
type="password"
formControlName="password"
required
/>
</mat-form-field>
</form>
</mat-card-content>
<mat-card-actions>
<button
mat-raised-button
color="primary"
[disabled]="credentials.dirty && credentials.invalid"
class="signup-button"
(click)="submit()"
>
Sign Up
</button>
</mat-card-actions>
<mat-card-footer>
<p class="login">
Already have an account?
<a class="accent" routerLink="/login">
Login
</a>
</p>
</mat-card-footer>
</mat-card>
</div>
</div>
|
# oss-ldms-webapp
Frontend web application for OSS Land Degradation Monitoring Service (LDNS)
# Maps (maps)
App to show rasta and tif files on maps
## Install the dependencies
```bash
npm install
```
### Start the app in development mode (hot-code reloading, error reporting, etc.)
```bash
quasar dev
```
### Build the app for production
```bash
quasar build
```
## Prerequisites
1. Install node js (prefered latest stable version)
2. Install quasar Cli
```bash
npm install -g @quasar/cli
```
One can now clone the repository, install dependencies and run or build using the commands provided above
# Project structure
```📦src
┣ 📂assets
┃ ┣ 📂images
┃ ┃ ┣ 📜auweblogo-en.png
┃ ┃ ┣ 📜Flag-European-Union.jpg
┃ ┃ ┣ 📜gmes.png
┃ ┃ ┣ 📜li.png
┃ ┃ ┣ 📜Observertoire.png
┃ ┃ ┣ 📜rsz_1rsz_observertoire.png
┃ ┃ ┣ 📜rsz_observertoire.png
┃ ┃ ┗ 📜rsz_visuelmisland.png
┃ ┗ 📜quasar-logo-full.svg
┣ 📂boot
┃ ┣ 📜.gitkeep
┃ ┣ 📜auth_guards.js
┃ ┣ 📜axios.js
┃ ┣ 📜i18n.js
┃ ┗ 📜VueGtag.js
┣ 📂Calculations
┃ ┗ 📜LULC_Calculation.js
┣ 📂colors
┃ ┗ 📜colors.js
┣ 📂components
┃ ┣ 📂Admin
┃ ┃ ┣ 📂Lists
┃ ┃ ┃ ┣ 📜CustomRegions.vue
┃ ┃ ┃ ┣ 📜ECOUnitList.vue
┃ ┃ ┃ ┗ 📜SOCList.vue
┃ ┃ ┗ 📂Uploads
┃ ┃ ┃ ┗ 📜uploaders.vue
┃ ┣ 📂Charts
┃ ┃ ┣ 📜BarChart.vue
┃ ┃ ┣ 📜Doughnut.vue
┃ ┃ ┣ 📜linechart.vue
┃ ┃ ┗ 📜PieChart.vue
┃ ┣ 📂CommonTabItems
┃ ┃ ┣ 📜Icons.vue
┃ ┃ ┣ 📜Summary.vue
┃ ┃ ┗ 📜YearSelection.vue
┃ ┣ 📂Dialogs
┃ ┃ ┗ 📜LargeAreaDialog.vue
┃ ┣ 📂Forms
┃ ┃ ┗ 📜Edit_User_Details.vue
┃ ┣ 📂HomePageComponents
┃ ┃ ┣ 📜Accordion.vue
┃ ┃ ┗ 📜UserFeedback.vue
┃ ┣ 📂Legend
┃ ┃ ┗ 📜Legend.vue
┃ ┣ 📂TabComponents
┃ ┃ ┣ 📂ForestChange
┃ ┃ ┃ ┣ 📂ForestChangeCalculations
┃ ┃ ┃ ┃ ┗ 📜HansenAnalysis.js
┃ ┃ ┃ ┗ 📜ForestChange.vue
┃ ┃ ┣ 📂ForestFire
┃ ┃ ┃ ┣ 📜ForestFire.vue
┃ ┃ ┃ ┣ 📜ForestFireSelections.vue
┃ ┃ ┃ ┗ 📜ForestFireStats.js
┃ ┃ ┣ 📂LDH
┃ ┃ ┃ ┗ 📜LDH.vue
┃ ┃ ┣ 📂Medalus
┃ ┃ ┃ ┣ 📂Medaluscalculations
┃ ┃ ┃ ┃ ┗ 📜MedalusCalculations.js
┃ ┃ ┃ ┣ 📜IsdSelection.vue
┃ ┃ ┃ ┗ 📜Medalus.vue
┃ ┃ ┗ 📂Sdg1531
┃ ┃ ┃ ┣ 📜Sdg1531.vue
┃ ┃ ┃ ┗ 📜SDGs.vue
┃ ┣ 📜Select_Features.vue
┃ ┗ 📜Tabs.vue
┣ 📂css
┃ ┣ 📜app.sass
┃ ┗ 📜quasar.variables.sass
┣ 📂Download_Utils
┃ ┣ 📜Download_Chart.js
┃ ┗ 📜Download_CSV.js
┣ 📂Helpers
┃ ┣ 📂EventBus
┃ ┃ ┗ 📜eventBus.js
┃ ┣ 📂MapProviders
┃ ┃ ┗ 📜leaflet-providers.js
┃ ┗ 📂Markers_Icons
┃ ┃ ┗ 📜Marker.js
┣ 📂i18n
┃ ┣ 📂en-us
┃ ┃ ┗ 📜index.js
┃ ┣ 📂fr
┃ ┃ ┗ 📜index.js
┃ ┗ 📜index.js
┣ 📂layouts
┃ ┗ 📜MainLayout.vue
┣ 📂Mixins
┃ ┣ 📜CalculateArea.vue
┃ ┣ 📜GoogleAnalytics.vue
┃ ┣ 📜ReferenceRasters.vue
┃ ┣ 📜RenderRaster.vue
┃ ┗ 📜UserRegData.vue
┣ 📂pages
┃ ┣ 📂Admin
┃ ┃ ┗ 📜Admin.vue
┃ ┣ 📂Authentication
┃ ┃ ┗ 📜Login.vue
┃ ┣ 📂Faq
┃ ┃ ┗ 📜Faq.vue
┃ ┣ 📂FeedBack
┃ ┃ ┗ 📜FeedBackPage.vue
┃ ┣ 📂Home
┃ ┃ ┗ 📜Index.vue
┃ ┣ 📂Map
┃ ┃ ┗ 📜Maps.vue
┃ ┣ 📂UserProfile
┃ ┃ ┗ 📜Profile.vue
┃ ┗ 📜Error404.vue
┣ 📂RasterDataForrmatters
┃ ┣ 📜LULC_RasterFormatter.js
┃ ┗ 📜RasterRenderer.js
┣ 📂router
┃ ┣ 📜index.js
┃ ┗ 📜routes.js
┣ 📂SDG_Selection
┃ ┗ 📜SDGselection.js
┣ 📂Services
┃ ┣ 📜Logger.js
┃ ┣ 📜Notifications.js
┃ ┗ 📜RequestAnalysis.js
┣ 📂store
┃ ┣ 📂ApiSettings
┃ ┃ ┣ 📜actions.js
┃ ┃ ┣ 📜getters.js
┃ ┃ ┣ 📜index.js
┃ ┃ ┣ 📜mutations.js
┃ ┃ ┗ 📜state.js
┃ ┣ 📂auth
┃ ┃ ┣ 📜actions.js
┃ ┃ ┣ 📜getters.js
┃ ┃ ┣ 📜index.js
┃ ┃ ┣ 📜mutations.js
┃ ┃ ┗ 📜state.js
┃ ┣ 📂carousel
┃ ┃ ┣ 📜actions.js
┃ ┃ ┣ 📜getters.js
┃ ┃ ┣ 📜index.js
┃ ┃ ┣ 📜mutations.js
┃ ┃ ┗ 📜state.js
┃ ┣ 📂Faq
┃ ┃ ┣ 📜actions.js
┃ ┃ ┣ 📜getters.js
┃ ┃ ┣ 📜index.js
┃ ┃ ┣ 📜mutations.js
┃ ┃ ┗ 📜state.js
┃ ┣ 📂geotiffs
┃ ┃ ┣ 📜actions.js
┃ ┃ ┣ 📜getters.js
┃ ┃ ┣ 📜index.js
┃ ┃ ┣ 📜mutations.js
┃ ┃ ┗ 📜state.js
┃ ┣ 📂queuedResults
┃ ┃ ┣ 📜actions.js
┃ ┃ ┣ 📜getters.js
┃ ┃ ┣ 📜index.js
┃ ┃ ┣ 📜mutations.js
┃ ┃ ┗ 📜state.js
┃ ┣ 📂RasterTypes
┃ ┃ ┣ 📜actions.js
┃ ┃ ┣ 📜getters.js
┃ ┃ ┣ 📜index.js
┃ ┃ ┣ 📜mutations.js
┃ ┃ ┗ 📜state.js
┃ ┣ 📂shapefiles
┃ ┃ ┣ 📜actions.js
┃ ┃ ┣ 📜getters.js
┃ ┃ ┣ 📜index.js
┃ ┃ ┣ 📜mutations.js
┃ ┃ ┗ 📜state.js
┃ ┣ 📂users
┃ ┃ ┣ 📜actions.js
┃ ┃ ┣ 📜getters.js
┃ ┃ ┣ 📜index.js
┃ ┃ ┣ 📜mutations.js
┃ ┃ ┗ 📜state.js
┃ ┣ 📜index.js
┃ ┗ 📜store-flag.d.ts
┣ 📜App.vue
┗ 📜index.template.html
```
|
/**-------------------------------------------------------------------------------------------------------------------
*
* @file DIOModBusElectricMeter.cpp
*
* @class DIOMODBUSELECTRICMETER
* @brief Data Input/Output ModBus Electric Meter class
* @ingroup DATAIO
*
* @copyright GEN Group. All rights reserved.
*
* @cond
* 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.
* @endcond
*
* --------------------------------------------------------------------------------------------------------------------*/
/*---- PRECOMPILATION CONTROL ----------------------------------------------------------------------------------------*/
#include "GEN_Defines.h"
/*---- INCLUDES ------------------------------------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "XDateTime.h"
#include "XTimer.h"
#include "XFactory.h"
#include "XFSMachine.h"
#include "XBuffer.h"
#include "XTrace.h"
#include "DIOStream.h"
#include "DIOModBusElectricMeter.h"
#include "XMemory_Control.h"
/*---- GENERAL VARIABLE ----------------------------------------------------------------------------------------------*/
/*---- CLASS MEMBERS -------------------------------------------------------------------------------------------------*/
#pragma region DIOMODBUSELECTRICMETERXEVENT
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn DIOMODBUSELECTRICMETERXEVENT::DIOMODBUSELECTRICMETERXEVENT(XSUBJECT* subject,XDWORD type)
* @brief Constructor
* @ingroup DATAIO
*
* @param[in] XSUBJECT* :
* @param[in] XDWORD :
*
* @return Does not return anything.
*
* --------------------------------------------------------------------------------------------------------------------*/
DIOMODBUSELECTRICMETERXEVENT::DIOMODBUSELECTRICMETERXEVENT(XSUBJECT* subject,XDWORD type) : XEVENT(subject,type)
{
Clean();
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn DIOMODBUSELECTRICMETERXEVENT::~DIOMODBUSELECTRICMETERXEVENT()
* @brief Destructor
* @note VIRTUAL
* @ingroup DATAIO
*
* @return Does not return anything.
*
* --------------------------------------------------------------------------------------------------------------------*/
DIOMODBUSELECTRICMETERXEVENT::~DIOMODBUSELECTRICMETERXEVENT()
{
Clean();
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn void DIOMODBUSELECTRICMETERXEVENT::Clean()
* @brief Clean the attributes of the class: Default initialice
* @note INTERNAL
* @ingroup DATAIO
*
* @return void : does not return anything.
*
* --------------------------------------------------------------------------------------------------------------------*/
void DIOMODBUSELECTRICMETERXEVENT::Clean()
{
}
#pragma endregion
#pragma region DIOMODBUSELECTRICMETER
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn DIOMODBUSELECTRICMETER::DIOMODBUSELECTRICMETER(DIOSTREAM* diostream, DIOMODBUS_CLIENTMODE mode)
* @brief Constructor
* @ingroup DATAIO
*
* @param[in] DIOSTREAM* :
* @param[in] DIOMODBUS_CLIENTMODE mode :
*
* @return Does not return anything.
*
* --------------------------------------------------------------------------------------------------------------------*/
DIOMODBUSELECTRICMETER::DIOMODBUSELECTRICMETER(DIOSTREAM* diostream, DIOMODBUS_CLIENTMODE mode)
{
Clean();
modbusprotocol = new DIOMODBUS_CLIENT(diostream, mode);
if(modbusprotocol)
{
RegisterEvent(DIOMODBUSELECTRICMETERXEVENT_TYPE_C_TR_AA_READVALUES);
RegisterEvent(DIOMODBUSELECTRICMETERXEVENT_TYPE_C_CI_NU_2_READVALUE);
GEN_XFACTORY_CREATE(xtimer, CreateTimer())
}
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn DIOMODBUSELECTRICMETER::~DIOMODBUSELECTRICMETER()
* @brief Destructor
* @note VIRTUAL
* @ingroup DATAIO
*
* @return Does not return anything.
*
* --------------------------------------------------------------------------------------------------------------------*/
DIOMODBUSELECTRICMETER::~DIOMODBUSELECTRICMETER()
{
GEN_XFACTORY.DeleteTimer(xtimer);
Disconnect();
DeRegisterEvent(DIOMODBUSELECTRICMETERXEVENT_TYPE_C_TR_AA_READVALUES);
DeRegisterEvent(DIOMODBUSELECTRICMETERXEVENT_TYPE_C_CI_NU_2_READVALUE);
delete modbusprotocol;
Clean();
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn DIOMODBUS_CLIENT* DIOMODBUSELECTRICMETER::GetModBusProtocol()
* @brief GetModBusProtocol
* @ingroup DATAIO
*
* @return DIOMODBUS_CLIENT* :
*
* --------------------------------------------------------------------------------------------------------------------*/
DIOMODBUS_CLIENT* DIOMODBUSELECTRICMETER::GetModBusProtocol()
{
return modbusprotocol;
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn bool DIOMODBUSELECTRICMETER::Connect(XBYTE unit, bool inlittleendian, int timeout)
* @brief Connect
* @ingroup DATAIO
*
* @param[in] unit :
* @param[in] inlittleendian :
* @param[in] timeout :
*
* @return bool : true if is succesful.
*
* --------------------------------------------------------------------------------------------------------------------*/
bool DIOMODBUSELECTRICMETER::Connect(XBYTE unit, bool inlittleendian, int timeout)
{
if(!modbusprotocol) return false;
if(!modbusprotocol->GetDIOStream()) return false;
if(modbusprotocol->GetDIOStream()->GetConnectStatus()!=DIOSTREAMSTATUS_DISCONNECTED) return false;
if(!modbusprotocol->Connect(unit,timeout)) return false;
this->unit = unit;
this->inlittleendian = inlittleendian;
canceloperations = false;
return true;
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn bool DIOMODBUSELECTRICMETER::CMD_C_CI_NU_2_ReadAllValues(int TM, XDATETIME* timestart, XDATETIME* timeend, XVECTOR<DIO_C_CI_NU_2_RESULT*>* results, int timeout)
* @brief CMD_C_CI_NU_2_ReadAllValues
* @ingroup DATAIO
*
* @param[in] TM :
* @param[in] timestart :
* @param[in] timeend :
* @param[in] results :
* @param[in] timeout :
*
* @return bool : true if is succesful.
*
* --------------------------------------------------------------------------------------------------------------------*/
bool DIOMODBUSELECTRICMETER::CMD_C_CI_NU_2_ReadAllValues(int TM, XDATETIME* timestart, XDATETIME* timeend, XVECTOR<DIO_C_CI_NU_2_RESULT*>* results, int timeout)
{
if(!results) return false;
if(!modbusprotocol) return false;
XBUFFER answer;
float fresult = 0.0f;
int iresult = 0;
bool status;
status = modbusprotocol->ReadHoldingRegisters(50812, 14, answer, timeout);
if(status)
{
DIO_C_CI_NU_2_RESULT* result;
result = new DIO_C_CI_NU_2_RESULT();
if(result)
{
result->GetDateTime()->Read();
result->GetDateTime()->SetSeconds(0);
switch(TM)
{
case 1 : for(int c=0; c<8; c++)
{
result->GetIndexValues()->Add(c+1);
result->GetValues()->Add(0);
}
ReadRegister(50780, 2, timeout, iresult);
result->GetIndexValues()->Add(1);
result->GetValues()->Add(iresult);
ReadRegister(50782, 2, timeout, iresult);
result->GetIndexValues()->Add(2);
result->GetValues()->Add(iresult);
break;
case 2 : ReadRegister(51046, 2, 100, timeout, fresult);
result->GetIndexValues()->Add(1);
result->GetValues()->Add((int)fresult);
for(int c=1; c<8; c++)
{
result->GetIndexValues()->Add(c+1);
result->GetValues()->Add(0);
}
break;
default : status = false;
break;
}
results->Add(result);
} else status = false;
}
return status;
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn bool DIOMODBUSELECTRICMETER::CMD_C_CI_NU_2_DeleteResults(XVECTOR<DIO_C_CI_NU_2_RESULT*>* results)
* @brief CMD_C_CI_NU_2_DeleteResults
* @ingroup DATAIO
*
* @param[in] results :
*
* @return bool : true if is succesful.
*
* --------------------------------------------------------------------------------------------------------------------*/
bool DIOMODBUSELECTRICMETER::CMD_C_CI_NU_2_DeleteResults(XVECTOR<DIO_C_CI_NU_2_RESULT*>* results)
{
if(!results) return false;
if(results->IsEmpty()) return false;
results->DeleteContents();
results->DeleteAll();
return true;
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn bool DIOMODBUSELECTRICMETER::CMD_C_TR_AA_ReadValues(DIO_C_TR_AA_RESULT* result, int timeout)
* @brief CMD_C_TR_AA_ReadValues
* @ingroup DATAIO
*
* @param[in] result :
* @param[in] timeout :
*
* @return bool : true if is succesful.
*
* --------------------------------------------------------------------------------------------------------------------*/
bool DIOMODBUSELECTRICMETER::CMD_C_TR_AA_ReadValues(DIO_C_TR_AA_RESULT* result, int timeout)
{
if(!result) return false;
if(!modbusprotocol) return false;
float fresult = 0.0f;
int iresult = 0;
// Totalizadores Energeticos
ReadRegister(50780, 2, timeout, iresult); result->SetActiveImport(iresult); // Activa Importacion
result->SetActiveExport(0); // Activa Exportacion
result->SetReactiveQ(1, 0); // Reactiva Q1
result->SetReactiveQ(2, 0); // Reactiva Q2
result->SetReactiveQ(3, 0); // Reactiva Q3
result->SetReactiveQ(4, 0); // Reactiva Q4
// Potencias Instantaneas
ReadRegister(50536, 2, 100, timeout, fresult); result->SetTotalActivePower((int)fresult); // Potencia Activa Total
ReadRegister(50538, 2, 100, timeout, fresult); result->SetTotalReactivePower((int)fresult); // Potencia Reactiva Total
ReadRegister(50542, 2, 1000, timeout, fresult); result->SetTotalPowerFactor(fresult); // Factor de Potencia Total
ReadRegister(50544, 2, 100, timeout, fresult); result->SetActivePowerPhase(1, (int)(fresult)); // Potencia Activa Fase I
ReadRegister(50550, 2, 100, timeout, fresult); result->SetReactivePowerPhase(1, (int)(fresult)); // Potencia Reactiva Fase I
ReadRegister(50562, 2, 1000, timeout, fresult); result->SetPowerFactorPhase(1, fresult); // Factor de Potencia Fase I
ReadRegister(50546, 2, 100, timeout, fresult); result->SetActivePowerPhase(2, (int)(fresult)); // Potencia Activa Fase II
ReadRegister(50552, 2, 100, timeout, fresult); result->SetReactivePowerPhase(2, (int)(fresult)); // Potencia Reactiva Fase II
ReadRegister(50564, 2, 1000, timeout, fresult); result->SetPowerFactorPhase(2, fresult); // Factor de Potencia Fase II
ReadRegister(50548, 2, 100, timeout, fresult); result->SetActivePowerPhase(3, (int)(fresult)); // Potencia Activa Fase III
ReadRegister(50554, 2, 100, timeout, fresult); result->SetReactivePowerPhase(3, (int)(fresult)); // Potencia Reactiva Fase III
ReadRegister(50566, 2, 1000, timeout, fresult); result->SetPowerFactorPhase(3, fresult); // Factor de Potencia Fase III
// Valores Secundarios
ReadRegister(50520, 2, 100, timeout, fresult); result->SetVoltagePhase(1, fresult); // Tension Fase I
ReadRegister(50528, 2, 1000, timeout, fresult); result->SetCurrentPhase(1, fresult); // Intensidad Fase I
ReadRegister(50522, 2, 100, timeout, fresult); result->SetVoltagePhase(2, fresult); // Tension Fase II
ReadRegister(50530, 2, 1000, timeout, fresult); result->SetCurrentPhase(2, fresult); // Intensidad Fase II
ReadRegister(50524, 2, 100, timeout, fresult); result->SetVoltagePhase(3, fresult); // Tension Fase III
ReadRegister(50532, 2, 1000, timeout, fresult); result->SetCurrentPhase(3, fresult); // Intensidad Fase III
return true;
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn bool DIOMODBUSELECTRICMETER::CancelOperations()
* @brief CancelOperations
* @ingroup DATAIO
*
* @return bool : true if is succesful.
*
* --------------------------------------------------------------------------------------------------------------------*/
bool DIOMODBUSELECTRICMETER::CancelOperations()
{
canceloperations = true;
return true;
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn void DIOMODBUSELECTRICMETER::Disconnect()
* @brief Disconnect
* @ingroup DATAIO
*
* @return void : does not return anything.
*
* --------------------------------------------------------------------------------------------------------------------*/
void DIOMODBUSELECTRICMETER::Disconnect()
{
if(!modbusprotocol) return;
modbusprotocol->Disconnect();
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn bool DIOMODBUSELECTRICMETER::ReadRegister(int registerID, int nwords, int divisor, int timeout, float& result)
* @brief ReadRegister
* @ingroup DATAIO
*
* @param[in] registerID :
* @param[in] nwords :
* @param[in] divisor :
* @param[in] timeout :
* @param[in] result :
*
* @return bool : true if is succesful.
*
* --------------------------------------------------------------------------------------------------------------------*/
bool DIOMODBUSELECTRICMETER::ReadRegister(int registerID, int nwords, int divisor, int timeout, float& result)
{
XBUFFER answer;
XDWORD dword = 0;
XWORD word = 0;
int data = 0;
result = 0.0f;
if(!modbusprotocol->ReadHoldingRegisters(registerID, nwords, answer, timeout)) return false;
if(nwords == 2)
{
answer.Get(dword);
data = (int)dword;
}
if(nwords == 1)
{
answer.Get(word);
data = (int)word;
}
result = ((float)data / divisor);
return true;
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn bool DIOMODBUSELECTRICMETER::ReadRegister(int registerID, int nwords, int timeout, int& result)
* @brief ReadRegister
* @ingroup DATAIO
*
* @param[in] registerID :
* @param[in] nwords :
* @param[in] timeout :
* @param[in] result :
*
* @return bool : true if is succesful.
*
* --------------------------------------------------------------------------------------------------------------------*/
bool DIOMODBUSELECTRICMETER::ReadRegister(int registerID, int nwords, int timeout, int& result)
{
XBUFFER answer;
XDWORD dword = 0;
XWORD word = 0;
result = 0;
if(!modbusprotocol->ReadHoldingRegisters(registerID, nwords, answer, timeout)) return false;
if(nwords == 2)
{
answer.Get(dword);
result = (int)dword;
}
if(nwords == 1)
{
answer.Get(word);
result = (int)word;
}
return true;
}
/**-------------------------------------------------------------------------------------------------------------------
*
* @fn void DIOMODBUSELECTRICMETER::Clean()
* @brief Clean the attributes of the class: Default initialice
* @note INTERNAL
* @ingroup DATAIO
*
* @return void : does not return anything.
*
* --------------------------------------------------------------------------------------------------------------------*/
void DIOMODBUSELECTRICMETER::Clean()
{
xtimer = NULL;
unit = 0;
inlittleendian = true;
lastactiveenergysum = 0;
lastreactiveenergysum = 0;
modbusprotocol = NULL;
canceloperations = false;
}
#pragma endregion
|
/**
* Día de la documentación: 05/09/2023
*
* Descripción del archivo "prestamosStore.js":
* Este archivo define un store de Pinia llamado "UsePrestamosStore" que se utiliza para gestionar el estado relacionado con los préstamos.
* El store almacena y gestiona los préstamos obtenidos desde Firestore y define columnas necesarias para tablas relacionadas con préstamos.
* También proporciona acciones para escuchar cambios en la base de datos Firestore y obtener préstamos por persona o producto.
*
* Características clave:
* - Manejo del estado de los préstamos.
* - Definición de columnas para tablas relacionadas con préstamos.
* - Acción para escuchar cambios en la base de datos Firestore.
* - Acción para obtener préstamos por persona.
* - Acción para obtener préstamos por producto.
*
* @store
*/
//importaciones
import { defineStore } from "pinia";
import {
collection,
doc,
getDoc,
getDocs,
onSnapshot,
orderBy,
query,
where,
} from "firebase/firestore";
import { db } from "src/firebaseInit";
import { UseUtilsStore } from "./utilsStore";
import { useDatabaseStore } from "./DatabaseStore";
// Definición del store de préstamos.
export const UsePrestamosStore = defineStore("prestamos", {
state: () => ({
prestamosDatabase: [],
// stadisticTableBarInfo: [],
/** Definición de los datos que se van a mostrar en las estadisticas
ejemplo:{
* name:nombre de la columana
* align:alineamiento
* label:label
* field:campo
* sortable:y el orden
* }
/** Definición de columnas para tablas relacionadas con prestamos.
Estos campos son los que se le pasan a la columna, y varian segun
las columnas y como se definan
ejemplo:{
* name:nombre de la columana
* align:alineamiento
* label:label
* field:campo
* sortable:y el orden
* }
*/
columns: [
{
name: "document",
align: "center",
label: "Documento",
field: (row) => row.customer.documentNumber,
sortable: true,
},
{
name: "name",
required: true,
label: "Nombre",
align: "left",
field: (row) => row.customer.name,
format: (val) => `${val}`,
sortable: true,
},
{
name: "rol",
label: "Rol",
field: (row) => row.customer.rol,
sortable: true,
},
{
name: "date",
label: "Fecha préstamo",
field: (row) => row.dateBorrowed,
format: (val) => new Date(val).toLocaleDateString(),
},
{
name: "amout",
label: "Cantida",
field: (row) => row.productosList[0].quantity,
},
{
name: "user",
label: "Usuario",
field: (row) => row.createdBy,
sortable: true,
},
],
internalColumns: [
//definición de las internal columns
{
name: "productoId",
align: "center",
label: "Id Producto",
field: (row) => row.productId,
sortable: true,
},
{
name: "product",
required: true,
label: "Producto",
align: "left",
field: (row) => row.product,
sortable: true,
},
{
name: "cantidad",
label: "Cantidad",
field: (row) => row.quantity,
sortable: true,
},
{
name: "fechaPrestado",
label: "Fecha préstamo",
field: (row) => row.dateBorrowed,
format: (val) => new Date(val).toLocaleDateString(),
},
{
name: "fechaEntrega",
label: "Fecha Entrega",
field: (row) => row.dueDate,
format: (val) => new Date(val).toLocaleDateString(),
},
{ name: "acciones", label: "Acciones", field: "acciones" },
],
/**
prestamosDatabase: [], Almacena la lista de préstamos obtenida de Firestore.
stadisticTableBarInfo: [ ... ], Información estadística de préstamos.
columns: [ ... ], Definición de columnas para tablas relacionadas con préstamos.
internalColumns: [ ... ], Definición de columnas internas para tablas relacionadas con préstamos.
allPersonDocs: [], Almacena todos los documentos de una persona.
allborrowingsPerson: [], Almacena todos los préstamos de una persona.
allBorrowingsProducts: [], Almacena todos los préstamos de un producto.
currentCustomer: {}, Almacena los datos de un cliente actual.
*/
allPersonDocs: [],
allborrowingsPerson: [],
allBorrowingsProducts: [],
currentCustomer: {},
}),
getters: {
activeBorrowings: (state) =>
state.allPersonDocs.filter(
(prestamo) => prestamo.returnedQuantity < prestamo.quantity
),
stadisticTableBarInfo(state) {
const array = [];
const usuarioPrestamo = state.prestamosDatabase.map(
(prestamo) => prestamo.customerDocumentNumber
);
const usuarioMas = Math.max(...usuarioPrestamo);
const usuarioMaximaCantidad = state.prestamosDatabase.filter(
(prestamo) => prestamo.customerDocumentNumber == usuarioMas
);
// const totalUsuario = {
// text_color: "text-light-black",
// titulo: "Usuario con mas prestamos",
// valor: usuarioMaximaCantidad[0].nombre,
// periodo: `Usuario: ${usuarioMaximaCantidad[0].customerDocumentNumber}`,
// };
// array.push(totalUsuario);
return array;
},
},
// Acción para escuchar cambios en la colección de préstamos en Firestore.
actions: {
resetCurrentCustomer() {
this.currentCustomer = {};
},
async listenChanges() {
// Crear una consulta para la colección "borrowings" ordenada por "dateBorrowed".
const q = query(collection(db, "borrowings"), orderBy("dateBorrowed"));
// Establecer un observador en la consulta.
onSnapshot(q, { includeMetadataChanges: true }, (snapshot) => {
snapshot.docChanges().forEach((change) => {
// si se añade un registro
if (change.type == "added") {
if (
!this.prestamosDatabase.some(
(item) => item.docId == change.doc.id
)
) {
const data = {
docId: change.doc.id,
...change.doc.data(),
};
// Agregar el préstamo al principio de la lista.
this.prestamosDatabase.unshift(data);
}
//En caso de que se modifique
} else if (change.type == "modified") {
let cambio = this.prestamosDatabase.find(
(item) => item.docId == change.doc.id
);
let index = this.prestamosDatabase.findIndex(
(item) => item.docId == change.doc.id
);
// Actualizar los datos del préstamo en la lista.
this.prestamosDatabase[index] = {
...cambio,
...change.doc.data(),
};
// En caso de que se remueva un registro o dato
} else if (change.type == "removed") {
// Si se elimina un préstamo, filtrar y actualizar la lista eliminando el préstamo correspondiente.
this.prestamosDatabase = this.prestamosDatabase.filter(
(item) => item.docId != change.doc.id
);
}
const source = snapshot.metadata.fromCache
? "local cache prestamos"
: "server";
console.log("Data came from " + source);
});
});
},
updateMoraPerson(cedula) {
const databaseStore = useDatabaseStore();
const moraActual = this.currentCustomer.enMora;
const enMora = this.activeBorrowings.some((pedido) => pedido.enMora);
console.log(moraActual, enMora);
if (moraActual != enMora) {
databaseStore.updateElement({ enMora }, "customers", cedula);
this.currentCustomer = { ...this.currentCustomer, enMora };
}
},
/**
* Acción para obtener préstamos por persona.
* @param {string} cedula - Cédula de la persona.
* @returns {Array} - Lista de préstamos de la persona.
*/
async getPrestamosByPerson(cedula) {
const utils = UseUtilsStore();
let docs;
const customerRef = doc(db, "customers", cedula);
this.currentCustomer = await getDoc(customerRef);
console.log(this.currentCustomer);
if (!this.currentCustomer.data()) {
utils.notifyError("No encontramos el cliente", "warning");
return;
}
this.currentCustomer = this.currentCustomer.data();
const q = query(collection(customerRef, "borrowings"));
docs = await getDocs(q);
docs = docs.docs.map((document, index) => {
const today = new Date().getTime();
const enMora =
today > document.data().dueDate &&
document.data().returnedQuantity < document.data().quantity;
return { index, docId: document.id, ...document.data(), enMora };
});
this.allPersonDocs = docs;
this.allPersonDocs.sort((a, b) => {
if (a.enMora === true && b.enMora === false) {
return -1;
} else if (a.enMora === false && b.enMora === true) {
return 1;
}
return 0;
});
this.updateMoraPerson(cedula);
console.log(this.allPersonDocs);
return docs;
},
/**
* Acción para obtener préstamos por producto.
* @param {string} id - ID del producto.
* @returns {Array} - Lista de préstamos del producto.
*/
async getPrestamosByProduct(id) {
const idString = id;
let docs;
const productRef = doc(db, "products", idString);
const q = query(
collection(productRef, "borrowings"),
orderBy("diaPrestamo", "desc")
);
docs = await getDocs(q);
docs = docs.docs.map((document, index) => {
return { index, docId: document.id, ...document.data() };
});
this.allBorrowingsProducts = docs;
return docs;
},
},
});
|
import { React, useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.css";
import PageHeader from "../../../components/pageheader/PageHeader";
import { Link } from "react-router-dom";
import { CheckOutlined, CloseOutlined } from "@ant-design/icons";
import TableINDEX from "../../../components/table";
import { Button, Space } from "antd";
import Swal from "sweetalert2";
import {
getListReturningRequest,
deleteReturningRequest,
completeReturning,
} from "../../../services";
import {
handleSort,
onChangeSearch,
onChangeSort,
onPageVisit,
dateFormatForReturning,
} from "../../../components/methods/methods";
import { useLayoutEffect } from "react";
function ReturnAsset() {
let [listRequests, setListRequests] = useState([]);
const [totalElements, setTotalElements] = useState();
const [functioned, setFunctioned] = useState(0);
const [returningStatus, setReturningStatus] = useState(0);
const [pageIndex, setPageIndex] = useState(1);
const [searchInput, setSearchInput] = useState("");
const [stateInput, setStateInput] = useState("");
const [returnedDateInput, setReturnedDateInput] = useState("");
const [sortInput, setSortInput] = useState("");
useLayoutEffect(() => {
document.addEventListener("visibilitychange", onVisibilityChange);
return () =>
document.removeEventListener("visibilitychange", onVisibilityChange);
}, []);
const onVisibilityChange = () => {
let temp = localStorage.getItem("assignment-request");
if (document.visibilityState === "visible") {
if (temp === "1") {
localStorage.removeItem("assignment-request");
setFunctioned(1);
}
}
};
useEffect(() => {
onPageVisit();
getListReturningRequest(
pageIndex - 1,
searchInput,
returnedDateInput,
sortInput,
stateInput
).then((response) => {
let temp = response.data.content.content;
setListRequests(temp);
setTotalElements(response.data.content.totalElements);
setFunctioned(0);
setReturningStatus(0);
});
}, [
pageIndex,
searchInput,
returnedDateInput,
stateInput,
sortInput,
functioned,
returningStatus,
]);
const searchAction = (value) => {
setSearchInput(onChangeSearch(value));
setPageIndex(1);
};
const sortActionState = (value) => {
setStateInput(onChangeSort(value));
setPageIndex(1);
};
const sortActionReturnedDate = (value) => {
setReturnedDateInput(onChangeSort(value));
setPageIndex(1);
};
const handlePageChange = (newpage) => {
setPageIndex(newpage);
};
const onChange = (pagination, filters, sorter, extra) => {
setSortInput(handleSort(sorter));
};
const state = [
{
label: "Completed",
value: "Completed",
},
{
label: "Waiting for returning",
value: "Waiting for returning",
},
];
const columns = [
{
title: "No.",
dataIndex: "id",
sorter: {
multiple: 1,
},
width: "10%",
render: (text) => <span>{text}</span>,
},
{
title: "Asset Code",
dataIndex: "assignment.asset.code",
sorter: {
multiple: 1,
},
width: "20%",
render: (text, record) => <span>{record.assignment.asset.code}</span>,
},
{
title: "Asset Name",
dataIndex: "assignment.asset.name",
sorter: {
multiple: 2,
},
width: "30%",
ellipsis: true,
render: (text, record) => <span>{record.assignment.asset.name}</span>,
},
{
title: "Requested By",
dataIndex: "requestedBy",
render: (text, record) => <span>{record.requestedBy.username}</span>,
sorter: {
multiple: 3,
},
width: "20%",
},
{
title: "Assigned Date",
dataIndex: "assignment.assignedDate",
render: (text, record) => (
<span>
{record.assignment.assignedDate?.split("-").reverse().join("-")}
</span>
),
sorter: {
multiple: 3,
},
width: "20%",
},
{
title: "Accepted By",
dataIndex: "acceptedBy",
render: (text, record) => <span>{record.acceptedBy?.username}</span>,
sorter: {
multiple: 3,
},
width: "20%",
},
{
title: "Returned Date",
dataIndex: "returnedDate",
render: (text, record) => (
<span>{record.returnedDate?.split("-").reverse().join("-")}</span>
),
sorter: {
multiple: 3,
},
width: "20%",
},
{
title: "State",
dataIndex: "state",
sorter: {
multiple: 4,
},
width: "20%",
render: (text) => <span>{text}</span>,
},
{
title: null,
key: "actions",
width: "10%",
render: (_, record) => (
<Space>
{record.state === "Waiting for returning" && (
<>
<Link
onClick={() => {
Swal.fire({
title: "",
html: `<div style="font-size:20px">Do you want to mark this returning request as "Completed"? </div>`,
icon: "question",
confirmButtonText: "Yes",
cancelButtonText: "No",
showCancelButton: true,
showConfirmButton: true,
confirmButtonColor: "#CF2338",
confirmButtonText: "Yes",
cancelButtonText: "No",
}).then((result) => {
if (result.isConfirmed) {
completeReturning(record.id).then(() => {
localStorage.setItem("returning-asset", "1");
localStorage.setItem("returning-assignment", "1");
setFunctioned(1);
Swal.fire({
title: "Completed",
icon: "success",
showConfirmButton: true,
confirmButtonColor: "#CF2338",
allowEscapeKey: true,
});
});
}
});
}}
>
<div className="icon-custom-small">
<CheckOutlined className="tickIcon" />
</div>
</Link>
<Link
onClick={() => {
Swal.fire({
title: "",
html: `<div style="font-size:20px">Do you want to cancel this returning request?</div>`,
icon: "warning",
confirmButtonText: "Yes",
cancelButtonText: "No",
showCancelButton: true,
showConfirmButton: true,
confirmButtonColor: "#CF2338",
confirmButtonText: "Yes",
cancelButtonText: "No",
}).then((result) => {
if (result.isConfirmed) {
deleteReturningRequest(record.id).then(() => {
localStorage.setItem("returning-assignment", "1");
setFunctioned(1);
Swal.fire({
title: "Deleted",
icon: "success",
showConfirmButton: true,
confirmButtonColor: "#CF2338",
allowEscapeKey: true,
});
});
}
});
}}
>
<div className="icon-custom-small">
<CloseOutlined className="xIcon" />
</div>
</Link>
</>
)}
{record.state === "Declined" && (
<>
<Button style={{ padding: 0 }} type="link" disabled>
<div className="icon-custom-small">
<CheckOutlined className="tickIcon-disable" />
</div>
</Button>
<Button style={{ padding: 0 }} type="link" disabled>
<div className="icon-custom-small">
<CloseOutlined className="xIcon-disable" />
</div>
</Button>
</>
)}
</Space>
),
},
];
const menu = [
{
type: "SortBar",
props: {
id: "stateSort",
title: "stateSort",
menu: state,
handleChange: sortActionState,
placeholder: "State",
},
},
{
type: "DateBar",
props: {
placeholder: "Returned Date",
onChange: sortActionReturnedDate,
},
},
{
type: "SearchBar",
props: {
onSearch: searchAction,
},
},
];
return (
<>
<PageHeader tableName="Request list" menu={menu} />
<TableINDEX
tableOnchange={onChange}
columns={columns}
totalElements={totalElements}
data={listRequests || []}
pagination={{
current: pageIndex,
pageSize: 10,
total: totalElements,
onChange: handlePageChange,
size: "medium",
}}
/>
</>
);
}
export default ReturnAsset;
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head th:replace="/fragments/head :: head"></head>
<body>
<nav th:replace="/fragments/navbar :: nav"></nav>
<div class="container-fluid m-5 contenedor">
<div th:if="${error != null}" class="card text-white bg-danger mb-3 mensajeError" >
<div class="card-body">
<h5 class="card-title">Error!</h5>
<p class="card-text" th:text="${error}"></p>
</div>
</div>
<div th:if="${exito != null}" class="card text-white bg-success mb-3 mt-3 mensajeExito" >
<div class="card-body">
<h5 class="card-title">Exito!</h5>
<p class="card-text" th:text="${exito}"></p>
</div>
</div>
<form class="formulario" th:action="@{/logincheck}" method="POST">
<div class="form-group my-3">
<h3 class="card-title">Accede a la Biblioteca!</h3>
</div>
<div class="form-group my-3">
<input type="email" class="form-control" name="email" placeholder="EMAIL">
</div>
<div class="form-group my-3">
<input type="password" class="form-control" name="password" placeholder="CONTRASEÑA">
</div>
<button type="submit" class="btn btn-primary mt-3 botones">Ingresar!</button>
</form>
<section class=" text-center container">
<div class="row mt-3">
<div class="divVolver">
<a th:href="@{/}" class="btn btn-secondary my-2 botonVolver botones">Volver</a>
</div>
</div>
</section>
</div>
<footer th:replace="/fragments/footer :: footer"></footer>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
</body>
</html>
|
//
// WebserviceManager.swift
// WhiteRabbitMachineTest
//
// Created by Midhun KM on 19/06/22.
//
import Foundation
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
typealias WebServiceCompletionHandler = (_ success: Bool, _ responseObject: AnyObject?, _ error: NSError?) -> Void
class WebserviceManager {
static let shared = WebserviceManager()
func requestArray<T: Mappable>(with url: String, method: HTTPMethod, parameter: [String: Any]?, header: HTTPHeaders?, mappableOf: [T].Type, completionHandler: @escaping WebServiceCompletionHandler) {
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 30
manager.session.configuration.timeoutIntervalForResource = 30
// Alamofire Request
manager.request(url, method: method, parameters: parameter, encoding: JSONEncoding.default, headers: header)
.validate()
.responseArray {(response: DataResponse<[T]>) in
switch response.result {
case .success(let successResult): // Success 200
if let item = successResult.toJSON() as? [NSDictionary] {
debugPrint(item)
}
completionHandler(true, successResult as AnyObject, nil)
case.failure(let error): // Failed
let networkError = NSError(domain: "Error", code: error._code, userInfo: nil)
completionHandler(false, nil, networkError)
}
}
}
}
|
package com.p4zd4n.bibliothecachudyana.controller;
import com.p4zd4n.bibliothecachudyana.entity.Book;
import com.p4zd4n.bibliothecachudyana.entity.Discount;
import com.p4zd4n.bibliothecachudyana.service.BookService;
import com.p4zd4n.bibliothecachudyana.service.DiscountService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
public class DiscountsController {
@Autowired
private DiscountService discountService;
@Autowired
private BookService bookService;
@GetMapping("/discounts")
public String displayDiscounts(Model model) {
List<Discount> discounts = discountService.findAll();
model.addAttribute("discounts", discounts);
return "/discounts/discounts";
}
@GetMapping("/add-discount")
public String displayAddDiscountForm(Model model) {
List<Book> books = bookService.findAll();
Discount discount = new Discount();
discount.setBook(new Book());
model.addAttribute("books", books);
model.addAttribute("discount", discount);
return "/discounts/save-discount";
}
@PostMapping("/save-discount")
public String saveDiscount(
@RequestParam(required = false) Integer id,
@RequestParam("bookId") Integer bookId,
@Valid @ModelAttribute("discount") Discount discount,
BindingResult bindingResult,
Model model
) {
if (bindingResult.hasErrors()) {
List<Book> books =
(id == null) ?
List.of(bookService.findById(bookId)) :
List.of(discountService.findById(id).getBook());
model.addAttribute("books", books);
model.addAttribute("bookId", bookId);
return "/discounts/save-discount";
}
Book book = bookService.findById(bookId);
discount.setBook(book);
if (id == null) {
discountService.save(discount);
} else {
discountService.update(discount);
}
return "redirect:/discounts";
}
@GetMapping("/update-discount")
public String showUpdateDiscountForm(@RequestParam("discountId") Integer id, Model model) {
Discount discount = discountService.findById(id);
model.addAttribute("discount", discount);
return "/discounts/save-discount";
}
@GetMapping("/delete-discount")
public String deleteDiscount(@RequestParam("discountId") Integer id) {
Discount discountToDelete = discountService.findById(id);
discountService.delete(discountToDelete);
return "redirect:/discounts";
}
}
|
#+STARTUP: showeverything logdone
#+options: num:nil
links related to this page:
* [[file:NSF Advanced Learning Technologies Grant Planning Page.org][NSF Advanced Learning Technologies Grant Planning Page]]
* [[file:NSF_ALT_2005_Grant_Proposal_Draft|original proposal draft.org][NSF_ALT_2005_Grant_Proposal_Draft|original proposal draft]]
* [[file:Collaborative_Version_Of_NSF_ALT_2005_Proposal_Introduction|proposal introduction for this version.org][Collaborative_Version_Of_NSF_ALT_2005_Proposal_Introduction|proposal introduction for this version]]
* Plan of Work
In this section we discuss specific work items for this grant. We give some ideas for starting
points and technical directions, which will have to be further investigated once the project
activities begin.
** Improved Deployability of Noosphere
Current efforts to extend Noosphere to other instances, establishing new virtual communities, have been
significantly retarded by the fact that it is difficult to deploy. The problem is that it was designed
around a single instance, the PlanetMath site. While it was quickly realized that the collaborative
digital library system concepts could be applied to many math and science digital library settings, the
project has thus far lacked the resources to appropriately package and generalize Noosphere.
Thus, we propose to make Noosphere easy to deploy, including the aspects of:
* packaging it for easy installation (rpms, debs, self-extracting installers)
* making it easy to configure (unified location configuration, "configurator" interfaces)
* making it easy to customize (uniform templating, proper stylesheeting, PlanetMath-instance-specific
things removed from the distribution)
* more complete documentation
* fewer dependencies
PlanetComputing will serve as a test case for the deployability of Noosphere.
** Improvements to Educational Metadata and Organization, and Community Support
Noosphere currently lacks support for standard learning object metadata fields, such as educational level,
difficulty, time to learn, and intended audience (e.g. teacher, student, practitioner, etc.). The value
of these fields is that they can be connected up to browsing, searching, and filtering services, saving
a lot of time for learners and preventing information overload. It should be obvious that, for example,
elementary school students should not have to see the same content as researchers. In this spirit, profiles
could be saved for each user which automate the filtering and in general give them a personalized "view"
of the digital library (as in CITIDEL).
In addition, while the MSC-based subject organization (currently built into PlanetMath and Noosphere) is
comprehensive and excellent for researchers, it is too advanced and daunting for students and not quite what
is needed for teachers. Other subject based organizations should be produced and mapped in, and Noosphere
should be more fully generalized to support any classification scheme (cite akrowne work on multischeming).
Content-based filtering should be combined with subject organization and attached to notification, to create
"filtering and routing" services that forward new content and activity in particular subject areas to interested
parties. This could be combined with forums which track subject hierarchies designed for different
subcommunities (for example, it should be easy to subscribe to a notification for a forum in high-school-level
geometry, or one for research-level topology).
Finally, a common complaint we have heard from users is that web-based forums are a pain to use because they
are not integrated with email. Currently, notification of activity on web-based virtual communities
typically goes one way: from the web site to email. But there is no reason why in principle it cannot
go both ways, with users gaining the ability to send replies or initial commentary from email to the web-based
system. This would allow the web-based virtual community to capitalize on the high priority today's internet users
place on email. We propose to add such a "bridge" system to Noosphere to help foster more collaboration
and communication with the community.
** Integrating Feedback for Quality Control
To assist in controlling the quality of artifacts in Noosphere, feedback consisting of user judgements
(implicit or explicit) should be integrated into the system. Aggregated, derived, or inferred metadata about
quality can be used not only for filtering, but to put pressure on content creators and other
contributors to improve where quality is lacking and direct their attention to where it is most
needed.
Candidates for solutions include:
* Explicit ratings of content artifacts (potentially including messages) used as the
basis of a collaborative filtering system (for example, Slashdot's karma system)
* A "card-based" system to determine which content to include or exclude by default
* Tracking of dispute and controversy, and alerting users to it
(cite some things on CF)
** Strengthening of Reputations
Integrating reputations explicitly into virtual communities creates an incentive to meet higher
quality standards and act with a greater sense of social responsibility.
Binding of creative activities to reputations allows for the
automatic integration of reputation metrics into quality control tasks, like filtering.
While Noosphere currently has scores and user identities (full anonymity is not allowed), the
reputation architecture could be improved. The current reputation system is based on the metric of /score/,
which is rigid and does not take into
account the actual value of contributed content. Rather, it assumes each type of object has
a fixed value. As anyone who has experienced teaching materials with different values can
attest to, this is good only as the roughest of approximations.
The utility of an automated reputations system is highlighted by the intuitive fact that
not all ratings should be equal. A rating of an object by a new user should not be counted the same as a
rating from a long-time, highly-reputable user. In the former case, we can make only a small
claim of certainty about the object's quality, while in the latter case, we can basically assume
the object has been moderated and approved by an expert.
A few important things could be done to enhance reputations and foster social responsibility:
* Start allowing, facilitating, and encouraging, the use of real-world identities.
* Replace the scoring system with a holistic one which integrates collective feedback about artifact quality
into reptuations, and reputations into artifact quality.
(cite some things on reputation systems and reputations in online communities, incl. kelly/sung/farnham paper)
** Improved Editorial Features
In a system in which informating is taking place, care must be taken to separate more ethereal
components of community interaction from those with lasting value. In other words, the "signal"
must be separated from the "noise". Deliberation which could be misleading or time-consuming to
sort through should be clearly separated. Along these lines, we propose to provide the following
system extensions:
* editorial discussion areas (as apart from generic discussion areas attached to each object, see
kuro5hin.org as an example)
* the ability for object owners to move messages to more appropriate areas (i.e. from main to "editorial")
* the ability for object owners to change superimposed objects from one type to another (i.e. message to
correction, message to request, etc.)
* the requests system, which currently requires a verification step by admins, could be more fully
distributed, with object owners performing verification of fulfilled requests.
(point out how other collaborative systems, such as mediawiki or scoop do some of this)
** Collaborative Content-Sharing Framework
Currently in the digital library world, generalized content sharing is performed using the Open Archives
Protocol for Metadata Harvesting (OAI-PMH). It has been a great success in allowing for the sharing
and syndication of library and digital library content, especially as evidenced by its use as the basis
of the core integration effort of the National STEM Digital Library (NSDL).
Yet, OAI-PMH was designed with the assumption that the records being shared are static and that each
sharing relationship is one-way, with a provider and a harvester. In the case that the harvester
periodically updates records, OAI-PMH still works, assuming the harvester expects mutable records. However,
in the case where the the sharing relationship is two-way (or bi-directional), with both participants
updating the same content base, OAI-PMH breaks down. In this situation-- where two productive digital
libraries are collaborating at the same authoritative level-- no solution exists to coordinate the production
or sharing activities.
We can no longer ignore this problem, as our effort concerns not only productive digital libraries, but
a situation wherein such digital libraries have the opportunity to share overlapping portions of content.
For example:
* PlanetMath should share CS theory entries with PlanetComputing (and vice versa)
* PlanetMath should share entries with ramifications for physics with PlanetPhysics (e.g. Green's
theorem, Stokes' law, Gauss' law, etc.) (and vice versa)
* PlanetComputing should share computational physics entries with PlanetPhysics (e.g. limits of
computing, quantum computing, etc.) (and vice versa)
It is key to note that all of these sites have differing-enough communities and focii that they are
better off managed and technically established as separate entities. Yet, it would be a great shame
if they could not easily share content and productive effort when appropriate.
To date, there have been efforts to share content with the PlanetMath instance of Noosphere, but
all of these efforts have been one-way:
* All of PlanetMath's content is harvested via OAI-PMH by NSDL
* The CS theory subset of PlanetMath's content is harvested via OAI-PMH by CITIDEL
* Wikipedia is selectively ingesting and porting PlanetMath's entire collection /manually/
In the last instance in particular, a bi-directional content sharing system would add great value.
Once Wikipedians have modified entries or portions thereof acquired from PlanetMath, these changes
should be candidates for application back at the source on PlanetMath. However, there is no framework
currently available to automate this process, so it is unclear whether the enhancements will ever make
it back to PlanetMath.
** User Studies
Much of PlanetMath's success thus far can be ascribed to its origins as a grassroots effort. That is, members of the user community took a part in most formative discussions about how to build PlanetMath (and Noosphere), as well as took a strong role in testing it through real-world use. However, this participatory design and development was naturally limited to a "colloquial" format, and could not extend much further than the circle of users the lead developers directly knew. Today, PlanetMath has over 10,000 registered users, and countless tens of thousands of readers.
To get a good reading of the needs of this vast user community, and even more importantly, who it is, real resources are needed and an explicit, formal study must be conducted. In addition, we propose to study learners and teachers in formal settings as well, to discover
the use of, the potential for, and utility of Noosphere-based systems in formal education
environments.
The user study will have many components, e.g., a survey-style study, an in-person
(or other synchronous, such as telephone-based) one-on-one interview study, and perhaps
a focus-group style study. Each type of interaction has the potential to yield unique insights, and multiple methods are needed to cover the various overlapping benefits and
drawbacks, given costs.
|
<?php
namespace App;
use App\Events\Exams\ExamDeleted;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Exam extends Model
{
protected $table = 'exams';
protected $fillable = [
'course_id',
'file_name',
'name',
'grade',
'points',
'path',
'date',
'type',
'slug',
'created_from',
'changed_from'
];
protected $dispatchesEvents = [
'deleted' => ExamDeleted::class,
];
public function course(){
return $this->belongsTo('App\Course');
}
use HasSlug;
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->usingSeparator( '-' )
->usingLanguage( 'sv' );
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
public static function updateAttributes( Request $request, $id )
{
$result = Verification::run( $request, 'exam' );
if( $result )
{
$exam = Exam::findOrFail( $id );
$exam->update( $request->except( '_token', '_method', 'recaptcha', 'type', 'created_from' ) );
return [ 'success', 'Ändring av uppgifterna lyckades, yippie!' ];
}
return [ 'error', 'Något gick fel när du ändrade uppgifterna, försök igen.' ];
}
public static function store( Request $request )
{
$course = Course::findOrFail( $request->course_id );
$path = Exam::getStoragePath( $request, $course );
$date = $request->date ? $request->date : date( 'Y-m-d' );
Exam::create( [
'name' => $request->name,
'grade' => $request->grade,
'points' => $request->points,
'file_name' => $request->exam->getClientOriginalName(),
'course_id' => $request->course_id,
'path' => $path,
'date' => $date,
'type' => $request->type,
'created_from' => $request->created_from,
] );
return [ 'success', 'Ny tenta uppladdad! Yay.' ];
}
public static function automaticStore( Request $request )
{
$fileName = $request->exam->getClientOriginalName();
// Splits the exam information from file type
$temp = explode( '.', $fileName );
$temp = explode( '-', $temp[ 0 ] );
$courseCode = $temp[ 0 ];
$year = $temp[ 1 ];
$month = $temp[ 2 ];
$day = $temp[ 3 ];
$result = Exam::getCourse( $courseCode );
if( $result[ 0 ] === 'error' )
{
return [ $result[ 0 ], $result[ 1 ] ];
}
$course = $result[ 2 ];
$path = Exam::getStoragePath( $request, $course );
$random = Exam::getRandomNumber();
$date = $year . '-' . $month . '-' . $day . ' 00:00:00';
Exam::create( [
'name' => 'Tenta ' . $random,
'file_name' => $fileName,
'course_id' => $course->id,
'path' => $path,
'date' => $date,
'type' => $request->type,
'created_from' => $request->created_from,
] );
return [ 'success', 'Tenta uppladdad, bra jobbat.' ];
}
public static function getCourse( $code )
{
$course = Course::where( 'code', $code )->first();
if( $course )
{
return [ 'success', 'Ny tenta uppladdad! Du kan nu titta och ladda ner den.', $course ];
}
return [ 'error', 'Ingen kurs matchar tentan. Vänligen lägg till kursen eller kontakta en föreningsansvarig för att lägga till kursen.' ];
}
public static function getStoragePath( $request, $course ) {
$temp = Exam::getRandomNumber();
$association = Association::findOrFail( $course->association_id );
$university = University::findOrFail( $association->university_id );
$exam = $request->exam->getClientOriginalName();
$filename = pathinfo($exam, PATHINFO_FILENAME);
$extension = pathinfo($exam, PATHINFO_EXTENSION);
$exam = Storage::putFileAs(
'exams/' . $university->slug . '/' . $association->slug . '/' . $course->code,
new File( $request->exam ), $filename . '-' . $temp . '.' . $extension
);
return $exam;
}
// Gets a random 4-digit number based on the current time minus a fixed date
public static function getRandomNumber()
{
$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$random = $now - $your_date;
$length = 4;
return substr( round( $random ), -$length, $length );
}
}
|
import ddf.minim.*; // import an external library
Minim minim; // this is the audio engine
AudioInput in; // this is the audio input
void setup()
{
size(200, 512);
minim = new Minim(this); // this starts the audio engine
// use the getLineIn method of the Minim object to get an AudioInput
in = minim.getLineIn();
}
void draw()
{
background(0);
fill(255);
noStroke();
float amp = 0.;
// draw the waveforms so we can see what we are monitoring
for(int i = 0; i < in.bufferSize() - 1; i++)
{
amp = amp + abs(in.left.get(i)); // add the abs value of the current sample to the amp
}
amp = amp / in.bufferSize();
rect(0, height-(height*amp), width, height*amp);
String theamp = nf(amp, 0, 2);
println(theamp);
}
void keyPressed()
{
}
|
[{invert}]
= "Continuous Everything"
== Livraison Continue
Continuous Delivery (CD)
== 🤔 Pourquoi la Livraison Continue ?
* Diminuer les risque liés au déploiement
* Permettre de récolter des retours utilisateurs plus souvent
* Rendre l'avancement visible par *tous*
[quote, Mary and Tom Poppendieck]
____
How long would it take to your organization to deploy a change that
involves just one single line of code?
____
== Qu'est ce que la Livraison Continue ?
* Suite logique de l'intégration continue:
** Chaque changement est *potentiellement* déployable en production
** Le déploiement peut donc être effectué à *tout* moment
[quote, Martin Fowler]
____
Your team prioritizes keeping the software *deployable* over working on new features
____
[{invert}]
== !
La livraison continue est l'exercice de **mettre à disposition automatiquement** le produit logiciel pour qu'il soit prêt à être déployé à tout moment.
== Livraison Continue avec GitHub Actions
== Prérequis: exécution conditionnelle des jobs
Il est possible d’exécuter conditionnellement un job ou un step à l'aide du mot clé `if` (link:https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsif[documentation de `if`,window="_blank"])
[source,yaml]
----
jobs:
release:
steps:
# Lance le step dire coucou uniquement si la branche est main.
- name: "Dire Coucou"
run: echo "coucou"
if: contains('refs/heads/main', github.ref)
----
== 🎓 Secret GitHub / DockerHub Token
* Reprenez (ou recréez) votre token DockerHub
** 💡 https://docs.docker.com/docker-hub/access-tokens/[Documentation "Manage access tokens",window="_blank"]
* Insérez le token DockerHub comme secret dans votre dépôt GitHub
** 💡 https://docs.github.com/en/actions/security-guides/encrypted-secrets#creating-encrypted-secrets-for-a-repository[Creating encrypted secrets for a repository,window="_blank"]
== 🎓 Livraison Continue sur le DockerHub
* *But :* Automatiser le déploiement de l'image dans le DockerHub lorsqu'un tag est poussé
* Changez votre workflow de CI de façon à ce que, sur un push de tag, les tâches suivantes soient effectuées :
** Comme avant: Build, Tests, Build Package
** SI c'est un tag, alors il faut pousser (et éventuellement reconstruire avec le bon nom) l'image sur le DockerHub
* 💡 Il va falloir adapter `make release` pour qu'il ne pousse plus de tag
* 💡 Utilisez les GitHub Action suivantes :
** https://github.com/marketplace/actions/docker-login[docker-login, window="_blank]
== ✅ Livraison Continue sur le DockerHub
[source,yml]
----
include::../code-samples/gh-actions/ci-docker-push-tag.yml[]
----
== Déploiement Continu
🇬🇧 Continuous Deployment / "CD"
== 🤔 Qu'est ce que le Déploiement Continu ?
* Version "avancée" de la livraison continue:
** Chaque changement *est* déployé en production, de manière *automatique*
== Continuous Delivery versus Deployment
image::continuous-depl-vs-delivery.jpg[caption=Continuous Delivery vs Deployment,width=700]
[.small]
Source : http://blog.crisp.se/2013/02/05/yassalsundman/continuous-delivery-vs-continuous-deployment
== Bénéfices du Déploiement Continu
* Rends triviale les procédures de mise en production et de rollback
** Encourage à mettre en production le plus souvent possible
** Encourage à faire des mises en production incrémentales
* Limite les risques d'erreur lors de la mise en production
* Fonctionne de 1 à 1000 serveurs et plus encore...
== 🎓 Déploiement Continu sur le DockerHub
* *But :* Déployer votre image `vehicle-server` continuellement sur le DockerHub
* Changez votre workflow de CI de façon à ce que, sur un push sur la branch `main`, les tâches suivantes soient effectuées :
** Comme avant: on joue le cycle de vie via make.
** SI c'est la branche `main`, alors il faut pousser l'image avec le tag `main` sur le DockerHub
** Conservez les autre cas avec les tags
== ✅ Déploiement Continu sur le DockerHub
[source,bash]
----
include::../code-samples/gh-actions/ci-docker-push-main.yml[]
----
== Checkpoint 🎯
* La livraison continue et le déploiement continu étendent les concepts du CI
* Les 2 sont automatisées, mais un être humain est nécessaire comme déclencheur pour la 1ère
* Le choix dépends des risques et de la "production"
* On a vu comment automatiser le déploiement dans GitHub Actions
** Conditions dans le workflow
** Gestion de secrets
|
import { StAvatar } from 'pages/ProfilePage/style';
import { fetchAvatarChange } from 'store/User/profile/actions';
import { useAppDispatch } from 'hooks/redux';
import Button from 'components/Button/Button';
import {
avatarStyles,
StAvatarContainer,
StAvatarInputWrapper,
StAvatarInput,
StAvatarLabel,
StAvatarError,
StButtonWrapper,
errorStyle,
} from './style';
import formatBytes from 'utils/formatBytes';
import { css } from 'styled-components';
import { useRef } from 'react';
import { errorReset } from 'store/User/userSlice';
import { userState } from 'hooks/userState';
import { FormError } from 'components/Form/style';
const MAX_FILE_SIZE = 1048576;
const buttontStyles = css`
font-weight: 700;
font-size: 25px;
line-height: 38px;
width: 372px;
`;
interface AvatarModal {
handleCloseModal: () => void;
image: string | undefined;
}
const AvatarModalWindow = ({ handleCloseModal, image }: AvatarModal) => {
const dispatch = useAppDispatch();
const { userError } = userState();
const errorCancel = () => {
if (userError) dispatch(errorReset());
};
const avatarErrorRef = useRef<HTMLDivElement>(null);
const userAvatarRef = useRef<HTMLDivElement>(null);
let avatarFile: File;
const onAvatarChange = (evt: React.ChangeEvent<HTMLInputElement>) => {
if (!evt.target.files) {
return;
}
avatarFile = evt.target.files[0];
const avatarError = avatarErrorRef.current;
const size = avatarFile.size;
if (avatarError) {
if (size > MAX_FILE_SIZE) {
const sizeKb = formatBytes(size);
avatarError.textContent = `размер файла ${sizeKb} допустимый не более 1Мб`;
return;
}
avatarError.textContent = '';
}
const avatar = userAvatarRef.current;
if (avatar) {
const reader = new FileReader();
reader.onload = (function (img) {
return function (event) {
img.style.backgroundImage = `url('${event.target?.result}')`;
};
})(avatar);
reader.readAsDataURL(avatarFile);
}
};
const onSubmit = (evt: React.SyntheticEvent<HTMLFormElement>) => {
evt.preventDefault();
if (!avatarFile) {
return;
}
const formData = new FormData();
formData.append('avatar', avatarFile);
dispatch(fetchAvatarChange(formData)).then(action => {
if ('error' in action && action.error) return;
errorCancel();
handleCloseModal();
});
};
return (
<StAvatarContainer onSubmit={onSubmit} onClick={errorCancel}>
<StAvatarInput
name="avatarFile"
type="file"
id="avatarFile"
onChange={onAvatarChange}
accept="image/png, image/gif, image/jpeg"
/>
<StAvatarInputWrapper>
<StAvatarLabel htmlFor="avatarFile">Выбрать файл</StAvatarLabel>
<StAvatarError ref={avatarErrorRef}></StAvatarError>
</StAvatarInputWrapper>
<StAvatar ref={userAvatarRef} css={avatarStyles} image={image} />
<StButtonWrapper>
<Button
css={buttontStyles}
type="submit"
text="Установить фотографию"
/>
<FormError css={errorStyle}>{userError}</FormError>
</StButtonWrapper>
</StAvatarContainer>
);
};
export default AvatarModalWindow;
|
import * as Device from "expo-device";
import * as Notifications from "expo-notifications";
import React, { useState, useEffect, useRef } from "react";
import {
Text,
View,
Button,
Platform,
StyleSheet,
TouchableHighlight,
Alert,
} from "react-native";
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
Notifications.setNotificationCategoryAsync("reply", [
{
buttonTitle: "Enviar 2623",
identifier: "reply",
options: {
isAuthenticationRequired: false,
opensAppToForeground: false,
isDestructive: true,
},
},
]);
export default function App() {
const [expoPushToken, setExpoPushToken] = useState("");
const [notification, setNotification] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();
useEffect(() => {
registerForPushNotificationsAsync().then((token) =>
setExpoPushToken(token)
);
// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
});
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
console.log("Response: ", response);
if (response.actionIdentifier === "reply") {
const { userToken } = response.notification.request.content.data;
send2623Notification(userToken);
}
});
return () => {
Notifications.removeNotificationSubscription(
notificationListener.current
);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
return (
<View style={styles.container}>
<TouchableHighlight
onPress={async () => {
await send223Notification(expoPushToken);
}}
>
<View style={styles.mainButton}>
<Text style={styles.buttonLabel}>Enviar um 223 {"<"}3</Text>
</View>
</TouchableHighlight>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "black",
alignItems: "center",
justifyContent: "space-around",
},
mainButton: {
width: 300,
height: 300,
backgroundColor: "red",
justifyContent: "center",
alignItems: "center",
borderRadius: 500,
},
buttonLabel: {
color: "white",
fontSize: 30,
},
});
// Can use this function below, OR use Expo's Push Notification Tool-> https://expo.dev/notifications
async function send223Notification(expoPushToken) {
const message = {
to: "ExponentPushToken[7hB04_IbU74xq3gefJ6183]",
sound: "default",
title: "Flah te enviou um 223",
body: "<3",
data: { userToken: expoPushToken },
priority: "high",
_displayInForeground: true,
_category: "reply",
categoryId: "reply",
};
try {
await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
Accept: "application/json",
"Accept-encoding": "gzip, deflate",
"Content-Type": "application/json",
},
body: JSON.stringify(message),
});
Alert.alert("Sucesso!", "O Laranjinha recebeu seu 223 <3");
} catch (err) {
Alert.alert(
"Oops",
"Ocorre um erro ao tentar enviar um 223 pro Laranjinha :("
);
console.log(err);
}
}
async function send2623Notification(userToken) {
console.log("sending 2623...");
const message = {
to: userToken,
sound: "default",
title: "Laranjinha respondeu!",
body: "2623 <3",
data: { userToken: userToken },
priority: "high",
_displayInForeground: true,
};
await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
Accept: "application/json",
"Accept-encoding": "gzip, deflate",
"Content-Type": "application/json",
},
body: JSON.stringify(message),
});
}
async function registerForPushNotificationsAsync() {
let token;
if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
return token;
}
|
import { useState } from "react";
import CoinItem from "./CoinItem";
const CoinSearch = ({ coins }) => {
const [searchText, setSearchText] = useState("");
return (
<div className="rounded-div m-4">
<div className="flex flex-col md:flex-row justify-between text-center py-4 md:text-right ">
<h1 className="text-2xl font-semibold my-2">Search Crypto</h1>
<form>
<input
onChange={(e) => setSearchText(e.target.value)}
className="bg-primary border border-input rounded-2xl shadow-xl w-full py-2 px-4"
type="text"
placeholder="Enter a coin"
/>
</form>
</div>
<table className="w-full text-center border-collapse">
<thead>
<tr className="border-b">
<th></th>
<th className="px-4">#</th>
<th className="text-left">Coin</th>
<th></th>
<th>Price</th>
<th>24h</th>
<th className="hidden md:table-cell">24h Volume</th>
<th className="hidden sm:table-cell">Mkt</th>
<th>1 Week Vol</th>
</tr>
</thead>
<tbody>
{coins
.filter((value) => {
if (searchText === "") {
return value;
} else if (
value.name.toLowerCase().includes(searchText.toLowerCase())
) {
return value;
}
})
.map((coin) => (
<CoinItem key={coin.id} coin={coin} />
))}
</tbody>
</table>
</div>
);
};
export default CoinSearch;
|
import { createContext, ReactNode, useContext, useState } from "react";
type Addon = {
scoops: {
[name: string]: number;
};
toppings: {
[name: string]: boolean;
};
};
export interface IAddonContext {
value: Addon;
setAddOnQuantity: (
addon: "scoops" | "toppings",
name: string,
value: number | boolean
) => void;
}
const AddonContext = createContext<IAddonContext | undefined>(undefined);
export const useAddonContext = () => {
const context = useContext(AddonContext);
if (context === undefined) {
throw new Error("useAddonContext must be used within AddonContextProvider");
}
return context;
};
export const AddonContextProvider = ({ children }: { children: ReactNode }) => {
const [context, setContext] = useState<Addon>({
scoops: {},
toppings: {},
});
const setAddOnQuantity = (
addon: "scoops" | "toppings",
name: string,
value: number | boolean
) => {
setContext((current) => ({
...current,
[addon]: {
...current[addon],
[name]: value,
},
}));
};
return (
<AddonContext.Provider value={{ value: context, setAddOnQuantity }}>
{children}
</AddonContext.Provider>
);
};
|
class Admin::CouponsController < AdminController
before_action :find_coupon, only: %i[show edit destroy]
def index
@pagy, @coupons = pagy(Coupon.search(params[:search], params[:sort], params[:direction]), items: 5)
end
def new
@coupon = Coupon.new
end
def create
result = CreateCoupon.call(coupon_params: coupon_params)
if result.success?
redirect_to admin_coupons_path, notice: 'Coupon was successfully created.'
else
@coupon = result.coupon
render :new
end
end
def show; end
def edit; end
def update
result = UpdateCoupon.call(coupon_params: coupon_params, id: params[:id])
if result.success?
redirect_to admin_coupons_path, notice: 'Coupon was successfully Updated.'
else
@coupon = result.coupon
render :edit
end
end
def destroy
@coupon.destroy
end
def export_csv
result = GenerateCouponCsv.call
respond_to do |format|
format.csv do
send_data result.csv_data, filename: 'coupon.csv'
end
end
end
private
def coupon_params
params.require(:coupon).permit(:name, :value, product_ids: [])
end
def find_coupon
@coupon = Coupon.find(params[:id])
end
end
|
from flask import Flask, request, jsonify, render_template
import uuid
from token_controller.token_generator import TokenCreator
from token_controller.token_autorization import Auth
from token_controller.token_decode import TokenVerify
from db_controller.db_connect import Database
import jwt
app = Flask(__name__)
db = Database('alt', 'postgres', 'admin', 'localhost')
@app.route('/')
def start():
return render_template("index.html")
# Definir registro de usuário
@app.route("/create", methods=["POST"])
def create_user():
user = request.headers.get("username")
password = request.headers.get("password")
id = uuid.uuid4()
permission = 0
token = TokenCreator(user, password, id, permission)
user_token = token.create()
db.add_user(user_token)
return jsonify({
'user_token': user_token
}),200
@app.route("/validate", methods=["GET"])
def validate_user():
user = request.headers.get("username")
password = request.headers.get("password")
validate = db.validate_user(user, password)
if validate["Code"] == 'E1' or validate["Code"] == 'E2':
return jsonify({
'Status': False
}), 401
generate_auth = Auth()
token_auth = generate_auth.authorization(validate["Token"])
return jsonify({
'Status': True,
'uid': validate["Token"],
'Token': token_auth
})
@app.route('/admin', methods=["GET"])
def admin_painel():
token = request.headers.get("Authorization")
if not token:
return jsonify({
'Message': 'Token ausente!'
}), 401
try:
payload = jwt.decode(token, key='exp_token', algorithms='HS256')
uid = payload["uid"]
validate = db.validate_permission(uid)
if validate["Code"] == 'E3':
return jsonify({
'Status': False
}), 401
return jsonify({
'Status': True,
'Permission': validate["Permission"]
}),200
except jwt.ExpiredSignatureError:
return jsonify({
'Error': 'Token expirado!'
}), 401
except jwt.InvalidSignatureError:
return jsonify({
'Error': 'Token inválido!'
}), 401
@app.route("/home", methods=["GET"])
def home():
token = request.headers.get("Authorization")
if not token:
return jsonify({
'Message': 'Token ausente!'
}), 401
try:
payload = jwt.decode(token, key='exp_token', algorithms='HS256')
return jsonify({
'Status': True,
'User': payload["uid"]
}), 200
except jwt.ExpiredSignatureError:
return jsonify({
'Error': 'Token expirado!'
}), 401
except jwt.InvalidSignatureError:
return jsonify({
'Error': 'Token inválido!'
}), 401
if __name__ == ("__main__"):
app.run(debug=True)
|
{% extends "cms/cms-base.html" %}
{% block title %}{{ course.name }}{% endblock %}
{% block content %}
<section>
<div class="container section-container admin">
<div class="row">
<div class="col s12">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div class="flash-messages">
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
{% if category=='warning' %}
<span class="fas fa-exclamation-triangle"></span>
{% elif category=='success' %}
<span class="fas fa-check-circle"></span>
{% endif %}
{{ message }}
</div>
{% endfor %}
</div>
{% endif %}
{% endwith %}
</div>
</div>
<h3 class="black-text section-header course-name-header">{{ course.name }}</h3>
<div class="course-actions">
<a href="{{ url_for('CMS.course_to_pdf', course_id=course.id, course_namestring='kurs_' + course.startDate.strftime('%d-%m-%Y')) }}" target="_blank">
<span class="fas fa-file-pdf grey-text text-darken-2"></span>
</a>
<a href="{{ url_for('CMS.update_course', course_id=course.id) }}">
<span class="fas fa-edit yellow-text text-darken-3"></span>
</a>
<a href="#delete-{{ course.id }}-modal" class="modal-trigger">
<span class="fas fa-trash red-text text-darken-3"></span>
</a>
</div>
<div class="row white course-info-container">
<div class="col s12 l4">
<h5 class="blue-text text-darken-3"><span class="far fa-calendar-alt"></span> Data rozpoczęcia:</h5>
<p>
{{ formatted_course_data.startDate }}, godz. {{ formatted_course_data.startTime }}
</p>
<h5 class="blue-text text-darken-3"><span class="far fa-calendar-alt"></span> Spotkanie organizacyjne:</h5>
<p>
{{ formatted_course_data.organizingMeetingDate }}, godz. {{ formatted_course_data.organizingMeetingTime }}
</p>
</div>
<div class="col s12 l4">
<h5 class="blue-text text-darken-3"><span class="fas fa-dollar-sign"></span> Koszt:</h5>
<p>
{{ course.cost }} zł
</p>
<h5 class="blue-text text-darken-3"><span class="fas fa-users"></span> Limit:</h5>
<p>
{% if course.studentLimit == 0 %}
nie podano
{% else %}
{{ course.studentLimit }}
{% endif %}
</p>
</div>
<div class="col s12 l4 amount-of-students-box">
<h4 class="blue-text text-darken-3">Liczba uczestników:</h4>
<span>{{ students.total }}</span>
</div>
<div class="col s12 course-additional-data">
<h5 class="blue-text text-darken-3"><span class="fas fa-info"></span> Dodatkowe informacje:</h5>
{% if not course.additionalData %}
<p>brak</p>
{% else %}
<p>{{ course.additionalData }}</p>
{% endif %}
</div>
</div>
<div class="row white course-students-container">
<h4>Uczestnicy</h4>
<div class="students-table-box">
<table>
<tr>
<th>Imię i nazwisko</th>
<th>Telefon</th>
<th>E-mail</th>
<th>Adres</th>
<th>Wiek</th>
</tr>
{% for student in students.items %}
<tr>
<td>{{ student.name }} {{ student.surname }}</td>
<td>{{ student.phone }}</td>
<td>{{ student.email }}</td>
<td>{{ student.address }}</td>
<td>{{ student.age }}</td>
</tr>
{% endfor %}
</table>
</div>
<div class="col s12 pagination-container">
<ul class="pagination">
{% if students.has_prev %}
<li class="waves-effect"><a href="{{ url_for('CMS.specific_course', course_id=course.id, strona=students.prev_num) }}"><i class="material-icons">chevron_left</i></a></li>
{% else %}
<li class="disabled"><a><i class="material-icons">chevron_left</i></a></li>
{% endif %}
{% for page_num in students.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
{% if page_num %}
{% if students.page == page_num %}
<li class="active blue darken-3">
<a href="{{ url_for('CMS.specific_course', course_id=course.id, strona=page_num) }}">{{ page_num }}</a>
</li>
{% else %}
<li class="waves-effect">
<a href="{{ url_for('CMS.specific_course', course_id=course.id, strona=page_num) }}">{{ page_num }}</a>
</li>
{% endif %}
{% else %}
...
{% endif %}
{% endfor %}
{% if students.has_next %}
<li class="waves-effect"><a href="{{ url_for('CMS.specific_course', course_id=course.id, strona=students.next_num) }}"><i class="material-icons">chevron_right</i></a></li>
{% else %}
<li class="disabled"><a><i class="material-icons">chevron_right</i></a></li>
{% endif %}
</ul>
</div>
</div>
</div>
</section>
<div id="delete-{{ course.id }}-modal" class="modal">
<div class="modal-content">
<h5>Czy na pewno chcesz usunąć kurs {{ course.name }} i wszystkich jego uczestników?</h5>
</div>
<div class="modal-footer">
<a href="#" class="modal-close waves-effect btn-flat">ANULUJ</a>
<form action="{{ url_for('CMS.delete_course', course_id=course.id) }}" method="POST" class="right">
<button type="submit" class="waves-effect btn-flat red darken-3 white-text">USUŃ</button>
</form>
</div>
</div>
{% endblock %}
{% block additionalScript %}
<script src="{{ url_for('static', filename='js/html2canvas.js') }}"></script>
<script src="{{ url_for('static', filename='js/all-courses.js') }}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.debug.js" integrity="sha384-THVO/sM0mFD9h7dfSndI6TS0PgAGavwKvB5hAxRRvc0o9cPLohB0wb/PTA7LdUHs" crossorigin="anonymous"></script>
{% endblock %}
|
Enter password: *****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 41
Server version: 5.5.62 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use nikhil;
Database changed
mysql> show tables;
+------------------+
| Tables_in_nikhil |
+------------------+
| employee |
| faculty |
| student |
+------------------+
3 rows in set (0.00 sec)
mysql> desc employee;
+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| employee_name | varchar(20) | YES | | NULL | |
| employee_id | int(10) | YES | | NULL | |
| mobile_no | int(10) | YES | | NULL | |
+---------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
mysql> desc faculty;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| faculty_name | varchar(20) | YES | | NULL | |
| faculty_id | int(10) | YES | | NULL | |
| mobile_no | int(10) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
mysql> desc student;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| student_name | varchar(20) | YES | | NULL | |
| roll_no | int(10) | YES | | NULL | |
| mobile_no | int(10) | YES | | NULL | |
| age | int(3) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.02 sec)
mysql> alter table student add primary key(mobile_no);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc student;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| student_name | varchar(20) | YES | | NULL | |
| roll_no | int(10) | YES | | NULL | |
| mobile_no | int(10) | NO | PRI | 0 | |
| age | int(3) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
mysql> alter table faculty add foreign key(mobile_no) references student(mobile_no);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc faculty;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| faculty_name | varchar(20) | YES | | NULL | |
| faculty_id | int(10) | YES | | NULL | |
| mobile_no | int(10) | YES | MUL | NULL | |
+--------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
mysql> alter table student add unique(mobile_no);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc student;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| student_name | varchar(20) | YES | | NULL | |
| roll_no | int(10) | YES | | NULL | |
| mobile_no | int(10) | NO | PRI | 0 | |
| age | int(3) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
mysql> alter table student add check(age>=15);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
|
package com.weather
import cats.effect.IO
import cats.effect.kernel.Resource
import cats.effect.testing.scalatest.AsyncIOSpec
import com.weather.http.{Fixtures, HttpApi}
import com.weather.module.{LiveWeatherForecast, LiveWeatherPoint}
import org.http4s.{Method, Request, Response}
import org.http4s.client.Client
import org.http4s.dsl.Http4sDsl
import org.http4s.implicits._
import org.scalatest.freespec.AsyncFreeSpec
import org.scalatest.matchers.must.Matchers
import fs2.Stream
import org.scalatest.matchers.should.Matchers.convertToAnyShouldWrapper
class AppSpec extends AsyncFreeSpec with AsyncIOSpec with Matchers with Http4sDsl[IO] with Fixtures{
def httpClient(body: String): Client[IO] = Client.apply[IO] { _ =>
Resource.eval(IO(Response[IO](body = Stream.emits(body.getBytes("UTF-8")))))
}
val clientResource = Resource.liftK(IO(httpClient("""{"body":"json"}""")))
"WeatherApp" - {
"unparsable client response to fetch point results in NotFound" in {
clientResource.use{ client =>
val program = for{
weatherPoint <- LiveWeatherPoint(client)
weatherForecast <- LiveWeatherForecast(client)
response <- HttpApi[IO](weatherPoint, weatherForecast).endpoints.orNotFound.run(
Request(method = Method.GET, uri = uri"/weather?lat=45&long=55")
)
} yield response
program.asserting(e => e.status shouldBe NotFound)
}
}
}
}
|
"use client";
import React, { useState, useEffect } from "react";
import Image from "next/image";
import OnTheRiseLogo from "../../../public/images/OnTheRiseLogo.png";
import { Allison, Advent_Pro } from "next/font/google";
import { map as _map } from "lodash";
import { getAuth, onAuthStateChanged } from "firebase/auth";
import { initializeApp } from 'firebase/app';
import dotenv from 'dotenv';
dotenv.config();
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_apiKey,
authDomain: process.env.NEXT_PUBLIC_authDomain,
projectId: process.env.NEXT_PUBLIC_projectId,
storageBucket: process.env.NEXT_PUBLIC_storageBucket,
messagingSenderId: process.env.NEXT_PUBLIC_messagingSenderId,
appId: process.env.NEXT_PUBLIC_appId,
measurementId: process.env.NEXT_PUBLIC_measurementId
};
// Initialize Firebase app
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
import {
AppBar,
Box,
Button,
IconButton,
Link,
Stack,
Toolbar,
Typography,
Drawer,
List,
ListItem,
} from "@mui/material";
import MenuIcon from "@mui/icons-material/Menu";
const allison = Allison({
weight: ["400"],
style: ["normal"],
display: "swap",
subsets: ["latin", "latin-ext", "vietnamese"],
});
const advent_pro = Advent_Pro({
weight: ["100", "200", "300", "400", "500", "600", "700", "800", "900"],
style: ["normal", "italic"],
display: "swap",
subsets: ["cyrillic", "cyrillic-ext", "greek", "latin", "latin-ext"],
});
const headerLink = [
{
href: "/about",
text: "About Us",
},
{
href: "/events",
text: "Events",
},
{
href: "/calendar",
text: "Calendar",
},
{
href: "/members",
text: "Members",
},
{
href: "/services",
text: "Services",
},
{
href: "/contact-us",
text: "Contact Us",
},
{
href: "/login",
text: "Log In",
},
];
const Header = () => {
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
const toggleDrawer = (open:any) => () => {
setIsDrawerOpen(open);
};
useEffect(()=>{
onAuthStateChanged(auth, (user) => {
if (user) {
const uid = user.uid;
console.log("uid", uid)
} else {
console.log("user is logged out")
}
});
}, [])
return (
<>
<AppBar
position="sticky"
sx={{
background: "#131310",
height: ["50px", "65px", "75px"],
flexDirection: "row",
alignItems: "center",
zIndex: "1000",
}}
>
<Toolbar>
<IconButton
size="large"
edge="start"
color="inherit"
onClick={toggleDrawer(true)}
sx={{
marginRight: "2",
display: ["flex", "none"], // Show only on smaller screens
}}
>
<MenuIcon />
</IconButton>
<div
style={{
display: "flex",
alignItems: "center",
}}
>
<Button href="/">
<Image
src={OnTheRiseLogo}
alt=""
style={{
width: "73px",
height: "73px",
objectFit: "fill",
margin: "20px",
}}
/>
</Button>
<Typography
component={Link}
href="/"
sx={{
color: "#FFFFFF",
fontSize: "25px",
fontFamily: allison.style.fontFamily,
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
On The Rise
</Typography>
</div>
</Toolbar>
</AppBar>
<Drawer anchor="left" open={isDrawerOpen} onClose={toggleDrawer(false)}>
<List>
{_map(headerLink, (linkInfo, index) => (
<ListItem key={index}>
<Link
href={linkInfo.href}
color="inherit"
sx={{ textDecoration: "none", color: "#000000" }}
onClick={toggleDrawer(false)}
>
{linkInfo.text}
</Link>
</ListItem>
))}
</List>
</Drawer>
<Stack
sx={{
background: "#1B1B1B",
height: ["50px", "65px", "75px"],
position: "sticky",
justifyContent: "center",
alignItems: "center",
flexDirection: "row",
zIndex: "1000",
top: "0",
}}
>
<Stack
sx={{
flexDirection: "row",
color: "#DAA520",
fontSize: ["14px", "16px", "18px"],
fontWeight: "normal",
textAlign: "center",
justifyContent: "center",
display: ["none", "flex"],
}}
>
{_map(headerLink, (linkInfo, index) =>
linkInfo.href === "/login" ? (
<Link
key={linkInfo.href}
href={linkInfo.href}
sx={{
mx: ["50px", "50px"],
marginTop: ["-5px", "-5px"],
textDecoration: "none",
backgroundColor: "rgba(19, 19, 16, 0.9)",
width: "75px",
height: "15px",
borderRadius: "5px",
padding: "10px 10px",
color: "#FFFFFF",
transition: "background-color 0.3s, transform 0.3s",
":hover": {
backgroundColor: "#FFD700",
},
}}
>
{linkInfo.text}
</Link>
) : linkInfo.text === "Log In" ? (
<Link
key={linkInfo.href}
href={linkInfo.href}
sx={{
mx: ["15px", "5px"],
position: "sticky",
textDecoration: "none",
color: "#FFFFFF",
transition: "color 0.3s ease, transform 0.5s ease",
fontFamily: advent_pro.style.fontFamily,
fontSize: "2px",
":hover": {
color: "#FFD700",
transform: "scale(1.1)",
},
}}
>
{linkInfo.text}
</Link>
) : (
<Link
key={linkInfo.href}
href={linkInfo.href}
sx={{
mx: ["50px", "50px"],
marginTop: "3px",
textDecoration: "none",
color: "#FFFFFF",
transition: "color 0.3s ease",
":hover": {
color: "#FFD700",
},
}}
>
{linkInfo.text}
</Link>
)
)}
<div style={{ flex: 1 }}></div>
</Stack>
</Stack>
</>
);
};
export default Header;
|
import 'package:flutter/material.dart';
import 'package:appcore/components/text_field_container.dart';
import 'package:appcore/constants.dart';
class RoundedPasswordField extends StatelessWidget {
final ValueChanged<String> onChanged;
const RoundedPasswordField({
Key? key,
required this.onChanged,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextFieldContainer(
child: TextField(
obscureText: true,
onChanged: onChanged,
cursorColor: kPrimaryColor,
decoration: const InputDecoration(
hintText: "Contraseña",
icon: Icon(
Icons.lock,
color: Colors.black,
),
suffixIcon: Icon(
Icons.visibility,
color: Colors.white,
),
border: InputBorder.none,
),
),
);
}
}
|
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "campaignDateContainer", "campaignDate", "repeatInteralContainer", "repeatInteral", "applicabilityField", "sourceCheckbox", "destCheckbox", "dueAt"]
initialize() {
this.highlight_due_tasks()
}
toggleCampaign(event) {
if (event.target.value == "campaign") {
this.enableCampaignFields()
this.disableRecurringFields()
} else if (event.target.value == "recurring") {
this.enableRecurringFields()
this.disableCampaignFields()
}
}
enableCampaignFields() {
for (var field of this.applicabilityFieldTargets) {
field.classList.remove("transparent")
}
this.campaignDateContainerTarget.classList.remove("hidden")
this.campaignDateTarget.required = true
}
disableCampaignFields() {
for (var field of this.applicabilityFieldTargets) {
field.classList.add("transparent")
}
this.campaignDateContainerTarget.classList.add("hidden")
this.campaignDateTarget.required = false
}
enableRecurringFields() {
this.repeatInteralContainerTarget.classList.remove("hidden")
this.repeatInteralTarget.required = true
}
disableRecurringFields() {
this.repeatInteralContainerTarget.classList.add("hidden")
this.repeatInteralTarget.required = false
}
toggleCheckboxes() {
var isChecked = this.sourceCheckboxTarget.checked // Returns true or false
this.updateCheckboxes(this.destCheckboxTargets, isChecked)
}
updateCheckboxes(destCheckboxs, value) {
for (var destCheckbox of destCheckboxs) {
destCheckbox.checked = value;
}
}
highlight_due_tasks() {
var todayDate = moment.utc(moment().format('YYYY-MM-DD')).valueOf();
for (var dueAt of this.dueAtTargets) {
if(dueAt.dataset.recurring == 'recurring'){
let due_value = dueAt.dataset.due.length > 0 ? moment.utc(dueAt.dataset.due).valueOf() : ''
if( due_value && due_value < todayDate ) {
dueAt.classList.add("error")
} else if( due_value && due_value == todayDate ) {
dueAt.classList.add("warn")
}
}
}
}
}
|
const mongoose = require('mongoose');
const validator = require('validator');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'A user must have a name'],
unique: true,
trim: true,
minlength: [10, 'A user name must have more than or equal 10 characters'],
validate: [validator.isAlpha, 'A user name must only contain characters'],
},
email: {
type: String,
required: [true, 'A user must have an email'],
unique: true,
trim: true,
lowercase: true,
validate: [validator.isEmail, 'Please provide a valid email'],
},
photo: {
type: String,
required: [true, 'A user must have a cover image'],
},
password: {
type: String,
required: [true, 'A user must have a password'],
unique: true,
trim: true,
maxlength: [40, 'A user name must have less than or equal 40 characters'],
minlength: [8, 'A user name must have more than or equal 8 characters'],
},
passwordConfirm: {
type: String,
required: [true, 'password must be the same'],
unique: true,
trim: true,
maxlength: [40, 'A user name must have less than or equal 40 characters'],
minlength: [8, 'A user name must have more than or equal 8 characters'],
},
});
const User = mongoose.model('User', userSchema);
module.exports = User;
|
import {
CreationOptional,
DataTypes,
InferCreationAttributes,
InferAttributes,
Model,
Sequelize
} from 'sequelize'
export class MBelanja extends Model<
InferAttributes<MBelanja>,
InferCreationAttributes<MBelanja>
> {
declare id_belanja: CreationOptional<number>
declare tanggal_belanja: string | null
declare nama_item: string
declare id_item: number
declare harga_item: number | null
declare tempat_belanja: string | null
declare catatan: string | null
declare harga_jual: number | null
declare jumlah_pcs: number | null
declare createdAt: CreationOptional<Date>
declare updatedAt: CreationOptional<Date>
static initModel(sequelize: Sequelize): typeof MBelanja {
MBelanja.init({
id_belanja: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
tanggal_belanja: {
type: DataTypes.DATEONLY,
defaultValue: DataTypes.NOW
},
nama_item: {
type: DataTypes.STRING(50),
allowNull: false
},
id_item: {
type: DataTypes.INTEGER,
allowNull: false
},
harga_item: {
type: DataTypes.INTEGER
},
tempat_belanja: {
type: DataTypes.STRING(50)
},
catatan: {
type: DataTypes.STRING(50)
},
harga_jual: {
type: DataTypes.INTEGER
},
jumlah_pcs: {
type: DataTypes.INTEGER
},
createdAt: {
type: DataTypes.DATE
},
updatedAt: {
type: DataTypes.DATE
}
}, {
tableName: "belanja",
sequelize
})
return MBelanja
}
}
|
# problems.py - plugin to list problems
#
# Copyright (C) 1998, 1999 Albert Hopkins (marduk)
# Copyright (C) 2002 Mike W. Meyer
# Copyright (C) 2005, 2006 Arthur de Jong
#
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
#
# The files produced as output from the software do not automatically fall
# under the copyright of the software, unless explicitly stated otherwise.
"""Present an overview of all encountered problems per author."""
__title__ = 'problems by author'
__author__ = 'Arthur de Jong'
__outputfile__ = 'problems.html'
import plugins
import urllib
def generate(site):
"""Output the overview of problems to the given file descriptor."""
# make a list of problems per author
problem_db = {}
for link in site.linkMap.values():
# skip external pages
if not link.isinternal or len(link.pageproblems) == 0:
continue
# make a normal name for the author
if link.author:
author = link.author.strip()
else:
author = unicode('Unknown')
# store the problem
if problem_db.has_key(author):
problem_db[author].append(link)
else:
problem_db[author] = [link]
fp = plugins.open_html(plugins.problems, site)
if not problem_db:
fp.write(
' <p class="description">\n'
' No problems were found on this site, hurray.\n'
' </p>\n' )
plugins.close_html(fp)
return
# print description
fp.write(
' <p class="description">\n'
' This is an overview of all the problems on the site, grouped by\n'
' author.\n'
' </p>\n' )
# get a list of authors
authors = problem_db.keys()
authors.sort()
# generate short list of authors
if len(authors) > 1:
fp.write(' <ul class="authorlist">\n')
for author in authors:
fp.write(
' <li><a href="#%(authorref)s">Author: %(author)s</a></li>\n'
% { 'authorref': urllib.quote(author,''),
'author': plugins.htmlescape(author) })
fp.write(' </ul>\n')
# generate problem report
fp.write(' <ul>\n')
for author in authors:
fp.write(
' <li>\n'
' <a name="%(authorref)s">Author: %(author)s</a>\n'
' <ul>\n'
% { 'authorref': urllib.quote(author,''),
'author': plugins.htmlescape(author) })
# sort pages by url
problem_db[author].sort(lambda a, b: cmp(a.url, b.url))
# list problems for this author
for link in problem_db[author]:
# present the links
fp.write(
' <li>\n'
' %(link)s\n'
' <ul class="problems">\n'
% { 'link': plugins.make_link(link) })
# sort problems by name
link.pageproblems.sort()
# list the problems
for problem in link.pageproblems:
fp.write(
' <li>%(problem)s</li>\n'
% { 'problem': plugins.htmlescape(problem) })
# end the list item
fp.write(
' </ul>\n'
' </li>\n' )
fp.write(
' </ul>\n'
' </li>\n' )
fp.write(
' </ul>\n' )
plugins.close_html(fp)
|
/*
* Copyright 2011,2012 Evgeniy Khilkevitch
*
* This file is part of scigraphics.
*
* Scigraphics 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.
*
* Scigraphics 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 scigraphics. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "scigraphics/numbers.h"
#include "scigraphics/geometry.h"
#include <string>
#include <vector>
#include <utility>
namespace scigraphics
{
class lineStyle;
class brushStyle;
class textStyle;
class color;
class drawer
{
protected:
static size_t numOfLinesInString( const std::string &String );
public:
virtual wcoord width() const = 0;
virtual wcoord height() const = 0;
wrectangle plotRectangle() const;
virtual void eraseAll();
virtual void setLineStyle( const lineStyle &Style ) = 0;
virtual void setBrushStyle( const brushStyle &Style ) = 0;
virtual void setTextStyle( const textStyle &Style ) = 0;
virtual void drawLine( const wpoint &A, const wpoint &B ) = 0;
virtual void drawPolyline( const std::vector<wpoint> &Points );
virtual void drawRectangle( const wrectangle& Rectangle ) = 0;
virtual void drawPolygon( const std::vector<wpoint> &Points ) = 0;
virtual void drawText( const std::string &Text, const wrectangle& Rectangle, double RotAngle = 0 ) = 0;
virtual void eraseRectangle( const wrectangle& Rectangle );
virtual void flush();
virtual std::pair<wcoord,wcoord> textWidthHeight( const std::string &Text, const textStyle &Style ) = 0;
virtual ~drawer();
};
}
|
import { fetchMovieReviews } from "API";
import HandleError from "components/HandleError/HandleError";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Item, List, Wrapper, Author, Text } from "./Reviews.styled";
const Reviews = () => {
const { movieId } = useParams();
const [reviews, setReviews] = useState([]);
const [error, setError] = useState(false);
useEffect(() => {
setError(false);
const fetchReviews = async () => {
try {
const response = await fetchMovieReviews(movieId);
if (response.length === 0) setError(true);
setReviews(response);
} catch (error) {
setError(true);
console.error(error.message);
}
}
fetchReviews();
}, [movieId])
return (<Wrapper>
{reviews.length > 0 && (<List>
{reviews.map(({ id, author, content }) => {
return (<Item key={id}>
<Author>Author: {author}</Author>
<Text>{ content}</Text>
</Item>)})}
</List>)}
{error && <HandleError title="Sorry, there are no reviews for this movie"/>}
</Wrapper>)
}
export default Reviews;
|
import React, { ReactElement, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { hot } from 'react-hot-loader/root';
import HelloWorldSettings from './HelloWorldSettings';
interface Props {
settingsElement: HTMLElement;
createOrder: (side: 'BUY' | 'SELL', quantity: number) => void;
listenSettingsSave: (handler: () => void) => (() => void)
listenSettingsCancel: (handler: () => void) => (() => void)
}
const HelloWorld = ({
settingsElement, createOrder, listenSettingsSave, listenSettingsCancel,
}: Props): ReactElement => {
const [qty, setQty] = useState('0');
const [btnSize, setBtnSize] = useState(localStorage.helloWorldReactButonSize as '' | 'sm' | 'lg' ?? '');
useEffect(() => listenSettingsSave(() => {
// save
localStorage.helloWorldReactButonSize = btnSize;
}));
useEffect(() => listenSettingsCancel(() => {
// reset
setBtnSize(localStorage.helloWorldReactButonSize as '' | 'sm' | 'lg');
}));
return (
<>
{createPortal((
<HelloWorldSettings btnSize={btnSize} setBtnSize={setBtnSize} />
), settingsElement)}
<div className="row">
<div className="col-12 mb-1">
{/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
<label htmlFor="hello_world_react_qty" className="form-label">Quantity</label>
<input
id="hello_world_react_qty"
type="text"
placeholder="Quantity"
className="form-control"
value={qty}
onChange={({ target }) => setQty(target.value)}
/>
</div>
<div className="col-6 d-grid">
<button
type="button"
className={`btn btn-success mt-3 btn-block${btnSize ? ` btn-${btnSize}` : ''}`}
disabled={!+qty}
onClick={() => {
if (+qty) createOrder('BUY', +qty);
}}
>
Buy
</button>
</div>
<div className="col-6 d-grid">
<button
type="button"
className={`btn btn-sell mt-3 btn-block${btnSize ? ` btn-${btnSize}` : ''}`}
disabled={!+qty}
onClick={() => {
if (+qty) createOrder('SELL', +qty);
}}
>
Sell
</button>
</div>
</div>
</>
);
};
export default hot(HelloWorld);
|
<html>
<head>
<title>FastTyping</title>
<script src="words.js" charset="UTF-8"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="main-wrapper">
<div class="centered">
<div class="word-table">
<div>
<span class="word" id="word-1"></span>
<span class="word" id="word-2"></span>
<span class="word" id="word-3"></span>
<span class="word" id="word-4"></span>
<span class="word" id="word-5"></span>
<span class="word" id="word-6"></span>
</div>
<div>
<span class="word" id="word-7"></span>
<span class="word" id="word-8"></span>
<span class="word" id="word-9"></span>
<span class="word" id="word-10"></span>
<span class="word" id="word-11"></span>
<span class="word" id="word-12"></span>
</div>
<div>
<span class="word" id="word-13"></span>
<span class="word" id="word-14"></span>
<span class="word" id="word-15"></span>
<span class="word" id="word-16"></span>
<span class="word" id="word-17"></span>
<span class="word" id="word-18"></span>
</div>
</div>
<input type="text" placeholder="Type here to start" autofocus="autofocus" id="input" spellcheck="false"></input>
<div class="textbox">
<div id="countdown">60</div>
<select id="language" onchange="changeLanguage()">
<option value="finnish">Finnish</option>
<option value="english">English</option>
</select>
</div>
<div id="displayWhenDone">
<div id="feedback"></div>
<button onclick="window.location.reload();">Restart</button>
</div>
</div>
</div>
</body>
</html>
<script>
const outputText = document.getElementById("output");
const inputText = document.getElementById("input");
const feedback = document.getElementById("feedback");
const countdown = document.getElementById("countdown");
const languageSelect = document.getElementById("language");
// generate new array of 18 words
newWordArray = (arr) => {
let wordsArr = new Array(18);
for (let i = 0; i < 18; i++) {
// new random word
wordsArr[i] = arr[Math.floor(Math.random() * arr.length)];
}
return wordsArr;
}
seedTableWithWords = (arr) => {
for (let i = 0; i < arr.length; i++) {
document.getElementById("word-" + (i + 1)).innerText = arr[i];
}
}
// generate array of words, and seed the table with them (using method [getWords] from external js-file)
let wordlist = wordsFin;
let currentWords = newWordArray(wordlist);
changeLanguage = () => {
const selected = languageSelect.value;
switch(selected) {
case "finnish":
wordlist = wordsFin;
break;
case "english":
wordlist = wordsEng;
break;
}
newWordSet();
}
seedTableWithWords(currentWords);
// for calculation & statistics
let correctWords = 0;
let wrongWords = 0;
let correctChars = 0;
let wrongChars = 0;
let wordsPerMinute = 0;
let nthWord = 0;
const currentWordBackground = "#d5d5d5";
// first word settings
let currentWord = currentWords[nthWord];
nthWord++;
document.getElementById("word-1").style.background = currentWordBackground;
// timer
let seconds = 60;
let timerStarted = false;
var timerFunction = setTimeout(function(){
setInterval(function(){
// run timer until timer reaches zero
if (timerStarted && seconds > 0) {
seconds = seconds - 1;
countdown.innerText = seconds;
inputText.placeholder = "";
}
// when test is over
if (seconds == 0) {
clearInterval(timerFunction);
countdown.style.display = "none";
// stop input
inputText.readOnly = true;
inputText.style.display = "none";
// show statistics
feedback.innerHTML = "WPM: " + countWPM(correctChars)
+ "<br>accuracy: " + accuracy() + "%"
+ "<br><br>correct characters: " + correctChars
+ "<br>wrong characters: " + wrongChars
+ "<br><br>correct words: " + correctWords
+ "<br>wrong words: " + wrongWords;
document.getElementById("displayWhenDone").style.display = "flex";
}
}, 1000);
}, 1000);
// handle key presses
inputText.addEventListener('keyup', (e) => {
// timer starts when typing starts
if (inputText.value != "" && seconds == 60) {
timerStarted = true;
// hide language selection
languageSelect.style.display = "none";
}
// when space is pressed, check if typed word is correct
if (e.keyCode == 32) {
let typedWord = inputText.value;
typedWord = typedWord.trim();
inputText.value = "";
if (typedWord === currentWord) { // if word is correct
correctChars += typedWord.length + 1; // + space press will count as correct char
correctWords++;
console.log("correct! correct words: " + correctWords + "\tcorrect chars: " + correctChars);
// color word green
document.getElementById("word-" + (nthWord)).style.background = "#a0ffa0";
} else { // if word is wrong
wrongChars += typedWord.length + 1 ;
wrongWords++;
console.log("wrong! wrong words: " + wrongWords + "\twrong chars: " + wrongChars);
// color word red
document.getElementById("word-" + (nthWord)).style.background = "#ffa0a0";
}
newWord();
} else {
// check if substring is correct: if not, color text background to red
inputTemp = inputText.value;
inputTempSub = inputTemp.substr(0, inputTemp.length - 1);
outputSub = currentWord.substr(0, inputTemp.length);
inputLastChar = inputTemp[inputTemp.length - 1];
if (inputTemp == outputSub || (inputLastChar == " " && inputTempSub == outputSub)) {
document.getElementById("word-" + (nthWord)).style.background = currentWordBackground;
} else {
document.getElementById("word-" + (nthWord)).style.background = "#ffa0a0";
}
}
});
// calculate words per minute by international standard
countWPM = (chars) => {
if (chars == 0) {
return 0;
}
return (chars / 5).toFixed(0);
}
// calculate accuracy stat
accuracy = () => {
let acc = correctChars/(correctChars + wrongChars);
acc *= 100;
acc = acc.toFixed(1);
// return acc if it is number, else 0
return (acc === NaN ? 0 : acc);
}
clearTableStyles = () => {
for (let i = 1; i <= currentWords.length; i++) {
document.getElementById("word-" + (i)).style.background = "none";
}
// also highlight first word
document.getElementById("word-1").style.background = currentWordBackground;
}
// generate new wordset and display it on page
newWordSet = () => {
clearTableStyles();
currentWords = newWordArray(wordlist);
seedTableWithWords(currentWords);
nthWord = 0;
currentWord = currentWords[0];
nthWord++;
}
newWord = () => {
if (nthWord < currentWords.length) {
currentWord = currentWords[nthWord];
nthWord++;
document.getElementById("word-" + nthWord).style.background = currentWordBackground;
} else {
newWordSet();
}
}
</script>
|
import React, { useContext } from "react";
import CustomDropdown from "../CustomDropdown";
import { AppContext } from "../../providers/context";
interface IDateRange {
value: string;
}
const DateRange: React.FC<IDateRange> = () => {
const { dispatch, state } = useContext(AppContext);
const handleClick = (value: { label: string; value: string }) => {
if (dispatch) {
dispatch({ type: "setDateRange", newState: value });
}
};
const options = [
{
label: "Today",
value: "daily",
},
{
label: "This week",
value: "weekly",
},
{
label: "This month",
value: "monthly",
},
];
return (
<CustomDropdown
options={options}
label="Date range"
value={state?.dateRange?.label}
handleClick={(value: { label: string; value: string }) => {
handleClick(value);
}}
/>
);
};
export default DateRange;
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from glob import glob
import cv2
def ann(x_train,y_train,x_test,y_test,settings='manual',input_dims=1,nourons=[],activations=[],optimizer='adams',loss='sparse_categorical_crossentropy',epochs=30,batch_size=32,resize=False,size=()):
from tensorflow.keras import models,layers
from tensorflow.keras.layers import Dense
x_train,x_test=x_train/255,x_test/255
if resize:
x_train = np.reshape(x_train, size)
x_test = np.reshape(x_test, size)
model=models.Sequential()
for n in nourons:
if nourons.index(n) == 0:
model.add(Dense(units=n,activation=activations[nourons.index(n)],input_dim=input_dims))
else:
model.add(Dense(n,activation=activations[nourons.index(n)]))
model.compile(optimizer=optimizer,
loss=loss,
metrics=['accuracy'])
h=model.fit(x_train,y_train,epochs=epochs,batch_size=batch_size,validation_data=(x_test,y_test))
return (model,h)
def read_dataset(add='',labels=[],need=0,ilabel=[],asize=(250,250)):
#labels=[1,0]
images=[]
imlabels=[]
c=1
#add="D:/robotic/Python/hotdog-nothotdog/hotdog-nothotdog/train/"
for a in labels:
if need:
z=ilabel[labels.index(a)]
else:
z=str(a)
print("\nreading",z)
for image in glob(add+z+"//*"):
print('.',end='')
img=cv2.imread(image)
img=cv2.resize(img, asize)
img=img.flatten()
imlabels.append(a)
images.append(img)
if(c==4000):
print('\nalmost done\n')
c+=1
images=np.array(images)
imlabels=np.array(imlabels)
print('\nDetails:')
print('shape:',images.shape)
print('pixel colors:',images.shape[1]/(asize[0]*asize[1]))
if images.shape[1]/(asize[0]*asize[1]):
print('Colored pictures')
else:
print('gray scale or binary images')
print(images.shape[0],'pictures')
print('size of images:',asize)
print('Flattened: YES')
return (images,imlabels)
def fitmodel(images,imlabels,algorithm,k=0):
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(images,imlabels,test_size=0.2,shuffle=1)
if(algorithm=='svm' or algorithm=='SVM'):
from sklearn.svm import SVC
model=SVC()
model.fit(x_train,y_train)
elif(algorithm=='logistic regression' or algorithm=='Linear Regression'):
from sklearn.linear_model import LogisticRegression
model=LogisticRegression()
model.fit(x_train, y_train)
elif(algorithm=='knn'):
from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier(n_neighbors=1)
model.fit(x_train,y_train)
else:
print("not available yet")
return (model,x_test,y_test)
def cheatsheet(func):
if func=="read_dataset":
print("read_dataset(add='',labels=[],need=0,ilabel=[],asize=(250,250))")
print("Used to read picture dataset and preprocess")
print("add: adress of the dataset")
print("labels: list of labels(if it is in string format turn it into num e.g: ['hello','goodbye'] > [1,0])")
print('need: if the folder adress is not equal to labels')
print('ilabel: the adress of the file(if the folder adress is not equal to labels)')
print('asize: the size of the images you want to have')
print('it will return a tuple containing the preprocessed images and labels')
elif func=='fitmodel':
print('images: the images you want to fit with the model')
print('imlabel: the labels you want to fit with the model')
print('algorithm: the algorithm you want to use e.g: knn or svm')
print('k for knn')
print('it will return the model(that you can predict with model.predict() and have the score with model.score())')
elif func=='k_recommendation':
print('images:the images you want to fit with the model')
print('imlabel: the labels you want to fit with the model')
print('returns best k for knn model')
else:
print('images:the images you want to fit and predict')
print('eps and m for epsilon and min sample of dbscan')
def k_recommendation(images,imlabels):
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(images,imlabels,test_size=0.2,shuffle=1)
from sklearn.neighbors import KNeighborsClassifier
error_rate = []
for i in range(0,50):
knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(x_train,y_train)
pred = knn.predict(x_test)
error_rate.append(np.mean(pred != y_test))
return error_rate.index(min(error_rate))
def dbscan(images,eps=29,m=3):
from sklearn.cluster import DBSCAN
db=DBSCAN(eps=eps,min_samples= m)
return db.fit_predict(images)
def save(model,name='model'):
from pickle import dump
dump(model,'O2'+name)
|
/* eslint-disable simple-import-sort/imports */
import 'jest-styled-components';
import { cleanup } from '@testing-library/react';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import { configure } from 'enzyme';
import { SessionStorage } from '../../domain/storage/SessionStorage';
configure({ adapter: new Adapter() });
afterEach(cleanup);
beforeEach(() => {
global.sessionStorage.clear();
});
describe('Lokal Storage', () => {
it('Session Storage class should persist data to session storage', () => {
const sessionStorage = new SessionStorage();
sessionStorage.setItem('roomId', 'ABCD');
expect(global.sessionStorage.getItem('roomId')).toBe('ABCD');
});
it('Session Storage class should remove data from session storage', () => {
global.sessionStorage.setItem('roomId', 'ABCD');
const sessionStorage = new SessionStorage();
sessionStorage.removeItem('roomId');
expect(global.sessionStorage.getItem('roomId')).toBe(null);
});
it('Session Storage class should retrieve data from session storage', () => {
global.sessionStorage.setItem('roomId', 'ABCD');
const sessionStorage = new SessionStorage();
expect(sessionStorage.getItem('roomId')).toBe('ABCD');
});
});
|
<html>
<head>
<title>Object Detection</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.js"></script>
<script src="https://unpkg.com/ml5@latest/dist/ml5.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body background="gar.png">
<center>
<h1 class="btn btn-info heading">Object Detection</h1>
<h3 id="status" class="btn btn-danger"></h3>
<h3 id="number_of_objects" class="btn btn-warning"></h3>
</center>
<script src="main.js">
function preload() {
img = loadImage('gar.png');
}
function setup() {
canvas = createCanvas(380, 380);
canvas.center();
video = createCapture(VIDEO);
video.size(380, 380);
video.hide();
objectDetector = ml5.objectDetector('cocossd', modelLoaded);
document.getElementById("status").innerHTML = "Status : Detecting Objects";
}
img = "";
status = "";
objects = [];
function draw() {
image(video, 0, 0, 380, 380);
if (status != "") {
objectDetector.detect(video, gotResults);
for (i = 0; i < objects.length; i++) {
document.getElementById("status").innerHTML = "Status : Object Detected";
document.getElementById("number_of_objects").innerHTML = "Number of objects detected are :" +
objects.length;
fill("#FF0000");
percent = floor(objects[i].confidence * 100);
text(objects[i].label + " " + percent + "%", objects[i].x, objects[i].y);
noFill();
stroke("#FF0000");
rect(objects[i].x, objects[i].y, objects[i].width, objects[i].height);
}
}
}
function modelLoaded() {
console.log("Model Loaded!")
status = true;
objectDetector.detect(video, gotResults);
}
function gotResults(error, results) {
if (error) {
console.log(error);
}
console.log(results);
objects = results;
}
</script>
</body>
</html>
|
package de.yanos.islam.ui.knowledge.topics.sub
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import de.yanos.islam.R
import de.yanos.islam.ui.knowledge.topics.main.TopicButtons
import de.yanos.islam.util.KnowledgeNavigationAction
import de.yanos.islam.util.Lottie
import de.yanos.islam.util.NavigationAction
import de.yanos.islam.util.headlineMedium
@Composable
fun SubTopicsScreen(
modifier: Modifier = Modifier,
vm: SubTopicViewModel = hiltViewModel(),
onNavigationChange: (NavigationAction) -> Unit
) {
Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) {
Lottie(modifier = Modifier.height(180.dp), resId = R.raw.lottie_thinking, applyColor = false)
Text(modifier = Modifier.padding(bottom = 32.dp), text = vm.topicName.collectAsState(initial = listOf()).value.firstOrNull() ?: "", style = headlineMedium())
TopicButtons(topics = vm.list.collectAsState(initial = listOf()).value) { topic -> onNavigationChange(KnowledgeNavigationAction.NavigateToTopicQuestions(topic.id, topic.parentId)) }
}
}
|
import {
Group,
Button,
Image,
useMantineColorScheme,
ActionIcon,
useComputedColorScheme,
Avatar,
Text,
Anchor,
} from '@mantine/core';;
import classes from './css/headerMenu.module.css';
import pageLogo from './assets/samuraiX.png'
import cx from 'clsx';
import { IconSun, IconMoon } from '@tabler/icons-react';
import actClasses from './css/actionToggle.module.css';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
function NotLoggedIn() {
return (
<>
<Button
href="/login"
component='a'
className={classes.authButton}
>
Log In
</Button>
<Button
href="/signup"
className={classes.authButton}
component='a'
>
Register
</Button>
</>
)
}
function LoggedIn({username, uid}) {
const displayName = username.slice(0,2).toUpperCase()
const navigate = useNavigate()
const logoutHandle = (e) =>{
try {
axios.post('http://localhost:8000/logout/', {
token : localStorage.getItem('token')
},{
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token ' + localStorage.getItem('token')
}
});
// console.log('logout response: ',response.data)
// console.log('token = ', localStorage.getItem('token'))
localStorage.removeItem('username')
localStorage.removeItem('token')
localStorage.removeItem('uid')
navigate('/login')
} catch (error) {
console.error('Logout failed:', error);
}
}
return (
<>
<Group gap="sm" className={classes.avatar} component='a' href={'/users/'+uid}>
<Avatar color="cyan" h={41} w={41} ml={'10px'} radius="xl">{displayName}</Avatar>
<Text className={classes.text} fz="lg" fw={500} mr={'10px'} >
{username}
</Text>
</Group>
<Button
className={classes.authButton}
onClick={logoutHandle}
>
Log Out
</Button>
</>
)
}
export function HeaderMegaMenu({page=''}) {
const { setColorScheme } = useMantineColorScheme();
const computedColorScheme = useComputedColorScheme('light', { getInitialValueInEffect: true });
const [activedPage, setActivedPage] = useState(page);
const navigate = useNavigate();
const username = localStorage.getItem('username')
const uid = localStorage.getItem('uid')
const isAuthenticated = localStorage.getItem('token') !== null
let actUrl = (username===undefined)? 'login' : `/users/${uid}/activities/all`
const links = [
{ link: '/home', label: 'Home' },
{ link: actUrl, label: 'Activities' },
{ link: '/aboutme', label: 'About me' },
]
const headerItems = links.map((link)=> (
<a
key={link.label}
href={link.link}
className={classes.link}
data-active={activedPage === link.label || undefined}
onClick={ (event) => {
event.preventDefault()
setActivedPage(link.label)
navigate(link.link)
}
}
>
{link.label}
</a>
));
return (
<header className={classes.header}>
<Group justify="space-between" h="100%">
<Anchor href='/home'>
<Image src={pageLogo} h={65} w={65} radius={'50%'}/>
</Anchor>
<Group h="100%" gap={0} visibleFrom="sm">
{headerItems}
</Group>
<Group visibleFrom="sm">
{isAuthenticated ? <LoggedIn username={username} uid={uid}/> : <NotLoggedIn/>}
<ActionIcon
onClick={() => setColorScheme(computedColorScheme === 'light' ? 'dark' : 'light')}
variant="outline"
h={38} w={38}
radius={19}
aria-label="Toggle color scheme"
>
<IconSun className={cx(actClasses.icon, actClasses.light)} stroke={1.5} />
<IconMoon className={cx(actClasses.icon, actClasses.dark)} stroke={1.5} />
</ActionIcon>
</Group>
</Group>
</header>
);
}
|
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Welcome to Vue</title>
<script src="https://unpkg.com/vue"></script>
<link rel="stylesheet" href="styles/reset.css">
<link rel="stylesheet" href="styles/main.css">
<link rel="stylesheet" href="styles/circle.css">
</head>
<body>
<div id="app">
<section>
<div class="cash">
<input class="special-input" type="text" v-model="newUser">
</div>
<div class="count">
<button class="counter" v-on:click="addInheritence(newUser)">Dodaj</button>
</div>
</section>
<section v-for="person in persons">
<div class="name">
<span>{{person.name}}</span>
<button v-on:click="removeInheritence(person)">X</button>
</div>
<div class="fraction" v-for="(fraction, index) in person.fractions" v-bind:style="{ order: index }">
<input class="special-input" type="text" v-model="fraction.top">
<hr>
<input class="special-input" type="text" v-model="fraction.bottom">
</div>
<div class="signs" style="order: 0;">
<input class="special-input" type="text" disabled="" value="*">
</div>
<div class="signs" style="order: 1;">
<input class="special-input" type="text" disabled="" value="*">
</div>
<div class="count" style="order: 2;">
<button class="counter" v-on:click="countInheritence(person)" >Policz</button>
</div>
<div class="fraction" style="order: 2;">
<input class="special-input" type="text" v-model="person.total.top">
<hr>
<input class="special-input" type="text" v-model="person.total.bottom">
</div>
<div class="c100 center" v-bind:class="[person.total.class]" style="order: 2;">
<span>{{ (person.total.sum * 100).toFixed(0) }}</span>
<div class="slice"><div class="bar"></div><div class="fill"></div></div>
</div>
</div>
</section>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
newUser: '',
persons: {
barbara: {
name: "barbara",
fractions: [
{top: 1, bottom: 2},
{top: 1, bottom: 2},
{top: 1, bottom: 2},
],
total: {
top: 0,
bottom: 0,
sum: 0,
class : 'p0'
}
}
}
},
methods: {
countInheritence: function (person) {
value1 = parseFloat( person.fractions[0].top );
value2 = parseFloat( person.fractions[0].bottom );
value3 = parseFloat( person.fractions[1].top );
value4 = parseFloat( person.fractions[1].bottom );
value5 = parseFloat( person.fractions[2].top );
value6 = parseFloat( person.fractions[2].bottom );
let topFractionValue = value1 * value3 * value5;
let bottomFractionValue = value2 * value4 * value6;
let topFractionValueLowered = false;
let bottomFractionValueLowered = false;
function lowerNumbers (value1 , value2 ) {
if (value1 % 7 == 0 && value2 % 7 == 0)
{
topFractionValueLowered = value1 / 7;
bottomFractionValueLowered = value2 / 7;
} else if (value1 % 5 == 0 && value2 % 5 == 0)
{
topFractionValueLowered = value1 / 5;
bottomFractionValueLowered = value2 / 5;
} else if (value1 % 3 == 0 && value2 % 3 == 0)
{
topFractionValueLowered = value1 / 3;
bottomFractionValueLowered = value2 / 3;
} else if (value1 % 2 == 0 && value2 % 2 == 0)
{
topFractionValueLowered = value1 / 2;
bottomFractionValueLowered = value2 / 2;
} else {
return true;
}
if (lowerNumbers(topFractionValueLowered, bottomFractionValueLowered)) {
return true;
} else {
lowerNumbers(topFractionValueLowered, bottomFractionValueLowered);
}
}
lowerNumbers(topFractionValue, bottomFractionValue);
person.total.top = topFractionValueLowered ? topFractionValueLowered : topFractionValue;
person.total.bottom = bottomFractionValueLowered ? bottomFractionValueLowered : bottomFractionValue;
person.total.sum = person.total.top / person.total.bottom;
person.total.class = 'p' + ( person.total.sum * 100 ).toFixed(0);
},
removeInheritence: function (person) {
Vue.delete(this.persons, person.name);
},
addInheritence: function (personName) {
if (personName == '') return false;
Vue.set(
this.persons,
personName,
{
name: personName,
fractions: [
{top: 1, bottom: 2},
{top: 1, bottom: 2},
{top: 1, bottom: 2},
],
total: {
top: 0,
bottom: 0,
sum: 0,
class : 'p0'
}
}
)
}
}
})
</script>
</body>
</html>
|
import React, { memo, useEffect, useRef } from "react";
import TitleChart from "./TitleChart";
import { useTranslation } from "react-i18next";
import { Stack, Typography } from "@mui/material";
import CreateForm, { CreateFormProps } from "./CreateForm";
import Lottie, { LottieRefCurrentProps } from "lottie-react";
import { MovePlantBirthAnimation } from "assets/animations";
import { makeStyles } from "@mui/styles";
import { ThemeProps } from "models/types";
import { useMobile } from "hooks";
const CreateBirthChart = ({ onCreateChart }: CreateFormProps) => {
const classes = useStyles();
const isMobile = useMobile();
const lottieRef = useRef<LottieRefCurrentProps>(null);
const { t: getLabel } = useTranslation();
const handleOverPlant = () => {
if (lottieRef.current) {
lottieRef.current.play();
}
};
const handleBlurPlant = () => {
if (lottieRef.current) {
lottieRef.current.pause();
}
};
useEffect(() => {
if (lottieRef.current) {
lottieRef.current.setSpeed(0.4);
}
}, []);
return (
<Stack
alignItems="center"
spacing={{ xs: 0, lg: 15.5 }}
direction={{ xs: "column", lg: "row" }}
width="100%"
>
<Stack flex={1} spacing={{ xs: 4, sm: 3 }} sx={{ position: "relative", zIndex: 2 }}>
<Stack spacing={2}>
<TitleChart
title={getLabel("lCreateYourOwnBirth", { count: isMobile ? 0 : 1 })}
textAlign="center"
/>
{isMobile && (
<Typography fontSize={12} lineHeight="20px" textAlign="center">
{getLabel("lCreateYourOwnBirthDesc")}
</Typography>
)}
</Stack>
<CreateForm onCreateChart={onCreateChart} />
</Stack>
<Lottie
animationData={MovePlantBirthAnimation}
onMouseOver={handleOverPlant}
onMouseLeave={handleBlurPlant}
lottieRef={lottieRef}
className={classes.lottie}
autoplay={false}
/>
</Stack>
);
};
export default memo(CreateBirthChart);
const useStyles = makeStyles((theme: ThemeProps) => ({
lottie: {
width: 670,
[theme.breakpoints.down("lg")]: {
width: 550,
},
[theme.breakpoints.down("sm")]: {
width: 360,
},
},
}));
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import nltk
import seaborn as sns
import string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report, accuracy_score, confusion_matrix
df = pd.read_csv('data/input/nlp-getting-started/train.csv')
df.head()
df.info()
df.isna().sum() / len(df) * 100
df['keyword'].value_counts(normalize=True)[:10].plot(kind='bar')
plt.title('Top 10 Keywords')
plt.ylabel('%')
plt.xticks(rotation=55)
(df['location'].value_counts(normalize=True)[:10] * 100).plot(kind='bar')
plt.title('Top 10 Locations')
plt.ylabel('%')
plt.xticks(rotation=55)
(df['target'].value_counts(normalize=True) * 100).plot(kind='bar')
plt.title('Ratio of Target Data')
plt.xticks(ticks=[0, 1], labels=['False Disaster', 'True Disaster'], rotation=0)
df[df['target'] == 1].groupby('keyword')['target'].sum().sort_values(ascending=False)[:10].plot(kind='bar')
df[df['target'] == 1].groupby('location')['target'].sum().sort_values(ascending=False)[:10].plot(kind='bar')
new_df = df.copy()
new_df.fillna(' ', inplace=True)
new_df
new_df['text_merged'] = new_df['keyword'] + new_df['location'] + new_df['text']
new_df.sample(5)
nltk.download('stopwords')
stopwords = nltk.corpus.stopwords.words('english')
stopwords[:10]
def text_cleaner(text):
clean_words = []
text = ''.join([s for s in text if not s in string.punctuation])
list = text.split()
for word in list:
word = word.lower().strip()
if word.isalpha():
if len(word) > 3:
if word not in stopwords:
clean_words.append(word)
else:
continue
return clean_words
tfidf = TfidfVectorizer(analyzer=text_cleaner)
new_df['text_merged']
(X_train, X_test, y_train, y_test) = train_test_split(new_df['text_merged'], new_df['target'], test_size=0.3, stratify=new_df['target'], random_state=20)
X_train = tfidf.fit_transform(X_train)
X_test = tfidf.transform(X_test)
clf = LogisticRegression(random_state=20)
|
import { BadRequestException, NotFoundException, ExecutionContext, ForbiddenException, Injectable, Res, UnauthorizedException } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { Auth42Dto, AuthDto, AuthTokenDto } from "./dto";
import * as argon from 'argon2';
import { User } from "@prisma/client";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime";
import { JwtService } from "@nestjs/jwt";
import { ConfigService } from '@nestjs/config';
import { SigninDto } from "./dto/signin.dto";
import { UserService } from "src/user/user.service";
export interface Profile_42 {
// id: number;
username: string;
email: string;
avatar: string;
ftAvatar: string;
}
interface DecodedToken {
header: {
alg: string,
typ: string
},
payload: {
sub: string,
email: string,
iat: number,
exp: number
},
signature: string
}
@Injectable()
export class AuthService {
constructor(private userService: UserService, private prisma: PrismaService, private jwt: JwtService, private config: ConfigService) {}
async signup(dto: AuthDto): Promise<AuthTokenDto> {
// destructure dto
const { email, username, password } = dto;
// const defaultAvatar = process.env.DEFAULT_AVATAR
//generate the password
const hash = await argon.hash(password);
//save new user in the db
try {
const user = await this.userService.createUser(
email,
username,
hash,
);
// return a hashed user
const tokens = await this.generateTokens(user.id, user.email);
await this.updateRefreshToken(user.id, tokens.refresh_token);
return tokens;
} catch(error) {
if (error instanceof PrismaClientKnownRequestError) {
if (error.code === 'P2002') {
throw new ForbiddenException('Credentials taken');
}
}
throw error;
}
}
async validateUser(email: string, pass: string): Promise<any> {
const user = await this.userService.getByEmail(email);
if (!user)
throw new ForbiddenException('Credentials incorrect');
const pwMatches = await argon.verify(user.hash, pass);
if (pwMatches) {
return user;
}
return null;
}
async signin(dto: SigninDto) {
const user = await this.validateUser(dto.email, dto.password)
if (!user)
throw new ForbiddenException('Credentials incorrect');
const tokens = await this.generateTokens(user.id, user.email, user.twoFA);
// update refresh token
await this.updateRefreshToken(user.id, tokens.refresh_token);
return tokens;
}
async updateStatus(tokens: AuthTokenDto) {
const user = await this.verifyAccessToken(tokens.access_token);
if (!user)
throw new ForbiddenException('Credentials incorrect');
await this.prisma.user.update({
where: { id: user.id },
data: { status: 'ONLINE' },
});
await this.userService.updateAchievement(user.id, 'Welcome');
}
async signin_42(profile: Profile_42): Promise<User> {
// check if user exists
let user = await this.userService.getByEmail(profile.email);
if (!user) {
return this.create_42_user(profile);
}
return user;
}
async create_42_user(profile: Profile_42): Promise<User> {
const { email, username, avatar, ftAvatar } = profile;
// generate random password
const rdm_string = this.generate_random_password();
// hash password using argon2
const hash = await argon.hash(rdm_string);
//create new user
const user = await this.userService.createUser(
email,
username,
hash,
avatar,
ftAvatar,
);
return user;
}
async signout(user: any) {
const { userId } = user;
const delog = await this.prisma.user.updateMany({
where: {
id: userId,
hashedRtoken: { not: null },
},
data: {
hashedRtoken: null,
status: 'OFFLINE',
},
});
return userId;
//sending status update to the front
// this.appGateway.offlineFromService(userId);
}
async generateTokens(userId: number, email: string, is2FA = false): Promise<AuthTokenDto> {
const payload = {
sub: userId,
email: email,
};
// const payload = { username: user.username, sub: user.userId };
const secret = this.config.get('JWT_SECRET');
const access_token_expiration = this.config.get('ACCESS_TOKEN_EXPIRATION');
const refresh_token_expiration = this.config.get('REFRESH_TOKEN_EXPIRATION');
const Atoken = await this.jwt.sign(payload, {
expiresIn: access_token_expiration,
secret: secret,
});
const Rtoken = await this.jwt.sign(payload, {
expiresIn: refresh_token_expiration,
secret: secret,
});
return {
access_token: Atoken,
refresh_token: Rtoken,
};
}
async refresh_token(refreshToken: string): Promise<AuthTokenDto> {
const decodedToken = this.jwt.decode(refreshToken, { complete: true }) as DecodedToken;
if (!decodedToken) {
throw new BadRequestException('Invalid token');
}
const userId = decodedToken.payload.sub;
const user = await this.userService.getUser(parseInt(userId));
// Check if user exists and is logged in
if (!user || !user.hashedRtoken) {
throw new ForbiddenException('Invalid Credentials');
}
// Verify hashed Refresh Token
const pwMatches = await argon.verify(user.hashedRtoken, refreshToken);
if (!pwMatches) {
throw new ForbiddenException('Invalid Credentials');
}
// Generate new tokens
const tokens = await this.generateTokens(user.id, user.email);
// Update Refresh Token - if user is logged in and valid
await this.updateRefreshToken(user.id, tokens.refresh_token);
return tokens;
}
async updateRefreshToken(userId: number, refreshToken: string): Promise<void> {
// hash le refresh token
const hash = await argon.hash(refreshToken);
// update le user refresh token (log in)
const user = await this.prisma.user.update({
where: {
id: userId,
},
data: {
hashedRtoken: hash,
},
});
}
async verifyAccessToken(token: string): Promise<User> {
try {
const decoded = this.jwt.verify(token);
if (!decoded) {
throw new BadRequestException('Invalid access token');
}
return await this.userService.getByEmail(decoded.email);
} catch (e) {
throw new BadRequestException('Invalid access token');
}
}
async exchangeCodeForTokens(code: string): Promise<{ access_token: string, refresh_token: string}> {
const clientID = process.env.FORTYTWO_CLIENT_ID;
const clientSecret = process.env.FORTYTWO_CLIENT_SECRET;
const redirectURI = process.env.FORTYTWO_CALLBACK_URL;
const tokenEndpoint = 'https://api.intra.42.fr/oauth/token';
const formData = new FormData();
formData.append('grant_type', 'authorization_code');
formData.append('client_id', clientID);
formData.append('client_secret', clientSecret);
formData.append('redirect_uri', redirectURI);
formData.append('code', code);
const response = await fetch(tokenEndpoint, {
method: 'POST',
body: formData
});
const tokens = await response.json();
return {
access_token: tokens.access_token,
refresh_token: tokens.refresh_token
};
}
async getFortyTwoUserProfile(accessToken: string): Promise<Profile_42> {
try {
const headers = { Authorization: `Bearer ${accessToken}` };
const url = 'https://api.intra.42.fr/v2/me';
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error('Failed to get user profile');
}
const data = await response.json();
const profile: Profile_42 = {
// id: data.id,
username: data.login,
email: data.email,
avatar: '',
ftAvatar: data.image.versions.small,
};
return profile;
} catch (error) {
console.log(error);
}
}
generate_random_password(): string {
// generate random password for 42 User
const password =
Math.random().toString(36).slice(2, 15) +
Math.random().toString(36).slice(2, 15);
return password;
}
async verifySocketToken(token: string) {
// try {
// const decoded = this.jwt.verify(token);
// if (!decoded)
{
return ("OK");
// throw new BadRequestException('Invalid access token');
}
// const check2 = await this.userService.getByEmail(decoded.email);
// if (!2)
// {return ("KO");}
return ("OK")
// } catch (e) {
// throw new BadRequestException('Invalid access token');
}
}
|
"""
✅ GOOD Greedy
Daily Challenge (01/13/2022:01/04/2023)
Labuladong P381: Greedy (Interval Scheduling)
tag: medium, Greedy
"""
from typing import List
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
def intervalSchedule():
""" "
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/887690/Python-O(n-log-n)-solution-explained
Runtime: 1236 ms, faster than 93.30% of Python3 online submissions for Minimum Number of Arrows to Burst Balloons.
T: O(N)
"""
points.sort(key=lambda x: x[1])
n, count = len(points), 1
if n == 0:
return 0
curr = points[0]
for i in range(n):
if curr[1] < points[i][0]:
count += 1
curr = points[i]
return count
return intervalSchedule()
sl = Solution()
points = [[10, 16], [2, 8], [1, 6], [7, 12]]
points = [[1, 2], [3, 4], [5, 6], [7, 8]]
points = [[1, 2], [2, 3], [3, 4], [4, 5]]
print(sl.findMinArrowShots(points))
|
package padroes_comportamentais.state;
public class ReservedState extends BookState {
private static ReservedState instance = new ReservedState();
private ReservedState() {
};
@Override
public String getState() {
return "Reserved";
}
public static ReservedState getInstance() {
return instance;
}
@Override
public boolean returnBook(Book book) {
book.setState(AvailableState.getInstance());
return true;
}
@Override
public boolean lostBook(Book book) {
book.setState(LoseState.getInstance());
return true;
}
}
|
using FluentValidation;
using Hellang.Middleware.ProblemDetails;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Persistence.DbContexts;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;
using System.Reflection;
namespace Host.Helpers;
public static class ProgramHelpers
{
public static void AddProblemDetailsServices(this IServiceCollection services)
{
services.AddProblemDetails(options =>
{
options.MapToStatusCode<KeyNotFoundException>(StatusCodes.Status404NotFound);
options.MapToStatusCode<ValidationException>(StatusCodes.Status422UnprocessableEntity);
options.MapToStatusCode<Exception>(StatusCodes.Status500InternalServerError);
});
}
public static void AddSwaggerServices(this IServiceCollection services)
{
var versionProvider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
services.AddSwaggerGen(options =>
{
foreach (var apiVersion in versionProvider.ApiVersionDescriptions.Select(x => x.ApiVersion.ToString()))
{
options.SwaggerDoc(apiVersion,
new OpenApiInfo
{
Title = $"API {apiVersion}",
Version = apiVersion
});
}
// Add Swagger documentation for each methods that has an ApiVersion attribute
options.DocInclusionPredicate((version, desc) =>
{
if (!desc.TryGetMethodInfo(out var methodInfo))
{
return false;
}
// Use method version if present, otherwise use controller version
var methodVersions = methodInfo.GetApiVersions();
return methodVersions.Count > 0
? methodVersions.Exists(v => v.ToString() == version)
: methodInfo.DeclaringType!.GetApiVersions().Exists(v => v.ToString() == version);
});
options.DescribeAllParametersInCamelCase();
options.UseInlineDefinitionsForEnums();
options.SupportNonNullableReferenceTypes();
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Program).Assembly.GetName().Name}.xml"), true);
options.CustomSchemaIds(type => type.ToString().Replace("+", "."));
});
}
public static void EnsureDatabasesMigrated(this WebApplication app)
{
using var dbContext = app.Services.CreateScope().ServiceProvider.GetRequiredService<WriteDbContext>();
dbContext.Database.Migrate();
}
public static void UseSwaggerUiServices(this WebApplication app)
{
var versionProvider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
app.UseSwaggerUI(options =>
{
foreach (var apiVersion in versionProvider.ApiVersionDescriptions.Select(x => x.ApiVersion.ToString()))
{
options.SwaggerEndpoint($"/swagger/{apiVersion}/swagger.json", apiVersion);
}
options.DocExpansion(DocExpansion.None);
});
}
private static List<ApiVersion> GetApiVersions(this ICustomAttributeProvider customAttributeProvider)
=> customAttributeProvider.GetCustomAttributes(true).OfType<ApiVersionAttribute>().SelectMany(attr => attr.Versions).ToList();
}
|
<?php
namespace App\Entity;
use DateTimeImmutable;
use Cocur\Slugify\Slugify;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\ActualiteRepository;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\File\File;
use Doctrine\Common\Collections\ArrayCollection;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
#[ORM\Entity(repositoryClass: ActualiteRepository::class)]
#[Vich\Uploadable]
class Actualite extends ServiceEntityRepository
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $description = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $lieu = null;
#[ORM\ManyToMany(targetEntity: Province::class, mappedBy: 'relation')]
private Collection $provinces;
#[ORM\Column(length: 255, nullable: true)]
private ?string $Lien = null;
#[ORM\Column(type: 'datetime_immutable')]
private ?\DateTimeImmutable $updatedAt = null;
#[ORM\Column(type: 'datetime_immutable')]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\Column(length: 255)]
private ?string $title = null;
#[Vich\UploadableField(mapping: 'products', fileNameProperty: 'Lien')]
private ?File $LienImage = null;
#[ORM\OneToMany(targetEntity: ActualiteImage::class, mappedBy: 'actualite', cascade: ['persist', 'remove'])]
private Collection $galerie;
public function __construct()
{
$this->galerie = new ArrayCollection();
$this->provinces = new ArrayCollection();
$this->createdAt = new \DateTimeImmutable();
}
public function getSlug(): string
{
return (new Slugify())->slugify($this->title);
}
public function getId(): ?int
{
return $this->id;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getLieu(): ?string
{
return $this->lieu;
}
public function setLieu(?string $lieu): self
{
$this->lieu = $lieu;
return $this;
}
/**
* @return Collection<int, Province>
*/
public function getProvinces(): Collection
{
return $this->provinces;
}
public function addProvince(Province $province): static
{
if (!$this->provinces->contains($province)) {
$this->provinces->add($province);
$province->addRelation($this);
}
return $this;
}
public function removeProvince(Province $province): static
{
if ($this->provinces->removeElement($province)) {
$province->removeRelation($this);
}
return $this;
}
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function getFormattedCreatedAt(): string
{
if (!$this->createdAt) {
return '';
}
$formatter = new \IntlDateFormatter(
'fr_FR',
\IntlDateFormatter::LONG,
\IntlDateFormatter::SHORT,
'Indian/Antananarivo',
\IntlDateFormatter::GREGORIAN
);
return $formatter->format($this->createdAt);
}
public function getLien(): ?string
{
return $this->Lien;
}
public function setLien(?string $Lien): self
{
$this->Lien = $Lien;
return $this;
}
public function getLienImage(): ?File
{
return $this->LienImage;
}
public function setLienImage(?File $LienImage): void
{
$this->LienImage = $LienImage;
if (null !== $LienImage) {
$this->updatedAt = new \DateTimeImmutable();
}
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
/**
* @return Collection<int, ActualiteImage>
*/
public function getGalerie(): Collection
{
return $this->galerie;
}
public function addGalerie(ActualiteImage $actualiteImage): self
{
if (!$this->galerie->contains($actualiteImage)) {
$this->galerie[] = $actualiteImage;
$actualiteImage->setActualite($this);
}
return $this;
}
public function removeGalerie(ActualiteImage $actualiteImage): self
{
if ($this->galerie->removeElement($actualiteImage)) {
// set the owning side to null (unless already changed)
if ($actualiteImage->getActualite() === $this) {
$actualiteImage->setActualite(null);
}
}
return $this;
}
}
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<%@ include file="common/nav.jsp" %>
<div class="container">
<div class="mt-2 p-5" style="width:500px; position: absolute; left:35%;">
<h1>회원가입</h1>
<h5> 너 우리 동료가 되어랏</h5>
<div class="alert alert-danger" id="alert-error-register" style="display:none;"></div>
<form id="form-register" method="post" action="/rest/login">
<div class="mb-3 mt-3">
<label class="form-label text-danger" id="label_name">*이름</label>
<input type="text" class="form-control" name="name" placeholder="김홍홍"/>
</div>
<!-- <div class="mb-3">
<label class="form-label text-danger" id="label_tel">*핸드폰 번호</label>
<input type="number" class="form-control" name="tel" placeholder="010-0000-0000"/>
<p><small>예시와 같이 핸드폰번호 형식에 맞춰서 작성해주세요.</small></p>
</div>
-->
<div class="mb-3">
<label class="form-label text-danger" id="label_email">*이메일</label>
<input type="text" class="form-control" name="email" placeholder="example@gmail.com"/>
<p><small class="form-text">이메일 형식에 맞춰서 작성해주세요.</small></p>
</div>
<div class="mb-3">
<label class="form-label text-danger" id="label_email_check">*이메일 확인</label>
<input type="text" class="form-control" name="email_check" placeholder="example@gmail.com"></input>
</div>
<div class="mb-3">
<label class="form-label text-danger" id="label_pwd">*비밀번호</label>
<input type="password" class="form-control" name="pwd" placeholder="****"/>
<p><small class="form-text">[비밀번호 조건] <br>특수문자/ 문자 / 숫자 포함 8~20자리 이내의 암호를 입력해주세요.</small></p>
</div>
<div class="mb-3">
<label class="form-label text-danger" id="label_pwd_check">*비밀번호 확인</label>
<input type="password" class="form-control" name="pwd_check" placeholder="****"/>
</div>
<button type="button" class="btn btn-success" id="btn-register">가입하기</button>
</form>
</div>
</div>
<%@ include file="common/footer.jsp" %>
<script type="text/javascript">
$(function(){
$("#btn-register").click(function(event){
$("#alert-error-register").hide();
let name = $("#form-register [name=name]").val();
let tel = $("#form-register [name=tel]").val();
let email = $("#form-register [name=email]").val();
let emailCheck = $("#form-register [name=email_check]").val();
let password = $("#form-register [name=pwd]").val();
let passwordCheck = $("#form-register [name=pwd_check]").val();
// 유효성확인
var emailPattern = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
var pwdPattern = /^.*(?=^.{8,20}$)(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&+=]).*$/;
if(name == "" || tel == "" || email == "" || password == "" || emailCheck == "" || passwordCheck == ""){
$("#alert-error-register").show().text("비어있는 필수입력정보를 입력해주세요.");
return;
}
if( email != emailCheck){
$("#alert-error-register").show().text("이메일확인을 다시 입력해주세요.");
return;
}
if( password != passwordCheck){
$("#alert-error-register").show().text("비밀번호확인을 다시 입력해주세요.");
return;
}
if(!emailPattern.test(email)){
$("#alert-error-register").show().text("이메일 형식을 맞춰주세요");
return;
}
if(!pwdPattern.test(password)){
$("#alert-error-register").show().text("비밀번호조건을 맞춰주세요");
return;
}
// 비동기 회원가입
$.getJSON({
type: "post"
,url: "rest/registerUser"
,dataType: "json"
,data: {
name: name
,email: email
,password: password
},
success : function(response){
if(response.status == "OK"){
alert("가입이 완료되었습니다. 인프런의 팀원이 되신 걸 환영합니다~");
location.href = "/hello";
}else{
$("#alert-error-register").show().text(response.error);
}
}
})
})
})
</script>
</body>
</html>
|
#
# Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA
#
# Freesound 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.
#
# Freesound 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 <http://www.gnu.org/licenses/>.
#
# Authors:
# See AUTHORS file.
#
import datetime
import json
import logging
import os
from django.conf import settings
from freesound.celery import get_queues_task_counts
from sounds.models import Sound
from utils.management_commands import LoggingBaseCommand
console_logger = logging.getLogger("console")
class Command(LoggingBaseCommand):
help = """Progressively reprocesses all sounds in the database and replaces their images and preview files. This command is
expected to be run multiple times untill all sounds have been processed. The progress of the reprocessing task is saved using
in a file in the server which uses the parameter "-id" in its name. Multiple executions of this command with the same ID will
therefore continue the reprocessing task from where it was left.
"""
def add_arguments(self, parser):
parser.add_argument(
'--reprocessing-id',
action='store',
dest='reprocessing-id',
help='Unique ID for the reprocessing task. This is used to store information about the progress of the reprocessing ' \
'task across multiple runs of the same command.')
parser.add_argument(
'--limit',
action='store',
dest='limit',
default=1000,
help='Maximum number of sounds in the processing queue (it will only send new sounds untill the queue is filled '\
'with this number).')
parser.add_argument(
'--max-sound-id',
action='store',
dest='max-sound-id',
default=999999999,
help='The biggest sound ID which should be re-processed.')
parser.add_argument(
'--skip-images',
action="store_true",
help="Don't run the waveform/spectrogram generation step.")
parser.add_argument(
'--skip-previews',
action="store_true",
help="Don't run the mp3/ogg generation step.")
def handle(self, *args, **options):
self.log_start()
queues_counts_dict = {item[0]: item[1] + item[2] for item in get_queues_task_counts()}
n_sounds_currently_in_processing = queues_counts_dict[settings.CELERY_SOUND_PROCESSING_QUEUE_NAME]
limit = int(options['limit'])
max_sounds_to_send = limit - n_sounds_currently_in_processing
n_sent = 0
last_reprocessed_sound_id = 0
reprocessing_progress = []
num_sounds_failed_processing_before_command_run = Sound.objects.filter(processing_state='FA').count()
if max_sounds_to_send <= 0:
console_logger.info(f'Not sending any sounds to the queue as it is already full (litmit: {limit}, '
f'currently in queue: {n_sounds_currently_in_processing})')
else:
progress_file_path = os.path.join(settings.DATA_PATH, f'reprocessing_progress_{options["reprocessing-id"]}.json')
if os.path.exists(progress_file_path):
reprocessing_progress = json.load(open(progress_file_path))
last_reprocessed_sound_id = reprocessing_progress[-1]['last_sound_id']
sound_ids_to_reprocess = Sound.objects.filter(id__gt=last_reprocessed_sound_id, id__lte=int(options['max-sound-id'])).order_by('id')[:max_sounds_to_send]
if sound_ids_to_reprocess == 0:
# All sounds have been reprocessed!
console_logger.info(f'Not sending any sounds to the queue as all sounds have been reprocessed!')
else:
# Send sounds to processing
console_logger.info(f'Will send {sound_ids_to_reprocess.count()} sounds to processing queue...')
for sound in sound_ids_to_reprocess:
sound.process(skip_previews=options.get('skip-previews', False), skip_displays=options.get('skip-images', False), force=True)
n_sent += 1
last_reprocessed_sound_id = sound.id
# Save current progress
console_logger.info(f'{n_sent} sounds sent to processing queue, last sound ID: {last_reprocessed_sound_id}')
reprocessing_progress.append({'last_sound_id': last_reprocessed_sound_id, 'date': str(datetime.datetime.now())})
json.dump(reprocessing_progress, open(progress_file_path, 'w'))
self.log_end({'n_sent_to_processing': n_sent,
'last_reprocessed_sound_id': last_reprocessed_sound_id,
'num_sounds_failed_processing_before_command_run': num_sounds_failed_processing_before_command_run})
|
{- https://stepik.org/lesson/8442/step/7?unit=1577
5.7 Монада Writer step 7
Измените определение типа Shopping и доработайте функцию purchase из предыдущего задания
таким образом, чтобы можно было реализовать функцию items, возвращающую список купленных товаров
(в том же порядке, в котором они были перечислены при покупке):
Реализуйте функцию items и исправьте функцию total, чтобы она работала как и прежде.
-}
import Control.Monad.Writer
type Shopping = Writer ([String], Sum Integer) ()
purchase :: String -> Integer -> Shopping
purchase item cost = tell ([item], Sum cost)
total :: Shopping -> Integer
total = getSum . snd . execWriter
items :: Shopping -> [String]
items = fst . execWriter
shopping1 :: Shopping
shopping1 = do
purchase "Jeans" 19200
purchase "Water" 180
purchase "Lettuce" 328
testTotal = total shopping1 == 19708
testItems = items shopping1 == ["Jeans","Water","Lettuce"]
test = testTotal && testItems
|
package com.unistrong.ssoclient;
import org.apache.http.conn.ssl.SSLSocketFactory;
import android.util.Log;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
class SSLSocketFactoryEx extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public SSLSocketFactoryEx(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException {
Log.v("checkClientTrusted", "checkClientTrusted---------------------------");
Log.v("Client cer-authType", authType);
if (chain != null){
for ( java.security.cert.X509Certificate cer : chain) {
Log.v("Client cer-cer", cer.toString());
}
}
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException {
Log.v("checkServerTrusted", "checkServerTrusted---------------------------");
Log.v("Server cer-authType", authType);
if (chain != null){
for ( java.security.cert.X509Certificate cer : chain) {
Log.v("Server cer-cer", cer.toString());
}
}
}
};
sslContext.init(null, new TrustManager[] {
tm
}, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port,
autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
|
<template>
<div class="col-md-4 offset-md-4">
<form @submit.prevent="saveTask()" class="card card-body">
<h2 class="text-center mb-3">Create Task</h2>
<input
type="text"
placeholder="Write a Title"
id=""
v-model="task.title"
class="form-control mb-4"
autofocus
/>
<textarea
name=""
id=""
rows="4"
placeholder="Write a Description"
v-model="task.description"
class="form-control mb-4"
></textarea>
<button class="btn btn-lg btn-info" :disabled="!task.title || !task.description" >Save</button>
</form>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { Task } from "@/interfaces/Task";
import { createTask } from "@/services/TaskService";
export default defineComponent({
data() {
return {
task: {} as Task,
};
},
methods: {
async saveTask() {
const res = await createTask(this.task);
console.log(res);
this.$router.push({ name: "tasks" });
},
},
});
</script>
|
package task
import NewBuilderInstructionUtils
import kotlinx.coroutines.*
import org.jf.baksmali.Adaptors.ClassDefinition
import org.jf.baksmali.BaksmaliOptions
import org.jf.baksmali.formatter.BaksmaliWriter
import org.jf.dexlib2.*
import org.jf.dexlib2.base.reference.BaseMethodReference
import org.jf.dexlib2.builder.BuilderInstruction
import org.jf.dexlib2.builder.MutableMethodImplementation
import org.jf.dexlib2.builder.instruction.*
import org.jf.dexlib2.dexbacked.DexBackedDexFile
import org.jf.dexlib2.dexbacked.raw.CodeItem
import org.jf.dexlib2.iface.*
import org.jf.dexlib2.iface.Annotation
import org.jf.dexlib2.iface.instruction.OneRegisterInstruction
import org.jf.dexlib2.iface.instruction.ReferenceInstruction
import org.jf.dexlib2.iface.instruction.formats.Instruction31c
import org.jf.dexlib2.immutable.reference.ImmutableMethodReference
import org.jf.dexlib2.immutable.reference.ImmutableStringReference
import org.jf.dexlib2.rewriter.*
import org.jf.dexlib2.writer.io.FileDataStore
import org.jf.dexlib2.writer.pool.DexPool
import util.Log
import java.io.File
import java.io.StringWriter
import java.util.*
class ModifyDexInjectMethodTask(val unZipFile: File, val virus: String) :
Task<File, File>() {
var intcount = 0
override fun execute(): File = runBlocking<File> {
// 读取需要注入的方法
val readInjectConfig = readInjectConfig()
if (readInjectConfig.isEmpty()) {
Log.d("ModifyDexInjectMethodTask", "无需注入Trace方法")
return@runBlocking unZipFile
}
// 注入方法
injectMethod(readInjectConfig)
return@runBlocking unZipFile
}
private fun readInjectConfig(): List<String> {
try {
val parent = File(virus).parent
return File(parent, "injectMethod.config").apply {
Log.d("ModifyDexInjectMethodTask", "配置路径${absolutePath}")
if (!exists()) {
createNewFile()
}
}.readText().split("\n")
} catch (e: Exception) {
e.printStackTrace()
}
return emptyList()
}
private suspend fun CoroutineScope.injectMethod(configs: List<String>) {
// 寻找 Application 的 Dex
// 过滤 dex 文件
val dexs = unZipFile.listFiles { dir, name -> name.endsWith(".dex") }
val jobs = mutableListOf<Job>()
// 多线程查找
for (dex in dexs) {
val childJob = launch(Dispatchers.IO) {
val dexFile = injectDex(dex.absolutePath, configs)
val dexPool = DexPool(dexFile.opcodes)
// 写入new dex
for (classDef in dexFile.classes) {
dexPool.internClass(classDef)
}
// 删除原来的
dex.delete()
// 从新写入
dexPool.writeTo(FileDataStore(dex));
}
jobs.add(childJob)
}
jobs.joinAll()
}
private fun toJavaPkg(pkg: String): String {
return pkg.removeRange(0, 1).replace("/", ".").replace(";->", ".")
}
private fun classToSmali(classDef: ClassDef): String {
val options = BaksmaliOptions()
options.deodex = false
options.implicitReferences = false
options.parameterRegisters = true
options.localsDirective = true
options.sequentialLabels = true
options.debugInfo = true
options.codeOffsets = false
options.accessorComments = false
options.registerInfo = 0
options.inlineResolver = null
val classDefinition =
ClassDefinition(options, classDef)
val stringWriter = StringWriter()
val indentingWriter = BaksmaliWriter(stringWriter,"")
classDefinition.writeTo(indentingWriter)
return stringWriter.toString()
}
override fun complete(result: File) {
Log.d("ModifyDexInjectMethodTask", "操作完成")
}
private fun injectDex(path: String, configs: List<String>): DexFile {
val dexBackedDexFile =
DexFileFactory.loadDexFile(File(path), Opcodes.getDefault())
val dexWriter = DexRewriter(object : RewriterModule() {
override fun getMethodRewriter(rewriters: Rewriters): Rewriter<Method> {
return Rewriter { method ->
val result = configs.stream().filter { configS ->
toJavaPkg(method.toString()).matches(Regex(configS))
}.findFirst()
if (result.isEmpty) {
return@Rewriter method
}
intcount++
Log.t("提示", "注入方法$method 注入总数:$intcount")
InjectRewrittenMethod(rewriters, method)
}
}
override fun getClassDefRewriter(rewriters: Rewriters): Rewriter<ClassDef> {
val classDef = super.getClassDefRewriter(rewriters)
return classDef
}
})
return dexWriter.dexFileRewriter.rewrite(dexBackedDexFile)
}
class InjectRewrittenMethod(private var rewriters: Rewriters, var method: Method) :
BaseMethodReference(), Method {
var injectMethodImplementation: MethodImplementation? = null
override fun getDefiningClass(): String {
return rewriters.methodReferenceRewriter.rewrite(method).definingClass
}
override fun getName(): String {
return rewriters.methodReferenceRewriter.rewrite(method).name
}
override fun getParameterTypes(): List<CharSequence?> {
return rewriters.methodReferenceRewriter.rewrite(method).parameterTypes
}
override fun getParameters(): List<MethodParameter> {
return RewriterUtils.rewriteList(rewriters.methodParameterRewriter, method.parameters)
}
override fun getReturnType(): String {
return rewriters.methodReferenceRewriter.rewrite(method).returnType
}
override fun getAccessFlags(): Int {
return method.accessFlags
}
override fun getAnnotations(): Set<Annotation> {
return RewriterUtils.rewriteSet(rewriters.annotationRewriter, method.annotations)
}
override fun getHiddenApiRestrictions(): Set<HiddenApiRestriction> {
return method.hiddenApiRestrictions
}
override fun getImplementation(): MethodImplementation? {
var brek = AccessFlags.ABSTRACT.isSet(accessFlags) || AccessFlags.INTERFACE.isSet(accessFlags) || AccessFlags.CONSTRUCTOR.isSet(accessFlags)
val rewriteNullable = RewriterUtils.rewriteNullable(
rewriters.methodImplementationRewriter,
method.implementation
)
if (brek) return rewriteNullable
if (injectMethodImplementation != null) {
return injectMethodImplementation
}
if (rewriteNullable != null) {
val addRegisterCount = 1
// 增加 XpRoot.start() 方法
val mutableMethodImplementation = object : MutableMethodImplementation(rewriteNullable) {
val addRegisterCount = 1
override fun getRegisterCount(): Int {
val localCount = getLocalCountCount()
return if (localCount >= addRegisterCount) {
super.getRegisterCount()
} else {
super.getRegisterCount() + (addRegisterCount - localCount)
}
}
fun getLocalCountCount(): Int {
try {
val ins = getInsSize()
return super.getRegisterCount() - ins
} catch (e: Exception) {
e.printStackTrace()
}
val isStatic = AccessFlags.STATIC.isSet(accessFlags)
val localCount = if (isStatic) {
super.getRegisterCount() - method.parameters.size
} else {
super.getRegisterCount() - method.parameters.size - 1
}
return localCount
}
public fun getInsSize(): Int {
val dexFile: DexBackedDexFile = method::class.java.getDeclaredField("dexFile").let {
it.isAccessible = true
it.get(method)
} as DexBackedDexFile
val codeOffset: Int = method::class.java.getDeclaredField("codeOffset").let {
it.isAccessible = true
it.get(method)
} as Int
val ins = dexFile.dataBuffer.readUshort(codeOffset + CodeItem.INS_OFFSET)
return ins
}
}
// // 参数 todo
if (mutableMethodImplementation.getInsSize() >= 15) {
return rewriteNullable
}
val startRegister = mutableMethodImplementation.registerCount - parameters.size
val isStatic = AccessFlags.STATIC.isSet(accessFlags)
val isCons = AccessFlags.CONSTRUCTOR.isSet(accessFlags)
val instructions = mutableListOf<BuilderInstruction>()
var str = method.toString()
if (str.length > 127) {
str = str.substring(0, 127);
}
instructions.add(
BuilderInstruction21c(
Opcode.CONST_STRING,
0,
ImmutableStringReference(str)
)
)
instructions.add(
BuilderInstruction35c(
Opcode.INVOKE_STATIC, 1, 0, 0, 0, 0, 0,
ImmutableMethodReference(
"Landroid/os/Trace;",
"beginSection",
mutableListOf("Ljava/lang/String;"),
"V"
)
)
)
// 所有寄存器 偏移 1
if (mutableMethodImplementation.getLocalCountCount() < addRegisterCount) {
// 出现寄存器增加情况,将P变量向下移动
println("增加寄存器触发:${method}")
/*
val localCountCount = mutableMethodImplementation.getLocalCountCount()
val off = if (isStatic) {
0
} else {
// 先移动p0
instructions.add(
BuilderInstruction22x(
Opcode.MOVE_OBJECT_FROM16,
localCountCount,
localCountCount + 1
)
)
1
}
for (i in parameters.indices) {
println(parameters[i].type)
if (parameters[i].type.endsWith(";")) {
// 对象
instructions.add(
BuilderInstruction22x(
Opcode.MOVE_OBJECT_FROM16,
localCountCount + i + off,
localCountCount + i + 1 + off
)
)
} else {
// 基本数据类型
instructions.add(
BuilderInstruction22x(
Opcode.MOVE_WIDE_FROM16,
localCountCount + i + off,
localCountCount + i + 1 + off
)
)
}
}
*/
val newBuilderInstructionUtils =
NewBuilderInstructionUtils(addRegisterCount - mutableMethodImplementation.getLocalCountCount())
mutableMethodImplementation.instructions.forEachIndexed { index, ins ->
mutableMethodImplementation.replaceInstruction(
index,
newBuilderInstructionUtils.offInstruction(ins)
)
}
}
val insertIndex = TreeSet<Int>()
// 查找所有方法 return 指令
mutableMethodImplementation.instructions.forEachIndexed { index, ins ->
if (ins.opcode == Opcode.RETURN_VOID || ins.opcode == Opcode.RETURN
|| ins.opcode == Opcode.RETURN_OBJECT || ins.opcode == Opcode.RETURN_WIDE
|| ins.opcode == Opcode.RETURN_VOID_BARRIER || ins.opcode == Opcode.RETURN_VOID_BARRIER
) {
insertIndex.add(index)
}
}
insertIndex.reversed().forEach {
val oldReturn = mutableMethodImplementation.instructions[it]
// 插入结束
mutableMethodImplementation.replaceInstruction(
it,
BuilderInstruction35c(
Opcode.INVOKE_STATIC, 0, 0, 0, 0, 0, 0,
ImmutableMethodReference(
"Landroid/os/Trace;",
"endSection",
null,
"V"
)
)
)
// 插入原来的return
val buidler = NewBuilderInstructionUtils(0)
mutableMethodImplementation.addInstruction(it + 1, buidler.offInstruction(oldReturn))
}
// 如果是构造方法 跳过第一条super指令
instructions.reversed().forEach { mutableMethodImplementation.addInstruction(0, it) }
injectMethodImplementation = mutableMethodImplementation
return mutableMethodImplementation
}
return rewriteNullable
}
}
}
|
package com.tokopedia.topads.dashboard.view.adapter.group_item.viewholder
import android.view.View
import androidx.annotation.LayoutRes
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.tokopedia.kotlin.extensions.view.getResDrawable
import com.tokopedia.topads.common.analytics.TopAdsCreateAnalytics
import com.tokopedia.topads.common.data.response.groupitem.DataItem
import com.tokopedia.topads.dashboard.R
import com.tokopedia.topads.dashboard.data.constant.TopAdsDashboardConstant.ACTIVE
import com.tokopedia.topads.dashboard.data.constant.TopAdsDashboardConstant.NOT_VALID
import com.tokopedia.topads.dashboard.data.constant.TopAdsDashboardConstant.TIDAK_AKTIF
import com.tokopedia.topads.dashboard.data.constant.TopAdsDashboardConstant.TIDAK_TAMPIL
import com.tokopedia.topads.common.data.model.CountDataItem
import com.tokopedia.topads.dashboard.data.utils.Utils
import com.tokopedia.topads.dashboard.view.adapter.group_item.viewmodel.GroupItemsItemModel
import com.tokopedia.topads.dashboard.view.sheet.TopadsSelectActionSheet
import com.tokopedia.unifycomponents.*
import com.tokopedia.unifycomponents.selectioncontrol.CheckboxUnify
import com.tokopedia.unifyprinciples.Typography
/**
* Created by Pika on 2/6/20.
*/
private const val CLICK_ATUR_IKLAN = "click - atur iklan"
private const val CLICK_IMG_MENU = "click - edit group button"
private const val CLICK_NON_AKTIFKAN = "click - nonaktifkan group ads"
private const val CLICK_UHBAH = "click - ubah iklan group ads"
private const val CLICK_HAPUS = "click - hapus iklan group ads"
class GroupItemsItemViewHolder(
val view: View, var selectMode: ((select: Boolean) -> Unit),
var actionDelete: ((pos: Int) -> Unit),
var actionStatusChange: ((pos: Int, status: Int) -> Unit),
private var editDone: ((groupId: String, strategy: String) -> Unit),
private var onClickItem: ((id: String, priceSpent: String, groupName: String) -> Unit),
) : GroupItemsViewHolder<GroupItemsItemModel>(view) {
private val cardView: CardUnify = view.findViewById(R.id.card_view)
private val itemCard: ConstraintLayout = view.findViewById(R.id.item_card)
private val img: ImageUnify = view.findViewById(R.id.img)
private val groupTitle: Typography = view.findViewById(R.id.group_title)
private val imgMenu: UnifyImageButton = view.findViewById(R.id.img_menu)
private val checkBox: CheckboxUnify = view.findViewById(R.id.check_box)
private val label: Label = view.findViewById(R.id.label)
private val imgTotal: ImageUnify = view.findViewById(R.id.img_total)
private val totalItem: Typography = view.findViewById(R.id.total_item)
private val imgKey: ImageUnify = view.findViewById(R.id.img_key)
private val keyCount: Typography = view.findViewById(R.id.key_count)
private val scheduleImg: ImageUnify = view.findViewById(R.id.scheduleImg)
private val tampilCount: Typography = view.findViewById(R.id.tampil_count)
private val pengeluaranCount: Typography = view.findViewById(R.id.pengeluaran_count)
private val klikCount: Typography = view.findViewById(R.id.klik_count)
private val pendapatanCount: Typography = view.findViewById(R.id.pendapatan_count)
private val persentaseKlikCount: Typography = view.findViewById(R.id.persentase_klik_count)
private val produkTerjualCount: Typography = view.findViewById(R.id.produk_terjual_count)
private val progressLayout: ConstraintLayout = view.findViewById(R.id.progress_layout)
private val progressStatus1: Typography = view.findViewById(R.id.progress_status1)
private val progressStatus2: Typography = view.findViewById(R.id.progress_status2)
private val progressBar: ProgressBarUnify = view.findViewById(R.id.progress_bar)
companion object {
@LayoutRes
var LAYOUT = R.layout.topads_dash_item_with_group_card
}
private val sheet: TopadsSelectActionSheet? by lazy(LazyThreadSafetyMode.NONE) {
TopadsSelectActionSheet.newInstance()
}
override fun bind(
item: GroupItemsItemModel,
selectedMode: Boolean,
fromSearch: Boolean,
statsData: MutableMap<String, DataItem>,
countList: MutableList<CountDataItem>,
) {
item.let {
val stats = statsData[item.data.groupId] ?: item.data
if (item.data.strategies.isNotEmpty() && item.data.strategies[0].isNotEmpty()) {
imgKey.visibility = View.GONE
keyCount.visibility = View.GONE
} else {
imgKey.visibility = View.VISIBLE
keyCount.visibility = View.VISIBLE
}
img.setImageDrawable(view.context.getResDrawable(R.drawable.topads_dashboard_folder))
imgTotal.setImageDrawable(view.context.getResDrawable(R.drawable.topads_dashboard_total))
imgKey.setImageDrawable(view.context.getResDrawable(R.drawable.topads_dashboard_key))
scheduleImg.setImageDrawable(view.context.getResDrawable(com.tokopedia.topads.common.R.drawable.topads_ic_calendar))
imgMenu.setImageDrawable(view.context.getResDrawable(com.tokopedia.topads.common.R.drawable.ic_topads_menu))
if (selectedMode) {
imgMenu.visibility = View.INVISIBLE
checkBox.visibility = View.VISIBLE
} else {
cardView.setBackgroundColor(ContextCompat.getColor(view.context,
com.tokopedia.unifyprinciples.R.color.Unify_NN0
))
imgMenu.visibility = View.VISIBLE
checkBox.visibility = View.GONE
checkBox.isChecked = false
it.isChecked = false
}
checkBox.isChecked = it.isChecked
if (!checkBox.isChecked) {
cardView.setBackgroundColor(ContextCompat.getColor(view.context,
com.tokopedia.unifyprinciples.R.color.Unify_NN0
))
} else {
cardView.setBackgroundColor(ContextCompat.getColor(view.context,
com.tokopedia.unifyprinciples.R.color.Unify_BN400_20))
}
when (it.data.groupStatusDesc) {
ACTIVE -> label.setLabelType(Label.GENERAL_DARK_GREEN)
TIDAK_AKTIF -> label.setLabelType(Label.GENERAL_LIGHT_ORANGE)
TIDAK_TAMPIL -> label.setLabelType(Label.GENERAL_LIGHT_GREY)
}
groupTitle.text = it.data.groupName
label.text = it.data.groupStatusDesc
if (countList.isNotEmpty() && adapterPosition < countList.size && adapterPosition != RecyclerView.NO_POSITION) {
totalItem.text = countList[adapterPosition].totalAds.toString()
keyCount.text = countList[adapterPosition].totalKeywords.toString()
}
tampilCount.text = stats.statTotalImpression
klikCount.text = stats.statTotalClick
persentaseKlikCount.text = stats.statTotalCtr
pengeluaranCount.text = stats.statTotalSpent
pendapatanCount.text = stats.groupTotalIncome
produkTerjualCount.text = stats.statTotalConversion
setProgressBar(stats)
itemCard?.setOnClickListener { _ ->
if (!selectedMode) {
if (item.data.groupPriceDailyBar.isNotEmpty())
onClickItem.invoke(item.data.groupId,
stats.groupPriceDailySpentFmt,
item.data.groupName)
else
onClickItem.invoke(item.data.groupId, NOT_VALID, item.data.groupName)
} else {
checkBox.isChecked = !checkBox.isChecked
it.isChecked = checkBox.isChecked
if (checkBox.isChecked)
cardView.setBackgroundColor(ContextCompat.getColor(view.context,
com.tokopedia.unifyprinciples.R.color.Unify_BN400_20))
else
cardView.setBackgroundColor(ContextCompat.getColor(view.context,
com.tokopedia.unifyprinciples.R.color.Unify_NN0))
}
}
itemCard.setOnLongClickListener {
item.isChecked = true
checkBox.isChecked = true
cardView.setBackgroundColor(ContextCompat.getColor(view.context,
com.tokopedia.unifyprinciples.R.color.Unify_BN400_20))
selectMode.invoke(true)
true
}
}
imgMenu.setOnClickListener {
TopAdsCreateAnalytics.topAdsCreateAnalytics.sendTopAdsGroupEvent(CLICK_IMG_MENU, "")
sheet?.show(((view.context as FragmentActivity).supportFragmentManager),
item.data.groupStatus,
item.data.groupName,
item.data.groupId)
sheet?.onEditAction = {
TopAdsCreateAnalytics.topAdsCreateAnalytics.sendTopAdsGroupEvent(CLICK_UHBAH, "")
if (item.data.strategies.size > 0 && item.data.strategies.isNotEmpty()) {
editDone.invoke(item.data.groupId, item.data.strategies[0])
} else {
editDone.invoke(item.data.groupId, "")
}
TopAdsCreateAnalytics.topAdsCreateAnalytics.sendTopAdsDashboardEvent(
CLICK_ATUR_IKLAN,
"")
}
sheet?.onDeleteClick = {
TopAdsCreateAnalytics.topAdsCreateAnalytics.sendTopAdsGroupEvent(CLICK_HAPUS, "")
if (adapterPosition != RecyclerView.NO_POSITION)
actionDelete(adapterPosition)
}
sheet?.changeStatus = {
TopAdsCreateAnalytics.topAdsCreateAnalytics.sendTopAdsGroupEvent(
CLICK_NON_AKTIFKAN, "")
if (adapterPosition != RecyclerView.NO_POSITION)
actionStatusChange(adapterPosition, it)
}
}
}
private fun setProgressBar(data: DataItem) {
if (data.groupPriceDailySpentFmt.isNotEmpty()) {
progressLayout.visibility = View.VISIBLE
progressBar.progressBarColorType = ProgressBarUnify.COLOR_GREEN
try {
progressBar.setValue(Utils.convertMoneyToValue(data.groupPriceDailySpentFmt),
true)
} catch (e: NumberFormatException) {
e.printStackTrace()
}
progressStatus1.text = data.groupPriceDailySpentFmt
progressStatus2.text =
String.format(view.context.resources.getString(com.tokopedia.topads.common.R.string.topads_dash_group_item_progress_status),
data.groupPriceDaily)
} else {
progressLayout.visibility = View.GONE
}
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Movie Store</title>
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link rel="stylesheet" href="~/css/animate.css" />
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
@RenderSection("Styles", required: false)
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand"><img width="30px" style="display:inline-block" id="app-logo" src="~/images/viewster-logo-300x300.png" />Movie App</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="StoreBranches" asp-action="MapView">Branches</a></li>
<li><a asp-area="" asp-controller="Movies" asp-action="Search">Movies</a></li>
<li><a asp-area="" asp-controller="customers" asp-action="Search">Customer</a></li>
<li><a asp-area="" asp-controller="Recommender" asp-action="index">Movie Recommender</a></li>
<li><a asp-area="" asp-controller="Statistic" asp-action="index">Statistics</a></li>
@if (User.IsInRole("Admin"))
{
<li><a asp-area="" asp-controller="suppliers" asp-action="Search">Suppliers</a></li>
<li><a asp-area="" asp-controller="Admin" asp-action="Index">Admin</a></li>
}
</ul>
@await Html.PartialAsync("_LoginPartial")
</div>
</div>
</nav>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© 2018 - MovieProject</p>
</footer>
</div>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
@*<script src="~/js/typehead.js"></script>*@
@RenderSection("Scripts", required: false)
</body>
</html>
|
<!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>John Doe-Protfolio Website</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div id="wrapper">
<div class="container">
<div class="navbar">
<div class="logo-container">
<div class="logo"><img src="/NavLogo.jpg" alt=""></div>
<div class="logo-text">ohn Doe</div>
</div>
<div class="logo-items">
<div class="projects"><a href="#project-section">Projects</a></div>
<div class="skills"><a href="#skill-container">Skills</a></div>
<div class="contactme"><a href="#">Contact Me</a></div>
</div>
</div>
<div class="hero-section">
<div class="faded-text">John Doe</div>
<div class="hero-section-left">
<div class="heading">Hi! John Doe</div>
<div class="subheading">
I am a <span class="role"></span>
</div>
<div class="hero-section-description">
I’m a software developer and here is my portfolio website. Here you’ll learn about my journey as
a software developer.
</div>
<button class="btn-pink">Hire Me</button>
</div>
<div class="hero-section-right">
<div class="absolute icons icon-dots">
<img src="/dots.png" alt="" />
</div>
<div class="absolute icons icon-cube">
<img src="/cube.png" alt="" />
</div>
<div class="absolute icons icon-circle">
<img src="/circle.png" alt="" />
</div>
<div class="absolute icons icon-zigzag">
<img src="/zigzags.png" alt="" />
</div>
<div class="absolute icons icon-plus">
<img src="/plus.png" alt="" />
</div>
<div class="user-image">
<img src="/UserImage.png" alt="" />
</div>
</div>
</div>
</div>
<div class="project-section" id="project-section">
<h2 class="project-heading">Projects</h2>
<div class="project-container">
<div class="project-card" id=" card1">
<div class="project-number" id="project-number-right">01</div>
<div class="project-content" id="project-content-left">
<div class="icon">
<img src="./stack/HTML.png" alt="" class="icon-img">
<img src="./stack/CSS.png" alt="" class="icon-img">
<img src="./stack/Javascript.svg" alt="" class="icon-img">
<img src="./stack/Express.png" alt="" class="icon-img">
<img src="./stack/Next.svg" alt="" class="icon-img">
<img src="./stack/Tailwind.png" alt="" class="icon-img">
<img src="./stack/NodeJs.svg" alt="" class="icon-img">
<img src="./stack/MongoDB.svg" alt="" class="icon-img">
<img src="./stack/Redux.svg" alt="" class="icon-img">
<img src="./stack/Vercel.svg" alt="" class="icon-img">
</div>
<div class="content-heading">Tint & Orange</div>
<div class="content-subheading">It is a car modification company which provide you sheets to
protect your car from scratch</div>
<div class="btn-group">
<button class="btn-pink">Read More</button>
<a href="">
<i title="GitHubLink" class="fa-brands fa-github icons"></i>
</a>
<a href="">
<i title="Live Link" class="fa-solid fa-link icons"></i>
</a>
</div>
</div>
</div>
<div class="project-card " id="card2">
<div class="project-number" id="project-number-left">02</div>
<div class="project-content" id="project-content-right">
<div class="icon">
<img src="./stack/HTML.png" alt="" class="icon-img">
<img src="./stack/CSS.png" alt="" class="icon-img">
<img src="./stack/Javascript.svg" alt="" class="icon-img">
<img src="./stack/Express.png" alt="" class="icon-img">
<img src="./stack/Next.svg" alt="" class="icon-img">
<img src="./stack/Tailwind.png" alt="" class="icon-img">
<img src="./stack/NodeJs.svg" alt="" class="icon-img">
<img src="./stack/MongoDB.svg" alt="" class="icon-img">
<img src="./stack/Redux.svg" alt="" class="icon-img">
<img src="./stack/Vercel.svg" alt="" class="icon-img">
</div>
<div class="content-heading">Breaking Copyrights</div>
<div class="content-subheading">A platform to download copyrights free youtube music</div>
<div class="btn-group">
<button class="btn-pink">Read More</button>
<a href="">
<i title="GitHubLink" class="fa-brands fa-github icons"></i>
</a>
<a href="">
<i title="Live Link" class="fa-solid fa-link icons"></i>
</a>
</div>
</div>
</div>
<div class="project-card" id="card3">
<div class="project-number" id="project-number-right">03</div>
<div class="project-content" id="project-content-left">
<div class="icon">
<img src="./stack/HTML.png" alt="" class="icon-img">
<img src="./stack/CSS.png" alt="" class="icon-img">
<img src="./stack/Javascript.svg" alt="" class="icon-img">
<img src="./stack/Express.png" alt="" class="icon-img">
<img src="./stack/Next.svg" alt="" class="icon-img">
<img src="./stack/Tailwind.png" alt="" class="icon-img">
<img src="./stack/NodeJs.svg" alt="" class="icon-img">
<img src="./stack/MongoDB.svg" alt="" class="icon-img">
<img src="./stack/Redux.svg" alt="" class="icon-img">
<img src="./stack/Vercel.svg" alt="" class="icon-img">
</div>
<div class="content-heading">Isha Tattva</div>
<div class="content-subheading">A Website for interior designer to showcase her works and
samples</div>
<div class="btn-group">
<button class="btn-pink">Read More</button>
<a href="">
<i title="GitHubLink" class="fa-brands fa-github icons"></i>
</a>
<a href="">
<i title="Live Link" class="fa-solid fa-link icons"></i>
</a>
</div>
</div>
</div>
<div class="project-card" id="card4">
<div class="project-number" id="project-number-left">04</div>
<div class="project-content" id="project-content-right">
<div class="icon">
<img src="./stack/HTML.png" alt="" class="icon-img">
<img src="./stack/CSS.png" alt="" class="icon-img">
<img src="./stack/Javascript.svg" alt="" class="icon-img">
<img src="./stack/Express.png" alt="" class="icon-img">
<img src="./stack/Next.svg" alt="" class="icon-img">
<img src="./stack/Tailwind.png" alt="" class="icon-img">
<img src="./stack/NodeJs.svg" alt="" class="icon-img">
<img src="./stack/MongoDB.svg" alt="" class="icon-img">
<img src="./stack/Redux.svg" alt="" class="icon-img">
<img src="./stack/Vercel.svg" alt="" class="icon-img">
</div>
<div class="content-heading">Granit</div>
<div class="content-subheading">A architectural website to plan your building or home (Hebrew
Language)</div>
<div class="btn-group">
<button class="btn-pink">Read More</button>
<a href="">
<i title="GitHubLink" class="fa-brands fa-github icons"></i>
</a>
<a href="">
<i title="Live Link" class="fa-solid fa-link icons"></i>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="skill-container" id="skill-container">
<div class="skill-content">
<div class="skill-heading">Skills</div>
<div class="skill-content-left">
<div class="skill-subheading">
<span id="cap">M</span>e and
<br>MyTech Stack
</div><br>
<div class="skill-description">
<p>Hi Everyone My name is John Doe I am a Full Stack Web Developer I have been working for last
3 Years and Currently I am working with a Budding Startup in USA and a full Time Freelancer.
Currently I am working on NextJs and Making Beautiful UI-UX are my fey features</p><br>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Atque quo recusandae tempora amet
distinctio ullam, nam nostrum sed officia iure, deserunt eveniet incidunt, similique ex
laudantium minus odio molestiae vel.
</p><br>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quo aperiam, eum soluta
perspiciatis cumque itaque placeat nihil harum libero voluptas assumenda, dolorum quam
consequuntur voluptatibus aspernatur at natus aliquid voluptates?</p>
</div>
</div>
<div class="skill-content-right">
<img src="./blob vector.png" alt="" class="blob">
<img src="./stack/HTML.png" alt="" class="skill-icon">
<img src="./stack/CSS.png" alt="" class="skill-icon">
<img src="./stack/Javascript.svg" alt="" class="skill-icon">
<img src="./stack/Bash.svg" alt="" class="skill-icon">
<img src="./stack/Bootstrap.svg" alt="" class="skill-icon">
<img src="./stack/ChartJs.svg" alt="" class="skill-icon">
<img src="./stack/Docker.svg" alt="" class="skill-icon">
<img src="./stack/Express.png" alt="" class="skill-icon">
<img src="./stack/Git.svg" alt="" class="skill-icon">
<img src="./stack/Github.svg" alt="" class="skill-icon">
<img src="./stack/Graphql.svg" alt="" class="skill-icon">
<img src="./stack/K8s.svg" alt="" class="skill-icon">
<img src="./stack/MaterialUI.svg" alt="" class="skill-icon">
<img src="./stack/MongoDB.svg" alt="" class="skill-icon">
<img src="./stack/Next.svg" alt="" class="skill-icon">
<img src="./stack/NextJsCircle.png" alt="" class="skill-icon">
<img src="./stack/NodeJs.svg" alt="" class="skill-icon"> <img src="./stack/React.png" alt=""
class="skill-icon"> <img src="./stack/Redux.svg" alt="" class="skill-icon"> <img
src="./stack/Saas.svg" alt="" class="skill-icon"> <img src="./stack/Tailwind.png" alt=""
class="skill-icon">
<img src="./stack/Typescript.svg" alt="" class="skill-icon"> <img src="./stack/Vercel.svg" alt=""
class="skill-icon">
</div>
</div>
</div>
<div class="contactus-form-container" id="contactme">
<div class="container">
<h1 class="contactus-heading">Contact me</h1>
<h3 class="contactus-sub-heading">
Questions, thoughts, or just want to say hello?
</h3>
<div class="contactus-form-container">
<form class="form" action="">
<div class="formfield-container">
<input class="formfield"
type="text"
name="name"
id=""
placeholder="Enter your name" />
<input class="formfield"
type="email"
name="email"
id=""
placeholder="Enter your email address" />
<input class="formfield"
type="text"
name="subject"
id=""
placeholder="Enter your subject" />
<textarea name="message"
id="" cols="30" rows="10"
class="formfield formfield-textarea"
placeholder="Enter your message"></textarea>
</div>
<div>
<button type="submit" class="btn-pink" id="submit-btn">
Send Message<i class="submit-icon fa-solid fa-paper-plane"></i>
</button>
</div>
</form>
</div>
</div>
</div>
<footer>
<div class="container">
<div class="footer-wrapper">
<div class="footer-faded-text">John Doe</div>
<div class="link-wrapper">
<div>
<a href="#projects">Projects</a>
</div>
<div>
<a href="#skills">Skills</a>
</div>
<div>
<a href="#contactme">Contact Me</a>
</div>
</div>
<div class="icon-wrapper">
<i class="fa-brands fa-linkedin connect"></i>
<i class="fa-brands fa-github connect"></i>
<i class="fa-brands fa-twitter connect"></i>
<i class="fa-brands fa-instagram connect"></i>
<i class="fa-regular fa-envelope connect"></i>
</div>
</div>
</div>
</footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12"></script>
<script src="https://kit.fontawesome.com/58a810656e.js" crossorigin="anonymous"></script>
<script>
var typeData = new Typed(".role", {
strings: [
"Full Stack Developer",
"Web Developer",
"UI-UX Designer",
"Backend Developer",
"Coder",
],
loop: true,
typeSpeed: 100,
backSpeed: 80,
backDelay: 1000,
});
</script>
</body>
</html>
|
//
// TouristInformationView.swift
// Hotels
//
// Created by Lol Kek on 28/01/2024.
//
import SwiftUI
struct TouristInformationView: View {
@ObservedObject var viewModel: UserInfoViewModel
var body: some View {
VStack(alignment: .leading, spacing: LayoutConstants.padding8) {
ValidatedTextField(text: $viewModel.firstName,
title: viewModel.firstNameTitle,
isValid: $viewModel.isFirstNameValid)
{ text in
viewModel.validateText(text)
}.id(viewModel.firstNameTitle)
ValidatedTextField(text: $viewModel.lastName,
title: viewModel.lastNameTitle,
isValid: $viewModel.isLastNameValid)
{ text in
viewModel.validateText(text)
}.id(viewModel.lastNameTitle)
ValidatedTextField(text: $viewModel.birthDate,
title: viewModel.birthDateTitle,
keyboarType: .numberPad,
isValid: $viewModel.isBirthDateValid)
{ text in
viewModel.validateText(text)
}.id(viewModel.birthDateTitle)
ValidatedTextField(text: $viewModel.citizens,
title: viewModel.citizensTitle,
isValid: $viewModel.isCitizensValid)
{ text in
viewModel.validateText(text)
}.id(viewModel.citizensTitle)
ValidatedTextField(text: $viewModel.passNumber,
title: viewModel.passNumberTitle,
keyboarType: .numberPad,
isValid: $viewModel.isPassNumberValid) { text in
viewModel.validateText(text)
}.id(viewModel.passNumberTitle)
ValidatedTextField(text: $viewModel.passExpirationDate,
title: viewModel.passExpirationDateTitle,
keyboarType: .numberPad,
isValid: $viewModel.isPassExpirationDateValid) { text in
viewModel.validateText(text)
}.id(viewModel.passExpirationDateTitle)
}
.padding(.horizontal)
.padding(.top, 0)
.padding(.bottom)
.background(ColorConstants.background)
.cornerRadius(LayoutConstants.cornerRadius12, corners: [.bottomLeft, .bottomRight])
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - financeapp</title>
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/financeapp.styles.css" asp-append-version="true" />
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
gridTemplateColumns: {
fluid: "repeat(auto-fit, minmax(20rem, 1fr))",
},
colors: {
'primary': {
'50': '#fffbeb',
'100': '#fef3c7',
'200': '#fde58a',
'300': '#fbd24e',
'400': '#fabe25',
'500': '#f49d0c',
'600': '#d87607',
'700': '#bc560a',
'800': '#923f0e',
'900': '#78340f',
'950': '#451a03',
DEFAULT: '#d87607',
},
}
}
}
}
</script>
</head>
<body class="bg-stone-900 text-stone-100">
<header class="max-w-7xl w-full mx-auto">
<nav class="flex gap-4 items-center py-4 px-5 sm:px-10">
<a class="font-bold uppercase" asp-area="" asp-controller="Home" asp-action="Index">financeapp</a>
<ul class="flex gap-4 justify-between w-full">
<div class="flex gap-2">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
@if (User.Identity.IsAuthenticated && User.IsInRole("Admin"))
{
<li>
<a class="nav-link text-dark" asp-area="" asp-controller="User" asp-action="Index">Users</a>
</li>
}
</div>
@if (User.Identity != null && User.Identity.IsAuthenticated)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Login" asp-action="Logout">Logout</a>
</li>
}
else
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Login" asp-action="Index">Login</a>
</li>
}
</ul>
</nav>
</header>
<main role="main" class="max-w-7xl w-full mx-auto pt-20 pb-40">
@RenderBody()
</main>
<footer class="footer text-muted">
<div class="container mx-auto">
© 2024 - financeapp - <a asp-area="" asp-controller="User" asp-action="Index">Users</a>
</div>
</footer>
@await RenderSectionAsync("Functions", required: false)
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
|
import Sweets.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class GiftMaker {
public static void launch() {
ArrayList<Sweet> sweets = new ArrayList();
sweets.add(new Cake("Торт", 0.1, new BigDecimal("65"), 1500));
sweets.add(new Candy("Леденцы", 0.2, new BigDecimal("225"), "aруктовые"));
sweets.add(new Chocolate("Шоколад", 1.2, new BigDecimal("215"), "Forastero"));
sweets.add(new Cookie("Печенье", 0.4, new BigDecimal("240"), "овсяная"));
sweets.add(new CottonCandy("Сахарная вата", 0.12, new BigDecimal("145"), "клубника"));
sweets.add(new Gummy("Мармелад", 0.3, new BigDecimal("300"), "в форме мишек"));
sweets.add(new JellyBeans("Желе бобы", 0.2, new BigDecimal("270"), "красный"));
sweets.add(new Lollipop("Sweets.Lollipop", 0.2, new BigDecimal("70"), "USA"));
sweets.add(new Marshmallow("Зефир", 0.07, new BigDecimal("85"), "средняя"));
sweets.add(new PeppermintTwist("Мятные палочки", 0.12, new BigDecimal("2602"), "сильная"));
sweets.add(new Toffee("Ирис", 0.12, new BigDecimal("2602"), "ореховое"));
//Найти общий вес подарка, общую стоимость подарка
DecimalFormat df = new DecimalFormat("#.##");
String totalWeight = df.format(getTotalWeight(sweets));
System.out.println("Общий вес подарка: " + totalWeight + " кг.");
System.out.println("Общая стоимость подарка: " + getTotalCost(sweets) + " руб.");
System.out.println("\nСостав подарка:");
for(Object sweet : sweets){
System.out.println(sweet.toString());
}
}
public static BigDecimal getTotalCost(ArrayList<Sweet> sweets){
BigDecimal totalCost = new BigDecimal(0);
for (Sweet sweet : sweets){
totalCost = totalCost.add(sweet.getCost());
}
return totalCost;
}
public static Double getTotalWeight(ArrayList<Sweet> sweets){
Double totalWeight = 0.0;
for (Sweet sweet : sweets){
totalWeight += sweet.getWeight();
}
return totalWeight;
}
}
|
/*
* meteopoll.cc -- successor to meteoloop, polls the station using the loop
* command, and writes data to mysql database. Is aware of
* nonmetric units
*
* (c) 2003 Dr. Andreas Mueller, Beratung und Entwicklung
*
* $Id: meteopoll.cc,v 1.29 2008/09/07 15:18:52 afm Exp $
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#include <Station.h>
#include <StationFactory.h>
#include <Configuration.h>
#include <MeteoException.h>
#include <Mapfile.h>
#include <XmlOutletFactory.h>
#include <QueryOutlet.h>
#include <Datasink.h>
#include <Daemon.h>
#include <mdebug.h>
#include <errno.h>
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include <fstream>
#include <iostream>
#include <printver.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#include <sys/resource.h>
#define ALARMTIMEOUT 30
pid_t clpid;
bool allowfork = true;;
// signal handler to kill child when parent is sent a signal
void kill_child(int cause) {
switch (cause) {
case SIGTERM:
case SIGINT:
if (allowfork)
kill(clpid, cause);
mdebug(LOG_INFO, MDEBUG_LOG, 0, "caught signal, exiting");
exit(EXIT_SUCCESS);
break;
case SIGHUP:
mdebug(LOG_INFO, MDEBUG_LOG, 0,
"caught SIGHUP, killing child");
if (allowfork)
kill(clpid, SIGTERM);
break;
}
return;
}
static void loop(const std::string& station,
const std::string& mapfilename, const meteo::stringlist& xmloutlets) {
// limit memory to 16MB so this process cannot monopolize the system
#define memmax 0x1 << 25
struct rlimit l;
getrlimit(RLIMIT_STACK, &l); // stack segment
if (l.rlim_max > memmax)
l.rlim_max = memmax;
setrlimit(RLIMIT_STACK, &l);
getrlimit(RLIMIT_DATA, &l); // data segment
if (l.rlim_max > memmax)
l.rlim_max = memmax;
setrlimit(RLIMIT_DATA, &l);
// create a new station object (this always returns something
// connected)
mdebug(LOG_DEBUG, MDEBUG_LOG, 0, "starting new station '%s'",
station.c_str());
meteo::Station *s = meteo::StationFactory().newStation(station);
mdebug(LOG_DEBUG, MDEBUG_LOG, 0, "station %s ready", station.c_str());
// add the mapfile if mapfilename is set
if (!mapfilename.empty()) {
meteo::Mapfile *mapfile = new meteo::Mapfile(mapfilename, true);
mapfile->setStationname(station);
s->addMapfile(mapfile); // takes ownership
}
// if we have an XML file, create a XmlOutlet with a delegate
for (meteo::stringlist::const_iterator i = xmloutlets.begin(); i != xmloutlets.end(); i++) {
if (!i->empty()) {
mdebug(LOG_DEBUG, MDEBUG_LOG, 0, "preparing XML outlet to %s",
i->c_str());
meteo::XmlOutlet *xmloutlet = meteo::XmlOutletFactory::get(station, *i);
s->addOutlet(xmloutlet); // takes ownership
}
}
// create a data sink (new implementation uses QueryOutlet class)
s->addOutlet(new meteo::QueryOutlet(station));
// loop:
meteo::Timeval looptime; looptime.now();
int minute = looptime.getMinute();
while (true) {
// start the loop, expecting 10 data packets
mdebug(LOG_DEBUG, MDEBUG_LOG, 0, "request 10 packets");
s->startLoop(10);
while (s->expectMorePackets()) {
mdebug(LOG_DEBUG, MDEBUG_LOG, 0,
"wait for more packets");
// reset the alarm timer: if reading the packet takes
// longer than 10 seconds, the connection is probably
// broken
mdebug(LOG_DEBUG, MDEBUG_LOG, 0, "resetting timer");
alarm(ALARMTIMEOUT);
// read a packet from the station
std::string p = s->getPacket();
mdebug(LOG_DEBUG, MDEBUG_LOG, 0,
"received packet of length %d", p.length());
// update the data from the packet in the station
s->update(p);
// if the minute has increased by one since the last
// update save the current record in the database and
// reset the datarecord
looptime.now();
if (minute != looptime.getMinute()) {
// send data to outlets
s->sendOutlets(looptime.getTimekey());
// reset and restart
s->reset();
minute = looptime.getMinute();
}
}
}
}
static void usage(void) {
printf(
"usage: meteopoll [ -dFVh? ] [ -l logurl ] [ -f conffile ] [ -b prefs ] \\\n"
" [ -p pidfile ] [ -m mapfile ] [ -x xmlfile ] -s stationname\n"
" -d increase debug level\n"
" -F don't fork (used for debugging)\n"
" -V print version and exit\n"
" -h, -? print this help screen and exit\n"
" -f conffile use conffile, see meteo.xml(5)\n"
" -s stationname let this process connect to station named stationname\n"
" -b prefs add backend preference prefs (one of msgqueue, mysql\n"
" file, debug)\n"
" -p pidfile write the process pid to this file\n"
" -m mapfile keep current sensor information in mapfile\n"
" -x xmlfile send output to XML file as well\n");
}
static int meteopoll(int argc, char *argv[]) {
std::string conffile(METEOCONFFILE);
std::string logurl("file:///-"); // logging to stderr
std::string station, mapfilename;
meteo::stringlist xmloutlets;
meteo::stringlist preferences;
std::string pidfileprefix;
// parse command line
int c;
while (EOF != (c = getopt(argc, argv, "dl:f:m:s:b:p:VFh?x:")))
switch (c) {
case 'd':
debug++;
break;
case 'l':
logurl = std::string(optarg);
break;
case 'f':
conffile = std::string(optarg);
break;
case 's':
station = std::string(optarg);
break;
case 'b':
preferences.push_back(std::string(optarg));
break;
case 'p':
pidfileprefix = std::string(optarg);
break;
case 'V':
fprintver(stdout);
exit(EXIT_SUCCESS);
break;
case 'F':
allowfork = false;
break;
case 'h':
case '?':
usage();
exit(EXIT_SUCCESS);
case 'm':
mapfilename = std::string(optarg);
break;
case 'x':
xmloutlets.push_back(std::string(optarg));
break;
default:
mdebug(LOG_ERR, MDEBUG_LOG, 0,
"option %c not implemented", c);
break;
}
// set up logging
mdebug_setup("meteopoll", logurl.c_str());
mdebug(LOG_DEBUG, MDEBUG_LOG, 0, "set up logging to %s",
logurl.c_str());
// it is an error if station name or conf
if (station.empty()) {
fprintf(stderr, "%s: station name not set\n", argv[0]);
mdebug(LOG_CRIT, MDEBUG_LOG, 0, "station name not set");
exit(EXIT_FAILURE);
}
// pid file
if (pidfileprefix.empty())
pidfileprefix = "/var/run/meteopoll-";
// fork if necessary
meteo::Daemon d(pidfileprefix, station, !allowfork);
// open the configuration object
meteo::Configuration conf(conffile);
mdebug(LOG_DEBUG, MDEBUG_LOG, 0, "read configuration %s",
conffile.c_str());
// create the Datasink object based on the configuration and prefs
if (0 == preferences.size()) {
preferences.push_back("debug");
}
meteo::DatasinkFactory dsf(preferences);
// install signal handlers
signal(SIGTERM, kill_child);
signal(SIGINT, kill_child);
signal(SIGHUP, kill_child);
// loop: fork a process and wait for it to die, exit if the child
// exits naturally
int status;
bool giveup = false;
do {
mdebug(LOG_DEBUG, MDEBUG_LOG, 0, "start loop");
// fork only if allowed to do so
if (allowfork)
clpid = fork();
else
clpid = 0;
// if the fork is not possible, we have some serious problem
if (clpid < 0) {
mdebug(LOG_CRIT, MDEBUG_LOG, MDEBUG_ERRNO,
"fork failed: %s", strerror(errno));
exit(EXIT_FAILURE);
}
// the child simply starts the loop
if (clpid == 0) {
if (allowfork)
mdebug(LOG_DEBUG, MDEBUG_LOG, 0,
"starting new child");
// reset signal dispositions so that child can easily
// be killed
signal(SIGHUP, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGINT, SIG_DFL);
// start looping
try {
mdebug(LOG_DEBUG, MDEBUG_LOG, 0,
"starting loop(%s)", station.c_str());
loop(station, mapfilename, xmloutlets);
mdebug(LOG_DEBUG, MDEBUG_LOG, 0,
"return from loop");
} catch (meteo::MeteoException& e) {
mdebug(LOG_ERR, MDEBUG_LOG, 0,
"MeteoException(%s, %s)",
e.getReason().c_str(),
e.getAddinfo().c_str());
// when we exit at this point, the parent
// process will fork a new child (if there is a
// a parent, that is), and it will know that we
// had a problem
exit(EXIT_FAILURE);
}
// exiting at this point means that for some reason loop
// ended without error. This should not really happen,
// but to tell the parent that something different happend
// we exit with EXIT_SUCCESS
exit(EXIT_SUCCESS);
} // end of child code
// here we wait for the child to terminate
if (waitpid(clpid, &status, 0) < 0) {
mdebug(LOG_ERR, MDEBUG_LOG, 0, "error during wait: %s",
strerror(errno));
} else {
// here we should be a bit more verbose, so that it
// becomes less difficult to find out what happened
// to the child
if (WIFEXITED(status)) {
mdebug(LOG_DEBUG, MDEBUG_LOG, 0,
"child %d exited with status %d",
clpid, WEXITSTATUS(status));
giveup = (WEXITSTATUS(status) == 0);
}
if (WIFSIGNALED(status)) {
mdebug(LOG_DEBUG, MDEBUG_LOG, 0,
"child %d killed by signal %d",
clpid, WTERMSIG(status));
}
if (WIFSTOPPED(status)) {
// this should definitely not happen, lets kill
// the process and start a new one
mdebug(LOG_DEBUG, MDEBUG_LOG, 0,
"child %d stopped by signal %d",
clpid, WSTOPSIG(status));
kill(clpid, SIGKILL);
}
mdebug(LOG_CRIT, MDEBUG_LOG, 0,
"child process died: %d", WEXITSTATUS(status));
}
// if there is a problem with the station, we should wait a
// few seconds so the station can recover from the problem.
// This also prevents meteopoll from looping.
mdebug(LOG_DEBUG, MDEBUG_LOG, 0, "sleeping for 3 seconds to "
"give station time to recover from error condition");
sleep(3);
} while (!giveup);
// child exited ok, so we do the same
exit(EXIT_SUCCESS);
}
// main(argc, argv) the main function is only needed as a wrapper to
// catch an Exception and print a nice error message
// on standard error (nothing is logged in this case
// as it is unlikely that logging has been initialized
// already
int main(int argc, char *argv[]) {
try {
meteopoll(argc, argv);
} catch (meteo::MeteoException& me) {
fprintf(stderr, "MeteoException in meteopoll: %s/%s\n",
me.getReason().c_str(), me.getAddinfo().c_str());
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
|
### 解题思路
l,r分别表示结果字符串中左右括号的数量。如果l==r==n,即字符串中左右括号的数量都为n,则改字符串为合法字符串,输出。其他分为两种情况:1)什么时候添加'(' ? 已有的字符串满足左右括号相等,并且左括号数l<n, 则添加'(' ; 2)什么时候添加')' ? 右括号数r<左括号数l。即逐个添加左括号和右括号。
### 代码
```python3
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
def f(l, r, s):
if l == r == n:
res.append(s)
if l < n:
f(l+1, r, s+'(')
if r < l:
f(l, r+1, s+')')
f(0, 0, '')
return res
```
|
'use client';
import Backdrop from '@mui/material/Backdrop';
import CircularProgress from '@mui/material/CircularProgress';
import { useEffect } from 'react';
import { useAppSelector } from '@redux/hooks';
function GlobalBackdrop() {
const disableTabKey = (event: KeyboardEvent) => {
if (event.key === 'Tab') {
event.preventDefault();
}
};
const statusState = useAppSelector((state) => state.status);
useEffect(() => {
if (statusState.isLoading)
document.addEventListener('keydown', disableTabKey);
return () => {
document.removeEventListener('keydown', disableTabKey);
};
}, [statusState.isLoading]);
return (
<Backdrop
open={statusState.isLoading}
sx={{ zIndex: (theme) => theme.zIndex.drawer + 1 }}
>
<CircularProgress color='primary' />
</Backdrop>
);
}
export default GlobalBackdrop;
|
//
// CoreDataManager.swift
// Cocktails
//
// Created by Владимир Ли on 19.04.2022.
//
import Foundation
import CoreData
class CoreDataManager {
static let shared = CoreDataManager()
private var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Cocktails")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
private var context: NSManagedObjectContext {
return persistentContainer.viewContext
}
private init() {}
func saveContext () {
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func saveFavorite(from cocktailData: CocktailData, ingredients: String?, completion: (Cocktail) -> Void){
guard let entityDescription = NSEntityDescription.entity(forEntityName: "Cocktail", in: context) else { return }
guard let cocktail = NSManagedObject(entity: entityDescription, insertInto: context) as? Cocktail else { return }
cocktail.title = cocktailData.title
cocktail.imageString = cocktailData.imageString
cocktail.alcoholic = cocktailData.alcoholic
cocktail.glass = cocktailData.glass
cocktail.ingredients = ingredients
cocktail.instruction = cocktailData.instruction
completion(cocktail)
saveContext()
}
func fetchData() -> [Cocktail] {
var cocktails: [Cocktail] = []
let fetchRequest: NSFetchRequest<Cocktail> = Cocktail.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "title", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
cocktails = try persistentContainer.viewContext.fetch(fetchRequest)
} catch let error {
print(error.localizedDescription)
}
return cocktails
}
func deleteFavorite(cocktail: Cocktail) {
context.delete(cocktail)
saveContext()
}
}
|
'use client'
import { useEffect, useState, useCallback, ForwardRefExoticComponent } from 'react'
import { CSSTransition } from 'react-transition-group'
import { useNotificationsStore } from '@/store/notificationsStore'
import { WarningCircle, CheckCircle, XCircle, X, IconProps } from '@phosphor-icons/react'
import { classNames } from '@/utils/index'
type Notification = {
id: string,
message: string,
type: 'success' | 'failure' | 'warning'
hasAutoClose?: boolean,
}
type NotificationProps = {
notification: Notification
}
type Icons = {
success: ForwardRefExoticComponent<IconProps>
failure: ForwardRefExoticComponent<IconProps>
warning: ForwardRefExoticComponent<IconProps>
}
const Notification = ({ notification }: NotificationProps) => {
const [shouldShow, setShouldShow] = useState(false)
const { id, type, message, hasAutoClose = true } = notification
const removeNotification = useNotificationsStore((state) => state.removeNotification)
const icons: Icons = {
success: CheckCircle,
failure: XCircle,
warning: WarningCircle,
}
const classes = {
success: 'bg-green-100',
failure: 'bg-red-100',
warning: 'bg-yellow-100',
}
const Icon = icons[type]
const className = classes[type]
const close = useCallback((id: string) => {
setShouldShow(false)
setTimeout(() => removeNotification(id), 300)
}, [removeNotification])
useEffect(() => {
setShouldShow(true)
}, [])
useEffect(() => {
if (! hasAutoClose) {
return
}
const timeoutId = setTimeout(() => {
close(id)
}, 3000)
return () => {
clearTimeout(timeoutId)
}
}, [id, close, hasAutoClose])
return (
<CSSTransition
in={shouldShow}
timeout={300}
classNames={{
enter: 'translate-x-full',
enterActive: 'translate-x-px transition duration-300',
enterDone: 'translate-x-px',
exitActive: 'translate-x-full transition duration-300',
exitDone: 'translate-x-full',
}}
>
<div
className={classNames(
'relative mb-2 last:mb-0',
'h-16 w-[400px] px-12',
'rounded-md text-sm',
'flex justify-center items-center',
'translate-x-full',
className
)}>
<Icon size={24} weight="bold" className="absolute top-1/2 -translate-y-1/2 left-4" />
<p>{message}</p>
<button onClick={() => close(id)} className="absolute top-1/2 -translate-y-1/2 right-4">
<X size={16} weight="bold" />
</button>
</div>
</CSSTransition>
)
}
export default Notification
|
import React, { useState } from 'react';
// import moment from 'moment';
import { useFormik } from 'formik';
import { Calendar as DatePicker } from 'react-date-range';
// import classNames from 'classnames';
import SubHeader, { SubHeaderRight, SubheaderSeparator } from '../../../layout/SubHeader/SubHeader';
import Button from '../../../components/bootstrap/Button';
import PageWrapper from '../../../layout/PageWrapper/PageWrapper';
import Page from '../../../layout/Page/Page';
import Card, {
CardActions,
CardBody,
CardHeader,
CardLabel,
CardTitle,
} from '../../../components/bootstrap/Card';
import Dropdown, {
DropdownItem,
DropdownMenu,
DropdownToggle,
} from '../../../components/bootstrap/Dropdown';
import Checks, { ChecksGroup } from '../../../components/bootstrap/forms/Checks';
import InputGroup, { InputGroupText } from '../../../components/bootstrap/forms/InputGroup';
import Input from '../../../components/bootstrap/forms/Input';
import FormGroup from '../../../components/bootstrap/forms/FormGroup';
import Label from '../../../components/bootstrap/forms/Label';
import CommonFilterTag from '../../_common/CommonFilterTag';
// import CommonTableRow from '../../_common/CommonTableRow';
import Select from '../../../components/bootstrap/forms/Select';
// import Popovers from '../../../components/bootstrap/Popovers';
import { layoutMenu } from '../../../menu';
import data from '../../../common/data/dummyProductData';
import PaginationButtons, {
dataPagination,
PER_COUNT,
} from '../../../components/PaginationButtons';
import useSortableData from '../../../hooks/useSortableData';
import useSelectTable from '../../../hooks/useSelectTable';
// import useDarkMode from '../../../hooks/useDarkMode';
import TableComponent from 'theme/pages/_common/TableComponent';
import Zone from '../../../assets/img/portalTable/zone.png';
import AddZoneModal from 'theme/components/AddZoneModal/AddZoneModal';
const Zones = () => {
// const { themeStatus, darkModeStatus } = useDarkMode();
// const [date, setDate] = useState<Date>(new Date());
const [filterMenu, setFilterMenu] = useState<boolean>(false);
const formik = useFormik({
initialValues: {
minPrice: '',
maxPrice: '',
categoryName: '3D Shapes',
companyA: true,
companyB: true,
companyC: true,
companyD: true,
},
onSubmit: (values) => {
setFilterMenu(false);
},
});
const filteredData = data.filter(
(f) =>
// Category
f.category === formik.values.categoryName &&
// Price
(formik.values.minPrice === '' || f.price > Number(formik.values.minPrice)) &&
(formik.values.maxPrice === '' || f.price < Number(formik.values.maxPrice)) &&
// Company
((formik.values.companyA ? f.store === 'Company A' : false) ||
(formik.values.companyB ? f.store === 'Company B' : false) ||
(formik.values.companyC ? f.store === 'Company C' : false) ||
(formik.values.companyD ? f.store === 'Company D' : false)),
);
const [currentPage, setCurrentPage] = useState<number>(1);
const [perPage, setPerPage] = useState<number>(PER_COUNT['10']);
const { items, requestSort, getClassNamesFor } = useSortableData(filteredData);
const onCurrentPageItems = dataPagination(items, currentPage, perPage);
const { selectTable, SelectAllCheck } = useSelectTable(onCurrentPageItems);
// Data
const dummyDataHeader = [
'Name',
'Type',
'Wear House',
'Racks',
'Units',
'Bins',
'Availability',
'Last Activity',
];
const dummyDataToShow = [
{
// id: 1,
name: 'John',
type: 'Storage',
wearHouse: 'Austin Texas',
racks: 8,
units: 10,
bins: 11,
availability: 221,
lastActivity: '10/10/2022',
},
{
// id: 2,
name: 'Marvos',
type: 'Storage',
wearHouse: 'Austin Texas',
racks: 9,
units: 10,
bins: 11,
availability: 221,
lastActivity: '10/10/2022',
},
{
// id: 3,
name: 'Carlous',
type: 'Storage',
wearHouse: 'Austin Texas',
racks: 10,
units: 10,
bins: 11,
availability: 221,
lastActivity: '10/10/2022',
},
{
// id: 4,
name: 'Mike',
type: 'Storage',
wearHouse: 'Austin Texas',
racks: 11,
units: 10,
bins: 11,
availability: 221,
lastActivity: '10/10/2022',
},
{
// id: 5,
name: 'Wick',
type: 'Storage',
wearHouse: 'Austin Texas',
racks: 12,
units: 10,
bins: 11,
availability: 221,
lastActivity: '10/10/2022',
},
];
// Delete Invitation ID
const handleDeleteZone = (value: any) => {
console.log("Delete Zone", value);
}
// Modal Dialog States
const [modalShow, setModalShow] = useState<boolean>(false);
const [currentData, setCurrentData] = useState<any>(null);
return (
<>
<AddZoneModal isOpen={modalShow} setIsOpen={setModalShow} />
<PageWrapper title={layoutMenu.zones.text}>
<SubHeader>
<SubHeaderRight>
{/* {(!!formik.values.minPrice || !!formik.values.maxPrice) && (
<CommonFilterTag
title='Price'
text={`${formik.values.minPrice || '0'} to ${
formik.values.maxPrice || 'no limit'
}`}
/>
)} */}
{!!formik.values.categoryName && (
<CommonFilterTag title='Category' text={formik.values.categoryName} />
)}
{(formik.values.companyA ||
formik.values.companyB ||
formik.values.companyC ||
formik.values.companyD) && (
<CommonFilterTag
title='Store'
text={
(formik.values.companyA ? 'Company A, ' : '') +
(formik.values.companyB ? 'Company B, ' : '') +
(formik.values.companyC ? 'Company C, ' : '') +
(formik.values.companyD ? 'Company D ' : '')
}
/>
)}
<SubheaderSeparator />
<Dropdown isOpen={filterMenu} setIsOpen={setFilterMenu}>
<DropdownToggle hasIcon={false}>
<Button icon='Filter' color='primary' isLight data-tour='filter'>
Filter
<span className='visually-hidden'>filter</span>
</Button>
</DropdownToggle>
<DropdownMenu
isAlignmentEnd
size='lg'
isCloseAfterLeave={false}
data-tour='filter-menu'>
<div className='container py-2'>
<form className='row g-3' onSubmit={formik.handleSubmit}>
<div className='col-12'>
<FormGroup>
<Label htmlFor='minPrice'>Price</Label>
<InputGroup>
<Input
id='minPrice'
ariaLabel='Minimum price'
placeholder='Min.'
onChange={formik.handleChange}
value={formik.values.minPrice}
/>
<InputGroupText>to</InputGroupText>
<Input
id='maxPrice'
ariaLabel='Maximum price'
placeholder='Max.'
onChange={formik.handleChange}
value={formik.values.maxPrice}
/>
</InputGroup>
</FormGroup>
</div>
<div className='col-12'>
<FormGroup>
<Label htmlFor='categoryName'>Category</Label>
<Select
id='categoryName'
ariaLabel='Category'
placeholder='Category Name'
list={[
{ value: '3D Shapes', text: '3D Shapes' },
{ value: 'Illustrator', text: 'Illustrator' },
{ value: 'Photo', text: 'Photo' },
]}
onChange={formik.handleChange}
value={formik.values.categoryName}
/>
</FormGroup>
</div>
<div className='col-12'>
<FormGroup>
<Label>Store</Label>
<ChecksGroup>
<Checks
id='companyA'
label='Company A'
onChange={formik.handleChange}
checked={formik.values.companyA}
/>
<Checks
id='companyB'
label='Company B'
onChange={formik.handleChange}
checked={formik.values.companyB}
/>
<Checks
id='companyC'
label='Company C'
onChange={formik.handleChange}
checked={formik.values.companyC}
/>
<Checks
id='companyD'
label='Company D'
onChange={formik.handleChange}
checked={formik.values.companyD}
/>
</ChecksGroup>
</FormGroup>
</div>
<div className='col-6'>
<Button
color='primary'
isOutline
className='w-100'
onClick={formik.resetForm}>
Reset
</Button>
</div>
<div className='col-6'>
<Button color='primary' className='w-100' type='submit'>
Filter
</Button>
</div>
</form>
</div>
</DropdownMenu>
</Dropdown>
</SubHeaderRight>
</SubHeader>
<Page>
<Card stretch data-tour='list'>
<CardHeader>
<CardLabel>
<CardTitle style={{ display: 'flex', alignItems: 'center' }}>
<img src={Zone} style={{ width: '28px', marginRight: '12px' }} alt='Zone' />
Zones{' '}
<small className='ms-2'>
Item:{' '}
{selectTable.values.selectedList.length
? `${selectTable.values.selectedList.length} / `
: null}
{filteredData.length}
</small>
</CardTitle>
</CardLabel>
<CardActions>
<Button
color='info'
icon='Add'
isLight
// tag='a'
// to='/somefile.txt'
// target='_blank'
// download
onClick={() => setModalShow(true)}>
Add
</Button>
<Dropdown isButtonGroup>
{/* <Popovers
desc={
<DatePicker
onChange={(item) => setDate(item)}
date={date}
color={process.env.REACT_APP_PRIMARY_COLOR}
/>
}
placement='bottom-end'
className='mw-100'
trigger='click'> */}
<Button color='success' isLight>
Latest
</Button>
{/* </Popovers> */}
<DropdownToggle>
<Button color='success' isLight />
</DropdownToggle>
<DropdownMenu isAlignmentEnd>
<DropdownItem>
<span>Last Hour</span>
</DropdownItem>
<DropdownItem>
<span>Last Day</span>
</DropdownItem>
<DropdownItem>
<span>Last Week</span>
</DropdownItem>
<DropdownItem>
<span>Last Month</span>
</DropdownItem>
</DropdownMenu>
</Dropdown>
{/* Extra Options */}
{/* <Dropdown className='d-inline'>
<DropdownToggle hasIcon={false}>
<Button color={themeStatus} icon='MoreHoriz' />
</DropdownToggle>
<DropdownMenu isAlignmentEnd>
<DropdownItem>
<Button icon='Edit'>Edit</Button>
</DropdownItem>
<DropdownItem>
<Button icon='Delete'>Delete</Button>
</DropdownItem>
</DropdownMenu>
</Dropdown> */}
</CardActions>
</CardHeader>
<CardBody className='table-responsive' isScrollable>
{/* <table className='table table-modern table-hover'>
<thead>
<tr>
<th scope='col'>{SelectAllCheck}</th>
<th
scope='col'
onClick={() => requestSort('id')}
className='cursor-pointer text-decoration-underline'>
#{' '}
<Icon size='lg' className={getClassNamesFor('id')} icon='FilterList' />
</th>
<th scope='col'>Name</th>
<th scope='col'>Type</th>
<th scope='col'>Wear House</th>
<th scope='col'>Racks</th>
<th scope='col'>Units</th>
<th scope='col'>Bins</th>
<th scope='col'>Availability</th>
<th scope='col'>Last Activity</th>
<th scope='col' className='text-center'>
Actions
</th>
</tr>
</thead>
<tbody>
{onCurrentPageItems.map((i) => (
<ZonesTable
key={i.id}
// eslint-disable-next-line react/jsx-props-no-spreading
{...i}
selectName='selectedList'
selectOnChange={selectTable.handleChange}
selectChecked={selectTable.values.selectedList.includes(
// @ts-ignore
i.id.toString(),
)}
/>
))}
</tbody>
</table> */}
<TableComponent
dummyDataHeader={dummyDataHeader}
dummyDataToShow={dummyDataToShow}
name='zones'
setModalShow={setModalShow}
setCurrentData={setCurrentData}
handleDeleteInvitation={handleDeleteZone}
/>
</CardBody>
<PaginationButtons
data={items}
label='items'
setCurrentPage={setCurrentPage}
currentPage={currentPage}
perPage={perPage}
setPerPage={setPerPage}
/>
</Card>
</Page>
</PageWrapper>
</>
);
};
export default Zones;
|
from sys import float_info
from avro.schema import (
RecordSchema,
PrimitiveSchema,
LogicalSchema,
ArraySchema,
UnionSchema,
)
from avro.name import Names
import avro_validator
from avro_validator.schema import Schema
import json
import pretty_errors
from rich.console import Console
import rich
from rich.panel import Panel
from runner import vrl
error_console = Console(stderr=True, style="bold red")
PRIMITIVE_FIELD_TYPE_MAPPING_ICEBERG_TO_AVRO = {
"boolean": "boolean",
"binary": "bytes",
"double": "double",
"float": "float",
"int": "int",
"long": "long",
"string": "string",
# "timestamp": "long",
}
PRIMITIVE_FIELD_TYPE_MAPPING_ICEBERG_TO_PY_TYPES = {
"boolean": (bool,),
"binary": (bytes,),
"double": (int, float,),
"float": (int, float,),
"int": (int,),
"long": (int, float),
"string": (str,),
"timestamp": (float, int,),
}
# LOGICAL_FIELD_TYPE_MAPPING = {
# "timestamp": ("timestamp-micros", "long")
# }
def iceberg_pretty_validator(datum, schema, *, path=""):
root = not path
# if root:
# rich.print("[bold white]Validating:")
# rich.print(datum, "\n")
print_path = (
f"[bold white]field [bold cyan]{path}[reset]"
if path
else "[bold white]root record[reset]"
)
if type(schema) == dict:
if datum is not None and type(datum) != dict:
error_console.print(
f"[bold red]Validation Error[reset]: {print_path} should be a [green]dict[reset]: not [red]{type(datum).__name__}"
)
rich.print(
Panel.fit(
f"{json.dumps(datum, indent=2)}",
title=f"{print_path.replace('field ', '')}",
)
)
return False
for k in set(datum.keys() if datum else {}) - set(schema.keys()):
if path == "" and k == "ts":
iceberg_pretty_validator(datum[k], "timestamp", path=".ts")
continue
v = datum[k]
if type(v) == dict:
extra_keys = vrl("""
keys = []
for_each(flatten!(.value)) -> |k, v| {{
keys = push(keys, k)
}}
keys
""", {"value": datum[k]})[1]
for ex_k in extra_keys:
error_console.print(f"[bold yellow]Warning: Extra key in datum: [reset][bold]: {path}.{k}.{ex_k}")
else:
error_console.print(f"[bold yellow]Warning: Extra key in datum: [reset][bold]: {path}.{k}")
return all(
[
iceberg_pretty_validator(
datum.get(k) if datum else None, v, path=f"{path}.{k}"
)
for k, v in schema.items()
]
)
elif type(schema) == list:
if datum and type(datum) != list:
error_console.print(
f"[bold red]Validation Error[reset]: {print_path} should be a [green]list[reset]: not [red]{type(datum).__name__}"
)
rich.print(
Panel.fit(
f"{json.dumps(datum, indent=2)}",
title=f"{print_path.replace('field ', '')}",
)
)
return False
return all(
[
iceberg_pretty_validator(item, schema[0], path=f"{path}.items[{i}]")
for i, item in enumerate(datum or [])
]
)
elif schema == "timestamp":
if (
datum
and not (
type(datum) == str
and (
datum.endswith("Z") or datum.startswith("20") or datum.startswith("19")
)
)
):
error_console.print(
f"[bold red]Validation Error[reset]: {print_path} should be a [green]timestamp (long)[reset]: not [red]{type(datum).__name__}"
)
rich.print(
Panel.fit(
f"{json.dumps(datum, indent=2)}",
title=f"{print_path.replace('field ', '')}",
)
)
return False
else:
if (
datum
and type(datum)
not in PRIMITIVE_FIELD_TYPE_MAPPING_ICEBERG_TO_PY_TYPES[schema]
):
pytypes = " | ".join(
[
t.__name__
for t in PRIMITIVE_FIELD_TYPE_MAPPING_ICEBERG_TO_PY_TYPES[schema]
]
)
error_console.print(
f"[bold red]Validation Error[reset]: {print_path} should be a [green]{pytypes}[reset]: not [red]{type(datum).__name__}"
)
rich.print(
Panel.fit(
f"{json.dumps(datum, indent=2)}",
title=f"{print_path.replace('field ', '')}",
)
)
return False
return True
def iceberg_to_avro_schema(schema, *, root=False, path="root"):
if type(schema) == dict:
def schema_to_field(s, k):
info = s.to_json()
return {"name": k, "type": info, "default": "null"}
# return Field(info, p, has_default = True, default = "null")
avro_schema = RecordSchema(
path,
"dddjjd",
names=Names(),
fields=[
schema_to_field(iceberg_to_avro_schema(v, path=f"{path}.{k}"), f"{k}")
for k, v in schema.items()
],
)
elif type(schema) == list:
avro_schema = ArraySchema(
items=iceberg_to_avro_schema(schema[0], path=f"{path}.items").to_json(),
)
elif schema == "timestamp":
avro_schema = TimestampMicrosSchema()
else:
avro_schema = PrimitiveSchema(
PRIMITIVE_FIELD_TYPE_MAPPING_ICEBERG_TO_AVRO[schema],
)
if not root:
return UnionSchema(
[PrimitiveSchema("null").to_json(), avro_schema.to_json()], names=Names()
)
return avro_schema
def validate_iceberg_schema(schema, test_records):
# avro_schema = iceberg_to_avro_schema(schema, root=True)
# avro_schema_json = avro_schema.to_json()
# validator = Schema(json.dumps(avro_schema_json)).parse()
results = []
for record in test_records:
# avro_validate_result = validator.validate(record)
# if avro_validate_result:
# assert avro_validate_result == iceberg_pretty_validator(record, schema)
res = iceberg_pretty_validator(record, schema)
if not res:
rich.print("\n❌ [bold white]Object failed validation:")
rich.print(record, "\n")
results.append(res)
return all(results)
# validate_iceberg_schema(
# {"john": {"blake": "integer", "cherry": "string"}},
# [
# {"john": {"blake": 2}},
# {"john": {"blake": 2.0}},
# {"john": {"blake": "2", "cherry": 1, "hane": 1}},
# {"john": {"blake": {"john": {"blake": "2"}}}},
# ],
# )
|
<template>
<Navbar />
<section class="">
<div v-if="success" class="text-center my-5">
<span class="mb-5"> Vous êtes connecté ! </span>
</div>
<div class="flex flex-col items-center justify-center px-6 py-16 mx-auto">
<div
class="w-full rounded-lg shadow border-2 md:mt-0 sm:max-w-xs xl:p-0 dark:bg-gray-950 dark:border-gray-960"
>
<div class="p-6 space-y-4 md:space-y-6 sm:p-8">
<h1
class="text-lg font-bold leading-tight tracking-tight text-white md:text-2xl dark:text-white"
>
Connexion
</h1>
<div class="space-y-4 md:space-y-6">
<div>
<label
for="email"
class="block mb-2 text-xs font-medium text-white dark:text-white"
>Votre email</label
>
<input
type="email"
name="email"
v-model="email"
id="email"
class="border border-gray-960 text-gray-950 sm:text-xs rounded-lg block w-full p-1.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-gray-960 dark:focus:border-gray-960"
placeholder="nom@compagnie.com"
/><!--Mettre 'required=""' a gauche au besoin -->
</div>
<div>
<label
for="password"
class="block mb-2 text-xs font-medium text-white dark:text-white"
>Mot de passe</label
>
<input
type="password"
name="password"
v-model="password"
id="password"
placeholder="••••••••"
class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-xs rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-1.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
/><!--Mettre 'required=""' a gauche au besoin -->
</div>
<div class="flex flex-col">
<div class="flex flex-col items-center justify-between">
<div class="flex items-center h-5 mb-2">
<input
id="remember"
aria-describedby="remember"
type="checkbox"
class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-primary-600 dark:ring-offset-gray-800"
/><!--Mettre 'required=""' a gauche au besoin -->
<label
for="remember"
class="text-gray-300 dark:text-gray-300 ml-3 text-xs"
>Se souvenir de moi</label
>
</div>
<a
href="forgot-password"
class="text-xs font-medium text-primary-600 text-gray-300 hover:underline dark:text-primary-500 mb-2"
>Mot de passe oublié?</a
>
</div>
<Button
@click="login"
type="submit"
:class="{ shake: disabled }"
class="w-1/2 bg-gray-500 mx-auto my-2"
>
Connexion
</Button>
<span v-if="error" class="text-red-700 text-center"
>{{ error }}!</span
>
<span v-if="disabled" class="text-red-700"
>Veuillez remplir les champs !</span
>
<div
class="text-xs font-light text-gray-200 dark:text-gray-400 text-center mt-3"
>
Vous n'avez pas encore de compte?
<a
href="/inscription"
class="font-medium text-primary-600 hover:underline dark:text-primary-500"
>Inscription</a
>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
import Button from "./Button.vue";
import Navbar from "./Navbar.vue";
export default {
name: "Connexion",
components: { Button, Navbar },
data() {
return {
email: "",
password: "",
disabled: false,
error: "",
user: "",
remember: false,
success: "",
};
},
methods: {
login() {
this.error = "";
if (!this.email || !this.password) {
return this.warnDisabled();
} else {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Accept", "application/json");
var urlencoded = new URLSearchParams();
urlencoded.append("email", this.email);
urlencoded.append("password", this.password);
var requestOptions = {
method: "POST",
headers: myHeaders,
body: urlencoded,
redirect: "follow",
};
fetch("http://localhost:8000/api/login", requestOptions)
.then((response) => response.json())
.then((data) => {
if (data.error) {
this.error = "Email ou Password incorrect !";
} else {
this.success = true;
if (this.remember) {
localStorage.setItem("user", JSON.stringify(data.user));
localStorage.setItem("token", data.token);
this.user = JSON.parse(localStorage.getItem("user"));
this.logged = !this.logged;
} else {
sessionStorage.setItem("user", JSON.stringify(data.user));
sessionStorage.setItem("token", data.token);
this.user = JSON.parse(sessionStorage.getItem("user"));
this.logged = !this.logged;
}
this.email = "";
this.password = "";
this.remember = true;
setTimeout(() => {
window.location.href = "/";
}, 2000);
}
})
.catch((error) => console.log("error", error));
}
},
warnDisabled() {
this.disabled = true;
setTimeout(() => {
this.disabled = false;
}, 1500);
},
},
};
</script>
<style>
.shake {
animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
transform: translate3d(0, 0, 0);
}
@keyframes shake {
10%,
90% {
transform: translate3d(-1px, 0, 0);
}
20%,
80% {
transform: translate3d(2px, 0, 0);
}
30%,
50%,
70% {
transform: translate3d(-4px, 0, 0);
}
40%,
60% {
transform: translate3d(4px, 0, 0);
}
}
</style>
|
"""egrub URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/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 path, include
from django.conf import settings
from django.conf.urls.static import static
from customers.views import IndexPage, AboutPage, Order, ConfirmOrder, ConfirmOrderPayment, MenuList, SearchMenuList
from restaurant.views import StaffDashboard, OrderInformation
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('', IndexPage.as_view(), name='index'),
path('about/', AboutPage.as_view(), name='about'),
path('menu-list/', MenuList.as_view(), name='menu-list'),
path('search-menu-list/', SearchMenuList.as_view(), name='search-menu-list'),
path('order/', Order.as_view(), name='order'),
path('order-confirm/<int:pk>', ConfirmOrder.as_view(), name='order-confirm'),
path('confirm-order-payment/', ConfirmOrderPayment.as_view(), name='confirm-order-payment'),
path('dashboard/', StaffDashboard.as_view(), name='dashboard'),
path('orders/<int:pk>/', OrderInformation.as_view(), name='order-information'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
module;
#include <filesystem>
// #include <stacktrace>
#include <string_view>
#include <utility>
#include <defines.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>
export module logger;
export namespace logger
{
using level = spdlog::level::level_enum;
class Logger
{
template<level lvl, typename... Args>
friend void log(std::string_view const& msg, Args&&... args);
public:
static auto get() -> std::shared_ptr<spdlog::logger> const& { return m_logger; }
private:
static void log(std::string_view msg,
spdlog::level::level_enum level,
char const* file,
int line)
{
constexpr size_t kRootDirPathLength =
std::string_view(ROOT_SOURCE_DIR).length() + 1;
m_logger->log(
spdlog::source_loc { file + kRootDirPathLength, line, "hi" },
level,
msg
);
}
static auto create() -> std::shared_ptr<spdlog::logger>;
inline static std::shared_ptr<spdlog::logger> const m_logger { create() };
};
template<level lvl, typename... Args>
ALWAYS_INLINE void log(std::string_view const& msg, Args&&... args)
{
if constexpr (lvl >= SPDLOG_ACTIVE_LEVEL)
{
// auto const stacktrace = std::stacktrace::current()[0];
Logger::log(
fmt::vformat(msg, fmt::make_format_args(std::forward<Args>(args)...)),
lvl,
"",
0);
}
}
template<typename... Args>
ALWAYS_INLINE void trace(std::string_view const& msg, Args&&... args)
{
log<level::trace>(msg, std::forward<Args>(args)...);
}
template<typename... Args>
ALWAYS_INLINE void debug(std::string_view const& msg, Args&&... args)
{
log<level::debug>(msg, std::forward<Args>(args)...);
}
template<typename... Args>
ALWAYS_INLINE void info(std::string_view const& msg, Args&&... args)
{
log<level::info>(msg, std::forward<Args>(args)...);
}
template<typename... Args>
ALWAYS_INLINE void warn(std::string_view const& msg, Args&&... args)
{
log<level::warn>(msg, std::forward<Args>(args)...);
}
template<typename... Args>
ALWAYS_INLINE void error(std::string_view const& msg, Args&&... args)
{
log<level::err>(msg, std::forward<Args>(args)...);
}
template<typename... Args>
ALWAYS_INLINE void critical(std::string_view const& msg, Args&&... args)
{
log<level::critical>(msg, std::forward<Args>(args)...);
}
auto Logger::create() -> std::shared_ptr<spdlog::logger>
{
using namespace std::chrono_literals;
auto logFilePath { std::filesystem::current_path() / "playground.log" };
spdlog::level::level_enum level { SPDLOG_ACTIVE_LEVEL };
std::vector<spdlog::sink_ptr> sinks {
std::make_shared<spdlog::sinks::stdout_color_sink_mt>(),
std::make_shared<spdlog::sinks::basic_file_sink_mt>(logFilePath.string(),
true)
};
for (auto& sink : sinks)
{
#ifdef NDEBUG
sink->set_pattern("%^[%l] [%r]: %v%$");
#else
sink->set_pattern("%^[%l] [%r] %@: %v%$");
#endif
}
auto logger =
std::make_shared<spdlog::logger>("MAIN", sinks.begin(), sinks.end());
spdlog::register_logger(m_logger);
logger->set_level(level);
spdlog::flush_every(2s);
return logger;
}
} // namespace logger
|
import React, {useEffect, useState} from 'react'
import { css, Theme } from '@emotion/react'
import { Button } from '../'
export interface IProps {
onChange?: Function
active: boolean
className?: string
}
const ButtonCss = (theme: Theme) => css`
z-index: 11;
& > div {
padding: 0;
.line-wrap {
transition: transform .3s;
width: 32px;
height: 20px;
span {
transition: transform .3s;
background-color: ${theme.color.text};
font-size: 0;
text-indent: -9999px;
height: 3px;
}
}
}
&.on {
& > div {
padding: 0;
.line-wrap {
transform: rotate(-180deg);
span {
&:nth-of-type(1) {
transform: translateY(8.5px) rotate(60deg);
}
&:nth-of-type(2) {
transform: rotate(360deg);
}
&:nth-of-type(3) {
transform: translateY(-8.5px) rotate(-60deg);
}
}
}
}
}
`
const NavButton: React.FC<IProps> = (props) => {
const [active, setActive] = useState<boolean>(props.active)
const useActive = () => {
if (props.active !== active) {
setActive(props.active)
}
}
const onNavButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault()
props.onChange?.(!active)
setActive(!active)
}
useEffect(useActive, [props.active])
return (
<Button
text
onClick={onNavButtonClick}
css={ButtonCss}
className={`${active ? 'on' : ''} ${props.className || ''}`}
>
<div className="d-flex line-wrap dir-column flex-wrap jc-space-between">
<span className="fill width">line</span>
<span className="fill width">line</span>
<span className="fill width">line</span>
</div>
</Button>
)
}
export default NavButton
|
import mongoose, { Document, Schema } from "mongoose";
export interface IUser extends Document {
username: string;
email: string;
profile_image: string;
about: string;
display_name: string;
}
const userSchema = new Schema<IUser>(
{
username: {
type: String,
},
email: {
type: String,
required: true,
unique: true,
},
profile_image: {
type: String,
},
about: {
type: String,
},
display_name: {
type: String,
},
},
{
timestamps: true,
}
);
const User = mongoose.model<IUser>("User", userSchema);
export default User;
|
public void start(Stage stage) throws Exception{
// parent layout
BorderPane bp = new BorderPane();
bp.setMinSize(500,300);
// child layout(1)
VBox vb = new VBox();
vb.setMinHeight(80);
vb.setMinWidth(Region.USE_COMPUTED_SIZE);
vb.setStyle("-fx-border-color:black;-fx-border-width:0 0 1 0");
// child layout(2)
VBox vb2 = new VBox();
vb2.setMinHeight(Region.USE_COMPUTED_SIZE);
vb2.setMinWidth(Region.USE_COMPUTED_SIZE);
vb2.setAlignment(Pos.CENTER);
vb2.setSpacing(20);
vb2.setStyle("-fx-border-color:red;-fx-background-color:#D4F2FC");
// node 1: user name
TextField tf = new TextField("User Name");
tf.setMaxWidth(200);
tf.setAlignment(Pos.CENTER);
// node 2: password
TextField tf2 = new TextField("Password");
tf2.setMaxWidth(200);
tf2.setAlignment(Pos.CENTER);
// node 3: parameter showing success or failed message
Label lb = new Label();
// node 4: Submit Button
Button btn = new Button("Sumbit");
btn.setAlignment(Pos.CENTER);
btn.setOnAction(e-> showLabel(tf, tf2,lb));
// Main Scene
Scene sc = new Scene(bp);
// connecting layout and nodes with scene
vb2.getChildren().addAll(tf,tf2,btn,lb);
bp.setTop(vb);
bp.setCenter(vb2);
// showing stage title, scene
stage.setTitle("Login Application");
stage.setScene(sc);
stage.show();
}
void showLabel(TextField usr, TextField pas, Label lbl){
String user = usr.getText();
String pass = pas.getText();
if(user.equals("Fahad") && pass.equals("1234")) {
lbl.setText("Success!!!");
}
else{
lbl.setText("Failed!!!");
}
}
|
<template>
<div class="schedule-container">
<div class="schedule-type-container">
<div class="schedule-type" :class="{active: (nowTap === tap?true:false)}" v-for="tap in nav" @click="tapChange(tap)">{{ tap.name }}</div>
</div>
<div class="schdule-contents-container">
<div class="contents" v-for="day,index in dayList">
<h1 class="date">DAY {{ index+1 }} </h1> <p class="description"> {{ DateToStringFormat1(setDate(startDate,index)) }}</p>
<div class="plan" v-for="plan,index2 in dailyScheduleList[index]" @click="goDetailPage(plan)" >
<PlanItem v-if="nowTap['type']==='' || nowTap['type'] === dailyScheduleList[index][index2]['type'] " v-model="dailyScheduleList[index][index2]"/>
</div>
</div>
</div>
</div>
<div class="create-container">
<div v-if="nowTap.name !== '전체'" class="create-botton">
<span class="plus-button green">
<font-awesome-icon icon="fa-solid fa-plus" id="plus-button-img" @click="createPlan(nowTap.type)" />
</span>
</div>
</div>
</template>
<style lang="scss" scoped>
.schedule-container{
display: flex;
flex-direction: row;
height: 100%;
overflow: hidden;
.schedule-type-container{
max-width:100px;
height: 100%;
margin:0.3rem;
.schedule-type{
cursor: pointer;
padding-top: 1rem;
margin: auto;
margin-bottom: 1rem;
height: 3.8rem;
font-size:2rem;
}
div.active{
color: $orange;
}
}
.schdule-contents-container{
width:100%;
height: 100%;
overflow-y: auto;
padding:1rem;
flex: 1;
.contents{
// padding:2vh;
padding-right:0px;
padding-top:0px;
.date{
margin-left:1rem;
margin-right:0.8rem;
}
.plan{
margin-bottom: 2rem;
}
h1{
font-size:2.5rem;
display: inline;
}
p{
font-size: 1.4rem;
display: inline;
}
}
}
}
.create-container{
position:relative;
width: 100%;
bottom:0rem;
left: 0px;
margin: auto;
text-align: center;
display: flex;
justify-content: center;
.create-botton{
position:absolute;
bottom:-0.5rem;
cursor: pointer;
margin:auto;
}
}
.description{
color:gray;
}
</style>
<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { storeToRefs } from "pinia";
import { useScheduleStore } from "../../../stores/plan/schedule";
import { useTravelStore } from "../../../stores/travel";
import { DateToStringFormat1 } from "../../../composable/util";
import { computed } from "@vue/reactivity";
import PlanItem from "../../../components/PlanItem.vue";
import { useMapStore } from "../../../stores/map";
import { useBookStore } from "../../../stores/plan/book";
const route = useRoute();
const router = useRouter();
const scheduleStore = useScheduleStore();
const travelStore = useTravelStore();
const mapStore = useMapStore()
const bookStore =useBookStore()
//contents
const travelId = computed(()=>route.params.id)
const nowTap = ref({});
const tapChange = (tap)=>{
nowTap.value = tap
}
const nav = computed(()=>bookStore.nav)
const startDate = computed(()=>new Date(travelStore.travel.startDate.split('T')[0]))
const dayList = computed(()=>travelStore.dayList)
const dailyScheduleList = computed(()=>scheduleStore.dailyScheduleList)
const createPlan = (type)=>{
router.push({
name: 'book-detail',
params:{
id : travelId.value,
planType:type,
planId:'register'
}
})
}
const setDate = (date,index)=>{
const newDate = new Date(date)
newDate.setDate(date.getDate()+index)
return newDate
}
const goDetailPage = (plan)=>{
router.push({
name:'book-detail',
params:{
id : travelId.value,
planId : plan.id,
planType:plan.type
}
})
}
const setDailyMarkerList = ()=>{
// mapStore.setDailyMarkerList(dailyScheduleList.value)
}
onMounted(async() => {
console.log("Mounted!");
await scheduleStore.getscheduleList(travelId.value)
setDailyMarkerList()
nowTap.value = nav.value[0]
});
</script>
|
@extends('layouts.template')
@section('title', 'Book List-')
@section('content')
<div class="mt-4 p-5 bg-black text-white rounded">
<h1>All Books Data</h1>
</div>
@if (session()->has('success'))
<div class="alert alert-success mt-4">
{{ session()->get('success') }}
</div>
@endif
<div class="container mt-5">
<div><a href="{{ route('books.create', $books) }}" class="btn btn-outline-success btn-lg">Input Data</a></div><br>
<table class="table table-bordered mb-5">
<thead>
<tr class="table-success">
<th scope="col">ISBN</th>
<th scope="col">Judul</th>
<th scope="col">Halaman</th>
<th scope="col">Kategori</th>
<th scope="col">Penerbit</th>
<th scope="col">Created At</th>
<th scope="col">Updated At</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@forelse ($books as $book)
<tr>
<th scope="row">{{ $book->isbn }}</th>
<td><a href="{{ route('books.show', $book) }}">
{{ $book->judul }}
</a></td>
<td>{{ $book->halaman }}</td>
<td>{{ $book->kategori }}</td>
<td>{{ $book->penerbit }}</td>
<td>{{ $book->created_at }}</td>
<td>{{ $book->updated_at }}</td>
<td>
<a href="{{ route('books.edit', $book) }}" class="btn btn-primary btn-sm">
Edit
</a>
<form action="{{ route('books.destroy', $book) }}" method="POST" class="d-inline-block">
@method('DELETE')
@csrf
<button type="submit" class="btn btn-danger btn-sm"
onclick="return confirm('Are you sure?')">Delete
</button>
</form>
</td>
</tr>
@empty
<tr>
<td colspan="6">No books found.</td>
</tr>
@endforelse
</tbody>
</table>
<div class="d-flex justify-content-center">
{!! $books->links() !!}
</div>
</div>
@endsection
|
import React, { Component } from 'react'
import API_CONFIG from '../../api'
import axios from 'axios'
import './Topic.css'
class Topic extends Component {
constructor (props) {
super(props);
this.state = {
res: {
title: '加载中',
content: '加载中',
reply_count: 0,
replies: []
}
}
}
fetchTopic = () => {
axios.get(`${API_CONFIG.topicDetail}${this.props.match.params.id}`)
.then(res => {
if( res.data.success ) {
// console.log(res.data.data)
this.setState({res: res.data.data});
}
})
.catch(e => {
this.props.history.replace('/');
});
}
componentDidMount () {
this.fetchTopic()
}
render() {
var repos = this.state.res.replies;
var repoList = repos.map(function (item, index) {
return (
<li key={item.id}>
<div className="authorAvatar">
<img src={item.author.avatar_url} alt="头像"/>
</div>
<div className="authorName">{item.author.loginname}</div>
<div className="replyContent markdown-body" dangerouslySetInnerHTML={{__html: item.content}}></div>
</li>
);
});
return (
<section className="topic">
<div className="content">
<h1>{this.state.res.title}</h1>
<div className="markdown-body" dangerouslySetInnerHTML={{__html: this.state.res.content}}></div>
</div>
<div className="comment">
<div className="reply-count">{ this.state.res.reply_count } 回复</div>
<ul>{repoList}</ul>
</div>
</section>
)
}
}
export default Topic;
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:leafcare/src/presentation/views/camera/bloc/camera_bloc.dart';
import 'package:leafcare/src/presentation/views/camera/camera.dart';
import 'package:leafcare/src/presentation/views/home/bloc/home_bloc.dart';
import 'package:leafcare/src/presentation/views/home/home.dart';
import 'package:leafcare/src/presentation/views/predict/bloc/predict_bloc.dart';
import 'package:leafcare/src/presentation/views/predict/predict_page.dart';
import 'package:leafcare/src/presentation/views/settings/bloc/settings_bloc.dart';
import 'package:leafcare/src/presentation/views/settings/settings_page.dart';
import 'package:leafcare/src/utils/constants.dart';
class AppRouter {
static List<AppRoute> routes() => [
AppRoute(
route: AppRouteStrings.home,
view: const HomePage(),
bloc: BlocProvider(
create: (context) => HomeBloc(),
),
),
AppRoute(
route: AppRouteStrings.camera,
view: const CameraPage(),
bloc: BlocProvider(
create: (context) => CameraBloc(),
),
),
AppRoute(
route: AppRouteStrings.predict,
view: const PredictionPage(),
bloc: BlocProvider(
create: (context) => PredictBloc(),
),
),
AppRoute(
route: AppRouteStrings.settings,
view: const SettingsPage(),
bloc: BlocProvider(
create: (context) => SettingsBloc(),
),
)
];
static MaterialPageRoute onGenerateRoute(RouteSettings settings) {
if (settings.name != null) {
var results = routes().where((element) => element.route == settings.name);
if (results.isNotEmpty) {
return MaterialPageRoute(builder: (context) => results.first.view);
}
return MaterialPageRoute(builder: (context) => const BadRoute());
}
return MaterialPageRoute(builder: (context) => const BadRoute());
}
static allBlocProviders() {
List blocProviders = [];
for (var i in routes()) {
blocProviders.add(i.bloc);
}
return blocProviders;
}
}
class BadRoute extends StatelessWidget {
const BadRoute({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: 500,
width: 375.w,
child: Column(
children: [
const Text('Something went wrong!'),
GestureDetector(
onTap: () {
Navigator.pushReplacementNamed(context, AppRouteStrings.home);
},
child: Container(
height: 45.h,
width: 180.w,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(15),
),
child: const Center(
child: Text('Back to Home'),
),
),
),
],
),
),
);
}
}
class AppRoute {
String route;
Widget view;
dynamic bloc;
AppRoute({
required this.route,
required this.view,
required this.bloc,
});
}
|
<?php
namespace HolidayLink\Core;
use GuzzleHttp;
use GuzzleHttp\Exception\RequestException;
/**
* Class GuzzleHttpConnection
* @package HolidayLink\Core
*/
class GuzzleHttpConnection {
/**
* @var GuzzleHttpConnection
*/
private $client;
/**
* Supported request methods
*
* @var array
*/
private $requestMethods = [
'GET' => 'get',
'POST' => 'post',
'PUT' => 'put',
'DELETE' => 'delete',
];
/**
* GuzzleHttpConnection constructor.
*/
public function __construct() {
$this->client = new GuzzleHttp\Client();
}
/**
* Execute guzzle method
*
* @param $url
* @param $method
*
* @return bool
* @throws \Exception
*/
public function execute ($url, $method, $headers) {
if (!array_key_exists($method, $this->requestMethods)) {
throw new \Exception('Undefined method');
}
try {
$options = array_merge([
'headers' => $headers['headers'],
'verify' => false,
],
array_key_exists('data', $headers) ? $headers['data'] : []
);
$request = $this->client->createRequest($this->requestMethods[$method], $url, $options);
$response = $this->client->send($request);
} catch (RequestException $e) {
echo $e->getRequest() . "\n";
if ($e->hasResponse()) {
echo $e->getResponse() . "\n";
}
return false;
}
return $response;
}
}
|
<!DOCTYPE html>
<head>
<title>Titulo Elementos</title>
<meta charset="utf-8">
<link rel="icon" href="./images/favicon.png">
</head>
<html>
<body>
<h2>Encontrando Elementos HTML mediante document.images</h2>
<img src="https://www.w3schools.com/js/pic_htmltree.gif" width="486" height="266">
<img src="https://www.w3schools.com/js/pic_navigate.gif" width="362" height="255">
<p id="demo"></p>
<p id="imagen"></p>
<hr>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<hr>
<div id="div1">
<p id="h1">hijo 1</p>
<p id="h2">hijo 2</p>
<p id="h3">hijo 3</p>
</div>
<hr>
<p id="nodos"></p>
<script>
document.getElementById("demo").innerHTML =
"Number of images: " + document.images.length;
document.getElementById("imagen").innerHTML =
"Imagen 1 -> " + document.images[0].src;
document.getElementById("p1").innerHTML = document.documentElement.firstChild.textContent;
document.getElementById("p2").innerHTML = document.head.textContent;
document.getElementById("p3").innerHTML = document.body.lastChild.innerHTML;
let elemento = document.getElementById('div1');
document.getElementById("nodos").innerHTML = elemento.childNodes.length;
if (elemento.hasChildNodes){
//document.write(elemento.firstElementChild.textContent);
//document.write(elemento.childNodes[3].textContent);
//document.write(elemento.lastElementChild.textContent);
for (let i = 0; i< elemento.childNodes.length; i++){
if (elemento.childNodes[i].textContent){
document.write(elemento.childNodes[i].textContent)
}
}
}
//document.write(elemento.firstChild.innerHTML);
//if (elemento.hasChildNodes()){
// document.write(elemento.length)
//}
</script>
</body>
</html>
|
#include "headers.h"
int main() {
srand(static_cast<unsigned>(time(NULL)));
int option = -1;
list<Process> processes;
createNamedProcess(processes, "P1", 0, 10, 3);
createNamedProcess(processes, "P2", 1, 1, 1);
createNamedProcess(processes, "P3", 2, 2, 3);
createNamedProcess(processes, "P4", 3, 1, 4);
createNamedProcess(processes, "P5", 4, 5, 2);
clearConsole();
while (option != 0) {
cout << "\033[34mProcess scheduler Simulator\033[0m" << endl;
cout << "0 - Exit" << endl;
cout << "1 - List Processes" << endl;
cout << "2 - FCFS - First Come First Served" << endl;
cout << "3 - SJF - Shortest Job First" << endl;
cout << "4 - Prioridades" << endl;
cout << "5 - RR" << endl;
cout << "\033[34mChoose an option >\033[0m ";
cin >> option;
clearConsole();
switch (option) {
case 1:
printProcesses(processes);
break;
case 2:
runFCFS(processes);
break;
case 3:
runSJF(processes);
break;
case 4:
runPriorities(processes);
break;
case 5:
runRoundRobin(processes);
break;
case 0:
cout << "\033[1;32mExiting...\033[0m" << endl;
break;
default:
cout << "\033[1;31mERROR: Choose a valid option\033[0m" << endl;
break;
}
}
return 0;
}
|
{% extends 'base.html.twig' %}
{% block title %}Le café{% endblock %}
{% block body %}
<div class="container d-flex flex-column align-items-center">
<span class="d-flex align-items-center min-vh-100">
<video class="rounded-circle" muted autoplay preload="auto" loop>
<source src="{{ asset('build/images/sm-Coffee.mp4') }}" type="video/mp4" media="all and (max-width:768px)">
<source src="{{ asset('build/images/Coffee.mp4') }}" type="video/mp4"/>
</video>
</span>
<div class="container my-5 reveal">
<div class="row my-5" id="carousel">
<div class="col-12">
<h3>Costa Rica</h3>
<img src="{{ asset('build/images/coffee-costa-rica.jpg') }}" alt="image costa rica" style="height: 10rem;"/>
</div>
<div class="col-12">
<h3>Ethiopie</h3>
<img src="{{ asset('build/images/coffee-ethiopie.jpg') }}" alt="image ethiopie" style="height: 10rem;"/>
</div>
<div class="col-12">
<h3>Nicaragua</h3>
<img src="{{ asset('build/images/coffee-nicaragua.jpg') }}" alt="image nicaragua" style="height: 10rem;"/>
</div>
<div class="col-12">
<h3>Brésil</h3>
<img src="{{ asset('build/images/coffee-bresil.jpg') }}" alt="image brésil" style="height: 10rem;"/>
</div>
<div class="col-12">
<h3>Kenya</h3>
<img src="{{ asset('build/images/coffee-kenya.jpg') }}" alt="image kenya" style="height: 10rem;"/>
</div>
<div class="col-12">
<h3>Colombie</h3>
<img src="{{ asset('build/images/coffee-colombia.jpg') }}" alt="image colombie" style="height: 10rem;"/>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js" integrity="sha512-XtmMtDEcNz2j7ekrtHvOVR4iwwaD6o/FUJe6+Zq+HgcCsk3kj4uSQQR8weQ2QVj1o0Pk6PwYLohm206ZzNfubg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
$('#carousel').slick({
autoplay: true,
dots: false,
infinite: true,
arrows: true,
slidesToShow: 5,
slidesToScroll: 1,
centerPadding: '20px',
rows: 0,
responsive: [
{
breakpoint: 992,
settings: {
arrows: true,
centerPadding: '20px',
slidesToShow: 3
}
},
{
breakpoint: 768,
settings: {
arrows: false,
centerPadding: '20px',
slidesToShow: 2
}
},
{
breakpoint: 480,
settings: {
arrows: false,
centerPadding: '20px',
slidesToShow: 1
}
}
]
});
</script>
<script type="text/javascript">
const ratio = 0.5
var options = {
root: null,
rootMargin: '0px',
threshold: ratio
}
const handleIntersect = function(entries, observer) {
console.log(entries);
entries.forEach(entry => {
//quand l'élément est visible
if (entry.intersectionRatio > ratio) {
entry.target.classList.add('reveal-visible');
//désactiver l'observer pour ne pas répéter l'animation plusieurs fois
observer.unobserve(entry.target)
}
/*si on souhaite relancer l'animation à chaque passage, on peut utiliser
un else ici exécuter du code lorsque l'élément devient invisible*/
})
}
var observer = new IntersectionObserver(handleIntersect, options);
observer.observe(document.querySelector('.reveal'));
//Si on souhaite utiliser la classe sur plusieurs élément
/* document.querySelectorAll('.reveal').forEach(function (r) {
observer.observe(r);
)} */
</script>
{% endblock %}
|
<template>
<div>
<f-button type="primary" @click="restart">restart</f-button>
<div class="mt-15" flex="cross:center">
<div style="font-size: 18px; color: #1a5cff; width: 120px; margin-right: 16px">
<f-count-to
ref="countTo1"
:start-val="startVal"
:end-val="endVal"
:duration="3000"
></f-count-to>
</div>
<div style="font-size: 18px; color: #1a5cff; width: 120px; margin-right: 16px">
<f-count-to
ref="countTo2"
:start-val="startVal"
:end-val="endVal"
:duration="3000"
:decimals="2"
></f-count-to>
</div>
<div style="font-size: 18px; color: #1a5cff; width: 120px; margin-right: 16px">
<f-count-to
ref="countTo3"
:start-val="startVal"
:end-val="endVal"
:duration="3000"
separator=""
></f-count-to>
</div>
<div style="font-size: 18px; color: #1a5cff; width: 120px; margin-right: 16px">
<f-count-to
ref="countTo4"
:start-val="startVal"
:end-val="endVal"
:duration="3000"
prefix="$"
suffix="美金"
></f-count-to>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const startVal = ref(0)
const endVal = ref(2023)
const countTo1 = ref(null)
const countTo2 = ref(null)
const countTo3 = ref(null)
const countTo4 = ref(null)
function restart() {
countTo1.value?.restart()
countTo2.value?.restart()
countTo3.value?.restart()
countTo4.value?.restart()
}
</script>
|
package com.antonelli.activeone.di
import android.content.Context
import com.antonelli.activeone.repository.AuthRepository
import com.antonelli.activeone.repository.AuthRepositoryImpl
import com.antonelli.activeone.repository.LogInRepository
import com.antonelli.activeone.repository.LogInRepositoryImp
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
@Singleton
@Provides
fun provideAuthRepository(@ApplicationContext context: Context): AuthRepository {
return AuthRepositoryImpl(context)
}
@Provides
fun providesLoginRepo(authRepository: AuthRepository): LogInRepository {
return LogInRepositoryImp(authRepository)
}
}
|
const DestinasiWisata = require("../models/destinasiwisata");
const KategoriDestinasi = require("../models/kategoridestinasi");
const DesaWisata = require("../models/desawisata");
const fs = require("fs");
const path = require("path");
const slugify = require('slugify');
const { Op } = require("sequelize")
exports.postDestinasiWisata = async (req, res) => {
try {
const { nama, deskripsi, id_kategoridestinasi, id_desawisata } = req.body;
// cek apakah ada gambar di upload
const gambar = req.file ? req.file.filename : null;
let slug = slugify(nama, { lower: true, strict: true });
let uniqueSlug = slug;
let count = 1;
while (await DestinasiWisata.findOne({ where: { slug: uniqueSlug } })) {
uniqueSlug = `${slug}-${count}`;
count++;
}
const kategoriDestinasi = await KategoriDestinasi.findOne({
where: { id: id_kategoridestinasi },
});
const desaWisata = await DesaWisata.findOne({
where: { id: id_desawisata },
});
// Validasi kategoridestinasi
if (!kategoriDestinasi) {
throw new Error("Kategori destinasi tidak ditemukan");
}
// Validasi desawisata
if (!desaWisata) {
throw new Error("Desa wisata tidak ditemukan");
}
await DestinasiWisata.create({
nama: nama,
slug: uniqueSlug,
deskripsi: deskripsi,
gambar: gambar,
id_kategoridestinasi: kategoriDestinasi.id,
id_desawisata: desaWisata.id,
});
return res.json({ msg: "Add successful" });
} catch (error) {
console.error(error);
// Hapus file gambar yang sudah diunggah jika ada error
if (req.file) {
const tempImagePath = req.file.path;
try {
fs.unlinkSync(tempImagePath);
console.log("Uploaded image deleted due to failed data saving.");
} catch (error) {
console.error("Error deleting uploaded image:", error);
}
}
if (error.name === "SequelizeUniqueConstraintError") {
return res.status(400).json({ error: "Constraint Error" });
} else {
console.error("Error while creating account:", error);
return res.status(500).json({ error: error.message });
}
}
};
exports.updateDestinasiWisata = async (req, res) => {
try {
const id = parseInt(req.params.id);
const { nama, deskripsi, id_kategoridestinasi, id_desawisata } = req.body;
// cek apakah ada gambar di upload
const gambar = req.file ? req.file.filename : null;
// Pastikan destinasi telah diinisialisasi sebelumnya
const destinasiWisata = await DestinasiWisata.findByPk(id);
if (!destinasiWisata) {
throw new Error("Destinasi tidak ditemukan");
}
if (nama) {
destinasiWisata.nama = nama;
let slug = slugify(nama, { lower: true, strict: true });
let uniqueSlug = slug;
let count = 1;
while (await DestinasiWisata.findOne({ where: { slug: uniqueSlug, id: { [Op.ne]: id } } })) {
uniqueSlug = `${slug}-${count}`;
count++;
}
destinasiWisata.slug = uniqueSlug;
}
if (gambar) {
// Cek apakah ada gambar sebelumnya, jika ada maka hapus gambar sebelumnya
if (destinasiWisata.gambar) {
const imagePath = path.join(
__dirname,
"../../uploads/resource/destinasiwisata",
destinasiWisata.gambar
);
try {
fs.unlinkSync(imagePath);
} catch (error) {
console.error("Error deleting previous image:", error);
}
}
destinasiWisata.gambar = gambar;
}
if (deskripsi) {
destinasiWisata.deskripsi = deskripsi;
}
if (id_kategoridestinasi) {
const kategoriDestinasi = await KategoriDestinasi.findOne({
where: { id: id_kategoridestinasi },
});
// Validasi kategoridestinasi
if (!kategoriDestinasi) {
throw new Error("Kategori destinasi tidak ditemukan");
}
destinasiWisata.id_kategoridestinasi = kategoriDestinasi.id;
}
if (id_desawisata) {
const desaWisata = await DesaWisata.findOne({
where: { id: id_desawisata },
});
// Validasi desawisata
if (!desaWisata) {
throw new Error("Desa wisata tidak ditemukan");
}
destinasiWisata.id_desawisata = desaWisata.id;
}
await destinasiWisata.save();
return res.status(200).json({ message: "Destinasi wisata berhasil diperbarui" });
} catch (error) {
console.error("Error updating :", error);
// Hapus file gambar yang sudah diunggah jika ada error
if (req.file) {
const tempImagePath = req.file.path;
try {
fs.unlinkSync(tempImagePath);
console.log("Uploaded image deleted due to failed data saving.");
} catch (error) {
console.error("Error deleting uploaded image:", error);
}
}
return res.status(500).json({
error: error.message
});
}
};
exports.deleteDestinasiWisata = async (req, res) => {
try {
const { id } = req.params;
const destinasiwisata = await DestinasiWisata.findOne({ where: { id: id } });
if (!destinasiwisata) {
return res.status(404).json({ message: "Destinasi Wisata tidak ditemukan" });
}
const gambarDestinasiwisataLama = destinasiwisata.gambar;
const deletedDestinasiwisataCount = await DestinasiWisata.destroy({
where: {
id: id,
},
});
if (deletedDestinasiwisataCount > 0) {
if (gambarDestinasiwisataLama) {
const imagePath = path.join(
__dirname,
"../../uploads/resource/destinasiwisata",
gambarDestinasiwisataLama
);
if (fs.existsSync(imagePath)) {
fs.unlinkSync(imagePath);
console.log("Foto Destinasi berhasil dihapus:", gambarDestinasiwisataLama);
} else {
console.log("Foto Destinasi tidak ditemukan:", gambarDestinasiwisataLama);
}
}
return res.status(200).json({ message: "Destinasi wisata berhasil dihapus" });
} else {
return res.status(404).json({ message: "Destinasi wisata tidak ditemukan" });
}
} catch (error) {
console.error("Error :", error);
return res
.status(500)
.json({ error: error.message });
}
};
exports.getOneDestinasiWisata = async (req, res) => {
const { id } = req.params;
try {
const destinasiWisata = await DestinasiWisata.findOne({
where: { id: id },
});
if (!destinasiWisata) {
return res.status(404).json({ error: "Destinasi wisata tidak ditemukan" });
}
res.json(destinasiWisata);
} catch (error) {
console.error(error);
res.status(500).json({ error: error.message });
}
};
exports.getDestinasiWisataByIdDesa = async (req, res) => {
const { id } = req.params;
try {
const destinasiWisata = await DestinasiWisata.findAll({
where: { id_desawisata: id },
});
if (!destinasiWisata) {
return res.status(404).json({ error: "Destinasi wisata tidak ditemukan" });
}
res.json(destinasiWisata);
} catch (error) {
console.error(error);
res.status(500).json({ error: error.message });
}
};
exports.getAllDestinasiWisata = async (req, res) => {
try {
const destinasiWisataList = await DestinasiWisata.findAll({
attributes: { exclude: [] },
});
res.json(destinasiWisataList);
} catch (error) {
console.error(error);
res.status(500).json({ error: error.message });
}
};
|
import Link from "next/link"
import Image from "next/image"
import { BiRightArrowCircle } from "react-icons/bi"
import { GameProps } from "@/utils/types/game"
interface GameCardProps {
game: GameProps
}
const GameCard = ({ game }: GameCardProps) => {
return (
<Link href={`/game/${game.id}`}>
<section className="w-full bg rounded-lg p-4 mb-5 transition-all duration-300 hover:shadow-medium hover:bg-white">
<div className="relative w-full h-56">
<Image
className="rounded-md object-cover "
src={game.image_url}
alt={game.title}
fill={true}
quality={100}
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 33vw"
/>
</div>
<div className="flex items-center mt-3 justify-between border-b border-main-blue">
<p className="text-sm font-bold py-1 text-ellipsis truncate whitespace-nowrap overflow-hidden">
{game.title}
</p>
<BiRightArrowCircle size={24} color="#3865d7" />
</div>
</section>
</Link>
)
}
export default GameCard
|
from rest_framework.permissions import BasePermission
class IsOwnerOrReadOnly(BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
Assumes the model instance has a `user` attribute.
"""
def has_object_permission(self, request, view, obj):
if request.method in ['GET', 'HEAD', 'OPTIONS']:
return True
return obj.user == request.user
class IsAdminUser(BasePermission):
def has_permission(self, request, view):
if request.user and request.user.is_authenticated:
# Check if the user has the 'admin' role
return 'Admin' == request.user.role
return False
|
<?php declare(strict_types=1);
/**
* @license MIT
* @author Samuel Adeshina <samueladeshina73@gmail.calculhmac(clent, data)om>
*
* This file is part of the EmmetBlue project, please read the license document
* available in the root level of the project
*/
namespace EmmetBlue\Plugins\Audit\Logs;
use EmmetBlue\Core\Builder\QueryBuilder\QueryBuilder as QB;
use EmmetBlue\Core\Builder\BuilderFactory as Builder;
use EmmetBlue\Core\Exception\SQLException;
use EmmetBlue\Core\Exception\UndefinedValueException;
use EmmetBlue\Core\Factory\DatabaseConnectionFactory as DBConnectionFactory;
use EmmetBlue\Core\Factory\DatabaseQueryFactory as DBQueryFactory;
use EmmetBlue\Core\Factory\ElasticSearchClientFactory as ESClientFactory;
use EmmetBlue\Core\Logger\DatabaseLog;
use EmmetBlue\Core\Logger\ErrorLog;
use EmmetBlue\Core\Session\Session;
use EmmetBlue\Core\Constant;
/**
* class UnlockLog.
*
* UnlockLog Controller
*
* @author Samuel Adeshina <samueladeshina73@gmail.com>
* @since v0.0.1 01/23/2017 6:49 AM
*/
class UnlockLog
{
public static function view(array $data = [])
{
$start = $data['startdate'];
$end = $data['enddate'];
$query = "SELECT ROW_NUMBER() OVER (ORDER BY a.DateLogged) AS RowNum, a.*, b.Status, b.StatusNote, b.StaffID FROM Patients.PatientProfileUnlockLog a LEFT OUTER JOIN FinancialAuditing.UnlockLogStatus b ON a.LogID = b.LogID INNER JOIN Patients.Patient c ON a.PatientID = c.PatientID INNER JOIN Patients.PatientType d ON c.PatientType = d.PatientTypeID WHERE CONVERT(date, a.DateLogged) BETWEEN '$start' AND '$end'";
if (isset($data['paginate'])) {
if (isset($data['keywordsearch'])) {
$keyword = $data['keywordsearch'];
$query .= " AND (c.PatientFullName LIKE '%$keyword%' OR d.PatientTypeName LIKE '%$keyword%' OR d.CategoryName LIKE '%$keyword%')";
}
$size = $data['from'] + $data['size'];
$_query = "SELECT COUNT(*) as Count FROM Patients.PatientProfileUnlockLog a LEFT OUTER JOIN FinancialAuditing.UnlockLogStatus b ON a.LogID = b.LogID WHERE CONVERT(date, a.DateLogged) BETWEEN '$start' AND '$end'";
$query = "SELECT * FROM ($query) AS RowConstrainedResult WHERE RowNum >= " . $data['from'] . ' AND RowNum < ' . $size . ' ORDER BY RowNum';
}
$result = DBConnectionFactory::getConnection()->query($query)->fetchall(\PDO::FETCH_ASSOC);
$retrievedStaffs = [];
foreach ($result as $key => $value) {
if (!isset($retrievedStaffs[$value['Staff']])) {
$retrievedStaffs[$value['Staff']] = \EmmetBlue\Plugins\HumanResources\StaffProfile\StaffProfile::viewStaffFullName((int) $value['Staff']);
}
$result[$key]['StaffFullName'] = $retrievedStaffs[$value['Staff']]['StaffFullName'];
$result[$key]['PatientInfo'] = \EmmetBlue\Plugins\Patients\Patient\Patient::viewBasic((int) $value['PatientID']);
if (isset($result[$key]['PatientInfo']['_source'])) {
$result[$key]['PatientInfo'] = $result[$key]['PatientInfo']['_source'];
}
if (!is_null($value['StaffID'])) {
if (!isset($retrievedStaffs[$value['StaffID']])) {
$retrievedStaffs[$value['StaffID']] = \EmmetBlue\Plugins\HumanResources\StaffProfile\StaffProfile::viewStaffFullName((int) $value['StaffID']);
}
if (isset($retrievedStaffs[$value['StaffID']]['StaffFullName'])) {
$result[$key]['StatusStaffFullName'] = $retrievedStaffs[$value['StaffID']]['StaffFullName'];
}
if (isset($retrievedStaffs[$value['StaffID']]['StaffPicture'])) {
$result[$key]['StatusStaffPicture'] = $retrievedStaffs[$value['StaffID']]['StaffPicture'];
}
}
}
if (isset($data['paginate'])) {
$total = DBConnectionFactory::getConnection()->query($_query)->fetchAll(\PDO::FETCH_ASSOC)[0]['Count'];
// $filtered = count($_result) + 1;
$result = [
'data' => $result,
'total' => $total,
'filtered' => $total
];
}
return $result;
}
public static function setStatus(int $resourceId, array $data)
{
$status = $data['status'];
$note = $data['statusNote'] ?? null;
$staff = $data['staff'] ?? null;
try {
$query = "SELECT COUNT(*) as total FROM FinancialAuditing.UnlockLogStatus WHERE LogID = $resourceId;";
$result = DBConnectionFactory::getConnection()->query($query)->fetchAll(\PDO::FETCH_ASSOC)[0]['total'];
if ($result == 1) {
$query = "UPDATE FinancialAuditing.UnlockLogStatus SET Status = $status, StatusNote = '$note', StaffID = $staff WHERE LogID = $resourceId";
} else {
$query = "INSERT INTO FinancialAuditing.UnlockLogStatus (LogID, Status, StatusNote, StaffID) VALUES ($resourceId, $status, '$note', $staff);";
}
$result = DBConnectionFactory::getConnection()->exec($query);
} catch (\PDOException $e) {
return $e->getMessage();
}
return $result;
}
}
|
import { Component } from '@angular/core';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
import { Car, CarService } from '../services/car-service/car.service';
import { AuthenticationService } from '../services/authentication-service/authentication.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-default-user',
templateUrl: './default-user.component.html',
styleUrls: ['./default-user.component.scss']
})
export class DefaultUserComponent {
cars: Car[] = [];
nickname: any;
isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => result.matches),
shareReplay()
);
constructor(
private breakpointObserver: BreakpointObserver,
private carService: CarService,
private authService: AuthenticationService,
private router: Router,
) { }
ngOnInit(): void {
this.carService.getUserCars().subscribe(data => {
this.cars = data;
}
);
this.nickname = localStorage.getItem("nickname");
}
onLogout() {
this.authService.logout();
}
}
|
from django.db import models
from django.utils.translation import ugettext_lazy as _
from app.utils import PROFILE_CHOICES
from app.utils.base_model import BaseModel
class Pricing(BaseModel):
monthly_price = models.FloatField(
verbose_name=_("Monthly Price"),
default=0
)
yearly_price = models.FloatField(
verbose_name=_("Yearly Price"),
default=0
)
choice = models.CharField(
verbose_name=_("Profile Choice"),
choices=PROFILE_CHOICES,
max_length=200,
default="blank"
)
class Meta:
verbose_name = _("Pricing")
verbose_name_plural = _("Pricings")
def __str__(self):
return self.choice
|
/* Problema "idades"
* Fazer um programa para ler o nome e idade de duas pessoas.
* Ao final mostrar uma mensagem com os nomes e a idade média entre essas pessoas,
* com uma casa decimal
*/
programa
{
inclua biblioteca Matematica --> mat
cadeia nome1, nome2
inteiro idade1, idade2
real media
funcao inicio()
{
escreva("Dados da primeira pessoa:\n")
escreva("Nome: ")
leia(nome1)
escreva("Idade: ")
leia(idade1)
escreva("Dados da segunda pessoa:\n")
escreva("Nome: ")
leia(nome2)
escreva("Idade: ")
leia(idade2)
media = mat.arredondar((idade1 + idade2) / 2.0, 1)
escreva("A idade média de ", nome1, " e ", nome2, " é de ", media, " anos.\n")
}
}
/* $$$ Portugol Studio $$$
*
* Esta seção do arquivo guarda informações do Portugol Studio.
* Você pode apagá-la se estiver utilizando outro editor.
*
* @POSICAO-CURSOR = 591;
* @PONTOS-DE-PARADA = ;
* @SIMBOLOS-INSPECIONADOS = ;
* @FILTRO-ARVORE-TIPOS-DE-DADO = inteiro, real, logico, cadeia, caracter, vazio;
* @FILTRO-ARVORE-TIPOS-DE-SIMBOLO = variavel, vetor, matriz, funcao;
*/
|
// -- this is perfect explanation and example for React-Refs feature
import { Component, createRef } from "react";
class ReactRefs extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
};
this.ref = createRef();
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
handleSubmit = (e) => {
e.preventDefault();
// alert(`your emailId "${this.state.email}" submitted successfully 👍`);
alert(
`your emailId "${this.ref.current.value}" submitted successfully from dom value👍`
);
this.setState({
email: "",
});
};
//--------------------------------------------------------------------------
componentDidMount() {
console.log(this.ref);
this.ref.current.focus();
}
//--------------------------------------------------------------------------
render() {
const innerDivStyle = {
height: "100px",
width: "40%",
border: "1px solid #CCC",
display: "flex",
alignItems: "center",
justifyContent: "flex-start",
padding: "5px",
};
return (
<>
<h4>Refs concept</h4>
<p>
key points - with React Refs we can directly control the dom element
with in react and also we can access the dom node element value
directly
</p>
<p>There are 3 simple steps we can achieve this</p>
<div style={innerDivStyle}>
<form onSubmit={this.handleSubmit}>
<label htmlFor="email">Enter your EmailId:</label>
<input
type="email"
id="email"
name="email"
value={this.state.email}
onChange={this.handleChange}
ref={this.ref}
/>
<button type="submit">submit</button>
</form>
</div>
</>
);
}
}
export default ReactRefs;
|
#include <iostream>
using namespace std;
/*Given a non-negative int n, return the count of the occurrences of 7 as a digit,
so for example 717 yields 2. (no loops).
Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6),
while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).*/
int countSeven(int n){
//Base case
if( n<=10 ){
if(n%7 == 0){
return 1;
}
return 0;
}
//Recursion
else{
if(n%10 == 7){
return 1 + countSeven(n/10);
}
return countSeven(n/10);
}
}
int main(){
int n;
cout << "Please insert a positive integer. " << endl;
cin >> n;
cout << "There are " << countSeven(n) << " 7s in this integer" << endl;
return 0;
}
|
# Protocol Constants
from typing import List, Tuple, Union
CMD_FIELD_LENGTH = 16 # Exact length of cmd field (in bytes)
LENGTH_FIELD_LENGTH = 4 # Exact length of length field (in bytes)
MAX_DATA_LENGTH = 10 ** LENGTH_FIELD_LENGTH - 1 # Max size of data field according to protocol
MSG_HEADER_LENGTH = CMD_FIELD_LENGTH + 1 + LENGTH_FIELD_LENGTH + 1 # Exact size of header (CMD+LENGTH fields)
MAX_MSG_LENGTH = MSG_HEADER_LENGTH + MAX_DATA_LENGTH # Max size of total message
DELIMITER = "|" # Delimiter character in protocol
DATA_DELIMITER = "#" # Delimiter in the data part of the message
# Protocol Messages
# In this dictionary we will have all the client and server command names
PROTOCOL_CLIENT = {
"login_msg": "LOGIN",
"logout_msg": "LOGOUT",
"get_login_players": "LOGGED",
"get_question": "GET_QUESTION",
"send_answer": "SEND_ANSWER",
"get_score_msg": "MY_SCORE",
"get_high_score_msg": "HIGHSCORE",
}
PROTOCOL_SERVER = {
"error_msg": "ERROR",
"login_ok_msg": "LOGIN_OK",
"login_failed_msg": "LOGIN_FAILED",
"get_login_players_msg": "LOGGED_ANSWER",
"get_question": "YOUR_QUESTION",
"correct_answer": "CORRECT_ANSWER",
"wrong_answer": "WRONG_ANSWER",
"get_score_msg": "YOUR_SCORE",
"get_high_score_msg": "ALL_SCORE",
"no_questions": "NO_QUESTIONS",
}
def build_message(cmd: str, data: str) -> Union[str, None]:
"""
Gets command name (str) and data field (str) and creates a valid protocol message
Returns: str, or None if error occurred
"""
if cmd not in PROTOCOL_SERVER.values() and cmd not in PROTOCOL_CLIENT.values():
return None
if len(data) > MAX_DATA_LENGTH:
return None
cmd_part = f'{cmd}{" " * (CMD_FIELD_LENGTH - len(cmd))}'
data_len_part = str(len(data)).zfill(LENGTH_FIELD_LENGTH)
return f'{cmd_part}|{data_len_part}|{data}'
def parse_message(data: str) -> Union[Tuple[str, str], Tuple[None, None]]:
"""
Parses protocol message and returns command name and data field
Returns: cmd (str), data (str). If some error occurred, returns None, None
"""
if data is None or len(data) > MAX_MSG_LENGTH:
return None, None
split_msg_by_delimiter = data.split(DELIMITER)
# check if the message has 3 parts
if len(split_msg_by_delimiter) != 3:
return None, None
# check if we get a valid length of cmd
if len(split_msg_by_delimiter[0]) != CMD_FIELD_LENGTH:
return None, None
# remove white spaces from cmd
cleaned_cmd = split_msg_by_delimiter[0].replace(" ", "")
data_length = split_msg_by_delimiter[1]
# check if the length is 4 digits
if len(data_length) != 4 or not data_length.isdigit():
return None, None
data_length = int(data_length) # convert to string to int to get only the number
data = split_msg_by_delimiter[2] # get the data part of the message
# check if all the data has been received
if data_length != len(data):
return None, None
return cleaned_cmd, data
def split_data(msg: str, expected_fields: int) -> Union[List[str], None]:
"""
Helper method. gets a string and number of expected fields in it. Splits the string
using protocol's data field delimiter (|#) and validates that there are correct number of fields.
Returns: list of fields if all ok. If some error occurred, returns None
"""
if msg is None or msg.count(DATA_DELIMITER) != expected_fields - 1:
return None
return msg.split(DATA_DELIMITER)
def join_data(msg_fields: List[str]) -> str:
"""
Helper method. Gets a list, joins all of its fields to one string divided by the data delimiter.
Returns: string that looks like cell1#cell2#cell3
"""
return DATA_DELIMITER.join(msg_fields)
|
---
keywords: Business,Marketing Essentials
title: グリーンウォッシング
description: グリーンウォッシングは、企業またはその製品が実際よりも環境的に健全であるという誤った印象を伝えています。
---
# グリーンウォッシング
##グリーンウォッシングとは何ですか?
グリーンウォッシングは、誤った印象を伝えたり、企業の製品がどのように環境に配慮しているかについて誤解を招く情報を提供したりするプロセスです。グリーンウォッシングは、企業の製品が環境に優しいと消費者に信じ込ませる根拠のない主張と見なされています。
たとえば、グリーンウォッシングの行動に関与している企業は、自社の製品がリサイクルされた材料からのものである、またはエネルギー節約の利点があると主張する場合があります。環境に関する主張の一部は部分的に真実かもしれませんが、グリーンウォッシングに従事する企業は通常、消費者を誤解させるために主張や利益を誇張しています。
グリーンウォッシングは、「ホワイトウォッシング」という用語の遊びです。これは、誤解を招く情報を使用して、悪い行動を理解することを意味します。
##グリーンウォッシングの仕組み
「グリーンシャイン」としても知られるグリーンウォッシングは、環境に配慮した製品に対する需要の高まりを利用する試みです。つまり、より自然で、健康的で、化学物質がなく、リサイクル可能で、天然資源の無駄が少ないということです。
この用語は、ホテル業界がグリーンウォッシングの最も露骨な例の1つを考案した1960年代に始まりました。彼らはホテルの部屋に通知を出し、環境を守るためにタオルを再利用するようにゲストに求めました。ホテルは、より低い洗濯コストの恩恵を享受しました。
最近では、従来のエネルギー会社など、世界最大の炭素排出者の一部が、環境のチャンピオンとしてのブランド名を変更しようとしています。製品は、名前の変更、ブランド変更、または再パッケージ化のプロセスを通じてグリーンウォッシュされます。グリーンウォッシュ製品は、競合ブランドよりも自然で、健康的で、化学物質を含まないという考えを伝える可能性があります。
企業は、クリーンエネルギーや汚染削減の取り組みを宣伝するプレスリリースやコマーシャルを通じてグリーンウォッシングに取り組んできました。実際には、会社は[グリーンイニシアチブに有意義なコミットメントを行っていない可能性があります](/green-investing)。要するに、自社の製品が環境的に安全である、または何らかのグリーン効果を提供するという**根拠のない** d **主張**を行う企業は、グリーンウォッシングに関与しています。
##特別な考慮事項
もちろん、すべての企業がグリーンウォッシングに関与しているわけではありません。一部の製品は真にグリーンです。これらの製品は通常、競合他社のバージョンとの内容の実際の違いを説明するパッケージで提供されます。
真にグリーンな製品のマーケターは、彼らの製品の有益な属性について具体的に説明するのはあまりにも幸せです。たとえば、Allbirdsのウェブサイトでは、スニーカーはメリノウールで作られ、レースはリサイクルされたペットボトルで作られ、インソールにはトウゴマ油が含まれていると説明されています。発送に使用する箱もリサイクル段ボールで作られています。
米国連邦貿易委員会(FTC)は、競争力のある公正な市場を確保するために設計された法律を施行することにより、消費者の保護を支援しています。 FTCは、本物のグリーンとグリーンウォッシュを区別する方法に関するガイドラインを提供しています。
-パッケージングと広告では、製品のグリーンクレームを、クレームのすぐ近くにわかりやすい言葉で説明する必要があります。
-環境マーケティングの主張は、それが製品、パッケージ、または製品またはパッケージの一部のみを指すかどうかを指定する必要があります。
-製品のマーケティングの主張は、直接または暗示的に、環境属性または利益を誇張してはなりません。
-製品が競合他社と比較して利益を主張する場合、その主張は立証されるべきです。
##グリーンウォッシングの例
米国連邦貿易委員会(FTC)は、そのWebサイトで、グリーンウォッシングのいくつかの図を提供しています。これは、欺瞞的なグリーンマーケティングの主張に関する自主的なガイドラインを詳しく説明しています。以下は、グリーンウォッシングと見なされる根拠のない主張の例を含むリストです。
-新しいシャワーカーテンが入ったプラスチックパッケージには、「リサイクル可能」というラベルが付いています。パッケージとシャワーカーテンのどちらがリサイクル可能かは不明です。いずれの場合も、パッケージの一部またはその内容物(マイナーコンポーネント以外)をリサイクルできない場合、ラベルは誤解を招く可能性があります。
-エリアラグには、「以前より50%多いリサイクルコンテンツ」というラベルが付いています。メーカーはリサイクル含有量を2%から3%に増やしました。技術的には真実ですが、このメッセージは、ラグにかなりの量のリサイクル繊維が含まれているという誤った印象を伝えています。
-ゴミ袋には「リサイクル可能」というラベルが付いています。ゴミ袋は通常、埋め立て地や焼却炉で他のゴミから分離されないため、目的を問わず再び使用される可能性はほとんどありません。この主張は、意味のある利益が存在しない環境上の利益を主張しているため、欺瞞的です。
##ハイライト
-グリーンウォッシングは、企業またはその製品が環境的に健全であるという誤った印象を伝える可能性があります。
-グリーンウォッシングは、環境に配慮した製品に対する需要の高まりを利用する試みです。
-真にグリーンな製品は、事実と詳細で主張を裏付けています。
|
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2024 Evan Debenham
*
* 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 <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.levels.rooms.standard.entrance;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.SPDSettings;
import com.shatteredpixel.shatteredpixeldungeon.items.journal.GuidePage;
import com.shatteredpixel.shatteredpixeldungeon.items.journal.Guidebook;
import com.shatteredpixel.shatteredpixeldungeon.journal.Document;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain;
import com.shatteredpixel.shatteredpixeldungeon.levels.features.LevelTransition;
import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter;
import com.shatteredpixel.shatteredpixeldungeon.levels.rooms.Room;
import com.shatteredpixel.shatteredpixeldungeon.levels.rooms.standard.StandardRoom;
import com.watabou.utils.Point;
import com.watabou.utils.Random;
import com.watabou.utils.Reflection;
import java.util.ArrayList;
public class EntranceRoom extends StandardRoom {
@Override
public int minWidth() {
return Math.max(super.minWidth(), 5);
}
@Override
public int minHeight() {
return Math.max(super.minHeight(), 5);
}
@Override
public boolean isEntrance() {
return true;
}
@Override
public boolean canMerge(Level l, Room other, Point p, int mergeTerrain) {
if (Dungeon.depth <= 2) {
return false;
} else {
return super.canMerge(l, other, p, mergeTerrain);
}
}
@Override
public boolean canPlaceTrap(Point p) {
if (Dungeon.depth == 1) {
return false;
} else {
return super.canPlaceTrap(p);
}
}
public void paint(Level level ) {
Painter.fill( level, this, Terrain.WALL );
Painter.fill( level, this, 1, Terrain.EMPTY );
for (Room.Door door : connected.values()) {
door.set( Room.Door.Type.REGULAR );
}
int entrance;
do {
entrance = level.pointToCell(random(2));
} while (level.findMob(entrance) != null);
Painter.set( level, entrance, Terrain.ENTRANCE );
if (Dungeon.depth == 1){
level.transitions.add(new LevelTransition(level, entrance, LevelTransition.Type.SURFACE));
} else {
if (Dungeon.branch == 2) {
if (Dungeon.depth % 5 == 1) {
level.transitions.add(new LevelTransition(level, entrance, LevelTransition.Type.BRANCH_ENTRANCE, Dungeon.depth-2, 0, LevelTransition.Type.BRANCH_EXIT));
} else {
level.transitions.add(new LevelTransition(level, entrance, LevelTransition.Type.BRANCH_ENTRANCE, Dungeon.depth-1, Dungeon.branch, LevelTransition.Type.BRANCH_EXIT));
}
} else {
level.transitions.add(new LevelTransition(level, entrance, LevelTransition.Type.REGULAR_ENTRANCE));
}
}
//use a separate generator here so meta progression doesn't affect levelgen
Random.pushGenerator();
//places the first guidebook page on floor 1
if (Dungeon.depth == 1 &&
(!Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_INTRO) || SPDSettings.intro() )){
int pos;
do {
//can't be on bottom row of tiles
pos = level.pointToCell(new Point( Random.IntRange( left + 1, right - 1 ),
Random.IntRange( top + 1, bottom - 2 )));
} while (pos == level.entrance() || level.findMob(level.entrance()) != null);
level.drop( new Guidebook(), pos );
Document.ADVENTURERS_GUIDE.deletePage(Document.GUIDE_INTRO);
}
//places the third guidebook page on floor 2
if (Dungeon.depth == 2 && !Document.ADVENTURERS_GUIDE.isPageFound(Document.GUIDE_SEARCHING)){
int pos;
do {
//can't be on bottom row of tiles
pos = level.pointToCell(new Point( Random.IntRange( left + 1, right - 1 ),
Random.IntRange( top + 1, bottom - 2 )));
} while (pos == level.entrance() || level.findMob(level.entrance()) != null);
GuidePage p = new GuidePage();
p.page(Document.GUIDE_SEARCHING);
level.drop( p, pos );
}
Random.popGenerator();
}
private static ArrayList<Class<?extends StandardRoom>> rooms = new ArrayList<>();
static {
rooms.add(EntranceRoom.class);
rooms.add(WaterBridgeEntranceRoom.class);
rooms.add(CircleBasinEntranceRoom.class);
rooms.add(ChasmBridgeEntranceRoom.class);
rooms.add(PillarsEntranceRoom.class);
rooms.add(CaveEntranceRoom.class);
rooms.add(CavesFissureEntranceRoom.class);
rooms.add(HallwayEntranceRoom.class);
rooms.add(StatuesEntranceRoom.class);
rooms.add(ChasmEntranceRoom.class);
rooms.add(RitualEntranceRoom.class);
rooms.add(TempleLibraryEntranceRoom.class);
rooms.add(TempleMazeEntranceRoom.class);
}
private static float[][] chances = new float[32][];
static {
chances[1] = new float[]{1, 0,0, 0,0, 0,0, 0,0, 0,0, 0,0};
chances[2] = chances[1];
chances[3] = new float[]{3, 6,1, 0,0, 0,0, 0,0, 0,0, 0,0};
chances[5] = chances[4] = chances[3];
chances[6] = new float[]{2, 0,0, 4,4, 0,0, 0,0, 0,0, 0,0};
chances[10] = chances[9] = chances[8] = chances[7] = chances[6];
chances[11] = new float[]{2, 0,0, 0,0, 4,4, 0,0, 0,0, 0,0};
chances[15] = chances[14] = chances[13] = chances[12] = chances[11];
chances[16] = new float[]{2, 0,0, 0,0, 0,0, 4,4, 0,0, 0,0};
chances[20] = chances[19] = chances[18] = chances[17] = chances[16];
chances[21] = new float[]{3, 0,0, 0,0, 0,0, 0,0, 6,1, 0,0};
chances[25] = chances[24] = chances[23] = chances[22] = chances[21];
chances[26] = new float[]{2, 1,1, 1,1, 1,1, 1,1, 1,1, 0,0};
chances[31] = chances[30] = chances[29] = chances[28] = chances[27] = chances[26];
}
private static float[][] branchChances = new float[32][];
static {
branchChances[1] = new float[]{0, 0,0, 0,0, 0,0, 0,0, 0,0, 1,1};
branchChances[31]
= branchChances[30]
= branchChances[29]
= branchChances[28]
= branchChances[27]
= branchChances[26]
= branchChances[25]
= branchChances[24]
= branchChances[23]
= branchChances[22]
= branchChances[21]
= branchChances[20]
= branchChances[19]
= branchChances[18]
= branchChances[17]
= branchChances[16]
= branchChances[15]
= branchChances[14]
= branchChances[13]
= branchChances[12]
= branchChances[11]
= branchChances[10]
= branchChances[9]
= branchChances[8]
= branchChances[7]
= branchChances[6]
= branchChances[5]
= branchChances[4]
= branchChances[3]
= branchChances[2]
= branchChances[1];
}
public static StandardRoom createEntrance(){
if (Dungeon.branch == 0) {
return Reflection.newInstance(rooms.get(Random.chances(chances[Dungeon.depth])));
} else {
return Reflection.newInstance(rooms.get(Random.chances(branchChances[Dungeon.depth])));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.