text stringlengths 184 4.48M |
|---|
import { get, has, isEmpty, isNil } from "lodash";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { useAccount } from "wagmi";
import { constants } from "../../config";
import { fetchUserDetails, useAppDispatch, useAppSelector } from "../../store";
import { isRight } from "../../utils/fp";
import { trpc, trpcProxy } from "../../utils/trpc";
import * as utils from "../../utils";
import { ConnectWalletButton } from "../Button/ConnectWallet";
import { InterfacesModal, WebOnBoardModal } from "../Modal";
import { toast } from "react-toastify";
import {UserAccount} from "../UserAccount";
const UserOnboard = () => {
const { address } = useAccount();
const [webOnboard, setWebOnboard] = useState(false);
const [socialInterfaces, setSocialInterfaces] = useState(false);
const [isUser,setUser] = useState<boolean>(false);
const router = useRouter();
const code = router.query.code as string;
const dispatch = useAppDispatch();
const didSession = useAppSelector((state) => state.user.didSession);
const userPlatforms = useAppSelector((state) => state.user.userPlatforms);
const userId = useAppSelector((state) => state.user.id);
const createUser = trpc.user.createUser.useMutation();
const updateUser = trpc.user.updateUser.useMutation();
const currentUser = trpc.user.getUser.useQuery({ address });
useEffect((()=>{
setUser(isNil(userId))
}),[userId])
useEffect(() => {
dispatch(fetchUserDetails(address));
}, [address]);
useEffect(() => {
if (code) {
handleDiscordAuthCallback(code).catch(() => toast.dismiss());
}
}, [code]);
useEffect(() => {
const checkUser = () => {
if (address && (isNil(userPlatforms) || isNil(userPlatforms[0].platformId))) {
setWebOnboard(true);
}
else{
setWebOnboard(false);
}
};
checkUser();
}, [userPlatforms]);
useEffect(() => {
const checkDiscordUser = () => {
if (address && (!isNil(userPlatforms) && !isNil(userPlatforms[0].platformId))) {
const hasDiscord = userPlatforms.find(
(platform) => platform.platformName === "discord"
);
if(isNil(hasDiscord)){
setSocialInterfaces(true);
}
else{
setSocialInterfaces(false);
}
}
};
checkDiscordUser();
}, [userPlatforms]);
const handleDiscordAuthCallback = async (code: string) => {
const response = await fetch(`/api/user/discord-auth/profile?code=${code}`);
if (!response.ok) {
return;
}
const profile = await response.json();
const hasDiscord = userPlatforms.filter(
(platform) => platform.platformName === "discord"
)[0];
if (hasDiscord) {
return;
}
toast.loading("Creating you profile!");
await updateUserProfileWithDiscord(profile);
};
const updateUserProfileWithDiscord = async (profile) => {
const user = await updateUser.mutateAsync({
session: didSession,
userPlatformDetails: {
platformId: profile.id,
platformName: constants.PLATFORM_DISCORD_NAME,
platformUsername: utils.getDiscordUsername(
profile.username,
profile.discriminator
),
platformAvatar: utils.getDiscordAvatarUrl(profile.id, profile.avatar),
},
walletAddress: address,
});
if (isRight(user)) {
currentUser.refetch().then((response) => {
if (has(response, "data.value.id")) {
setSocialInterfaces(false);
dispatch(fetchUserDetails(address));
}
});
toast.dismiss();
toast.success("Updated profile with discord info!");
}
};
const handleOnUserConnected = async () => {
const existingUser = await trpcProxy.user.getUser.query({ address });
if (isRight(existingUser) && !existingUser.value.id) {
setWebOnboard(true);
} else {
if (has(existingUser, "value.userPlatforms")) {
const platforms = get(existingUser, "value.userPlatforms");
const hasDiscord = platforms.filter(
(platform) =>
platform.platformName === constants.PLATFORM_DISCORD_NAME
);
if (isEmpty(hasDiscord)) {
setSocialInterfaces(true);
}
}
}
};
const handleWebOnboardSubmit = async (details) => {
const user = await createUser.mutateAsync({
session: didSession,
userPlatformDetails: {
platformId: constants.PLATFORM_DEVNODE_ID,
platformName: constants.PLATFORM_DEVNODE_NAME,
platformUsername: details.name,
platformAvatar: details.imageUrl,
},
walletAddress: address,
});
if (isRight(user)) {
currentUser.refetch().then((response) => {
if (has(response, "data.value.id")) {
dispatch(fetchUserDetails(address));
}
setWebOnboard(false);
setSocialInterfaces(true);
});
}
};
return (
<div className={"w-full"}>
{isUser && <ConnectWalletButton onSessionCreated={handleOnUserConnected} />}
<UserAccount/>
<WebOnBoardModal
onSubmit={handleWebOnboardSubmit}
open={webOnboard}
onClose={() => setWebOnboard(false)}
/>
<InterfacesModal
type={"user"}
open={socialInterfaces}
onClose={() => {}}
/>
</div>
);
};
export default UserOnboard; |
package com.googlecode.lanterna.gui2;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Test/example class for various kinds of window manager behaviours
* @author Martin
*/
public class SimpleWindowManagerTest extends TestBase {
public static void main(String[] args) throws IOException, InterruptedException {
new SimpleWindowManagerTest().run(args);
}
@Override
public void init(final WindowBasedTextGUI textGUI) {
final Window mainWindow = new BasicWindow("Choose test");
Panel contentArea = new Panel();
contentArea.setLayoutManager(new LinearLayout(Direction.VERTICAL));
contentArea.addComponent(new Button("Centered window", new Runnable() {
@Override
public void run() {
textGUI.addWindow(new CenteredWindow());
}
}));
contentArea.addComponent(new Button("Undecorated window", new Runnable() {
@Override
public void run() {
textGUI.addWindow(new UndecoratedWindow());
}
}));
contentArea.addComponent(new Button("Undecorated + Centered window", new Runnable() {
@Override
public void run() {
textGUI.addWindow(new UndecoratedCenteredWindow());
}
}));
contentArea.addComponent(new Button("Close", new Runnable() {
@Override
public void run() {
mainWindow.close();
}
}));
mainWindow.setComponent(contentArea);
textGUI.addWindow(mainWindow);
}
private static class CenteredWindow extends TestWindow {
CenteredWindow() {
super("Centered window");
}
@Override
public Set<Hint> getHints() {
return new HashSet<Hint>(Arrays.asList(Hint.CENTERED));
}
}
private static class UndecoratedWindow extends TestWindow {
UndecoratedWindow() {
super("Undecorated");
}
@Override
public Set<Hint> getHints() {
return new HashSet<Hint>(Arrays.asList(Hint.NO_DECORATIONS));
}
@Override
public void draw(TextGUIGraphics graphics) {
super.draw(graphics);
}
}
private class UndecoratedCenteredWindow extends TestWindow {
UndecoratedCenteredWindow() {
super("UndecoratedCentered");
}
@Override
public Set<Hint> getHints() {
return new HashSet<Hint>(Arrays.asList(Hint.NO_DECORATIONS, Hint.CENTERED));
}
@Override
public void draw(TextGUIGraphics graphics) {
super.draw(graphics);
}
}
private static class TestWindow extends BasicWindow {
TestWindow(String title) {
super(title);
setComponent(new Button("Close", new Runnable() {
@Override
public void run() {
close();
}
}));
}
}
} |
def infinite_fibonacci():
x_1=0
x_2=1
#The yield keyword in python works like a return with the only difference is that instead of returning a value,
# it gives back a generator object to the caller.
#When a function is called and the thread of execution finds a yield keyword in the function, the function
#execution stops at that line itself and it returns a generator object back to the caller.
yield x_1
yield x_2
#Here while loop never bacame false,yield hekps to exit while loop
while True:
yield x_1+x_2
x_2,x_1=x_2,x_1+x_2
infinite_fib=infinite_fibonacci()
next(infinite_fib)
for i in range(10):
print(next(infinite_fib)) |
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import sqlite3
import json
from impressao_ci import imprimir_ci
from iscas import localiza_iscas
app = Flask(__name__, template_folder='templates', static_folder='static')
DATABASE = 'bd_norte.db'
@app.route('/')
def index():
return render_template('index.html')
def get_db_connection():
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
return conn
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
return response
@app.route('/<path:path>', methods=['OPTIONS'])
def options_handler(path):
response = jsonify({})
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
return response
@app.route('/report_iscas', methods=['GET', 'POST'])
def report_iscas():
return jsonify(localiza_iscas())
@app.route('/comunicacoes', methods=['GET'])
def get_comunicacoes():
conn = get_db_connection()
comunicacoes = conn.execute('SELECT * FROM comunicacao_interna ORDER BY ci_num DESC').fetchall()
conn.close()
return jsonify([dict(row) for row in comunicacoes])
@app.route('/print_comunicacao', methods=['POST'])
def print_comunicacao():
data = request.get_json()
if not data or 'ci_num' not in data:
return jsonify({'error': 'ci_num is required'}), 400
ci_num = data['ci_num']
conn = get_db_connection()
comunicacao = conn.execute('SELECT * FROM comunicacao_interna WHERE ci_num = ?', (ci_num,)).fetchone()
conn.close()
if comunicacao is None:
return jsonify({'error': 'Comunicação não encontrada'}), 404
imprimir_ci(dict(comunicacao))
return jsonify(dict(comunicacao))
@app.route('/comunicacao/<int:ci_num>', methods=['GET'])
def get_comunicacao(ci_num):
conn = get_db_connection()
comunicacao = conn.execute('SELECT * FROM comunicacao_interna WHERE ci_num = ?', (ci_num,)).fetchone()
conn.close()
if comunicacao is None:
return jsonify({'error': 'Comunicação não encontrada'}), 404
return jsonify(dict(comunicacao))
@app.route('/comunicacao', methods=['POST'])
def create_comunicacao():
data = request.get_json()
destinatario = data.get('destinatario')
manifesto_numero = data.get('manifesto_numero')
motorista = data.get('motorista')
valor_frete = data.get('valor_frete')
percurso = data.get('percurso')
data_comunicacao = data.get('data')
observacao = data.get('observacao')
isca_1 = data.get('isca_1')
isca_2 = data.get('isca_2')
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''INSERT INTO comunicacao_interna
(destinatario, manifesto_numero, motorista, valor_frete, percurso, data, observacao, isca_1, isca_2)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(destinatario, manifesto_numero, motorista, valor_frete, percurso, data_comunicacao, observacao, isca_1, isca_2))
comunicacao_id = cursor.lastrowid
conn.commit()
conn.close()
return jsonify({'status': 'Comunicação criada com sucesso'}), 201
@app.route('/comunicacao/<int:ci_num>', methods=['PUT'])
def update_comunicacao(ci_num):
data = request.get_json()
destinatario = data['destinatario']
manifesto_numero = data['manifesto_numero']
motorista = data['motorista']
valor_frete = data['valor_frete']
percurso = data['percurso']
data_comunicacao = data['data']
observacao = data['observacao']
isca_1 = data['isca_1']
isca_2 = data['isca_2']
conn = get_db_connection()
conn.execute('UPDATE comunicacao_interna SET destinatario = ?, manifesto_numero = ?, motorista = ?, valor_frete = ?, percurso = ?, data = ?, observacao = ?, isca_1 = ?, isca_2 = ? WHERE ci_num = ?',
(destinatario, manifesto_numero, motorista, valor_frete, percurso, data_comunicacao, observacao, isca_1, isca_2, ci_num))
conn.commit()
conn.close()
return jsonify({'status': 'Comunicação atualizada com sucesso'})
@app.route('/comunicacao/<int:ci_num>', methods=['DELETE'])
def delete_comunicacao(ci_num):
conn = get_db_connection()
conn.execute('DELETE FROM comunicacao_interna WHERE ci_num = ?', (ci_num,))
conn.commit()
conn.close()
return jsonify({'status': 'Comunicação deletada com sucesso'})
if __name__ == '__main__':
app.run(debug=True) |
import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from "./components/Home";
import SearchResults from "./components/SearchResults";
import BookDetails from "./components/BookDetails";
import "./App.css";
function App() {
return (
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/search" element={<SearchResults />} />
<Route path="/details/:id" element={<BookDetails />} />
</Routes>
</Router>
);
}
export default App; |
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dartz/dartz.dart';
import 'package:food_court/repository/rating_repository.dart';
import 'package:mofeed_owner/features/auth/data/user_storage.dart';
import 'package:mofeed_shared/constants/fireabse_constants.dart';
import 'package:mofeed_shared/data/network_info.dart';
import 'package:mofeed_shared/error/error_codes.dart';
import 'package:mofeed_shared/error/failure.dart';
import 'package:mofeed_shared/helper/storage_client.dart';
import 'package:mofeed_shared/model/rating_model.dart';
import 'package:mofeed_shared/utils/const_methods.dart';
import 'package:mofeed_shared/utils/typdefs/typedefs.dart';
class RatingRepositoryImpl implements RatingRepository {
final FirebaseFirestore _firestore;
final AuthStorage _storage;
final NetWorkInfo _netWorkInfo;
const RatingRepositoryImpl({
required FirebaseFirestore firestore,
required AuthStorage storage,
required NetWorkInfo netWorkInfo,
}) : _firestore = firestore,
_storage = storage,
_netWorkInfo = netWorkInfo;
@override
FutureEither<List<RatingModel>> getRatings({
String? restaurantId,
String? lastDocId,
int limit = 10,
}) async {
try {
if (!await _netWorkInfo.isConnected) {
return const Left(netWorkFailure);
} else {
final uid = await _storage.getUid();
final query = _restaurants
.doc(uid)
.collection(FirebaseConst.ratings)
.orderBy("createdAt", descending: true)
.limit(limit);
final ratings = await firestorePagination<RatingModel>(
query: query,
lastDocColl:
_restaurants.doc(uid).collection(FirebaseConst.ratings),
mapList: (list) async {
return list.map((e) => RatingModel.fromMap(e)).toList();
});
return Right(ratings);
}
} on FirebaseException catch (e, st) {
return Left(Failure(e.mapCodeToError, st));
} on StorageException catch (e, st) {
return Left(Failure(e.toString(), st));
}
}
CollectionReference<MapJson> get _restaurants =>
_firestore.collection(FirebaseConst.restaurants);
} |
const mongoose = require('mongoose');
const { isURL } = require('validator');
const { VALIDATION_ERROR } = require('../utils/constants').ERROR_MESSAGES;
const cardSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minLength: 2,
maxLength: 30,
},
link: {
type: String,
required: true,
validate: {
validator: (link) => isURL(link),
message: VALIDATION_ERROR,
},
},
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
required: true,
},
likes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
default: [],
},
],
createdAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('card', cardSchema); |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DevFolio</title>
<link href="images/favicon.ico" rel="icon" size="32x32">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<nav id="navbar" class="navbar navbar-expand-lg fixed-top bg-black navbar-dark ">
<div class="container-fluid container">
<a class="navbar-brand" href="#">DevFolio</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse line" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">HOME</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">ABOUT</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">SERVICES </a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">WORK</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">BLOG</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
DROP DOWN
</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
<li class="dropdown">
<a class="dropdown-item dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Another action1</a
>
<ul>
<li>
<a class="dropdown-item" href="#">Another action 1</a>
</li>
<li>
<a class="dropdown-item" href="#">Another action 1</a>
</li>
<li>
<a class="dropdown-item" href="#">Another action 1</a>
</li>
<li>
<a class="dropdown-item" href="#">Another action 1</a>
</li>
<li>
<a class="dropdown-item" href="#">Another action 1</a>
</li>
<li>
<a class="dropdown-item" href="#">Another action 1</a>
</li>
</ul>
</li>
<li></li>
<li><a class="dropdown-item" href="#">Another action 2</a></li>
<li></li>
<li><a class="dropdown-item" href="#">Another action 3</a></li>
<li>
<!-- <hr class="dropdown-divider" /> -->
</li>
<li>
<a class="dropdown-item" href="#">Something else here</a>
</li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link" href="#">CONTACT</a>
</li>
</ul>
</div>
</div>
</nav>
<header id="home">
<div class="layer w-100 vh-100 lyr-black " </div>
<div class="container vh-100 text-danger text-center d-flex justify-content-center align-items-center">
<div class="home-content ">
<h1>I am Morgan Freeman
</h1>
<p>Developer</p>
</div>
</div>
</header>
<section id="about" class="py-5">
<div class="container bg-white shadow rounded">
<div class="about-box row">
<div class="about-left col-md-6 ">
<div class="row">
<div class="about-img col-sm-6 col-md-4 ">
<img class=" rounded me" src="images/testimonial-2.jpg" alt="">
</div>
<div class="about-info col-sm-6 col-md-8">
<p><span><strong>Name:</strong></span> Morgan Freeman<span></span></p>
<p><span><strong>Name:</strong></span> Morgan Freeman<span></span></p>
<p><span><strong>Name:</strong></span> Morgan Freeman<span></span></p>
</div>
</div>
<div class="skills-div mt-5">
<p><strong>Skill</strong></p>
<span>Html</span> <span>85%</span>
<div class="progress mb-4 position-relative rounded-0" style="background-color: rgb(205 225 248)">
<div class=" progress-bar w-75 h-100 position-absolute" style="background-color: rgb(0 120 255);"></div>
</div>
<span>Html</span> <span>85%</span>
<div class="progress mb-4 position-relative col-12 rounded-0" style="background-color: rgb(205 225 248)">
<div class=" progress-bar col-9 h-100 position-absolute" style="background-color: rgb(0 120 255);"></div>
</div>
<span>Html</span> <span>85%</span>
<div class="progress mb-4 position-relative col-12 rounded-0" style="background-color: rgb(205 225 248)">
<div class=" progress-bar col-10 h-100 position-absolute" style="background-color: rgb(0 120 255);"></div>
</div>
<span>Html</span> <span>85%</span>
<div class="progress mb-4 position-relative col-12 rounded-0" style="background-color: rgb(205 225 248)">
<div class=" progress-bar col-7 h-100 position-absolute" style="background-color: rgb(0 120 255);"></div>
</div>
</div>
</div>
<div class=" about-right col-md-6 ">
<h5 class="">About Me</h5>
<p>Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla porttitor accumsan tincidunt.</p>
<p>Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Vivamus suscipit tortor eget felis porttitor volutpat. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. porttitor at sem.</p>
<p>Nulla porttitor accumsan tincidunt. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Nulla porttitor accumsan tincidunt. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a.</p>
</div>
</div>
</div>
</section>
<section id="services" class=" py-5">
<div class="container ">
<div class="row">
<div class="title-box text-center col-sm-12 py-5 ">
<h3 class="title">
Services
</h3>
<p class="subtitle">
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
</p>
<div class="line"></div>
</div>
</div>
<div class="row text-center ">
<div class="my-card col-md-4">
<div class="service-box">
<div class="service-ico p-3">
<span class="ico-circle"><i class="bi bi-briefcase"></i></span>
</div>
<div class="service-content">
<h2 class="s-title">Web Design</h2>
<p class="s-description text-center">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni adipisci eaque autem fugiat! Quia, provident vitae! Magni tempora perferendis eum non provident.
</p>
</div>
</div>
</div>
<div class="my-card col-md-4">
<div class="service-box ">
<div class="service-ico p-3">
<span class="ico-circle"><i class="bi bi-briefcase"></i></span>
</div>
<div class="service-content">
<h2 class="s-title">Web Design</h2>
<p class="s-description text-center">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni adipisci eaque autem fugiat! Quia, provident vitae! Magni tempora perferendis eum non provident.
</p>
</div>
</div>
</div>
<div class="my-card col-md-4">
<div class="service-box ">
<div class="service-ico p-3">
<span class="ico-circle"><i class="bi bi-briefcase"></i></span>
</div>
<div class="service-content">
<h2 class="s-title">Web Design</h2>
<p class="s-description text-center">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni adipisci eaque autem fugiat! Quia, provident vitae! Magni tempora perferendis eum non provident.
</p>
</div>
</div>
</div>
<div class="my-card col-md-4">
<div class="service-box ">
<div class="service-ico p-3">
<span class="ico-circle"><i class="bi bi-briefcase"></i></span>
</div>
<div class="service-content">
<h2 class="s-title">Web Design</h2>
<p class="s-description text-center">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni adipisci eaque autem fugiat! Quia, provident vitae! Magni tempora perferendis eum non provident.
</p>
</div>
</div>
</div>
<div class="my-card col-md-4">
<div class="service-box ">
<div class="service-ico p-3">
<span class="ico-circle"><i class="bi bi-briefcase"></i></span>
</div>
<div class="service-content">
<h2 class="s-title">Web Design</h2>
<p class="s-description text-center">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni adipisci eaque autem fugiat! Quia, provident vitae! Magni tempora perferendis eum non provident.
</p>
</div>
</div>
</div>
<div class="my-card col-md-4">
<div class="service-box ">
<div class="service-ico p-3">
<span class="ico-circle"><i class="bi bi-briefcase"></i></span>
</div>
<div class="service-content">
<h2 class="s-title">Web Design</h2>
<p class="s-description text-center">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni adipisci eaque autem fugiat! Quia, provident vitae! Magni tempora perferendis eum non provident.
</p>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="counter" class="paralax-mf">
<div class="overlay-mf "></div>
<div class="container position-relative">
<div class="row">
<div class="col-sm-3 col-lg-3 ">
<div class="counter-box d-flex flex-column justify-content-center align-items-center text-center text-white mb-4">
<div class="counter-ico">
<span class="ico-circle"><i class="bi bi-check"></i></span>
</div>
<div class="counter-num">
<p>450</p>
<span class="counter-text">WORKS COMPLETED</span>
</div>
</div>
</div>
<div class="col-sm-3 col-lg-3">
<div class="counter-box d-flex flex-column justify-content-center align-items-center text-center text-white mb-4">
<div class="counter-ico">
<span class="ico-circle"><i class="bi bi-journal-richtext"></i></span>
</div>
<div class="counter-num">
<p>25</p>
<span class="counter-text">YEARS OF EXPERIENCE</span>
</div>
</div>
</div>
<div class="col-sm-3 col-lg-3">
<div class="counter-box d-flex flex-column justify-content-center align-items-center text-center text-white mb-4">
<div class="counter-ico">
<span class="ico-circle"><i class="bi bi-people"></i></span>
</div>
<div class="counter-num">
<p>550</p>
<span class="counter-text">TOTAL CLIENTS</span>
</div>
</div>
</div>
<div class="col-sm-3 col-lg-3">
<div class="counter-box d-flex flex-column justify-content-center align-items-center text-center text-white mb-4">
<div class="counter-ico">
<span class="ico-circle"><i class="bi bi-award"></i></span>
</div>
<div class="counter-num">
<p>48</p>
<span class="counter-text">AWARD WON</span>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="portfolio">
<div class=" container">
<div class="row">
<div class="title-box text-center col-sm-12 py-5 ">
<h3 class="title">
PORTFOLIO
</h3>
<p class="subtitle">
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
</p>
<div class="line"></div>
</div>
</div>
<div class="row g-5">
<div class="col-md-4">
<div class="card ">
<div class="card-img"> <img src="images/work-1.jpg" class="card-img-top" alt="">
</div>
<div class="card-body row">
<div class="col-8 ">
<h5>Lorem impsum dolor</h5>
<p class="caption-2 ">
<span>Web Design</span> / <span>18 Sep. 2018</span>
</p>
</div>
<div class="col-sm-4 my-icon d-flex justify-content-end ">
<div class="w-like ">
<a href="portfolio-details.html "> <span class="bi bi-plus-circle "></span></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card ">
<div class="card-img"> <img src="images/work-2.jpg" class="card-img-top" alt="">
</div>
<div class="card-body row">
<div class="col-8">
<h5>Lorem impsum dolor</h5>
<p class="caption-2">
<span>Web Design</span> / <span>18 Sep. 2018</span>
</p>
</div>
<div class="col-sm-4 my-icon d-flex justify-content-end ">
<div class="w-like ">
<a href="portfolio-details.html "> <span class="bi bi-plus-circle "></span></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card ">
<div class="card-img"> <img src="images/work-3.jpg" class="card-img-top" alt="">
</div>
<div class="card-body row">
<div class="col-8 ">
<h5>Lorem impsum dolor</h5>
<p class="caption-2 ">
<span>Web Design</span> / <span>18 Sep. 2018</span>
</p>
</div>
<div class="col-sm-4 my-icon d-flex justify-content-end ">
<div class="w-like ">
<a href="portfolio-details.html "> <span class="bi bi-plus-circle "></span></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card ">
<div class="card-img"> <img src="images/work-4.jpg" class="card-img-top" alt="">
</div>
<div class="card-body row">
<div class="col-8 ">
<h5>Lorem impsum dolor</h5>
<p class="caption-2 ">
<span>Web Design</span> / <span>18 Sep. 2018</span>
</p>
</div>
<div class="col-sm-4 my-icon d-flex justify-content-end ">
<div class="w-like ">
<a href="portfolio-details.html "> <span class="bi bi-plus-circle "></span></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card ">
<div class="card-img"> <img src="images/work-5.jpg" class="card-img-top" alt="">
</div>
<div class="card-body row">
<div class="col-8 ">
<h5>Lorem impsum dolor</h5>
<p class="caption-2 ">
<span>Web Design</span> / <span>18 Sep. 2018</span>
</p>
</div>
<div class="col-sm-4 my-icon d-flex justify-content-end ">
<div class="w-like ">
<a href="portfolio-details.html "> <span class="bi bi-plus-circle "></span></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card ">
<div class="card-img"> <img src="images/work-6.jpg" class="card-img-top" alt="">
</div>
<div class="card-body row">
<div class="col-8 ">
<h5>Lorem impsum dolor</h5>
<p class="caption-2 ">
<span>Web Design</span> / <span>18 Sep. 2018</span>
</p>
</div>
<div class="col-sm-4 my-icon d-flex justify-content-end ">
<div class="w-like ">
<a href="portfolio-details.html "> <span class="bi bi-plus-circle "></span></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="swipe">
<div class="overlay-mf "></div>
<div class="container position-relative ">
<div id="carouselExampleCaptions" class="carousel slide">
<div class="carousel-indicators">
<button type="button " data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button>
</div>
<div class=" carousel-inner ">
<div class="carousel-item active">
<img src="images/testimonial-4.jpg" class="rounded-circle" alt="...">
<div class="carousel-caption">
<h5>Xavi Alonso</h5>
<p>Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Lorem ipsum dolor sit amet,
</p>
</div>
</div>
<div class="carousel-item">
<img src="images/testimonial-4.jpg" class="rounded-circle" alt="...">
<div class="carousel-caption">
<h5>Xavi Alonso</h5>
<p>Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Lorem ipsum dolor sit amet,
</p>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="blog" class="mt-5">
<div class=" container">
<div class="head-title row">
<div class="title-box text-center col-sm-12 py-5">
<h3 class="title">
Blog
</h3>
<p class="subtitle">
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
</p>
<div class="line"></div>
</div>
</div>
<div class="row g-4 mt-3">
<div class="col-md-4">
<div class="card">
<img src="images/post-1.jpg" class="card-img-top" alt="...">
<div class="card-body position-relative">
<div class="category-box"><span>travel</span></div>
<h5 class="card-title"><a href="">See more ideas about Travel</a></h5>
<p class="card-text">Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. </p>
</div>
<div class="card-footer ">
<div class=" row">
<div class="col-8 col-lg-8 col-md-12 col-sm-8 ">
<a href="">
<img class="col-2 rounded-circle" src="images/testimonial-2.jpg" alt="">
<span class="col-10">Morgan Freeman</span>
</a>
</div>
<div class="post-date col-lg-4 col-md-12 col-sm-4 d-flex justify-content-end align-items-center">
<span class="bi bi-clock"></span><span class=" mx-1">10 min</span>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<img src="images/post-2.jpg" class="card-img-top" alt="...">
<div class="card-body position-relative">
<div class="category-box"><span>web design</span></div>
<h5 class="card-title"><a href="">See more ideas about Travel</a></h5>
<p class="card-text">Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. </p>
</div>
<div class="card-footer">
<div class=" row">
<div class="col-lg-8 col-md-12 col-sm-8 ">
<a href="">
<img class="col-2 rounded-circle" src="images/testimonial-2.jpg" alt="">
<span class="col-10">Morgan Freeman</span>
</a>
</div>
<div class="post-date col-lg-4 col-md-12 col-sm-4 d-flex justify-content-end align-items-center">
<span class="bi bi-clock"></span> <span class=" mx-1">10 min</span>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<img src="images/post-3.jpg" class="card-img-top" alt="...">
<div class="card-body position-relative">
<div class="category-box">
<span>web design</span>
</div>
<h5 class="card-title"><a href="">See more ideas about Travel</a></h5>
<p class="card-text">Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. </p>
</div>
<div class="card-footer">
<div class=" row">
<div class="col-lg-8 col-md-12 col-sm-8 ">
<a href="">
<img class="col-2 rounded-circle" src="images/testimonial-2.jpg" alt="">
<span class="col-10">Morgan Freeman</span>
</a>
</div>
<div class="post-date col-lg-4 col-md-12 col-sm-4 d-flex justify-content-end align-items-center">
<span class="bi bi-clock"></span> <span class=" mx-1">10 min</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="contact" class="p-5 mt-5">
<div class="overlay-mf"></div>
<div class="container position-relative bg-light p-5">
<div class="contact-box p-3">
<div class="row">
<div class="contact-left col-md-6">
<h5>Send Message Us</h5>
<form class="dflex">
<div class="mb-3">
<input type="text" class="form-control" id="name" name="name" placeholder="Your Name">
</div>
<div class="mb-3">
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject">
</div>
<div class="mb-3">
<textarea class="form-control" id="textarea" name="message" rows="5" placeholder="Message"></textarea>
</div>
<div class="col-12 text-center"> <button type="submit" class="btn-primary ">Send Message</button></div>
</form>
</div>
<div class=" contact-right g-sm-5 g-md-0 col-md-6 ">
<h5 class="">Get in Touch</h5>
<div class="row">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis dolorum dolorem soluta quidem expedita aperiam aliquid at. Totam magni ipsum suscipit amet? Autem nemo esse laboriosam ratione nobis mollitia inventore?</p>
<ul class="list-ico">
<li><span class="bi bi-geo-alt"></span> 329 WASHINGTON ST BOSTON, MA 02108</li>
<li><span class="bi bi-phone"></span> (617) 557-0089</li>
<li><span class="bi bi-envelope"></span> contact@example.com</li>
</ul>
</div>
<div class="socials row ">
<ul class=" d-flex gap-4">
<li><a href=""><span class="ico-circle"><i class="bi bi-facebook"></i></span></a></li>
<li><a href=""><span class="ico-circle"><i class="bi bi-instagram"></i></span></a></li>
<li><a href=""><span class="ico-circle"><i class="bi bi-twitter"></i></span></a></li>
<li><a href=""><span class="ico-circle"><i class="bi bi-linkedin"></i></span></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</section>
<footer class="">
<div class="container">
<div class="row">
<div class="col-sm-12 ">
<div class="copyright-box">
<p class="copyright">© Copyright <strong>DevFolio</strong>. All Rights Reserved</p>
<div class="credits">
<span>Designed by</span> <a href="https://bootstrapmade.com/">BootstrapMade</a>
</div>
</div>
</div>
</div>
</div>
</footer>
<script src="js/bootstrap.bundle.min.js "></script>
</body>
</html> |
import React, { useState, useEffect} from "react";
import generateRandomKey from "../helpers/randomKey";
import Place from "../components/Place";
const Places = () => {
const [ placeKeys, setPlaceKeys ] = useState([]);
const [ placeValues, setPlaceValues ] = useState([]);
const [ placeLoaded, setPlaceLoaded ] = useState(false);
useEffect( () => {
const fetchData = async () => {
const result = await fetch("http://localhost:3000/api/places", {
method: "GET"
});
const res = await result.json();
setPlaceKeys(Object.keys(res.place));
setPlaceValues(Object.values(res.place));
setPlaceLoaded(true);
}
fetchData ();
}, [])
return (
<section className="page places-page">
{ !placeLoaded &&
<p className="first"> Loading </p>
}
{ placeLoaded &&
<>
{ placeKeys.map(type => {
return(
<>
<h2 key = { generateRandomKey(20)}> { type } </h2>
{ placeValues[ placeKeys.indexOf(type)].map(value => {
return (
<article key = { value._id}>
<Place id = { value._id} place = { value }/>
</article>
)
})}
<hr />
</>
)
})}
</>
}
</section>
)
};
export default Places; |
package E_Commerce.Client.oauth;
import E_Commerce.Client.domain.AuthenticationType;
import E_Commerce.Client.domain.Customer;
import E_Commerce.Client.service.CustomerService;
import E_Commerce.Client.service.ICustomerService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class OAuth2LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired
private ICustomerService iCustomerService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
CustomerOAuth2User oauth2User = (CustomerOAuth2User) authentication.getPrincipal();
String name = oauth2User.getName();
String email = oauth2User.getEmail();
String clientName = oauth2User.getClientName();
AuthenticationType authenticationType = getAuthenticationType(clientName);
Customer customer = iCustomerService.getCustomerByEmail(email);
if (customer == null) {
iCustomerService.addNewCustomerUponOAuthLogin(name, email, authenticationType);
} else {
oauth2User.setFullName(customer.getFullName());
iCustomerService.updateAuthenticationType(customer, authenticationType);
}
super.onAuthenticationSuccess(request, response, authentication);
}
private AuthenticationType getAuthenticationType(String clientName) {
if (clientName.equals("Google")) {
return AuthenticationType.GOOGLE;
} else if (clientName.equals("Facebook")) {
return AuthenticationType.FACEBOOK;
} else {
return AuthenticationType.DATABASE;
}
}
} |
---
title: 《c++之路》用户定义的类型--User-Defined Types
tags:
- c++
- Types
keywords: 'c++,Types,分片下载'
description: 文件下载在文件大小、网络带宽等限制下就会呈现劣化趋势,故此要解决特殊手段解决
abbrlink: '8905'
date: 2023-07-29 21:41:08
categories:
photos:
cover:
sticky:
---
c++除了内置类型外,还支持用户自定义类型,以便用户可以方便的编写高级应用程序,此处我们主要学习`struct`, `union`,`enum`,`class`
<!-- more -->
## enum
枚举应用:在实际中,有些值无论数值或者字符型的,取值在一个固定范围内,设计者提前知道其取值,但是每个变量只能取其中之一的值,这时可以考虑使用枚举类型。例如:一周有七天;一周有12门课,访问数据类型指定为固定的几个类型。这些都可以使用枚举类型。
枚举定义: enum 枚举类型名{枚举元素1,枚举元素2,枚举元素3…};
枚举变量的声明:同结构体和联合体一样,枚举变量也可以用不同的方式说明,即先声明后定义或者直接在声明时定义。
```c++
enum weekend {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
```
## struct
-有时用户需要将不同类型的数据结合到一起,这时我们不能使用数组,因为数组必须是同一类型的数据,这样就诞生了结构体类型,结构体使我们把有相互联系的不同类型的数据组合到一起,它相当于高级语言中的记录。定义一个结构体类型的两种形式:一种是声明和定义一起;另一种是声明和定义分开。
- struct 结构体类型名{类型1 成员1;类型2 成员2;…}结构体变量名;
- struct 结构体类型名{类型1 成员1;类型2 成员2;…}; struct 类型名 结构体变量名;(C++可以省略struct 关键字)
```c++
struct {
int num;
char name[10];
char sex;
char job;
};
```
## union
有时我们需要使几种不同类型的变量存放在同一内存单元中。例如,把一个整型变量、一个字符型变量、一个双精度型变量放在同一个地址开始的内存单元。这时我们就可以使用共用体union。共用体类型的一般声明形式:
- 声明:union 共用体类型名{成员列表};
- 定义:共用体类型名 共用体变量名; 同样可以在声明共用体类型的同时定义变量
共用体的特点:
- 不能引用共用体变量,而只能引用共用体变量的成员;
- 使用共用体变量时,在每一瞬时只能存放期中一种,而不是同时存放几种,即每一瞬时只有一个成员起作用。
- 能够访问共用体中最后一次被赋值的成员,在对一个新成员赋值后原有的成员就失去了作用。
- 共用体变量的地址和它的成员的地址都是同一地址。
- 不能对共用体变量名赋值,不能企图用变量名来得到一个值;不能再定义共用体变量时对它初始化;不能用共用体变量名做函数参数。
```c++
union P{
int grade;
char position[10];
} category;
```
## 总结
struct,enum和union是C语言中的三种数据类型。
struct是一种复合数据类型,它可以用来组合不同类型的变量,并将它们存储在一起。例如:
struct student { int age; char name[20]; } s1;
enum是一种枚举数据类型,它可以用来定义一组常量。例如:
enum week {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
union是一种特殊的数据类型,它可以存储不同的数据类型,但一次只能存储一种数据类型。例如:
union data { int i; float f; char str[20]; } u;
总结:
- struct是复合数据类型,可以存储不同类型的变量在一起。
- enum是枚举数据类型,用于定义一组常量。
- union是特殊数据类型,可以存储不同类型的数据,但一次只能存储一种。 |
CREATE TABLE emp
(
`Emp_id` INT NOT NULL,
`Emp_name` VARCHAR(40),
`Dept` VARCHAR(40),
`Salary` INT,
PRIMARY KEY (`Emp_id`)
);
INSERT INTO emp (`Emp_id`, `Emp_name`, `Dept`, `Salary` )
VALUES
('1', 'Ram', 'HR', '10000'),
('2', 'Amrit', 'MRKT', '20000'),
('3', 'Ravi', 'HR', '30000'),
('4', 'Nitin', 'MRKT', '40000'),
('5', 'Varun', 'IT', '50000');
-- Find the max salary given
SELECT MAX(salary) FROM emp;
-- NESTED/ SUBQUERIES
-- Find employee taking the max salary
SELECT `Emp_name` FROM emp
WHERE salary = (SELECT MAX(salary) FROM emp);
-- Find the second Highest salary from the table
SELECT MAX(salary) FROM emp
WHERE salary <> (SELECT MAX(salary) FROM emp);
-- Find name of the employee taking home the second highest salary
SELECT `Emp_name` FROM emp
WHERE salary = (SELECT MAX(salary) FROM emp WHERE salary <> (SELECT MAX(salary) FROM emp));
-- GROUP BY CLAUSE
-- Find the no of people working in each department
SELECT Dept, COUNT(*) AS `Number of People` FROM emp
GROUP BY Dept;
-- HAVING CLAUSE
-- Find the department having number of employess less than 2
SELECT Dept FROM emp GROUP BY Dept
HAVING COUNT(*) < 2;
-- Find the name of the employee working in the department having number of employess less than 2
SELECT Emp_name FROM emp
WHERE Dept
IN (SELECT Dept FROM emp GROUP BY Dept
HAVING COUNT(*) < 2);
-- Find the name of the employees taking away the highest salary from each department
SELECT Emp_name, Dept, Salary FROM emp
WHERE (Dept,salary) IN
(SELECT Dept, MAX(salary) FROM emp
GROUP BY Dept); |
package ar.edu.unlp.info.oo1.ejercicio18;
import java.time.LocalDate;
public abstract class Contrato {
protected LocalDate inicioContrato;
protected Empleado empleado;
public Contrato(LocalDate inicioContrato, Empleado empleado) {
this.inicioContrato = inicioContrato;
this.empleado = empleado;
}
public LocalDate getFechaInicio() {
return this.inicioContrato;
}
public double totalACobrar() {
return this.sueldoBasico() + (this.sueldoBasico() * this.montoPorAntiguedad());
}
protected double montoPorAntiguedad() {
if(this.empleado.getAntiguedad() >= 5 && this.empleado.getAntiguedad() < 10) {
return 0.30;
}else if(this.empleado.getAntiguedad() >= 10 && this.empleado.getAntiguedad() < 15){
return 0.50;
}else if(this.empleado.getAntiguedad() >= 15 && this.empleado.getAntiguedad() < 20) {
return 0.70;
}else if(this.empleado.getAntiguedad() == 20){
return 1.0;
}
return 0;
}
protected abstract double sueldoBasico();
public abstract boolean estaActivo();
public abstract boolean estaVencido();
} |
<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', [HomeController::class, 'index'])->name('home');
Route::resource('posts', PostController::class);
Route::get('category/{category_id}/posts', [CategoryController::class, 'showPosts'])->name('category.posts');
Route::get('authors/{author}', [UserController::class, 'showAuthorPosts'])->name('authors.user_id'); |
{% extends 'base.html.twig' %}
{% block title %}Products{% endblock %}
{% block body %}
<style>
.example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
.example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>
<div class="example-wrapper">
<h1 align="center">{{ 'product_list'|trans }}</h1>
<button type="button" class="btn btn-primary" id="btn_add_product">{{ 'add_product'|trans }}</button>
<table id='empTable' width='100%' class="table table-stripped">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Price</td>
<td>Created At</td>
<td>Product Image</td>
{% if is_granted('ROLE_ADMIN') %}
<td>Action</td>
{% endif %}
</tr>
</thead>
<tbody></tbody>
</table>
<!-- Modal -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addModalLabel">{{ 'add_product'|trans }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
{{ form_start(form, {'attr': {'id': 'frm_add'}}) }}
<div class="modal-body">
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter name">
<span class="errors error-name"></span>
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<textarea class="form-control" name="description" id="description" rows="3"></textarea>
<span class="errors error-description"></span>
</div>
<div class="mb-3">
<label for="price" class="form-label">Price</label>
<input type="number" class="form-control" name="price" id="price" placeholder="Enter price">
<span class="errors error-price"></span>
</div>
<div class="mb-3">
<label for="product_image" class="form-label">Image</label>
<input type="file" class="form-control" name="product_image" id="product_image">
<span class="errors error-productimage"></span>
</div>
<strong>Product Variation</strong>
{% include 'product/product_variations.html.twig' %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" id="btn_save" class="btn btn-primary">Save changes</button>
</div>
{{ form_end(form) }}
</div>
</div>
</div>
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="updateModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="updateModalLabel">{{ 'update_product'|trans }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="frm_update">
<input type="hidden" name="product_form[_token]" value="{{ csrf_token('update-item') }}">
<input type="hidden" class="form-control" name="edit_id" id="edit_id" >
<div class="modal-body">
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" name="name" id="u_name" placeholder="Enter name">
<span class="errors error-name"></span>
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<textarea class="form-control" name="description" id="u_description" rows="3"></textarea>
<span class="errors error-description"></span>
</div>
<div class="mb-3">
<label for="price" class="form-label">Price</label>
<input type="number" class="form-control" name="price" id="u_price" placeholder="Enter price">
<span class="errors error-price"></span>
</div>
<div class="mb-3">
<label for="u_product_image" class="form-label">Image</label>
<input type="file" class="form-control" name="product_image" id="u_product_image">
<span class="errors error-productimage"></span>
</div>
<strong>Product Variation</strong>
<div id="res_product_variations"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" id="btn_update" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
<!-- Script -->
<script type="text/javascript">
$(document).ready(function(){
// DataTable
{% if is_granted('ROLE_ADMIN') %}
let columns = [
{ data: 'id',name:'id' },
{ data: 'name',name:'name' },
{ data: 'price',name:'price' },
{ data: 'created_at',name:'created_at' },
{ data: 'product_image',name:'product_image' },
{ data: 'action',searchable:false,orderable:false },
];
{% else %}
let columns = [
{ data: 'id',name:'id' },
{ data: 'name',name:'name' },
{ data: 'price',name:'price' },
{ data: 'created_at',name:'created_at' },
{ data: 'product_image',name:'product_image' },
];
{% endif %}
var table = $('#empTable').DataTable({
processing: true,
serverSide: true,
ajax: {
"url": "{{ path('get_products_list_datatables')}}",
"type": "POST"
},
paging : true,
info : true,
searching : true,
columns: columns,
});
$("#btn_add_product").on('click',function(){
$("#addModal").modal('show');
$("#frm_add")[0].reset();
});
$("#btn_save").on('click',function(){
$("#frm_add .errors").text('');
var action_url = "{{ path('add_edit_product') }}";
var formData = new FormData($("#frm_add")[0]);
$.ajax({
url:action_url,
data:formData,
contentType:false,
processData:false,
dataType:'JSON',
type:"POST",
success:function(response){
if(response.success == 1) {
$("#addModal").modal('hide');
table.ajax.reload();
}
if(response.errors) {
$.each(response.errors,function(field_name,error_message){
$("#frm_add .error-"+field_name).html(error_message);
});
}
},
error:function(){
}
});
});
$("#btn_update").on('click',function(){
$("#frm_update .errors").text('');
var action_url = "{{ path('add_edit_product') }}";
var formData = new FormData($("#frm_update")[0]);
$.ajax({
url:action_url,
data:formData,
contentType:false,
processData:false,
dataType:'JSON',
type:"POST",
success:function(response){
if(response.success == 1) {
$("#updateModal").modal('hide');
table.ajax.reload();
}
if(response.errors) {
$.each(response.errors,function(field_name,error_message){
$("#frm_update .error-"+field_name).html(error_message);
});
}
},
error:function(){
}
});
});
$(document).on('click','.action_edit',function(){
var id = $(this).data('id');
var edit_url = "{{ path('edit_product',{'id':':id'}) }}";
edit_url = edit_url.replace(':id',id);
$.ajax({
url:edit_url,
dataType:'JSON',
_method:"GET",
success:function(response){
if(response.success == 1) {
$("#frm_update")[0].reset();
$("#updateModal").modal('show');
$("#edit_id").val(response.data.id);
$("#u_name").val(response.data.name);
$("#u_description").text(response.data.description);
$("#u_price").val(response.data.price);
$("#res_product_variations").html(response.data.product_variations);
document
.querySelectorAll('#res_product_variations ul.product_variations li')
.forEach((tag) => {
addTagFormDeleteLink(tag)
});
}
},
error:function(){
}
});
});
$(document).on('click','.action_delete',function(){
var id = $(this).data('id');
if(confirm('Are you sure want to delete?')) {
var delete_url = "{{ path('delete_product',{'id':':id'}) }}";
delete_url = delete_url.replace(':id',id);
$.ajax({
url:delete_url,
dataType:'JSON',
_method:"DELETE",
success:function(response){
if(response.success == 1) {
table.ajax.reload();
}
},
error:function(){
}
});
}
});
});
</script>
<script>
const addTagFormDeleteLink = (item) => {
const removeFormButton = document.createElement('button');
removeFormButton.innerText = 'Delete this variation';
removeFormButton.className = "btn btn-sm btn-danger";
item.append(removeFormButton);
removeFormButton.addEventListener('click', (e) => {
e.preventDefault();
item.remove();
});
}
$(document).on('click','#frm_add .add_item_link',function(e){
const collectionHolder = document.querySelector('#frm_add .' + e.currentTarget.dataset.collectionHolderClass);
const item = document.createElement('li');
item.innerHTML = collectionHolder
.dataset
.prototype
.replace(
/__name__/g,
collectionHolder.dataset.index
);
collectionHolder.appendChild(item);
collectionHolder.dataset.index++;
addTagFormDeleteLink(item);
});
$(document).on('click','#frm_update .add_item_link',function(e){
const collectionHolder = document.querySelector('#frm_update .' + e.currentTarget.dataset.collectionHolderClass);
const item = document.createElement('li');
item.innerHTML = collectionHolder
.dataset
.prototype
.replace(
/__name__/g,
collectionHolder.dataset.index
);
collectionHolder.appendChild(item);
collectionHolder.dataset.index++;
addTagFormDeleteLink(item);
});
</script>
</div>
{% endblock %} |
package network.palace.dashboard.utils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.Getter;
import network.palace.dashboard.Dashboard;
import network.palace.dashboard.Launcher;
import network.palace.dashboard.handlers.InventoryCache;
import network.palace.dashboard.handlers.InventoryUpdate;
import network.palace.dashboard.handlers.ResortInventory;
import network.palace.dashboard.handlers.UpdateData;
import network.palace.dashboard.packets.inventory.PacketInventoryContent;
import network.palace.dashboard.packets.inventory.Resort;
import org.bson.*;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* @author Innectic
* @since 6/10/2017
*/
@SuppressWarnings({"DuplicatedCode", "rawtypes"})
public class InventoryUtil {
public static final int STORAGE_VERSION = 1;
@Getter private Map<UUID, InventoryCache> cachedInventories = new HashMap<>();
public InventoryUtil() {
Dashboard dashboard = Launcher.getDashboard();
File f = new File("inventories.txt");
if (f.exists()) {
try {
Scanner scanner = new Scanner(new FileReader(f));
while (scanner.hasNextLine()) {
String json = scanner.nextLine();
JsonObject o = new JsonParser().parse(json).getAsJsonObject();
UUID uuid = UUID.fromString(o.get("uuid").getAsString().trim());
HashMap<Resort, ResortInventory> map = new HashMap<>();
JsonArray arr = o.get("resorts").getAsJsonArray();
for (int i = 0; i < arr.size(); i++) {
JsonObject ob = arr.get(i).getAsJsonObject();
Resort resort = Resort.fromId(ob.get("resort").getAsInt());
String packJSON;
String packHash;
String dbPackHash;
int packsize;
String lockerJSON;
String lockerHash;
String dbLockerHash;
int lockersize;
String baseJSON;
String baseHash;
String dbBaseHash;
String buildJSON;
String buildHash;
String dbBuildHash;
if (ob.get("backpackJSON").isJsonNull()) {
packJSON = "";
} else {
packJSON = ob.get("backpackJSON").getAsString();
}
if (ob.get("backpackHash").isJsonNull()) {
packHash = "";
} else {
packHash = ob.get("backpackHash").getAsString();
}
if (ob.get("dbBackpackHash").isJsonNull()) {
dbPackHash = "";
} else {
dbPackHash = ob.get("dbBackpackHash").getAsString();
}
if (ob.get("backpacksize").isJsonNull()) {
packsize = 0;
} else {
packsize = ob.get("backpacksize").getAsInt();
}
if (ob.get("lockerJSON").isJsonNull()) {
lockerJSON = "";
} else {
lockerJSON = ob.get("lockerJSON").getAsString();
}
if (ob.get("lockerHash").isJsonNull()) {
lockerHash = "";
} else {
lockerHash = ob.get("lockerHash").getAsString();
}
if (ob.get("dbLockerHash").isJsonNull()) {
dbLockerHash = "";
} else {
dbLockerHash = ob.get("dbLockerHash").getAsString();
}
if (ob.get("lockersize").isJsonNull()) {
lockersize = 0;
} else {
lockersize = ob.get("lockersize").getAsInt();
}
if (ob.get("baseJSON").isJsonNull()) {
baseJSON = "";
} else {
baseJSON = ob.get("baseJSON").getAsString();
}
if (ob.get("baseHash").isJsonNull()) {
baseHash = "";
} else {
baseHash = ob.get("baseHash").getAsString();
}
if (ob.get("dbBaseHash").isJsonNull()) {
dbBaseHash = "";
} else {
dbBaseHash = ob.get("dbBaseHash").getAsString();
}
if (ob.get("buildJSON").isJsonNull()) {
buildJSON = "";
} else {
buildJSON = ob.get("buildJSON").getAsString();
}
if (ob.get("buildHash").isJsonNull()) {
buildHash = "";
} else {
buildHash = ob.get("buildHash").getAsString();
}
if (ob.get("dbBuildHash").isJsonNull()) {
dbBuildHash = "";
} else {
dbBuildHash = ob.get("dbBuildHash").getAsString();
}
map.put(resort, new ResortInventory(resort, packJSON, packHash, dbPackHash, packsize, lockerJSON,
lockerHash, dbLockerHash, lockersize, baseJSON, baseHash, dbBaseHash, buildJSON, buildHash, dbBuildHash));
}
InventoryCache cache = new InventoryCache(uuid, map);
cachedInventories.put(uuid, cache);
}
} catch (Exception e) {
dashboard.getLogger().error("An exception occurred while parsing inventories.txt", e);
}
}
new Timer().schedule(new TimerTask() {
@Override
public void run() {
for (InventoryCache cache : new ArrayList<>(cachedInventories.values())) {
try {
if (cache == null || cache.getResorts() == null) continue;
InventoryUpdate update = new InventoryUpdate();
for (ResortInventory inv : cache.getResorts().values()) {
if (inv == null) continue;
if (!inv.getDbBackpackHash().equals(inv.getBackpackHash()) ||
!inv.getDbLockerHash().equals(inv.getLockerHash()) ||
!inv.getDbBaseHash().equals(inv.getBaseHash()) ||
!inv.getDbBuildHash().equals(inv.getBuildHash())) {
String backpackJSON = inv.getBackpackJSON();
int packSize = inv.getBackpackSize();
String lockerJSON = inv.getLockerJSON();
int lockerSize = inv.getLockerSize();
String baseJSON = inv.getBaseJSON();
String buildJSON = inv.getBuildJSON();
UpdateData data = getDataFromJson(backpackJSON, packSize, lockerJSON, lockerSize, baseJSON, buildJSON);
update.setData(inv.getResort(), data);
inv.setDbBackpackHash(inv.getBackpackHash());
inv.setDbLockerHash(inv.getLockerHash());
inv.setDbBaseHash(inv.getBaseHash());
inv.setDbBuildHash(inv.getBuildHash());
}
}
boolean updated = false;
Runnable runnable = () -> updateData(cache.getUuid(), update);
if (update.shouldUpdate()) {
updated = true;
dashboard.getSchedulerManager().runAsync(runnable);
}
if (dashboard.getPlayer(cache.getUuid()) == null) {
cachedInventories.remove(cache.getUuid());
if (!updated) {
dashboard.getSchedulerManager().runAsync(runnable);
}
}
} catch (Exception e) {
dashboard.getLogger().error("ERROR UPDATING INVENTORY FOR " + cache.getUuid() + ": " + e.getMessage(), e);
}
}
}
}, 15000, 10000);
}
/**
* Create an UpdateData object based on the provided inventory JSON
*
* @param backpackJSON the backpack JSON
* @param backpackSize the backpack size
* @param lockerJSON the locker JSON
* @param lockerSize the locker size
* @param baseJSON the base JSON
* @param buildJSON the build JSON
* @return an UpdateData object based on the provided inventory JSON
*/
public static UpdateData getDataFromJson(String backpackJSON, int backpackSize, String lockerJSON, int lockerSize, String baseJSON, String buildJSON) {
BsonArray pack = jsonToArray(backpackJSON);
BsonArray locker = jsonToArray(lockerJSON);
BsonArray base = jsonToArray(baseJSON);
BsonArray build = jsonToArray(buildJSON);
return new UpdateData(pack, backpackSize, locker, lockerSize, base, build);
}
/**
* Create a BsonArray from the provided JSON string
*
* @param json the JSON string
* @return the BsonArray
*/
public static BsonArray jsonToArray(String json) {
BsonArray array = new BsonArray();
if (json == null || json.isEmpty()) return array;
JsonElement element = new JsonParser().parse(json);
if (element.isJsonArray()) {
JsonArray baseArray = element.getAsJsonArray();
int i = 0;
for (JsonElement e2 : baseArray) {
JsonObject o = e2.getAsJsonObject();
BsonDocument item = InventoryUtil.getBsonFromJson(o.toString());
array.add(item);
i++;
}
}
return array;
}
/**
* Cache a player's inventory in Dashboard, or update an existing cache of the player's inventory
*
* @param uuid the uuid of the player to cache
* @param packet A packet containing the player's inventory data
*/
public void cacheInventory(UUID uuid, PacketInventoryContent packet) {
if (cachedInventories.containsKey(uuid)) {
//If a cache exists, update its data with the new data
ResortInventory cache = cachedInventories.get(uuid).getResorts().get(packet.getResort());
if (cache == null) {
return;
}
ResortInventory inv = new ResortInventory();
inv.setResort(packet.getResort());
if (packet.getBackpackHash().equals("")) {
inv.setBackpackHash(cache.getBackpackHash());
inv.setBackpackJSON(cache.getBackpackJSON());
inv.setDbBackpackHash(cache.getDbBackpackHash());
} else {
inv.setBackpackHash(packet.getBackpackHash());
inv.setBackpackJSON(packet.getBackpackJson());
inv.setDbBackpackHash("");
}
if (packet.getBackpackSize() == -1) {
inv.setBackpackSize(cache.getBackpackSize());
} else {
inv.setBackpackSize(packet.getBackpackSize());
}
if (packet.getLockerHash().equals("")) {
inv.setLockerHash(cache.getLockerHash());
inv.setLockerJSON(cache.getLockerJSON());
inv.setDbLockerHash(cache.getDbLockerHash());
} else {
inv.setLockerHash(packet.getLockerHash());
inv.setLockerJSON(packet.getLockerJson());
inv.setDbLockerHash("");
}
if (packet.getLockerSize() == -1) {
inv.setLockerSize(cache.getLockerSize());
} else {
inv.setLockerSize(packet.getLockerSize());
}
if (packet.getBaseHash().equals("")) {
inv.setBaseHash(cache.getBaseHash());
inv.setBaseJSON(cache.getBaseJSON());
inv.setDbBaseHash(cache.getDbBaseHash());
} else {
inv.setBaseHash(packet.getBaseHash());
inv.setBaseJSON(packet.getBaseJson());
inv.setDbBaseHash("");
}
if (packet.getBuildHash().equals("")) {
inv.setBuildHash(cache.getBuildHash());
inv.setBuildJSON(cache.getBuildJSON());
inv.setDbBuildHash(cache.getDbBuildHash());
} else {
inv.setBuildHash(packet.getBuildHash());
inv.setBuildJSON(packet.getBuildJson());
inv.setDbBuildHash("");
}
cachedInventories.get(uuid).setInventory(packet.getResort(), inv);
} else {
//If a cache doesn't exist, make one
HashMap<Resort, ResortInventory> map = new HashMap<>();
map.put(packet.getResort(), new ResortInventory(packet.getResort(), packet.getBackpackJson(), packet.getBackpackHash(),
"", packet.getBackpackSize(), packet.getLockerJson(), packet.getLockerHash(),
"", packet.getLockerSize(), packet.getBaseJson(), packet.getBaseHash(),
"", packet.getBuildJson(), packet.getBuildHash(), ""));
InventoryCache cache = new InventoryCache(uuid, map);
cachedInventories.put(uuid, cache);
fillMapAsync(uuid);
//Fill the new cache with other resort data from the database if it exists
}
}
/**
* Asynchronously fill a player's InventoryCache with missing resort data from the database
*
* @param uuid the uuid of the player's cache to fill
*/
private void fillMapAsync(UUID uuid) {
Launcher.getDashboard().getSchedulerManager().runAsync(() -> {
InventoryCache cache = cachedInventories.get(uuid);
if (cache == null) cache = new InventoryCache(uuid, new HashMap<>());
HashMap<Resort, ResortInventory> resorts = cache.getResorts();
boolean changed = false;
for (Resort resort : Resort.values()) {
if (resorts.containsKey(resort)) continue;
//A cache entry already exists for that resort, so skip
changed = true;
ResortInventory inv = getResortInventoryFromDatabase(uuid, resort);
if (inv.isEmpty()) continue;
//The database entry is empty, so don't cache it (could be a bad entry)
cache.setInventory(resort, inv);
}
if (!changed) return;
//Only update if any changes were actually made
cachedInventories.put(uuid, cache);
});
}
/**
* Get the inventory for a player
*
* @param uuid the uuid of the player
* @return the inventory of the player. Defaults to a blank string if none is present
*/
public ResortInventory getInventory(UUID uuid, Resort resort) {
try {
InventoryCache cache = cachedInventories.get(uuid);
if (cache == null) {
cache = getInventoryFromDatabase(uuid);
cachedInventories.put(uuid, cache);
}
ResortInventory inv = cache.getResorts().get(resort);
if (inv == null) {
return createResortInventory(uuid, resort);
}
return inv;
} catch (Exception e) {
Launcher.getDashboard().getLogger().error("Error loading inventory", e);
return new ResortInventory();
}
}
private ResortInventory createResortInventory(UUID uuid, Resort resort) {
Dashboard dashboard = Launcher.getDashboard();
ResortInventory inv = new ResortInventory();
inv.setResort(resort);
dashboard.getMongoHandler().setInventoryData(uuid, inv);
InventoryCache cache = cachedInventories.get(uuid);
if (cache != null) {
cache.setInventory(resort, inv);
cachedInventories.put(uuid, cache);
}
return inv;
}
/**
* Get all inventory entries from database for a specific user
*
* @param uuid the player's uuid
* @return A cache with all of the player's resort inventories
*/
private InventoryCache getInventoryFromDatabase(UUID uuid) {
HashMap<Resort, ResortInventory> map = new HashMap<>();
try {
Dashboard dashboard = Launcher.getDashboard();
Document invData = dashboard.getMongoHandler().getParkInventoryData(uuid);
if (invData == null) return new InventoryCache(uuid, map);
for (Resort r : Resort.values()) {
if (!invData.containsKey(r.getName())) continue;
ResortInventory resortInventory = getResortInventoryFromDocument(uuid, (Document) invData.get(r.getName()), r);
map.put(resortInventory.getResort(), resortInventory);
}
if (invData.containsKey("storage")) {
for (Object o : invData.get("storage", ArrayList.class)) {
Document doc = (Document) o;
int resortID = doc.getInteger("resort");
Resort resort = Resort.fromId(resortID);
if (map.containsKey(resort)) continue;
ResortInventory resortInventory = getResortInventoryFromDocument(uuid, (Document) o, resort);
map.put(resortInventory.getResort(), resortInventory);
}
}
} catch (Exception e) {
Launcher.getDashboard().getLogger().error("Error loading inventory from database", e);
}
return new InventoryCache(uuid, map);
}
private ResortInventory getResortInventoryFromDocument(UUID uuid, Document inv, Resort resort) {
if (!inv.containsKey("version")) {
Launcher.getDashboard().getLogger().info("UNVERSIONED STORAGE FOUND " + uuid.toString());
return null;
}
int version = inv.getInteger("version");
if (version != STORAGE_VERSION) {
Launcher.getDashboard().getLogger().info("INCORRECT STORAGE VERSION FOUND " + uuid.toString());
return null;
}
StringBuilder backpack = new StringBuilder("[");
ArrayList packcontents = inv.get("backpack", ArrayList.class);
for (int i = 0; i < packcontents.size(); i++) {
Document item = (Document) packcontents.get(i);
if (!item.containsKey("amount") || !(item.get("amount") instanceof Integer)) {
backpack.append("{}");
} else {
backpack.append("{type:'").append(item.getString("type"))
.append("',data:").append(item.getInteger("data"))
.append(",amount:").append(item.getInteger("amount"))
.append(",tag:'").append(item.getString("tag")).append("'}");
}
if (i < (packcontents.size() - 1)) {
backpack.append(",");
}
}
backpack.append("]");
StringBuilder locker = new StringBuilder("[");
ArrayList lockercontents = inv.get("locker", ArrayList.class);
for (int i = 0; i < lockercontents.size(); i++) {
Document item = (Document) lockercontents.get(i);
if (!item.containsKey("amount") || !(item.get("amount") instanceof Integer)) {
locker.append("{}");
} else {
locker.append("{type:'").append(item.getString("type"))
.append("',data:").append(item.getInteger("data"))
.append(",amount:").append(item.getInteger("amount"))
.append(",tag:'").append(item.getString("tag")).append("'}");
}
if (i < (lockercontents.size() - 1)) {
locker.append(",");
}
}
locker.append("]");
StringBuilder base = new StringBuilder("[");
ArrayList basecontents = inv.get("base", ArrayList.class);
for (int i = 0; i < basecontents.size(); i++) {
Document item = (Document) basecontents.get(i);
if (!item.containsKey("amount") || !(item.get("amount") instanceof Integer)) {
base.append("{}");
} else {
base.append("{type:'").append(item.getString("type"))
.append("',data:").append(item.getInteger("data"))
.append(",amount:").append(item.getInteger("amount"))
.append(",tag:'").append(item.getString("tag")).append("'}");
}
if (i < (basecontents.size() - 1)) {
base.append(",");
}
}
base.append("]");
StringBuilder build = new StringBuilder("[");
ArrayList buildcontents = inv.get("build", ArrayList.class);
for (int i = 0; i < buildcontents.size(); i++) {
Document item = (Document) buildcontents.get(i);
if (!item.containsKey("amount") || !(item.get("amount") instanceof Integer)) {
build.append("{}");
} else {
build.append("{type:'").append(item.getString("type"))
.append("',data:").append(item.getInteger("data"))
.append(",amount:").append(item.getInteger("amount"))
.append(",tag:'").append(item.getString("tag")).append("'}");
}
if (i < (buildcontents.size() - 1)) {
build.append(",");
}
}
build.append("]");
int backpacksize = inv.getInteger("backpacksize");
int lockersize = inv.getInteger("lockersize");
return new ResortInventory(resort, backpack.toString(), generateHash(backpack.toString()), "", backpacksize,
locker.toString(), generateHash(locker.toString()), "", lockersize,
base.toString(), generateHash(base.toString()), "",
build.toString(), generateHash(build.toString()), "");
}
/**
* Get a resort's inventory for a player
*
* @param uuid the uuid of the player
* @param resort the resort inventory to retrieve
* @return the resort's inventory for the player
*/
private ResortInventory getResortInventoryFromDatabase(UUID uuid, Resort resort) {
Dashboard dashboard = Launcher.getDashboard();
Document doc = dashboard.getMongoHandler().getParkInventory(uuid, resort);
BsonArray pack = doc.get("backpack", BsonArray.class);
int backpackSize = doc.getInteger("backpacksize");
BsonArray locker = doc.get("locker", BsonArray.class);
int lockerSize = doc.getInteger("lockersize");
BsonArray base = doc.get("base", BsonArray.class);
BsonArray build = doc.get("build", BsonArray.class);
String backpackJSON = pack.toString();
String lockerJSON = locker.toString();
String baseJSON = base.toString();
String buildJSON = build.toString();
return new ResortInventory(resort, backpackJSON, generateHash(backpackJSON), "", backpackSize,
lockerJSON, generateHash(lockerJSON), "", lockerSize,
baseJSON, generateHash(baseJSON), "",
buildJSON, generateHash(buildJSON), "");
}
/**
* Generate hash for inventory JSON
*
* @param inventory the JSON
* @return MD5 hash of inventory
*/
private String generateHash(String inventory) {
if (inventory == null) {
inventory = "";
}
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(inventory.getBytes());
return DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();
} catch (NoSuchAlgorithmException e) {
Launcher.getDashboard().getLogger().error("Error generaing inventory hash", e);
return "null";
}
}
/**
* Update player inventory data in the database
*
* @param uuid player's uuid
* @param update class containing all values to change
*/
private void updateData(UUID uuid, InventoryUpdate update) {
try {
Launcher.getDashboard().getMongoHandler().updateInventoryData(uuid, update);
} catch (Exception e) {
Launcher.getDashboard().getLogger().error("Error updating inventory in database", e);
}
}
/**
* Convert a JSON string to a Mongo Document
*
* @param json the JSON string
* @return a Mongo document
*/
public static Document getItemFromJson(String json) {
JsonObject o = new JsonParser().parse(json).getAsJsonObject();
if (!o.has("type")) {
return new Document();
}
Document doc;
try {
doc = new Document("type", o.get("type").getAsString())
.append("data", o.get("data").getAsInt())
.append("amount", o.get("amount").getAsInt())
.append("tag", o.get("tag").getAsString());
} catch (IllegalArgumentException ignored) {
return null;
}
return doc;
}
/**
* Convert a JSON string to a BsonDocument
*
* @param json the JSON string
* @return a Bsondocument
*/
public static BsonDocument getBsonFromJson(String json) {
JsonObject o = new JsonParser().parse(json).getAsJsonObject();
if (!o.has("type")) {
return new BsonDocument();
}
BsonDocument doc;
try {
doc = new BsonDocument("type", new BsonString(o.get("type").getAsString()))
.append("data", new BsonInt32(o.get("data").getAsInt()))
.append("amount", new BsonInt32(o.get("amount").getAsInt()))
.append("tag", o.get("tag") == null ? new BsonString("") : new BsonString(o.get("tag").getAsString()));
} catch (IllegalArgumentException e) {
Launcher.getDashboard().getLogger().error("Error converting Json to Bson", e);
return null;
}
return doc;
}
} |
import React, { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FieldArray, Formik } from 'formik';
import { FormikHelpers, FormikProps } from 'formik/dist/types';
import { array as validateArray, object as validateObject } from 'yup';
import dayjs from 'dayjs';
import { ResponseValues } from 'axios-hooks';
import { useLocation } from 'react-router-dom';
import { KnownPersonChooser } from './KnownPersonChooser';
import { FormInput, FormSelect, FormTextArea } from '../../form/FormikFields';
import { Person } from '../../types/Person';
import { SubmitButton } from '../../components/SubmitButton';
import { requiredString, validateDateString } from '../../yupHelper';
import { CreateContract, useContractFilenames, useCreateContract } from './contract.api';
import { Loadable } from '../../components/Loadable';
import { LoadingIndicator } from '../../LoadingIndicator';
import { LoginDataProps } from '../../utils/LoginData';
import Markdown from '../../utils/markdown/Markdown';
import { Card } from '../../components/Card';
import { formatJson } from '../../utils/json';
import { StyledButton } from '../../components/StyledButton';
export function CreateContractForm({ loginData }: LoginDataProps) {
const { t } = useTranslation();
const [{
data,
loading,
error,
}, submitContract] = useCreateContract();
const onSubmit: (values: CreateContract, formikHelpers: FormikHelpers<CreateContract>) => void | Promise<any> = useCallback(async (values, {
setSubmitting,
resetForm,
}) => {
if (!loginData) {
setSubmitting(false);
return;
}
submitContract(values, loginData)
.then(resetForm)
.then(() => setSubmitting(false));
}, [loginData, submitContract]);
const locationPerson = useLocation().state as (Person | undefined);
return (
<div className="py-2 mx-auto w-full rounded-lg border border-gray-200 md:w-1/2">
<h3 className="mb-2">{t('admin.contract.storedPersons')}</h3>
<Formik
onSubmit={onSubmit}
initialValues={{
contractType: '',
dueDate: '',
persons: [locationPerson ?? createPerson()],
text: '',
baseUrl: `${window.location.protocol}//${window.location.host}`,
}}
validationSchema={validateObject({
contractType: requiredString(),
text: requiredString(),
dueDate: validateDateString()
.required(t('form.errors.required'))
.min(new Date(), t('form.errors.date.requireFutureDate')),
persons: validateArray()
.of(
validateObject({
firstName: requiredString(),
lastName: requiredString(),
email: requiredString()
.email(t('form.errors.email')),
birthday: validateDateString()
.required(t('form.errors.required'))
.max(dayjs()
.add(-1, 'y')
.toDate(), t('form.errors.date.requirePastDate')),
}),
)
.min(2),
})}
>
{(props) => (
<>
<CreateContractFormContent {...props} data={data} loading={loading} error={error} />
{!!props.errors && <pre>{formatJson(props.errors)}</pre>}
</>
)}
</Formik>
</div>
);
}
type CreateContractFormikProps =
FormikProps<CreateContract>
& ResponseValues<unknown, unknown, unknown>;
function CreateContractFormContent(formik: CreateContractFormikProps) {
const {
data,
loading,
error,
values,
setFieldValue,
} = formik;
const {
persons,
text,
} = values;
const { t } = useTranslation();
const [{
data: contractData,
loading: contractLoading,
error: contractError,
}] = useContractFilenames();
const [eur, setEur] = useState(25);
return (
<div className="px-4">
<FieldArray name="persons">
{(arrayHelper) => (
<>
{persons.map((_, idx) => (
<PersonForm
// eslint-disable-next-line react/no-array-index-key
key={idx}
formFieldPrefix="persons"
idx={idx}
/>
))}
<KnownPersonChooser onPersonSelected={(p) => arrayHelper.insert(0, p)} />
<div className="flex justify-around m-4 mx-auto w-full md:w-1/3">
<StyledButton
onClick={() => {
arrayHelper.push(createPerson());
}}
className="p-4 w-14 text-center bg-reisishot rounded-xl"
>
+
</StyledButton>
<StyledButton
onClick={() => {
if (values.persons.length > 1) {
arrayHelper.pop();
}
}}
disabled={values.persons.length <= 1}
className="p-4 w-14 text-center bg-red-500 rounded-xl"
>
-
</StyledButton>
</div>
</>
)}
</FieldArray>
<Loadable
data={contractData}
loading={contractLoading}
error={contractError}
loadingElement={<LoadingIndicator height="2rem" />}
>
{(response) => (
<FormSelect
options={response}
className="w-full"
label={t('admin.contract.selectContract')}
required
name="contractType"
disabledOption={t('admin.contract.selectContract')}
/>
)}
</Loadable>
<FormInput
className="w-full"
label={t('admin.contract.dueDate')}
required
name="dueDate"
type="datetime-local"
/>
<div className="flex my-2">
<FormInput step="0.01" value={eur} onChange={(e) => setEur(Number(e.currentTarget.value))} name="eur" label="Mindestwert" type="number" />
<StyledButton onClick={() => {
setFieldValue('text', `## Kosten\nAls Entgelt wird "Pay what you want" mit einem Mindestbeitrag von ${eur.toLocaleString('de')}€ vereinbart.\n${values.text}`);
}}
>
Einfügen
</StyledButton>
</div>
<FormTextArea name="text" required label={t('admin.contract.additionalText')} />
{!!text && (
<Card className="my-4">
<Markdown className="text-center" content={text} />
</Card>
)}
<div className="mx-4">
<SubmitButton data={data} loading={loading} error={error} formik={formik} />
</div>
</div>
);
}
function PersonForm({
formFieldPrefix,
idx,
}: { formFieldPrefix: string, idx: number }) {
const { t } = useTranslation();
const baseName = `${formFieldPrefix}.${idx}`;
return (
<div className="py-4">
<h3 className="mb-1">
{idx + 1}
. Person
</h3>
<div className="flex space-x-2">
<FormInput
className="w-1/2"
label={t('person.firstname')}
name={`${baseName}.firstName`}
required
/>
<FormInput
className="w-1/2"
label={t('person.lastname')}
name={`${baseName}.lastName`}
required
/>
</div>
<div>
<FormInput
className="w-full"
label={t('person.email')}
name={`${baseName}.email`}
required
type="email"
/>
</div>
<div>
<FormInput
className="w-full"
data-date-placeholder={t('person.birthday.placeholder.supported')}
placeholder={t('person.birthday.placeholder.unsupported')}
label={t('person.birthday.title')}
name={`${baseName}.birthday`}
required
type="date"
/>
</div>
</div>
);
}
function createPerson(): Person {
return {
firstName: '',
lastName: '',
email: '',
birthday: '',
};
} |
import React, { useEffect, useState } from "react";
import useSwiper from "swr";
import MovieCard from "../component/movie/MovieCard";
import { fetcher, keyId } from "../config";
// https://api.themoviedb.org/3/search/movie?api_key=
const MoviesPage = () => {
const [itemOffset, setItemOffset] = useState(0);
// Simulate fetching items from another resources.
// (This could be items from props; or items loaded in a local state
// from an API endpoint with useEffect and useState)
const [fillter, setFillter] = useState("");
const [submit, setSubmit] = useState();
const [url, setUrl] = useState(
"https://api.themoviedb.org/3/movie/popular?api_key=95de03c33a2b80e244f5e32c20b99528"
);
const handleFilterChange = (e) => {
setFillter(e.target.value);
};
const handleSubmit = () => {
setSubmit(fillter);
};
useEffect(() => {
if (submit) {
setUrl(
` https://api.themoviedb.org/3/search/movie?api_key=${keyId}&query=${submit}`
);
} else {
setUrl(
"https://api.themoviedb.org/3/movie/popular?api_key=95de03c33a2b80e244f5e32c20b99528"
);
}
}, [submit]);
const { data } = useSwiper(url, fetcher);
const movies = data?.results || [];
return (
<div className="p-10 ">
<div className="w-full text-white flex items-center mb-10 ">
<input
type="text"
className="w-full p-3 bg-slate-800 outline-none"
placeholder="search movies"
onChange={handleFilterChange}
/>
<button onClick={handleSubmit} className="bg-primary p-3 ">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
stroke="currentColor"
className="w-6 h-6"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"
/>
</svg>
</button>
</div>
<div className="grid grid-cols-4 gap-10">
{movies.length > 0 &&
movies.map((item) => (
<MovieCard key={item.id} item={item}></MovieCard>
))}
</div>
</div>
);
};
export default MoviesPage; |
import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { ShopItem } from 'src/shop/shop-item.entity';
import { UserService } from '../user/user.service';
import { ShopService } from '../shop/shop.service';
import { AddItemEntity, AddProductToBasketRes, GetTotalBasketPriceRes, ListProductFromBasketRes, OneItemInBasketRes, RemoveProductFromBasketRes, UserPermissions } from '../types';
import { BasketItem } from './item-in-basket.entity';
import { User } from '../user/user.entity';
@Injectable()
export class BasketService {
constructor(
@Inject(forwardRef( () => ShopService)) private shopService: ShopService,
@Inject(forwardRef( () => UserService)) private userService: UserService,
) {
}
filter(product: BasketItem): OneItemInBasketRes {
return { id: product.id,
count: product.count,
price: product.shopItem.price,
productName: product.shopItem.productName,
shortDescription: product.shopItem.shortDescription,
idProduct: product.shopItem.id,
isPromotion: product.shopItem.isPromotion,
}
}
async list(): Promise<ListProductFromBasketRes> {
const products: BasketItem[] = await BasketItem.find();
const retObject: ListProductFromBasketRes = products.map(this.filter);
return retObject;
}
async getAll(): Promise<BasketItem[]> {
return BasketItem.find({
relations: ['shopItem'],
});
}
async getAllForUser(userId: string): Promise<ListProductFromBasketRes> {
const user = await this.userService.getOneUser(userId);
if (!user) {
throw new Error('User not found!');
}
const products: BasketItem[] = await BasketItem.find({
where: {
user: {
id: userId,
},
},
relations: ['shopItem'],
});
const retObject: ListProductFromBasketRes = products.map(this.filter);
return retObject;
}
async getAllForAdmin(user: User): Promise<BasketItem[]> {
const checkUser = this.shopService.checkUserPermission(user, UserPermissions.ADMIN);
if (checkUser.isSucces === false) {
return [];
}
return BasketItem.find({
relations: ['shopItem'],
});
}
async add(item: AddItemEntity): Promise<AddProductToBasketRes> {
const {count, productId, userId} = item;
const shopItem = await this.shopService.getOneItemOfProduct(productId);
const user = await this.userService.getOneUser(userId);
if ( typeof productId !== 'string'
|| typeof userId !== 'string'
|| typeof count !== 'number'
|| userId === ''
|| productId === ''
|| count < 1
|| !shopItem
|| !user
) {
return {
isSuccess: false,
message: "Sprawdz dane wejściowe",
};
}
const newItem = new BasketItem();
newItem.count = count;
try {
await newItem.save();
newItem.shopItem = shopItem;
newItem.user = user;
await newItem.save();
this.shopService.addBoughtCounter(productId);
return {
isSuccess: true,
id: newItem.id,
};
} catch (err) {
return {
isSuccess: false,
message: "Nie udało się dodać produktu do koszyka",
};
}
}
async remove(itemInBadketId: string, userId: string): Promise<RemoveProductFromBasketRes> {
const user = await this.userService.getOneUser(userId);
if (!user) {
throw new Error('User not found!');
}
const item = await BasketItem.findOne({
where: {
id: itemInBadketId,
user: {
id: userId,
}
}
})
if (item) {
await item.remove();
return {
isSuccess: true,
};
}
return {
isSuccess: false,
};
}
async getTotalPrice(userId: string): Promise<GetTotalBasketPriceRes> {
const items = await this.getAllForUser(userId);
const price = (await Promise.all(items.map(async item => Number(item.price) * item.count * 1.23 )))
.reduce((prev, curr) => prev + curr, 0);
return {
isSuccess: true,
price,
}
}
async clearBasket(userId: string) {
const user = await this.userService.getOneUser(userId);
if (!user) {
throw new Error('User not found!');
}
await BasketItem.delete({
user: {
id: userId,
},
});
return {
isSuccess: true,
}
}
} |
import { Field, InputType } from "type-graphql";
@InputType()
export class UpdatePersonDto {
@Field()
userid: number;
@Field({ nullable: true })
name?: string;
@Field({ nullable: true })
email?: string;
@Field({ nullable: true })
mobile?: string;
@Field({ nullable: true })
gender?: string;
@Field({ nullable: true })
age?: number;
@Field(() => Boolean, { nullable: true })
isactive?: boolean;
} |
package com.example.video.streaming.controller;
import static com.example.video.streaming.helper.VideoCreator.createBasicVideoResponseDto;
import static com.example.video.streaming.helper.VideoCreator.createVideoRequestDto;
import static com.example.video.streaming.helper.VideoCreator.createVideoResponseDto;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import com.example.video.streaming.dto.BasicVideoResponseDto;
import com.example.video.streaming.dto.EngagementStatisticsResponseDto;
import com.example.video.streaming.dto.VideoContentResponseDto;
import com.example.video.streaming.dto.VideoListResponseDto;
import com.example.video.streaming.dto.VideoRequestDto;
import com.example.video.streaming.dto.VideoResponseDto;
import com.example.video.streaming.model.EngagementType;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.jdbc.JdbcTestUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class VideoControllerIntegrationTest {
@Autowired private TestRestTemplate restTemplate;
@Autowired private ResourceLoader resourceLoader;
@Autowired private JdbcTemplate jdbcTemplate;
private ResponseEntity<VideoListResponseDto> callSearchVideos(VideoRequestDto request) {
String urlTemplate =
UriComponentsBuilder.fromPath("/api/v1/videos/search")
.queryParam("title", request.getTitle())
.queryParam("synopsis", request.getSynopsis())
.queryParam("director", request.getDirector())
.queryParam("actor", request.getActor())
.queryParam("year_of_release", request.getYearOfRelease())
.queryParam("genre", request.getGenre())
.queryParam("running_time", request.getRunningTime())
.toUriString();
return restTemplate.getForEntity(urlTemplate, VideoListResponseDto.class);
}
private ResponseEntity<VideoResponseDto> callGetVideo(long videoId) {
return restTemplate.getForEntity("/api/v1/videos/" + videoId, VideoResponseDto.class);
}
private ResponseEntity<VideoContentResponseDto> callPlayVideo(long videoId) {
return restTemplate.getForEntity(
"/api/v1/videos/" + videoId + "/play", VideoContentResponseDto.class);
}
private ResponseEntity<EngagementStatisticsResponseDto> callEngagementStatistics(long videoId) {
return restTemplate.getForEntity(
"/api/v1/videos/" + videoId + "/engagements", EngagementStatisticsResponseDto.class);
}
private ResponseEntity<Void> callDelistVideo(long videoId) {
return restTemplate.exchange("/api/v1/videos/" + videoId, HttpMethod.DELETE, null, Void.class);
}
private ResponseEntity<VideoResponseDto> callSaveVideo() {
Resource videoResource = resourceLoader.getResource("classpath:static/test-video.mov");
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", videoResource);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
return restTemplate.postForEntity("/api/v1/videos", requestEntity, VideoResponseDto.class);
}
private ResponseEntity<VideoResponseDto> callUpdateVideo(
long videoId, VideoRequestDto videoRequestDto) {
HttpEntity<VideoRequestDto> requestEntity = new HttpEntity<>(videoRequestDto);
return restTemplate.exchange(
"/api/v1/videos/" + videoId, HttpMethod.PUT, requestEntity, VideoResponseDto.class);
}
private ResponseEntity<VideoListResponseDto> callListAllVideo() {
return restTemplate.getForEntity("/api/v1/videos", VideoListResponseDto.class);
}
@BeforeEach
void tearDown() {
JdbcTestUtils.deleteFromTables(jdbcTemplate, "engagement_events", "videos");
// add a sample item to Video table
ResponseEntity<VideoResponseDto> savedVideo = callSaveVideo();
long videoId = Objects.requireNonNull(savedVideo.getBody()).getVideoId();
callUpdateVideo(videoId, createVideoRequestDto());
}
@Test
@DisplayName("when list all available videos, should return all videos which exists")
public void whenPublishVideoAndMetadata_returnsVideoResponse() {
// Publish a video
ResponseEntity<VideoResponseDto> savedVideo = callSaveVideo();
assertThat(savedVideo.getBody())
.usingRecursiveComparison()
.ignoringFields("videoId", "createdAt", "updatedAt")
.isEqualTo(
VideoResponseDto.builder()
.contentLink("test-video.mov")
.engagementEventsCount(Collections.emptyMap())
.build());
// Add and Edit the metadata associated with the video
long videoId = Objects.requireNonNull(savedVideo.getBody()).getVideoId();
ResponseEntity<VideoResponseDto> updatedVideo =
callUpdateVideo(videoId, createVideoRequestDto());
assertThat(updatedVideo.getBody())
.usingRecursiveComparison()
.ignoringFields("videoId", "createdAt", "updatedAt")
.isEqualTo(createVideoResponseDto(false, emptyMap()));
}
@Test
@DisplayName("when list all available videos, should return all videos which exists")
public void whenDelistingVideo_shouldNotReturnDelistedVideo() {
// List all available videos
ResponseEntity<VideoListResponseDto> callListAllVideoResponse = callListAllVideo();
assertThat(callListAllVideoResponse.getBody())
.usingRecursiveComparison()
.ignoringFields("videos.videoId")
.isEqualTo(
VideoListResponseDto.builder().videos(List.of(createBasicVideoResponseDto())).build());
long videoId = callListAllVideoResponse.getBody().getVideos().get(0).getVideoId();
// Delist (soft delete) a video and its associated metadata
callDelistVideo(videoId);
// List all available videos
ResponseEntity<VideoListResponseDto> callListAllVideoEmptyResponse = callListAllVideo();
assertThat(callListAllVideoEmptyResponse.getBody())
.isEqualTo(VideoListResponseDto.builder().videos(List.of()).build());
}
@Test
@DisplayName(
"when retrieving the engagement statistic for a video, should return the statistic for impressions and views")
public void whenRetrievingEngagementStatistic_shouldReturnStatistic() {
// List all available videos to know the video id
ResponseEntity<VideoListResponseDto> callListAllVideoResponse = callListAllVideo();
long videoId = callListAllVideoResponse.getBody().getVideos().get(0).getVideoId();
// Load a video – return the video metadata and the corresponding content.
ResponseEntity<VideoResponseDto> callGetVideoResponse = callGetVideo(videoId);
assertThat(callGetVideoResponse.getBody())
.usingRecursiveComparison()
.ignoringFields("videoId", "createdAt", "updatedAt")
.isEqualTo(
createVideoResponseDto(
false, Map.of(EngagementType.IMPRESSION.name().toLowerCase(), 1L)));
// Play a video – return the content related to a video.
ResponseEntity<VideoContentResponseDto> callPlayVideoResponse = callPlayVideo(videoId);
VideoContentResponseDto videoContentResponseDto = new VideoContentResponseDto("test-video.mov");
assertThat(callPlayVideoResponse.getBody())
.usingRecursiveComparison()
.isEqualTo(videoContentResponseDto);
// Retrieve the engagement statistic for a video.
// Since the video was loaded and played already, the engagement statistic should contain 1 for
// both impression and view.
ResponseEntity<EngagementStatisticsResponseDto> callEngagementStatisticsResponse =
callEngagementStatistics(videoId);
assertThat(callEngagementStatisticsResponse.getBody())
.isEqualTo(new EngagementStatisticsResponseDto(videoId, 1, 1));
}
@ParameterizedTest
@MethodSource("videoSearchProvider")
@DisplayName(
"when searching for videos based on some search/query criteria, should return the matched video")
public void whenSearchingVideosBasedOnQuery_shouldReturnMatchedVideos(
VideoRequestDto request, List<BasicVideoResponseDto> expectedBasicVideoResponseDto) {
// Search for videos based on some search/query criteria (e.g.: Movies directed by a specific
// director)
ResponseEntity<VideoListResponseDto> callSearchVideosResponse = callSearchVideos(request);
assertThat(callSearchVideosResponse.getBody())
.usingRecursiveComparison()
.ignoringFields("videos.videoId")
.isEqualTo(VideoListResponseDto.builder().videos(expectedBasicVideoResponseDto).build());
}
private static Stream<Arguments> videoSearchProvider() {
return Stream.of(
Arguments.of(
createVideoRequestDto(),
List.of(createBasicVideoResponseDto()),
Arguments.of(VideoRequestDto.builder().actor("no-actor").build(), List.of()),
Arguments.of(VideoRequestDto.builder().title("no-title").build(), List.of()),
Arguments.of(VideoRequestDto.builder().genre("no-genre").build(), List.of()),
Arguments.of(VideoRequestDto.builder().director("no-director").build(), List.of()),
Arguments.of(VideoRequestDto.builder().synopsis("no-synopsis").build(), List.of()),
Arguments.of(VideoRequestDto.builder().yearOfRelease(1995).build(), List.of()),
Arguments.of(VideoRequestDto.builder().runningTime(3000).build(), List.of())));
}
} |
import { useGithubQuery } from "../../../../types.d";
import { ContributionType, ContributesData } from "./types";
const judgeContributionType = (contributionCount: number) => {
switch (contributionCount) {
case 0:
return ContributionType.NONE;
case 1:
return ContributionType.ONCE;
case 2:
return ContributionType.TWICE;
case 3:
return ContributionType.THREE_TIMES;
default:
return ContributionType.MORE_TIMES;
}
};
const countConsecutiveContribution = (
weeks: {
__typename?: "ContributionCalendarWeek";
contributionDays: {
__typename?: "ContributionCalendarDay";
contributionCount: number;
date: any;
}[];
}[]
): number => {
let totalCount = 0;
let countFlg = false;
while (!countFlg) {
[...weeks].reverse().map((week) => {
[...week.contributionDays].reverse().map((day) => {
if (day.contributionCount > 0 && !countFlg) {
totalCount += 1;
} else {
countFlg = true;
}
});
});
}
return totalCount;
};
export const useGithub = (): {
loading: boolean;
contributesData: ContributesData;
} => {
const { loading, data } = useGithubQuery({
variables: { userName: "souenxx" },
});
if (loading || !data || !data.user) {
return {
loading: true,
contributesData: {
totalContributions: 0,
weeks: [],
consecutiveContribution: 0,
},
};
}
const { weeks, totalContributions } =
data.user.contributionsCollection.contributionCalendar;
const contributesData = {
totalContributions: totalContributions,
weeks: weeks.map((week) => {
return {
contributionDays: week.contributionDays.map((day) => {
const { contributionCount, date } = day;
return {
contributionColor: judgeContributionType(contributionCount),
contributionCount: contributionCount,
date: date,
};
}),
};
}),
consecutiveContribution: countConsecutiveContribution(weeks),
};
return { loading: false, contributesData };
}; |
import random
# my global variables
obstacles = []
my_x = -97
my_y = 197
def does_it_overlap(obstacles, point):
"""
This function checks if the obstacle we are trying to create overlaps
with any of the obstacles already in the list.
:Params - obstacles - (list of tuples) list of aleady existing obstacles
- point - (tuple) the new obstacle we are trying to create
:Return - return true if it overlaps, false if it doesnt
"""
if obstacles == []:
return False
for obstacle in obstacles:
if point[0] >= obstacle[0] and point[0] <= obstacle[0]+4:
if point[1] >= obstacle[1] and point[1] <= obstacle[1]+4:
return True
return False
def create_rectangle_horizontals(vertical_wall, start_x, end_x):
global obstacles
my_door = random.randrange(start_x+4, end_x-8 ,4)
for i in range(start_x, end_x, 4):
if i == my_door or i == my_door+4:
continue
point = (i, vertical_wall)
obstacles.append(point)
def create_rectangle_verticals(horizontal_wall, start_y, end_y):
global obstacles
my_door = random.randrange(start_y, end_y-8, 4)
for i in range(start_y, end_y, 4):
if i == my_door or i == my_door+4:
continue
point = (horizontal_wall, i)
obstacles.append(point)
def create_obstacles(min_x, min_y, max_x, max_y):
"""
Function creates a list of obstacles. Calls the the create_obstacle function and
does_it_overlap function.
:Return - (list of tuples) returns a list with all the obstacles in it as tuples.
"""
global obstacles
obstacles = []
upper_wall = 186
lower_wall = -190
left_wall = -90
right_wall = 86
start_x = -90
end_x = 90
start_y = -186
end_y = 186
number_of_rectangles = 6
for i in range(number_of_rectangles):
create_rectangle_horizontals(upper_wall, start_x, end_x)
create_rectangle_horizontals(lower_wall, start_x, end_x)
create_rectangle_verticals(left_wall, start_y, end_y)
create_rectangle_verticals(right_wall, start_y, end_y)
upper_wall -= 14
lower_wall += 14
left_wall += 14
right_wall -= 14
start_x += 14
end_x -= 14
start_y += 14
end_y -= 14
return obstacles
def get_obstacles():
return obstacles
def is_position_blocked(x2, y2):
"""
This function checks if the the position that the robot is trying to
land on blocked.
:Params - x2 and xy are the coordinates of the new potential position of
the robot
:Return - returns True if position overlaps and false if it doesnt
"""
point = (x2,y2)
if does_it_overlap(obstacles, point):
return True
return False
def is_path_blocked(x1,y1,x2,y2):
"""
This function checks if the path that the robot is heading to blocked
depending on where the new coordinates say the robot should go.
:Params - x1 and y1 are the coordinates of the position of the robot. x2 and y2 are
the coordinates of the new position robot should go to.
:Return - Returns true if there is an obstacle in the way and false if there isn't.
"""
min_x = min(x1, x2)
max_x = max(x1, x2)
min_y = min(y1, y2)
max_y = max(y1, y2)
blocked = False
if x1 == x2:
for i in range(min_y, max_y + 1):
if is_position_blocked(x1, i) == True:
blocked = True
elif y1 == y2:
for i in range(min_x, max_x + 1):
if is_position_blocked(i, y1) == True:
blocked = True
return blocked
def delete_list():
obstacles = [] |
import * as XLSX from 'xlsx'
describe('Login Fallido', function() {
beforeEach(() => {
cy.task('logMessage', 'Iniciando prueba para verificar Listener');
cy.visit(Cypress.env('baseUrl'));
});
it('Intento de inicio de sesión fallido con datos del Excel', () => {
cy.readFile('cypress/fixtures/login_fallido.xlsx', 'binary').then((fileContent) => {
const workbook = XLSX.read(fileContent, { type: 'binary' });
const worksheet = workbook.Sheets['Sheet1']; // Reemplaza "Sheet1" por el nombre de la hoja de tu archivo Excel
const loginData = XLSX.utils.sheet_to_json(worksheet) as { username: string; password: string }[];
loginData.forEach((data) => {
cy.get('[data-test="username"]').type(data.username);
cy.get('[data-test="password"]').type(data.password);
cy.get('[data-test="login-button"]').click();
cy.get('[data-test="error"]').should('be.visible');
cy.reload(); // Reiniciar el estado para el siguiente intento de inicio de sesión
});
});
});
}); |
<!--
File containing signup page
@author: Dominik Vágner
@email: xvagne10@stud.fit.vutbr.cz
-->
{% extends "layout.html" %}
{% from "macros/fields.html" import render_text_field, render_boolean_field, render_alert%}
{% block title %} Login - Smartcity {% endblock %}
{% block body %}
<div class="vh-100 d-flex justify-content-center align-items-center">
<div class="container">
<div class="row d-flex justify-content-center">
<div class="col-12 col-md-10 col-lg-8">
<div style="border: 4px solid #96031A"></div>
<div class="card bg-white shadow-lg" style="border-top-left-radius: 0; border-top-right-radius: 0">
<div class="card-body pb-5 px-5 pt-3">
<form id="form" class="mb-3 mt-md-4" method="POST" novalidate>
<p><a class="mb-5 mt-1 text-decoration-none text-dark" href="{{ url_for("home.index") }}"><i class="las la-angle-double-left pb-1" style="font-size: 18px;"></i>Go back</a></p>
<i class="las la-city" style="font-size: 36px"></i><b style="font-size: 32px; margin-left: 10px">SMARTCITY</b>
<p class="mt-3 mb-4 mt-1">Get started with your account!</p>
{# CSRF Token #}
{{ form.csrf_token() }}
<div id="csrf_token_error" class="text-danger"></div>
{# Form fields #}
<div class="mb-3 row">
<div class="col">
{{ render_text_field(form.name) }}
</div>
<div class="col">
{{ render_text_field(form.surname) }}
</div>
</div>
<div class="mb-3">
{{ render_text_field(form.email) }}
</div>
<div class="mb-3">
{{ render_text_field(form.password) }}
</div>
<div class="my-3">
{{ render_text_field(form.confirm) }}
</div>
<div class="d-grid mt-5">
<button class="btn btn-outline-dark" type="submit">Signup</button>
</div>
</form>
<div>
<p class="mt-3 text-center">Do you already have an account? <a href="{{ url_for("auth.login") }}" class="fw-bold" style="color: #96031A">Login</a></p>
</div>
<div id="alerts" class="mt-3"></div>
<div id="success-message" style="display: none;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block js %}
<script>
// Force email keyboard on mobile devices
let x = document.getElementById("email");
x.type = "email";
// Get form elements by IDs
const form = document.getElementById("form")
const successMessage = document.getElementById("success-message");
const alerts = document.getElementById("alerts");
const fields = {
csrf_token: {
input: document.getElementById('csrf_token'),
error: document.getElementById('csrf_token-error')
},
name: {
input: document.getElementById('name'),
error: document.getElementById('name-error')
},
surname: {
input: document.getElementById('surname'),
error: document.getElementById('surname-error')
},
email: {
input: document.getElementById('email'),
error: document.getElementById('email-error')
},
password: {
input: document.getElementById('password'),
error: document.getElementById('password-error')
},
confirm: {
input: document.getElementById('confirm'),
error: document.getElementById('confirm-error')
}
}
// React to form submission
form.addEventListener("submit", async (e) => {
e.preventDefault();
// Make JSON out of the form input value
let data = JSON.stringify({
csrf_token: fields.csrf_token.input.value,
name: fields.name.input.value,
surname: fields.surname.input.value,
email: fields.email.input.value,
password: fields.password.input.value,
confirm: fields.confirm.input.value,
role: 1,
});
const response = await fetch("{{ url_for("auth.signup") }}", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: data,
});
for (let key in fields) {
if (fields[key].input.classList.contains("is-invalid")) {
fields[key].input.classList.remove("is-invalid");
fields[key].error.innerText = "";
}
}
if (response.ok) {
const api_response = await fetch("{{ url_for("api.auth_api.signup") }}", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: data,
});
if (api_response.ok) {
window.location.assign("{{ url_for("home.index") }}")
} else {
const message = await api_response.json();
alerts.innerHTML = bootstrap_alert_macro(message["message"], "danger")
}
} else {
const errors = await response.json();
Object.keys(errors).forEach((key) => {
fields[key].input.classList.add("is-invalid");
fields[key].error.innerText = errors[key][0];
});
}
});
</script>
{% endblock %} |
Secure API Endpoints in Ubuntu: Step-by-Step Guide
This tutorial will guide you through the process of setting up and securing API endpoints in Ubuntu using Node.js, Express, HTTPS, and JWT authentication.
Step 1: Install Prerequisites
First, ensure Node.js and npm (Node Package Manager) are installed on your Ubuntu system.
sudo apt update
sudo apt install nodejs npm
Verify the installation:
node -v
npm -v
Step 2: Create a Node.js Project
Create a new directory for your project and initialize a new Node.js project:
mkdir secure-api
cd secure-api
npm init -y
Step 3: Install Necessary Packages
Install the necessary packages for your API, including Express (for creating the server), JWT (for authentication), and other security-related packages:
npm install express jsonwebtoken bcryptjs helmet cors dotenv
Step 4: Set Up Environment Variables
Create a .env file in the root of your project to store your environment variables securely:
touch .env
Add the following variables to your .env file:
PORT=3000
SECRET_KEY=your_secret_key
Replace your_secret_key with a strong secret key of your choice.
Step 5: Create the Server
Create a file named server.js and set up a basic Express server with HTTPS support:
javascript
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const helmet = require('helmet');
const cors = require('cors');
const https = require('https');
const fs = require('fs');
require('dotenv').config();
const app = express();
app.use(helmet());
app.use(cors());
app.use(express.json());
const PORT = process.env.PORT || 3000;
const SECRET_KEY = process.env.SECRET_KEY;
// Middleware to protect routes
const authenticateToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.sendStatus(401);
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
// Example unprotected route
app.get('/', (req, res) => {
res.send('Welcome to the secure API!');
});
// Example protected route
app.get('/protected', authenticateToken, (req, res) => {
res.send('This is a protected route');
});
// User registration
app.post('/register', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
// Save user to database (pseudo code)
// db.saveUser({ username, password: hashedPassword });
res.send('User registered successfully');
});
// User login
app.post('/login', async (req, res) => {
const { username, password } = req.body;
// Fetch user from database (pseudo code)
// const user = db.getUserByUsername(username);
const user = { username: 'test', password: '$2a$10$KIXaIvoT9zy8zC/o5PqihOLbVJxW9Yd4ePNL8A2NSl/KxHS9n9uX.' }; // Sample user for demo
if (!user) return res.sendStatus(404);
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) return res.sendStatus(403);
const token = jwt.sign({ username: user.username }, SECRET_KEY, { expiresIn: '1h' });
res.json({ token });
});
// SSL certificates
const key = fs.readFileSync('./ssl/server.key');
const cert = fs.readFileSync('./ssl/server.cert');
const server = https.createServer({ key, cert }, app);
server.listen(PORT, () => {
console.log(`Secure server running on port ${PORT}`);
});
Step 6: Generate SSL Certificates
Generate a self-signed SSL certificate (for development purposes):
mkdir ssl
cd ssl
openssl req -nodes -new -x509 -keyout server.key -out server.cert
cd ..
Step 7: Start Your Server
Start your server using the following command:
node server.js
Step 8: Test Your API
Access your API endpoints using a tool like Postman:
Unprotected route: https://localhost:3000/
Protected route: https://localhost:3000/protected (requires JWT token)
User registration: https://localhost:3000/register
User login: https://localhost:3000/login
For the protected route, include the JWT token in the Authorization header.
Step 9: Deploy Your API (Optional)
For deployment, consider using a cloud provider like AWS, Google Cloud, or DigitalOcean. Ensure your environment variables are set securely and your SSL certificates are properly configured.
Conclusion
By following these steps, you can secure your API endpoints in an Ubuntu environment using HTTPS and JWT authentication. Always follow best practices for security and keep your dependencies up to date. |
import { call, put, select, takeLatest } from "redux-saga/effects";
import {
requestUsers,
addUsers,
setError,
deleteUser,
DeleteUserPayload,
RequestUsersPayload
} from "../../slices/users";
import { getUsers, deleteUser as deleteUSerRequest } from "../../../api/users";
import { PayloadAction } from "@reduxjs/toolkit";
import { RootState } from "../../stroreConfig";
function* getUsersHandler(action: PayloadAction<RequestUsersPayload>) {
try {
const page: number = yield select(
(state: RootState) => state.users.pagesLoaded
);
const { data: users } = yield call(getUsers, page, action.payload.limit);
yield put(addUsers({ users }));
} catch (error) {
yield put(setError());
}
}
function* deleteUserHandler(action: PayloadAction<DeleteUserPayload>) {
try {
yield call(deleteUSerRequest, action.payload.id);
} catch (error) {
yield put(setError());
}
}
export function* usersWatcher() {
yield takeLatest(requestUsers.type, getUsersHandler);
yield takeLatest(deleteUser.type, deleteUserHandler);
} |
import '../../dbHelper/constants.dart';
import 'package:flutter/material.dart';
import '../charts.dart';
import '../panel_left/panel_left_page.dart';
class Product {
String name;
bool enable;
Product({this.enable = true, required this.name});
}
class PanelRightPage extends StatefulWidget {
@override
_PanelRightPageState createState() => _PanelRightPageState();
}
class _PanelRightPageState extends State<PanelRightPage> {
List<Product> _products = [
Product(name: "LED Submersible Lights", enable: true),
Product(name: "Portable Projector", enable: true),
Product(name: "Bluetooth Speaker", enable: true),
Product(name: "Smart Watch", enable: true),
Product(name: "Temporary Tattoos", enable: true),
Product(name: "Bookends", enable: true),
Product(name: "Vegetable Chopper", enable: true),
Product(name: "Neck Massager", enable: true),
Product(name: "Facial Cleanser", enable: true),
Product(name: "Back Cushion", enable: true),
];
final List<Todo> _todos = [
Todo(name: "Student Attendance Portal Activate", enable: true),
Todo(name: "Volunteer Attendance Portal Activate", enable: true),
Todo(name: "Send data to Head Branch", enable: true),
Todo(name: "Revenue Strategy Analysis", enable: true),
// Todo(name: "Selling furniture", enable: true),
// Todo(name: "Finish the disclosure", enable: true),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(
right: Constants.kPadding / 2,
top: Constants.kPadding / 2,
left: Constants.kPadding / 2),
child: Card(
color: Constants.purpleLight,
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
child: Container(
width: double.infinity,
child: const ListTile(
leading: Icon(Icons.arrow_upward_sharp, color: Colors.green, size: 40,),
title: Text(
"Gross Revenue",
style: TextStyle(color: Colors.white),
),
subtitle: Text(
"75% of Avg. Revenue",
style: TextStyle(color: Colors.white),
),
trailing: Chip(
label: Text(
"Rs. 36.5L",
style: TextStyle(color: Colors.green),
),
),
),
),
),
),
LineChartSample1(),
Padding(
padding: const EdgeInsets.only(
right: Constants.kPadding / 2,
bottom: Constants.kPadding,
top: Constants.kPadding,
left: Constants.kPadding / 2),
child: Card(
color: Constants.purpleLight,
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: Column(
children: List.generate(
_todos.length,
(index) => SwitchListTile.adaptive(
title: Text(
_todos[index].name,
style: TextStyle(color: Colors.white),
),
value: _todos[index].enable,
onChanged: (newValue) {
setState(() {
_todos[index].enable = newValue;
});
},
),
),
),
),
),
],
),
),
);
}
} |
import numpy as np
import matplotlib.pyplot as plt
# Load matrix data from CSV files, treat all data as strings
matrix1 = np.genfromtxt('matrix1.csv', delimiter=',', dtype='str')
matrix2 = np.genfromtxt('matrix2.csv', delimiter=',', dtype='str')
# Use the first row as headers
headers = matrix1[0, :]
matrix1 = matrix1[1:, :]
matrix2 = matrix2[1:, :]
# Find non-matching values
mismatch_matrix = matrix1 != matrix2
# Display the original matrices and the mismatch matrix
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
print("\nMismatch Matrix:")
print(mismatch_matrix)
# Plot the matrices and highlight mismatch points
plt.figure(figsize=(12, 4))
plt.subplot(131)
plt.title('Matrix 1')
plt.imshow(mismatch_matrix, cmap='viridis', interpolation='none', origin='upper', aspect='auto')
plt.xticks(np.arange(len(headers)), headers, rotation=45, ha='right')
plt.yticks(np.arange(matrix1.shape[0]), np.arange(1, matrix1.shape[0] + 1))
# Plot the matrices and highlight mismatch points
plt.subplot(132)
plt.title('Matrix 2')
plt.imshow(mismatch_matrix, cmap='viridis', interpolation='none', origin='upper', aspect='auto')
plt.xticks(np.arange(len(headers)), headers, rotation=45, ha='right')
plt.yticks(np.arange(matrix1.shape[0]), np.arange(1, matrix1.shape[0] + 1))
# Plot the mismatch matrix
plt.subplot(133)
plt.title('Mismatch Matrix')
plt.imshow(mismatch_matrix, cmap='Reds', interpolation='none', origin='upper', aspect='auto')
plt.xticks(np.arange(len(headers)), headers, rotation=45, ha='right')
plt.yticks(np.arange(matrix1.shape[0]), np.arange(1, matrix1.shape[0] + 1))
# Highlight mismatch points
for i in range(matrix1.shape[0]):
for j in range(matrix1.shape[1]):
if mismatch_matrix[i, j]:
plt.text(j, i, 'X', ha='center', va='center', color='black')
plt.tight_layout()
plt.show() |
import React from 'react';
import { ComponentStory, ComponentMeta } from '@storybook/react';
import { LeaderBoardTable } from './LeaderBoardTable';
// More on default export: https://storybook.js.org/docs/react/writing-stories/introduction#default-export
export default {
title: 'Lockspread/LeaderBoardTable',
component: LeaderBoardTable,
// More on argTypes: https://storybook.js.org/docs/react/api/argtypes
argTypes: {
backgroundColor: { control: 'color' },
},
} as ComponentMeta<typeof LeaderBoardTable>;
// More on component templates: https://storybook.js.org/docs/react/writing-stories/introduction#using-args
const Template: ComponentStory<typeof LeaderBoardTable> = (args) => (
<LeaderBoardTable {...args} />
);
export const Default = Template.bind({});
// More on args: https://storybook.js.org/docs/react/writing-stories/args
Default.args = {
contests: [
{
selected: true,
onClick: () => {
alert('click');
},
// no returned filters should be disabled
disabled: false,
children: <span className="capitalize text-xs">Contest 1</span>,
name: 'Pill1',
},
{
selected: true,
onClick: () => {
alert('click');
},
// no returned filters should be disabled
disabled: false,
children: <span className="capitalize text-xs">Contest 2</span>,
name: 'Pill1',
},
{
selected: true,
onClick: () => {
alert('click');
},
// no returned filters should be disabled
disabled: false,
children: <span className="capitalize text-xs">Contest 3</span>,
name: 'Pill1',
},
],
leaders: [
{
id: '1',
avatar: {
imgSrc:
'https://as2.ftcdn.net/v2/jpg/04/73/65/63/1000_F_473656322_63yWjOsNFidcGDp8rH6nVOYHhT8RoaDj.jpg',
height: 30,
width: 30,
},
isTopRanked: false,
name: 'Leader 33',
points: 25,
rank: 2,
showHeader: true,
},
{
id: '2',
avatar: {
imgSrc:
'https://as2.ftcdn.net/v2/jpg/04/73/65/63/1000_F_473656322_63yWjOsNFidcGDp8rH6nVOYHhT8RoaDj.jpg',
height: 30,
width: 30,
},
isTopRanked: false,
name: 'Leader 44',
points: 20,
rank: 3,
showHeader: true,
},
{
id: '5',
avatar: {
imgSrc:
'https://as2.ftcdn.net/v2/jpg/04/73/65/63/1000_F_473656322_63yWjOsNFidcGDp8rH6nVOYHhT8RoaDj.jpg',
height: 30,
width: 30,
},
isTopRanked: true,
name: 'Leader 1',
points: 30,
rank: 1,
showHeader: true,
},
{
id: '1',
avatar: {
imgSrc:
'https://as2.ftcdn.net/v2/jpg/04/73/65/63/1000_F_473656322_63yWjOsNFidcGDp8rH6nVOYHhT8RoaDj.jpg',
height: 30,
width: 30,
},
isTopRanked: true,
name: 'Leader 1',
points: 30,
rank: 1,
showHeader: true,
},
],
}; |
import { Elysia } from "elysia";
import { getAllOrdersWithBookDetails, getAllCustomers, getAllBooks } from "../handler/index";
// Define routes using the Elysia router
const appRoutes = new Elysia()
// Route to retrieve all orders with book details
.get('/orders', async ({set}) => {
try {
const result = await getAllOrdersWithBookDetails();
if (result.error) {
set.status = result.statusCode;
console.error(result.error);
return { error: result.error };
} else {
return result.data;
}
} catch (error) {
set.status = 500;
console.error('Error handling request');
return { error: 'Internal Server Error' };
}
})
// Route to retrieve all customers
.get('/customers', async ({set}) => {
try {
const result = await getAllCustomers();
if (result.error) {
set.status = result.statusCode;
console.error(result.error);
return { error: result.error };
} else {
return result.data;
}
} catch (error) {
set.status = 500;
console.error('Error handling request:', error);
return { error: 'Internal Server Error' };
}
})
// Route to retrieve all books, optionally filtered by query
.get('/books', async ({ request, set }) => {
try {
const query = new URL(request.url).searchParams.get('q'); // Get the query parameter from the request
const result = await getAllBooks(query ?? undefined); // Pass the query to getAllBooks
if (result.error) {
set.status = result.statusCode;
console.error(result.error);
return { error: result.error };
} else {
return result.data;
}
} catch (error) {
set.status = 500;
console.error('Error handling request:', error);
return { error: 'Internal Server Error' };
}
})
// Export the routes
export default appRoutes; |
import bind from 'decorators/bind';
import Component from 'components/component';
import React from 'react';
import PropTypes from 'prop-types';
import {addUser} from 'actions/users';
import New from './new';
export default class NewUserContainer extends Component {
static propTypes = {
fragments: PropTypes.object.isRequired,
onClose: PropTypes.func.isRequired
};
static contextTypes = {
store: PropTypes.object.isRequired
};
getInitState () {
return {
username: '',
password: '',
email: '',
name: '',
loading: false
};
}
@bind
submit () {
if (!this.state.loading) {
this.setState({
loading: true
}, () => {
const {store} = this.context;
const {fragments, onClose} = this.props;
const {username, password, email, name} = this.state;
store.dispatch(addUser(fragments, {username, password, email, name}, true)).then(() => {
onClose && onClose();
});
});
}
}
@bind
changeField (field, value) {
this.setState({
[field]: value
});
}
render () {
return (
<New
{...this.state}
submit={this.submit}
changeField={this.changeField}
/>
);
}
} |
using System.Linq;
namespace BetterDay.Models
{
public struct Percentage
{
public DateTime startDate { get; set; }
public DateTime endDate { get; set; }
public int totalTasks { get; set; }
public int tasksDone { get; set; }
public float percentage { get; set; }
}
public class TaskStatsModel
{
public async static Task<Percentage> GetPercentage(string username, DateTime startDate, DateTime endDate)
{
IEnumerable<TaskModel> tasks = TaskModel.GetTasksBetweenDates(username, startDate, endDate).Result;
Percentage stats = new Percentage();
stats.startDate = startDate;
stats.endDate = endDate;
stats.totalTasks = tasks.Count();
stats.tasksDone = tasks.Count(task => task.Status == true);
if (stats.totalTasks == 0)
{
stats.percentage = 0;
}
else
{
stats.percentage = (float)Math.Round(((double)stats.tasksDone / (double)stats.totalTasks),2);
}
return stats;
}
public async static Task<IEnumerable<Percentage>> GetPercentagesByInterval(string username, DateTime startDate, DateTime endDate, int interval)
{
List<Percentage> statsList = new List<Percentage>();
while(startDate < endDate)
{
DateTime intervalEnd = startDate.AddDays(interval);
statsList.Add(await GetPercentage(username, startDate, intervalEnd));
startDate = startDate.AddDays(interval);
}
return statsList;
}
public async static Task<IEnumerable<DateTime>> GetDaysWithUnfinishedTasks(string username, DateTime startDate, DateTime endDate)
{
IEnumerable<TaskModel> tasks = TaskModel.GetTasksBetweenDates(username, startDate, endDate).Result;
return tasks.Where(task => task.Status == false).Select(task => (DateTime)task.Date).Distinct();
}
}
} |
# Minor_DET_IoT_AnoukPebesma
<h1>Hoe maak je een Philips Hue in minder dan 5 euro?</h1>
In dit artikel/verslag neem ik jou meer naar hoe jij dit kan maken. Ik zal hierbij de stappen uitleggen en de daarbij gemaakte fouten ook laten zien.
<h2> Wat heb je nodig? </h2>
<li>1x Arduino Board (ESP8266)</li>
<li>1x Jump wire</li>
<li>1x LEDstrip </li>
<li>Een 5Ghz WiFi (of hotspot) verbinding</li>
<li>Maar natuurlijk ook een laptop/computer en een USB-c kabel om de Arduino te verbinden. </li>
<h2> Stap 1: Installeer de Arduino IO library </h2>
<ol>
<li>
De eerste stap is om een extra library te installeren, de Adafruit IO Arduino (gemaakt door: Adafruit).<br>
Deze vind je door naar de library manager te gaan en 'Adafruit IO Arduino' op te zoeken in het zoekvlak, heb je hem gevonden? <br>
Druk op install all.
</li>
</ol>
<img width="242" alt="step1 1" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/55d80757-109b-417b-911b-fac5b87ca2c5">
<br>
<h2> Stap 2: Adafruit IO Setup </h2>
<ol>
<li>
Om te kunnen beginnen en gebruik te mogen maken van deze library. Moeten we een account aanmaken. <br>
Hiervoor gaan we naar 'https://io.adafruit.com/'. Druk hierbij op 'get started for free' en maak een account aan.
<img width="326" alt="step2" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/4895e213-334e-4914-8975-63704313c61b)"> <br>
Je zult dit scherm zien, druk hierbij bovenin oo IO, om naar stap 2 te kunnen.
</li>
<li>
In Adafruit IO aangekomen druk je op de gele sleutel in het menu.<br>
<img width="326" alt="step3" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/9b5286ca-b0f5-4419-85d8-04e16b931f20)"><br>
</li>
<li>
In het scherm dat je nu ziet, kopiër jij je key en je username. Deze heb je zo nodig!
</li>
</ol>
<br>
<h2> Stap 3: Adafruit IO Feed en Colorpicker aanmaken </h2>
<ol>
<li>
Ga naar Dashboards, in het menu van de io.adafruit site te vinden. Maak hierbij een nieuw dashboard aan, klik op 'New Dashboard'.<br>
<img width="326" alt="step4" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/0d911c3c-bb3f-4228-9bea-6867fc4339b6)"> <br>
</li>
<li>
Ga naar het dashboard.
</li>
<li>
Creëer een nieuw block, druk op het instellingen icoontje, zoals te zien op de afbeelding hieronder.<br>
<img width="326" alt="step5" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/1ea1b522-7745-45c9-a191-50c40ad9594e)"><br>
Hierbij krijg je onderstaand beeld tezien. Druk hierbij op 'Create New Block'. <br>
<img width="326" alt="step6" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/a0fc1e22-036d-402a-9622-df4b6fb40eeb)"> <br>
</li>
<li>
Kies color picker. <br>
<img width="326" alt="step7" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/f11cfa04-fbf6-4568-a5db-62dca2fad3c9"><br>
</li>
<li>
Creëer de feed naam: "color".<br>
Vergeet de feednaam niet! Deze moet je later toevoegen in je Arduino code. <br> Dit heeft even gekost voordat ik hier achterkwam, maar het is een belangrijk deel dat je beter niet kan vergeten. <br>
<img width="326" alt="step8" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/c67e8e88-c5a2-4fb8-89f0-917aaf089b2f"> <br>
Als je, je muis naast het tekst veld houd. Verschijnt hier een Creëer knop. <br>
<img width="326" alt="step9" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/9be94224-379c-4d09-9d72-95d812dc114c"> <br>
</li>
<li>
Creëer block.
</li>
<li>
Stel een kleur in met de color picker. Druk hierbij op de feed: color, die je zojuist hebt gemaakt.<br> Ga hierbij naar de volgende stap en verander de HEX code.<br>
<img width="326" alt="step10" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/1f6e797f-ff56-47e1-aa98-ec022cbf0ae4"> <br>
</li>
</ol>
<br>
<h2> Stap 4: Code aanpassen! </h2>
<ol>
<li>
Ga naar Arduino IDE. <br>
Ga naar file > examples > Adafruit IO Arduino > Adafruitio_14_neopixel <br>
<img width="1045" alt="step 11" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/c367cb5b-0889-4bc6-9e43-a5d27b60a67b"><br>
</li>
<li>
In tab ‘config.h’: plak je Adafruit IO username en Key in. <br>
<img width="780" alt="step12" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/364adf32-dc09-4c29-b651-bf3984263bec"><br>
</li>
<li>
In tab ‘config.h’: voer het wifi netwerk en wachtwoord in. <br>
A. (De NodeMCU werkt niet op 5Ghz WiFi) <br>
B. Gebruik liefst de hotspot van je telefoon, dit gebruikt < 0.1 Mb data per uur, dus niet bang zijn.<br>
Je moet even uittesten wat beter werkt. Bij de hotspot op mijn telefoon werkte het niet, maar op de wifi ging het wel goed! <br>
<img width="779" alt="step13" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/59c50387-0a64-4565-89e0-ee725e4fc29f"><br>
</li>
<li>
Ga naar de Tab adafruit_14_Neopixel.ino <br>
A. Pas: #define PIXEL_PIN 5 aan naar #define PIXEL_PIN D5<br>
B. Pas: #define PIXEL_COUNT 24 aan naar de hoeveelheid aan leds die je hebt. (Dit is iets wat ik eerst ook fout deed, maar het aanpassen laat de LEDstrip wel beter werken).<br> Verander alleen het getal 24 naar de hoeveelheid. <br>
<img width="447" alt="step14" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/8aa22a0c-8c0a-493f-8e45-c081483227a8"><br>
</li>
</ol>
<h2> Stap 5: Code uploaden </h2>
<ol>
<li>
Upoad de code!
</li>
<li>
Activeer de 'serial monitor'. Dit doe je door op de knop te drukken die hier onderstaand te zien is. <br>
<img width="48" alt="step15" src="https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/85f1ec5c-c338-4059-9c03-08af1ecc88c1">
<br>
</li>
<li>
Open de serial monitor (tab onderaan).
</li>
<li>
Zet de serial monitor op 115200 baud.
</li>
<li>
Als alles gelukt is zie je in de serial monitor dat je verbonden bent.
</li>
<li>
Verander nu in Adafruit IO de kleur, dat zie je terug in de Serial monitor.
</li>
<li>
Is je ledstrip ook goed aangesloten, dan kun je met de colorpicker de LED kleur aanpassen. Je hebt dus zelf een Philips (Signify) HUE gemaakt. Voor een paar euro. Adafruit draait ook op je mobiel!
</li>
</ol> <br>
<h2> Uiteindelijk resultaat!</h2>
Alle stappen doorlopen? Topper ben je! Geniet van je goedkope eigengemaakte Hue!<br>
https://github.com/AnoukPNL/Minor_DET_IoT_AnoukPebesma/assets/112867115/19f298ae-2da5-4c83-ba31-17fbda805cf6 |
<?php
/**
* CubeWp admin gallary field
*
* @version 1.0
* @package cubewp/cube/fields/admin
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* CubeWp_Admin_Gallery_Field
*/
class CubeWp_Admin_Gallery_Field extends CubeWp_Admin {
public function __construct( ) {
add_filter('cubewp/admin/post/gallery/field', array($this, 'render_gallery_field'), 10, 2);
}
/**
* Method render_gallery_field
*
* @param string $output
* @param array $args
*
* @return string html
* @since 1.0.0
*/
public function render_gallery_field( $output = '', $args = array() ) {
$args = apply_filters( 'cubewp/admin/field/parametrs', $args );
$output = $this->cwp_field_wrap_start($args);
if(!did_action( 'wp_enqueue_media')) wp_enqueue_media();
$args['not_formatted_value'] = $args['value'];
$args['value'] = cwp_handle_data_format( $args );
$input_name = !empty($args['custom_name']) ? $args['custom_name'] : 'cwp_meta[' . $args['name'] . ']';
$attachments = isset($args['value']) && is_array($args['value']) ? array_filter($args['value']) : $args['value'];
$attachments_list = '';
if(isset($attachments) && !empty($attachments)){
foreach($attachments as $attachment_id){
$attachment_id = cwp_get_attachment_id( $attachment_id );
$attachments_list .= '<li class="cwp-gallery-item" data-slug="'. $attachment_id .'">
<input type="hidden" name="'. $input_name .'[]" value="'. $attachment_id .'">
<div class="thumbnail">
<img src="'. wp_get_attachment_url($attachment_id) .'" alt="image">
</div>
<div class="cwp-gallery-actions">
<a class="remove-gallery-item" href="javascript:void(0);"><span class="dashicons dashicons-trash"></span></a>
</div>
</li>';
}
}
$accept_types = '';
if (isset($args["file_types"]) && !empty($args["file_types"])) {
$accept_types = $args["file_types"];
}
$output .= '<div id="cwp-gallery-' . $args['name'] . '" class="cwp-custom-field cwp-gallery-field" data-id="' . $args['name'] . '">
<div class="cwp-field">';
if (!empty($args['custom_name'])) {
$output .= '<input type="hidden" class="cwp-gallery-have-custom-name" value="' . esc_attr($args['custom_name']) . '">';
}
$output .= '<div class="cwp-gallery">
<ul class="cwp-gallery-list">
' . $attachments_list . '
</ul>
</div>
<a href="javascript:void(0);" class="button button-primary cwp-gallery-btn" data-allowed-types="' . $accept_types . '">Add Gallery Images</a>
</div>
</div>';
$output .= $this->cwp_field_wrap_end($args);
$output = apply_filters("cubewp/admin/{$args['name']}/field", $output, $args);
return $output;
}
}
new CubeWp_Admin_Gallery_Field(); |
@html_text_substitution=readme.txt|<a href="readme.html">readme.txt</a>
@external-css=allegro.css
@document_title=Allegro `const'-correctness
<center><h1><b>
Allegro `const'-correctness
</b></h1></center>
<hr>
<i>
This is a short document about the introduction of `const'-correctness
to Allegro. It details what changes have occurred to internal library
code, the API changes (mainly transparent) and what you will need to do
to adapt code to compile without warnings (again, mainly nothing).
</i>
@!text
@heading
Contents
@shortcontents
@text
@heading
Library changes
There are very few actual changes to the library code itself; only some
symbol declarations and definitions have been altered to include
AL_CONST. See below for a description of the AL_CONST preprocessor
define. In a few places, some string was changed that should not have
been - in these cases, the string is simply duplicated and then the
duplicate is erased on exiting the function.
In all, there were very few changes to the library code.
@heading
The AL_CONST preprocessor define
In order to support compilers which don't know about the `const'
keyword, or perhaps use a different keyword, the preprocessor symbol
AL_CONST is used wherever `const' would normally be used. Note that in
the documentation, I have used `const' for readability.
@heading
Allegro API changes
These are, generally speaking, totally transparent to the user. I did
not change the behaviour of any function; only its parameter types.
Basically, if you can pass it as <code>type* ptr</code>, then you can
pass it as <code>const type* ptr</code> without any problem whatsoever.
Note also that certain changes may remove warnings in your program as
static strings, etc, are now treated as `const' by Allegro functions.
There are a few places, described below, where there will be an effect
on existing code.
`const'-correctness is deemed important for two reasons. Firstly, it can
increase code readability and comprehension of Allegro functions (for
instance, you can see which parameters are altered and which are not).
Secondly, it ensures that the Allegro code is not changing data which it
should not be, and that client callback functions are not breaking
Allegro by changing data they should not be.
@heading
Callback functions and Pointers to Pointers
Certain callback functions now have a different type - they take `const'
pointers as opposed to non-`const' pointers. As far as I know, a
compiler will issue a warning about incompatible pointer types. You
should update your callback function to the new format (which will be
listed in the main Allegro documentation).
Also, when passing a pointer to a pointer to an Allegro function which
is declared as taking an <code>AL_CONST type** ptr</code>, you will need
to cast your pointer to be `const' if it is not already. For instance:
<codeblock>
int some_allegro_function(AL_CONST char** p);
void my_func(char** x)
{
some_allegro_function((AL_CONST char**) x);
}
<endblock>
I realise that this is a change to the Allegro API, and that we are
supposed to avoid those at all costs, but this is essentially fixing a
bug in Allegro and changing behaviour. It also ensures that
client-supplied callback functions are functioning correctly, and not
altering data that they should not. Callback functions which do not
treat relevant parameters as `const' are, in a small (but potentially
signficant) way, broken.
Please note that for the Unicode function ugetx(), I have provided an
alternative version ugetxc(), which takes a `const char**' parameter as
opposed to a `char**' parameter. This is because it is valid to pass
either a `char**' or a `const char**', but unfortunately there is no way
to tell the compiler exactly what we mean.
@heading
BITMAP objects
Allegro represents both a screen bitmap and a memory bitmap by a single
object; a BITMAP. Unfortunately, these two things can be very different.
For instance, reading a pixel from a bitmap would not seem to change it,
but if it is a screen bitmap we are reading from, then it is possible
that some parameter of the video card is changed to select the correct
line, etc.
Therefore, a const BITMAP parameter does not make sense, and is not used
throughout the library. This is unfortunate, but I cannot see any way
around it.
@heading
Finally...
Allegro `const'-correctness has been tested for quite enough time to say
that it is working OK. However, if you still find problems with a compiler,
please contact the Allegro mailing list; see `Contact info' in the Allegro
documentation (readme.txt).
Email: <email>lwithers@lwithers.demon.co.uk</a>.
Thanks for listening :-) |
<?php
/**
* novena_wp functions and definitions
*
* @link https://developer.wordpress.org/themes/basics/theme-functions/
*
* @package novena_wp
*/
if ( ! defined( '_S_VERSION' ) ) {
// Replace the version number of the theme on each release.
define( '_S_VERSION', '1.0.0' );
}
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which
* runs before the init hook. The init hook is too late for some features, such
* as indicating support for post thumbnails.
*/
function novena_wp_setup() {
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
* If you're building a theme based on novena_wp, use a find and replace
* to change 'novena_wp' to the name of your theme in all the template files.
*/
load_theme_textdomain( 'novena_wp', get_template_directory() . '/languages' );
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
/*
* Let WordPress manage the document title.
* By adding theme support, we declare that this theme does not use a
* hard-coded <title> tag in the document head, and expect WordPress to
* provide it for us.
*/
add_theme_support( 'title-tag' );
/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
*/
add_theme_support( 'post-thumbnails' );
// This theme uses wp_nav_menu() in one location.
register_nav_menus(
array(
'menu-1' => esc_html__( 'Primary', 'novena_wp' ),
)
);
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support(
'html5',
array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
'style',
'script',
)
);
// Set up the WordPress core custom background feature.
add_theme_support(
'custom-background',
apply_filters(
'novena_wp_custom_background_args',
array(
'default-color' => 'ffffff',
'default-image' => '',
)
)
);
// Add theme support for selective refresh for widgets.
add_theme_support( 'customize-selective-refresh-widgets' );
/**
* Add support for core custom logo.
*
* @link https://codex.wordpress.org/Theme_Logo
*/
add_theme_support(
'custom-logo',
array(
'height' => 250,
'width' => 250,
'flex-width' => true,
'flex-height' => true,
)
);
}
add_action( 'after_setup_theme', 'novena_wp_setup' );
/**
* Set the content width in pixels, based on the theme's design and stylesheet.
*
* Priority 0 to make it available to lower priority callbacks.
*
* @global int $content_width
*/
function novena_wp_content_width() {
$GLOBALS['content_width'] = apply_filters( 'novena_wp_content_width', 640 );
}
add_action( 'after_setup_theme', 'novena_wp_content_width', 0 );
/**
* Register widget area.
*
* @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
*/
function novena_wp_widgets_init() {
register_sidebar(
array(
'name' => esc_html__( 'Sidebar', 'novena_wp' ),
'id' => 'sidebar-1',
'description' => esc_html__( 'Add widgets here.', 'novena_wp' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
)
);
}
add_action( 'widgets_init', 'novena_wp_widgets_init' );
/**
* Enqueue scripts and styles.
*/
function novena_wp_scripts() {
// Bootstrap CSS
wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/assets/plugins/bootstrap/bootstrap.min.css', array(), _S_VERSION, 'all' );
// Iconfont CSS
wp_enqueue_style( 'iconfont', get_template_directory_uri() . '/assets/plugins/icofont/icofont.min.css', array(), _S_VERSION, 'all' );
// Font Awesome
wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.0/css/all.min.css', array(), _S_VERSION, 'all');
// Slick CSS
wp_enqueue_style( 'slick', get_template_directory_uri() . '/assets/plugins/slick-carousel/slick/slick.css', array(), _S_VERSION, 'all' );
// Main CSS
wp_enqueue_style( 'main', get_template_directory_uri() . '/assets/css/style.css', array(), _S_VERSION, 'all' );
// Slick Theme CSS
wp_enqueue_style( 'slick-theme', get_template_directory_uri() . '/assets/plugins/slick-carousel/slick/slick-theme.css', array(), _S_VERSION, 'all' );
wp_enqueue_style( 'novena-style', get_stylesheet_uri(), array(), _S_VERSION );
wp_style_add_data( 'novena-style', 'rtl', 'replace' );
// Bootstrap JS
wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/assets/plugins/bootstrap/bootstrap.min.js', array('jquery'), _S_VERSION, true );
// Slick JS
wp_enqueue_script( 'slick', get_template_directory_uri() . '/assets/plugins/slick-carousel/slick/slick.min.js', array('jquery'), _S_VERSION, true );
// Shuffle JS
wp_enqueue_script( 'shuffle', get_template_directory_uri() . '/assets/plugins/shuffle/shuffle.min.js', array('jquery'), _S_VERSION, true );
// Google Map JS
wp_enqueue_script( 'google-map', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAkeLMlsiwzp6b3Gnaxd86lvakimwGA6UA', array('jquery'), _S_VERSION, true );
// Gmap JS
wp_enqueue_script( 'gmap', get_template_directory_uri() . '/assets/plugins/google-map/gmap.js', array('jquery'), _S_VERSION, true );
// Script JS
wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/script.js', array('jquery'), _S_VERSION, true );
wp_enqueue_script( 'novena-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'novena_wp_scripts' );
/**
* Implement the Custom Header feature.
*/
require get_template_directory() . '/inc/custom-header.php';
/**
* Custom template tags for this theme.
*/
require get_template_directory() . '/inc/template-tags.php';
/**
* Functions which enhance the theme by hooking into WordPress.
*/
require get_template_directory() . '/inc/template-functions.php';
/**
* Customizer additions.
*/
require get_template_directory() . '/inc/customizer.php';
/**
* Load Jetpack compatibility file.
*/
if ( defined( 'JETPACK__VERSION' ) ) {
require get_template_directory() . '/inc/jetpack.php';
}
/**
* Load WooCommerce compatibility file.
*/
if ( class_exists( 'WooCommerce' ) ) {
require get_template_directory() . '/inc/woocommerce.php';
} |
package DiningPhilosopher;
import java.util.Random;
/**
* Created by tianbingleng on 2/12/2017.
*/
public class Philosopher implements Runnable{
private int id;
private Chopstick leftChopstick;
private Chopstick rightChopstick;
private Random random;
private int eatingCounter;
private volatile boolean isFull = false; // volatile make sure get from main memory, not from catch
public Philosopher(int id, Chopstick leftChopstick, Chopstick rightChopstick) {
this.id = id;
this.leftChopstick = leftChopstick;
this.rightChopstick = rightChopstick;
this.random = new Random();
}
@Override
public void run() {
try {
// whether stop or not (controlled by main)
while (!isFull) {
think();
if (leftChopstick.pickUp(this, State.LEFT)) {
if (rightChopstick.pickUp(this, State.RIGHT)) {
eat();
rightChopstick.putDown(this, State.RIGHT);
}
leftChopstick.putDown(this, State.LEFT);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void think() throws InterruptedException {
System.out.println(this + " is thinking...");
Thread.sleep(random.nextInt(1000));
}
private void eat() throws InterruptedException {
System.out.println(this + " is eating...");
this.eatingCounter++;
Thread.sleep(random.nextInt(1000));
}
public int getCounter() {
return this.eatingCounter;
}
public void setFull(boolean full) {
this.isFull = full;
}
@Override
public String toString() {
return " Philosopher " + this.id;
}
} |
// Copyright 2023 lucarondanini
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"bufio"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
)
type Configuration struct {
CLI_IP string `yaml:"ip"`
CLI_PORT string `yaml:"port"`
CLUSTER_NODE_IP string `yaml:"clusterNodeIp"`
CLUSTER_NODE_PORT string `yaml:"clusterNodePort"`
}
var (
configFileName = "bit-box-cli"
configFileType = "yaml"
configPaths = []string{
"/etc/bit-box/",
"$HOME/.bit-box",
".",
}
)
func LoadConfiguration(confFilePath string) (Configuration, error) {
if confFilePath != "" {
fmt.Println("Using configuration file: ", confFilePath)
locationPath := filepath.Dir(confFilePath)
tmpFileName := filepath.Base(confFilePath)
ext := filepath.Ext(confFilePath)
if ext != ".yaml" && ext != ".yml" {
panic("Configuration file requires .yaml or .yml extension")
}
fileName := strings.ReplaceAll(tmpFileName, ext, "")
return initConfiguration(fileName, configFileType, []string{locationPath})
} else {
return initConfiguration(configFileName, configFileType, configPaths)
}
}
func initConfiguration(fileName string, fileType string, paths []string) (Configuration, error) {
viper.SetConfigName(fileName)
viper.SetConfigType(fileType)
// call multiple times to add many search paths
for _, p := range configPaths {
viper.AddConfigPath(p)
}
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
conf := Configuration{}
//trying to guess local ip and port
if conf.CLI_IP == "" {
conf.CLI_IP = findLocalIp()
}
if conf.CLI_PORT == "" {
conf.CLI_PORT = findFreePort("", 0)
}
return conf, errors.New("CONFIG_FILE_NOT_FOUND")
} else {
// Config file was found but another error was produced
panic(fmt.Errorf("error loading config: %w ", err))
}
}
conf := Configuration{
CLI_IP: viper.GetString("ip"),
CLI_PORT: viper.GetString("port"),
CLUSTER_NODE_IP: viper.GetString("clusterNodeIp"),
CLUSTER_NODE_PORT: viper.GetString("clusterNodePort"),
}
return conf, nil
}
func findLocalIp() string {
netInterfaceAddresses, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, netInterfaceAddress := range netInterfaceAddresses {
networkIp, ok := netInterfaceAddress.(*net.IPNet)
if ok && !networkIp.IP.IsLoopback() && networkIp.IP.To4() != nil {
ip := networkIp.IP.String()
return ip
}
}
return ""
}
func findFreePort(p string, i int) string {
port := p
if port == "" {
port = "36367"
} else {
tmp, _ := strconv.Atoi(port)
tmp = tmp + 1
port = strconv.Itoa(tmp)
if i > 10 {
return ""
}
}
ln, err := net.Listen("tcp", ":"+port)
if err != nil {
//try next port
return findFreePort(port, i+1)
}
ln.Close()
return port
}
func getUserInput() string {
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
return strings.Replace(text, "\n", "", -1)
}
func getLocalIp(conf *Configuration) error {
fmt.Print("Local IP [" + conf.CLI_IP + "]: ")
cliIp := getUserInput()
if cliIp == "" && conf.CLI_IP != "" {
return nil
} else if cliIp == "q" {
return errors.New("USER_EXIT")
} else if cliIp == "" && conf.CLI_IP == "" {
fmt.Print("IP cannot be empty - type q to exit")
return getLocalIp(conf)
} else if cliIp != "" {
if net.ParseIP(cliIp) == nil {
fmt.Printf("Invalid IP Address: %s - type q to exit\n", cliIp)
return getLocalIp(conf)
}
conf.CLI_IP = cliIp
}
return nil
}
func getLocalPort(conf *Configuration) error {
fmt.Print("Local Port [" + conf.CLI_PORT + "]: ")
cliPort := getUserInput()
if cliPort == "" && conf.CLI_PORT != "" {
return nil
} else if cliPort == "q" {
return errors.New("USER_EXIT")
} else if cliPort == "" && conf.CLI_PORT == "" {
fmt.Println("Port cannot be empty - type q to exit")
fmt.Println()
return getLocalIp(conf)
} else if cliPort != "" {
conf.CLI_PORT = cliPort
}
return nil
}
func getLocalNetConf(conf *Configuration) error {
err := getLocalIp(conf)
if err != nil {
return err
}
err = getLocalPort(conf)
if err != nil {
return err
}
//test configuration:
ln, err := net.Listen("tcp", conf.CLI_IP+":"+conf.CLI_PORT)
if err != nil {
//try next port
fmt.Println("Error: " + err.Error())
fmt.Println()
getLocalNetConf(conf)
} else {
ln.Close()
}
return nil
}
func getRemoteIp(conf *Configuration) error {
fmt.Print("Cluster Node IP [" + conf.CLUSTER_NODE_IP + "]: ")
cliIp := getUserInput()
if cliIp == "" && conf.CLUSTER_NODE_IP != "" {
return nil
} else if cliIp == "q" {
return errors.New("USER_EXIT")
} else if cliIp == "" && conf.CLUSTER_NODE_IP == "" {
fmt.Println("IP cannot be empty - type q to exit")
fmt.Println()
return getRemoteIp(conf)
} else if cliIp != "" {
if cliIp != "localhost" {
if net.ParseIP(cliIp) == nil {
fmt.Printf("Invalid IP Address: %s - type q to exit\n", cliIp)
fmt.Println()
return getRemoteIp(conf)
}
}
conf.CLUSTER_NODE_IP = cliIp
}
return nil
}
func getRemotePort(conf *Configuration) error {
fmt.Print("Cluster Node Port [" + conf.CLUSTER_NODE_PORT + "]: ")
cliPort := getUserInput()
if cliPort == "" && conf.CLUSTER_NODE_PORT != "" {
return nil
} else if cliPort == "q" {
return errors.New("USER_EXIT")
} else if cliPort == "" && conf.CLUSTER_NODE_PORT == "" {
fmt.Print("Port cannot be empty - type q to exit")
fmt.Println()
return getRemotePort(conf)
} else if cliPort != "" {
conf.CLUSTER_NODE_PORT = cliPort
}
return nil
}
func getRemoteNetConf(conf *Configuration) error {
err := getRemoteIp(conf)
if err != nil {
return err
}
err = getRemotePort(conf)
if err != nil {
return err
}
return nil
}
func ConfigureCli(conf *Configuration) error {
err := getLocalNetConf(conf)
if err != nil {
return err
}
err = getRemoteNetConf(conf)
if err != nil {
return err
}
confFileName := "./" + configFileName + ".yml"
fmt.Print("Saving conf to " + confFileName + "? (Y/n): ")
goSave := getUserInput()
if goSave == "" || goSave == "y" || goSave == "Y" {
yamlData, err := yaml.Marshal(&conf)
if err != nil {
fmt.Println("Error: " + err.Error())
} else {
yamlData = append([]byte("# Conf file for bit-box CLI\n\n"), yamlData...)
err := os.WriteFile(confFileName, yamlData, 0644)
if err != nil {
fmt.Println("Could not save conf file: " + err.Error())
}
}
}
fmt.Println()
return nil
} |
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<title>
@yield('title')
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" sizes="180x180"
href="{{asset('storage/app/public/company')}}/{{$web_config['fav_icon']->value}}">
<link rel="icon" type="image/png" sizes="32x32"
href="{{asset('storage/app/public/company')}}/{{$web_config['fav_icon']->value}}">
<link rel="stylesheet" media="screen"
href="{{asset('public/assets/front-end')}}/vendor/simplebar/dist/simplebar.min.css"/>
<link rel="stylesheet" media="screen"
href="{{asset('public/assets/front-end')}}/vendor/tiny-slider/dist/tiny-slider.css"/>
<link rel="stylesheet" media="screen"
href="{{asset('public/assets/front-end')}}/vendor/drift-zoom/dist/drift-basic.min.css"/>
<link rel="stylesheet" media="screen"
href="{{asset('public/assets/front-end')}}/vendor/lightgallery.js/dist/css/lightgallery.min.css"/>
<link rel="stylesheet" href="{{asset('public/assets/back-end')}}/css/toastr.css"/>
<link rel="stylesheet" href="{{asset('css/bootstrap.css')}}"/>
<link rel="stylesheet" href="{{asset('css/all.min.css')}}"/>
<!-- Main Theme Styles + Bootstrap-->
<link rel="stylesheet" media="screen" href="{{asset('public/assets/front-end')}}/css/theme.min.css">
<link rel="stylesheet" media="screen" href="{{asset('public/assets/front-end')}}/css/slick.css">
<link rel="stylesheet" media="screen" href="{{asset('public/assets/front-end')}}/css/font-awesome.min.css">
<!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">-->
<link rel="stylesheet" href="{{asset('public/assets/back-end')}}/css/toastr.css"/>
<link rel="stylesheet" href="{{asset('public/assets/front-end')}}/css/master.css"/>
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Titillium+Web:wght@400;600;700&display=swap"
rel="stylesheet">
{{-- light box --}}
<link rel="stylesheet" href="{{asset('public/css/lightbox.css')}}">
<link rel="stylesheet" href="{{asset('public/assets/back-end')}}/vendor/icon-set/style.css">
@stack('css_or_js')
<link rel="stylesheet" href="{{asset('public/assets/front-end')}}/css/home.css"/>
<link rel="stylesheet" href="{{asset('public/assets/front-end')}}/css/responsive1.css"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
{{--dont touch this--}}
<meta name="_token" content="{{csrf_token()}}">
{{--dont touch this--}}
<!--to make http ajax request to https-->
<!--<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">-->
<style>
/* Button used to open the chat form - fixed at the bottom of the page */
.open-button {
background-color: #555;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
opacity: 0.8;
position: fixed;
bottom: 23px;
right: 28px;
width: 280px;
}
/* The popup chat - hidden by default */
.chat-popup {
display: none;
position: fixed;
bottom: 0;
right: 15px;
border: 3px solid #f1f1f1;
z-index: 9;
width:25rem
}
/* Add styles to the form container */
.form-container {
max-width: 100%;
/* padding: 10px; */
background-color: white;
min-height:30rem
}
/* Full-width textarea */
.form-container textarea {
border: none;
resize: none;
width:100%
}
/* When the textarea gets focus, do something */
.form-container textarea:focus {
background-color: #ddd;
outline: none;
}
/* Set a style for the submit/send button */
.form-container .btn {
background-color: #04AA6D;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
width: 100%;
margin-bottom:10px;
opacity: 0.8;
}
/* Add a red background color to the cancel button */
/* .form-container .cancel {
background-color: red;
} */
/* Add some hover effects to buttons */
.form-container .btn:hover, .open-button:hover {
opacity: 1;
}
body {
background-color: #fff;
}
.rtl {
direction: {{ Session::get('direction') }};
}
.password-toggle-btn .password-toggle-indicator:hover {
color: {{$web_config['primary_color']}};
}
.password-toggle-btn .custom-control-input:checked ~ .password-toggle-indicator {
color: {{$web_config['secondary_color']}};
}
.dropdown-item:hover, .dropdown-item:focus {
color: {{$web_config['primary_color']}};
text-decoration: none;
background-color: rgba(0, 0, 0, 0)
}
.dropdown-item.active, .dropdown-item:active {
color: {{$web_config['secondary_color']}};
text-decoration: none;
background-color: rgba(0, 0, 0, 0)
}
.topbar a {
color: black !important;
}
.navbar-light .navbar-tool-icon-box {
color: {{$web_config['primary_color']}};
}
.search_button {
background-color: {{$web_config['primary_color']}};
border: none;
}
.nav-link {
color: white !important;
}
.navbar-stuck-menu {
background-color: {{$web_config['primary_color']}};
min-height: 0;
padding-top: 0;
padding-bottom: 0;
}
.mega-nav {
background: white;
position: relative;
margin-top: 6px;
line-height: 17px;
width: 304px;
border-radius: 3px;
}
.mega-nav .nav-item .nav-link {
padding-top: 11px !important;
color: {{$web_config['primary_color']}} !important;
font-size: 20px;
font-weight: 600;
padding-left: 20px !important;
}
.nav-item .dropdown-toggle::after {
margin-left: 20px !important;
}
.navbar-tool-text {
padding-left: 5px !important;
font-size: 16px;
}
.navbar-tool-text > small {
color: #4b566b !important;
}
.modal-header .nav-tabs .nav-item .nav-link {
color: black !important;
/*border: 1px solid #E2F0FF;*/
}
.checkbox-alphanumeric::after,
.checkbox-alphanumeric::before {
content: '';
display: table;
}
.checkbox-alphanumeric::after {
clear: both;
}
.checkbox-alphanumeric input {
left: -9999px;
position: absolute;
}
.checkbox-alphanumeric label {
width: 2.25rem;
height: 2.25rem;
float: left;
padding: 0.375rem 0;
margin-right: 0.375rem;
display: block;
color: #818a91;
font-size: 0.875rem;
font-weight: 400;
text-align: center;
background: transparent;
text-transform: uppercase;
border: 1px solid #e6e6e6;
border-radius: 2px;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
transition: all 0.3s ease;
transform: scale(0.95);
}
.checkbox-alphanumeric-circle label {
border-radius: 100%;
}
.checkbox-alphanumeric label > img {
max-width: 100%;
}
.checkbox-alphanumeric label:hover {
cursor: pointer;
border-color: {{$web_config['primary_color']}};
}
.checkbox-alphanumeric input:checked ~ label {
transform: scale(1.1);
border-color: red !important;
}
.checkbox-alphanumeric--style-1 label {
width: auto;
padding-left: 1rem;
padding-right: 1rem;
border-radius: 2px;
}
.d-table.checkbox-alphanumeric--style-1 {
width: 100%;
}
.d-table.checkbox-alphanumeric--style-1 label {
width: 100%;
}
/* CUSTOM COLOR INPUT */
.checkbox-color::after,
.checkbox-color::before {
content: '';
display: table;
}
.checkbox-color::after {
clear: both;
}
.checkbox-color input {
left: -9999px;
position: absolute;
}
.checkbox-color label {
width: 2.25rem;
height: 2.25rem;
float: left;
padding: 0.375rem;
margin-right: 0.375rem;
display: block;
font-size: 0.875rem;
text-align: center;
opacity: 0.7;
border: 2px solid #d3d3d3;
border-radius: 50%;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
transition: all 0.3s ease;
transform: scale(0.95);
}
.checkbox-color-circle label {
border-radius: 100%;
}
.checkbox-color label:hover {
cursor: pointer;
opacity: 1;
}
.checkbox-color input:checked ~ label {
transform: scale(1.1);
opacity: 1;
border-color: red !important;
}
.checkbox-color input:checked ~ label:after {
content: "\f121";
font-family: "Ionicons";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: rgba(255, 255, 255, 0.7);
font-size: 14px;
}
.card-img-top img, figure {
max-width: 200px;
max-height: 200px !important;
vertical-align: middle;
}
.product-card {
box-shadow: 1px 1px 6px #00000014;
border-radius: 5px;
}
.product-card .card-header {
text-align: center;
background: white 0% 0% no-repeat padding-box;
border-radius: 5px 5px 0px 0px;
border-bottom: white !important;
}
.product-title {
font-family: 'Roboto', sans-serif !important;
font-weight: 400 !important;
font-size: 22px !important;
color: #000000 !important;
}
.feature_header span {
font-weight: 700;
font-size: 25px;
text-transform: uppercase;
}
html[dir="ltr"] .feature_header span {
padding-right: 15px;
}
html[dir="rtl"] .feature_header span {
padding-left: 15px;
}
@media (max-width: 768px ) {
.feature_header {
margin-top: 0;
display: flex;
justify-content: flex-start !important;
}
.store-contents {
justify-content: center;
}
.feature_header span {
padding-right: 0;
padding-left: 0;
font-weight: 700;
font-size: 25px;
text-transform: uppercase;
}
.view_border {
margin: 16px 0px;
border-top: 2px solid #E2F0FF !important;
}
}
.scroll-bar {
max-height: calc(100vh - 100px);
overflow-y: auto !important;
}
::-webkit-scrollbar-track {
box-shadow: inset 0 0 5px white;
border-radius: 5px;
}
::-webkit-scrollbar {
width: 3px;
}
::-webkit-scrollbar-thumb {
background: rgba(194, 194, 194, 0.38) !important;
border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
background: {{$web_config['secondary_color']}} !important;
}
.mobileshow {
display: none;
}
@media screen and (max-width: 500px) {
.mobileshow {
display: block;
}
}
[type="radio"] {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
[type="radio"] + span:after {
content: '';
display: inline-block;
width: 1.1em;
height: 1.1em;
vertical-align: -0.10em;
border-radius: 1em;
border: 0.35em solid #fff;
box-shadow: 0 0 0 0.10em{{$web_config['secondary_color']}};
margin-left: 0.75em;
transition: 0.5s ease all;
}
[type="radio"]:checked + span:after {
background: {{$web_config['secondary_color']}};
box-shadow: 0 0 0 0.10em{{$web_config['secondary_color']}};
}
[type="radio"]:focus + span::before {
font-size: 1.2em;
line-height: 1;
vertical-align: -0.125em;
}
.checkbox-color label {
box-shadow: 0px 3px 6px #0000000D;
border: none;
border-radius: 3px !important;
max-height: 35px;
}
.checkbox-color input:checked ~ label {
transform: scale(1.1);
opacity: 1;
border: 1px solid #ffb943 !important;
}
.checkbox-color input:checked ~ label:after {
font-family: "Ionicons", serif;
position: absolute;
content: "\2713" !important;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: rgba(255, 255, 255, 0.7);
font-size: 14px;
}
.navbar-tool .navbar-tool-label {
position: absolute;
top: -.3125rem;
right: -.3125rem;
width: 1.25rem;
height: 1.25rem;
border-radius: 50%;
background-color: {{$web_config['secondary_color']}}!important;
color: #fff;
font-size: .75rem;
font-weight: 500;
text-align: center;
line-height: 1.25rem;
}
.btn-primary {
color: #fff;
background-color: {{$web_config['primary_color']}}!important;
border-color: {{$web_config['primary_color']}}!important;
}
.btn-primary:hover {
color: #fff;
background-color: {{$web_config['primary_color']}}!important;
border-color: {{$web_config['primary_color']}}!important;
}
.btn-secondary {
background-color: {{$web_config['secondary_color']}}!important;
border-color: {{$web_config['secondary_color']}}!important;
}
.btn-outline-accent:hover {
color: #fff;
background-color: {{$web_config['primary_color']}};
border-color: {{$web_config['primary_color']}};
}
.btn-outline-accent {
color: {{$web_config['primary_color']}};
border-color: {{$web_config['primary_color']}};
}
.text-accent {
font-family: 'Roboto', sans-serif;
font-weight: 700;
font-size: 18px;
color: {{$web_config['primary_color']}};
}
a:hover {
color: {{$web_config['secondary_color']}};
text-decoration: none
}
.active-menu {
color: {{$web_config['secondary_color']}}!important;
}
.page-item.active > .page-link {
box-shadow: 0 0.5rem 1.125rem -0.425rem{{$web_config['primary_color']}}
}
.page-item.active .page-link {
z-index: 3;
color: #fff;
background-color: {{$web_config['primary_color']}};
border-color: rgba(0, 0, 0, 0)
}
.btn-outline-accent:not(:disabled):not(.disabled):active, .btn-outline-accent:not(:disabled):not(.disabled).active, .show > .btn-outline-accent.dropdown-toggle {
color: #fff;
background-color: {{$web_config['secondary_color']}};
border-color: {{$web_config['secondary_color']}};
}
.btn-outline-primary {
color: {{$web_config['primary_color']}};
border-color: {{$web_config['primary_color']}};
}
.btn-outline-primary:hover {
color: #fff;
background-color: {{$web_config['secondary_color']}};
border-color: {{$web_config['secondary_color']}};
}
.btn-outline-primary:focus, .btn-outline-primary.focus {
box-shadow: 0 0 0 0{{$web_config['secondary_color']}};
}
.btn-outline-primary.disabled, .btn-outline-primary:disabled {
color: #6f6f6f;
background-color: transparent
}
.btn-outline-primary:not(:disabled):not(.disabled):active, .btn-outline-primary:not(:disabled):not(.disabled).active, .show > .btn-outline-primary.dropdown-toggle {
color: #fff;
background-color: {{$web_config['primary_color']}};
border-color: {{$web_config['primary_color']}};
}
.btn-outline-primary:not(:disabled):not(.disabled):active:focus, .btn-outline-primary:not(:disabled):not(.disabled).active:focus, .show > .btn-outline-primary.dropdown-toggle:focus {
box-shadow: 0 0 0 0{{$web_config['primary_color']}};
}
.feature_header span {
background-color: #fafafc !important
}
.discount-top-f {
position: absolute;
}
html[dir="ltr"] .discount-top-f {
left: 0;
}
html[dir="rtl"] .discount-top-f {
right: 0;
}
.for-discoutn-value {
background: {{$web_config['primary_color']}};
}
.czi-star-filled {
color: #fea569 !important;
}
.flex-start {
display: flex;
justify-content: flex-start;
}
.flex-center {
display: flex;
justify-content: center;
}
.flex-around {
display: flex;
justify-content: space-around;
}
.flex-between {
display: flex;
justify-content: space-between;
}
.row-reverse {
display: flex;
flex-direction: row-reverse;
}
.count-value {
width: 1.25rem;
height: 1.25rem;
border-radius: 50%;
color: #fff;
font-size: 0.75rem;
font-weight: 500;
text-align: center;
line-height: 1.25rem;
}
</style>
<!--for product-->
<style>
.stock-out {
position: absolute;
top: 40% !important;
color: white !important;
font-weight: 900;
font-size: 15px;
}
html[dir="ltr"] .stock-out {
left: 35% !important;
}
html[dir="rtl"] .stock-out {
right: 35% !important;
}
.product-card {
height: 100%;
}
.badge-style {
left: 75% !important;
margin-top: -2px !important;
background: transparent !important;
color: black !important;
}
html[dir="ltr"] .badge-style {
right: 0 !important;
}
html[dir="rtl"] .badge-style {
left: 0 !important;
}
</style>
<style>
.dropdown-menu {
min-width: 304px !important;
/* margin-{{Session::get('direction') === "rtl" ? 'right' : 'left'}}: -8px !important; */
border-top-left-radius: 0px;
border-top-right-radius: 0px;
}
</style>
{!! \App\CPU\Helpers::get_business_settings('pixel_analytics') !!}
</head>
<!-- Body-->
<body class="toolbar-enabled">
<!-- Sign in / sign up modal-->
@include('layouts.front-end.partials._modals')
<!-- Navbar-->
<!-- Quick View Modal-->
@include('layouts.front-end.partials._quick-view-modal')
<!-- Navbar Electronics Store-->
@include('layouts.front-end.partials._header')
<!-- Page title-->
{{--loader--}}
<div class="row">
<div class="col-12" style="margin-top:10rem;position: fixed;z-index: 9999;">
<div id="loading" style="display: none;">
<center>
<img width="200"
src="{{asset('storage/app/public/company')}}/{{\App\CPU\Helpers::get_business_settings('loader_gif')}}"
onerror="this.src='{{asset('public/assets/front-end/img/loader.gif')}}'">
</center>
</div>
</div>
</div>
{{--loader--}}
<!-- Page Content-->
@yield('content')
<!-- Footer-->
<!-- Footer-->
@include('layouts.front-end.partials._footer')
<!-- Toolbar for handheld devices-->
<!--<div class="cz-handheld-toolbar" id="toolbar">
{{--@include('layouts.front-end.partials._toolbar')--}}
</div>-->
<!-- Back To Top Button-->
<button class="open-button" onclick="openForm()" style="width:4rem;height:4rem;border-radius:50%;background:#800080"><i class="fa-regular fa-comment fa-2x"></i></button>
<div class="chat-popup" id="myForm">
<form action="{{route('customers.messages.store')}}" method="post" class="form-container">
@csrf
<div style="display:flex;justify-content:space-between;background:#800080;padding:0.75rem 0.75rem 0 0.75rem">
<a style="cursor:pointer;color:#fff;" class="cancel text-white" onclick="closeForm()">X</a>
<p style="font-weight:700;color:#fff">{{ \App\CPU\translate('imdad')}}</p>
</div>
<div style="background: #f1f1f1;width:100%;min-height:24rem" id="chatImg"></div>
<div style="display:flex">
<textarea name="message" id="message" required style="background:#fff;padding:1rem 0 1rem 1rem"></textarea>
<button style="position:absolute;bottom:0.5rem;left:0.5rem;border:none;background:inherit" type="submit"><i class="fa-solid fa-plus"></i></button>
</div>
</form>
</div>
<!-- Vendor scrits: js libraries and plugins-->
<script src="{{asset('js/bootstrap.min.js')}}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
{{--<script src="{{asset('public/assets/front-end')}}/vendor/jquery/dist/jquery.slim.min.js"></script>--}}
<script src="{{asset('public/assets/front-end')}}/vendor/jquery/dist/jquery-2.2.4.min.js"></script>
<script src="{{asset('public/assets/front-end')}}/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script
src="{{asset('public/assets/front-end')}}/vendor/bs-custom-file-input/dist/bs-custom-file-input.min.js"></script>
<script src="{{asset('public/assets/front-end')}}/vendor/simplebar/dist/simplebar.min.js"></script>
<script src="{{asset('public/assets/front-end')}}/vendor/tiny-slider/dist/min/tiny-slider.js"></script>
<script src="{{asset('public/assets/front-end')}}/vendor/smooth-scroll/dist/smooth-scroll.polyfills.min.js"></script>
{{-- light box --}}
<script src="{{asset('public/js/lightbox.min.js')}}"></script>
<script src="{{asset('public/assets/front-end')}}/vendor/drift-zoom/dist/Drift.min.js"></script>
<script src="{{asset('public/assets/front-end')}}/vendor/lightgallery.js/dist/js/lightgallery.min.js"></script>
<script src="{{asset('public/assets/front-end')}}/vendor/lg-video.js/dist/lg-video.min.js"></script>
{{--Toastr--}}
<script src={{asset("public/assets/back-end/js/toastr.js")}}></script>
<!-- Main theme script-->
<script src="{{asset('public/assets/front-end')}}/js/theme.min.js"></script>
<script src="{{asset('public/assets/front-end')}}/js/slick.min.js"></script>
<script src="{{asset('public/assets/front-end')}}/js/sweet_alert.js"></script>
{{--Toastr--}}
<script src={{asset("public/assets/back-end/js/toastr.js")}}></script>
{!! Toastr::message() !!}
<script>
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
</script>
<script>
$(document).ready(function(){
$('#remove_cart_item').submit(function(e){
e.preventDefault();
let formData = new FormData(this);
let myId = $('input[name=myId]').val();
$.ajax({
type:'POST',
url: "/cart-remove-item/"+ myId +"",
data: formData,
contentType: false,
processData: false,
success: (response) => {
console.log(response);
},
error: function(response){
$('#image-input-error').text(response.responseJSON.message);
}
});
/* console.log(myId); */
});
$('.form-container').submit(function(e){
e.preventDefault();
let formData = new FormData(this);
let message = $('#message').val();
$.ajax({
type:'POST',
url: "{{route('customers.messages.store')}}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
this.reset();
Swal.fire('تم ارسال رسالتك بنجاح',);
$('#chatImg').append('<section><p>'+'ME:'+ message +'</p></section>')
/* console.log(response); */
},
});
/* console.log(myId); */
});
})
</script>
<script>
function addWishlist(product_id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: "{{route('store-wishlist')}}",
method: 'POST',
data: {
product_id: product_id
},
success: function (data) {
if (data.value == 1) {
Swal.fire({
position: 'top-end',
type: 'success',
title: data.success,
showConfirmButton: false,
timer: 1500,
});
$('.countWishlist').html(data.count);
$('.countWishlist-' + product_id).text(data.product_count);
$('.tooltip').html('');
} else if (data.value == 2) {
Swal.fire({
type: 'info',
title: 'WishList',
text: data.error
});
} else {
Swal.fire({
type: 'error',
title: 'WishList',
text: data.error
});
}
}
});
}
function removeWishlist(product_id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: "{{route('delete-wishlist')}}",
method: 'POST',
data: {
id: product_id
},
beforeSend: function () {
$('#loading').show();
},
success: function (data) {
Swal.fire({
type: 'success',
title: 'WishList',
text: data.success
});
$('.countWishlist').html(data.count);
$('#set-wish-list').html(data.wishlist);
$('.tooltip').html('');
},
complete: function () {
$('#loading').hide();
},
});
}
function quickView(product_id) {
$.get({
url: '{{route("quick-view")}}',
dataType: 'json',
data: {
product_id: product_id
},
beforeSend: function () {
$('#loading').show();
},
success: function (data) {
console.log("success...")
$('#quick-view').modal('show');
$('#quick-view-modal').empty().html(data.view);
},
complete: function () {
$('#loading').hide();
},
});
}
function addToCart(form_id = 'add-to-cart-form', redirect_to_checkout=false) {
if (checkAddToCartValidity()) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.post({
url: '{{ route("cart.add") }}',
data: $('#' + form_id).serializeArray(),
beforeSend: function () {
$('#loading').show();
},
success: function (response) {
console.log(response);
if (response.status == 1) {
updateNavCart();
toastr.success(response.message, {
CloseButton: true,
ProgressBar: true,
});
$('.call-when-done').click();
if(redirect_to_checkout)
{
location.href = "{{route('checkout-details')}}";
}
return false;
} else if (response.status == 0) {
Swal.fire({
icon: 'error',
title: 'Cart',
text: response.message
});
return false;
}
},
complete: function () {
$('#loading').hide();
}
});
} else {
Swal.fire({
type: 'info',
title: 'Cart',
text: '{{\App\CPU\translate("please_choose_all_the_options")}}'
});
}
}
function buy_now() {
addToCart('add-to-cart-form',true);
/* location.href = "{{route('checkout-details')}}"; */
}
function currency_change(currency_code) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '{{route("currency.change")}}',
data: {
currency_code: currency_code
},
success: function (data) {
toastr.success('{{\App\CPU\translate("Currency changed to")}}' + data.name);
location.reload();
}
});
}
function removeFromCart(key) {
$.post('{{ route("cart.remove") }}', {_token: '{{ csrf_token() }}', key: key}, function (response) {
console.log(response)
updateNavCart();
$('#cart-summary').empty().html(response.data);
toastr.info('{{\App\CPU\translate("Item has been removed from cart")}}', {
CloseButton: true,
ProgressBar: true
});
});
}
function updateNavCart() {
$.post('{{route("cart.nav-cart")}}', {_token: '{{csrf_token()}}'}, function (response) {
$('#cart_items').html(response.data);
});
}
function cartQuantityInitialize() {
$('.btn-number').click(function (e) {
e.preventDefault();
fieldName = $(this).attr('data-field');
type = $(this).attr('data-type');
var input = $("input[name='" + fieldName + "']");
var currentVal = parseInt(input.val());
if (!isNaN(currentVal)) {
if (type == 'minus') {
if (currentVal > input.attr('min')) {
input.val(currentVal - 1).change();
}
if (parseInt(input.val()) == input.attr('min')) {
$(this).attr('disabled', true);
}
} else if (type == 'plus') {
if (currentVal < input.attr('max')) {
input.val(currentVal + 1).change();
}
if (parseInt(input.val()) == input.attr('max')) {
$(this).attr('disabled', true);
}
}
} else {
input.val(0);
}
});
$('.input-number').focusin(function () {
$(this).data('oldValue', $(this).val());
});
$('.input-number').change(function () {
minValue = parseInt($(this).attr('min'));
maxValue = parseInt($(this).attr('max'));
valueCurrent = parseInt($(this).val());
var name = $(this).attr('name');
if (valueCurrent >= minValue) {
$(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
} else {
Swal.fire({
icon: 'error',
title: 'Cart',
text: '{{\App\CPU\translate("Sorry, the minimum value was reached")}}'
});
$(this).val($(this).data('oldValue'));
}
if (valueCurrent <= maxValue) {
$(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
} else {
Swal.fire({
icon: 'error',
title: 'Cart',
text: '{{\App\CPU\translate("Sorry, stock limit exceeded")}}.'
});
$(this).val($(this).data('oldValue'));
}
});
$(".input-number").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
}
function updateQuantity(key, element) {
$.post('<?php echo e(route("cart.updateQuantity")); ?>', {
_token: '<?php echo e(csrf_token()); ?>',
key: key,
quantity: element.value
}, function (data) {
updateNavCart();
$('#cart-summary').empty().html(data);
});
}
function updateCartQuantity(key) {
var quantity = $("#cartQuantity" + key).children("option:selected").val();
$.post('{{route("cart.updateQuantity")}}', {
_token: '{{csrf_token()}}',
key: key,
quantity: quantity
}, function (response) {
if (response.status == 0) {
toastr.error(response.message, {
CloseButton: true,
ProgressBar: true
});
$("#cartQuantity" + key).val(response['qty']);
} else {
updateNavCart();
$('#cart-summary').empty().html(response);
}
});
}
$('#add-to-cart-form input').on('change', function () {
getVariantPrice();
});
function getVariantPrice() {
if ($('#add-to-cart-form input[name=quantity]').val() > 0 && checkAddToCartValidity()) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: '{{ route("cart.variant_price") }}',
data: $('#add-to-cart-form').serializeArray(),
success: function (data) {
console.log(data)
$('#add-to-cart-form #chosen_price_div').removeClass('d-none');
$('#add-to-cart-form #chosen_price_div #chosen_price').html(data.price);
$('#set-tax-amount').html(data.tax);
$('#set-discount-amount').html(data.discount);
$('#available-quantity').html(data.quantity);
$('.cart-qty-field').attr('max', data.quantity);
}
});
}
}
function checkAddToCartValidity() {
var names = {};
$('#add-to-cart-form input:radio').each(function () { // find unique names
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function () { // then count them
count++;
});
if ($('input:radio:checked').length == count) {
return true;
}
return false;
}
$(".clickable").click(function () {
window.location = $(this).find("a").attr("href");
return false;
});
</script>
@if ($errors->any())
<script>
@foreach($errors->all() as $error)
toastr.error('{{$error}}', Error, {
CloseButton: true,
ProgressBar: true
});
@endforeach
</script>
@endif
<script>
jQuery(".search-bar-input").keyup(function () {
$(".search-card").css("display", "block");
let name = $(".search-bar-input").val();
if (name.length > 0) {
$.get({
url: '{{url('/')}}/searched-products',
dataType: 'json',
data: {
name: name
},
beforeSend: function () {
$('#loading').show();
},
success: function (data) {
$('.search-result-box').empty().html(data.result)
},
complete: function () {
$('#loading').hide();
},
});
} else {
$('.search-result-box').empty();
}
});
jQuery(".search-bar-input-mobile").keyup(function () {
$(".search-card").css("display", "block");
let name = $(".search-bar-input-mobile").val();
if (name.length > 0) {
$.get({
url: '{{url('/')}}/searched-products',
dataType: 'json',
data: {
name: name
},
beforeSend: function () {
$('#loading').show();
},
success: function (data) {
$('.search-result-box').empty().html(data.result)
},
complete: function () {
$('#loading').hide();
},
});
} else {
$('.search-result-box').empty();
}
});
jQuery(document).mouseup(function (e) {
var container = $(".search-card");
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide();
}
});
const img = document.getElementByTagName("img")
img.addEventListener("error", function (event) {
event.target.src = '{{asset('public/assets/front-end/img/image-place-holder.png')}}';
event.onerror = null
})
function route_alert(route, message) {
Swal.fire({
title: '{{\App\CPU\translate('Are you sure')}}?',
text: message,
type: 'warning',
showCancelButton: true,
cancelButtonColor: 'default',
confirmButtonColor: '{{$web_config['primary_color']}}',
cancelButtonText: 'No',
confirmButtonText: 'Yes',
reverseButtons: true
}).then((result) => {
if (result.value) {
location.href = route;
}
})
}
</script>
<script>
$(document).ready(function(){
$('#coupon-code-ajax').submit(function(e){
e.preventDefault();
let formData = new FormData(this);
$.ajax({
type:'POST',
url: "{{ route('check.copoun.code') }}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response.total_after_discount) {
this.reset();
Swal.fire(
'كود الخصم صحيح',
);
$('#cart_value').text(response.total_after_discount + ' ريال');
} else {
this.reset();
Swal.fire(
'كود الخصم غير صحيح',
)
}
},
error: function(response){
$('#image-input-error').text(response.responseJSON.message);
}
});
/* console.log('good'); */
});
/*
$('#sub_filters').submit(function(e){
e.preventDefault();
let formData = new FormData(this);
$.ajax({
type:'POST',
url: "{{ route('sub.category.search') }}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response.Product) {
/* console.log('good'); */
/* $('#pro_row').append().empty();
$.each(response.Product,function(key,item){
$('#pro_row').append('<div class="card" style="width: 18rem;"><a href="/product/"+ item.id +"">khaled adam</a></div>')
})
} else {
console.log('bad'); */
/* }
},
error: function(response){
$('#image-input-error').text(response.responseJSON.message);
} */
/* }); */
/* console.log('good'); */
/* }); */
})
</script>
<script>
$(document).ready(function(){
$('.coupon_code_check').submit(function(e){
e.preventDefault();
let formData = new FormData(this);
$.ajax({
type:'POST',
url: "{{ route('check.copoun.code') }}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response) {
this.reset();
Swal.fire(
response.total_after_discount
)
/* location.reload(); */
}
},
error: function(response){
$('#image-input-error').text(response.responseJSON.message);
}
});
});
});
</script>
@stack('script')
</body>
</html> |
using Audiobookshelf.ApiClient.JsonConverters;
using System;
using Newtonsoft.Json;
namespace Audiobookshelf.ApiClient.Dto
{
public class BookChapter
{
/// <summary>
/// The ID of the book chapter.
/// </summary>
[JsonProperty("id")]
public int Id { get; private set; }
/// <summary>
/// When in the book the chapter starts.
/// </summary>
[JsonProperty("start")]
[JsonConverter(typeof(AudiobookshelfSecondsToTimeSpan))]
public TimeSpan Start { get; private set; }
/// <summary>
/// When in the book the chapter ends.
/// </summary>
[JsonProperty("end")]
[JsonConverter(typeof(AudiobookshelfSecondsToTimeSpan))]
public TimeSpan End { get; private set; }
/// <summary>
/// The title of the chapter.
/// </summary>
[JsonProperty("title")]
public string Title { get; private set; }
}
} |
import datetime
import logging
from typing import Annotated, Literal
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import ExpiredSignatureError, JWTError, jwt
import bcrypt
from api.database import database, user_table
logger = logging.getLogger(__name__)
SECRET_KEY = "FsCyRyw001vCurt7d5qzQxZrxux3qXYU"
ALGORITHM = "HS256"
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/user/token")
def create_credentials_exception(detail: str) -> HTTPException:
return HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=detail,
headers={"WWW-Authenticate": "Bearer"},
)
def access_token_expire_minutes() -> int:
return 30
def confirm_token_expire_minutes() -> int:
return 24 * 60
def create_access_token(email: str, role: str):
logger.debug("Creating access token", extra={"email": email, "role": role})
expire = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=access_token_expire_minutes()
)
jwt_data = {"sub": email, "exp": expire, "type": "access", "role": role}
encoded_jwt = jwt.encode(jwt_data, key=SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def create_confirmation_token(email: str, role: str):
logger.debug("Creating confirmation token", extra={"email": email, "role": role})
expire = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=confirm_token_expire_minutes()
)
jwt_data = {"sub": email, "exp": expire, "type": "confirmation", "role": role}
encoded_jwt = jwt.encode(jwt_data, key=SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def get_subject_for_token_type(
token: str, type: Literal["access", "confirmation"]
) -> str:
try:
payload = jwt.decode(token, key=SECRET_KEY, algorithms=[ALGORITHM])
except ExpiredSignatureError as e:
raise create_credentials_exception("Token has expired") from e
except JWTError as e:
raise create_credentials_exception("Invalid token") from e
email = payload.get("sub")
if email is None:
raise create_credentials_exception("Token is missing 'sub' field")
token_type = payload.get("type")
if type is None or token_type != type:
raise create_credentials_exception(
f"Token has incorrect type, expected '{type}'"
)
return email
def get_password_hash(password: str) -> str:
pwd_bytes = password.encode('utf-8')
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password=pwd_bytes, salt=salt)
return hashed_password
def verify_password(plain_password: str, hashed_password: str) -> bool:
password_byte_enc = plain_password.encode('utf-8')
return bcrypt.checkpw(password = password_byte_enc , hashed_password = hashed_password)
async def get_user(email: str):
logger.debug("Fetching user from the database", extra={"email": email})
query = user_table.select().where(user_table.c.email == email)
logger.debug(f"Query: {query}")
result = await database.fetch_one(query)
if result:
return result
async def authenticate_user(email: str, password: str):
logger.debug("Authenticating user", extra={"email": email})
user = await get_user(email)
if not user:
raise create_credentials_exception("Invalid email or password")
if not verify_password(password, user.password):
raise create_credentials_exception("Invalid email or password")
if not user.confirmed:
raise create_credentials_exception("User has not confirmed email")
return user
async def authenticate_user_with_role(email: str, password: str, role: str):
logger.debug(f"Authenticating user with role {role}", extra={"email": email})
user = await get_user(email)
if not user:
raise create_credentials_exception("Invalid email or password")
if not verify_password(password, user.password):
raise create_credentials_exception("Invalid email or password")
if not user.confirmed:
raise create_credentials_exception("User has not confirmed email")
if user.role != role:
raise create_credentials_exception(f"User is not a {role}")
return user
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
email = get_subject_for_token_type(token, "access")
user = await get_user(email=email)
if user is None:
raise create_credentials_exception("Could not find user for this token")
return user |
- What is Database?
- database server - RDBMS type / NoSQL (eg. MongoDB)
- SQL-91 is the standard to write the queries
- database consists of
- table
- rows and colummns (a single column is a tuple)
- products
- postgresql, mysql, MariaDB, Oracle, MySQL server, Cassandra, MongoDB etc.
- installation of postgres
- sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
- wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
- sudo apt-get update
- sudo apt-get -y install postgresql
- sudop apt install postgtresql-contrib
- to install pgadmin4 - the interface
- curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add
- sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update'
- sudo apt update
- sudo apt install pgadmin4
- sudo /usr/pgadmin4/bin/setup-web.sh
- type http://127.0.0.1/pgadmin4 , to open pgadmin interface in browser
- to setup sever in pgadmin4
- sudo su - postgres
- psql
- create user <username> with password '<password>';
- create databse <database_name>
- grant all privileges on databse <databse_name> to <username>;
- ALTER USER user_name CREATEDB CREATEROLE LOGIN; --> gives username permission to create database
- queries
- create table
create table roles(
roleId SERIAL PRIMARY KEY,
rolename varchar(255),
datecreated date,
isSystemRole bool
)
create table users(
userId SERIAL,
First_name varchar (50),
Last_name varchar(50),
roleId int REFERENCES roles(roleId)
)
- data types
- int
- float
- decimal
- char
- varchar
- date
- timestamp
- time
- bool
- enum ["val1", "val2"] -> provides choice between the values (more than 2 allowed options are there, then use enum)
- insert
insert into roles (roleId, rolename, datecreated, isSystemRole) values(1, 'admin', now(), true)
- select
- in production, dont use * instead if needed type all the column(s) name
- auto increment
- serial --> postgres
- identity --> MsSQL
- auto_increment --> mysql
- relationship
- primary key --> it is a unique key, can't be NULL. usually it is assigned to the ID of the table
- foreign key
- alter table
alter table users add column emailId varchar(100) unique
alter table users alter column emailId type varchar (150)
- IN
- NOT IN
- select * from pg_database --> gives details about all the databases
- SELECT * FROM pg_catalog.pg_tables WHERE schemaname = 'public' --> shows the tables and their details
- select * from information_schema.columns where table_name = 'movies'; --> to describe a table
- Wildcard character
- * (of linux) == % in postgres, and mysql too
- ? (of linux) == _ (underscore) in postgres
- BETWEEN <DATE> AND <DATE> --> same can be done with, >= <date> and <= <date>
- better to use between..and, instead of logical operators. it is more optimised (in case of dates)
- select * from <table> LIMIT 5 --> gives first 5 records
- select * from <table> limit 5 offset 10 --> offset, so it removes first 10 characters and then shows 5 records
- in mysql, select * from <table> limit 5,10 --> it starts from 5th record and shows the next 10 records
- select * from <table> fetch first <n> row only --> gives the first n rows
- select top 5 from <table> --> same as others, but in MsSQL
- select * from <table> order by salary desc fetch first 5 row only --> maximum 5 salary records, use this instead using order by limit, it is more optimal
- select * from <table> offset 10 rows fetch first 10 rows only -> start with 11th row and display first 10 rows
- to get the last row, order by <auto_incremented_column> desc
- select distinct <column_name(s)> from <table> --> unique records wrt to the comboination of columns after distinct
- select 'text1' || 'text2' as <column_alias> --> shows, text1text2 under column 'column_alias'
- select concat(text1,text2) from <table> --> same as above
- select concat_ws(' ', text1, text2) from <table> --> it takes the separator first and places it at the required location
- aggregate functions
- SUM, MAX, MIN, COUNT, AVG
- select count(*) from <table> --> tell the no of records in the table
- again, * will result into large time, we can use count(movie_id), like the index column, we will still get the same result
- provide the alias ("as")
- it will also neglect the null value, if count is used for a particular column. while using for * it counts null value too
- select sum(column_name) from <table> --> returns the sum of the values of the mentioned column
- select min(column_name) from <table> --> tells the minimum value from the column
- select max(column_name) from <table> --> tells the maximum value from the column
- select avg(column_name) from <table> --> tells the average value from the column
- in case of null values, the above operation doesn;t count it, they just neglect it as it doesn't hold any value
- group by
- select <xxxxxx> from <table> group by <column_name> --> in place of xxxxx, use the column name used to group by, insted of *
- we can also use two or more columns to group by
- having
- we can't use where with aggregate functions, so we use having
- having is mainly used with group by
- ...group by having count(column_name) >5 --> shows the records with count of the column name values >5
- we can use where in combination with having, but where clause mustn't contain aggreagate function
- select 1+2 as ans --> these kind of calculations are also possible
- table relationships
- one to one
- one to many
- many to many
- JOINS
- INNER join
- select directors.director_id,
directors.first_name,
directors.last_name,
movies.movie_name
from directors
inner join movies
on directors.director_id = movies.director_id
where movies.movie_lang = 'English'
- select directors.director_id,
directors.first_name,
directors.last_name,
movies.movie_name,
movie_revenues.domestic_takings
from
directors
inner join movies
on directors.director_id = movies.director_id
inner join movie_revenues on
movies.movie_id = movie_revenues.movie_id
--> the above is the method to join 3 tables, we have to type inner join separately and use on with it separately too
- LEFT join
- select d.director_id,
d.first_name,
d.last_name,
mo.movie_name
from directors d
left join
movies mo
on d.director_id = mo.director_id
- RIGHT join
- select d.director_id,
d.first_name,
d.last_name,
mo.movie_name
from movies mo
right join
directors d
on d.director_id = mo.director_id
- FULL join
- select d.director_id,
d.first_name,
d.last_name,
mo.movie_name
from movies mo
full join
directors d
on d.director_id = mo.director_id
- JOINS are more time efficient than subqueries
- UNION
- merge tables but the same column number from them
- select first_name,last_name from actors UNION
select first_name, last_name from directors
- if there is a duplicacy in the tables, it shows one instance only
- it is like the (U) symbol in mathematics
- UNION ALL
- it doesn't remove the duplicate values, it keeps them all
- INTERSECT
- it does the same function as the intersect in maths
- select first_name from directors INTERSECT select first_name from actors
- EXCEPT
- just opposite of INTERSECT
- select first_name from directors EXCEPT select first_name from actors
- SUBQUERIES
- non correlated subquery
- select movie_name, movie_length from movies where movie_length > (select avg(movie_length) from movies)
--> here we haven't hardcoded the avg value, instead we kept it dynamic
- correlated subquery
- select
d1.first_name,
d1.last_name,
d1.date_of_birth,
d1.nationality
from directors d1
where date_of_birth = (select min(date_of_birth) from directors d2 where d2.nationality=d1.nationality)
- using IN
- select movie_name from
movies
where movie_id IN
(select movie_id from movie_revenues where
international_takings > domestic_takings)
ALTERNATE to above command (not same result, just showing the use)
select
mo.movie_id,
mo.movie_name,
d.first_name,
d.last_name
from movies mo
join
directors d
on mo.director_id = d.director_id
where movie_id IN
(select movie_id from movie_revenues where
international_takings > domestic_takings)
- string functions
- select 'daksh bindal' --> return daksh bindal
- select UPPER('abc') --> uppercase
- select LOWER("ABC") --> convert to lower case
- select INITCAP('abc') --> capitalise initial letter for space separated keywords
- also applicable to column of tables
- select left('india',3) --> shows 3 characters from left
- select left('india', -2) --> it will remove last 2 characters. and prints the remaining
- select right('india',3) --> shows the right 3 characters, here 'dia'
---- space is included in both left and right
- select reverse('india') --> reverses the string
- select substring('india',x,y) --> starting from x, displays the next y characters (including xth letter). for first charcter x=1
- select replace('i am from india','india','USA') --> original text, text to replace, text to replace with
- select split_part('firstname.lastname@google.com','@',1) --> splits it into parts, the separator is @ (here),separator is not included anywhere, 1 is for showing the 1st part
- select adte_of_birth::TEXT from directors --> coonvert dob which was originally date data type to text data type using the shown syntax
- codes
- code 1.
# -- Database: innov
# -- DROP DATABASE IF EXISTS innov;
# -- drop table roles;
# create table roles(
# roleId SERIAL PRIMARY KEY,
# rolename varchar(255),
# datecreated date,
# isSystemRole bool
# )
# create table users(
# userId SERIAL,
# First_name varchar (50),
# Last_name varchar(50),
# roleId int REFERENCES roles(roleId)
# )
# insert into roles (roleId, rolename, datecreated, isSystemRole) values(1, 'admin', now(), true)
# select * from roles;
# alter table users add column emailId varchar(100) unique
# alter table users alter column emailId type varchar (150)
# select * from users
# - delete from <table_name> --> deletes the data from the table but not the table
# - drop table <table_nbame> --> delete the whole table
# - truncate also does what delete does, but truncate doesn't use where cluase, while delete does
- code 2
# -- Database: innov
# -- DROP DATABASE IF EXISTS innov;
# -- drop table roles;
# create table roles(
# roleId SERIAL PRIMARY KEY,
# rolename varchar(255),
# datecreated date,
# isSystemRole bool
# )
# create table users(
# userId SERIAL,
# First_name varchar (50),
# Last_name varchar(50),
# roleId int REFERENCES roles(roleId)
# )
# insert into roles (roleId, rolename, datecreated, isSystemRole) values(1, 'admin', now(), true)
# select * from roles;
# alter table users add column emailId varchar(100) unique
# alter table users alter column emailId type varchar (150)
# select * from users
# -- insert into roles (rolename, datecreatd, issystemrole) into
# -- select rolename, datecreated, issystemrole from rolesold where issystemrole is true
# update roles set rolename = 'Sr. Manager' where roleid= 3
- insert into roles (rolename, datecreatd, issystemrole) into
select rolename, datecreated, issystemrole from rolesold where issystemrole is true
--> the above query insert the output from rolesold table to the roles table
- CRUD operation
- create
- read --> select command
- update --> update roles set rolename = 'Sr. Manager' where roleid= 3
- delete --> delete from roles where roleId= 3, deletes the record for roleid=3
- TODO
- find the optimisation techniques
# - to run
# - sudo su - postgres
# - psql
- JSON
- JAVASCRIPT OBJECT NOTATION
- In mongo db data is stored in json formal not in tabular format
-
[
{
'column1':value,
'column2':value,
'column3':value
},
{
.......
}
]
- data in each curly bracket is row data
- the above data is a text format of json
- in JSONB, the data is stored in binary format, so it would be faster than the text format
- select '{....}' --> the content inside the {} brackket is called json object which will be stored in the tuple as a text format
- select '{"title":"i am iron man"}'::JSON --> this is the format if we want to convert text to json
- if there are spaces in {} before "" then convert to jsonb format using ::jsonb
- create table books(
bookId serial primary key,
bookinfo jsonb
)
insert into books (bookinfo) values ('{"title":"book 1"}')
insert into books (bookinfo) values ('{"title":"book 2"}')
insert into books (bookinfo) values ('{"title":"book 3"}')
select * from books
in this json object will be inserted into the table
- select bookId, bookinfo->'title' from books --> this gives the value corresponding to the title in bookinfo column in the string format
- select bookId, bookinfo->>'title' from books --> here it will give the content inside the value of the key
- update books set bookinfo =bookinfo || '{"author":"authorname"}' where bookId=1 --> it will upodate
- now if we will run this query again, we would not see other author key, but update the previous one
this is only possible in postgre when done with json
- update books set bookinfo = bookinfo || '{"author":"author 1", "category":"science"}' where bookinfo->> 'author'='authorname new' --> see the >> used, used to change the content
- update books set bookinfo = bookinfo - 'category' where bookinfo->> 'author'='author 1' --> here the category key will be removed
- to convert a simple rdbms table to format of json object
- select row_to_json(directors) from directors
- select row_to_json(mydirectors) from (select director_id, first_name, last_name from directors) as mydirectors
--> it converts the specified column to json object only
- VIEWS
- virtual representation of any statement and you give a particular name to that statement which act as virtual table where you can perform operations without affecting the actual table
- virtual table basically
- create or replace view moviedetails as <query> --> creats a view
- select * from moviedetails --> see the view
- it basically behaves exactly like a table and doesn't bother the original tables
- it has no physical presence
- views cant be modified in postgres
- Triggers and functions
- a trigger is defined as any event that sets a course of sequence or action in a real time environment
- events
- insert, update, delete, truncate
- when
- before the event happens
- after the event has happened
- instead of the event, we are bypassing the event and doing something of our own
- level
- table
- row
- triggers are applied on tables and views only
- a FUNCTION is a logic which will be executed on triggered event
- way to create function and trigger
create table players(
player_id serial primary key,
name varchar(100)
);
create table players_audits(
player_audit_id serial primary key,
player_id int not null,
name varchar(100),
edit_date timestamp not null
)
insert into players (name) values('Virat Kohli');
insert into players (name) values('Ms Dhoni');
insert into players (name) values('Rohit sharma');
create or replace function fn_player_name_changes_log()
returns trigger
language PLPGSQL #-- language
as $$
begin
if new.name <> old.name then
insert into players_audits (player_id, name, edit_date) values (old.player_id, old.name, now());
end if;
return new;
end;
$$
# -- creating a trigger for the function on the table player
create trigger trigger_player_name_changes
# --before|after|instead insert|update|delete|truncate
before update
on players
for each row
execute procedure fn_player_name_changes_log();
update players set name = 'Mahendra singh dhoni' where player_id= 2
update players set name = 'Sourav Ganguly' where player_id=2
select * from players
select * from players_audits;
- MONGO DB
- data is never stored in rows and column
- maintained in json format
- no need to establish relationship
- collection==tables, document=row
- collections are there, everything is clubbed into json format
- the database style is known as NoSQL
- https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/
- follow the above tutorial to install mongodb
- the mongod stands for mongo+daemon
- mongodb is the database
- to start mongodb, type mongo in the terminal
- there are 3 options for user interface; monogdb compass, robo3t/studio3t, shell/terminal
- download robo3t or studio3t, robo is free version of studio
- unzip the file and go to bin folder and run the robo3t script using ./robot3t, as it is an executable
- give the chmod permissions if needed
- do the formatlities
- create a new connection, test it and connect it
- working on mongodb
- open terminal or open through right clicking on server menu and click open shell
- use <db_name> --> switch to database, if doenst exists create the database
- db.<db_name>.insertOne --> db.Employee.insertOne --> allows us to insert "one" record into the newly created table(employee)
db.Employeee.insertOne(
{
firstname: "Nilesh",
lastname: "Parekh",
email: "nilesh@google.com",
age: 45,
isMarried: true
}
)
--> creates new record
--> this will auto insert an auto incremented id key in this document
--> auto increment SHA256 unique identifier
--> id is the alphanumeric, not numeric
- db.Employeee.insertMany([{
firstname: "Nitin",
lastname: "Shah",
email: "nitin@google.com",
age: 42,
isMarried: true
},
{
firstname: "Sachin",
lastname: "Shah",
email: "sachin@google.com",
age: 40,
isMarried: true
}])
--> can insert mulitple records using insertMany
--> used [] to make it an array for easy insertion
- db.RecordsDB.insertMany(
[
{
name: "Marsh", age: "6 years", species: "Dog",
ownerAddress: "380 W. Fir Ave", chipped: true
},
{
name: "Kitana", age: "4 years",
species: "Cat", ownerAddress: "521 E. Cortland", chipped: true
}
]
)
- we can insert more columns in the table than we have inserted earlier, i.e. we can introduced new column(s) for a particular record(s) also, so the schema is flexible
- db.RecordsDB.find() --> list all the records
- db.<dbname>.find({"firstname":"John"}) --> to fetch user with name John, equivalent to Select * from dbname where firstname="John"
- db.<dbname>.find({firstname:1, lastname:1}) --> equivalent to select firstname, lastname from dbname;
- db.<dbname>.find({column1:0, column:2}) --> lists all the columns except column1 and column2 (0 means false, 1 means true)
- db.RecordsDB.findOne({"age": "8 years"}) --> lists the first row it encounters fulfilling the given constraint
- db.RecordsDB.find( { status: "A" }, { item: 1, status: 1 } ) --> Specific fields
- db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } ) --> ignore _id
- db.inventory.find( { status: "A" }, { status: 0, instock: 0 } ) --> return all but these fields
- db.<dbname>.find({}).sort({age: 1}) --> sort by ascending order
- db.<dbname>.find({}).sort({age: -1}) --> sort by descending order
- db.<dbname>.find( { $and:[ {firstname:"xyz"}, {lastname: "abc"}] }) --> listing records matching both condition
- db.<dbname>.find( { $or:[ {firstname:"xyz"}, {lastname: "abc"}] }) --> listing records matching either condition
- db.<dbname>.find( {age: {$in: [40,42]}}) --> listing with either 40 or 42
- db.RecordsDB.updateOne({name: "Marsh"}, { $set: {ownerAddress: "451 W. Coffee St. A204"}})
- db.RecordsDB.updateMany({species: "Dog"}, {$set: {age: "5"}})
- db.RecordsDB.replaceOne({name: "Kevin"}, {name: "Maki"})
- db.RecordsDB.deleteOne({name: "Maki"})
- db.RecordsDB.deleteMany({species: "Dog"})
- db.RecordsDB.count()
- db.RecordsDB.find().limit(10) --> showing first 10 only
- if we run mongo through aws server, then want to connect it with robo3t, either do ssh tunnel or go to etc/mongod.conf and scroll down
to IP and at the place of 127.0.0.1, write 0.0.0.0 and save
- restart the mongo service and connect with robo3t. at the time of creation in robo3t type public ip at the place of localhost
- ELASTIC SEARCH |
/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";
import Image from "next/image";
import React, { useEffect, useState, useRef } from "react";
interface Props {
label: string;
visible?: boolean;
color?:string;
setVisible?: React.Dispatch<React.SetStateAction<boolean>>;
withIcon?: boolean;
iconComponent?: React.ReactNode;
value: string;
placeholder: string;
disabled?: boolean;
setValue: (e: React.ChangeEvent<HTMLInputElement>) => void;
name?: string;
handleKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
type?:string
}
export default function SettingsTextField({ label, name, ...rest }: Props) {
const ref = useRef(null)
const[divFocus, setDivFocus] = useState(false)
const active = () => {
if(typeof window !== "undefined"){
return document.activeElement
}
}
const activeElement = active()
useEffect(() => {
if(activeElement === ref.current){
setDivFocus(true)
}else {
setDivFocus(false)
}
},[activeElement])
// const handleClick = () => {
// if(ref.current !== null){
// ref.current.focus()
// }
// }
return (
<div css ={{display: "flex" , flexDirection: "column", marginBottom: "1rem"}}>
<label
css={{
fontSize: "16px",
fontWeight: "bold",
fontFamily: "'Nunito', sans-serif",
marginBottom: "0.6rem"
}}
>
{label}
</label>
<div
tabIndex={0}
css={{
position: "relative",
border: divFocus ? `2px solid ${"#7C35AB"}` : `1px solid ${"#C0C0C0"}`,
borderRadius: "10px",
background: "#fff",
height: "49px",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
paddingRight: "13px",
":hover" : {
border: rest.disabled ? `1px solid ${"#C0C0C0"}` : `2px solid ${"#7C35AB"}`,
},
}}
>
<input
css={{
border: "none",
outline: "none",
background: "inherit",
width: "100%",
height: "100%",
borderRadius: "10px",
paddingLeft: "5%",
color: "#000",
fontFamily: "'Poppins', sans-serif",
}}
ref = {ref}
onClick={() => setDivFocus(true)}
type={rest.type || "text"}
value={rest.value}
name={name}
disabled = {rest.disabled}
placeholder={rest.placeholder}
onChange={(e) => rest.setValue(e)}
onKeyDown={(e) => {
if(rest.handleKeyDown){
rest.handleKeyDown(e);
}
}}
/>
{rest.withIcon && <>{rest.iconComponent}</>}
</div>
</div>
);
}
export const SettingsPasswordTextField = ({ label,placeholder, ...rest }: Props) => {
const [value, setValue] = useState("");
return (
<div css ={{display: "flex" , flexDirection: "column", marginBottom: "1rem"}}>
<label
css={{
fontSize: "16px",
fontWeight: "bold",
fontFamily: "'Nunito', sans-serif",
marginBottom: "0.6rem"
}}
>
{label}
</label>
<div
css={{
position: "relative",
border: `1px solid ${"#C0C0C0"}`,
borderRadius: "7px",
background: "#fff",
height: "50px",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
paddingRight: "13px",
}}
>
<input
css={{
border: "none",
outline: "none",
background: "inherit",
width: "100%",
height: "100%",
borderRadius: "7px",
paddingLeft: "3%",
fontFamily: "'Nunito', sans-serif",
color: rest.color ? rest.color : "#AEAEAE",
fontWeight: "bold",
}}
type={rest.visible ? "text" : "password"}
placeholder={placeholder}
onChange={(e) => setValue(e.target.value)}
/>
<div
css={css`
transform: ${rest.visible ? "rotate(180deg)" : "rotate(0deg)"};
cursor: pointer;
`}
onClick={() =>
(rest.setVisible as React.Dispatch<React.SetStateAction<boolean>>)(
!rest.visible
)
}
>
<Image
src="/assets/svgs/eye_close.svg"
alt="icon"
width={13.39}
height={6.55}
/>
</div>
</div>
</div>
);
}; |
import React, { Provider } from 'react'
import { Alert, Image, StatusBar } from 'react-native'
import { Text, View } from 'react-native-animatable'
import { SafeAreaView } from 'react-native-safe-area-context'
import { styles } from '../Stylos/Styles'
import RadialGradient from 'react-native-radial-gradient';
import { TextField, FilledTextField, OutlinedTextField } from 'rn-material-ui-textfield'
import AwesomeButton, { AfterPressFn } from "react-native-really-awesome-button-fixed";
import { NativeStackNavigationProp } from '@react-navigation/native-stack'
import RootStackParamList, { RootMain } from '../TypeDefinitios/DefinitiosNavigateMain'
import { useNavigation } from '@react-navigation/native'
import auth from '@react-native-firebase/auth';
import { printLocation } from 'graphql'
type ProfileScreenHomeNavigation = NativeStackNavigationProp<RootStackParamList, 'PresOne'>;
type ProfileScreenHomeRoot = NativeStackNavigationProp<RootMain, 'Auth'>;
async function functionRegister(user:string,pwd:string,nombre:string):Promise<String>{
return await auth()
.createUserWithEmailAndPassword(user, pwd)
.then((result) => {
console.log('User account created & signed in!');
result.user.updateProfile({
displayName:nombre
})
return 'true'
})
.catch(error => {
if (error.code === 'auth/email-already-in-use') {
console.log('That email address is already in use!');
return 'useemail'
}
if (error.code === 'auth/invalid-email') {
console.log('That email address is invalid!');
return 'invalided'
}
return error.code
}).finally(() => {
return 'false'
})
}
function showAlert(title:string,subtitle:string,button:string,dat:Function) {
Alert.alert(
title,
subtitle,
[{
text: button,
onPress: () => dat
},]
)
}
function ReguisterScreen() {
const AuthStack = useNavigation<ProfileScreenHomeNavigation>();
const AuthStackroot = useNavigation<ProfileScreenHomeRoot>();
const nombre = React.createRef<TextField>()
const email = React.createRef<TextField>()
const password = React.createRef<TextField>()
const pwdverifi = React.createRef<TextField>()
const [button,setbutton] = React.useState<boolean>(false)
const [stateError,setstateError] = React.useState<String>("")
const [stateEmail,setstateEmail] = React.useState<String>("")
const [stateButton,setButton] = React.useState<Boolean>(false);
React.useEffect(() => {
if(nombre.current?.value()!= "" && email.current?.value()!="" && password.current?.value()!= "" && pwdverifi.current?.value()!=""){
if(stateError=="" && stateEmail==""){
setbutton(true)
}else{
setbutton(false)
}
}else{
setbutton(false)
}
}, [stateError,stateEmail]);
function onSubmitPassword() {
console.log("SE EDITO")
password.current?.blur()
}
function onEmailVerify(params:string) {
const regexp = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
if(regexp.test(params)){
setstateEmail("")
}else{
setstateEmail("Email no es correcto")
}
}
function onChangeVerify(pwd:String) {
if(password.current?.value() != pwd ){
setstateError("La contraseña no es igual")
}else{
setstateError("")
}
}
return (
<SafeAreaView style={[styles.container, { backgroundColor: '#004B63' }]}>
<StatusBar hidden={true} showHideTransition={'fade'} />
<View style={{
zIndex: 2, alignItems: 'center',
shadowOffset: {
width: 10,
height: 200,
},
width: 380, height: 700, borderTopLeftRadius: 90, borderTopRightRadius: 90, borderBottomLeftRadius: 91, borderBottomRightRadius: 91, borderWidth: 0,
shadowColor: '#00FFF2',
shadowOpacity: 0.5,
shadowRadius: 20,
elevation: 25
}}>
<RadialGradient style={{ position: 'absolute', width: 360, height: 500, justifyContent: 'center', alignItems: 'center' }} colors={['#3BFFF533', '#182B3733', 'transparent']}
stops={[0.5, 0.2, 0.2, 0.2]}
center={[190, 250]}
radius={350}>
<Image style={{ width: 180, height: 180, bottom: 90, borderRadius: 100,borderWidth:1,borderColor: '#36A382'}} source={require('../Dranwable/TabsDraws/Icon/MyLogo.png')} />
</RadialGradient>
<View style={{ width: 280, height: 400, padding: 15, top: 250 }}>
<FilledTextField
// style={{borderBottomWidth:2}}
ref={nombre}
lineWidth={3}
clearTextOnFocus={false}
inputContainerStyle={{
// fontWeight: 'bold',
paddingTop: 6,
paddingLeft: 10,
backgroundColor: 'transparent',
borderColor: 'aqua',
borderRadius: 20,
shadowColor: '#00FFF2',
shadowOpacity: 0.5,
shadowRadius: 100,
elevation: 30
}}
textColor='white'
tintColor='white'
baseColor='#00FFDD95'
fontSize={15}
labelFontSize={20}
secureTextEntry={false}
autoCapitalize="none"
autoCorrect={false}
enablesReturnKeyAutomatically={true}
returnKeyType="done"
label="Nombre"
title="Inserte su Nombre"
maxLength={30}
characterRestriction={30}
autoCompleteType="username"
textContentType="name"
keyboardType="default"
/>
<FilledTextField
ref={email}
clearTextOnFocus={false}
onChangeText={(text) => {onEmailVerify(text)}}
error={stateEmail.toString()}
lineWidth={3}
inputContainerStyle={{
// fontWeight: 'bold',
paddingTop: 6,
paddingLeft: 10,
backgroundColor: 'transparent',
borderColor: 'aqua',
borderRadius: 20,
shadowColor: '#00FFF2',
shadowOpacity: 0.5,
shadowRadius: 100,
elevation: 30
}}
textColor='white'
tintColor='white'
baseColor='#00FFDD95'
fontSize={15}
labelFontSize={20}
secureTextEntry={false}
autoCapitalize="none"
autoCorrect={false}
enablesReturnKeyAutomatically={true}
returnKeyType="done"
label="Email"
title="Inserte su correo electronico"
maxLength={30}
characterRestriction={30}
autoCompleteType="email"
textContentType="emailAddress"
keyboardType="email-address"
/>
<FilledTextField
ref={password}
// style={{borderBottomWidth:2}}
lineWidth={3}
clearTextOnFocus={false}
inputContainerStyle={{
paddingTop: 6,
paddingLeft: 10,
backgroundColor: 'transparent',
borderColor: 'aqua',
borderRadius: 20,
shadowColor: '#00FFF2',
shadowOpacity: 0.5,
shadowRadius: 100,
elevation: 30
}}
textColor='white'
tintColor='white'
baseColor='#00FFDD95'
fontSize={15}
labelFontSize={20}
secureTextEntry={true}
autoCapitalize="none"
autoCorrect={false}
enablesReturnKeyAutomatically={true}
returnKeyType="done"
label="Password"
title="Inserte su contraseña"
maxLength={30}
textContentType="password"
// keyboardType="visible-password"
characterRestriction={30}
/>
<FilledTextField
ref={pwdverifi}
clearTextOnFocus={false}
error={stateError.toString()}
lineWidth={3}
onChangeText={(pwd)=>{onChangeVerify(pwd)}}
onSubmitEditing={onSubmitPassword}
inputContainerStyle={{
paddingTop: 6,
paddingLeft: 10,
backgroundColor: 'transparent',
borderColor: 'aqua',
borderRadius: 20,
shadowColor: '#00FFF2',
shadowOpacity: 0.5,
shadowRadius: 100,
elevation: 30
}}
textColor='white'
tintColor='white'
baseColor='#00FFDD95'
fontSize={15}
labelFontSize={20}
secureTextEntry={true}
autoCapitalize="none"
autoCorrect={false}
enablesReturnKeyAutomatically={true}
returnKeyType="done"
textContentType="newPassword"
// keyboardType="visible-password"
label="Password"
title="Confirme su contraseña"
maxLength={30}
characterRestriction={30}
/>
{/* <View style={{ flex: 1, flexDirection: 'column' }}> */}
{/* </View> */}
<AwesomeButton disabled={!button} progress style={{ height: 40 ,top:20}} backgroundDarker={'#36A382'} borderColor={'aqua'} width={150} height={40} textColor='black' borderWidth={1.5} backgroundColor={!button?'#00ACB240':'#00FFE560'} backgroundShadow={'#4C63D2'} springRelease onPress={(nexttt?:AfterPressFn) => {
nexttt!(async()=>{
const datOP = await functionRegister(email.current?.value()!,password.current?.value()!,nombre.current?.value()!)
console.log(datOP)
if(datOP=="true"){
AuthStackroot.reset({
index: 1, routes: [{ name: 'MainInit' }],
})
}else{
if(datOP=='invalided'){
showAlert('Error','Emain invalido cambielo inserte otro','Aceptar',(()=>{
email.current?.focus()
}))
}else if(datOP=='useemail'){
showAlert('Error','Email ya registrado inserte otro','Aceptar',(()=>{
email.current?.focus()
}))
}else{
showAlert('Error','Erro no identificado '+datOP,'Reintentar',(()=>{
email.current?.focus()
}))
}
}
});
}}>
Registrame
</AwesomeButton>
</View>
{/* <BlurView blurType='dark' blurAmount={2} >
<Text>Hi, I am a tiny menu item</Text>
</BlurView> */}
{/* <Image style={{backgroundColor:'#F2FFF233'}} blurRadius={10} source={require('./ImagenAuth/FondLogin.png')}/> */}
</View>
</SafeAreaView>
)
}
export default ReguisterScreen |
function validator(value) {
// 1.传入15位或者18位身份证号码,18位号码末位可以为数字或X
const idCard = value
// 2.身份证中的X,必须是大写的
if (value.includes('x'))
return '证件号码错误'
// 3.判断输入的身份证长度
if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(idCard)))
return '证件号码错误'
// 4.验证前两位城市编码是否正确
const aCity = {
11: '北京',
12: '天津',
13: '河北',
14: '山西',
15: '内蒙古',
21: '辽宁',
22: '吉林',
23: '黑龙江',
31: '上海',
32: '江苏',
33: '浙江',
34: '安徽',
35: '福建',
36: '江西',
37: '山东',
41: '河南',
42: '湖北',
43: '湖南',
44: '广东',
45: '广西',
46: '海南',
50: '重庆',
51: '四川',
52: '贵州',
53: '云南',
54: '西藏',
61: '陕西',
62: '甘肃',
63: '青海',
64: '宁夏',
65: '新疆',
71: '台湾',
81: '香港',
82: '澳门',
91: '国外',
}
if (aCity[Number.parseInt(idCard.substr(0, 2))] === null)
return '证件号码错误'
// 5.验证出生日期和校验位
if (validId15(idCard) || validId18(idCard))
return true
else
return '证件号码错误'
// 身份证18位号码验证
function validId18(str) {
if (str.length !== 18)
return '证件号码错误'
// 1. 出生日期验证
const re = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/
const arrSplit = str.match(re) // 检查生日日期是否正确
if (arrSplit != null) {
if (!YearMonthDayValidate(arrSplit[2], arrSplit[3], arrSplit[4]))
return '证件号码错误'
}
else {
return '证件号码错误'
}
// 2. 校验位验证
const iW = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]// 加权因子
let iSum = 0
for (let i = 0; i < 17; i++) {
const iC = str.charAt(i)
const iVal = Number.parseInt(iC)
iSum += iVal * iW[i]
}
const iJYM = iSum % 11// 取模
let sJYM = ''
// 获取的模查找对应的校验码字符值
if (iJYM === 0)
sJYM = '1'
else if (iJYM === 1)
sJYM = '0'
else if (iJYM === 2)
sJYM = 'x'
else if (iJYM === 3)
sJYM = '9'
else if (iJYM === 4)
sJYM = '8'
else if (iJYM === 5)
sJYM = '7'
else if (iJYM === 6)
sJYM = '6'
else if (iJYM === 7)
sJYM = '5'
else if (iJYM === 8)
sJYM = '4'
else if (iJYM === 9)
sJYM = '3'
else if (iJYM === 10)
sJYM = '2'
const cCheck = str.charAt(17).toLowerCase()
if (cCheck !== sJYM)
return '证件号码错误'
return true
}
// 身份证15位(1984-2004)身份验证
function validId15(str) {
if (str.length !== 15)
return '证件号码错误'
// 1. 出生日期验证
const re = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/
const arrSplit = str.match(re) // 检查生日日期是否正确
if (arrSplit != null) {
if (Number.parseInt(arrSplit[2].substr(1)) > 0)
arrSplit[2] = `19${arrSplit[2]}`
else
arrSplit[2] = `20${arrSplit[2]}`
if (!YearMonthDayValidate(arrSplit[2], arrSplit[3], arrSplit[4]))
return '证件号码错误'
}
else {
return '证件号码错误'
}
return true
}
// 出生日期的年月日验证
function YearMonthDayValidate(year, month, day) {
year = Number.parseInt(year) // 年
month = Number.parseInt(month)// 月
day = Number.parseInt(day)// 日
// 判断年,月,日是否为空
if (Number.isNaN(year) || Number.isNaN(month) || Number.isNaN(day))
return '证件号码错误'
// 判断月是否是在1-12月之间
if (month < 1 || month > 12)
return '证件号码错误'
// 返回当月的最后一天
const date = new Date(year, month, 0)
// 判断是否超过天数范围
if (day < 1 || day > date.getDate())
return '证件号码错误'
return true
}
}
const res = validator('4116272000061051xx')
console.log('res', res) |
import { Typography } from '@mui/material';
import React from 'react';
type ReportEntry = {
soma: number;
qualificacao: string;
};
type Report = {
[area: string]: ReportEntry;
};
type ReportComponentProps = {
report: Report | undefined; // Use the correct prop name and allow for 'undefined'
};
const bulletStyles:any = {
'Desafios': {
color: 'red',
marginRight: '8px',
},
'Pontos de Atenção': {
color: 'yellow',
marginRight: '8px',
},
'Pontos Fortes': {
color: 'green',
marginRight: '8px',
}
};
const ReportComponent: React.FC<ReportComponentProps> = ({ report }) => {
// Guard clause to handle the case when report is undefined
if (!report) {
return <Typography>Nenhum relatório disponível.</Typography>;
}
const groupedByQualification = Object.entries(report).reduce((acc, [area, { qualificacao }]) => {
// Initialize the group array if it doesn't already exist
if (!acc[qualificacao]) {
acc[qualificacao] = [];
}
acc[qualificacao].push(area);
return acc;
}, {} as { [qualificacao: string]: string[] });
return (
<div>
{Object.entries(groupedByQualification).map(([qualificacao, areas]) => (
<div key={qualificacao} style={{marginBottom:15}}>
<Typography variant="h6" gutterBottom>
{bulletStyles[qualificacao] && (
<span style={{
...bulletStyles[qualificacao],
height: '10px',
width: '10px',
backgroundColor: bulletStyles[qualificacao].color,
borderRadius: '50%',
display: 'inline-block',
verticalAlign: 'middle',
}} />
)}
{' '}{qualificacao}
</Typography>
{areas.map((area) => (
<Typography fontSize={12} key={area}>
{area}
</Typography>
))}
</div>
))}
</div>
);
};
export default ReportComponent; |
package com.sterotype;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.List;
@Component("emp")
public class Employee {
@Value("coder")
private String name;
@Value("1")
private int id;
@Value(("#{ad}"))
private List<String> addrss;
public List<String> getAddrss() {
return addrss;
}
public void setAddrss(List<String> addrss) {
this.addrss = addrss;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", id=" + id +
", addrss=" + addrss +
'}';
}
} |
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tenantmodule/services/payments_service.dart';
class UtilityPaymentTab extends StatefulWidget {
const UtilityPaymentTab(
{Key? key,
required this.unitItems,
required this.paymentOptions,
required this.showCustomDialog})
: super(key: key);
final List<DropdownMenuItem<String>> unitItems;
final List<DropdownMenuItem<String>> paymentOptions;
final Function showCustomDialog;
@override
State<UtilityPaymentTab> createState() => _UtilityPaymentTabState();
}
class _UtilityPaymentTabState extends State<UtilityPaymentTab> {
late String _paymentMode;
late String _propertyUnit;
// ignore: unused_field
late String _utility;
final _utilityPaymentFormKey = GlobalKey<FormState>();
final _utilityAmountController = TextEditingController();
final _phoneNumberController = TextEditingController();
late PaymentsProvider _paymentsProvider;
List<DropdownMenuItem<String>> get utilityItems {
List<DropdownMenuItem<String>> menuItems = [
const DropdownMenuItem(
value: "ELECTRICITY",
child: Text(
"Electricity",
),
),
const DropdownMenuItem(
value: "WATER",
child: Text(
"Water",
),
),
];
return menuItems;
}
_initiateUtilityPaymentRequest() {
if (_utilityPaymentFormKey.currentState!.validate()) {
if (_paymentMode == 'M-Pesa') {
_paymentsProvider
.processMpesaAdhocPayment(_phoneNumberController.text,
double.parse(_utilityAmountController.text), _propertyUnit)
.then((displayMessage) => widget.showCustomDialog(displayMessage));
}
}
}
@override
void initState() {
super.initState();
Future.delayed(Duration.zero).then((value) {
_paymentsProvider = Provider.of<PaymentsProvider>(context, listen: false);
_propertyUnit = widget.unitItems[0].value!;
_paymentMode = widget.paymentOptions[0].value!;
_utility = utilityItems[0].value!;
});
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: [
const SizedBox(
height: 30,
),
Form(
key: _utilityPaymentFormKey,
child: Column(
children: [
const SizedBox(
height: 10,
),
DropdownButtonFormField<String>(
decoration: const InputDecoration(
labelStyle: TextStyle(
fontWeight: FontWeight.w300,
),
labelText: 'Select Utility'),
items: utilityItems,
value: utilityItems[0].value,
onChanged: (value) {
setState(() {
_utility = value!;
});
},
),
const SizedBox(
height: 20,
),
DropdownButtonFormField<String>(
decoration: const InputDecoration(
labelStyle: TextStyle(
fontWeight: FontWeight.w300,
),
labelText: 'Select Unit'),
items: widget.unitItems,
value: widget.unitItems[0].value,
onChanged: (value) {
setState(() {
_propertyUnit = value!;
});
},
),
const SizedBox(
height: 20,
),
TextFormField(
keyboardType: TextInputType.number,
controller: _utilityAmountController,
validator: (value) {
if (value!.isEmpty) {
return "Enter the amount to be paid";
}
return null;
},
textInputAction: TextInputAction.next,
decoration: const InputDecoration(
labelStyle: TextStyle(
fontWeight: FontWeight.w300,
),
labelText: 'Utility Amount',
),
),
const SizedBox(
height: 20,
),
DropdownButtonFormField<String>(
decoration: const InputDecoration(
labelStyle: TextStyle(
fontWeight: FontWeight.w300,
),
labelText: 'Choose Payment Method'),
items: widget.paymentOptions,
value: widget.paymentOptions[0].value,
onChanged: (value) {
setState(() {
_paymentMode = value!;
});
},
),
const SizedBox(
height: 20,
),
TextFormField(
keyboardType: TextInputType.phone,
controller: _phoneNumberController,
validator: (value) {
if (value!.isEmpty) {
return "Enter the Phone Number";
}
if (value.length < 10) {
return "Phone number should be a minimum of 10 digits";
}
return null;
},
textInputAction: TextInputAction.done,
decoration: const InputDecoration(
labelStyle: TextStyle(
fontWeight: FontWeight.w300,
),
labelText: 'Enter Phone Number to be Charged',
),
),
const SizedBox(
height: 20,
),
Consumer<PaymentsProvider>(
builder: ((_, paymentsProvider, __) =>
paymentsProvider.paymentStatus ==
ProcessingStatus.processing
? const CircularProgressIndicator()
: SizedBox(
width: MediaQuery.of(context).size.width * .7,
child: ElevatedButton(
onPressed: _initiateUtilityPaymentRequest,
child: const Text(
"Pay Utility",
),
),
)),
),
],
),
),
],
),
);
}
} |
import { AuthService } from '@app/auth/services/auth.service';
import { UserCredentials } from '@app/auth/user-credentials.interface';
import { ServerLogger } from '@app/logger/logger';
import { ConversationService } from '@app/messages-service/services/conversation.service';
import { UserCreation } from '@app/user/interfaces/user-creation.interface';
import { User } from '@app/user/interfaces/user.interface';
import { UserService } from '@app/user/services/user.service';
import { Router } from 'express';
import { StatusCodes } from 'http-status-codes';
import { Service } from 'typedi';
export enum AuthErrors {
EmailNotFound = 'EMAIL_NOT_FOUND',
InvalidPassword = 'INVALID_PASSWORD',
NotAuth = 'NOT_AUTH',
AlreadyAuth = 'ALREADY_AUTH',
}
@Service()
export class AuthController {
router: Router;
constructor(private authService: AuthService, private userService: UserService, private conversationService: ConversationService) {
this.configureRouter();
}
private configureRouter() {
this.router = Router();
this.router.get('/logout', async (req, res) => {
return new Promise((resolve) => {
const session = req.session as unknown as { userId: string };
if (session.userId === undefined) {
res.sendStatus(StatusCodes.BAD_REQUEST);
resolve();
return;
}
req.session.destroy((error) => {
if (error) {
ServerLogger.logError(error);
res.sendStatus(StatusCodes.INTERNAL_SERVER_ERROR);
resolve();
return;
}
res.sendStatus(StatusCodes.OK);
resolve();
});
});
});
this.router.post('/register', async (req, res) => {
const { email, name, password, avatar } = req.body;
if (!email || !name || !password || !avatar) {
return res.sendStatus(StatusCodes.BAD_REQUEST);
}
const userCreation: UserCreation = {
email,
name,
avatar,
};
const { object: newUser, errors } = await this.userService.createUser(userCreation);
if (errors.length !== 0) {
return res.status(StatusCodes.CONFLICT).send({ errors });
}
const { _id: userId } = newUser as User;
const userCreds = {
email,
password,
};
await this.authService.addCredentialsToUser(userId, userCreds);
await this.conversationService.addUserToGeneralChannel(userId);
return res.send({ user: newUser });
});
this.router.post('/login', async (req, res) => {
// User already that already have session
const { email, password } = req.body;
if (!email || !password) {
return res.status(StatusCodes.BAD_REQUEST).send({ errors: ['There is one or more missing field'] });
}
const user = await this.userService.getUser({ email });
if (!user) {
return res.status(StatusCodes.BAD_REQUEST).send({
errors: [AuthErrors.EmailNotFound],
});
}
const userCredentials: UserCredentials = {
email,
password,
};
const valid = await this.authService.validateCredentials(userCredentials);
if (!valid) {
return res.status(StatusCodes.BAD_REQUEST).send({
errors: [AuthErrors.InvalidPassword],
});
}
const session = req.session as unknown as { userId: string; loggedIn: boolean };
const { _id: userId } = user;
if (this.authService.isUserActive(userId)) {
return res.status(StatusCodes.CONFLICT).send({ errors: [AuthErrors.AlreadyAuth] });
}
session.userId = userId;
session.loggedIn = true;
return res.status(StatusCodes.OK).send({ message: 'OK' });
});
this.router.get('/validatesession', async (req, res) => {
const { userId } = req.session as unknown as { userId: string };
if (userId === undefined) {
return res.status(StatusCodes.UNAUTHORIZED).send({ errors: [AuthErrors.NotAuth] });
}
const activeSessionId = this.authService.getAssignedUserSession(userId);
if (!activeSessionId) {
return res.status(StatusCodes.OK).send({ message: 'OK' });
}
if (activeSessionId !== req.sessionID) {
return res.status(StatusCodes.UNAUTHORIZED).send({ errors: [AuthErrors.AlreadyAuth] });
}
return res.status(StatusCodes.OK).send({ message: 'OK' });
});
}
} |
/***************** Writing Markup with JSX *********************/
// - In React, rendering logic and markup live together in the same place—components.
// - Each React component is a JavaScript function that may contain some markup that React renders into the browser.
/* - JSX and React are two separate things. They’re often used together, but you can use them
independently of each other. JSX is a syntax extension, while React is a JavaScript library. */
/* The Rules of JSX
1. Return a single root element.
- To return multiple elements from a component, wrap them with a single parent tag.
- If you don’t want to add an extra <div> to your markup, you can write <> and </> instead:
- Why do multiple JSX tags need to be wrapped? JSX looks like HTML, but under the hood it is
transformed into plain JavaScript objects. You can’t return two objects from a function without
wrapping them into an array.
2. Close all the tags
- JSX requires tags to be explicitly closed: self-closing tags like <img> must become <img />,
and wrapping tags like <li>oranges must be written as <li>oranges</li>.
3. camelCase most of the things!
- JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects.
- Attributes can't contain dashes or reserved words like `class`
- React components group rendering logic together with markup because they are related.
- JSX is similar to HTML, with a few differences. You can use a converter if you need to.
- Error messages will often point you in the right direction to fixing your markup.
*/ |
import { Schema } from '@coveo/bueno';
import { DateRangeRequest } from '../../../../../features/facets/range-facets/date-facet-set/interfaces/request';
import { RangeFacetRangeAlgorithm, RangeFacetSortCriterion } from '../../../../../features/facets/range-facets/generic/interfaces/request';
import { ConfigurationSection, DateFacetSection, SearchSection } from '../../../../../state/state-sections';
import { CoreEngine } from '../../../../../app/engine';
export interface DateFacetOptions {
/**
* The field whose values you want to display in the facet.
*/
field: string;
/**
* Whether the index should automatically create range values.
*
* Tip: If you set this parameter to true, you should ensure that the ['Use cache for numeric queries' option](https://docs.coveo.com/en/1982/#use-cache-for-numeric-queries) is enabled for this facet's field in your index in order to speed up automatic range evaluation.
*/
generateAutomaticRanges: boolean;
/**
* The values displayed by the facet in the search interface at the moment of the request.
*
* If `generateAutomaticRanges` is false, values must be specified.
* If `generateAutomaticRanges` is true, automatic ranges are going to be appended after the specified values.
*
* @defaultValue `[]`
*/
currentValues?: DateRangeRequest[];
/**
* A unique identifier for the controller.
* By default, a unique random identifier is generated.
*/
facetId?: string;
/**
* Whether to exclude folded result parents when estimating the result count for each facet value.
*
* @defaultValue `true`
*/
filterFacetCount?: boolean;
/**
* The maximum number of results to scan in the index to ensure that the facet lists all potential facet values.
*
* Note: A high injectionDepth may negatively impact the facet request performance.
*
* Minimum: `0`
*
* @defaultValue `1000`
*/
injectionDepth?: number;
/**
* The number of values to request for this facet.
* Also determines the number of additional values to request each time this facet is expanded, and the number of values to display when this facet is collapsed.
*
* Minimum: `1`
*
* @defaultValue `8`
*/
numberOfValues?: number;
/**
* The sort criterion to apply to the returned facet values.
*
* @defaultValue `ascending`
*/
sortCriteria?: RangeFacetSortCriterion;
/**
* The algorithm that's used for generating the ranges of this facet when they aren't manually defined. The default value of `"even"` generates equally sized facet ranges across all of the results. The value `"equiprobable"` generates facet ranges which vary in size but have a more balanced number of results within each range.
*
* @defaultValue `even`
*/
rangeAlgorithm?: RangeFacetRangeAlgorithm;
}
export declare const dateFacetOptionsSchema: Schema<Required<DateFacetOptions>>;
export declare function validateDateFacetOptions(engine: CoreEngine<ConfigurationSection & SearchSection & DateFacetSection>, options: DateFacetOptions): void; |
import java.util.*
fun main(){
// 확장 함수
// 이미 있는 클래스에 메서드를 추가하는 개념
// 추가된 메서드는 같은 프로그램 내에서만 사용이 가능하다.
// 자바 코드로 변경될 때 객체의 ID를 받아 사용하는 코드로 변경된다.
val str1 = "abcd"
// 추가한 메서드 호출
println(str1.getUpperString())
str1.printString()
}
// 확장함수 정의
// 클래스명.추가할 메서드
fun String.getUpperString() : String {
return this.uppercase(Locale.getDefault())
}
fun String.printString() {
println("문자열 : $this")
} |
## Application de la porte d'Hadamar
$$|\psi> = i|0> + (2 + i)|1>$$
$$H|\psi> = iH|0> + (2 + i)H|1>$$
$$H|\psi> = \frac{i}{\sqrt{2}}(|0> + |1>) + \frac{(2 + i)}{\sqrt{2}}(|0> - |1>)$$
$$H|\psi> = \frac{i|0>}{\sqrt{2}} + \frac{i|1>}{\sqrt{2}} + \frac{(2 + i)|0>}{\sqrt{2}} - \frac{(2 + i)|1>}{\sqrt{2}}$$
$$H|\psi> = \frac{i|0> + i|1> + (2 + i)|0> - (2 + i)|1>}{\sqrt{2}}$$
$$H|\psi> = \frac{(2 + 2i)|0> - (2 + 2i)|1>}{\sqrt{2}}$$
$$H|\psi> = \frac{(2 + 2i)}{\sqrt{2}}|0> - \frac{(2 + 2i)}{\sqrt{2}}|1>$$
$$H|\psi> = (\frac{2}{\sqrt{2}} + \frac{2}{\sqrt{2}}i)|0> - (\frac{2}{\sqrt{2}} + \frac{2i}{\sqrt{2}})|1>$$
## Hadammar for different values
### H |0>
---
$$H|0> = \frac{1}{\sqrt{2}}|0> + \frac{1}{\sqrt{2}}|1>$$
$$\Longrightarrow |H|0>|^2 = (\frac{1}{\sqrt{2}})^2 + (\frac{1}{\sqrt{2}})^2 = 1$$
### H |1>
---
$$H|1> = \frac{1}{\sqrt{2}}|0> - \frac{1}{\sqrt{2}}|1>$$
$$\Longrightarrow |H|1>|^2 = (\frac{1}{\sqrt{2}})^2 + (\frac{-1}{\sqrt{2}})^2 = 1$$
### H |PSI>
---
$$H|\psi> = \frac{\alpha}{\sqrt{2}}(|0> + |1>) + \frac{\beta}{\sqrt{2}}(|0> - |1>)$$
$$H|\psi> = \frac{\alpha}{\sqrt{2}}|0> + \frac{\alpha}{\sqrt{2}}|1> + \frac{\beta}{\sqrt{2}}|0> - \frac{\beta}{\sqrt{2}}|1>$$
$$H|\psi> = \frac{\alpha + \beta}{\sqrt{2}}|0> + \frac{\alpha - \beta}{\sqrt{2}}|1>$$
$$\Longrightarrow P|0> = \frac{\alpha + \beta}{\sqrt{2}}, P|1> = \frac{\alpha - \beta}{\sqrt{2}}$$
# Differents gates
## X gate (NOT)
$$X|0> = |1>$$
$$X|1> = |0>$$
$$|\psi> = \alpha|0> + \beta|1> \newline \Longrightarrow X|\psi> = \alpha X|0> + \beta X|1>$$
$$X|\psi> = \beta|0> + \alpha|1>$$
$$
X = \begin{pmatrix}
0 & 1 \\
1 & 0
\end{pmatrix}
\newline
|0> = \begin{pmatrix} 1 \\ 0 \end{pmatrix}, |1> = \begin{pmatrix} 0 \\ 1 \end{pmatrix}\newline
X|1> = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \begin{pmatrix} 0 \\ 1 \end{pmatrix} = \begin{pmatrix} 0*0+1*1 \\ 1*0+0*1 \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \end{pmatrix} = |0>\newline
X|0> = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \begin{pmatrix} 1 \\ 0 \end{pmatrix} = \begin{pmatrix} 0*1+1*0 \\ 1*1+0*0 \end{pmatrix} = \begin{pmatrix} 0 \\ 1 \end{pmatrix} = |1> \newline
X|\psi> = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \begin{pmatrix} \alpha \\ \beta \end{pmatrix} = \begin{pmatrix} 0*\alpha+1*\beta \\ 1*\alpha+0*\beta \end{pmatrix} = \begin{pmatrix} \beta \\ \alpha \end{pmatrix} \newline
$$
## Hadammar gate
$$|\psi> = \alpha|0> + \beta|1> \Longrightarrow H|\psi> = \alpha H|0> + \beta H|1>$$
$$H|0> = \frac{1}{\sqrt{2}}|0> + \frac{1}{\sqrt{2}}|1>$$
$$H|1> = \frac{1}{\sqrt{2}}|0> - \frac{1}{\sqrt{2}}|1>$$
$$\Longrightarrow H|\psi> = \frac{\alpha}{\sqrt{2}}|0> + \frac{\alpha}{\sqrt{2}}|1> + \frac{\beta}{\sqrt{2}}|0> - \frac{\beta}{\sqrt{2}}|1>$$
$$\Longrightarrow H|\psi> = \frac{\alpha+\beta}{\sqrt{2}}|0> + \frac{\alpha-\beta}{\sqrt{2}}|1>$$
$$
H = \begin{pmatrix}
\frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\
\frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}}
\end{pmatrix} \newline
H|0> = \begin{pmatrix}
\frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\
\frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}}
\end{pmatrix} \begin{pmatrix} 1 \\ 0 \end{pmatrix} = \begin{pmatrix} \frac{1}{\sqrt{2}}*1+\frac{1}{\sqrt{2}}*0 \\ \frac{1}{\sqrt{2}}*1-\frac{1}{\sqrt{2}}*0 \end{pmatrix} = \begin{pmatrix} \frac{1}{\sqrt{2}} \\ \frac{1}{\sqrt{2}} \end{pmatrix} = \frac{1}{\sqrt{2}}|0> + \frac{1}{\sqrt{2}}|1> \newline
H|1> = \begin{pmatrix}
\frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\
\frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}}
\end{pmatrix} \begin{pmatrix} 0 \\ 1 \end{pmatrix} = \begin{pmatrix} \frac{1}{\sqrt{2}}*0+\frac{1}{\sqrt{2}}*1 \\ \frac{1}{\sqrt{2}}*0-\frac{1}{\sqrt{2}}*1 \end{pmatrix} = \begin{pmatrix} \frac{1}{\sqrt{2}} \\ -\frac{1}{\sqrt{2}} \end{pmatrix} = \frac{1}{\sqrt{2}}|0> - \frac{1}{\sqrt{2}}|1> \newline
H|\psi> = \begin{pmatrix}
\frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\
\frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}}
\end{pmatrix} \begin{pmatrix} \alpha \\ \beta \end{pmatrix} = \begin{pmatrix} \frac{1}{\sqrt{2}}*\alpha+\frac{1}{\sqrt{2}}*\beta \\ \frac{1}{\sqrt{2}}*\alpha-\frac{1}{\sqrt{2}}*\beta \end{pmatrix} = \begin{pmatrix} \frac{\alpha+\beta}{\sqrt{2}} \\ \frac{\alpha-\beta}{\sqrt{2}} \end{pmatrix} = \frac{\alpha+\beta}{\sqrt{2}}|0> + \frac{\alpha-\beta}{\sqrt{2}}|1> \newline
$$
### Example
$$|\psi> = \frac{1}{\sqrt{2}}|0> + \frac{1}{\sqrt{2}}|1>$$
---
$$H|\psi> = \frac{1}{\sqrt{2}}H|0> + \frac{1}{\sqrt{2}}H|1> = \frac{1}{\sqrt{2}}(\frac{1}{\sqrt{2}}|0> + \frac{1}{\sqrt{2}}|1>) + \frac{1}{\sqrt{2}}(\frac{1}{\sqrt{2}}|0> - \frac{1}{\sqrt{2}}|1>)$$
Naive method
$$\Longrightarrow H|\psi> = \frac{1}{\sqrt{2}} * \frac{1}{\sqrt{2}}(|0> + |1>) + \frac{1}
{\sqrt{2}} * \frac{1}{\sqrt{2}}(|0> - |1>)$$
$$\Longrightarrow H|\psi> = \frac{1}{2}(|0> + |1>) + \frac{1}{2}(|0> - |1>)$$
$$\Longrightarrow H|\psi> = \frac{1}{2}|0> + \frac{1}{2}|1> + \frac{1}{2}|0> - \frac{1}{2}|1>$$
$$\Longrightarrow H|\psi> = |0>$$
---
Using formula method
$$\Longrightarrow H|\psi> = \frac{\frac{1}{\sqrt{2}}+\frac{1}{\sqrt{2}}}{\sqrt{2}}|0> + \frac{\frac{1}{\sqrt{2}}-\frac{1}{\sqrt{2}}}{\sqrt{2}}|1>$$
$$\Longrightarrow H|\psi> = \frac{\frac{2}{\sqrt{2}}}{\sqrt{2}}|0> = \frac{\frac{2\sqrt{2}}{2}}{\sqrt{2}}|0> = \frac{\sqrt{2}}{\sqrt{2}}|0>$$
$$\Longrightarrow H|\psi> = |0>$$
---
### Resume
$$H|0> = \frac{1}{\sqrt{2}}|0> + \frac{1}{\sqrt{2}}|1>, P(0) = |\frac{1}{\sqrt{2}}|^2 = \frac{1}{2}, P(1) = |-\frac{1}{\sqrt{2}}|^2 = \frac{1}{2}$$
$$H|1> = \frac{1}{\sqrt{2}}|0> - \frac{1}{\sqrt{2}}|1>, P(0) = |\frac{1}{\sqrt{2}}|^2 = \frac{1}{2}, P(1) = |-\frac{1}{\sqrt{2}}|^2 = \frac{1}{2}$$
$$H|\psi> = \frac{\alpha+\beta}{\sqrt{2}}|0> + \frac{\alpha-\beta}{\sqrt{2}}|1>$$
$$\Longrightarrow P(0) = |\frac{\alpha+\beta}{\sqrt{2}}|^2 = \frac{(\alpha+\beta)^2}{2} \newline \Longrightarrow P(1) = |\frac{\alpha-\beta}{\sqrt{2}}|^2 = \frac{(\alpha-\beta)^2}{2}$$
## Y gate
$$Y|0> = i|1>$$
$$Y|1> = -i|0>$$
$$
Y = \begin{pmatrix}0 & -i \\ i & 0\end{pmatrix} \newline
Y|0> = \begin{pmatrix}0 & -i \\ i & 0\end{pmatrix} \begin{pmatrix}1 \\ 0\end{pmatrix} = \begin{pmatrix}0*1+-i*0 \\ i*1+0*0\end{pmatrix} = \begin{pmatrix}0 \\ i\end{pmatrix} = i|1> \newline
Y|1> = \begin{pmatrix}0 & -i \\ i & 0\end{pmatrix} \begin{pmatrix}0 \\ 1\end{pmatrix} = \begin{pmatrix}0*-i+-i*1 \\ i*0+0*1\end{pmatrix} = \begin{pmatrix}-i \\ 0\end{pmatrix} = -i|0> \newline
Y|\psi> = \begin{pmatrix}0 & -i \\ i & 0\end{pmatrix} \begin{pmatrix}\alpha \\ \beta\end{pmatrix} = \begin{pmatrix}0*\alpha+-i*\beta \\ i*\alpha+0*\beta\end{pmatrix} = \begin{pmatrix}-i\beta \\ i\alpha\end{pmatrix} = i\alpha|1> - i\beta|0> \newline
$$
## Z gate
$$Z|0> = |0>$$
$$Z|1> = -|1>$$
$$
Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} \newline
Z|0> = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} \begin{pmatrix} 1 \\ 0 \end{pmatrix} = \begin{pmatrix} 1*1+0*0 \\ 0*1+-1*0 \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \end{pmatrix} = |0> \newline
Z|1> = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} \begin{pmatrix} 0 \\ 1 \end{pmatrix} = \begin{pmatrix} 1*0+0*1 \\ 0*0+-1*1 \end{pmatrix} = \begin{pmatrix} 0 \\ -1 \end{pmatrix} = -|1> \newline
Z|\psi> = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} \begin{pmatrix} \alpha \\ \beta \end{pmatrix} = \begin{pmatrix} 1*\alpha+0*\beta \\ 0*\alpha+-1*\beta \end{pmatrix} = \begin{pmatrix} \alpha \\ -\beta \end{pmatrix} = \alpha|0> - \beta|1> \newline
$$ |
<!--example of a survey form for feedback-->
<!--live demo can be found at https://codepen.io/aleks-hat/pen/wvprmjv -->
<!--layout inspiration from FCC: Survey Form-->
<!DOCTYPE HTML>
<html>
<head>
<title>Survey Form</title>
<link rel="stylesheet" href="styles.css">
</head>
<div class="container">
<header class="header">
<h1 id="title">Free Tutorials Survey Form</h1>
<p id="description" class="description text-center">
Thank you for taking the time to give us feedback!
</p>
</header>
<div class="grid">
<form id="survey-form">
<div class="form-div">
<label id="name-label" for="name">Name</label>
<input
type="text"
name="name"
id="name"
class="text-form"
placeholder="Enter your name"
required
/>
</div>
<div class="form-div">
<label id="email-label" for="email">Email</label>
<input
type="email"
name="email"
id="email"
class="text-form"
placeholder="Enter your Email"
required
/>
</div>
<div class="form-div">
<label id="number-label" for="number"
>Age<span class="text">(optional)</span></label
>
<input
type="number"
name="age"
id="number"
min="10"
max="99"
class="text-form"
placeholder="Age"
/>
</div>
<div class="form-div">
<p>Which option best describes your current role?</p>
<select id="dropdown" class="drop-form" name="role" required>
<option value="0" selected disabled>Select current role</option>
<option value="student">Student</option>
<option value="job">Full Time Job</option>
<option value="unemployed">Seeking Work</option>
<option value="blank">Prefer not to say</option>
<option value="other">Other</option>
</select>
</div>
<div class="form-div">
<p>Would you recommend our site to a friend?</p>
<label>
<input
name="recommend"
value="yes"
type="radio"
class="radio"
checked
/>Definitely</label
>
<label>
<input
name="recommend"
value="maybe"
type="radio"
class="radio"
/>Maybe</label>
<label
><input
name="recommend"
value="no"
type="radio"
class="radio"
/>No Thanks</label>
</div>
<div class="form-div">
<p>
What would you like to see improved?
<span class="text">(Check all that apply)</span>
</p>
<label
><input
name="prefer"
value="front-end-projects"
type="checkbox"
class="checkbox"
/>Front-end Projects</label
>
<label>
<input
name="prefer"
value="javascript"
type="checkbox"
class="checkbox"
/>JavaScript</label
>
<label
><input
name="prefer"
value="math"
type="checkbox"
class="checkbox"
/>Mathematics</label
>
<label
><input
name="prefer"
value="stats"
type="checkbox"
class="checkbox"
/>Statistics</label
>
<label
><input
name="prefer"
value="data-mining"
type="checkbox"
class="checkbox"
/>Data Mining</label
>
<label
><input
name="prefer"
value="challenges"
type="checkbox"
class="checkbox"
/>Challenges</label
>
<label
><input
name="prefer"
value="videos"
type="checkbox"
class="checkbox"
/>Videos</label
>
<label
><input
name="prefer"
value="additions"
type="checkbox"
class="checkbox"
/>Additional Courses</label
>
</div>
<div class="form-div">
<p>Any comments or suggestions?<span class="text">(optional)</span></p>
<textarea
id="comments"
class="textbox"
name="comment"
placeholder="Enter your comment here..."
></textarea>
</div>
<div class="form-div">
<button type="submit" id="submit" class="btn">
Submit
</button>
</div>
</form>
</div>
</div>
</body>
</html> |
#pragma once
#include <stdint.h>
#include <stdlib.h>
/** Min positive capacity of mutable byte buffer. */
extern const size_t kByteBufferMinPositiveCapacity;
/**
* Auto-resizable mutable byte buffer. Empty buffer is not allocated.
*/
struct MutableByteBuffer {
/**
* Beginning of buffer (or `NULL` if buffer is not yet allocated).
*/
uint8_t* ptr;
/** Number of bytes can be stored in buffer. */
size_t capacity;
/** Number of bytes stored in buffer. */
size_t length;
};
/** Initializes empty byte buffer. Does not make allocations. */
void mut_byte_buffer_init(struct MutableByteBuffer* buffer);
/** Destroys byte buffer by freeing underlying memory if presented. */
void mut_byte_buffer_destroy(struct MutableByteBuffer* buffer);
/**
* Ensures that capacity of given byte buffer is at least
* `required_capacity`. May make allocations.
*/
void mut_byte_buffer_extend_reallocate(
struct MutableByteBuffer* buffer,
size_t required_capacity);
/**
* Appends `length` bytes from address `buffer_to_append` to given
* buffer.
*/
void mut_byte_buffer_append_buffer(
struct MutableByteBuffer* buffer,
const void* buffer_to_append,
size_t length);
/**
* Appends C-string `str` to given buffer (including trailing '\0').
*/
void mut_byte_buffer_append_str(
struct MutableByteBuffer* buffer,
const char* str);
/** Appends single byte to given buffer. */
void mut_byte_buffer_append_byte(
struct MutableByteBuffer* buffer,
uint8_t byte);
/**
* Returns const pointer to memory allocated by buffer (may return
* `NULL` if buffer is not allocated).
*/
const uint8_t* mut_byte_buffer_ptr(const struct MutableByteBuffer* buffer);
/** Returns number of bytes stored in given buffer. */
size_t mut_byte_buffer_length(const struct MutableByteBuffer* buffer); |
//
// NSPersistentStoreCoordinator+Extension.swift
//
// Created by Sergey Spivakov on 1/30/17.
// Copyright © 2017 Sergey Spivakov. All rights reserved.
//
/// NSPersistentStoreCoordinator extension
import Foundation
import CoreData
/// Extension to support iOS 9 & iOS10+
extension NSPersistentStoreCoordinator {
/// NSPersistentStoreCoordinator error types
public enum CoordinatorError: Error {
/// .momd file not found
case modelFileIsNotFound
/// NSManagedObjectModel creation fail
case modelCreation
/// Gettings document directory fail
case storePathIsNotFound
}
/// Return NSPersistentStoreCoordinator object
static func coordinator(name: String) throws -> NSPersistentStoreCoordinator? {
guard let modelURL = Bundle.main.url(forResource: name, withExtension: "momd") else {
throw CoordinatorError.modelFileIsNotFound
}
guard let model = NSManagedObjectModel(contentsOf: modelURL) else {
throw CoordinatorError.modelCreation
}
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
guard let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
throw CoordinatorError.storePathIsNotFound
}
do {
let url = documents.appendingPathComponent("\(name).sqlite")
let options = [ NSMigratePersistentStoresAutomaticallyOption : true,
NSInferMappingModelAutomaticallyOption : true ]
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
} catch {
throw error
}
return coordinator
}
}
struct Storage {
static var shared = Storage()
@available(iOS 10.0, *)
private lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Model")
container.loadPersistentStores { (storeDescription, error) in
print("CoreData: Inited \(storeDescription)")
guard error == nil else {
print("CoreData: Unresolved error \(String(describing: error))")
return
}
}
return container
}()
private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
do {
return try NSPersistentStoreCoordinator.coordinator(name: "Model")
} catch {
print("CoreData: Unresolved error \(error)")
}
return nil
}()
private lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: Public methods
enum SaveStatus {
case saved, rolledBack, hasNoChanges
}
var context: NSManagedObjectContext {
mutating get {
if #available(iOS 10.0, *) {
return persistentContainer.viewContext
} else {
return managedObjectContext
}
}
}
mutating func save() -> SaveStatus {
if context.hasChanges {
do {
try context.save()
return .saved
} catch {
context.rollback()
return .rolledBack
}
}
return .hasNoChanges
}
} |
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthService } from 'src/app/auth/auth.service';
import Swal from 'sweetalert2';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent {
showDiv: boolean = true;
emailLogin!: FormGroup
otpLogin!: FormGroup
constructor(private router: Router, private fb: FormBuilder, private auth: AuthService) {
this.emailLogin = this.fb.group({
email: ['', Validators.required]
});
this.otpLogin = this.fb.group({
otp: ['', Validators.required]
})
}
getOtp() {
let value = this.emailLogin.value;
this.auth.beforeOTP(value)
.subscribe({
next: (res: any) => {
this.emailLogin.reset();
localStorage.setItem('email', value.email)
this.showDiv = !this.showDiv;
Swal.fire('Success', `${res.message}`, 'success')
},
error: (err: any) => {
console.log(err.error.error)
this.emailLogin.reset()
Swal.fire('Failed', `${err.error.error}`, 'error')
},
complete:()=>{
console.log('Success')
}
})
}
login(): void {
let otp = this.otpLogin.value.otp;
let email = localStorage.getItem('email');
let value = { email, otp }
this.auth.afterOTP(value).subscribe({
next: (res: any) => {
console.log(res)
localStorage.setItem('accessToken', res.token)
Swal.fire('Success', `${res.message}`, 'success')
},
error: (err: any) => {
console.log(err.error.error)
Swal.fire('Failed', `${err.error.error}`, 'error')
},
complete:()=>{
if(this.auth.isAdmin()){
this.router.navigate(['/admin']);
}
else{
this.router.navigate(['/user']);
}
}
})
}
} |
// components/MonthYearInput/MonthYearInput.tsx
import React, { useState } from "react";
import { DateTime } from "luxon";
const MonthYearInput: React.FC<{
value: string;
onChange: (value: string) => void;
}> = ({ value, onChange }) => {
const [date, setDate] = useState(
value ? DateTime.fromISO(value) : DateTime.now()
);
const handleMonthChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
const newDate = date.set({ month: parseInt(event.target.value) });
setDate(newDate);
const isoDate = newDate.toISODate();
if (isoDate) {
onChange(isoDate.slice(0, 7));
}
};
const handleYearChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
const newDate = date.set({ year: parseInt(event.target.value) });
setDate(newDate);
const isoDate = newDate.toISODate();
if (isoDate) {
onChange(isoDate.slice(0, 7));
}
};
return (
<>
<select value={date.month} onChange={handleMonthChange}>
{Array.from({ length: 12 }, (_, i) => i + 1).map((month) => (
<option key={month} value={month}>
{DateTime.fromObject({ month }).toFormat("LLL")}
</option>
))}
</select>
<select value={date.year} onChange={handleYearChange}>
{Array.from({ length: 11 }, (_, i) => i + date.year - 5).map((year) => (
<option key={year} value={year}>
{year}
</option>
))}
</select>
</>
);
};
export default MonthYearInput; |
import React, { useEffect } from 'react'
import { createContext, PropsWithChildren, useContext, useState } from 'react'
// import { mockTodos } from '../temp'
import { IGlobalContext } from '../types/IGlobalContext'
import { ITodo } from '../types/ITodo'
import AsyncStorage from '@react-native-async-storage/async-storage'
// @ts-ignore
const GlobalContext = createContext<IGlobalContext>({})
export const useGlobalContext = (): IGlobalContext => useContext(GlobalContext)
export const GlobalContextProvider: React.FC<PropsWithChildren> = ({ children }) => {
const [todos, setTodos] = useState<ITodo[]>([])
const [selectedTodoId, setSelectedTodoId] = useState<null | string | number>(null)
const createTodo = async (todo: Partial<ITodo>) => {
const newTodo = {
...todo,
id: +todos[todos.length - 1].id + 1,
createdAt: new Date(),
isCompleted: false,
}
await AsyncStorage.setItem('todos', JSON.stringify([...todos, newTodo]))
const updatedTodos = await AsyncStorage.getItem('todos')
if (updatedTodos) {
const serializedTodos = JSON.parse(updatedTodos).map((todo: ITodo) => ({
...todo,
createdAt: new Date(todo.createdAt),
}))
setTodos(serializedTodos)
}
}
const updateTodo = async (todo: Partial<ITodo>) => {
const selectedTodoIndex = todos.findIndex(t => t.id === todo.id)
if (selectedTodoIndex >= 0) {
const newTodos = todos.map((oldTodo, index) => {
if (index === selectedTodoIndex) {
return { ...oldTodo, ...todo }
} else {
return oldTodo
}
})
await AsyncStorage.setItem('todos', JSON.stringify(newTodos))
const updatedTodos = await AsyncStorage.getItem('todos')
if (updatedTodos) {
const serializedTodos = JSON.parse(updatedTodos).map((todo: ITodo) => ({
...todo,
createdAt: new Date(todo.createdAt),
}))
setTodos(serializedTodos)
}
}
}
const deleteTodo = async (id: string | number) => {
const newTodos = todos.filter(todo => todo.id != id)
await AsyncStorage.setItem('todos', JSON.stringify(newTodos))
const updatedTodos = await AsyncStorage.getItem('todos')
if (updatedTodos) {
const serializedTodos = JSON.parse(updatedTodos).map((todo: ITodo) => ({
...todo,
createdAt: new Date(todo.createdAt),
}))
setTodos(serializedTodos)
}
}
const addTodo = async (newTodo: ITodo) => {
const newTodos = [...todos, newTodo]
await AsyncStorage.setItem('todos', JSON.stringify(newTodos))
const updatedTodos = await AsyncStorage.getItem('todos')
if (updatedTodos) {
const serializedTodos = JSON.parse(updatedTodos).map((todo: ITodo) => ({
...todo,
createdAt: new Date(todo.createdAt),
}))
setTodos(serializedTodos)
}
}
const getTodos = async () => {
// uncomment for saving mock todos into async storage
// await AsyncStorage.setItem('todos', JSON.stringify(mockTodos))
const todosJson = await AsyncStorage.getItem('todos')
if (todos) {
const parsedTodos = JSON.parse(todosJson as string).map((todo: ITodo) => ({
...todo,
createdAt: new Date(todo.createdAt),
}))
setTodos(parsedTodos)
}
}
const value: IGlobalContext = {
todos,
deleteTodo,
addTodo,
updateTodo,
selectedTodoId,
setSelectedTodoId,
createTodo,
getTodos,
}
useEffect(() => {
getTodos()
}, [])
return <GlobalContext.Provider value={value}>{children}</GlobalContext.Provider>
} |
package com.pet.core.process
import com.pet.core.api.Changeable
import com.pet.core.api.Eventable
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlin.random.Random
class Pet(stats: Stats) :
Changeable<StateItem, StateChange, (change: StateChange) -> Unit>,
Eventable<(event: Event) -> Unit, Event> {
val name = stats.name
private val statsToAffect = listOf(StatsAffect.FOOD, StatsAffect.HEALTH, StatsAffect.MOOD)
private val onStateChangeListeners: MutableList<(state: StateChange) -> Unit> = arrayListOf()
private val onEventListeners: MutableList<(event: Event) -> Unit> = arrayListOf()
@Volatile
private var mood = StateProperty(stats.mood, State.BORED, State.HAPPY)
@Volatile
private var health = StateProperty(stats.health, State.ILL, State.HEALTHY)
@Volatile
private var food = StateProperty(stats.food, State.HUNGRY, State.FULL)
@Volatile
private var alive = true
@Volatile
private var isRunning = true
@Volatile
var isCrapped = false
fun getStats() = StateInfo(mood.getInfo(), health.getInfo(), food.getInfo())
fun adjustMood(value: Int) {
mood.adjustValue(value)
}
fun adjustHealth(value: Int) {
health.adjustValue(value)
if (health.getInfo().value == 0) {
alive = false
fire(Event.DEATH)
}
}
fun adjustFood(value: Int) {
food.adjustValue(value)
if (health.getInfo().value == 0) {
alive = false
fire(Event.DEATH)
}
}
@OptIn(DelicateCoroutinesApi::class)
fun run() {
GlobalScope.launch {
mainLoop()
}
}
fun stop() {
isRunning = false
}
override fun addOnEventListener(callback: (event: Event) -> Unit) = onEventListeners.add(callback)
override fun fire(event: Event) = onEventListeners.forEach { it.invoke(event) }
override fun addOnChangeListener(listener: (state: StateChange) -> Unit) = onStateChangeListeners.add(listener)
override fun update(change: StateChange) = onStateChangeListeners.forEach { it.invoke(change) }
private fun mainLoop() {
val onChangeCallBack: (StateChange) -> Unit = { newState ->
update(newState)
}
mood.addOnChangeListener(onChangeCallBack)
health.addOnChangeListener(onChangeCallBack)
food.addOnChangeListener(onChangeCallBack)
while (isRunning && alive) {
Thread.sleep(1000L * SECONDS_INTERVAL)
val destiny = Random.nextInt(5)
if (destiny + 1 > statsToAffect.size) {
continue
}
val value = Random.nextInt(1, 3)
when (statsToAffect[destiny]) {
StatsAffect.MOOD -> adjustMood(
if (isCrapped) {
-(value + 2)
} else {
-value
}
)
StatsAffect.HEALTH -> adjustHealth(-value)
StatsAffect.FOOD -> adjustFood(-value)
}
when (Random.nextInt(0, 21)) {
in 3..8 -> {
fire(Event.CRAP)
isCrapped = true
adjustMood(-Random.nextInt(2, 4))
adjustHealth(-Random.nextInt(0, 3))
}
in 17..20 -> {
fire(Event.ILLNESS)
adjustMood(-Random.nextInt(0, 3))
adjustHealth(-Random.nextInt(4, 6))
}
else -> continue
}
}
}
companion object {
const val SECONDS_INTERVAL = 10
}
enum class StatsAffect {
MOOD, HEALTH, FOOD
}
} |
"""
URL configuration for dmm project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.0/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
from dmm import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.homepage, name="home"),
path('about/', views.about, name="about"),
path('admin/', admin.site.urls, name="admin"),
path('services/', views.services, name="services"),
path('blogs/', views.blogs, name="blogs"),
path('contact/', views.contact, name="contact"),
path('userform/', views.userform, name="userform"),
path('thankyou/', views.thankyou, name ="thankyou"),
path('calc/', views.calculator, name = "calc"),
path('evenodd/', views.even_odd, name="evenodd"),
path('marksheet/', views.marksheet, name="marksheet"),
path('courses/', views.course),
path('courses/<courseid>', views.coursedetails),
path('blogsview/<slug>', views.blogview, name = "blogview"),
path('submit_enquiry/', views.submit_enquiry, name="submit_enquiry"),
]
if settings.DEBUG:
urlpatterns+=static(settings.MEDIA_URL,document_root =settings.MEDIA_ROOT) |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lists.h"
/**
* add_node - Adds a new node to the beginning of a list
* @head: double pointer
* @str: The new string that will be added
* Return: the & of the new input
*/
list_t *add_node(list_t **head, const char *str)
{
list_t *new;
unsigned int length = 0;
while (str[length])
length++;
new = malloc(sizeof(list_t));
if (!new)
return (NULL);
new->str = strdup(str);
new->len = length;
new->next = (*head);
(*head) = new;
return (*head);
} |
defmodule UneebeeWeb.Components.Upload do
@moduledoc """
Reusable file upload component.
"""
use UneebeeWeb, :live_component
alias UneebeeWeb.Shared.CloudStorage
attr :current_img, :string, default: nil
attr :label, :string, default: nil
attr :subtitle, :string, default: nil
attr :unstyled, :boolean, default: false
@impl Phoenix.LiveComponent
def render(assigns) do
~H"""
<form id={"upload-form-#{@id}"} phx-submit="save" class={[@unstyled && "flex flex-col-reverse"]} phx-change="validate" phx-drop-target={@uploads.file.ref} phx-target={@myself}>
<% entry = List.first(@uploads.file.entries) %>
<div class={["flex flex-wrap items-center gap-2", not @unstyled && "top-[57px] sticky bg-gray-50 p-4 sm:flex-nowrap sm:px-6 lg:px-8"]}>
<h1 :if={not @unstyled} class="text-base font-semibold leading-7 text-gray-900"><%= @label %></h1>
<div class={["flex gap-2", not @unstyled && "ml-auto", @unstyled && "flex-row-reverse"]}>
<.button :if={@current_img} id={"remove-#{@id}"} phx-click="remove" phx-target={@myself} icon="tabler-trash" type="button" color={:alert_light}>
<%= gettext("Remove") %>
</.button>
<.button type="submit" icon="tabler-cloud-upload" disabled={is_nil(entry)} phx-disable-with={gettext("Uploading...")}><%= gettext("Upload") %></.button>
</div>
</div>
<div class="container flex flex-col space-y-8">
<div class="flex items-center space-x-6">
<.live_img_preview :if={entry} entry={entry} class="h-16 rounded-2xl object-cover" />
<img :if={is_binary(@current_img) and is_nil(entry)} alt={@label} src={@current_img} class="w-16 rounded-xl object-cover" />
<.live_file_input
upload={@uploads.file}
class={[
"block w-full text-sm text-gray-500",
"file:mr-4 file:py-2 file:px-4",
"file:rounded-full file:border-0",
"file:text-sm file:font-semibold",
"file:bg-indigo-50 file:text-indigo-700",
"hover:file:bg-indigo-300"
]}
/>
</div>
<p :if={entry} class="text-sm text-gray-500">
<%= if entry.progress > 0,
do: gettext("Uploading file: %{progress}% concluded.", progress: entry.progress),
else: gettext("Click on the save button to upload your file.") %>
</p>
<p :for={err <- upload_errors(@uploads.file)}><%= error_to_string(err) %></p>
</div>
</form>
"""
end
@impl Phoenix.LiveComponent
def mount(socket) do
{:ok, upload_opts(socket, internal_storage?())}
end
@impl Phoenix.LiveComponent
def handle_event("validate", _params, socket) do
{:noreply, socket}
end
@impl Phoenix.LiveComponent
def handle_event("cancel", %{"ref" => ref, "value" => _value}, socket) do
{:noreply, cancel_upload(socket, :file, ref)}
end
@impl Phoenix.LiveComponent
def handle_event("save", _params, socket) do
case consume_uploaded_entries(socket, :file, &consume_entry/2) do
[] -> :ok
[upload_path] -> notify_parent(socket, upload_path)
end
{:noreply, socket}
end
@impl Phoenix.LiveComponent
def handle_event("remove", _params, socket) do
notify_parent(socket, nil)
{:noreply, socket}
end
defp notify_parent(socket, upload_path) do
send(self(), {__MODULE__, socket.assigns.id, upload_path})
:ok
end
# sobelow_skip ["Traversal.FileModule"]
defp consume_entry(%{path: path}, _entry) do
dest = Path.join([:code.priv_dir(:uneebee), "static", "uploads", Path.basename(path)])
File.cp!(path, dest)
file_name = Path.basename(dest)
{:ok, ~p"/uploads/#{file_name}"}
end
defp consume_entry(%{key: key}, _entry) do
{:ok, Application.get_env(:uneebee, :cdn)[:url] <> "/" <> key}
end
defp presign_upload(entry, socket) do
%{uploads: uploads} = socket.assigns
current_timestamp = DateTime.to_unix(DateTime.utc_now(), :second)
key = "#{current_timestamp}_#{entry.client_name}"
config = %{region: "auto", access_key_id: CloudStorage.access_key_id(), secret_access_key: CloudStorage.secret_access_key(), url: CloudStorage.bucket_url()}
{:ok, presigned_url} = CloudStorage.presigned_put(config, key: key, content_type: entry.client_type, max_file_size: uploads[entry.upload_config].max_file_size)
meta = %{uploader: "S3", key: key, url: presigned_url}
{:ok, meta, socket}
end
defp error_to_string(:too_large), do: dgettext("errors", "Too large")
defp error_to_string(:too_many_files), do: dgettext("errors", "You have selected too many files")
defp error_to_string(:not_accepted), do: dgettext("errors", "You have selected an unacceptable file type")
defp internal_storage?, do: is_nil(CloudStorage.bucket())
defp upload_opts(socket, true), do: allow_upload(socket, :file, accept: accept_files(), max_entries: 1)
defp upload_opts(socket, false), do: allow_upload(socket, :file, accept: accept_files(), max_entries: 1, external: &presign_upload/2)
defp accept_files, do: ~w(.jpg .jpeg .png .avif .gif .webp .svg)
end |
/*
* Copyright 2023 Datastrato Pvt Ltd.
* This software is licensed under the Apache License version 2.
*/
package com.datastrato.gravitino.dto.responses;
import com.datastrato.gravitino.rest.RESTResponse;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import javax.annotation.Nullable;
import lombok.EqualsAndHashCode;
import lombok.Getter;
/** Represents the response of an OAuth2 error. */
@Getter
@EqualsAndHashCode
public class OAuth2ErrorResponse implements RESTResponse {
@JsonProperty("error")
private String type;
@Nullable
@JsonProperty("error_description")
private String message;
/**
* Creates a new OAuth2ErrorResponse.
*
* @param type The type of the error.
* @param message The message of the error.
*/
public OAuth2ErrorResponse(String type, String message) {
this.type = type;
this.message = message;
}
/** This is the constructor that is used by Jackson deserializer */
public OAuth2ErrorResponse() {}
/**
* Validates the OAuth2ErrorResponse.
*
* @throws IllegalArgumentException if the OAuth2ErrorResponse is invalid.
*/
@Override
public void validate() throws IllegalArgumentException {
Preconditions.checkArgument(type != null, "OAuthErrorResponse should contain type");
}
} |
import axios from 'axios'
/**
*
* @param {string} email
* @param {string} password
* @returns Promise
*/
export const login = (email, password) => {
let body = {
email,
password
}
// Return the response with a promice
return axios.post('https://reqres.in/api/login', body)
}
export const getAllUsers = () => {
return axios.get('https://reqres.in/api/users')
}
export const getPagedUsers = (page) => {
return axios.get(`https://reqres.in/api/users?page=${page}`)
}
export const getUserByID = (id) => {
return axios.get(`https://reqres.in/api/users/${id}`)
}
export const createUser = (name, job) => {
let newUser = {
name,
job
}
return axios.post(`https://reqres.in/api/users`, newUser)
}
export const updateUser = (id, name, job) => {
let newData = {
name,
job
}
return axios.put(`https://reqres.in/api/users/${id}`, newData)
}
// TODO: delete user
export const deleteUser = (id) => {
return axios.delete(`https://reqres.in/api/users/${id}`)
} |
import React, { useState } from 'react';
import './Styles/main.css';
import Landing from './Pages/landing.js';
import NewProject from './Pages/newProject.js';
import ProjectHome from './Pages/projectHome.js';
import CategoryCreation from './Pages/categoryCreation.js';
import CategoryHome from './Pages/categoryHome.js';
// FAKE LODED SAVE FILE FOR TEST PURPOSES
const fakeSave = {
data: {
name: "Project Name",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur luctus purus a risus laoreet, nec dapibus sem accumsan. Fusce semper placerat augue ac scelerisque. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec eleifend rutrum risus id rutrum. Donec pulvinar velit quam, ac commodo ante porttitor ut. Vestibulum ut lectus quis erat varius rhoncus. Cras ultrices vel nisi ac condimentum. Pellentesque nec eros augue. \n Pellentesque at sodales justo, non accumsan tellus. Nunc pretium tellus eu porttitor interdum. Nam sit amet augue scelerisque, fringilla mauris quis, semper lectus. Ut orci quam, consequat eget finibus vel, posuere nec nibh. Aenean tincidunt fermentum elementum. Suspendisse sed pulvinar ex, id molestie eros. Donec luctus a arcu in hendrerit. Sed tincidunt sapien a laoreet dignissim. Nunc tincidunt sagittis odio ut aliquet. Ut maximus diam ut felis rutrum dignissim. Maecenas luctus placerat vulputate. Curabitur massa urna, efficitur ut turpis nec, laoreet sollicitudin urna. In hac habitasse platea dictumst.",
image: "",
categories: [
{
name: "Characters",
elements: [],
element_content: [
{
name: "Age",
type: "input"
}
],
}
]
}
}
export default function App() {
const [ page, setPage ] = useState("categoryHome");
const [ loadedSaveFile, setLoadedSaveFile ] = useState(fakeSave);
const [ navPage, setNavPage ] = useState(1);
const appInfo = {
get: { page, loadedSaveFile, navPage },
set: {
page: setPage,
loadedSaveFile: setLoadedSaveFile,
navPage: setNavPage
}
}
return (
<div>
{page === "landing" ? <Landing appInfo={appInfo} /> : null}
{page === "newProject" ? <NewProject appInfo={appInfo} /> : null}
{page === "projectHome" ? <ProjectHome appInfo={appInfo} /> : null}
{page === "categoryCreation" ? <CategoryCreation appInfo={appInfo} /> : null}
{page === "categoryHome" ? <CategoryHome appInfo={appInfo} /> : null}
</div>
)
} |
import {
ChangeEvent,
Dispatch,
MouseEvent,
SetStateAction,
useEffect,
useState,
} from 'react';
import {
Table as MUITable,
TableBody,
TableCell,
TableContainer,
TablePagination,
TableRow,
Typography,
Chip,
Collapse,
Box,
IconButton,
} from '@mui/material';
import CheckIcon from '@mui/icons-material/Check';
import VolumeOffIcon from '@mui/icons-material/VolumeOff';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import { s } from 'utils';
import Paper from 'components/Paper';
import Title from 'components/Title';
import TableHead from './TableHead';
import TableFilter from './TableFilter';
function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
if (a[orderBy] === null) return -1;
if (b[orderBy] === null) return 1;
if (b[orderBy] < a[orderBy]) return -1;
if (b[orderBy] > a[orderBy]) return 1;
return 0;
}
export type Order = 'asc' | 'desc';
function getComparator<Key extends keyof any>(
order: Order,
orderBy: Key,
): (a: { [key in Key]: any }, b: { [key in Key]: any }) => number {
return order === 'desc'
? (a, b) => descendingComparator(a, b, orderBy)
: (a, b) => -descendingComparator(a, b, orderBy);
}
export function getSortedColumns(row: any, header: boolean, columnsOrder: string[]) {
if (columnsOrder?.length) {
return columnsOrder.map((field) =>
header
? Object.keys(row).find((key) => key === field)
: Object.entries(row).find(([key]) => key === field),
);
} else {
return header ? Object.keys(row) : Object.entries(row);
}
}
const CellContents = ({ cell, column }): JSX.Element => {
if (Array.isArray(cell)) {
return <>{cell.join(', ')}</>;
} else if (typeof cell === 'boolean') {
if (cell) {
return column === 'muted' ? (
<VolumeOffIcon color="primary" />
) : (
<CheckIcon color="primary" />
);
} else {
return <>{'--'}</>;
}
} else if (cell === null) {
return <>{'--'}</>;
} else {
if (column === 'conditions') {
return (
<Typography
color={
cell.toLowerCase() === 'healthy'
? 'success.main'
: cell.toLowerCase() === 'pending'
? 'secondary.main'
: 'error'
}
>
{String(cell)}
</Typography>
);
}
return <>{String(cell)}</>;
}
};
interface TableProps<T> {
rows: T[];
height?: number | string;
searchable?: boolean;
paginate?: boolean;
expandable?: boolean;
loading?: boolean;
serverLoading?: boolean;
serverHasNextPage?: boolean;
expandKey?: keyof T;
numPerPage?: number;
selectedRow?: string;
type?: string;
columnsOrder?: string[];
filterOptions?: FilterOptions;
onSelectRow?: Dispatch<SetStateAction<any>>;
onPageChange?: Dispatch<number>;
onRowsPerPageChange?: Dispatch<number>;
mapDisplay?: (args: any) => any;
}
interface FilterOptions {
filters: string[];
filterFunctions: { [filter: string]: (args: any) => boolean };
}
export const Table = <T extends unknown>({
rows,
height,
searchable,
paginate,
expandable,
loading,
serverLoading,
serverHasNextPage,
expandKey,
numPerPage,
selectedRow,
type,
columnsOrder,
filterOptions,
onSelectRow,
onPageChange,
onRowsPerPageChange,
mapDisplay,
}: TableProps<T>) => {
type RowWithId = T & {
id: string;
};
const [allRows, setAllRows] = useState<RowWithId[]>([]);
const [currRows, setCurrRows] = useState(allRows);
const [order, setOrder] = useState<Order>('asc');
const [orderBy, setOrderBy] = useState('');
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(
paginate ? numPerPage || 25 : rows.length,
);
const [searchTerm, setSearchTerm] = useState<string>('');
const [filter, setFilter] = useState<string>('All');
const handleRequestSort = (_: MouseEvent<unknown>, property: any) => {
const isAsc = orderBy === property && order === 'asc';
setOrder(isAsc ? 'desc' : 'asc');
setOrderBy(property);
};
const handleChangePage = (_: unknown, newPage: number) => {
// if we dont have data for the next page then trigger api
if (serverLoading && serverHasNextPage && newPage >= allRows.length / rowsPerPage) {
onPageChange?.(newPage);
}
setPage(newPage);
};
const handleChangeRowsPerPage = (event: ChangeEvent<HTMLInputElement>) => {
onRowsPerPageChange?.(parseInt(event.target.value, 10));
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const { filters, filterFunctions } = filterOptions || {};
const filterEnabled = Boolean(filterOptions && filters && filterFunctions);
const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0;
useEffect(() => {
const rowsWithId: RowWithId[] = rows.map((row, index) => {
if (!(row as any).id) {
(row as any).id = `${index}`;
}
return row as T & { id: string };
});
setAllRows(rowsWithId);
}, [rows]);
useEffect(() => {
if (type === 'Log') {
if (allRows.length > 0) {
if (currRows.length === 0) {
setCurrRows(allRows);
}
// If we aren't loading and the whole page is empty rows reset page to zero
if (!loading && emptyRows > 0 && emptyRows >= rowsPerPage) {
setPage(0);
}
}
}
}, [currRows, allRows, page, rowsPerPage, emptyRows, loading, type]);
useEffect(() => {
let rows = allRows;
if (mapDisplay) {
rows = rows.map(mapDisplay);
}
if (searchable && searchTerm !== '') {
rows = rows.filter((row) =>
Object.values(row)
.join()
.toLowerCase()
.trim()
.includes(searchTerm.toLowerCase().trim()),
);
}
if (filterEnabled && filter && filter !== 'All') {
rows = rows.filter(filterFunctions[filter]);
}
setCurrRows(rows);
}, [
searchable,
searchTerm,
allRows,
filterEnabled,
filterFunctions,
filter,
mapDisplay,
type,
]);
useEffect(() => {
if (type !== 'Log') setPage(0);
}, [searchable, searchTerm, type]);
const getHeaderText = (): string => {
const filterString = !filterEnabled || filter === 'All' ? '' : filter;
const searchString = searchTerm ? `"${searchTerm}"` : '';
return `${
currRows.length !== 0 ? currRows.length : ''
} ${searchString} ${filterString} ${type}${s(currRows.length)}`;
};
const handleOnSelect = (row) => {
onSelectRow?.(allRows.find((r) => r.id === row.id));
};
return (
<Paper>
{type && <Title>{getHeaderText()}</Title>}
{(!!filterOptions || searchable) && (
<TableFilter
type={type}
filters={filters}
filter={filter}
setFilter={setFilter}
searchTerm={searchTerm}
setSearchTerm={setSearchTerm}
searchEnabled={searchable}
filterEnabled={!!filterOptions}
/>
)}
<TableContainer sx={{ maxHeight: height || 'none' }}>
<MUITable stickyHeader aria-labelledby="tableTitle" size="small">
<TableHead
rows={rows}
order={order}
orderBy={orderBy}
onRequestSort={handleRequestSort}
columnsOrder={columnsOrder}
expandable={expandable}
/>
<TableBody>
{!loading &&
currRows
.sort(getComparator(order, orderBy))
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row, index) => {
return (
<>
<TableRow
key={String(row.id) ?? index}
sx={{
'&:last-child td, &:last-child th': { border: 0 },
cursor: `${onSelectRow ? 'pointer' : 'default'}`,
height: 42,
}}
hover={!!onSelectRow}
selected={selectedRow === String(row.id)}
>
{expandable && (
<TableCell sx={{ display: 'flex', alignItems: 'center' }}>
{typeof (row as any).status === 'string' && (
<Chip
sx={{
height: '10px',
width: '10px',
marginTop: 2,
marginBottom: 2,
marginRight: 1,
top: '-1px',
position: 'relative',
}}
color={
({ OK: 'success', ERROR: 'error' }[
(row as any).status
] as any) || ('default' as any)
}
/>
)}
{row[expandKey] && (
<IconButton
aria-label="expand row"
size="small"
onClick={() => handleOnSelect(row)}
>
{selectedRow === String(row.id) ? (
<KeyboardArrowUpIcon />
) : (
<KeyboardArrowDownIcon />
)}
</IconButton>
)}
</TableCell>
)}
{getSortedColumns(row, false, columnsOrder)
.filter(([key]) => key !== 'id' && key !== '__typename')
.map(([_, value], i) => {
return (
<TableCell
key={`${value as any}-${i}`}
align={!i ? 'left' : 'right'}
onClick={() => handleOnSelect(row)}
>
<CellContents cell={value} column={columnsOrder[i]} />
</TableCell>
);
})}
</TableRow>
{expandable && row[expandKey] && (
<TableRow>
<TableCell
style={{ paddingBottom: 0, paddingTop: 0 }}
colSpan={6}
>
<Collapse
in={selectedRow === String(row.id)}
timeout="auto"
unmountOnExit
>
<Box sx={{ margin: 1 }}>
<Typography
gutterBottom
component="div"
style={{ fontSize: 10 }}
>
<div
style={{ whiteSpace: 'pre-wrap', maxWidth: '90%' }}
>
{JSON.stringify(row[expandKey], null, 2)}
</div>
</Typography>
</Box>
</Collapse>
</TableCell>
</TableRow>
)}
</>
);
})}
{emptyRows > 0 && (
<TableRow
style={{
height: 33 * emptyRows,
}}
>
<TableCell colSpan={6} />
</TableRow>
)}
</TableBody>
</MUITable>
</TableContainer>
{paginate && (
<TablePagination
rowsPerPageOptions={[5, 10, 25]}
component="div"
count={
allRows.length / rowsPerPage - 1 === page &&
serverLoading &&
serverHasNextPage
? -1
: currRows.length
}
rowsPerPage={rowsPerPage}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
)}
</Paper>
);
};
export default Table; |
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import instanse from '../../axios'
import { RootState } from '../store'
//получение постов
export const getPost = createAsyncThunk<dataType[]>('post/getPost', async () => {
const { data } = await instanse.get<dataType[]>('/posts')
return data
})
type deleteParams = {
_id: string
}
//удаление поста
export const DeleetePost = createAsyncThunk('post/DeleetePost', async ({ _id }: deleteParams) => {
const { data } = await instanse.delete(`/post/${_id}`)
return data
})
//посты по популярности
export const populatePost = createAsyncThunk('post/populatePost', async () => {
const { data } = await instanse.get('/populate')
return data
})
//посты по новизне
export const newSortPost = createAsyncThunk('post/newPost', async () => {
const { data } = await instanse.get('/new')
return data
})
type paramsTag = {
tag: string
}
export const articlesbytag = createAsyncThunk<dataType[], paramsTag>('post/articlesbytag', async (params) => {
const { tag } = params
const { data } = await instanse.get<dataType[]>('articlesbytag', { params: { tag } })
return data
})
type params = {
title: string,
tags: string,
text: string,
imageUrl: string
}
export const addPost = createAsyncThunk<postType[], params>('getPost/addPost', async (params: params) => {
const { data } = await instanse.post('/posts', params)
return data
})
type typeParams = {
title: string,
tags: string,
text: string,
imageUrl: string
}
type removeParamsType = {
_id: string | undefined,
params: typeParams
}
export const RemovePost = createAsyncThunk('getPost/RemovePost', async (removeParams: removeParamsType) => {
const { _id, params } = removeParams
const { data } = await instanse.patch(`/posts/${_id}`, params)
return data
})
export enum Status {
LOADING = 'loading',
SUCCESS = 'succes',
ERROR = 'error'
}
type userType = {
avatarUrl: string,
createdAt: string,
email: string,
fullName: string,
passwordHash: string,
updatedAt: string,
__v: number,
_id: string,
}
export type dataType = {
_id: string,
title: string,
text: string,
tags: string[],
viewsCount: number,
imageUrl: string,
createdAt: string,
updatedAt: string,
__v: number,
user: userType,
comments: commentsType[],
fullName: string,
email: string,
}
export type commentsType = {
createdAt: string,
post: string,
text: string,
updatedAt: string,
__v: number,
_id: string,
}
type postType = {
_id: string,
fullName: string,
email: string,
createdAt: string,
updatedAt: string,
__v: number,
imageUrl: string,
user: userType,
viewsCount: number,
tags: string[],
text: string,
title: string
comments: commentsType[],
}
interface initialStateType {
status: Status,
data: dataType[],
post: postType[],
poppup: boolean
}
const initialState: initialStateType = {
data: [],
// post: {
// _id: '',
// fullName: '',
// email: '',
// createdAt: '',
// updatedAt: '',
// __v: 0,
// imageUrl: '',
// user: '',
// viewsCount: 0,
// tags: [],
// text: '',
// title: '',
// comments: []
// },
post:[],
status: Status.LOADING,
poppup: false
}
const getPostSlice = createSlice({
name: 'getPost',
initialState,
reducers: {
eyePoppup: (state, action) => {
state.poppup = action.payload
}
},
extraReducers: (builder) => {
//получение постов
builder.addCase(getPost.pending, (state) => {
state.data = [];
state.status = Status.LOADING;
});
builder.addCase(getPost.fulfilled, (state, action) => {
state.data = action.payload;
state.status = Status.SUCCESS;
});
builder.addCase(getPost.rejected, (state) => {
state.data = [];
state.status = Status.ERROR;
});
//получение популярных постов
builder.addCase(populatePost.pending, (state) => {
state.data = [];
state.status = Status.LOADING;
});
builder.addCase(populatePost.fulfilled, (state, action) => {
state.data = action.payload;
state.status = Status.SUCCESS;
});
builder.addCase(populatePost.rejected, (state) => {
state.data = [];
state.status = Status.ERROR;
});
//получение новых
builder.addCase(newSortPost.pending, (state) => {
state.data = [];
state.status = Status.LOADING;
});
builder.addCase(newSortPost.fulfilled, (state, action) => {
state.data = action.payload;
state.status = Status.SUCCESS;
});
builder.addCase(newSortPost.rejected, (state) => {
state.data = [];
state.status = Status.ERROR;
});
//получение постов по тегу
builder.addCase(articlesbytag.pending, (state) => {
state.data = [];
state.status = Status.LOADING;
});
builder.addCase(articlesbytag.fulfilled, (state, action) => {
state.data = action.payload;
state.status = Status.SUCCESS;
});
builder.addCase(articlesbytag.rejected, (state) => {
state.data = [];
state.status = Status.ERROR;
});
//удаление поста
builder.addCase(DeleetePost.pending, (state, action) => {
state.data = state.data.filter(obj => obj._id !== action.meta.arg._id)
});
//создание поста
builder.addCase(addPost.pending, (state, action) => {
state.post = [];
state.status = Status.LOADING;
});
builder.addCase(addPost.fulfilled, (state, action) => {
const newData = action.payload.filter((item:postType) => {
return !state.data.some((existingItem) => existingItem._id === item._id);
});
state.data = [...state.data, ...newData];
state.status = Status.SUCCESS;
});
builder.addCase(addPost.rejected, (state, action) => {
state.status = Status.ERROR;
});
//измение поста
builder.addCase(RemovePost.pending, (state, action) => {
state.post =[];
state.status = Status.LOADING;
});
builder.addCase(RemovePost.fulfilled, (state, action) => {
state.data = action.payload;
state.status = Status.SUCCESS;
});
builder.addCase(RemovePost.rejected, (state, action) => {
state.post = []
state.status = Status.ERROR;
});
},
});
export const getPostSelector = (state: RootState) => state.getPost.data
export const getStatusSelector = (state: RootState) => state.getPost.status
export const getPostSelectorData = (state: RootState) => state.getPost
export const getPostSelectorPoppup = (state: RootState) => state.getPost.poppup
export const dataSelector = (state: RootState) => state.getPost.data
export const { eyePoppup } = getPostSlice.actions
export const getPostReduser = getPostSlice.reducer |
<script>
import axios from 'axios';
import { toast } from 'vue3-toastify';
import { useUserStore } from '@/stores/user';
import PeopleYouMayKnow from '@/components/PeopleYouMayKnow.vue';
import Trends from '@/components/Trends.vue';
import FeedItem from '@/components/FeedItem.vue';
import { RouterLink } from 'vue-router';
import FeedForm from '@/components/FeedForm.vue';
export default {
// 8a0f7d5f-a920-459a-ac9a-95fb3170c8c0
// 40a213f8-c283-42a4-a801-15085cc9acc4
name:'ProfileView',
setup() {
const userStore = useUserStore()
return {
userStore
}
},
components: {
PeopleYouMayKnow,
Trends,
FeedItem,
RouterLink,
FeedForm
},
data(){
return{
posts: [],
user: {
id: null
},
body: '',
is_private: false,
url: null,
can_send_friendship_request: null,
}
},
mounted() {
this.getFeed()
},
watch: {
'$route.params.id': {
handler:function() {
this.getFeed()
},
deep: true,
imediate:true
}
},
methods: {
onFileChange(e){
const file = e.target.files[0]
this.url = URL.createObjectURL(file);
},
sendDirectMessage(){
console.log('Send Messages');
axios
.get(`/api/chat/${this.$route.params.id}/get-or-create/`)
.then(response => {
console.log(response.data);
this.$router.push('/chat')
})
.catch(error => {
console.log('error', error);
})
},
sendFriendshipRequest(){
axios
.post(`/api/friends/${this.$route.params.id}/request/`)
.then(response => {
if(response.data.message === 'request already sent'){
toast.info('The request has already been sent')
this.can_send_friendship_request = false
} else {
toast.info('The request was sent')
}
})
.catch(error => {
console.log('error', error)
})
},
getFeed() {
axios
.get(`/api/posts/profile/${this.$route.params.id}`)
.then(response => {
this.posts = response.data.posts
this.user = response.data.user
this.can_send_friendship_request = response.data.can_send_friendship_request
})
.catch(error => {
console.log('error', error)
})
},
submitForm(){
let formData = new FormData()
formData.append('image', this.$refs.file.files[0])
formData.append('body', this.body)
formData.append('is_private', this.is_private)
axios
.post('/api/posts/create/', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
this.posts.unshift(response.data)
this.body = ''
this.is_private = false
this.$refs.file.value = ''
this.url = null
this.user.posts_count += 1
})
.catch(error => {
console.log('error', error)
})
},
logout() {
this.userStore.removeToken()
this.$router.push('/login')
},
deletePost(id){
this.posts = this.posts.filter(post => post.id !== id)
}
}
}
</script>
<template>
<div class="max-w-7xl mx-auto grid grid-cols-4 gap-4">
<div class="main-left col-span-1">
<div class="pb-4 bg-white border border-gray-200 text-center rounded-lg">
<img :src="user.get_avatar" class="mb-6 mt-2 mx-auto rounded-full">
<p><strong>{{ user.name }}</strong></p>
<div class="mt-6 flex space-x-8 justify-around" v-if="user.id">
<RouterLink :to="{name: 'friends', params: {id: user.id}}" class="text-xs text-gray-500">{{ user.friends_count }} friends</RouterLink>
<p class="text-xs text-gray-500">{{ user.posts_count }} posts</p>
</div>
<div class="mt-6" >
<button v-if="userStore.user.id !== user.id && can_send_friendship_request" class="inline-block py-4 px-3 bg-purple-600 text-xs text-white rounded-lg" @click="sendFriendshipRequest">Send friendship request</button>
<button v-if="userStore.user.id !== user.id" class="inline-block mt-4 py-4 px-3 bg-purple-600 text-xs text-white rounded-lg" @click="sendDirectMessage">Send Message</button>
<RouterLink v-if="userStore.user.id === user.id" class="inline-block mr-4 py-4 px-3 bg-purple-600 text-xs text-white rounded-lg" to="/profile/edit">Edit Profile</RouterLink>
<button v-if="userStore.user.id === user.id" class="inline-block py-4 px-3 bg-red-600 text-xs text-white rounded-lg" @click="logout">Log out</button>
</div>
</div>
</div>
<div class="main-center col-span-2 space-y-4">
<div
class=" bg-white border border-gray-200 rounded-lg"
v-if="userStore.user.id === user.id"
>
<FeedForm
v-bind:user="user"
v-bind:posts="posts"
/>
</div>
<div
class="p-4 bg-white border border-gray-200 rounded-lg"
v-for="post in posts"
v-bind:key="post.id"
>
<FeedItem v-bind:post="post" v-on:deletePost="deletePost"/>
</div>
</div>
<div class="main-right col-span-1 space-y-4">
<PeopleYouMayKnow />
<Trends />
</div>
</div>
</template>
<style>
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
</style> |
**SOAPEngine**
This generic [SOAP](http://www.wikipedia.org/wiki/SOAP) client allows you to access web services using a your [iOS](http://www.wikipedia.org/wiki/IOS) app and [Mac OS X](http://www.wikipedia.org/wiki/OS_X) app.
With this Framework you can create [iPhone](http://www.wikipedia.org/wiki/IPhone), [iPad](http://www.wikipedia.org/wiki/IPad) and [Mac OS X](http://www.wikipedia.org/wiki/OS_X) apps that supports [SOAP](http://www.wikipedia.org/wiki/SOAP) Client Protocol. This framework able executes methods at remote web services with [SOAP](http://www.wikipedia.org/wiki/SOAP) standard protocol.
## Features
* Support both 2001 (v1.1) and 2003 (v1.2) [XML](http://www.wikipedia.org/wiki/XML) schema.
* Support array, array of structs, dictionary and sets.
* Support for user-defined object with serialization of complex data types and array of complex data types, even embedded multilevel structures.
* Supports [ASMX](http://www.wikipedia.org/wiki/ASP.NET#Other_files) Services, [WCF](http://www.wikipedia.org/wiki/Windows_Communication_Foundation) Services ([SVC](http://www.wikipedia.org/wiki/ASP.NET#Other_files)) and now also the [WSDL](http://www.wikipedia.org/wiki/Web_Services_Description_Language) definitions.
* Supports [Basic](http://www.wikipedia.org/wiki/Basic_access_authentication), [Digest](http://www.wikipedia.org/wiki/Digest_access_authentication) and [NTLM](http://www.wikipedia.org/wiki/Integrated_Windows_Authentication) Authentication, [WS-Security](http://www.wikipedia.org/wiki/WS-Security), Client side Certificate and custom security header.
* Supports [iOS](http://www.wikipedia.org/wiki/IOS) Social Account to send [OAuth2.0](http://www.wikipedia.org/wiki/OAuth) token on the request.
* [AES256](http://www.wikipedia.org/wiki/Advanced_Encryption_Standard) or [3DES](http://www.wikipedia.org/wiki/Triple_DES) Encrypt/Decrypt data without [SSL](http://www.wikipedia.org/w/index.php?title=Transport_Layer_Security) security.
* An example of service and how to use it is included in source code.
## Requirements for [iOS](http://www.wikipedia.org/wiki/IOS)
* [iOS](http://www.wikipedia.org/wiki/IOS) 5.1.1, and later
* [XCode](http://www.wikipedia.org/wiki/Xcode) 5.0 or later
* Security.framework
* Accounts.framework
* Foundation.framework
* UIKit.framework
* libxml2.dylib
## Requirements for [Mac OS X](http://www.wikipedia.org/wiki/OS_X)
* [OS X](http://www.wikipedia.org/wiki/OS_X) 10.9 and later
* [XCode](http://www.wikipedia.org/wiki/Xcode) 5.0 or later
* Security.framework
* Accounts.framework
* Foundation.framework
* AppKit.framework
* Cocoa.framework
* libxml2.dylib
## Limitations
* for [WCF](http://www.wikipedia.org/wiki/Windows_Communication_Foundation) services, only supports basic http bindings [<basicHttpBinding>](https://msdn.microsoft.com/library/ms731361.aspx).
* in [Mac OS X](http://www.wikipedia.org/wiki/OS_X) unsupported image objects, instead you can use the [NSData](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html).
## How to use
with [Delegates](https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html) :
``` objective-c
#import <SOAPEngine/SOAPEngine.h>
// standard soap service (.asmx)
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.userAgent = @"SOAPEngine";
soap.delegate = self; // use SOAPEngineDelegate
// each single value
[soap setValue:@"my-value1" forKey:@"Param1"];
[soap setIntegerValue:1234 forKey:@"Param2"];
// service url without ?WSDL, and you can search the soapAction in the WSDL
[soap requestURL:@"http://www.my-web.com/my-service.asmx"
soapAction:@"http://www.my-web.com/My-Method-name"];
#pragma mark - SOAPEngine Delegates
- (void)soapEngine:(SOAPEngine *)soapEngine didFinishLoading:(NSString *)stringXML {
NSDictionary *result = [soapEngine dictionaryValue];
// read data from a dataset table
NSArray *list = [result valueForKeyPath:@"NewDataSet.Table"];
}
```
with [Block programming](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html) :
``` objective-c
#import <SOAPEngine/SOAPEngine.h>
// TODO: your user object
MyClass myObject = [[MyClass alloc] init];
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.userAgent = @"SOAPEngine";
soap.version = VERSION_WCF_1_1; // WCF service (.svc)
// service url without ?WSDL, and you can search the soapAction in the WSDL
[soap requestURL:@"http://www.my-web.com/my-service.svc"
soapAction:@"http://www.my-web.com/my-interface/my-method"
value:myObject
complete:^(NSInteger statusCode, NSString *stringXML) {
NSDictionary *result = [soap dictionaryValue];
NSLog(@"%@", result);
} failWithError:^(NSError *error) {
NSLog(@"%@", error);
}];
```
directly from [WSDL](http://www.wikipedia.org/wiki/Web_Services_Description_Language) (not recommended is slow) :
``` objective-c
#import <SOAPEngine/SOAPEngine.h>
// TODO: your user object
MyClass myObject = [[MyClass alloc] init];
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.userAgent = @"SOAPEngine";
// service url with WSDL, and operation (method name) without tempuri
[soap requestWSDL:@"http://www.my-web.com/my-service.amsx?wsdl"
operation:@"my-method-name"
value:myObject
completeWithDictionary:^(NSInteger statusCode, NSDictionary *dict) {
NSLog(@"Result: %@", dict);
} failWithError:^(NSError *error) {
NSLog(@"%@", error);
}];
```
with [Notifications](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/index.html) :
``` objective-c
#import <SOAPEngine/SOAPEngine.h>
// TODO: your user object
MyClass myObject = [[MyClass alloc] init];
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.userAgent = @"SOAPEngine";
soap.version = VERSION_WCF_1_1; // WCF service (.svc)
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(soapEngineDidFinishLoading:)
name:SOAPEngineDidFinishLoadingNotification
object:nil];
// service url without ?WSDL, and you can search the soapAction in the WSDL
[soap requestURL:@"http://www.my-web.com/my-service.svc"
soapAction:@"http://www.my-web.com/my-interface/my-method"
value:myObject];
#pragma mark - SOAPEngine Notifications
- (void)soapEngineDidFinishLoading:(NSNotification*)notification
{
SOAPEngine *engine = notification.object; // SOAPEngine object
NSDictionary *result = [engine dictionaryValue];
NSLog(@"%@", result);
}
```
Synchronous request :
``` objective-c
#import <SOAPEngine/SOAPEngine.h>
NSError *error = nil;
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.responseHeader = YES; // use only for non standard MS-SOAP service like PHP
NSDictionary *dict = [soap syncRequestURL:@"http://www.my-web.com/my-service.amsx"
soapAction:@"http://tempuri.org/my-method" error:&error];
NSLog(@"error: %@, result: %@", error, dict)
```
[Swift](http://www.wikipedia.org/wiki/Swift_programming_language) language :
``` swift
var soap = SOAPEngine()
soap.userAgent = "SOAPEngine"
soap.actionNamespaceSlash = true
soap.version = VERSION_1_1
soap.responseHeader = true // use only for non standard MS-SOAP service
soap.setValue("param-value", forKey: "param-name")
soap.requestURL("http://www.my-web.com/my-service.asmx",
soapAction: "http://www.my-web.com/My-Method-name",
completeWithDictionary: { (statusCode : Int,
dict : [NSObject : AnyObject]!) -> Void in
var result:Dictionary = dict as Dictionary
NSLog("%@", result)
}) { (error : NSError!) -> Void in
NSLog("%@", error)
}
```
settings for soap authentication :
``` objective-c
#import <SOAPEngine/SOAPEngine.h>
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.userAgent = @"SOAPEngine";
// authorization
soap.authorizationMethod = SOAP_AUTH_BASIC; // basic auth
soap.username = @"my-username";
soap.password = @"my-password";
// TODO: your code here...
```
settings for Social [OAuth2.0](http://www.wikipedia.org/wiki/OAuth) token :
``` objective-c
#import <SOAPEngine/SOAPEngine.h>
#import <Accounts/Accounts.h>
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.userAgent = @"SOAPEngine";
// token authorization
soap.authorizationMethod = SOAP_AUTH_SOCIAL;
soap.apiKey = @"1234567890"; // your apikey https://dev.twitter.com/
soap.socialName = ACAccountTypeIdentifierTwitter;
// TODO: your code here...
```
encryption/decryption data without SSL/HTTPS :
``` objective-c
#import <SOAPEngine/SOAPEngine.h>
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.userAgent = @"SOAPEngine";
soap.encryptionType = SOAP_ENCRYPT_AES256; // or SOAP_ENCRYPT_3DES
soap.encryptionPassword = @"my-password";
// TODO: your code here...
```
[W3Schools](http://www.w3schools.com) example :
``` objective-c
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.actionNamespaceSlash = YES;
// w3schools Celsius to Fahrenheit
[soap setValue:@"30" forKey:@"Celsius"];
[soap requestURL:@"http://www.w3schools.com/webservices/tempconvert.asmx"
soapAction:@"http://www.w3schools.com/webservices/CelsiusToFahrenheit"
complete:^(NSInteger statusCode, NSString *stringXML) {
NSLog(@"Result: %f", [soap floatValue]);
} failWithError:^(NSError *error) {
NSLog(@"%@", error);
}];
```
[WebServiceX](http://www.webservicex.net) example :
``` objective-c
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.actionNamespaceSlash = NO;
[soap setValue:@"Roma" forKey:@"CityName"];
[soap setValue:@"Italy" forKey:@"CountryName"];
[soap requestURL:@"http://www.webservicex.com/globalweather.asmx"
soapAction:@"http://www.webserviceX.NET/GetWeather"
completeWithDictionary:^(NSInteger statusCode, NSDictionary *dict) {
NSLog(@"Result: %@", dict);
} failWithError:^(NSError *error) {
NSLog(@"%@", error);
}];
```
[BarCode](http://www.wikipedia.org/wiki/Barcode) with [WebServiceX](http://www.webservicex.net) example :
``` objective-c
SOAPEngine *soap = [[SOAPEngine alloc] init];
soap.actionNamespaceSlash = NO;
NSDictionary *barCodeParam = @{
@"Height" : @(100),
@"Width" : @(150),
@"Angle" : @(0),
@"Ratio" : @(5),
@"Module" : @(0),
@"Left" : @(0),
@"Top" : @(0),
@"CheckSum" : @"true",
@"FontName" : @"Arial",
@"FontSize" : @(20),
@"BarColor" : @"black",
@"BGColor" : @"white",
@"barcodeOption" : @"None",
@"barcodeType" : @"CodeEAN13",
@"checkSumMethod" : @"None",
@"showTextPosition" : @"BottomCenter",
@"BarCodeImageFormat" : @"PNG" };
[soap setValue:barCodeParam forKey:@"BarCodeParam"];
[soap setValue:@"9783161484100" forKey:@"BarCodeText"];
[soap requestURL:@"http://www.webservicex.net/genericbarcode.asmx"
soapAction:@"http://www.webservicex.net/GenerateBarCode"
completeWithDictionary:^(NSInteger statusCode, NSDictionary *dict) {
NSString *imgBase64 = [soap stringValue];
NSData *base64 = [[NSData alloc] initWithBase64Encoding:imgBase64];
UIImage *barCodeImage = [[UIImage alloc] initWithData:base64];
} failWithError:^(NSError *error) {
NSLog(@"Error: %@", error);
}];
```
[PAYPAL](http://www.paypal.com) example :
``` objective-c
SOAPEngine *soap = [[SOAPEngine alloc] init];
// PAYPAL associates a set of API credentials with a specific PayPal account
// you can generate credentials from this https://developer.paypal.com/docs/classic/api/apiCredentials/
// and convert to a p12 from terminal use :
// openssl pkcs12 -export -in cert_key_pem.txt -inkey cert_key_pem.txt -out paypal_cert.p12
soap.authorizationMethod = SOAP_AUTH_PAYPAL;
soap.username = @"support_api1.your-username";
soap.password = @"your-api-password";
soap.clientCerficateName = @"paypal_cert.p12";
soap.clientCertificatePassword = @"certificate-password";
soap.responseHeader = YES;
// use paypal for urn:ebay:api:PayPalAPI namespace
[soap setValue:@"0" forKey:@"paypal:ReturnAllCurrencies"];
// use paypal1 for urn:ebay:apis:eBLBaseComponents namespace
[soap setValue:@"119.0" forKey:@"paypal1:Version"]; // ns:Version in WSDL file
// certificate : https://api.paypal.com/2.0/ sandbox https://api.sandbox.paypal.com/2.0/
// signature : https://api-3t.paypal.com/2.0/ sandbox https://api-3t.sandbox.paypal.com/2.0/
[soap requestURL:@"https://api.paypal.com/2.0/"
soapAction:@"GetBalance" completeWithDictionary:^(NSInteger statusCode, NSDictionary *dict) {
NSLog(@"Result: %@", dict);
} failWithError:^(NSError *error) {
NSLog(@"%@", error);
}];
```
Upload file :
``` objective-c
SOAPEngine *soap = [[SOAPEngine alloc] init];
// read local file
NSData *data = [NSData dataWithContentsOfFile:@"my_video.mp4"];
// send file data
[soap setValue:data forKey:@"video"];
[soap requestURL:@"http://www.my-web.com/my-service.asmx"
soapAction:@"http://www.my-web.com/UploadFile"
completeWithDictionary:^(NSInteger statusCode, NSDictionary *dict) {
NSLog(@"Result: %@", dict);
} failWithError:^(NSError *error) {
NSLog(@"%@", error);
}];
```
Download file :
``` objective-c
SOAPEngine *soap = [[SOAPEngine alloc] init];
// send filename to remote webservice
[soap setValue:"my_video.mp4" forKey:@"filename"];
[soap requestURL:@"http://www.my-web.com/my-service.asmx"
soapAction:@"http://www.my-web.com/DownloadFile"
completeWithDictionary:^(NSInteger statusCode, NSDictionary *dict) {
// local writable directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths firstObject] stringByAppendingPathComponent:@"my_video.mp4"];
// the service returns file data in the tag named video
NSData *data = dict[@"video"];
[data writeToFile:@"my_video.mp4" atomically:YES];
} failWithError:^(NSError *error) {
NSLog(@"%@", error);
}];
```
## Optimizations
When using the method named requestWSDL three steps are performed :
1. retrieve the WSDL with an http request.
2. processing to identify the soapAction.
3. calls the method with an http request.
this is not optimized, very slow, instead you can use the optimization below :
1. retrieving manually the SOAPAction directly from WSDL (once with your favorite browser).
2. use the method named requestURL instead of requestWSDL.
## Install in your apps
1. add -lxml2 in Build Settings --> Other Linker Flags.

2. add /usr/include/libxml2 in Build Settings --> Header Search Paths.

3. SOAPEngine64.framework (for iOS apps) or SOAPEngineOSX.framework (for Mac OS X apps).
4. add Security.framework.
5. add Accounts.framework.
6. add AppKit.framework (only for Mac OS X apps, not required for iOS apps).

7. in your class import <SOAPEngine64/SOAPEngine.h> or <SOAPEngineOSX/SOAPEngine.h>.

8. and don't forget to add your app, that use our framework, in the list of [CocoaControls](https://www.cocoacontrols.com/controls/soapengine), thanks!
**[GET IT NOW!](http://www.prioregroup.com/iphone/soapengine.aspx)**
##Contacts
- https://twitter.com/DaniloPriore
- https://www.facebook.com/prioregroup
- http://www.prioregroup.com/
- http://it.linkedin.com/in/priore/ |
//
// lesson_02_triangle.cpp
// learn_opengl
//
// Created by Felix Ji on 1/6/23.
//
#include "lesson_02_triangle.hpp"
// vertex shader
const static char *vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
// fragment shader
const static char *fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\0";
int Lesson02::entry(void) {
// create window
GLFWwindow* window = createGraphicWindow("OpenGL Lesson 02", 800, 600, false);
float vertices[] = {
-0.5f, -0.5f, 0.0f, //left
0.5f, -0.5f, 0.0f, //right
0.0f, 0.5f, 0.0f // top
};
GLuint VBO, VAO;
// create VBO
glGenBuffers(1, &VBO);
// bind
glBindBuffer(GL_ARRAY_BUFFER, VBO);
// copy data to the bond buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// create VAO
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// agttributes
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
GLenum types[] = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER};
const GLchar* codes[] = {vertexShaderSource, fragmentShaderSource};
GLuint shaderProgram = shaderProgramFromSource(types, codes, 2);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// render loop, each iteration is called a frame
while(!glfwWindowShouldClose(window))
{
processKeyInput(window);
// rendering commands here
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwSwapBuffers(window);
glfwPollEvents();
}
// clean up all the resources
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteProgram(shaderProgram);
glfwTerminate();
return 0;
} |
package frc.robot.subsystems;
import java.util.Optional;
import org.photonvision.EstimatedRobotPose;
import org.photonvision.PhotonCamera;
import org.photonvision.PhotonPoseEstimator;
import edu.wpi.first.math.Pair;
import edu.wpi.first.math.estimator.SwerveDrivePoseEstimator;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants.ApriltagConstants;
/**
* The class for the Photonlib pose estimator.
*/
public final class Apriltag extends SubsystemBase {
/**
* The instance of the {@link Apriltag} class.
*/
private static Apriltag apriltag = null;
/**
* Array of Pair<PhotonCamera, PhotonPoseEstimator>
*/
private static Pair<PhotonCamera, PhotonPoseEstimator>[] estimators;
/**
* Gets the instance of the {@link Apriltag} class.
*
* @return The instance of the {@link Apriltag} class.
*/
public static Apriltag getInstance() {
if (apriltag == null) {
apriltag = new Apriltag();
}
return apriltag;
}
/**
* The constructor for the {@link Amp} class.
*/
private Apriltag() {
estimators = createEstimatorsArray(ApriltagConstants.PHOTON_CAMERAS.length);
for (int i = 0; i < estimators.length; i++) {
PhotonCamera camera =
new PhotonCamera(ApriltagConstants.PHOTON_CAMERAS[i].getName());
PhotonPoseEstimator estimator =
new PhotonPoseEstimator(
ApriltagConstants.FIELD_LAYOUT,
ApriltagConstants.PHOTON_CAMERAS[i].getStrategy(),
camera,
ApriltagConstants.PHOTON_CAMERAS[i].getTransform());
estimators[i] =
new Pair<PhotonCamera, PhotonPoseEstimator>(camera, estimator);
if (!camera.isConnected()) {
System.out.println(
"PhotonCamera "
+ camera.getName()
+ " is not connected!");
}
SmartDashboard.putBoolean(
camera.getName()
+ " Connected",
camera.isConnected());
}
}
@SuppressWarnings("unchecked")
private Pair<PhotonCamera, PhotonPoseEstimator>[] createEstimatorsArray(int length) {
return (Pair<PhotonCamera, PhotonPoseEstimator>[]) new Pair<?, ?>[length];
}
/**
* The periodic method for the apriltag subsystem. This method
* is run by the command scheduler every 20 ms.
*/
@Override
public void periodic() {
SwerveDrivePoseEstimator robotEstimator = Swerve.getInstance().getPoseEstimator();
for (Pair<PhotonCamera, PhotonPoseEstimator> estimator : estimators) {
PhotonCamera camera = estimator.getFirst();
SmartDashboard.putBoolean(
camera.getName() + " Connected",
camera.isConnected());
if (!camera.isConnected()) continue;
PhotonPoseEstimator poseEstimator = estimator.getSecond();
Optional<EstimatedRobotPose> pose = poseEstimator.update();
if (pose.isPresent()) {
robotEstimator.addVisionMeasurement(
pose.get().estimatedPose.toPose2d(),
pose.get().timestampSeconds);
}
}
}
} |
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CountryController as C;
use App\Http\Controllers\HotelController as H;
use App\Http\Controllers\OrderController as O;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
//Front
Route::get('', [H::class, 'pick'])->name('hotels-pick');
// Countries
Route::prefix('countries')->name('countries-')->group(function () {
Route::get('', [C::class, 'index'])->name('index');
Route::get('create', [C::class, 'create'])->name('create');
Route::post('', [C::class, 'store'])->name('store');
Route::get('edit/{country}', [C::class, 'edit'])->name('edit');
Route::put('{country}', [C::class, 'update'])->name('update');
Route::delete('{country}', [C::class, 'destroy'])->name('delete');
Route::get('show/{id}', [C::class, 'show'])->name('show');
});
// Hotels
Route::prefix('hotels')->name('hotels-')->group(function () {
Route::get('', [H::class, 'index'])->name('index');
Route::get('create', [H::class, 'create'])->name('create');
Route::post('', [H::class, 'store'])->name('store');
Route::get('edit/{hotel}', [H::class, 'edit'])->name('edit');
Route::put('{hotel}', [H::class, 'update'])->name('update');
Route::delete('{hotel}', [H::class, 'destroy'])->name('delete');
Route::get('show/{id}', [H::class, 'show'])->name('show');
Route::put('delete-picture/{hotel}', [H::class, 'deletePicture'])->name('delete-picture');
});
// Orders
Route::post('add-hotel-to-order', [O::class, 'add'])->name('pickHotel-add');
Route::get('my-orders', [O::class, 'showMyOrders'])->name('my-orders');
Route::prefix('order')->name('selectedServices-')->group(function () {
Route::get('', [O::class, 'index'])->name('index');
Route::put('status/{order}', [O::class, 'setStatus'])->name('status');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); |
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:kitap_arkadasligi/src/configs/flavors.dart';
import 'package:kitap_arkadasligi/src/store/AppStore.dart';
import 'package:kitap_arkadasligi/src/utils/di/getit_register.dart';
import 'package:kitap_arkadasligi/src/utils/route/app_router.dart';
import 'package:overlay_support/overlay_support.dart';
AppStore appStore = AppStore();
Future<void> main() async {
F.appFlavor = Flavor.dev;
WidgetsFlutterBinding.ensureInitialized();
await setupGetIt();
//appStore.toggleDarkMode(value: getBoolAsync(isDarkModeOnPref));
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final AppRouter _appRouter = getIt<AppRouter>();
@override
void initState() {
Firebase.initializeApp();
super.initState();
}
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
//Close keyboard when background tapped
FocusScope.of(context).requestFocus(FocusNode());
},
child: OverlaySupport.global(
child: MaterialApp.router(
localizationsDelegates: const [],
onGenerateTitle: (BuildContext context) => "context.l10n.appTitle",
// Define a light and dark color theme. Then, read the user's
// preferred ThemeMode (light, dark, or system default) from the
// SettingsController to display the correct theme.
themeMode: ThemeMode.light,
// Router
routerDelegate: _appRouter.delegate(),
routeInformationProvider: _appRouter.routeInfoProvider(),
routeInformationParser: _appRouter.defaultRouteParser(),
// builder: EasyLoading.init(),
),
));
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
} |
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
using namespace std;
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
#define ALPHABET_SIZE 26
#define MAX_WORD_LENGTH 1000000
struct node {
int value;
node *children[ALPHABET_SIZE];
};
node *getNewNode(void) {
node *pNode = new node;
if(pNode) {
pNode->value = 0;
for(int i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
}
return pNode;
}
void insert(node *root, char word[]) {
int level;
int length = strlen(word);
int index;
node *currNode = root;
for( level = 0; level < length; level++ ) {
index = CHAR_TO_INDEX(word[level]);
if( !currNode->children[index] )
currNode->children[index] = getNewNode();
else
currNode->children[index]->value = 1;
currNode = currNode->children[index];
}
currNode->value = 1;
}
int minSearch(node *root, char word[]) {
int level = 0;
int length = strlen(word);
int index;
node *currNode;
currNode = root;
index = CHAR_TO_INDEX(word[level]);
currNode = currNode->children[index];
for(level = 1; level < length; level++) {
index = CHAR_TO_INDEX(word[level]);
if(!currNode->children[index])
return 0;
int count = 0;
if(currNode->value == 0) {
for (int i = 0; i < ALPHABET_SIZE; i++) {
if (currNode->children[i] != NULL)
count++;
if (count > 1)
break;
}
if (count == 1)
break;
}
currNode = currNode->children[index];
}
return level;
}
int main() {
int numCases;
ifstream infile("autocomplete.txt");
infile >> numCases;
int count = 0;
while (count < numCases) {
int numWords;
infile >> numWords;
int result = 0;
node *myTrieRoot = getNewNode();
while (numWords > 0) {
char word[MAX_WORD_LENGTH];
infile >> word;
insert(myTrieRoot, word);
result += minSearch(myTrieRoot, word);
numWords--;
}
count++;
cout << "Case #" << count << ": " << result << endl;
}
return 0;
} |
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const cors = require('cors');
const authRoute = require("./rootes/auth");
const userRoute = require("./rootes/Users");
const postRoute = require("./rootes/Posts");
const CategoriesRoute = require("./rootes/Categories");
const questinoRoute=require("./rootes/Question");
const multer = require("multer");
const UserModel = require("./models/User");
const path =require("path");
app.use("/images",express.static(path.join(__dirname,"/images")))
//bhanuprakashlagishetty
//gELEQAyZ1QHgUT7X
const url="mongodb+srv://bhanuprakashlagishetty:bhanuprakash@cluster1.lcpdkkr.mongodb.net/"
mongoose
.connect(url)
.then(console.log("connectd sunccesfully"))
.catch((err) => console.log(err));
app.use(express.json());
app.use(cors());
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
let name = Date.now().toString() + file.originalname;
req.body.filePath = name;
cb(null, name);
},
});
const upload = multer({ storage: storage });
app.post("/upload", upload.single("file"), (req, res) => {
console.log('Image Uploading Started');
const path=req.body.filePath;
const responseObject = { path };
const jsonString = JSON.stringify(responseObject);
// Send the JSON string as the response
return res.send(jsonString);
// return res.json(path);
})
app.use("/api/auth", authRoute);
app.use("/api/user", userRoute);
app.use("/api/posts", postRoute);
app.use("/api/categories", CategoriesRoute);
app.use("/api/question",CategoriesRoute);
app.get("/", (req, res) => {
app.use(express.static(path.resolve(__dirname, "frontend", "build")));
res.sendFile(path.resolve(__dirname, "frontend", "build", "index.html"));
});
app.listen("5000", () => {
console.log("backend is running");
}); |
import 'package:flutter/material.dart';
import 'package:flutter_onboarding_slider/flutter_onboarding_slider.dart';
void main() {
runApp(const WelcomePage());
}
class WelcomePage extends StatefulWidget {
const WelcomePage({super.key});
@override
State<WelcomePage> createState() => _WelcomePageState();
}
class _WelcomePageState extends State<WelcomePage> {
final Color kDarkBlueColor = const Color(0xFF053149);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: OnBoardingSlider(
indicatorAbove: true,
indicatorPosition: 0,
addButton: false,
controllerColor: Color.fromARGB(255, 131, 130, 130),
totalPage: 1,
headerBackgroundColor: Colors.transparent,
pageBackgroundColor: Colors.transparent,
background: [
Container(),
],
speed: 1.8,
pageBodies: [
Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
padding: const EdgeInsets.symmetric(horizontal: 40),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/4.png',
height: MediaQuery.of(context).size.height * 0.3,
),
Text(
'Welcome',
textAlign: TextAlign.center,
style: TextStyle(
color: kDarkBlueColor,
fontSize: 35,
fontWeight: FontWeight.w600,
),
),
const SizedBox(
height: 20,
),
const Text(
'Have a better sharing experience',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black26,
fontSize: 18.0,
fontWeight: FontWeight.w600,
),
),
SizedBox(
height: 50,
),
Column(
children: [
ElevatedButton(
onPressed: () {},
child: Padding(
padding: EdgeInsets.only(
left: MediaQuery.of(context).size.width * 0.1,
right: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.width * 0.03,
bottom: MediaQuery.of(context).size.width * 0.03,
),
child: Text(
'Create an account',
style: TextStyle(
fontSize: 20,
color: Color.fromARGB(255, 37, 37, 37),
fontWeight: FontWeight.bold),
),
),
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
backgroundColor:
Color.fromARGB(255, 241, 189, 74))),
SizedBox(
height: 5,
),
ElevatedButton(
onPressed: () {},
child: Padding(
padding: EdgeInsets.only(
left: MediaQuery.of(context).size.width * 0.1,
right: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.width * 0.03,
bottom: MediaQuery.of(context).size.width * 0.03,
),
child: Text(
'Log in',
style: TextStyle(
fontSize: 20,
color: Color.fromARGB(255, 245, 196, 60),
fontWeight: FontWeight.bold),
),
),
style: ElevatedButton.styleFrom(
side: BorderSide(
color: Color.fromARGB(255, 245, 196, 60),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
backgroundColor:
Color.fromARGB(255, 255, 255, 255))),
],
),
],
),
),
],
),
);
}
} |
use std::fmt::Display;
use pest::Parser;
use crate::{ast::parse_ast, errors::CompilationError, parser::*};
#[derive(Debug)]
pub enum CompilationStage {
LoadFile,
ParseGrammar,
BuildAst,
}
impl Display for CompilationStage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CompilationStage::ParseGrammar => write!(f, "parsing grammar"),
CompilationStage::BuildAst => write!(f, "building ast"),
CompilationStage::LoadFile => write!(f, "loading input"),
}
}
}
pub fn parse_str_to_ast(input: &str) -> Result<crate::ast::Ast, CompilationError> {
let pairs = DscpParser::parse(Rule::main, input);
if let Err(e) = pairs {
return Err(CompilationError {
stage: CompilationStage::ParseGrammar,
exit_code: exitcode::DATAERR,
inner: Box::new(e),
});
}
let pairs = pairs.unwrap();
parse_ast(pairs)
}
#[cfg(test)]
mod test {
use super::parse_str_to_ast;
#[test]
fn valid_empty_token() {
assert_eq!(
parse_str_to_ast(
r##"
token TestToken {}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_token_fields() {
assert_eq!(
parse_str_to_ast(
r##"
token TestToken {
role_field: Role,
token_field: Test,
literal_field: Literal,
file_field: File,
none_field: None,
spec_literal_field: "test",
union_field: "a" | "b" | "c"
}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_token_fields_trailing_comma() {
assert_eq!(
parse_str_to_ast(
r##"
token TestToken {
role_field: Role,
token_field: Test,
literal_field: Literal,
file_field: File,
none_field: None,
spec_literal_field: "test",
union_field: "a" | "b" | "c",
}
"##
)
.is_ok(),
true
);
}
#[test]
fn invalid_token_name() {
assert_eq!(
parse_str_to_ast(
r##"
token Test-Token {}
"##
)
.is_ok(),
false
);
}
#[test]
fn invalid_token_name_keyword() {
assert_eq!(
parse_str_to_ast(
r##"
token token {}
"##
)
.is_ok(),
false
);
}
#[test]
fn invalid_field_name() {
assert_eq!(
parse_str_to_ast(
r##"
token TestToken {
invalid-name: Role
}
"##
)
.is_ok(),
false
);
}
#[test]
fn invalid_field_name_keyword() {
assert_eq!(
parse_str_to_ast(
r##"
token TestToken {
where: Role
}
"##
)
.is_ok(),
false
);
}
#[test]
fn invalid_field_type() {
assert_eq!(
parse_str_to_ast(
r##"
token TestToken {
name: Ro-le
}
"##
)
.is_ok(),
false
);
}
#[test]
fn valid_empty_fn() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test || => || where {}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_pub_fn() {
assert_eq!(
parse_str_to_ast(
r##"
pub fn Test || => || where {}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_priv_fn() {
assert_eq!(
parse_str_to_ast(
r##"
priv fn Test || => || where {}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_args() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: Bar
| => |
biz: Baz
| where {}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_args_trailing_commas() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: Bar,
| => |
biz: Baz,
| where {}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_multiple_args() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: Bar,
foo2: Bar
| => |
biz: Baz,
biz2: Baz,
| where {}
"##
)
.is_ok(),
true
);
}
#[test]
fn invalid_input_arg_name() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
fo-o: Bar,
| => || where {}
"##
)
.is_ok(),
false
);
}
#[test]
fn invalid_input_arg_type() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: B-ar,
| => || where {}
"##
)
.is_ok(),
false
);
}
#[test]
fn invalid_output_arg_name() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test || => |
fo-o: Bar,
| where {}
"##
)
.is_ok(),
false
);
}
#[test]
fn invalid_output_arg_type() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test || => |
foo: B-ar,
| where {}
"##
)
.is_ok(),
false
);
}
#[test]
fn valid_where_eq_prop_token() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: Bar,
| => |
biz: Baz,
| where {
foo.a == biz
}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_where_eq_token_token() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: Bar,
| => |
biz: Baz,
| where {
foo == biz
}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_where_eq_prop_prop() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: Bar,
| => |
biz: Baz,
| where {
foo.a == biz.b
}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_where_neq() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: Bar,
| => |
biz: Baz,
| where {
foo.a != biz.b
}
"##
)
.is_ok(),
true
);
}
#[test]
fn valid_where_eq_prop_is() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: Bar,
| => |
biz: Baz,
| where {
foo.b: File
}
"##
)
.is_ok(),
true,
);
}
#[test]
fn valid_where_eq_prop_isnt() {
assert_eq!(
parse_str_to_ast(
r##"
fn Test |
foo: Bar,
| => |
biz: Baz,
| where {
foo.b !: File
}
"##
)
.is_ok(),
true,
);
}
#[test]
fn valid_end_to_end() {
let result = parse_str_to_ast(
r##"
token TestToken {
role_field: Role,
token_field: TestToken,
literal_field: Literal,
file_field: File,
none_field: None,
spec_literal_field: "test",
union_field: "a" | "b" | "c",
}
pub fn TestFn | in: TestToken | => | out: TestToken | where {
out.role_field == in.role_field,
out.literal_field == "literal",
(in.union_field == "a" | out.union_field == "b"),
}
"##,
);
assert_eq!(result.is_ok(), true);
}
} |
# Profundizando en diccionarios
# los diccionarios guardan un orden (a diferencia de un set)
diccionario = {'Nombre': 'Juan', 'Apellido': 'Perez', 'Edad': 28}
print(diccionario)
# los dic son mutables, pero las llaves deben ser inmutables
# diccionario = {(1, 2): 'Valor1'}
print(diccionario)
# Se agrega una llave si no se encuentra
diccionario['Departamento'] = 'Sistemas'
print(diccionario)
# No hay valores duplicados en las llaves de un diccionario (si ya existe, se reemplaza)
diccionario['Nombre'] = 'Juan Carlos'
print(diccionario)
# recuperar elementos de un diccionario - indicando una llave
print(diccionario['Nombre'])
# Si no encuentra la llave lanza una excepcion
# metodo get recupera una llave, y si no existe no lanza excepcion
# ademas podemos regresar un valor en caso que no exista la llave
print(diccionario.get('Nombre', 'No se encontro la llave'))
print(diccionario)
# setdefault si modifica el diccionario, ademas se puede agregar un valor por default
nombre = diccionario.setdefault('Nombre', 'Valor por default')
print(nombre)
# Imprimir con pprint
from pprint import pprint as pp
# help(pp)
pp(diccionario, sort_dicts=False) |
#include "main.h"
/**
* set_bit - sets the value of a bit to 1 at a given index
* @n: pointer to a number
* @index: the index of the bit to be set to 1
* Return: 1 if successful, otherwise -1
*/
int set_bit(unsigned long int *n, unsigned int index)
{
unsigned long int num;
num = 1;
if (index > 63)
{
return (-1);
}
else
{
num <<= index;
*n = *n | num;
return (1);
}
} |
# Deploying your containerized app to Azure Kubernetes Service with Jenkins CI/CD Pipeline and GitHub Webhook
# Part 5

This is the last part of the Jenkins CI/CD Pipeline series, where we will be deploying our containerized app to Azure Kubernetes Service.
In case you havent gone through the previous tutorials of this series, I highly recommend you review them before proceeding with this one for better continuity and understanding.
Create a Jenkins VM [Create a Jenkins Linux VM Part 1](./README.md)
Install Docker Engine on the Azure VM that is running Jenkins [Install Docker on a Linux VM Part 2](./install_docker_on_linux.md)
Run the Build manually to Deploy the new image build to your Azure Web App [Deploy Web App Part 3](./deploy_webapp.md)
Run the Build with GitHub Webhook to Deploy the new image build to your Azure Web App [Deploy Web App Part 4](./deploy_webapp_CICD.md)
Here are quick steps that we shall follow here for this tutorial:
> * Prepare your GitHub repository with the Application Code.
> * Deploy a sample NodeJS Application to an AKS cluster.
> * Create a basic Jenkins project.
> * Set up credentials for Jenkins to interact with ACR.
> * Create a Jenkins build job and GitHub webhook for automated builds.
> * Test the CI/CD Jenkins pipeline to update the application in AKS based on GitHub code commits.
# Prerequisites
> * Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
> * Jenkins - Install Jenkins on a Linux VM
> * Azure CLI: Install Azure CLI (version 2.0.67 or higher) on the Jenkins server.
> * Sample Application Code can be found at my Github Repository [HERE](https://github.com/mfkhan267/jenkins_on_azure2024.git)
# Create your Fully Automated CI/CD Jenkins Pipeline
## GitHub Repository with Sample Application Code
Create a new GitHub repository with your application code. Sample Application Code can be found at my Github Repository
[HERE](https://github.com/mfkhan267/jenkins_on_azure2024.git)
## GitHub Webhook
We will need to create a webhook for the GitHub repository that should be able to remotely trigger your builds jobs in Jenkins everytime the application changes are commited and pushed to the above application code repository.

We will define the Jenkins Pipeline with the Pipeline script from SCM method as shown below



This should now allow the GitHub repository webhook to remote trigger the Build Jobs for the above pipeline in Jenkins, whenever you commit changes to your application code hosted on GitHub.
# Deploy a sample NodeJS Application to an AKS cluster
Let us login to the Azure Portal >> Search >> Azure Kubernetes Servies >> Create Kubernetes Cluster with configurations as shown below

Click Add node pool >> Give the pool a name (nplinux OR npwindows) with User Mode and Node Size as D2s_v3 >> Add >> Review and Create

# Connecting to the AKS Cluster
Let us now launch the Azure Cloud Shell. The Cloud Shell has the kubectl pre-installed.
az aks get-credentials --resource-group aks_RG267 --name aks_demo267
This command downloads credentials and configures the Kubernetes CLI to use them. To verify our connection with the AKS Cluster, let us run the following
kubectl get nodes

Execute the below command to get the kubeconfig info, we will need to copy the entire content of the file to txt file that we will use to create a Jenkins Credentials with a secret file and name it "aks_secret.txt"
cat ~/.kube/config

How to verify integration between ACR and AKS Cluster?
az role assignment list --scope /subscriptions/<subscriptionID>/resourceGroups/<resourcegroupname>/providers/Microsoft.ContainerRegistry/registries/<acrname> -o table
az role assignment list --scope /subscriptions/<insert your subscriptions ID here>/resourceGroups/jenkins267/providers/Microsoft.ContainerRegistry/registries/acr267 -o table
Make sure that the output of the above command is not empty. If empty run the following command. For AKS to pull the Container images from the ACR, you will need to integrate your ACR with the AKS cluster using the az aks update command with the attach acr parameter and a valid value for acr-name or acr-resource-id. This should configure necessary permissions for AKS to access the ACR
az aks update --resource-group <myResourceGroup> --name <myAKSCluster> --attach-acr <acr-resource-id>
OR
az aks update --resource-group <myResourceGroup> --name <myAKSCluster> --attach-acr <acr-name>
az aks update --resource-group aks_RG267 --name aks_demo267 --attach-acr acr267
# Create a Secret File credential in Jenkins
We will now create a Secret File credential in Jenkins with the secret text file "aks_secret.txt" that we had create earlier. This will allow Jenkins to connect to the AKS Cluster and update the Image Version for the deployment that is already up and running.

# Deploy a sample NodeJS Application to the AKS cluster
To deploy the application, you use a manifest file to create all the objects required to run the AKS Store application. A Kubernetes manifest file defines a cluster's desired state, such as which container images to run. The manifest includes the following Kubernetes deployments and services.
In the Cloud Shell, let us donwload the sample repository files
git clone https://github.com/mfkhan267/jenkins_on_azure2024.git
cd deployments
kubectl apply -f svc-lb.yml
kubectl apply -f deploy-complete.yml
# Test the initial Application
Check for a public IP address for the web-deploy application in the load balancer service.
Monitor progress using the kubectl get service command with the --watch argument.
kubectl get service ps-lb


Once the EXTERNAL-IP address (public IP) is available for the load balancer service, open a web browser to the external IP address of your service to see the your sample NodeJS app is up and running.

# Commit and Push your application code changes to the Application repository on GitHub
Commit and push your changes to your application code on GitHub and the GitHub webhook should trigger the Jenkins Pipeline Build automatically.
The Jenkins Pipeline will automatically Build, Push and Deploy your containerized Application to the Azure Kubernetes Service Cluster as part of your complete CI/CD Job. The GitHub webhook should now trigger the Jenkins Pipeline Job and the Build Job should run automatically.


Wait until the Jenkins Pipeline build job is over. A graphic below the **Build History** heading indicates that the job is being executed or completed. Go to the job build and console output to see the results.
Congratulations! You have successfully **Deployed** your containerized app to your Azure Web App. Your Azure Web App should now be running your newly generated docker image with your App Code
# Testing your Web App that should now be running your newly generated docker image with your App Code
Below is Application v13 running as a Deployment on the AKS Cluster (your build version may differ)


The Application should now be running the new Build v14 as the recently modified deployment on the AKS Cluster (your build version may differ)


That's all folks. Hope you enjoyed the Jenkins series with Docker, Azure Container Registry, Azure WebApp and Azure Kubernetes Service.
Kindly share with the community.
Until next time.
See you soon.
## Next steps |
using System;
using Unity.Entities.CodeGeneratedJobForEach;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
namespace Unity.Entities
{
/// <summary>
/// An abstract class to implement in order to create a system that uses ECS-specific Jobs.
/// </summary>
/// <remarks>Implement a JobComponentSystem subclass for systems that perform their work using
/// <see cref="IJobForEach{T0}"/> or <see cref="IJobChunk"/>.</remarks>
/// <seealso cref="ComponentSystem"/>
public abstract class JobComponentSystem : ComponentSystemBase
{
JobHandle m_PreviousFrameDependency;
bool m_AlwaysSynchronizeSystem;
/// <summary>
/// Use Entities.ForEach((ref Translation translation, in Velocity velocity) => { translation.Value += velocity.Value * dt; }).Schedule(inputDependencies);
/// </summary>
protected internal ForEachLambdaJobDescription Entities => new ForEachLambdaJobDescription();
#if ENABLE_DOTS_COMPILER_CHUNKS
/// <summary>
/// Use query.Chunks.ForEach((ArchetypeChunk chunk, int chunkIndex, int indexInQueryOfFirstEntity) => { YourCodeGoesHere(); }).Schedule();
/// </summary>
public LambdaJobChunkDescription Chunks
{
get
{
return new LambdaJobChunkDescription();
}
}
#endif
/// <summary>
/// Use Job.WithCode(() => { YourCodeGoesHere(); }).Schedule(inputDependencies);
/// </summary>
protected internal LambdaSingleJobDescription Job
{
get
{
return new LambdaSingleJobDescription();
}
}
unsafe JobHandle BeforeOnUpdate()
{
BeforeUpdateVersioning();
// We need to wait on all previous frame dependencies, otherwise it is possible that we create infinitely long dependency chains
// without anyone ever waiting on it
m_PreviousFrameDependency.Complete();
if (m_AlwaysSynchronizeSystem)
{
CompleteDependencyInternal();
return default;
}
return m_DependencyManager->GetDependency(m_JobDependencyForReadingSystems.Ptr, m_JobDependencyForReadingSystems.Length, m_JobDependencyForWritingSystems.Ptr, m_JobDependencyForWritingSystems.Length);
}
#pragma warning disable 649
private unsafe struct JobHandleData
{
public void* jobGroup;
public int version;
}
#pragma warning restore 649
unsafe void AfterOnUpdate(JobHandle outputJob, bool throwException)
{
AfterUpdateVersioning();
// If outputJob says no relevant jobs were scheduled,
// then no need to batch them up or register them.
// This is a big optimization if we only Run methods on main thread...
if (((JobHandleData*) &outputJob)->jobGroup != null)
{
JobHandle.ScheduleBatchedJobs();
m_PreviousFrameDependency = m_DependencyManager->AddDependency(m_JobDependencyForReadingSystems.Ptr, m_JobDependencyForReadingSystems.Length, m_JobDependencyForWritingSystems.Ptr, m_JobDependencyForWritingSystems.Length, outputJob);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (JobsUtility.JobDebuggerEnabled)
{
var dependencyError = SystemDependencySafetyUtility.CheckSafetyAfterUpdate(this, ref m_JobDependencyForReadingSystems, ref m_JobDependencyForWritingSystems, m_DependencyManager);
if (throwException && dependencyError != null)
throw new InvalidOperationException(dependencyError);
}
#endif
}
public sealed override void Update()
{
#if ENABLE_PROFILER
using (m_ProfilerMarker.Auto())
#endif
{
if (Enabled && ShouldRunSystem())
{
if (!m_PreviouslyEnabled)
{
m_PreviouslyEnabled = true;
OnStartRunning();
}
var inputJob = BeforeOnUpdate();
JobHandle outputJob = new JobHandle();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var oldExecutingSystem = ms_ExecutingSystem;
ms_ExecutingSystem = this;
#endif
try
{
outputJob = OnUpdate(inputJob);
}
catch
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
ms_ExecutingSystem = oldExecutingSystem;
#endif
AfterOnUpdate(outputJob, false);
throw;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
ms_ExecutingSystem = oldExecutingSystem;
#endif
AfterOnUpdate(outputJob, true);
}
else if (m_PreviouslyEnabled)
{
m_PreviouslyEnabled = false;
OnStopRunning();
}
}
}
internal sealed override void OnBeforeCreateInternal(World world)
{
base.OnBeforeCreateInternal(world);
#if !NET_DOTS
m_AlwaysSynchronizeSystem = GetType().GetCustomAttributes(typeof(AlwaysSynchronizeSystemAttribute), true).Length != 0;
#else
m_AlwaysSynchronizeSystem = false;
var attrs = TypeManager.GetSystemAttributes(GetType());
foreach (var attr in attrs)
{
if (attr.GetType() == typeof(AlwaysSynchronizeSystemAttribute))
m_AlwaysSynchronizeSystem = true;
}
#endif
}
internal sealed override void OnBeforeDestroyInternal()
{
base.OnBeforeDestroyInternal();
m_PreviousFrameDependency.Complete();
}
/// <summary>Implement OnUpdate to perform the major work of this system.</summary>
/// <remarks>
/// The system invokes OnUpdate once per frame on the main thread when any of this system's
/// EntityQueries match existing entities, or if the system has the AlwaysUpdate
/// attribute.
///
/// To run a Job, create an instance of the Job struct, assign appropriate values to the struct fields and call
/// one of the Job schedule functions. The system passes any current dependencies between Jobs -- which can include Jobs
/// internal to this system, such as gathering entities or chunks, as well as Jobs external to this system,
/// such as Jobs that write to the components read by this system -- in the `inputDeps` parameter. Your function
/// must combine the input dependencies with any dependencies of the Jobs created in OnUpdate and return the
/// combined <see cref="JobHandle"/> object.
/// </remarks>
/// <param name="inputDeps">Existing dependencies for this system.</param>
/// <returns>A Job handle that contains the dependencies of the Jobs in this system.</returns>
protected abstract JobHandle OnUpdate(JobHandle inputDeps);
}
} |
import { useSelector, useDispatch } from "react-redux";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
LineElement,
Title,
Tooltip,
Legend,
PointElement,
} from "chart.js";
import { Bar, Line } from "react-chartjs-2";
import GeneralButton from "../components/GeneralButton";
import { ScrollView } from "react-native-web";
import { useState } from "react";
import colors from "../style-utils/colors";
import paddings from "../style-utils/paddings";
import margins from "../style-utils/margins";
import borders from "../style-utils/borders";
import radiuses from "../style-utils/radiuses";
import text_styles from "../style-utils/text_styles";
import styled from "styled-components";
import SearchedUserActivityChartContainer from "./SearchedUserActivityChartContainer";
import SearchedUserPuzzleTypeChartContainer from "./SearchedUserPuzzleChartsContainer";
import React from "react";
import CircularProgress from "@mui/material/CircularProgress";
import FormField from "../registration-components/FormField";
import { useRef } from "react";
import { emitMessage } from "../client";
import { utdActions } from "../store/user-to-display-slice";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
BarElement,
Title,
Tooltip,
Legend
);
const DisplaySearchedUser = (props) => {
const dispatch = useDispatch();
const { user, showUser, isFetchingRecentUser } = useSelector(
(state) => state.userToDisplay
);
const messageRef = useRef();
const subjectRef = useRef();
const [action, setAction] = useState("");
console.log(action);
const takeAction = async () => {
const message = messageRef.current.value.trim();
const subject = subjectRef.current.value.trim();
if (action === "ban") {
const response = await fetch(
`${process.env.REACT_APP_BACKEND_URL}users/resolve-ban`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
userID: user._id,
message,
subject,
}),
withCredentials: true,
credentials: "include",
}
);
if (response.ok) {
const { data } = await response.json();
console.log(data);
if (!data.user.active)
emitMessage("ban-account", {
userID: data.user._id,
});
dispatch(utdActions.setUserActive(data.user.active));
setAction("");
}
} else if (action === "message") {
if (message === "" || subject === "") {
setInvalid(true);
if (message === "") setInvalidMessage("Must provide message");
if (subject === "") setInvalidSubject("Must provide subject");
} else {
const response = await fetch(
`${process.env.REACT_APP_BACKEND_URL}users/send-message`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
userID: user._id,
message,
subject,
}),
withCredentials: true,
credentials: "include",
}
);
if (response.ok) {
const { data } = await response.json();
console.log(data);
emitMessage("send-message", {
userID: user._id,
});
setAction("");
} else {
console.log("Smth went worng");
}
}
}
};
const [invalid, setInvalid] = useState(false);
const [invalidMessage, setInvalidMessage] = useState(undefined);
const [invalidSubject, setInvalidSubject] = useState(undefined);
return (
<ScrollView
style={{
display: "flex",
flexDirection: "column",
height: 100,
}}
>
{user && showUser && !isFetchingRecentUser && (
<React.Fragment>
{action === "" && (
<UserInfo>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
width: "100%",
height: "100%",
padding: "1vw",
boxSizing: "border-box",
borderBottom: `${borders.med}px solid #${colors.chocolate}`,
}}
>
<div>
<b>User ID</b>: {user._id}
</div>
<div>
<b>Group ID</b>: {user.userID}
</div>
</div>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "space-evenly",
justifyContent: "space-evenly",
width: "40%",
height: "20vh",
}}
>
<div>
<b>Email</b>: {user.email}
</div>
<div>
<b>Name</b>: {user.name}
</div>
<div>
<b>Role</b>: {user.role}
</div>
<div>
<b>Group</b>: {user.groupID}
</div>
<div>
<b>Status</b>: {user.active ? "active" : "banned"}
</div>
</div>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
width: user.active ? "35%" : "45%",
}}
>
<GeneralButton
label={user.active ? "Ban account" : "Reactivate account"}
handleButtonPress={() => {
setAction("ban");
}}
/>
<GeneralButton
label={"Send message"}
handleButtonPress={() => {
setAction("message");
}}
/>
</div>
</div>
</UserInfo>
)}
{action !== "" && (
<UserInfo>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<MessageSection>
<div>
<FormField
title={`Subject ${action === "ban" ? "(optional)" : ""}`}
type={"text"}
smallLabel={true}
style={{ width: "40vw" }}
reference={subjectRef}
invalid={invalid}
message={invalidSubject || undefined}
onFocus={() => {
setInvalidMessage(undefined);
setInvalidSubject(undefined);
setInvalid(false);
}}
/>
<FormField
title={`Message ${action === "ban" ? "(optional)" : ""}`}
type={"text"}
extendedMessage={true}
smallLabel={true}
reference={messageRef}
invalid={invalid}
message={invalidMessage || undefined}
onFocus={() => {
setInvalidMessage(undefined);
setInvalidSubject(undefined);
setInvalid(false);
}}
/>
</div>
</MessageSection>
<ButtonGroup>
<GeneralButton
label={"Cancel"}
handleButtonPress={() => {
setAction("");
}}
/>
<GeneralButton
label={"Confirm"}
handleButtonPress={async () => {
await takeAction();
}}
/>
</ButtonGroup>
</div>
</UserInfo>
)}
<SearchedUserPuzzleTypeChartContainer />
<SearchedUserActivityChartContainer />
</React.Fragment>
)}
{isFetchingRecentUser && (
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: "100%",
height: "100%",
}}
>
<CircularProgress
style={{
width: 50,
height: 50,
color: `#${colors.creme}`,
}}
color={"inherit"}
/>
</div>
)}
</ScrollView>
);
};
const UserInfo = styled.div`
display: flex;
flex-direction: column;
justify-content: space-evenly;
color: #${colors.darkerChocolate};
width: 100%;
margin: auto;
border: ${borders.med}px solid #${colors.chocolate};
padding: ${paddings.xxsmall}vw;
box-sizing: border-box;
border-radius: ${radiuses.med}px;
gap: 1vw;
height: 100%;
margin-bottom: 2vw;
font-size: 2vh;
`;
const ButtonGroup = styled.div`
display: flex;
align-items: center;
justify-content: space-evenly;
width: 30%;
`;
const MessageSection = styled.div`
display: flex;
flex-direction: column;
justify-content: space-evenly;
width: 60%;
`;
export default DisplaySearchedUser; |
// To parse this JSON data, do
//
// final getTagsResponse = getTagsResponseFromJson(jsonString);
import 'package:freezed_annotation/freezed_annotation.dart';
import 'dart:convert';
part 'get_tags_model.freezed.dart';
part 'get_tags_model.g.dart';
List<GetTagsResponse> getTagsResponseFromJson(String str) =>
List<GetTagsResponse>.from(
json.decode(str).map((x) => GetTagsResponse.fromJson(x)));
String getTagsResponseToJson(List<GetTagsResponse> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
@freezed
class GetTagsResponse with _$GetTagsResponse {
const factory GetTagsResponse({
@JsonKey(name: "_id") String? id,
@JsonKey(name: "name") String? name,
@JsonKey(name: "color") String? color,
@JsonKey(name: "__v") int? v,
@JsonKey(name: "priority") int? priority,
}) = _GetTagsResponse;
factory GetTagsResponse.fromJson(Map<String, dynamic> json) =>
_$GetTagsResponseFromJson(json);
} |
package com.csmtech.exporter;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.csmtech.model.Candidate;
public class ResultExcelExporter {
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private List<Candidate> candidates;
public ResultExcelExporter(List<Candidate> candidates) {
this.candidates = candidates;
workbook = new XSSFWorkbook();
}
private void writeHeaderLine() {
sheet = workbook.createSheet("result");
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("Result");
// Merge cells for the title row
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
// Create a cell style for the title
CellStyle titleStyle = workbook.createCellStyle();
XSSFFont titleFont = workbook.createFont();
titleFont.setBold(true);
titleStyle.setFont(titleFont);
titleStyle.setAlignment(HorizontalAlignment.CENTER);
// Apply the style to the title cell
titleCell.setCellStyle(titleStyle);
Row row = sheet.createRow(1);
CellStyle style = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setBold(true);
style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER);
createCell(row, 0, "Candidate College Name", style);
createCell(row, 1, "Candidate Id", style);
createCell(row, 2, "Subtest Taker", style);
createCell(row, 3, "Mark Appear", style);
createCell(row, 4, "Total Mark", style);
}
private void createCell(Row row, int columnCount, Object value, CellStyle style) {
sheet.autoSizeColumn(columnCount);
Cell cell = row.createCell(columnCount);
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Boolean) {
cell.setCellValue((Boolean) value);
} else if(value instanceof Double) {
cell.setCellValue((Double)value);
}
else {
cell.setCellValue((String) value);
}
cell.setCellStyle(style);
}
private void writeDataLines() {
int rowCount = 1;
CellStyle style = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setFontHeight(14);
style.setFont(font);
for (Candidate cand : candidates)
{
int i = 0;
i++;
Row row = sheet.createRow(rowCount++);
int columnCount = 0;
// createCell(row, columnCount++, user.getId(), style); //
createCell(row,columnCount++, i, style);
createCell(row, columnCount++, cand.getCandidateemail(), style);
createCell(row, columnCount++, cand.getSubTestTaker().getSubTestTakerName(), style);
createCell(row, columnCount++, cand.getMarkAppear(), style);
createCell(row, columnCount++, cand.getTotalMark(), style);
}
}
public void export(HttpServletResponse response) throws IOException {
writeHeaderLine();
writeDataLines();
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
workbook.close();
outputStream.close();
}
} |
package kr.or.ddit.login.dao;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import kr.or.ddit.security.userdetailes.EmployeeVOWrapper;
import kr.or.ddit.vo.groupware.EmployeeVO;
/**
* @author 박민주
* @since 2023. 11. 7.
* @version 1.0
* @see javax.servlet.http.HttpServlet
* <pre>
* [[개정이력(Modification Information)]]
* 수정일 수정자 수정내용
* -------- -------- ----------------------
* 2023. 11. 7. 박민주 최초작성
* 2023. 12.4 박민주 updateEmpPwAndStatus,updateEmpPw 추가
* Copyright (c) 2023 by DDIT All right reserved
* </pre>
*/
@Mapper
public interface LoginDAO extends UserDetailsService {
@Override
default UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
EmployeeVO inputdata = new EmployeeVO();
inputdata.setEmpCd(username);
EmployeeVO member = selectEmpForAuth(inputdata);
if(member==null)
throw new UsernameNotFoundException(username+" 해당 사용자 없음.");
return new EmployeeVOWrapper(member);
}
/**
* 사번을 기반으로 사용자의 기본 정보를 조회
*
* @param inputData
* @return 검색 결과 객체로 존재하지 않는 경우, null 반환.
*/
public EmployeeVO selectEmpForAuth(EmployeeVO inputData);
/**
* 사원정보 수정
* @param inputData
* @return
*/
public int updateEmpCertfNo(EmployeeVO inputData);
/**
* 직원 비밀번호를 생년월일로, 상태를 N으로 업데이트
* @param employee
*/
public int updateEmpPwAndStatus(EmployeeVO employee);
/**
* 직원 비밀번호를 입력한 값으로, 상태를 E로 업데이트
* @param employee
* @return
*/
public int updateEmpPw(EmployeeVO employee);
} |
classdef Bowman2017 < otslm.iter.objectives.Objective
% Cost function used in Bowman et al. 2017 paper.
% Inherits from :class:`Objective`.
%
% .. math::
%
% C = 10^d * (1.0 - \sum_{nm} \sqrt{I_nm T_nm} \cos(phi_nm - psi_nm))^2
%
% target and trial should be the complex field amplitudes.
%
% Properties
% - scale -- ``d`` scaling factor in cost function
% - field -- 'complex', 'phase', or 'amplitude' for optimisation type
% - normalize -- Normalize target/trial every evaluation
%
% See also Bowman2017 and :class:`Intensity`.
% Copyright 2019 Isaac Lenton
% This file is part of OTSLM, see LICENSE.md for information about
% using/distributing this file.
properties
scale % `d` scaling factor in cost function
field % 'complex', 'phase', or 'amplitude' for optimisation type
normalize % Normalize target/trial every evaluation
end
methods
function obj = Bowman2017(varargin)
% Construct a new objective function instance
%
% Usage
% obj = Bowman2017(...) construct a new objective function instance.
%
% Optional named arguments
% - scale num -- `d` scaling factor in cost function.
% Default: 0.5
%
% - field [char] -- One of 'complex', 'phase', or 'amplitude'
% for optimisation type. Default: 'complex'.
%
% - normalize bool -- Normalize target/trial every
% evaluation. Default: true.
%
% - roi [] | logical | function_handle -- specify the roi
% to use when evaluating the fitness function.
% Can be a logical array or a function handle.
% Default: []
%
% - target [] | matrix -- specify the target pattern for this
% objective. If not supplied, the target must be supplied
% when the evaluate function is called.
% Default: []
p = inputParser;
p.KeepUnmatched = true;
p.addParameter('field', 'complex');
p.addParameter('normalize', true);
p.addParameter('scale', 0.5);
p.parse(varargin{:});
unmatched = [fieldnames(p.Unmatched).'; struct2cell(p.Unmatched).'];
obj = obj@otslm.iter.objectives.Objective(unmatched{:});
obj.scale = p.Results.scale;
obj.normalize = p.Results.normalize;
obj.field = p.Results.field;
end
function obj = set.field(obj, value)
% Check for valid type
assert(any(strcmpi(value, {'complex', 'phase', 'amplitude'})), ...
'field must be one of ''both'', ''phase'' or ''amplitude''');
obj.field = value;
end
end
methods (Hidden)
function fitness = evaluate_internal(obj, target, trial)
% Cost function used in Bowman et al. 2017 paper.
%
% Range: [+Inf, 0] (0 = best match)
% Calculate the target intensity and amplitude
phi = angle(target);
T = abs(target).^2;
% Calculate the current intensity and amplitude
psi = angle(trial);
I = abs(trial).^2;
% Switch between the different types
switch obj.field
case 'amplitude'
% Throw away phase information
phi = zeros(size(phi));
psi = zeros(size(psi));
case 'phase'
% Throw away amplitude information
I = ones(size(I));
T = ones(size(T));
otherwise
% Keep both
end
tol = eps(1);
% Calculate cost
overlap = sum(sqrt(T(:).*I(:)) .* cos(psi(:) - phi(:)));
if obj.normalize && abs(overlap) > tol
overlap = overlap / sqrt(sum(T(:)) * sum(I(:)));
end
fitness = 10^obj.scale * (1.0 - overlap).^2;
end
end
end |
@extends('layouts.auth')
@section('content')
{{-- sendiri --}}
<!-- Page Content -->
<div class="page-content page-auth" id="register">
<div class="section-store-auth" data-aos="fade-up">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-4">
<h2>
Memulai untuk jual beli <br />
dengan cara terbaru
</h2>
<form method="POST" action="{{ route('register') }}" class="mt-3">
@csrf
<div class="form-group">
<label for="">Full Name</label>
<x-text-input id="name"
class="form-control"
type="text"
name="name"
:value="old('name')"
required
autofocus
v-model="name"
autocomplete="name" />
<x-input-error :messages="$errors->get('name')" class="mt-2 text-danger" />
</div>
<div class="form-group">
<label for="">Email Address</label>
<x-text-input
id="email"
v-model="email"
@change="checkEmailAvailable()"
class="form-control"
{{-- :class="{ 'is-invalid' : this.email_unavailable }" --}}
{{-- :class="('is-invalid' : this.email_unavailable)" --}}
type="email"
name="email"
:value="old('email')"
required
autocomplete="email" />
<x-input-error :messages="$errors->get('email')" class="mt-2 text-danger" />
</div>
<div class="form-group">
<label for="">Nomer Handphone</label>
<x-text-input
id="phone_number"
class="form-control"
type="string"
name="phone_number"
:value="old('phone_number')"
required
v-model="phone_number"
autocomplete="phone_number" />
<x-input-error :messages="$errors->get('phone_number')" class="mt-2 text-danger" />
</div>
<div class="form-group">
<label for="">Password</label>
<x-text-input
id="password"
class="form-control"
type="password"
name="password"
required
autocomplete="new-password" />
<x-input-error :messages="$errors->get('password')" class="mt-2 text-danger" />
</div>
<div class="form-group">
<label for="">Konfrimasi Password</label>
<x-text-input
id="password_confirmation"
class="form-control"
type="password"
name="password_confirmation"
required
autocomplete="new-password" />
<x-input-error :messages="$errors->get('password_confirmation')" class="mt-2 text-danger" />
</div>
<div class="form-group">
<label for="">Store</label>
<p class="text-muted">Apakah anda juga ingin membuka toko?</p>
<div
class="custom-control custom-radio custom-control-inline"
>
<input
type="radio"
class="custom-control-input"
name="is_store_open"
id="openStoreTrue"
v-model="is_store_open"
:value="true"
/>
<label for="openStoreTrue" class="custom-control-label"
>Iya, Boleh</label
>
</div>
<div
class="custom-control custom-radio custom-control-inline"
>
<input
type="radio"
class="custom-control-input"
name="is_store_open"
id="openStoreFalse"
v-model="is_store_open"
:value="false"
/>
<label for="openStoreFalse" class="custom-control-label"
>Tidak, Terimakasih</label
>
</div>
</div>
<div class="form-group" v-if="is_store_open">
<label for="">Nama Toko</label>
<x-text-input
id="store_name"
v-model="store_name"
class="form-control"
type="text"
name="store_name"
required
autofocus
autocomplete />
<x-input-error :messages="$errors->get('store_name')" class="mt-2 text-danger" />
</div>
<div class="form-group" v-if="is_store_open">
<label>Kategori</label>
<select name="categories_id" class="form-control">
@foreach ($categories as $category)
<option value="{{ $category->id }}">
{{ $category->name }}
</option>
@endforeach
</select>
</div>
<button
href="/index.html"
type="submit"
class="btn btn-success btn-block mt-4"
:disabled="this.email_unavailable"
>Sign Up Now</button
>
<a href="{{ route('login') }}" class="btn btn-singup btn-block mt-2"
>Back to Sign In</a
>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
@push('addon-script')
<script src="/vendor/vue/vue.js"></script>
<script src="https://unpkg.com/vue-toasted"></script>
<script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
<script>
Vue.use(Toasted);
var register = new Vue({
el: "#register",
mounted() {
AOS.init();
},
methods: {
checkEmailAvailable: function(){
var self = this;
axios.get('{{ route('api-register-check') }}',{
params: {
email: this.email
}
})
.then(function (response) {
if(response.data == "Available"){
self.$toasted.error(
"Email anda tersedia",
{
position: "top-center",
className: "rounded",
duration: 1000,
}
);
self.email_unavailable = false;
} else {
self.$toasted.error(
"Maaf, tampaknya email sudah terdaftar pada sistem kami.",
{
position: "top-center",
className: "rounded",
duration: 1000,
}
);
self.email_unavailable = true;
}
// handle success
console.log(response);
})
}
},
data() {
return {
name: "Angga Hazza Sett",
email: "kamujagoan@bwa.id",
phone_number: "081234123422",
is_store_open: "true",
store_name: "",
email_unavailable: false
}
}
});
</script>
@endpush |
import * as dotenv from "dotenv";
dotenv.config();
import axios from "axios";
const graphqlEndpoint = "https://api.github.com/graphql";
async function getCorrectness(url: [string, string]) {
try {
const key = process.env.GITHUB_TOKEN;
const owner = url[0];
const name = url[1];
let totalOpenIssues = 0;
let totalClosedIssues = 0;
let lastReleaseWeeklyDownloads = 0;
let maxReleaseWeeklyDownloads = 0;
const variables = {
owner,
name,
};
const query = `
query ($owner: String!, $name: String!) {
repository(owner: $owner, name: $name) {
openIssues: issues(states: OPEN) {
totalCount
}
closedIssues: issues(states: CLOSED) {
totalCount
}
releases(first: 100, orderBy: { field: CREATED_AT, direction: DESC }) {
totalCount
nodes {
releaseAssets(first: 20) {
nodes {
name
downloadCount
createdAt
}
}
}
}
}
}
`;
const result = await axios({
url: graphqlEndpoint,
method: "post",
headers: {
Authorization: `Bearer ${key}`,
},
data: {
query,
variables,
},
});
totalOpenIssues = result.data.data.repository.openIssues.totalCount;
totalClosedIssues = result.data.data.repository.closedIssues.totalCount;
if (totalOpenIssues + totalClosedIssues == 0) {
totalClosedIssues = 0;
totalOpenIssues = 1;
}
const releases = result.data.data.repository.releases.nodes;
const releasesCount = releases.length;
// Find The First Release With Valid Assets
let recent = -1;
for (let i = 0; i < releasesCount; i++) {
if (
releases[i] === undefined ||
releases[i].releaseAssets === undefined ||
releases[i].releaseAssets.nodes[0] === undefined
)
continue;
recent = i;
break;
}
if (recent == -1) {
// No Releases With Valid Assets
//console.log("No Releases With Valid Assets");
return totalClosedIssues / (totalClosedIssues + totalOpenIssues);
}
let recentRelease = releases[recent].releaseAssets.nodes[0].createdAt;
let weeksDifference = calculateWeeksDifference(recentRelease);
let recentDownloads = releases[recent].releaseAssets.nodes[0].downloadCount;
lastReleaseWeeklyDownloads = recentDownloads / weeksDifference;
maxReleaseWeeklyDownloads = lastReleaseWeeklyDownloads;
// Find The Max Release With Valid Assets
for (let i = recent + 1; i < releasesCount; i++) {
if (
releases[i] === undefined ||
releases[i].releaseAssets.nodes[0] === undefined
)
continue;
recentRelease = releases[i].releaseAssets.nodes[0].createdAt;
weeksDifference = calculateWeeksDifference(recentRelease);
recentDownloads = releases[i].releaseAssets.nodes[0].downloadCount;
let CurrWeeklyDownloads = recentDownloads / weeksDifference;
if (CurrWeeklyDownloads > maxReleaseWeeklyDownloads)
maxReleaseWeeklyDownloads = CurrWeeklyDownloads;
}
let correctness = calcCorrectnessScore(
totalClosedIssues,
totalOpenIssues,
maxReleaseWeeklyDownloads,
lastReleaseWeeklyDownloads
);
return correctness;
} catch (error) {
// console.error("Error fetching data:", error);
// Handle the error or return a default value if necessary
return 0;
}
}
export async function calcCorrectnessScore(
totalClosedIssues: number,
totalOpenIssues: number,
maxReleaseWeeklyDownloads: number,
lastReleaseWeeklyDownloads: number
): Promise<number> {
const correctness =
0.5 * (totalClosedIssues / (totalOpenIssues + totalClosedIssues)) +
0.5 * (lastReleaseWeeklyDownloads / maxReleaseWeeklyDownloads);
return correctness;
}
export { getCorrectness };
export function calculateWeeksDifference(timestamp: string): number {
// Convert the timestamp to a JavaScript Date object
const startTime = new Date(timestamp);
// Check if the provided timestamp is a valid date
if (isNaN(startTime.getTime())) {
//console.error("Invalid timestamp format");
return -1;
}
// Get the current time
const currentTime = new Date();
// Calculate the time difference in milliseconds
const timeDifferenceMs = currentTime.getTime() - startTime.getTime();
// Convert the time difference to weeks
const weeksDifference = timeDifferenceMs / (1000 * 60 * 60 * 24 * 7);
return weeksDifference;
} |
const PORT = process.env.PORT ?? 8000
const express = require('express')
const { v4: uuidv4 } = require('uuid')
const cors = require('cors')
const app = express()
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const Pool = require('pg').Pool
require('dotenv').config()
const pool = new Pool({
user: process.env.DBUSER,
password: process.env.DBPASSWORD,
host: process.env.DBHOST,
port: process.env.DBPORT,
database: process.env.DATABASE,
})
const prodFrontendURL = process.env.FRONTEND_URL;
const devFrontendURL = 'http://localhost:3000';
console.log(prodFrontendURL + " prodFrontendURL")
console.log(pool)
app.use(cors())
app.use(express.json())
app.use(
cors({
origin: [prodFrontendURL, devFrontendURL],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true,
})
);
// get all todos
app.get('/todos/:userEmail', async (req, res) => {
const { userEmail } = req.params
try {
const todos = await pool.query('SELECT * FROM todos WHERE user_email = $1', [userEmail])
res.json(todos.rows)
} catch (err) {
console.error(err)
}
})
// create a new todo
app.post('/todos', async(req, res) => {
const { user_email, title, progress, date } = req.body
const id = uuidv4()
try {
const newToDo = await pool.query(`INSERT INTO todos(id, user_email, title, progress, date) VALUES($1, $2, $3, $4, $5)`,
[id, user_email, title, progress, date])
res.json(newToDo)
} catch (err) {
console.error(err)
}
})
// edit a new todo
app.put('/todos/:id', async (req, res) => {
const { id } = req.params
const { user_email, title, progress, date } = req.body
try {
const editToDo =
await pool.query('UPDATE todos SET user_email = $1, title = $2, progress = $3, date = $4 WHERE id = $5;',
[user_email, title, progress, date, id])
res.json(editToDo)
} catch (err) {
console.error(err)
}
})
// delete a todo
app.delete('/todos/:id', async (req, res) => {
const { id } = req.params
try {
const deleteToDo = await pool.query('DELETE FROM todos WHERE id = $1;', [id])
res.json(deleteToDo)
} catch (err) {
console.error(err)
}
})
// signup
app.post('/signup', async (req, res) => {
const { email, password } = req.body
const salt = bcrypt.genSaltSync(10)
const hashedPassword = bcrypt.hashSync(password, salt)
try {
const signUp = await pool.query(`INSERT INTO users (email, hashed_password) VALUES($1, $2)`,
[email, hashedPassword])
const token = jwt.sign({ email }, 'secret', { expiresIn: '1hr' })
res.json({ email, token })
} catch (err) {
console.error(err)
if (err) {
res.json({ detail: err.detail})
}
}
})
console.log("EEEEEEeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
// login
app.post('/login', async (req, res) => {
console.log(req.body)
const { email, password } = req.body
try {
const users = await pool.query('SELECT * FROM users WHERE email = $1', [email])
if (!users.rows.length) return res.json({ detail: 'User does not exist!' })
const success = await bcrypt.compare(password, users.rows[0].hashed_password)
const token = jwt.sign({ email }, 'secret', { expiresIn: '1hr' })
if (success) {
res.json({ 'email' : users.rows[0].email, token})
} else {
res.json({ detail: "Wrong password"})
}
} catch (err) {
console.error(err)
}
})
app.listen(PORT, ( )=> console.log(`Server running on PORT ${PORT}`)) |
import * as yup from "yup";
export const basicSchema = yup.object().shape({
name: yup
.string()
.min(8, "Nombre es muy corto")
.matches(
/^[A-Za-z\s]+$/,
"Nombre no puede contener números ni caracteres especiales"
)
.required("Campo nombre es obligatorio"),
address: yup
.string()
.min(10, "Direccion es muy corta")
.required("Campo direccion es obligatorio"),
phoneNumber: yup
.string()
.matches(/^[0-9()+]+$/, "Telefono solo puede contener números, +, ( y )")
.required("Campo telefono es obligatorio"),
region: yup
.string()
.matches(
/^[A-Za-z\s]+$/,
"Region no puede contener números ni caracteres especiales"
)
.required("Campo ciudad es obligatorio"),
city: yup
.string()
.matches(
/^[A-Za-z\s]+$/,
"Ciudad no puede contener números ni caracteres especiales"
)
.required("Campo ciudad es obligatorio"),
});
export const creditCardSchema = yup.object().shape({
creditCardNumber: yup
.string()
.matches(
/^\d{16}$/,
"El número de tarjeta de crédito debe tener 16 dígitos válidos"
)
.required("El número de tarjeta de crédito es obligatorio"),
expirationMonth: yup
.string()
.matches(/^(0[1-9]|1[0-2])$/, "El mes de vencimiento no es válido")
.required("El mes de vencimiento es obligatorio"),
expirationYear: yup
.string()
.matches(/^(20|2[1-9])\d{2}$/, "El año de vencimiento no es válido")
.required("El año de vencimiento es obligatorio"),
cvv: yup
.string()
.matches(/^\d{3,4}$/, "El CVV debe ser un número de 3 o 4 dígitos")
.required("El CVV es obligatorio"),
}); |
import React from 'react';
import { makeStyles } from '@mui/styles';
import { Box, Tooltip } from '@mui/material';
import { getBranchesNames, toAcronym } from 'helpers/userlistHelpers';
const useStyles = makeStyles((theme) => {
return {
eachCode: {
display: 'flex',
alignItems: 'baseline',
flexDirection: 'column',
'& .branchBox': {
display: 'flex',
maxWidth: '150px',
flexWrap: 'wrap',
gap: '5px',
marginTop: '10px',
},
},
codeBranch: {
background: '#ebf2fe',
borderRadius: '4px',
padding: '0px 8px',
textTransform: 'uppercase',
},
department: {
padding: '0 8px',
backgroundColor: '#EBF2FE',
borderRadius: 4,
},
};
});
const CellCode = ({ row }) => {
//! State
const classes = useStyles();
//! Function
//! Render
return (
<div className={classes.eachCode}>
<span>{row?.staffCode}</span>
<Tooltip
title={<span style={{ whiteSpace: 'pre-line' }}>{getBranchesNames(row?.branchDetails)}</span>}
followCursor
arrow
>
<div className="branchBox">
{row?.branchDetails?.map((item, index) => {
if (index >= 2) return;
return (
<Box key={item?.id} className={classes.department}>
{toAcronym(item?.name)}
</Box>
);
})}
</div>
</Tooltip>
</div>
);
};
export default CellCode; |
using Phu.Data.Base;
using Phu.Data.Interfaces;
using Phu.Data.Repositories;
using Phu.Service.Interfaces;
using Phu.Service.Services;
using System;
using Unity;
namespace Phu.WebAPI
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container => container.Value;
#endregion
/// <summary>
/// Registers the type mappings with the Unity container.
/// </summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>
/// There is no need to register concrete types such as controllers or
/// API controllers (unless you want to change the defaults), as Unity
/// allows resolving a concrete type even if it was not previously
/// registered.
/// </remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below.
// Make sure to add a Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your type's mappings here.
container.RegisterType<IStudentService, StudentService>();
container.RegisterType<IStudentRepository, StudentRepository>();
container.RegisterType<IUnitOfWork, UnitOfWork>();
container.RegisterType<IDbFactory , DbFactory>();
}
}
} |
import React from 'react';
import axios from 'axios';
import {
Stack,
ImageList,
ImageListItem,
ImageListItemBar,
Typography,
TextField,
IconButton,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
DialogContentText,
Autocomplete,
CircularProgress,
} from '@mui/material';
import { LoadingButton } from '@mui/lab';
import { saveAs } from 'file-saver';
import ArchiveIcon from '@mui/icons-material/Archive';
import BorderColorIcon from '@mui/icons-material/BorderColor';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import { useEffect } from 'react';
import { API_IMAGETAGLINK, API_CAMPAIGNTAGLINK } from '../../utils/api';
import { useSelector, useDispatch } from 'react-redux';
import { tagSliceSelector } from '../../hooks/tag/tagSlice';
import {
imageSliceSelector,
setImageSource,
setScrollPageNumber,
setPaginatedImageList
} from '../../hooks/image/imageSlice';
import useImage from '../../hooks/image/useImage';
import ImageDialog from './imageDialog';
// function component for image list
export default function TitlebarImageList() {
const scrollPageNumber = useSelector(imageSliceSelector.scrollPageNumber);
const imageSource = useSelector(imageSliceSelector.imageSource);
const allTagList = useSelector(tagSliceSelector.allTagList);
const allImageList = useSelector(imageSliceSelector.paginatedImageList);
const tableStatus = useSelector(imageSliceSelector.tableStatus);
const imageObject = useSelector(imageSliceSelector.imageObject);
const buttonStatus = useSelector(imageSliceSelector.buttonStatus);
console.log(imageObject)
const dispatch = useDispatch();
const {
getFilteredImage,
isReachedMaxImages,
getPaginatedImage,
isDetailDialogOpen,
onDetailDialogOpen,
onDetailDialogClose,
isDeleteDialogOpen,
onDeleteImage,
onDeleteDialogClose,
onSaveDelete,
} = useImage();
const observer = React.useRef();
const lastImageRef = React.useCallback(
(node) => {
//TODOs
//include a variable to define which API to call, whether it's a search result or a normal image list
if (tableStatus === 'LOADING') return;
if (observer.current) observer.current.disconnect();
observer.current = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !isReachedMaxImages) {
dispatch(setScrollPageNumber(scrollPageNumber + 1));
console.log('entered');
}
});
if (node) observer.current.observe(node);
},
[tableStatus, isReachedMaxImages, dispatch, scrollPageNumber]
);
const [detail, setDetail] = React.useState(false);
React.useEffect(() => {
imageSource !== 'SEARCH' && getPaginatedImage(scrollPageNumber);
}, [scrollPageNumber, imageSource]);
React.useEffect(() => console.log(scrollPageNumber), [scrollPageNumber]);
// search function for image list
const onSearch = async (event, value) => {
if ((Array.isArray(value) && value.length) === 0){
dispatch(setPaginatedImageList([]));
dispatch(setImageSource('DEFAULT'));
value = ""
}
else {
dispatch(setImageSource('SEARCH'));
value = Object.keys(value).map((key) => value[key].tag_name)
}
dispatch(setScrollPageNumber(1));
getFilteredImage(value);
};
React.useEffect(() => console.log(imageSource), [imageSource]);
// function open image dialog
const openDetailDialog = (item) => {
setDetail(item);
onDetailDialogOpen();
};
// function to download selected image
const downloadImage = async (item) => {
// Fetch the image from server
axios
.get(
`${process.env.REACT_APP_API_ENDPOINT}/image/download/?image_url=${item.image_url}`,
{ responseType: 'blob' }
)
.then((response) => {
// file name
const file_name = item.image_name + '.' + item.image_type;
// save the file.
saveAs(response.data, file_name);
})
.catch((response) => {
console.error('Could not Download the image from the backend.', response);
});
};
return (
<div>
{/* Search component */}
<Stack spacing={3} direction='row' justifyContent='space-between'>
<Typography variant='h5' sx={{ fontColor: 'blue' }}>
Image Gallery
</Typography>
<Autocomplete
onChange={onSearch}
sx={{ width: 500 }}
multiple
id='tags-standard'
options={allTagList.slice().sort((a, b) => a.tag_category.localeCompare(b.tag_category))}
groupBy={(option) => option.tag_category}
getOptionLabel={(option) => option.tag_name}
renderInput={(params) => (
<TextField
{...params}
variant='standard'
label='Search by hash tag'
placeholder='Hash tag'
/>
)}
/>
</Stack>
<Stack>
<ImageList sx={{ height: 800 }} cols={4}>
{/* Loop all the images */}
{tableStatus !== 'LOADING' &&
allImageList.map((item, index) => (
<ImageListItem
key={index}
ref={index + 1 === allImageList.length ? lastImageRef : null}
>
<img
src={`data:image/jpeg;base64,${item.img}`}
alt={item.image_name}
loading='lazy'
/>
<ImageListItemBar
title={item.image_name}
subtitle={item.tag}
actionIcon={
<>
{/* edit icon */}
<IconButton
onClick={() => {
return openDetailDialog(item);
}}
sx={{ color: 'rgba(255, 255, 255, 0.54)' }}
aria-label={`update ${item.image_name}`}
>
<BorderColorIcon />
</IconButton>
{/* download icon */}
<IconButton
onClick={() => {
return downloadImage(item);
}}
sx={{ color: 'rgba(255, 255, 255, 0.54)' }}
aria-label={`update ${item.image_name}`}
>
<ArchiveIcon />
</IconButton>
</>
}
/>
</ImageListItem>
))}
{tableStatus === 'LOADING' && (
<Stack
alignItems='center'
justifyContent='center'
sx={{ width: '100%', paddingTop: '2rem', paddingBottom: '2rem' }}
>
<CircularProgress />
</Stack>
)}
</ImageList>
</Stack>
{/* <Stack direction='row' justifyContent='space-between'>
<Pagination
count={Math.ceil(pageCount.current / 10)}
page={pageNumber}
onChange={onPaginate}
/>
</Stack> */}
{/* image add & update dialog component */}
<ImageDialog
detail={detail}
isDetailDialogOpen={isDetailDialogOpen}
onDetailDialogClose={onDetailDialogClose}
/>
{/* image delete confirmation dialog */}
<Dialog
open={isDeleteDialogOpen}
onClose={onDeleteDialogClose}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
>
<DialogTitle id='alert-dialog-title'>{'Confirm Deletion of Image'}</DialogTitle>
<DialogContent>
<DialogContentText id='alert-dialog-description'>
Deletion of image cannot be redo. Click "Confirm" to proceed.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={onDeleteDialogClose}>Close</Button>
<LoadingButton
loading={buttonStatus === 'LOADING'}
onClick={(e) => onSaveDelete(e, imageObject)}
>
{buttonStatus === 'SUCCESS' ? 'Success!' : 'Confirm'}
</LoadingButton>
</DialogActions>
</Dialog>
</div>
);
} |
import * as models from './models';
import { Ability } from './models';
import { spells } from './spells';
import { getRandomNumber } from './dice';
import { askSpell } from './input';
async function main() {
let isClear: boolean = false;
let enemyKobold = new models.Kobold();
let bardClass: models.CharacterClass = {
name: 'Bard',
hitDie: 8
};
let badassBard = new models.Caster(
{
0: 3,
1: 2
},
spells,
'Six',
'Half-Elf',
36,
bardClass,
new Map<models.Ability, number>([
[Ability.STR, 0],
[Ability.DEX, 1],
[Ability.CON, 1],
[Ability.INT, 2],
[Ability.WIS, 1],
[Ability.CHA, 4]
])
);
while (!isClear) {
let room: models.Room = new models.Room();
let exitState: string = 'no exit';
let isLastRoom: boolean = true;
if (room.exit) {
isLastRoom = false;
let article: string = 'a';
if (room.exit.name === 'iron door') {
article = 'an';
}
exitState = article + ' ' + room.exit.name;
}
console.log(`You enter a room with ${exitState}.`);
models.wait();
while (room.enemy.isAlive) {
console.log(`${models.capitalizeFirstLetter(room.enemy.name)} has ${room.enemy.hitPoints} hit points.`);
models.wait();
badassBard.logSpells();
let spellIndex: number = await askSpell(badassBard.spellList.length - 1);
let spell: models.Spell = badassBard.spellList[spellIndex];
badassBard.castSpell(spell, room.enemy);
}
if (room.exit) {
while (room.exit.isLocked) {
console.log(`${models.capitalizeFirstLetter(room.exit.name)} is locked.`);
badassBard.logSpells();
let spellIndex: number = await askSpell(badassBard.spellList.length - 1);
let spell: models.Spell = badassBard.spellList[spellIndex];
badassBard.castSpell(spell, room.exit);
}
}
if (isLastRoom) {
isClear = true;
}
}
console.log('Congratulations, ' + badassBard.name + "! You've cleared the dungeon!");
}
main(); |
<template>
<div id="app">
<variform ref="variform" :form-element-data="form" :validators="validators" :converters="converters" :slot-names="['custom']">
<!-- custom element with name custom -->
<template v-slot:custom="slotProps">
<custom-element :form-element-data="slotProps.formElementData" />
</template>
</variform>
<div class="container">
<div class="row">
<button @click="generate">capture data</button>
<div>{{outData}}</div>
</div>
<div class="row">
<button @click="reset">reset</button>
</div>
<div class="row">
<button @click="populate">populate form</button>
</div>
</div>
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import _ from 'lodash';
import Variform from './variform/Variform.vue';
import formTemplate from './form';
import validators from './validators';
import converters from './converters';
import CustomElement from './CustomElement.vue';
@Component({
components: {
CustomElement,
Variform,
},
})
export default class App extends Vue {
form = _.cloneDeep(formTemplate)
validators = validators
converters = converters
outData = {}
async generate() {
this.outData = await (this.$refs.variform as Variform).generateData(this.form);
}
async populate() {
await (this.$refs.variform as Variform).populateForm(this.form, this.outData);
}
reset() {
this.form = _.cloneDeep(formTemplate);
}
}
</script> |
<!DOCTYPE html>
<html lang="en" class="h-100">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load static %}
<link rel="stylesheet" href="{% static 'style.css' %}">
<title>View Book</title>
</head>
<body class="h-100 w-75 mx-auto text-center p-2">
<header class="d-flex justify-content-between">
<h1>Wellcome {{ user.first_name }} {{ user.last_name }} *_*</h1>
<div> <a class="btn btn-warning" href="/LogOut/">logOut</a> </div>
</header>
<main>
<div>
<h2>{{ the_book.title }}</h2>
<h4>Added By: {{ the_book.created_by.first_name }} {{ the_book.created_by.last_name }}</h4>
<h5>Added_on: {{ the_book.created_at }}</h5>
<h5>Last_updated: {{ the_book.updated_at }}</h5>
{% if the_book in user.created_books.all %}
<form class="form w-50 mx-auto p-3" action="/update_desc/" method="post">
{% csrf_token %}
<input class="form-control" type="hidden" name="book_id" value="{{ the_book.id }}">
<textarea class="form-control" name="desc" id="desc" cols="20" rows="4" required>{{ the_book.desc }}</textarea>
<button class="btn btn-info" type="submit"> update </button>
</form>
<a class="btn btn-danger" href="/delete_book/{{ the_book.id }}/">Delete Book</a>
{% endif %}
{% if the_book not in user.created_books.all %}
<h6>Description: {{ the_book.desc }}</h6>
{% endif %}
</div>
<div>
<h2>Users who likes this book:</h2>
<ul>
{% for x in the_book.liked_by.all %}
<li>{{ x.first_name }} {{ x.last_name }}</li>
{% endfor %}
</ul>
{% if the_book in user.liked_books.all %}
<a class="btn btn-primary" href="/unlike_book/{{ the_book.id }}/"> remove from favorites </a>
{% endif %}
{% if the_book not in user.liked_books.all %}
<a class="btn btn-primary" href="/like_book/{{ the_book.id }}/"> Add to your favorites </a>
{% endif %}
</div>
</main>
</body>
</html> |
package problema1.application;
import problema1.application.entites.Triangle;
import java.util.Locale;
import java.util.Scanner;
public class program {
public static void main(String[] args) {
//Fazer um programa para ler as medidas dos lados de dois triangulos X e Y (suponha medidas válidas) em seguida,
//mostrar o valor das areas dos doid triangulos e dizer qual dos dois triangulos possui a maior area.
//formula: area = raiz quadrada de p(p-a) * (p-b) * (p-c) onde p = a+b+c sobre 2;
Locale.setDefault(Locale.US);
Scanner sc = new Scanner(System.in);
/*double xA, xB, xC, yA, yB, yC;*/
Triangle x, y;
x = new Triangle();
y = new Triangle();
System.out.println("Enter the measures of triangle X: ");
x.a = sc.nextDouble();
x.b = sc.nextDouble();
x.c = sc.nextDouble();
System.out.println("Enter the measures of triangle Y: ");
y.a = sc.nextDouble();
y.b = sc.nextDouble();
y.c = sc.nextDouble();
/*double p = (x.a + x.b + x.c) / 2;
double areaX = Math.sqrt(p * ( p - x.a) * (p - x.b) * (p - x.c));*/
double areaX = x.area();
/*p = (y.a + y.b + y.c) / 2;
double areaY = Math.sqrt(p * ( p - y.a) * (p - y.b) * (p - y.c));*/
double areaY = y.area();
System.out.printf("Triangle X area: %.4f%n", areaX);
System.out.printf("Triangle Y area: %.4f%n", areaY);
if (areaX > areaY) {
System.out.println("Larger area: X");
} else {
System.out.println("Larger area: Y");
}
sc.close();
}
} |
import type { ComputedRef, Ref } from 'vue'
import type { IGroup } from '../views/user-types'
import { computed } from 'vue'
/**
* Format a group to a menu entry
*
* @param group the group
*/
function formatGroupMenu(group?: IGroup) {
if (typeof group === 'undefined') {
return null
}
const item = {
id: group.id,
title: group.name,
usercount: group.usercount,
count: Math.max(0, group.usercount - group.disabled),
}
return item
}
export const useFormatGroups = (groups: Ref<IGroup[]>|ComputedRef<IGroup[]>) => {
/**
* All non-disabled non-admin groups
*/
const userGroups = computed(() => {
const formatted = groups.value
// filter out disabled and admin
.filter(group => group.id !== 'disabled' && group.id !== 'admin')
// format group
.map(group => formatGroupMenu(group))
// remove invalid
.filter(group => group !== null)
return formatted as NonNullable<ReturnType<typeof formatGroupMenu>>[]
})
/**
* The admin group if found otherwise null
*/
const adminGroup = computed(() => formatGroupMenu(groups.value.find(group => group.id === 'admin')))
/**
* The group of disabled users
*/
const disabledGroup = computed(() => formatGroupMenu(groups.value.find(group => group.id === 'disabled')))
return { adminGroup, disabledGroup, userGroups }
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.