text stringlengths 184 4.48M |
|---|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CartStore Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="container-fluid px-4">
<div class="row g-4">
<div class="col-sm-12 col-xl-6">
<div class="bg-light text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Cart Store Chart</h6>
</div>
<canvas id="cartStoreChart" width="400" height="400"></canvas>
</div>
</div>
</div>
</div>
<script>
function getRandomColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const color = `rgba(${r}, ${g}, ${b}, 0.2)`;
return color;
}
async function fetchAllData() {
const response = await fetch('/api/cart/most-added-store');
const mostAddedStore = await response.json();
createCartStoreChart(mostAddedStore);
}
function createCartStoreChart(mostAddedStore) {
var ctx = document.getElementById('cartStoreChart').getContext('2d');
var labels = [];
var data = [];
var backgroundColors = [];
for (var i = 0; i < mostAddedStore.length; i++) {
labels.push(mostAddedStore[i][0]);
data.push(mostAddedStore[i][1]);
backgroundColors.push(getRandomColor());
}
var cartStoreChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
label: '장바구니에 가장 많이 담긴 지역',
data: data,
backgroundColor: backgroundColors,
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
},
options: {
scales: {
y: { beginAtZero: true }
}
}
});
}
fetchAllData();
</script>
</body>
</html> |
// importo las variables declaradas en el env
require('dotenv').config();
// Importo express que es el entorno que me permite usar node js
const express= require('express');
// indico la conexión a la base de datos en la carpeta db
const {dbConnection} = require('./src/db/config');
const cors = require('cors');
// llamo a la funcion express que me permite crear un servidor
const app = express();
// hago la conexión a la base de datos
dbConnection();
// interpreta la request que esta llegando en formato json
app.use(cors());
app.use(express.urlencoded({extended: true}));
app.use(express.json());
// cuando entre a la web de mi servidor me mandara una respuesta que es welcome server
// request cliente y response del servidor
app.get('/', (req, res) => {
res.status(200).send('You are connected to the project');
});
// se define una uri y un router para cada modelo en la carpeta models
app.use("/api/usuarios", require("./src/routes/usuarios.routes"));
app.use("/api/contactos", require("./src/routes/contactos.routes"));
// Le digo a la aplicacion escuchame este puerto
app.listen(process.env.PORT, () => {
console.log('Server running on port :' ,process.env.PORT);
});
module.exports = app;
// los proyectos se corren poniendo node y el name del archivo ej: node server o en el package.json puedo definir strats en un scripts. |
import Circle from "./Circle";
import { Bounds, Container } from "../../../packages/react-matters/index";
import Engine from "./Engine";
import Text from "./Text";
const circles = new Array(30).fill(null).map((_, idx) => {
return {
id: idx,
x: Math.random(),
y: Math.random(),
};
});
function App() {
return (
<div className="w-full">
<Container
className="w-full h-screen relative bg-gray-900 overflow-hidden"
style={{
width: "100vw",
height: "100vh",
position: "relative",
overflow: "hidden",
}}
initEngineOptions={{
gravity: {
x: 0,
y: 1,
},
}}
>
<Text />
{circles.map((circle) => (
<Circle key={circle.id} position={{ x: circle.x, y: circle.y }} />
))}
<Bounds />
<Engine />
</Container>
</div>
);
}
export default App; |
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorController;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
/**
* Created by RuiyingGao on 11/16/16.
*/
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorController;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
/**
* Created by citruseel on 10/26/2016.
*/
@Autonomous(name="Basic Linear Autonomous", group="Autonomous")
public class RedTeamAuto extends LinearOpMode {
/* Note:
* When you extend OpMode, you must declare the methods init() and loop()
*/
/**
* Declaring electronics
* This can be done with a separate class and can make creating code much easier / simpler.
*/
private DcMotorController motorControllerP1; // Motor Controller in port 1 of Core
private DcMotorController motorControllerP2; // Motor Controller in port 0 of Core
private DcMotor motor1; // Motor 1: port 1 in Motor Controller 1
private DcMotor motor2; // Motor 2: port 2 in Motor Controller 1
private DcMotor motor3; // Motor 3: port 1 in Motor Controller 2
private DcMotor motor4; // Motor 4: port 2 in Motor Controller 2
/* Declaring variables */
public void runOpMode() throws InterruptedException {
/** Initializing and mapping electronics (motors, motor controllers, servos, etc.) */
motorControllerP1 = hardwareMap.dcMotorController.get("MCP1");
motorControllerP2 = hardwareMap.dcMotorController.get("MCP2");
motor1 = hardwareMap.dcMotor.get("motorFrontR");
motor2 = hardwareMap.dcMotor.get("motorFrontL");
motor3 = hardwareMap.dcMotor.get("motorBack1");
motor4 = hardwareMap.dcMotor.get("motorBack2");
/**Setting channel modes
* When setting channel modes, use the names that are declared to the motors. */
motor1.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
motor2.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
motor3.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
motor4.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
motor1.setDirection(DcMotorSimple.Direction.REVERSE);
motor4.setDirection(DcMotorSimple.Direction.REVERSE);
waitForStart();
MoveForward(1, 2628/*milliseconds*/);
MoveLeft(1, 0617);
MoveForward(1,2250);
}
public void MoveForward(double power, long time) throws InterruptedException {
motor1.setPower(power); //left side motor foward
motor2.setPower(power); //right Side motor foward
motor3.setPower(power); //left side motor foward
motor4.setPower(power); //right Side motor foward
}
public void MoveLeft(double power, long time) throws InterruptedException {
motor1.setPower(-power); //left side motor reverse
motor3.setPower(-power); //left side motor reverse
motor2.setPower(power); //right Side motor foward
motor4.setPower(power); //right Side motor foward
}
public void MoveRight (double power, long time) throws InterruptedException {
motor2.setPower(-power); //right Side motor reverse
motor4.setPower(-power); //right Side motor reverse
motor1.setPower(power); //left side motor foward
motor3.setPower(power); //left side motor foward
}
public void MoveBack (double power, long time) throws InterruptedException {
motor1.setPower(-power); //left side motor reverse
motor2.setPower(-power); //right Side motor reverse
motor3.setPower(-power); //left side motor reverse
motor4.setPower(-power); //right Side motor reverse
}
} |
import sys
from typing import List
import pandas as pd
from PySide6.QtWidgets import QTableView, QApplication
from PySide6.QtCore import QAbstractTableModel, Qt, QModelIndex
class PandasModel(QAbstractTableModel):
"""A model to interface a Qt view with pandas dataframe """
def __init__(self, dataframe: pd.DataFrame, parent=None):
QAbstractTableModel.__init__(self, parent)
self._dataframe = dataframe
self.editable_cols = []
def rowCount(self, parent=QModelIndex()) -> int:
""" Override method from QAbstractTableModel
Return row count of the pandas DataFrame
"""
if parent == QModelIndex():
return len(self._dataframe)
return 0
def columnCount(self, parent=QModelIndex()) -> int:
"""Override method from QAbstractTableModel
Return column count of the pandas DataFrame
"""
if parent == QModelIndex():
return len(self._dataframe.columns)
return 0
def data(self, index: QModelIndex, role=Qt.DisplayRole) -> object:
"""Override method from QAbstractTableModel
Return data cell from the pandas DataFrame
"""
if not index.isValid():
return None
if role == Qt.DisplayRole:
return str(self._dataframe.iloc[index.row(), index.column()])
return None
def headerData(self, section: int, orientation: Qt.Orientation,
role=Qt.ItemDataRole) -> str or None:
"""Override method from QAbstractTableModel
Return dataframe index as vertical header data and columns as horizontal header data.
"""
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return str(self._dataframe.columns[section])
if orientation == Qt.Vertical:
return str(self._dataframe.index[section])
return None
def setData(self,
index: QModelIndex,
value: str,
role=Qt.EditRole):
if index.isValid() and role == Qt.EditRole:
self._dataframe.iloc[index.row(), index.column()] = value
self.dataChanged.emit(index, index)
return True
return False
def flags(self, index: QModelIndex):
if index.column() in self.editable_cols:
return Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable
else:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
def set_editable_cols(self, cols: List):
self.editable_cols = cols
if __name__ == "__main__":
app = QApplication(sys.argv)
df = pd.read_csv("files/numbers.csv")
view = QTableView()
view.resize(800, 500)
view.horizontalHeader().setStretchLastSection(True)
view.setAlternatingRowColors(True)
view.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
model = PandasModel(df)
model.set_editable_cols([2])
view.setModel(model)
view.show()
app.exec() |
/*
The Evolving Distribution Objects framework (EDO) is a template-based,
ANSI-C++ evolutionary computation library which helps you to write your
own estimation of distribution algorithms.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Copyright (C) 2010 Thales group
*/
/*
Authors:
Johann Dréo <johann.dreo@thalesgroup.com>
Caner Candan <caner.candan@thalesgroup.com>
*/
#ifndef _edoEstimatorNormalMulti_h
#define _edoEstimatorNormalMulti_h
#include "edoEstimator.h"
#include "edoNormalMulti.h"
#ifdef WITH_BOOST
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/lu.hpp>
namespace ublas = boost::numeric::ublas;
#else
#ifdef WITH_EIGEN
#include <Eigen/Dense>
#endif // WITH_EIGEN
#endif // WITH_BOOST
/** An estimator for edoNormalMulti
*
* Exists in two implementations, using either
* <a href="http://www.boost.org/doc/libs/1_50_0/libs/numeric/ublas/doc/index.htm">Boost::uBLAS</a> (if compiled WITH_BOOST)
* or <a href="http://eigen.tuxfamily.org">Eigen3</a> (WITH_EIGEN).
*
* @ingroup Estimators
* @ingroup EMNA
* @ingroup Multinormal
*/
template < typename EOT, typename D=edoNormalMulti<EOT> >
class edoEstimatorNormalMulti : public edoEstimator<D>
{
#ifdef WITH_BOOST
public:
class CovMatrix
{
public:
typedef typename EOT::AtomType AtomType;
CovMatrix( const eoPop< EOT >& pop )
{
//-------------------------------------------------------------
// Some checks before starting to estimate covar
//-------------------------------------------------------------
unsigned int p_size = pop.size(); // population size
assert(p_size > 0);
unsigned int s_size = pop[0].size(); // solution size
assert(s_size > 0);
//-------------------------------------------------------------
//-------------------------------------------------------------
// Copy the population to an ublas matrix
//-------------------------------------------------------------
ublas::matrix< AtomType > sample( p_size, s_size );
for (unsigned int i = 0; i < p_size; ++i)
{
for (unsigned int j = 0; j < s_size; ++j)
{
sample(i, j) = pop[i][j];
}
}
//-------------------------------------------------------------
_varcovar.resize(s_size);
//-------------------------------------------------------------
// variance-covariance matrix are symmetric (and semi-definite
// positive), thus a triangular storage is sufficient
//
// variance-covariance matrix computation : transpose(A) * A
//-------------------------------------------------------------
ublas::symmetric_matrix< AtomType, ublas::lower > var = ublas::prod( ublas::trans( sample ), sample );
// Be sure that the symmetric matrix got the good size
assert(var.size1() == s_size);
assert(var.size2() == s_size);
assert(var.size1() == _varcovar.size1());
assert(var.size2() == _varcovar.size2());
//-------------------------------------------------------------
// TODO: to remove the comment below
// for (unsigned int i = 0; i < s_size; ++i)
// {
// // triangular LOWER matrix, thus j is not going further than i
// for (unsigned int j = 0; j <= i; ++j)
// {
// // we want a reducted covariance matrix
// _varcovar(i, j) = var(i, j) / p_size;
// }
// }
_varcovar = var / p_size;
_mean.resize(s_size); // FIXME: check if it is really used because of the assignation below
// unit vector
ublas::scalar_vector< AtomType > u( p_size, 1 );
// sum over columns
_mean = ublas::prod( ublas::trans( sample ), u );
// division by n
_mean /= p_size;
}
const ublas::symmetric_matrix< AtomType, ublas::lower >& get_varcovar() const {return _varcovar;}
const ublas::vector< AtomType >& get_mean() const {return _mean;}
private:
ublas::symmetric_matrix< AtomType, ublas::lower > _varcovar;
ublas::vector< AtomType > _mean;
};
public:
typedef typename EOT::AtomType AtomType;
edoNormalMulti< EOT > operator()(eoPop<EOT>& pop)
{
unsigned int popsize = pop.size();
assert(popsize > 0);
unsigned int dimsize = pop[0].size();
assert(dimsize > 0);
CovMatrix cov( pop );
return edoNormalMulti< EOT >( cov.get_mean(), cov.get_varcovar() );
}
};
#else
#ifdef WITH_EIGEN
public:
class CovMatrix
{
public:
typedef typename EOT::AtomType AtomType;
typedef typename D::Vector Vector;
typedef typename D::Matrix Matrix;
CovMatrix( const eoPop< EOT >& pop )
{
// Some checks before starting to estimate covar
unsigned int p_size = pop.size(); // population size
assert(p_size > 0);
unsigned int s_size = pop[0].size(); // solution size
assert(s_size > 0);
// Copy the population to an ublas matrix
Matrix sample( p_size, s_size );
for (unsigned int i = 0; i < p_size; ++i) {
for (unsigned int j = 0; j < s_size; ++j) {
sample(i, j) = pop[i][j];
}
}
// variance-covariance matrix are symmetric, thus a triangular storage is sufficient
// variance-covariance matrix computation : transpose(A) * A
Matrix var = sample.transpose() * sample;
// Be sure that the symmetric matrix got the good size
assert(var.innerSize() == s_size);
assert(var.outerSize() == s_size);
_varcovar = var / p_size;
// unit vector
Vector u( p_size);
u = Vector::Constant(p_size, 1);
// sum over columns
_mean = sample.transpose() * u;
// division by n
_mean /= p_size;
}
const Matrix& get_varcovar() const {return _varcovar;}
const Vector& get_mean() const {return _mean;}
private:
Matrix _varcovar;
Vector _mean;
};
public:
typedef typename EOT::AtomType AtomType;
edoNormalMulti< EOT > operator()(eoPop<EOT>& pop)
{
unsigned int p_size = pop.size();
assert(p_size > 0);
unsigned int s_size = pop[0].size();
assert(s_size > 0);
CovMatrix cov( pop );
assert( cov.get_mean().innerSize() == s_size );
assert( cov.get_mean().outerSize() == 1 );
assert( cov.get_varcovar().innerSize() == s_size );
assert( cov.get_varcovar().outerSize() == s_size );
return edoNormalMulti< EOT >( cov.get_mean(), cov.get_varcovar() );
}
#endif // WITH_EIGEN
#endif // WITH_BOOST
}; // class edoNormalMulti
#endif // !_edoEstimatorNormalMulti_h |
package services
import (
"context"
models "project/model"
"strings"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
type UserServiceImpl struct {
collection *mongo.Collection
ctx context.Context
}
func NewUserServiceImpl(cl *mongo.Collection, ct context.Context) UserServiceImpl {
return UserServiceImpl{cl, ct}
}
func (u *UserServiceImpl) GetUserByMail(email string) (*models.User, error) {
var res *models.User
query := bson.M{"email": strings.ToLower(email)}
err := u.collection.FindOne(u.ctx, query).Decode(&res)
if err != nil {
if err == mongo.ErrNoDocuments {
return &models.User{}, err
}
return nil, err
}
return res, nil
}
func (u *UserServiceImpl) GetUserById(Id string) (*models.User, error) {
oid, _ := primitive.ObjectIDFromHex(Id)
var user *models.User
query := bson.M{"_id": oid}
err := u.collection.FindOne(u.ctx, query).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
return &models.User{}, err
}
return nil, err
}
return user, nil
} |
Sintassi dei comandi UNIX
Uno dei comandi piu' importanti (collocato in /bin) e' il
comando "ls" (list), ed e' l'equivalente del comando DOS "dir".
Argomenti di un comando
-------------------------
La sintassi del comando ls, ma anche quella di tutti gli altri
comandi, segue una regola ben precisa:
# nome_comando argomenti ...
Gli "argomenti" sono delle stringhe che si appongono, separate
da spazi, dopo il nome del comando stesso.
Essi possono essere "obbligatori" o "facoltativi".
Per indicare che un argomento e' facoltativo, in genere, nella
documentazione del comando, lo troviamo racchiuso tra
parentesi quadre [...].
Oltre a questa suddivisione, ve ne e' un altra: un argomento
puo' essere di tipo "opzione" (switch) o di tipo "dato".
Quelli di tipo "opzione" vengono prima di quelli di tipo "dato", ed
iniziano sempre con in "-", qualche volta con "--"
Esempi:
--------------
# ls -l /bin
Qui abbiamo richiesto la lista (ls) della directory /bin, specificando
che vogliamo il formato lungo (-l, long).
# ls -F /bin /usr/bin
Qui vogliamo la lista di due directory, specificando il formato
su piu' colonne (-F).
# ls --sort=time /bin
Qui vogliamo che la lista sia ordina in base alla data di creazione.
# ls -R /
Qui abbiamo richiesto la lista della directory radice (/), specificando
che vogliamo una lista ricorsiva (-R), cioe' di tutte le sottodirectory.
In pratica, in questo caso, avremo la lista di TUTTI i files
presenti nel sistema
# ls -l
Qui abbiamo omesso il nome della directory. In questo caso, il
comando assume che vogliamo listare la "directory corrente", cioe'
quella dove ci troviamo quando abbiamo battuto il comando.
# ls -a
Mostra tutti (-a, all) i files, anche quelli nascosti.
Combinare switch
-----------------
# ls -laR
In questo caso chiediamo la lista completa, ricorsiva, di tutti i files,
dalla directory corrente a scendere giu'.
Paradigma di un comando
-----------------------
Come in latino, anche i comandi UNIX hanno quello che possiamo
chiamare "paradigma"; in sostanza, una breve illustrazione di
come usare il comando (in inglese: sinopsis)
Per il comando "ls" il paradigma e' del tipo:
# ls [-laFR ...] [directory o files]
Con questa scrittura si vuol significare che sia gli switch che
i dati sono facoltativi, e che alcuni degli switch piu'
usati sono: -l, -a etc
Nota finale
-----------
Il comando "ls" ha circa 200-300 switch diverse!
Io ho illustrato solo le piu' usate. |
//
// StrapiRequestTests.swift
//
//
// Created by Alex Loren on 6/10/23.
//
import XCTest
@testable import StrapiSwiftCross
final class StrapiRequestTests: XCTestCase {
// MARK: - Functions
/// Tests creating a request with no filters
func testRequestWithNoFilters() {
let request = StrapiRequest(method: .get, contentType: "test")
XCTAssertEqual(request.method, .get)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
XCTAssertEqual(request.filters!.count, 0)
}
/// Tests creating a request with a single filter
func testRequestWithAFilter() {
let request = StrapiRequest(method: .get, contentType: "test")
XCTAssertEqual(request.method, .get)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
request.addFilter(type: .equalTo, onField: "test", forValue: "testing")
XCTAssertEqual(request.filters!.count, 1)
XCTAssertEqual(request.filters![0].type, FilterType.equalTo.rawValue)
XCTAssertEqual(request.filters![0].field, "test")
XCTAssertEqual(request.filters![0].value, "testing")
}
/// Tests creating a request with multiple filters
func testRequestWithMultipleFilters() {
let request = StrapiRequest(method: .get, contentType: "test")
XCTAssertEqual(request.method, .get)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
request.addFilter(type: .equalTo, onField: "test", forValue: "testing")
XCTAssertEqual(request.filters!.count, 1)
XCTAssertEqual(request.filters![0].type, FilterType.equalTo.rawValue)
XCTAssertEqual(request.filters![0].field, "test")
XCTAssertEqual(request.filters![0].value, "testing")
request.addFilter(type: .notIncludedIn, onField: "array", forValue: "others")
XCTAssertEqual(request.filters!.count, 2)
XCTAssertEqual(request.filters![1].type, FilterType.notIncludedIn.rawValue)
XCTAssertEqual(request.filters![1].field, "array")
XCTAssertEqual(request.filters![1].value, "others")
request.addFilter(type: .greaterThan, onField: "number", forValue: "4")
XCTAssertEqual(request.filters!.count, 3)
XCTAssertEqual(request.filters![2].type, FilterType.greaterThan.rawValue)
XCTAssertEqual(request.filters![2].field, "number")
XCTAssertEqual(request.filters![2].value, "4")
}
/// Tests creating a request that cannot support having a filter applied.
func testRequestIncapableOfFilter() {
let request = StrapiRequest(method: .post, contentType: "test")
XCTAssertEqual(request.method, .post)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
request.addFilter(type: .equalTo, onField: "test", forValue: "testing")
XCTAssertEqual(request.canSendFilters, false)
XCTAssertEqual(request.filters!.count, 0)
}
/// Tests creating a request that cannot support having a body.
func testRequestIncapableOfBody() {
let request = StrapiRequest(method: .get, contentType: "test")
XCTAssertEqual(request.method, .get)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
let body = """
{ "data": "A random string."}
"""
request.setBody(to: body)
XCTAssertEqual(request.canSendBody, false)
XCTAssertNil(request.body)
}
/// Tests creating a PUT request with a body.
func testRequestWithPutBody() {
let request = StrapiRequest(method: .put, contentType: "test")
XCTAssertEqual(request.method, .put)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
let body = """
{ "data": "A random string."}
"""
request.setBody(to: body)
XCTAssertEqual(request.body, body)
}
/// Tests creating a POST request with a body.
func testRequestWithPostBody() {
let request = StrapiRequest(method: .post, contentType: "test")
XCTAssertEqual(request.method, .post)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
let body = """
{ "data": "A random string."}
"""
request.setBody(to: body)
XCTAssertEqual(request.body, body)
}
/// Tests adding filters to a request then clearing them.
func testClearingFiltersFromRequest() {
let request = StrapiRequest(method: .get, contentType: "test")
XCTAssertEqual(request.method, .get)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
request.addFilter(type: .equalTo, onField: "test", forValue: "testing")
request.addFilter(type: .notIncludedIn, onField: "array", forValue: "others")
request.addFilter(type: .greaterThan, onField: "number", forValue: "4")
XCTAssertEqual(request.filters!.count, 3)
request.removeAllFilters()
XCTAssertEqual(request.filters!.count, 0)
}
/// Tests creating a request with relations populated.
func testRequestWithPopulation() {
let request = StrapiRequest(method: .get, contentType: "test")
XCTAssertEqual(request.method, .get)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
request.populate(relation: "*")
XCTAssertEqual(request.filters![0].type, "populate")
XCTAssertEqual(request.filters![0].field, "*")
}
/// Tests creating a request that sorts a field.
func testRequestWithSorting() {
let request = StrapiRequest(method: .get, contentType: "test")
XCTAssertEqual(request.method, .get)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
request.sort(field: "id", byDirection: .ascending)
XCTAssertEqual(request.filters![0].type, "sort")
XCTAssertEqual(request.filters![0].field, "id")
XCTAssertEqual(request.filters![0].value, SortDirection.ascending.rawValue)
}
/// Tests creating a request that randomly sorts results.
func testRequestWithRandomSorting() {
let request = StrapiRequest(method: .get, contentType: "test")
XCTAssertEqual(request.method, .get)
XCTAssertEqual(request.contentType, "test")
XCTAssertEqual(request.path, "")
request.randomize()
XCTAssertEqual(request.filters![0].type, "randomSort")
XCTAssertEqual(request.filters![0].value, "true")
}
} |
// final nombreYApellido = "Richar Cangui"; -> Variable global
void main() {
/// Argumentos posicionales
/// Como maximo para 2 variables - argumentos
saludo('Richar');
customPrint(saludo);
/// Llama a la funcion con multiples argumentos
variosArgumentos("Richar", 12, true);
/// Llamada al argumento nulo
argumentoNulo(null);
/// Opcional
opcionales("Rihcar");
}
void saludo(String nombre) {
print("Hola $nombre");
}
void customPrint(Object object) {
/// Function -> String o double -> Funcion
// if (object is Function) {
// object.call();
// return;
// }
print("Esto es un log: ${object.toString()}");
}
/// Varios argumentos de posicion
/// Separados de una coma
void variosArgumentos(String nombre, double edad, bool esSoltero) {
print("El nombre es: $nombre");
print("La edad es: $edad");
print("Es soltero: $esSoltero");
}
/// No usar esto
// void noTipoDeDato(nombre) {
// }
/// Como puedo pasarle un nulo
void argumentoNulo(String? nombre) {
print(nombre);
}
/// Argumentos opcionales
void opcionales(String? nombre, [double? edad]) {
print("El nombre es: $nombre y su edad es $edad");
} |
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link https://phpdoc.org
*/
namespace phpDocumentor\Guides\EventListener;
use phpDocumentor\Guides\Event\PostProjectNodeCreated;
use phpDocumentor\Guides\Settings\ComposerSettingsLoader;
use function dirname;
use function file_exists;
use function getcwd;
use function is_string;
final class LoadSettingsFromComposer
{
public function __construct(private readonly ComposerSettingsLoader $composerSettingsLoader)
{
}
public function __invoke(PostProjectNodeCreated $event): void
{
$workDir = getcwd();
if ($workDir === false) {
return;
}
$composerjson = $this->findComposerJson($workDir);
if (!is_string($composerjson)) {
return;
}
$projectNode = $event->getProjectNode();
$settings = $event->getSettings();
$this->composerSettingsLoader->loadSettings($projectNode, $settings, $composerjson);
}
private function findComposerJson(string $currentDir): string|null
{
// Navigate up the directory structure until finding the composer.json file
while (!file_exists($currentDir . '/composer.json') && $currentDir !== '/') {
$currentDir = dirname($currentDir);
}
// If found, return the path to the composer.json file; otherwise, return null
return file_exists($currentDir . '/composer.json') ? $currentDir . '/composer.json' : null;
}
} |
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigtw from 'aws-cdk-lib/aws-apigateway';
import * as cdk from 'aws-cdk-lib'
// import * as sqs from 'aws-cdk-lib/aws-sqs';
export class AwsApigwRestapiLambdaintegrationStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const fun = new lambda.Function(this, 'restapilambda', {
code: lambda.Code.fromInline('exports.handler = async (event){ const response = { statusCode = 200, body = JSON.stringify("Hello from lambda")}; return response;}'),
handler: 'index.handler',
runtime: lambda.Runtime.NODEJS_16_X
});
const api = new apigtw.RestApi(this, 'myrestapi');
const lambdaIntegrtion = new apigtw.LambdaIntegration(fun);
const v1 = api.root.addResource('v1');
v1.addMethod('GET', lambdaIntegrtion);
new cdk.CfnOutput(this, 'gatewayurl', {
value: api.url
})
}
} |
package com.tencent.devops.artifactory.store.service.impl
import com.tencent.devops.artifactory.constant.BKREPO_DEFAULT_USER
import com.tencent.devops.artifactory.constant.BK_CI_ATOM_DIR
import com.tencent.devops.artifactory.constant.BK_CI_PLUGIN_FE_DIR
import com.tencent.devops.artifactory.constant.REPO_NAME_STATIC
import com.tencent.devops.artifactory.util.DefaultPathUtils
import com.tencent.devops.common.api.constant.STATIC
import com.tencent.devops.common.api.exception.RemoteServiceException
import java.io.File
import java.io.InputStream
import javax.servlet.http.HttpServletResponse
import javax.ws.rs.NotFoundException
import org.glassfish.jersey.media.multipart.FormDataContentDisposition
import org.slf4j.LoggerFactory
abstract class ArchiveAtomToBkRepoServiceImpl : ArchiveAtomServiceImpl() {
override fun getAtomArchiveBasePath(): String {
return System.getProperty("java.io.tmpdir")
}
override fun handleArchiveFile(
disposition: FormDataContentDisposition,
inputStream: InputStream,
projectCode: String,
atomCode: String,
version: String
) {
unzipFile(
disposition = disposition,
inputStream = inputStream,
projectCode = projectCode,
atomCode = atomCode,
version = version
)
val atomArchivePath = buildAtomArchivePath(projectCode, atomCode, version)
val frontendDir = buildAtomFrontendPath(atomCode, version)
logger.info("atom plugin: $atomArchivePath, $frontendDir")
directoryIteration(
directoryFile = File(atomArchivePath),
prefix = "${getAtomArchiveBasePath()}/$BK_CI_ATOM_DIR",
directoryPath = atomArchivePath,
repoName = getBkRepoName()
)
directoryIteration(
directoryFile = File(frontendDir),
prefix = "${getAtomArchiveBasePath()}/$STATIC/$BK_CI_PLUGIN_FE_DIR",
directoryPath = frontendDir,
repoName = REPO_NAME_STATIC
)
}
private fun directoryIteration(directoryFile: File, prefix: String, directoryPath: String, repoName: String) {
directoryFile.walk().filter { it.path != directoryPath }.forEach {
if (it.isDirectory) {
directoryIteration(
directoryFile = it,
prefix = prefix,
directoryPath = it.path,
repoName = repoName
)
} else {
val path = it.path.removePrefix(prefix)
logger.debug("uploadLocalFile fileName=${it.name}|path=$path")
bkRepoClient.uploadLocalFile(
userId = BKREPO_DEFAULT_USER,
projectId = getBkRepoProjectId(),
repoName = repoName,
path = path,
file = it
)
}
}
}
override fun getAtomFileContent(filePath: String): String {
val tmpFile = DefaultPathUtils.randomFile()
return try {
bkRepoClient.downloadFile(
userId = BKREPO_DEFAULT_USER,
projectId = getBkRepoProjectId(),
repoName = getBkRepoName(),
fullPath = filePath,
destFile = tmpFile
)
tmpFile.readText(Charsets.UTF_8)
} catch (ignored: NotFoundException) {
logger.warn("file[$filePath] not exists")
""
} catch (ignored: RemoteServiceException) {
logger.warn("download file[$filePath] error: $ignored")
""
} finally {
tmpFile.delete()
}
}
override fun downloadAtomFile(filePath: String, response: HttpServletResponse) {
try {
bkRepoClient.downloadFile(
userId = BKREPO_DEFAULT_USER,
projectId = getBkRepoProjectId(),
repoName = getBkRepoName(),
fullPath = filePath,
outputStream = response.outputStream
)
} catch (ignored: NotFoundException) {
logger.warn("file[$filePath] not exists")
} catch (ignored: RemoteServiceException) {
logger.warn("download file[$filePath] error: $ignored")
}
}
override fun clearServerTmpFile(projectCode: String, atomCode: String, version: String) {
val atomArchivePath = buildAtomArchivePath(projectCode, atomCode, version)
val frontendDir = buildAtomFrontendPath(atomCode, version)
File(atomArchivePath).deleteRecursively()
File(frontendDir).deleteRecursively()
}
abstract fun getBkRepoProjectId(): String
abstract fun getBkRepoName(): String
companion object {
private val logger = LoggerFactory.getLogger(ArchiveAtomToBkRepoServiceImpl::class.java)
}
} |
class Bird:
pass
class Duck(Bird): # <1>
def quack(self):
print('Quack!')
def alert(birdie): # <2>
birdie.quack()
def alert_duck(birdie: Duck) -> None: # <3>
birdie.quack()
def alert_bird(birdie: Bird) -> None: # <4>
birdie.quack() |
import React, { useState } from 'react';
import Header from '../header';
interface FormProps {
onSubmit: () => void;
onBack: () => void;
onChange: () => void;
selectionSummary: any;
}
const Summary: React.FC<FormProps> = ({ onSubmit, onBack, selectionSummary, onChange }) => {
const handleBack = () => {
onBack();
}
const handleChange = () => {
onChange()
}
const handleSubmit = () => {
onSubmit();
};
const title = selectionSummary.selectedPlan;
const planAmount = selectionSummary.amount;
const billingType = selectionSummary.billingType;
const numericPlanAmount = parseFloat(planAmount.match(/\d+/)); // Extract numeric part
const addons = selectionSummary.selectedAddons;
let addonAmount = [];
addonAmount = addons.map((addon: any) => (
billingType === 'Monthly' ? addon.amountMonthly : addon.amountYearly
))
const totalAddonCost = addonAmount.reduce((total: any, amount: any) => {
const numericAmount = parseFloat(amount.match(/\d+/)); // Extract numeric part
return total + numericAmount;
}, 0);
const totalAmount = numericPlanAmount + totalAddonCost;
return (
<div className='app__info-form'>
<form className='form'>
<Header headerText="Finishing up" subtitleText="Double check everything looks Ok before confirming." />
<div className='summary-container'>
<div className='summary-title-container'>
<div>
<p>{title} ({billingType})</p>
<a className="subtitle-Text" style={{ textDecoration: 'underline' }} href="#" onClick={() => handleChange()}>Change</a>
</div>
<span>
{planAmount}
</span>
</div>
<div className='divider' />
<div>
{
addons.map((addon: any) => (
<div className='summary-title-container' key={addon.index}>
<div>
<p className="subtitle-Text">{addon.title}</p>
</div>
<span className='subtitle-Text'>
{
billingType === 'Monthly' ? addon.amountMonthly : addon.amountYearly
}
</span>
</div>
))
}
</div>
</div>
<div className='summary-total-container'>
<p className='subtitle-Text'>Total {billingType === 'Monthly' ? '(per Month)' : '(per Year)'}</p>
<span className='summary-amountText'>+${totalAmount}/{billingType === 'Monthly' ? 'mo' : 'yr'}</span>
</div>
</form>
<div className='app__form-buttons'>
<span onClick={() => handleBack()}>Go Back</span>
<button type='submit' onClick={() => handleSubmit()}>Confirm</button>
</div>
</div>
)
}
export default Summary; |
import React, {Component, Fragment} from 'react';
import PropTypes from 'prop-types';
import {Field} from 'react-final-form';
import {RichUtils} from 'draft-js';
import Editor from 'draft-js-plugins-editor';
import createInlineToolbarPlugin from 'draft-js-inline-toolbar-plugin';
import IconButton from '@material-ui/core/IconButton';
import {shouldDisplayError} from '../../../../services/control-errors';
import * as TEXT_STYLE from './constants/text-styles';
import {TOOLBAR_ICONS} from './constants/draft-js-toolbar';
import 'draft-js/dist/Draft.css';
import styles from './draft-js.module.css';
const inlineToolbarPlugin = createInlineToolbarPlugin();
const { InlineToolbar } = inlineToolbarPlugin;
export class DraftJs extends Component {
setEditor = editor => {
this.editor = editor;
};
focusEditor = () => {
if (this.editor) {
this.editor.focus();
}
};
onChange = editorState => {
const {name, setValue} = this.props;
setValue(name, editorState);
};
onStyleBtnClick = (e, value) => {
const style = e.currentTarget.name;
this.onChange(RichUtils.toggleInlineStyle(value, style));
};
handleKeyCommand = (command, editorState) => {
const newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
this.onChange(newState);
return 'handled';
}
return 'not-handled';
};
renderToolbar = ({value}) => {
const textStyles = [
TEXT_STYLE.BOLD,
TEXT_STYLE.ITALIC,
TEXT_STYLE.LINK
];
return (
<Fragment>
{
textStyles.map(style => (
<IconButton
key={style} name={style}
onClick={e => this.onStyleBtnClick(e, value)}
onMouseDown={e => e.preventDefault()}
>
{TOOLBAR_ICONS[style]}
</IconButton>
))
}
</Fragment>
);
};
renderEditor = ({input, meta}) => {
const {renderError} = this.props;
const errorClass = shouldDisplayError(meta) ? styles.error : '';
return (
<Fragment>
{renderError(meta)}
<div
className={`${styles.editor} ${errorClass}`}
onClick={this.focusEditor}
>
<Editor
{...input}
ref={this.setEditor}
editorState={input.value}
onChange={this.onChange}
handleKeyCommand={this.handleKeyCommand}
plugins={[inlineToolbarPlugin]}
/>
<InlineToolbar>
{() => this.renderToolbar(input)}
</InlineToolbar>
</div>
</Fragment>
);
};
render() {
const {name, validate, validateFields, isEqual} = this.props;
return (
<Field
name={name}
render={this.renderEditor}
validate={validate}
validateFields={validateFields}
isEqual={isEqual}
/>
);
}
}
DraftJs.propTypes = {
name: PropTypes.string.isRequired,
setValue: PropTypes.func.isRequired,
renderError: PropTypes.func.isRequired,
validate: PropTypes.func.isRequired,
validateFields: PropTypes.array.isRequired,
isEqual: PropTypes.func.isRequired
}; |
import React, { useState } from 'react';
import { toast } from "react-toastify";
import http from '../../services/httpservice';
import FormInput from '../form-input/input.component';
import FormButton from '../form-button/form-button.component';
import { apiUrl } from '../../config.json';
import './create-blog.styles.scss';
import auth from '../../services/authService';
const CreateBlog = ({ flag, handleClick }) => {
const classname = flag ? 'show' : 'hide';
const [blogContent, setBlogContent] = useState({ title: '', blog: '' })
const { title, blog } = blogContent;
const handleChange = e => {
const { value, name } = e.target;
setBlogContent({
...blogContent,
[name]: value
})
}
const handleSubmit = async e => {
e.preventDefault();
handleClick();
try {
const { name, email } = await auth.getCurrentUser();
const res = await http.post(apiUrl + 'blog', { blogContent, name, email });
console.log(res);
if (res.status === 200) toast.info('Blog added');
if (res.status && res.status !== 200) toast.error('Something went wrong')
} catch (err) {
return err ? toast.error('Something went wrong') : null;
}
setBlogContent({
...blogContent,
title: '',
blog: ''
});
}
return (
<div className={`create-blog-container ${classname}`}>
<div className="close-create-blog" onClick={handleClick}>X</div>
<div className="create-blog" >
<div className="title">Create a blog</div>
<div className="blog-area">
<form onSubmit={handleSubmit}>
<textarea name="blog" value={blog} onChange={handleChange} placeholder="It's time to blog..." required></textarea>
<FormInput className="blog-input" type="text" name="title" handleChange={handleChange} value={title} placeholder="Title..." required />
<FormButton className="blog-button" type="submit" name="submit">BLOG</FormButton>
</form>
</div>
</div>
</div>
);
}
export default CreateBlog; |
import axios from "axios";
import Notiflix from "notiflix";
import SimpleLightbox from "simplelightbox";
import "simplelightbox/dist/simple-lightbox.min.css";
// пошук по елементам
const refs = {
form: document.querySelector('.search-form'),
input: document.querySelector('.form__input'),
gallery: document.querySelector('.gallery'),
btnLoadMore: document.querySelector('.load-more')
};
let page = 1;
refs.btnLoadMore.style.display = 'none';
refs.form.addEventListener('submit', onSearch);
refs.btnLoadMore.addEventListener('click', onBtnLoadMore);
//екземпляр модального вікна слайдера-зображень
let simpleGallery = new SimpleLightbox('.gallery a');
function onSearch(e) {
e.preventDefault();
page = 1;
refs.gallery.innerHTML = '';
const name = refs.input.value.trim();
if (name !== '') {
pixabay(name)
} else {
// refs.btnLoadMore.style.display = 'none';
Notiflix.Notify.failure("The search field can't be empty. Please, enter your request.");
}
}
//робота з кнопкою LOAD MORE
function onBtnLoadMore() {
const name = refs.input.value.trim();
page =+ 1,
pixabay(name, page);
}
// робота з бек-ендом
async function pixabay(name, page) {
const API_URL = 'https://pixabay.com/api/';
const options = {
params: {
key: '33939880-6980ae7d7dcf6a315ba694d35',
q: name,
image_type: 'photo',
orientation: 'horizontal',
safeserch: 'true',
page: page,
per_page: 40,
},
};
try {
const response = await axios.get(API_URL, options)
if (response.data.totalHits > 40) {
refs.btnLoadMore.style.display = 'flex';
};
//Повідомлення про знайдені дані
if (response.data.totalHits === 0) {
Notiflix.Notify.failure('Sorry, there are no images matching your search query. Please try again.')
};
if (response.data.totalHits > 0) {
Notiflix.Notify.success(`Hoorray! We found ${response.data.totalHits}`)
};
//виклик функції для рендеру даних на сторінку
createMarkup(response.data);
} catch (error) {
console.log(error);
}
}
//функція для рендерингу розмітки в галерею
function createMarkup(array) {
const markup = array.hits.map(item =>
`<a class='photo-link' href='${item.largeImageURL}'>
<div class="photo-card">
<div class="photo">
<img src="${item.webformatURL}" alt="${item.tags}" loading="lazy" />
</div>
<div class="info">
<p class="info-item">
<b>Likes ${item.likes}</b>
</p>
<p class="info-item">
<b>Views ${item.views}</b>
</p>
<p class="info-item">
<b>Comments ${item.comments}</b>
</p>
<p class="info-item">
<b>Downloads ${item.downloads}</b>
</p>
</div>
</div>
</a>`
)
.join('');
refs.gallery.insertAdjacentHTML('beforeend', markup);
simpleGallery.refresh();
} |
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"time"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
var (
Version = "N/A"
BuildTime = "N/A"
)
//https://blog.csdn.net/tianlongtc/article/details/80038235
//go run main.go -timeout 1000ms . fmt
//为了测试 sync.ErrGroup 的所有特性, 我已经写了一个递归搜索指定目录的Go程序。并且我还加了一个超时的机制 。当程序超时了,所有的 goroutines 将被取消,程序退出。
func main() {
//第一步:命令行传进来的参数做了解析
duration := flag.Duration("timeout", 500*time.Millisecond, "timeout in milliseconds")
//一般用来提醒的,我们可以覆盖掉包中默认的,改成我们自定义的
flag.Usage = func() {
fmt.Printf("%s by Brian Ketelsen\n", os.Args[0])
fmt.Printf("Version %s, Built: %s \n", Version, BuildTime)
fmt.Println("Usage:")
fmt.Printf(" gogrep [flags] path pattern \n")
fmt.Println("Flags:")
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() != 2 {
flag.Usage()
os.Exit(-1)
}
path := flag.Arg(0)
pattern := flag.Arg(1)
//设置超时时间
ctx, cf := context.WithTimeout(context.Background(), *duration)
defer cf()
m, err := search(ctx, path, pattern)
if err != nil {
log.Fatal(err)
}
for _, name := range m {
fmt.Println(name)
}
fmt.Println(len(m), "hits")
}
func search(ctx context.Context, root string, pattern string) ([]string, error) {
g, ctx := errgroup.WithContext(ctx)
paths := make(chan string, 100)
// get all the paths
g.Go(func() error {
defer close(paths)
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return nil
}
if !info.IsDir() && !strings.HasSuffix(info.Name(), ".go") {
return nil
}
select {
case paths <- path:
case <-ctx.Done():
return ctx.Err()
}
return nil
})
})
c := make(chan string, 100)
for path := range paths {
p := path
g.Go(func() error {
data, err := ioutil.ReadFile(p)
if err != nil {
return err
}
if !bytes.Contains(data, []byte(pattern)) {
return nil
}
select {
case c <- p:
case <-ctx.Done():
return ctx.Err()
}
return nil
})
}
go func() {
g.Wait()
close(c)
}()
var m []string
for r := range c {
m = append(m, r)
}
return m, g.Wait()
} |
BayEsian LocaLisation Algorithm - BELLA
.. image:: http://img.shields.io/badge/powered%20by-SunPy-orange.svg?style=flat
:target: http://www.sunpy.org
:alt: Powered by SunPy Badge
.. image:: https://img.shields.io/badge/powered%20by-PyMC-blue
:target: http://www.pymc.io
:alt: Powered by PyMC Badge
.. image:: https://img.shields.io/badge/powered%20by-SolarMAP-orange
:target: https://pypi.org/project/solarmap/
:alt: Powered by SolarMAP Badge
BELLA uses Bayesian statistics to Localise sources of EM emission within one astronomical unit of the Sun.
Features:
- Type III Fitter: Fits a Type III radio burst and returns scatter data and/or fitted data, prepared for BELLA multilateration. Uses Kapteyn to fit the lightcurve of a Type III solar radio burst using Gaussian-Hermite polynomials.
typeIIIfitter: file with functions to fit a Type III lightcurve and fit the Type III morphology.
stacked_dyn_spectra: example file of data extraction of an event.
- BELLA Multilaterate: Uses pymc3 to perform Bayesian multilateration.
bayes_positioner: Bayesian Multilateration class and multilateration function.
bayesian_tracker: Functions for performing BELLA multilateration.
bella_plotter: Functions for plotting BELLA multilateration results.
bella_triangulation: Example of BELLA multilateration event.
positioner_mapping_parallel: Generates simulated data of the uncertainty map given a spacecraft configuration.
density_models: support file with density models and plasma physics functions.
Contributions and comments are welcome using Github at:
https://github.com/TCDSolar/BELLA_Multilateration/
Please note that BELLA requires:
- PyMC3
- SunPy
- Astropy
- Solarmap
- Kapteyn
- Pyspedas
- Radiospectra
Installation
You must run Fitter and Multilaterate in **different** virtual environments. This is due to package incompatibilities.
It is also recommended to make aliases in order to quickly change between environments.
Some packages such as Kapteyn or pyspedas, may give an error when installing in python different than python 3.8.
You must install virtual environments with python 3.8.
Install BELLA Type III Fitter
----
1 - Make a virtual env:
.. code-block:: bash
python3.8 -m venv ./bellaenv_fitter
source ./bellaenv_fitter/bin/activate
2 - Install HDF5:
.. code-block:: bash
brew install hdf5
See https://github.com/HDFGroup/hdf5 for other OS.
3 - Install the following packages:
.. code-block:: bash
pip install -r requirements_fitter.txt
4 - Install Kapteyn:
Kapteyn is a package developed and managed by the University of Groningen. It is recommended to install Kapteyn using
their local instructions. Note: "pip install kapteyn" gives error:
https://www.astro.rug.nl/software/kapteyn/intro.html#installinstructions
.. code-block:: bash
pip install https://www.astro.rug.nl/software/kapteyn/kapteyn-3.4.tar.gz
Note: If installation of Kapteyn gives a Numpy error make sure Numpy was deprecated to numpy==1.22
5 - Install radiospectra via pip. Note the current version of radiospectra gives error when running BELLA,
for now install this stable version:
.. code-block:: bash
pip install git+https://github.com/samaloney/radiospectra.git@6c1faa39d9eba52baec7f7bdc75966e5d8da3b81
6 - Install pyspedas via pip. Install this specific version.
.. code-block:: bash
pip install git+https://github.com/STBadman/pyspedas
7 - (Optional) Add alias to .bashrc // .bash_profile
.. code-block:: bash
echo 'alias fitter="source $(pwd)/bellaenv_fitter/bin/activate"' > $(HOME)/.bashrc
or
.. code-block:: bash
echo 'alias fitter="source $(pwd)/bellaenv_fitter/bin/activate"' > $(HOME)/.bash_profile
Install BELLA Multilaterate
----
1 - Make a virtual env:
.. code-block:: bash
python3.8 -m venv ./bellaenv_multilat
source ./bellaenv_multilat/bin/activate
2 - Install packages via pip:
.. code-block:: bash
pip install -r requirements_multilat.txt
3 - (Optional) Add alias to .bashrc // .bash_profile
.. code-block:: bash
echo 'alias multilat="source $(pwd)/bellaenv_multilat/bin/activate"' > $(HOME)/.bashrc
or
.. code-block:: bash
echo 'alias multilat="source $(pwd)/bellaenv_multilat/bin/activate"' > $(HOME)/.bash_profile
Usage
=====
1 - In **fitter** environment open **Type_III_Fitter/stacked_dyn_spectra_....py**
- Select date and time range. The code has been tested to run with leadingedge. (Running backbone might need the code to be updated.)
.. code-block:: python
YYYY = 2012
MM = 6
dd = 7
HH_0 = 19
mm_0 = 20
HH_1 = 20
mm_1 = 00
#
background_subtraction = True
leadingedge = True
backbone = False
plot_residuals = False
- Follow the code and comments to adapt the code to your needs. You might consider changing:
- Histogram levels - > Make Type III visible or improve contrast.
- Automatic detection settings - > Change initial inputs for automatic detection.
- Fine tuning of detected points. - > Fix outliers that make unphysical morphologies.
- Run stacked_dyn_spectra_YYYY_MM_dd.py
.. code-block:: bash
cd PATH/TO/Type_III_Fitter
python stacked_dyn_spectra_YYYY_MM_dd.py
- Once the stacked file has run. There should be two files generated in PATH/TO/Type_III_Fitter/Data/TypeIII/YYYY_MM_dd. These files are the extracted data, ready for multilateration.
- The output of stacked should show all the dynamic spectra with solid black line as the fit and dashed lines representing the cadence chosen for the multilateration:
.. image:: ./Figures_readme/stackedoutput.png
:align: center
- A directory showing all the lightcurve fits and automatic detections should have been generated in PATH/TO/Type_III_Fitter/lightcurves:
.. image:: ./Figures_readme/STEREOA_sigma_0.98.jpg
:align: center
2 - In **multilat** environment open **Multilaterate/positioner_mapping_parallel.py** to generate background uncertainty map.
- Select the date. If "surround", "test" or "manual" are selected in date string you may manually input any location for any amount of spacecraft. Note: surround is a particular orbital configuration, see https://www.dias.ie/surround/ for more information.
.. code-block:: python
day = 7
month = 6
year = 2012
date_str = f"{year}_{month:02d}_{day:02d}"
# date_str = f"surround"
if date_str == "surround":
# SURROUND
#############################################################################
theta_sc = int(sys.argv[1])
print(f"theta_sc: {theta_sc}")
L1 = [0.99*(au/R_sun),0]
L4 = [(au/R_sun)*np.cos(radians(60)),(au/R_sun)*np.sin(radians(60))]
L5 = [(au/R_sun)*np.cos(radians(60)),-(au/R_sun)*np.sin(radians(60))]
# ahead = [(au/R_sun)*np.cos(radians(theta_sc)),(au/R_sun)*np.sin(radians(theta_sc))]
# behind = [(au/R_sun)*np.cos(radians(theta_sc)),-(au/R_sun)*np.sin(radians(theta_sc))]
dh = 0.01
# theta_AB_deg = 90
theta_AB = np.radians(theta_sc)
ahead = pol2cart((1-dh)*(au / R_sun), theta_AB)
behind = pol2cart((1+dh)*(au / R_sun),-theta_AB)
stations_rsun = np.array([L1, ahead, behind])
#############################################################################
elif date_str == "test":
stations_rsun = np.array([[200, 200], [-200, -200], [-200, 200], [200, -200]])
elif date_str == "manual":
stations_rsun = np.array([[45.27337378, 9.90422281],[-24.42715218,-206.46280171],[ 212.88183411,0.]])
date_str = f"{year}_{month:02d}_{day:02d}"
else:
solarsystem = solarmap.get_sc_coord(date=[year, month, day], objects=["stereo_b", "stereo_a", "earth"])
stations_rsun = np.array(solarsystem.locate_simple())
- Select the spacecraft. Note for this particular date we use "earth" instead of "wind". The reason is Wind ephemeris is not available prior to A.D. 2019-OCT-08 00:01:09.1823 TD on Horizons. So 99% of Sun-Earth distance is assumed.
.. code-block:: python
solarsystem = solarmap.get_sc_coord(date=[year, month, day], objects=["stereo_b", "stereo_a", "earth"])
stations_rsun = np.array(solarsystem.locate_simple())
Redefine earth as Wind.
.. code-block:: python
spacecraft = ["stereo_b", "stereo_a", "wind"] # redefining wind as the name of the spacecraft
stations_rsun[2][0] = 0.99 * stations_rsun[2][0]
- Make the grid. **CAREFULLY** make your grid in Rsun units. The finer the grid (smaller xres) the longer it will take to run. An estimate of how long the code will take to run will be shown. You may improve this estimate by changing the time per loop "tpl_l" and "tpl_h" based on your machine performance.
.. code-block:: python
# Making grid
xrange = [-250,250]
xres = 10
yrange = [-250, 250]
yres = xres
xmapaxis = np.arange(xrange[0], xrange[1], xres)
ymapaxis = np.arange(yrange[0], yrange[1], yres)
- Select the cadence. A smaller cadence will lead to lower uncertainty results but will also lead to divergencies. Here we pick the conservative 60s cadence.
.. code-block:: python
cadence = 60
- Run **positioner_mapping_parallel.py**. Depending on your grid size, resolution and machine specs this step may take a few hours.
.. code-block:: bash
cd PATH/TO/Multilaterate
python positioner_mapping_parallel.py
- A file with the uncertainty bg results should be available in **PATH/TO/Multilaterate/Data/YYYY_MM_dd/bg/**
- If the showfigure=True then your ouput should look like:
.. image:: ./Figures_readme/bayes_positioner_map_median_-250_250_-250_250_10_10_3.jpg
:align: center
3 - In multilat environment open **Multilaterate/bella_triangulation_YYYY_MM_dd.py**
- Follow the code and adjust settings according to your needs.
- Run **bella_triangulation_YYYY_MM_dd.py**. This step may take from minutes to hours depending on your frequency range and resolution.
.. code-block:: bash
cd PATH/TO/Multilaterate
python bella_triangulation_YYYY_MM_dd.py
- A file with the multilateration results should be available in **PATH/TO/Multilaterate/Data/YYYY_MM_dd/**
- All the traceplots from the multilateration should be available at **PATH/TO/Multilaterate/Traceplots/**
.. image:: ./Figures_readme/traceplot_output.jpg
:align: center
4 - In multilat environment open **Multilaterate/bella_plotter.py**
- Follow the code and adjust settings accordingly. Make sure that the data filenames are correct.
- Run bella_plotter.py
.. code-block:: bash
cd PATH/TO/Multilaterate
python bella_plotter.py
.. image:: ./Figures_readme/bellaplotteroutput.png
:align: center
Documentation
BELLA uses a class in **bayes_positioner.py** called **BayesianTOAPositioner** adapted from benmoseley (https://github.com/benmoseley).
This class sets up a context manager for pymc3. This is where you can define your prior distributions.
Note v can be a Normal Distribution or Truncated Normal depending on whether you want to test if v is converging at c or whether you want to make c a limit.
.. code-block:: python
with pm.Model(): # CONTEXT MANAGER
# Priors
# v = pm.TruncatedNormal("v", mu=v_mu, sigma=v_sd, upper=v_mu+v_sd)
v = pm.Normal("v", mu=v_mu, sigma=v_sd)
# x = pm.Uniform("x", lower=-x_lim, upper=x_lim, shape=2) # prior on the source location (m)
x = pm.Normal("x", mu=0, sigma=x_lim/4, shape=2) # prior on the source location (m)
t0 = pm.Uniform("t0", lower=-t_lim, upper=t_lim) #
# Physics model
d = pm.math.sqrt(pm.math.sum((stations - x)**2, axis=1)) # distance between source and receivers
t1 = d/v # time of arrival of each receiver
t = t1-t0 # TOA dt
# Observations
print(f"\nt: {t} \n t_sd: {t_sd} \n toa: {toa}")
Y_obs = pm.Normal('Y_obs', mu=t, sd=t_sd, observed=toa) # DATA LIKELIHOOD function
# Posterior sampling
#step = pm.HamiltonianMC()
trace = pm.sample(draws=draws, tune=tune, chains=chains, cores=cores, target_accept=0.95, init=init, progressbar=progressbar,return_inferencedata=False)#, step=step)# i.e. tune for 1000 samples, then draw 5000 samples
summary = az.summary(trace)
The function "triangulate()" (soon to be multilaterate) found in bayes_positioner.py allows for one pymc3 multilateration loop, generates traceplots and also a quickview plot of the results. Some important information:
- cores=4 is the maximum pymc3 will allow. run cores=0 if triangulate is already running in a parallel process.
- chains=4. Generally recommended to use 4 chains.
- t_cadence=60. It is recommended to use a cadence that is equal or slightly worse than the instruments cadence. Otherwise divergences may occur.
- N_SAMPLES=2000. The number of samples and tunning values are 2000 because a larger number becomes computationally expensive. Tuning values and Samples are chosen to be equal but this is not necessary. Change if you need to.
bella_triangulation_YYYY_MM_dd.py or bayesian_tracker.py run triangulate() in a for loop in parallel. Make sure cores=0 in triangulate() if running triangulate() in a for loop in parallel.
Bugs and Warnings
WARNING: always import pymc3 before importing theano. If theano is imported first you might have to restart your shell.
WARNING: theano's cache might fill up. This usually happens when running several processes in parallel. To fix this run
this in your bash shell:
.. code-block:: bash
theano-cache purge
WARNING: Running BELLA scripts often requires parallelisation. By default BELLA will maximise the number of cores to be used. As a result of this, running several BELLA scripts simultaneously will cause problems.
Disclaimer: BELLA multilateration is relatively computationally expensive and there is room for speeding up the processes. Development of a faster computation is ongoing and contributions to making BELLA faster are welcome.
Please use Github to report bugs, feature requests and submit your code:
https://github.com/TCDSolar/BELLA_Multilateration/
:author: Luis Alberto Canizares
:date: 2022/11/22 |
import mongoose from 'mongoose';
import { Clientes } from './db';
import { rejects } from 'assert';
export const resolvers = {
Query: {
getClientes: (root, {limite}) => {
return Clientes.find({}).limit(limite);
},
getCliente: ({id}) => {
return new Cliente(id, clientesDB[id]);
}
},
Mutation: {
crearCliente: (root, {input}) => {
const nuevoCliente = new Clientes({
nombre: input.nombre,
apellido: input.apellido,
empresa: input.empresa,
emails: input.emails,
edad: input.edad,
tipo: input.tipo,
pedidos: input.pedidos
});
nuevoCliente.id = nuevoCliente._id;
return new Promise((resolve, object) => {
nuevoCliente.save((error) => {
if(error) rejects(error)
else resolve(nuevoCliente)
});
});
},
actualizarCliente: (root, {input}) => {
return new Promise((resolve, object) => {
Clientes.findOneAndUpdate({_id: input.id }, input, {new: true}, (error, cliente) => {
if(error) rejects(error);
else resolve(cliente);
});
});
},
eliminarCliente: (root, {id}) => {
return new Promise((resolve, object) => {
Clientes.findOneAndRemove({_id: id}, (error) => {
if(error) rejects(error);
else resolve("Se elimino correctamente");
});
});
}
}
} |
import React, { createContext, useContext, useEffect, useState } from "react";
import OvalLoader from "../components/OvalLoader.jsx";
const keyStorage = "userBlog";
export const UserContext = createContext(undefined);
export function UserProvider({ children, initialValue }) {
const [user, setUser] = useState(undefined);
const [authChecked, setAuthChecked] = useState(false);
function persistUser(dataUser) {
localStorage.setItem(keyStorage, JSON.stringify(dataUser));
setUser(dataUser);
}
function signOut() {
localStorage.removeItem(keyStorage);
setUser(undefined);
}
useEffect(() => {
if (initialValue) {
setUser(initialValue);
setAuthChecked(true);
return;
}
const userFromStorageString = localStorage.getItem(keyStorage);
if (!userFromStorageString) {
setAuthChecked(true);
return;
}
const userFromStorageJson = JSON.parse(userFromStorageString);
if (
parseInt(userFromStorageJson.token.expiresAccessToken) - Date.now() >
1000 * 60
) {
setUser(userFromStorageJson);
}
setAuthChecked(true);
}, []);
if (!authChecked) {
return (
<div className={"flex h-screen w-screen items-center justify-center"}>
<OvalLoader size={40} />
</div>
);
}
return (
<UserContext.Provider
value={{ user: user, persistUser: persistUser, signOut: signOut }}
>
{children}
</UserContext.Provider>
);
}
export const useUserContext = () => useContext(UserContext); |
package com.android.amm.weatherapp.di
import android.content.Context
import androidx.room.Room
import com.android.amm.weatherapp.data.db.AppDatabase
import com.android.amm.weatherapp.data.db.WeatherDao
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Provides
@Singleton
fun provideAppDatabase(@ApplicationContext appContext: Context): AppDatabase {
return Room.databaseBuilder(
appContext,
AppDatabase::class.java,
"weatherApp.db"
)
.createFromAsset("database/weather.db")
.build()
}
@Provides
fun provideWeatherDao(appDatabase: AppDatabase): WeatherDao {
return appDatabase.weatherDao()
}
} |
package com.pengode.server.role;
import com.pengode.server.common.jpa.TimestampAware;
import com.pengode.server.common.jpa.TimestampListener;
import com.pengode.server.privilige.Privilege;
import com.pengode.server.user.User;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@Entity
@Table(name = "role")
@EntityListeners({TimestampListener.class})
public class Role implements TimestampAware {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(
name = "id",
nullable = false
)
private Long id;
@Column(
name = "name",
nullable = false,
unique = true,
length = 32
)
private String name;
@Column(
name = "updated_at",
nullable = false
)
private LocalDateTime updatedAt = LocalDateTime.now();
@Column(
name = "created_at",
nullable = false
)
private LocalDateTime createdAt = LocalDateTime.now();
@ManyToMany(mappedBy = "roles")
private List<User> users = Collections.emptyList();
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "role_privilege",
joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "privilege_id")
)
private List<Privilege> privileges = Collections.emptyList();
} |
import { Button, LoadingOverlay, Stack, TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { useCallback, useState } from "react";
import { CommandHelper } from "../../utils/CommandHelper";
import ConsoleWrapper from "../ConsoleWrapper/ConsoleWrapper";
import { UserGuide } from "../UserGuide/UserGuide";
import { LoadingOverlayAndCancelButton } from "../OverlayAndCancelButton/OverlayAndCancelButton";
import { SaveOutputToTextFile_v2 } from "../SaveOutputToFile/SaveOutputToTextFile";
const title = "Parsero";
const description =
"Parsero is a free script written in Python which reads the Robots.txt file of a web server and looks at the Disallow entries." +
"The Disallow entries tell the search engines what directories or files hosted on a web server mustn’t be indexed. " +
"\n\nParsero Reference Guide: https://www.kali.org/tools/parsero/ \n\n" +
"How to use Parsero:\n\n" +
"Step 1: Enter an URL.\n" +
" E.g. www.google.com\n\n" +
"Step 2: Click Start Parsero" +
"\n\n Step 3 : View Results";
interface FormValues {
url: string;
}
const Parsero = () => {
const [loading, setLoading] = useState(false);
const [output, setOutput] = useState("");
const [pid, setPid] = useState("");
const [allowSave, setAllowSave] = useState(false);
const [hasSaved, setHasSaved] = useState(false);
let form = useForm({
initialValues: {
url: "",
},
});
// Uses the callback function of runCommandGetPidAndOutput to handle and save data
// generated by the executing process into the output state variable.
const handleProcessData = useCallback((data: string) => {
setOutput((prevOutput) => prevOutput + "\n" + data); // Update output
}, []);
// Uses the onTermination callback function of runCommandGetPidAndOutput to handle
// the termination of that process, resetting state variables, handling the output data,
// and informing the user.
const handleProcessTermination = useCallback(
({ code, signal }: { code: number; signal: number }) => {
if (code === 0) {
handleProcessData("\nProcess completed successfully.");
} else if (signal === 15) {
handleProcessData("\nProcess was manually terminated.");
} else {
handleProcessData(`\nProcess terminated with exit code: ${code} and signal code: ${signal}`);
}
// Clear the child process pid reference
setPid("");
// Cancel the Loading Overlay
setLoading(false);
},
[handleProcessData]
);
// Actions taken after saving the output
const handleSaveComplete = () => {
// Indicating that the file has saved which is passed
// back into SaveOutputToTextFile to inform the user
setHasSaved(true);
setAllowSave(false);
};
const onSubmit = async (values: FormValues) => {
// Disallow saving until the tool's execution is complete
setAllowSave(false);
// Enable the Loading Overlay
setLoading(true);
const args = [`-u`, values.url];
// Execute parsero
CommandHelper.runCommandGetPidAndOutput("parsero", args, handleProcessData, handleProcessTermination)
.then(({ pid, output }) => {
setPid(pid);
setOutput(output);
})
.catch((error) => {
setLoading(false);
setOutput(`Error: ${error.message}`);
});
};
const clearOutput = useCallback(() => {
setOutput("");
setHasSaved(false);
setAllowSave(false);
}, [setOutput]);
return (
<form onSubmit={form.onSubmit(onSubmit)}>
{LoadingOverlayAndCancelButton(loading, pid)}
<Stack>
{UserGuide(title, description)}
<TextInput label={"url"} required {...form.getInputProps("url")} />
<Button type={"submit"}>Start parsero</Button>
{SaveOutputToTextFile_v2(output, allowSave, hasSaved, handleSaveComplete)}
<ConsoleWrapper output={output} clearOutputCallback={clearOutput} />
</Stack>
</form>
);
};
export default Parsero; |
// Motor 1
#define IN1 4
#define IN2 5
#define enA 6
#define M1_ENCA 2
#define M1_ENCB 10
// Motor 2
#define IN3 7
#define IN4 8
#define enB 9
#define M2_ENCA 3
#define M2_ENCB 11
#define FORWARD 1
#define STOP 0
#define BACKWARD -1
unsigned long currentMillis;
unsigned long prevMillis;
const unsigned long PERIOD = 50;
long M1_encoder_val = 0;
long M2_encoder_val = 0;
long countsLeft = 0;
long countsRight = 0;
long prevLeft = 0;
long prevRight = 0;
const int COUNTS_PER_ROTATION = 14;
const float GEAR_RATIO = 100.0F;
const float WHEEL_DIAMETER = 6.8;
const float WHEEL_CIRCUMFERENCE = 21.36;
float Sl = 0.0F;
float Sr = 0.0F;
// right - M2 - B
// left - M1 - A
void setup() {
Serial.begin(115200);
pinMode(M1_ENCA,INPUT);
pinMode(M1_ENCB,INPUT);
attachInterrupt(digitalPinToInterrupt(M1_ENCA), readEncoderM1, RISING);
pinMode(M2_ENCA,INPUT);
pinMode(M2_ENCB,INPUT);
attachInterrupt(digitalPinToInterrupt(M2_ENCA), readEncoderM2, RISING);
Serial.println("target pos");
}
void loop() {
/*
// set target position
int target = 12000;
// PID constants
float kp = 1;
float kd = 0.025;
float ki = 0.0;
// time difference
long currT = micros();
float deltaT = ((float) (currT - prevT))/( 1.0e6 );
prevT = currT;
// error
int e = pos-target;
// derivative
float dedt = (e-eprev)/(deltaT);
// integral
eintegral = eintegral + e*deltaT;
// control signal
float u = kp*e + kd*dedt + ki*eintegral;
// motor power
float pwr = fabs(u);
if( pwr > 255 ){
pwr = 255;
}
// motor direction
int dir = 1;
if(u<0){
dir = -1;
}
// signal the motor
setMotor(dir, pwr, PWM, IN1, IN2);
// store previous error
eprev = e;
Serial.print(target);
Serial.print(" ");
Serial.print(pos);
Serial.println();
*/
checkEncoders();
}
void checkEncoders() {
currentMillis = millis();
if (currentMillis > prevMillis + PERIOD) {
countsLeft += M1_encoder_val;
M1_encoder_val = 0;
countsRight += M2_encoder_val;
M2_encoder_val = 0;
Sl += ((countsLeft - prevLeft) / (COUNTS_PER_ROTATION * GEAR_RATIO) * WHEEL_CIRCUMFERENCE);
Sr += ((countsRight - prevRight) / (COUNTS_PER_ROTATION * GEAR_RATIO) * WHEEL_CIRCUMFERENCE);
int wheelSpeed = 200;
if (Sr < 30) {
setMotor(FORWARD, wheelSpeed, enA, IN1, IN2);
setMotor(FORWARD, wheelSpeed, enB, IN3, IN4);
}
else {
setMotor(STOP, 0, enA, IN1, IN2);
setMotor(STOP, 0, enB, IN3, IN4);
}
Serial.print("Left: ");
Serial.println(Sl);
Serial.print("Right: ");
Serial.println(Sr);
prevLeft = countsLeft;
prevRight = countsRight;
prevMillis = currentMillis;
}
}
void setMotor(int dir, int pwmVal, int pwm_pin, int in1, int in2){
analogWrite(pwm_pin, pwmVal);
if(dir == -1){
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
}
else if(dir == 1){
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
}
else{
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
}
void readEncoderM1(){
int b = digitalRead(M1_ENCB);
if(b > 0){
M1_encoder_val++;
}
else{
M1_encoder_val--;
}
}
void readEncoderM2(){
int b = digitalRead(M2_ENCB);
if(b > 0){
M2_encoder_val++;
}
else{
M2_encoder_val--;
}
} |
import { useState } from 'react';
import { IPaginationFilter } from '../interfaces';
import { defaultPaginationFilter } from '../utils';
const usePagination = (initPaginationFilter?: IPaginationFilter) => {
const [paginationFilter, setPaginationFilter] = useState<IPaginationFilter>(
initPaginationFilter ?? defaultPaginationFilter
);
const onPageChange = (page: number, pageSize: number) => {
setPaginationFilter({
...paginationFilter,
pageIndex: page - 1,
pageSize,
});
};
const onSearch = (value: string) => {
setPaginationFilter({
...paginationFilter,
search: value.trim(),
});
};
return {
paginationFilter,
onPageChange,
onSearch,
};
};
export default usePagination; |
package com.application.racinghub.address.domain.model;
import com.application.racinghub.common.domain.model.BaseModel;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDateTime;
@Entity
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false)
@EntityListeners(AuditingEntityListener.class)
public class Address extends BaseModel{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String street;
@NotNull(message = "Cidade inválida")
private String city;
private String state;
@NotNull(message = "CEP inváido")
private String zip;
@NotNull(message = "País inválido")
private String country;
private Long number;
private String neighborhood;
@Size(max = 500, message = "Valor máximo oberservação: 500 caracteres")
private String note;
@CreatedDate
@JsonIgnore
private LocalDateTime created;
} |
/*
@author Karry
@date on 2023/8/13.
@comment Day 13 单调队列
*/
#include<iostream>
using namespace std;
const int N = 1e6;
int n, a[N];
int k; // window size
int q[N], hh, tt; // the queue and head tail
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> a[i];
// ---- get the minimize ---- //
hh = tt = 0; // 初始化 queue
for (int i = 0; i < n; i++) {
// 从前往后扫描原数组
// step 1. 先检查队头下标所代表的元素是否已经出窗口了,如果已经出窗口了,那队头就要出队列
if (hh < tt && q[hh] < i - k + 1) hh++;
// step 2. 对新元素进行判断,使之不打破单调性,一定要注意队尾元素是 q[tt- 1] !!!
while (hh < tt && a[i] < a[q[tt - 1]]) tt--;
// step 3. 新元素的下标入队列
q[tt++] = i;
// 输出结果,只有在窗口大小后才会输出结果
if (i + 1 >= k) cout << a[q[hh]] << " ";
}
cout << endl;
// ---- get the maximize ---- //
hh = tt = 0; // 初始化 queue
for (int i = 0; i < n; i++) {
// 从前往后扫描原数组
// step 1. 先检查队头下标所代表的元素是否已经出窗口了,如果已经出窗口了,那队头就要出队列
if (hh < tt && q[hh] < i - k + 1) hh++;
// step 2. 对新元素进行判断,使之不打破单调性,一定要注意队尾元素是 q[tt- 1] !!!
while (hh < tt && a[i] > a[q[tt - 1]]) tt--;
// step 3. 新元素的下标入队列
q[tt++] = i;
// 输出结果,只有在窗口大小后才会输出结果
if (i + 1 >= k) cout << a[q[hh]] << " ";
}
return 0;
} |
package com.example.spotify_wrapped.ui.profile;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import com.example.spotify_wrapped.AuthActivity;
import com.example.spotify_wrapped.R;
import com.example.spotify_wrapped.ui.home.HomeViewModel;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.EmailAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ReAuthFragment extends Fragment {
private EditText emailEditText;
private EditText passwordEditText;
private Button saveButton;
private FirebaseAuth firebaseAuth;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_reauth, container, false);
HomeViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
emailEditText = view.findViewById(R.id.email);
passwordEditText = view.findViewById(R.id.password);
saveButton = view.findViewById(R.id.save);
Bundle args = getArguments();
String op = args.getString("op");
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
saveButton.setOnClickListener(v -> {
if (user != null) {
String email = emailEditText.getText().toString().trim();
String password = passwordEditText.getText().toString().trim();
if (!email.isEmpty() && !password.isEmpty()) {
AuthCredential credential = EmailAuthProvider.getCredential(email, password);
user.reauthenticate(credential).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
if (op.equals("update")) {
Navigation.findNavController(v).navigate(R.id.ReAuthToUpdateLogin);
}
if (op.equals("delete")) {
String uid = user.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance()
.getReference("users")
.child(uid);
databaseReference.removeValue();
user.delete().addOnCompleteListener(deleted -> {
if (deleted.isSuccessful()) {
homeViewModel.logout();
Toast.makeText(
requireContext(),
"account deleted",
Toast.LENGTH_SHORT)
.show();
startActivity(
new Intent(requireActivity(), AuthActivity.class));
getActivity().finish();
} else {
Toast.makeText(
requireContext(),
"deleting failed",
Toast.LENGTH_SHORT)
.show();
}
});
}
} else {
Toast.makeText(
requireContext(),
"Authentication failed",
Toast.LENGTH_SHORT)
.show();
}
});
} else {
Toast.makeText(requireContext(), "Fields may not be empty", Toast.LENGTH_SHORT)
.show();
}
}
});
return view;
}
} |
import React, { useState } from 'react';
import PriceInput from '../../../atoms/PriceInput/PriceInput';
import { priceRangeData } from '../../../../assets/data/filter-data';
import { getAverage } from '../../../../utils/functions/functions';
import './PriceRangeSection.scss';
import MultiRangeSlider from '../../../atoms/MultiRangeSlider/MultiRangeSlider';
import FrequencyGraph from '../../../atoms/FrequencyGraph/FrequencyGraph';
const PriceRangeSection = () => {
const [minPrice, setMinPrice] = useState(10);
const [maxPrice, setMaxPrice] = useState(1000);
const updateMinPriceSlider = (percentage) => {
const newMin = (percentage / 100) * 1000;
setMinPrice(newMin);
};
const updateMaxPriceSlider = (percentage) => {
const newMax = (percentage / 100) * 1000;
setMaxPrice(newMax);
};
return (
<div className='PriceRangeSection_container'>
<div className='PriceRangeSection_heading'>Price range</div>
<div className='PriceRangeSection_average'>
The average nightly price is $
{Math.floor(getAverage(priceRangeData))}
</div>
<div className='PriceRangeSection_slider'>
<FrequencyGraph
arrOfNums={priceRangeData}
minPercentage={(minPrice / 1000) * 100}
maxPercentage={(maxPrice / 1000) * 100}
/>
<MultiRangeSlider
initialMin={(minPrice / 1000) * 100}
initialMax={(maxPrice / 1000) * 100}
getMinValue={updateMinPriceSlider}
getMaxValue={updateMaxPriceSlider}
minDisabled={false}
maxDisabled={false}
/>
</div>
<div className='PriceRangeSection_textbox'>
<div>
<PriceInput
label={'min price'}
startAdornment={'$'}
value={minPrice.toString()}
setValue={setMinPrice}
/>
</div>
<div className='PriceRangeSection_hyphen'>-</div>
<div>
<PriceInput
label={'max price'}
startAdornment={'$'}
value={maxPrice.toString()}
setValue={setMaxPrice}
/>
</div>
</div>
</div>
);
};
export default PriceRangeSection; |
import React, { useState } from "react";
import styles from "./SearchBar.module.css";
import searchIcon from "@/app/assets/post-images/mod-icons/search.svg";
import Image from "next/image";
/**
* Component Used to display no results in search
* @component
* @param {function} setIsSearch The function to set the search visibility
* @param {string} username The username to search for
* @param {function} setKeyword The function to set the keyword to search for
* @param {function} setValue The function to set the value of the search input
* @returns {JSX.Element} The rendered NoResult component.
*
* @example
* <NoResults setIsSearch={setIsSearch} username={username} setKeyword={setKeyword} setValue={setValue}/>
*/
function NoResults({ setIsSearch, username, setKeyword, setValue }) {
function handleSeeAll() {
setIsSearch(false);
setKeyword("");
setValue("");
}
return (
<div className={styles.noresult_container}>
<Image src={searchIcon} width={30} height={30} />
<div className={styles.noresult_text}>No results for {username}</div>
<button onClick={handleSeeAll} className={styles.noresult_btn}>
See all
</button>
</div>
);
}
export default NoResults; |
def pow(base: int, exponent: int = 2) -> int:
"""
Raise base to the power of exponent.
Args:
base (int): The base number.
exponent (int, optional): The power to which the base is raised.
Returns:
int: Result of base raised to exponent.
"""
return base**exponent
class Math:
"""
A simple math class.
Args:
rounding (int, optional): The number of decimal places to round to.
"""
def __init__(self, rounding: int = 6) -> None:
self.rounding = rounding
def _round(self, value: float | int) -> float | int:
return round(value, self.rounding)
def pow(self, base: int, exponent: int = 2) -> float:
"""
Raise base to the power of exponent.
Args:
base (int): The base number.
exponent (int, optional): The power to which the base is raised.
Returns:
float: Result of base raised to exponent.
"""
return self._round(base**exponent)
def add(self, a: int, b: int) -> float:
"""
Add two numbers.
Args:
a (int): First number.
b (int): Second number.
Returns:
float: Sum of a and b.
"""
return self._round(a + b)
def subtract(self, a: int, b: int) -> float:
"""
Subtract two numbers.
Args:
a (int): First number.
b (int): Second number.
Returns:
float: Difference of a and b.
"""
return self._round(a - b) |
const { Schema, model } = require('mongoose');
const reactionSchema = require('./Reaction');
const moment = require('moment');
const thoughtSchema = new Schema(
{
thoughtText: {
type: String,
required: true,
minLength: 1,
maxLength: 280
},
createdAt: {
type: Date,
default: Date.now,
get: () => { return moment().format('MMM Do, YYYY, [at] hh:mm a')}
},
username: {
type:String,
required:true,
},
reactions: [reactionSchema],
},
{
toJSON: {
getters: true,
},
}
);
thoughtSchema.virtual('reactionCount').get(function(){
return this.reactions.length;
});
const Thought = model('Thought', thoughtSchema);
module.exports = Thought; |
<template>
<div class="c-progressBar"
:class="{'c-progressBar--round': round}"
>
<span class="c-progressBar__percentage">30%</span>
<div class="c-progressBar__progress"
v-bind:style="{ width: percentage + '%'}"
>
<div class="c-progressBar__background"
:class="progressColor"
></div>
</div>
</div>
</template>
<script>
export default {
name: 'ProgressBar',
components: {
},
props:{
/**
* Value of progress bar
*/
percentage: {
type: [Number, String],
default: 0
},
/**
* Color of progress bar
*/
color: {
type: String,
default: "red"
},
/**
* Round or angled corners
*/
round: {
type: Boolean,
default: false
}
},
computed: {
classObj() {
return {
'c-btn--small': this.size === 'small',
'c-btn--med': this.size === 'med',
'c-btn--large': this.size === 'large',
}
},
progressColor() {
let colorClass = 'u-bgColor--red'
switch(this.color) {
case 'green':
colorClass = 'u-bgColor--green'
break;
case 'orange':
colorClass = 'u-bgColor--orange'
break;
case 'black':
colorClass = 'u-bgColor--black'
break;
default:
colorClass = 'u-bgColor--red'
}
return colorClass
}
}
}
</script>
<docs>
```jsx
<section class="progress-bars-wrapper">
<div class="progress-bars">
<ProgressBar percentage="20" />
<ProgressBar color="green" percentage="40" />
<ProgressBar color="orange" percentage="60" />
<ProgressBar color="black" percentage="80" />
</div>
<div class="progress-bars">
<ProgressBar percentage="20" round/>
<ProgressBar color="green" percentage="40" round/>
<ProgressBar color="orange" percentage="60" round />
<ProgressBar color="black" percentage="80" round />
</div>
</section>
```
</docs>
<style lang="postcss">
.progress-bars-wrapper {
display: grid;
grid-template-columns: 1fr 1fr;
grid-column-gap: 40px;
}
.c-progressBar {
position: relative;
width: 100%;
background-color: #eaeaeb;
height: auto;
margin-bottom: 10px;
padding: 4px;
&.c-progressBar--round {
border-radius: 20px;
}
}
.c-progressBar__percentage {
position: absolute;
color: #000;
transform: translateX(7px);
left: 0%;
line-height: 15px;
letter-spacing: 0;
font-size: 8px;
}
.c-progressBar__progress {
position: relative;
width: 0%;
height: 14px;
overflow: hidden;
.c-progressBar--round & {
border-radius: 50px;
}
}
.c-progressBar__background {
position: absolute;
left: 0;
width: 100%;
border-radius: 0;
height: 14px;
z-index: 1;
/* background: #ee2e2d; */
padding: 2px;
/* &--black {
background-color: #000;
}
&--green {
background-color: #7fc563;
}
&--orange {
background-color: #faa846;
} */
.c-progressBar--round & {
border-radius: 50px;
}
}
</style> |
from typing import List
from pyspark.sql import SparkSession, DataFrame, Row
from pyspark.sql.functions import round as spark_round
from pyspark.sql.functions import col, current_timestamp, expr, lit, coalesce, year, count, broadcast, avg, asc, desc, window, greatest, sequence, explode, date_sub, current_timestamp, floor
# from pyspark.sql.window import Window
from pyspark.sql.types import StringType, IntegerType
from functools import wraps
import time, sys, re
# from q1 import *
# from q2 import *
# from q3 import *
# from q4 import *
data_to_path = "/app/stack/"
Q1_PATH = f"{data_to_path}Q1/"
Q2_PATH = f"{data_to_path}Q2/"
Q3_PATH = f"{data_to_path}Q3/"
Q4_PATH = f"{data_to_path}Q4/"
times = {}
# utility to measure the runtime of some function
def timeit(f):
@wraps(f)
def wrap(*args, **kw):
t = time.time()
result = f(*args, **kw)
measured_time = round(time.time() - t, 3)
key = f"{f.__name__}_{args[-1]}"
if "q2" in f.__name__:
key = f"{f.__name__}_{args[-2]}_{args[-1]}"
if times.get(key, None) is not None:
times[key].append(measured_time)
else:
# times[key] = [measured_time]
times[key] = [] #? para caso queira ignorar a primeira medição
# print(f'{key}: {measured_time}s')
return result
return wrap
def count_rows(iterator):
yield len(list(iterator))
# show the number of rows in each partition
def showPartitionSize(df: DataFrame):
for partition, rows in enumerate(df.rdd.mapPartitions(count_rows).collect()):
print(f'Partition {partition} has {rows} rows')
def write_result(res, filename):
with open(filename, "w") as f:
for row in res:
f.write(str(row) + "\n")
# Queries analíticas
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#******************************** QUERY 1 ********************************
@timeit
def q1(users: DataFrame, questions: DataFrame, answers: DataFrame, comments: DataFrame, interval: StringType = "6 months") -> List[Row]:
questions_selected = questions
answers_selected = answers
comments_selected = comments#.select(col("userid").alias("owneruserid"), "creationdate")
lower_interval = current_timestamp() - expr(f"INTERVAL {interval}")
interactions = (
questions_selected
.union(answers_selected)
.union(comments_selected)
.filter(col("creationdate").between(lower_interval, current_timestamp()))
.groupBy("owneruserid")
.agg(count("*").alias("interaction_count"))
)
result_df = (
users
.join(broadcast(interactions), users["id"] == interactions["owneruserid"], "left")
.select(
users["id"],
users["displayname"],
coalesce(interactions["interaction_count"], lit(0)).cast(IntegerType()).alias("total")
)
.orderBy(col("total").desc())
.limit(100)
)
return result_df.collect()
@timeit
def q1_year(users: DataFrame, questions: DataFrame, answers: DataFrame, comments: DataFrame, interval: StringType = "6 months") -> List[Row]:
#> Versão com a coluna creation_year
questions_selected = questions.select("owneruserid", "creationdate", "creationyear")
answers_selected = answers.select("owneruserid", "creationdate", "creationyear")
comments_selected = comments.select(col("userid").alias("owneruserid"), "creationdate", "creationyear")
# print(questions_selected.rdd.getNumPartitions())
# print(answers_selected.rdd.getNumPartitions())
# print(comments_selected.rdd.getNumPartitions())
lower_interval = current_timestamp() - expr(f"INTERVAL {interval}")
lower_interval_year = year(lower_interval)
interactions = (
questions_selected
.union(answers_selected)
.union(comments_selected)
.filter((col("creationyear") >= lower_interval_year) & (col("creationdate").between(lower_interval, current_timestamp()))) #> Versão com a coluna creation_year
.groupBy("owneruserid")
.agg(count("*").alias("interaction_count"))
)
result_df = (
users
.join(broadcast(interactions), users["id"] == interactions["owneruserid"], "left")
.select(
users["id"],
users["displayname"],
coalesce(interactions["interaction_count"], lit(0)).cast(IntegerType()).alias("total")
)
.orderBy(col("total").desc())
.limit(100)
)
# result_df.show()
return result_df.collect()
#******************************** WORKLOAD 1 ********************************
# Q1
def w1():
# Reads
users = spark.read.parquet(f"{Q1_PATH}users_id_displayname")
questions = spark.read.parquet(f"{Q1_PATH}questions_creationdate_ordered")
answers = spark.read.parquet(f"{Q1_PATH}answers_creationdate_ordered")
comments = spark.read.parquet(f"{Q1_PATH}comments_creationdate_ordered")
reps = 6
for _ in range(reps):
q1(users, questions, answers, comments, '1 months')
for _ in range(reps):
q1(users, questions, answers, comments, '3 months')
for _ in range(reps):
q1(users, questions, answers, comments, '6 months')
for _ in range(reps):
q1(users, questions, answers, comments, '1 year')
for _ in range(reps):
q1(users, questions, answers, comments, '2 year')
# write_result(res, "w1.csv")
def w1_year():
# Reads
users = spark.read.parquet(f"{Q1_PATH}users_id_displayname")
questions = spark.read.parquet(f"{Q1_PATH}questions_parquet_part_year")
answers = spark.read.parquet(f"{Q1_PATH}answers_parquet_part_year")
comments = spark.read.parquet(f"{Q1_PATH}comments_parquet_part_year")
reps = 6
for _ in range(reps):
q1_year(users, questions, answers, comments, '1 month')
for _ in range(reps):
q1_year(users, questions, answers, comments, '3 month')
for _ in range(reps):
q1_year(users, questions, answers, comments, '6 months')
for _ in range(reps):
q1_year(users, questions, answers, comments, '1 year')
for _ in range(reps):
q1_year(users, questions, answers, comments, '2 year')
# write_result(res, "w1-year.csv")
def w1_range():
"""Using RepartitionByRange('creationdate') files"""
# Reads
users = spark.read.parquet(f"{Q1_PATH}users_id_displayname")
questions = spark.read.parquet(f"{Q1_PATH}questions_creationdate_reprange")
answers = spark.read.parquet(f"{Q1_PATH}answers_creationdate_reprange")
comments = spark.read.parquet(f"{Q1_PATH}comments_creationdate_reprange")
reps = 6
for _ in range(reps):
q1(users, questions, answers, comments, '1 month')
for _ in range(reps):
q1(users, questions, answers, comments, '3 month')
for _ in range(reps):
q1(users, questions, answers, comments, '6 months')
for _ in range(reps):
q1(users, questions, answers, comments, '1 year')
for _ in range(reps):
q1(users, questions, answers, comments, '2 year')
# write_result(res, "w1-range.csv")
def w1_final():
# Reads
users = spark.read.parquet(f"{Q1_PATH}users_id_displayname")
questions = spark.read.parquet(f"{Q1_PATH}questions_parquet_part_year")
answers = spark.read.parquet(f"{Q1_PATH}answers_parquet_part_year")
comments = spark.read.parquet(f"{Q1_PATH}comments_parquet_part_year")
reps = 6
for _ in range(reps):
q1_year(users, questions, answers, comments, '6 months')
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#******************************** QUERY 2 ********************************
def is_leap_year(year):
"""
Verifica se o ano é bissexto.
"""
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
def parse_interval_3(interval):
"""
Função para extrair o número e unidade do intervalo e calcular o número de dias correspondente de forma precisa.
"""
# Use expressão regular para extrair número e unidade do intervalo
match = re.match(r"(\d+)\s+(\w+)", interval)
if match:
number = int(match.group(1))
unit = match.group(2).lower()
if unit.startswith("year"):
# Calcular o número exato de dias em 'number' anos considerando anos bissextos
days = sum(366 if is_leap_year(year) else 365 for year in range(1, number + 1))
elif unit.startswith("month"):
# Calcular o número exato de dias em 'number' meses
days_in_month = [31, 29 if is_leap_year(year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = sum(days_in_month[:number])
elif unit.startswith("week"):
# Calcular o número exato de dias em 'number' semanas
days = number * 7
elif unit.startswith("day"):
# 'number' dias
days = number
else:
raise ValueError(f"Unidade de intervalo não suportada: {unit}")
return days
else:
raise ValueError(f"Formato de intervalo inválido: {interval}")
@timeit
def q2(u: DataFrame, year_range: DataFrame, max_reputation_per_year: DataFrame, interval: StringType = "5 years", bucketInterval: IntegerType = 5000):
# SELECT yr.year, generate_series(0, GREATEST(mr.max_rep,0), 5000) AS reputation_range
# FROM year_range yr
# LEFT JOIN max_reputation_per_year mr ON yr.year = mr.year
# juntar os dados de yr e mr
buckets = year_range.alias("yr").join(max_reputation_per_year.alias("mr"), year_range["year"] == max_reputation_per_year["year"], "left")
# gerar a coluna reputation_range
buckets = buckets.withColumn(
"reputation_range",
explode(sequence(lit(0), greatest(col("mr.max_rep"), lit(0)), lit(bucketInterval)))
)
buckets = buckets.select(col("yr.year").alias("year"), col("reputation_range"))
u = u.where(col("votes_creationdate") >= date_sub(current_timestamp(), parse_interval_3(interval))).select('id','creationdate','reputation').distinct()
u = u.withColumn("u_year", year(u["creationdate"]))
u = u.withColumn("reputation_range", floor(u["reputation"] / bucketInterval) * bucketInterval)
u = u.withColumnRenamed("reputation_range", "u_rg")
joined_df = buckets.join(u,
(buckets["year"] == u["u_year"]) &
(buckets["reputation_range"] == u["u_rg"]),
"left")
result_df = joined_df.groupBy("year", "reputation_range") \
.agg({"id": "count"}) \
.withColumnRenamed("count(id)", "total")
sorted_result_df = result_df.orderBy("year", "reputation_range")
return sorted_result_df.collect()
#******************************** WORKLOAD 2 ********************************
# Q2
def w2():
# Reads
year_range = spark.read.parquet(f"{Q2_PATH}year_range")
max_reputation_per_year = spark.read.parquet(f"{Q2_PATH}max_reputation_per_year")
u = spark.read.parquet(f"{Q2_PATH}u")
reps=6
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "1 year", 5000)
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "3 year", 5000)
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "5 year", 5000)
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "7 year", 5000)
def w2_ord():
# Reads
year_range = spark.read.parquet(f"{Q2_PATH}year_range")
max_reputation_per_year = spark.read.parquet(f"{Q2_PATH}max_reputation_per_year")
u = spark.read.parquet(f"{Q2_PATH}u_ord")
reps=6
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "1 year", 5000)
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "3 year", 5000)
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "5 year", 5000)
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "7 year", 5000)
#write_result(res, "w2.csv")
def w2_ord_part():
# Reads
year_range = spark.read.parquet(f"{Q2_PATH}year_range")
max_reputation_per_year = spark.read.parquet(f"{Q2_PATH}max_reputation_per_year")
u = spark.read.parquet(f"{Q2_PATH}u_ord_part")
reps=6
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "1 year", 5000)
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "3 year", 5000)
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "5 year", 5000)
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "7 year", 5000)
def w2_final():
# Reads
year_range = spark.read.parquet(f"{Q2_PATH}year_range")
max_reputation_per_year = spark.read.parquet(f"{Q2_PATH}max_reputation_per_year")
u = spark.read.parquet(f"{Q2_PATH}u")
reps=6
for _ in range(reps):
q2(u, year_range, max_reputation_per_year, "5 year", 5000)
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#******************************** QUERY 3 ********************************
@timeit
def q3(tags: DataFrame, questionstags: DataFrame, answers: DataFrame, inferiorLimit: IntegerType = 10):
questionstags.createOrReplaceTempView("questionstags")
tags.createOrReplaceTempView("tags")
answers.createOrReplaceTempView("answers")
result = spark.sql(f"""
SELECT tagname, round(avg(total), 3) AS avg_total, count(*) AS count_total
FROM (
SELECT t.tagname, qt.questionid, count(*) AS total
FROM tags t
JOIN questionstags qt ON qt.tagid = t.id
LEFT JOIN answers a ON a.parentid = qt.questionid
WHERE t.id IN (
SELECT tagid
FROM questionstags
GROUP BY tagid
HAVING count(*) > {inferiorLimit}
)
GROUP BY t.tagname, qt.questionid
) AS subquery
GROUP BY tagname
ORDER BY avg_total DESC, count_total DESC, tagname
""")
# result.show()
return result.collect()
@timeit
def q3_mv(mat_view: DataFrame, inferiorLimit: IntegerType = 10):
result = mat_view.filter(col("count") > inferiorLimit)
return result.collect()
#******************************** WORKLOAD 3 ********************************
def w3_base():
# Reads
tags = spark.read.parquet(f'{Q3_PATH}tags_parquet') # tabela estática
questionsTags = spark.read.parquet(f'{Q3_PATH}questionsTags_parquet')
answers = spark.read.parquet(f'{Q3_PATH}answers_parquet')
reps=3
for _ in range(reps):
q3(tags, questionsTags, answers, 10)
q3(tags, questionsTags, answers, 30)
q3(tags, questionsTags, answers, 50)
def w3_mv():
mat_view_q3 = spark.read.parquet(f"{Q3_PATH}mv_parquet")
# q3_mv(mat_view_q3, 50)
reps=6
for _ in range(reps):
q3_mv(mat_view_q3, 10)
for _ in range(reps):
q3_mv(mat_view_q3, 30)
for _ in range(reps):
q3_mv(mat_view_q3, 50)
for _ in range(reps):
q3_mv(mat_view_q3, 100)
def w3_mv_ord():
mat_view_q3 = spark.read.parquet(f"{Q3_PATH}mv_parquet_ord")
# q3_mv(mat_view_q3, 50)
reps=6
for _ in range(reps):
q3_mv(mat_view_q3, 10)
for _ in range(reps):
q3_mv(mat_view_q3, 30)
for _ in range(reps):
q3_mv(mat_view_q3, 50)
for _ in range(reps):
q3_mv(mat_view_q3, 100)
def w3_final():
mat_view_q3 = spark.read.parquet(f"{Q3_PATH}mv_parquet")
reps=6
for _ in range(reps):
q3_mv(mat_view_q3, 10)
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#******************************** QUERY 4 ********************************
@timeit
def q4(badges: DataFrame, bucketWindow: StringType = "1 minute"):
result = badges.groupBy(window(col("date"), bucketWindow)) \
.agg(count("*").alias("count")) \
.orderBy("window")
return result.collect()
#******************************** WORKLOAD 4 ********************************
def w4():
mv_badges = spark.read.parquet(f"{Q4_PATH}badges_mat_view")
reps = 3
for _ in range(reps):
q4(mv_badges, "1 minute")
for _ in range(reps):
q4(mv_badges, "10 minute")
for _ in range(reps):
q4(mv_badges, "30 minutes")
for _ in range(reps):
q4(mv_badges, "2 hour")
for _ in range(reps):
q4(mv_badges, "6 hour")
def w4_ord():
mv_badges = spark.read.parquet(f"{Q4_PATH}badges_mat_view_ord")
reps = 3
for _ in range(reps):
q4(mv_badges, "1 minute")
for _ in range(reps):
q4(mv_badges, "10 minute")
for _ in range(reps):
q4(mv_badges, "30 minutes")
for _ in range(reps):
q4(mv_badges, "2 hour")
for _ in range(reps):
q4(mv_badges, "6 hour")
def w4_final():
mv_badges = spark.read.parquet(f"{Q4_PATH}badges_mat_view_ord")
reps = 3
for _ in range(reps):
q4(mv_badges, "1 minute")
#?############################ SPARK SESSION ####################################
spark = SparkSession.builder \
.master("spark://spark:7077") \
.config("spark.eventLog.enabled", "true") \
.config("spark.eventLog.dir", "/tmp/spark-events") \
.config("spark.sql.adaptive.enabled", "true") \
.config("spark.executor.instances", 3) \
.config("spark.sql.shuffle.partitions", "8") \
.config("spark.driver.memory", "12g") \
.getOrCreate()
# .config("spark.driver.memory", "16g") \
# .config("spark.executor.cores", "2") \
# .config("spark.executor.memory", "1g") \
if len(sys.argv) < 2:
print("Running all queries...")
w1_final()
w2_final()
w3_final()
w4_final()
elif sys.argv[1] == "t":
pass
else:
locals()[sys.argv[1]]()
# Calculating average times
for func in times:
if len(times[func]) == 0:
continue
avg_time = sum(times[func]) / len(times[func])
avg_time = round(avg_time, 3)
print(f'Avg of {func}: {avg_time} seconds') |
/********************************************************************************
* * FILE DESCRIPTION * *
* ******************** *
* *
* File : LED.c *
* *
* Component : - *
* *
* Module : LED *
* *
* Description : Source file for the LED *
* *
* Author : Mahmoud Bayoumi *
* *
********************************************************************************/
/*******************************************************************************
* INCLUDES *
*******************************************************************************/
#include "LED.h"
#include "Port.h"
#include "std_types.h"
/********************************************************************************
* GLOBAL FUNCTION *
********************************************************************************/
/********************************************************************************
* \Syntax : LED_Initialize *
* \Description : Function to Initialize the led port using MCAL port *
* *
* \Sync\Async : Synchronous *
* \Reentrancy : Reentrant *
* \Parameters (in) : void *
* \Parameters (out) : None *
* \Return value : void *
* *
********************************************************************************/
void LED_Initialize (void)
{
Port_Initalize(&PortConfigType);
}
/********************************************************************************
* \Syntax : LED_ON *
* \Description : Function to turn on the led the using MCAL port *
* *
* \Sync\Async : Synchronous *
* \Reentrancy : Reentrant *
* \Parameters (in) : LED_Channel - LED_ChannelType *
* \Parameters (out) : None *
* \Return value : void *
* *
********************************************************************************/
void LED_ON (LED_ChannelType LED_Channel)
{
Dio_WriteChannel( LED_Channel, Dio_Level_HIGH);
}
/********************************************************************************
* \Syntax : LED_OFF *
* \Description : Function to turn off the led the using MCAL port *
* *
* \Sync\Async : Synchronous *
* \Reentrancy : Reentrant *
* \Parameters (in) : LED_Channel - LED_ChannelType *
* \Parameters (out) : None *
* \Return value : void *
* *
********************************************************************************/
void LED_OFF (LED_ChannelType LED_Channel)
{
Dio_WriteChannel( LED_Channel, Dio_Level_LOW);
}
/********************************************************************************
* \Syntax : LED_Toggle *
* \Description : Function to toggle the led the using MCAL port *
* *
* \Sync\Async : Synchronous *
* \Reentrancy : Reentrant *
* \Parameters (in) : LED_Channel - LED_ChannelType *
* \Parameters (out) : None *
* \Return value : void *
* *
********************************************************************************/
void LED_Toggle (LED_ChannelType LED_Channel)
{
Dio_FlipChannel( LED_Channel);
}
/********************************************************************************
* LOCAL DATA *
********************************************************************************/
/********************************************************************************
* GLOBAL DATA *
********************************************************************************/
/********************************************************************************
* LOCAL FUNCTION PROTOTYPES *
********************************************************************************/
/********************************************************************************
* LOCAL FUNCTIONS *
********************************************************************************/
/********************************************************************************
* GLOBAL FUNCTIONS PROTOTYPES *
********************************************************************************/
/********************************************************************************
* END OF FILE : LED.c *
********************************************************************************/ |
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pycountry
def mscatter(x, y, ax=None, m=None, **kw):
import matplotlib.markers as mmarkers
ax = ax or plt.gca()
sc = ax.scatter(x, y, **kw)
if (m is not None) and (len(m) == len(x)):
paths = []
for marker in m:
if isinstance(marker, mmarkers.MarkerStyle):
marker_obj = marker
else:
marker_obj = mmarkers.MarkerStyle(marker)
path = marker_obj.get_path().transformed(
marker_obj.get_transform())
paths.append(path)
sc.set_paths(paths)
return sc
color_map = {'all': 'red', 'stopwords': 'blue', 'content': 'green', 'function': 'black'}
offset_map = {'all': .35, 'stopwords': .116, 'content': -.116, 'function': -.35}
size_map = {'vanilla': 50, 'pos': 5, 'token': 5}
marker_map = {'vanilla': "o", 'pos': 7, 'token': 6}
df = pd.read_csv(
'results/csv/oscar_size_50000000_n_shuffle_10.csv',
names=[
'language', 'shuffling', 'run', 'filter',
'sparsity', 'Zipf R2', 'Zipf coeff'])
df['language_position'] = pd.factorize(df['language'])[0]
df['language_name'] = [pycountry.languages.get(alpha_2=lang_code).name
for lang_code in df['language']]
def scale_transformation(x):
return -np.log(1-x)
df['Zipf R2 (transformed scale)'] = scale_transformation(df['Zipf R2'])
fig, ax = plt.subplots(1, 3, figsize=(12, 8))
for ix, metric in enumerate(['sparsity', 'Zipf R2 (transformed scale)', 'Zipf coeff']):
mscatter(
df[metric],
df['language_position'] + [offset_map[f] for f in df['filter']],
ax[ix],
m=[marker_map[s] for s in df["shuffling"]],
c=[color_map[f] for f in df['filter']],
alpha=0.5,
s=[size_map[s] for s in df["shuffling"]],
)
ax[ix].set_xlabel(metric)
ax[ix].set_yticks([])
ax[ix].set_yticklabels([])
if metric == "sparsity":
ax[ix].set_ylabel('language')
ax[ix].set_yticks(df['language_position'].unique())
ax[ix].set_yticklabels(df['language_name'].unique())
ax[ix].set_xscale('log')
if metric == "Zipf R2 (transformed scale)":
x_values = np.array([.6, .7, .8, .9])
ax[ix].set_xticks(scale_transformation(x_values))
ax[ix].set_xticklabels(x_values)
for i, language in enumerate(df['language'].unique()):
if i != 0:
ax[ix].hlines(i - 0.5,
xmin=df[metric].min(), xmax=df[metric].max(),
linestyle='dotted', linewidth=0.5, color='grey')
legend_handles = [
mpatches.Patch(color=value, label=key)
for key, value in color_map.items()]
fig.legend(
title="Filtering:",
handles=legend_handles, loc='upper right')
legend_markers = [
plt.Line2D([0], [0], marker=value, color='w', label=key, markersize=10, markerfacecolor='black')
for key, value in marker_map.items()]
fig.legend(
title="Shuffling by:",
handles=legend_markers, loc='center right')
plt.show() |
import { NgModule, inject } from '@angular/core';
import { ActivatedRouteSnapshot, RouterModule, RouterStateSnapshot, Routes } from '@angular/router';
import { AuthService } from './shared/services/auth.service';
const routes: Routes = [
{path: '', redirectTo: 'login', pathMatch: 'full'},
{
path: 'storages',
loadChildren: () => import('./pages/storages/storages.module').then(m => m.StoragesModule)
},
{
path: 'transfers',
loadChildren: () => import('./pages/transfers/transfers.module').then(m => m.TransfersModule)
},
{
path: 'users',
canActivate: [(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
const authService = inject(AuthService);
const isAdmin = authService.user?.role === '1'
return isAdmin}],
loadChildren: () => import('./pages/users/users.module').then(m => m.UsersModule)
},
{
path: 'products',
canActivate: [(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
const authService = inject(AuthService);
const isAdmin = authService.user?.role === '1'
return isAdmin}],
loadChildren: () => import('./pages/products/products.module').then(m => m.ProductsModule)
},
{
path: 'login',
loadChildren: () => import('./pages/login/login.module').then(m => m.LoginModule)
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } |
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QString>
#include <QStringList>
#include <QCloseEvent>
#include <QDialog>
#include <QFileDialog>
#include <QMessageBox>
#include <memory>
#include "frame.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
Frame* createFrame();
void deleteFrame();
void saveActionSlot();
void saveAsActionSlot();
void openActionSlot();
void newActionSlot();
void versionActionSlot();
void updateSavedStatus(bool status);
private:
std::unique_ptr<Ui::MainWindow> _ui;
bool _saved;
QString _absolutePath;
void closeEvent(QCloseEvent *event) override;
void setupActions();
void connectSlots();
QFileDialog* createFileDialog(const QString& title, QFileDialog::AcceptMode acceptMode, QWidget* parent = nullptr);
QMessageBox::StandardButton createQuestionMessageBox();
QMessageBox::StandardButton createVersionMessageBox();
QMessageBox::StandardButton createErrorMessageBox(const QString& messageTitle, const QString& message);
bool save(const QString& absolutePath);
QJsonObject open(const QString& absolutePath);
void processUnsavedDocument();
void clearFrames();
QString getDestinationFilePathByQuestionWindow(const QString& title, QFileDialog::AcceptMode acceptMode);
};
#endif // MAINWINDOW_H |
import { Testable } from "../../../Testable.sol";
import { LenderCommitmentGroup_Smart_Override } from "./LenderCommitmentGroup_Smart_Override.sol";
import {TestERC20Token} from "../../../tokens/TestERC20Token.sol";
import {TellerV2SolMock} from "../../../../contracts/mock/TellerV2SolMock.sol";
import {UniswapV3PoolMock} from "../../../../contracts/mock/uniswap/UniswapV3PoolMock.sol";
import {UniswapV3FactoryMock} from "../../../../contracts/mock/uniswap/UniswapV3FactoryMock.sol";
import { PaymentType, PaymentCycleType } from "../../../../contracts/libraries/V2Calculations.sol";
import { LoanDetails, Payment, BidState , Bid, Terms } from "../../../../contracts/TellerV2Storage.sol";
import "lib/forge-std/src/console.sol";
//contract LenderCommitmentGroup_Smart_Mock is ExtensionsContextUpgradeable {}
/*
Write tests for a borrower . borrowing money from the group
- write tests for the LTV ratio and make sure that is working as expected (mock)
- write tests for the global liquidityThresholdPercent and built functionality for a user-specific liquidityThresholdPercent based on signalling shares.
-write a test that ensures that adding principal then removing it will mean that totalPrincipalCommitted is the net amount
*/
contract LenderCommitmentGroup_Smart_Test is Testable {
constructor() {}
User private extensionContract;
User private borrower;
User private lender;
User private liquidator;
TestERC20Token principalToken;
TestERC20Token collateralToken;
LenderCommitmentGroup_Smart_Override lenderCommitmentGroupSmart;
TellerV2SolMock _tellerV2;
SmartCommitmentForwarder _smartCommitmentForwarder;
UniswapV3PoolMock _uniswapV3Pool;
UniswapV3FactoryMock _uniswapV3Factory;
function setUp() public {
borrower = new User();
lender = new User();
liquidator = new User();
_tellerV2 = new TellerV2SolMock();
_smartCommitmentForwarder = new SmartCommitmentForwarder();
_uniswapV3Pool = new UniswapV3PoolMock();
_uniswapV3Factory = new UniswapV3FactoryMock();
_uniswapV3Factory.setPoolMock(address(_uniswapV3Pool));
principalToken = new TestERC20Token("wrappedETH", "WETH", 1e24, 18);
collateralToken = new TestERC20Token("PEPE", "pepe", 1e24, 18);
principalToken.transfer(address(lender), 1e18);
collateralToken.transfer(address(borrower), 1e18);
_uniswapV3Pool.set_mockToken0(address(principalToken));
_uniswapV3Pool.set_mockToken1(address(collateralToken));
lenderCommitmentGroupSmart = new LenderCommitmentGroup_Smart_Override(
address(_tellerV2),
address(_smartCommitmentForwarder),
address(_uniswapV3Factory)
);
}
function initialize_group_contract() public {
address _principalTokenAddress = address(principalToken);
address _collateralTokenAddress = address(collateralToken);
uint256 _marketId = 1;
uint32 _maxLoanDuration = 5000000;
uint16 _minInterestRate = 0;
uint16 _maxInterestRate = 800;
uint16 _liquidityThresholdPercent = 10000;
uint16 _loanToValuePercent = 10000;
uint24 _uniswapPoolFee = 3000;
uint32 _twapInterval = 5;
address _poolSharesToken = lenderCommitmentGroupSmart.initialize(
_principalTokenAddress,
_collateralTokenAddress,
_marketId,
_maxLoanDuration,
_minInterestRate,
_maxInterestRate,
_liquidityThresholdPercent,
_loanToValuePercent,
_uniswapPoolFee,
_twapInterval
);
}
function test_initialize() public {
address _principalTokenAddress = address(principalToken);
address _collateralTokenAddress = address(collateralToken);
uint256 _marketId = 1;
uint32 _maxLoanDuration = 5000000;
uint16 _minInterestRate = 100;
uint16 _maxInterestRate = 800;
uint16 _liquidityThresholdPercent = 10000;
uint16 _loanToValuePercent = 10000;
uint24 _uniswapPoolFee = 3000;
uint32 _twapInterval = 5;
address _poolSharesToken = lenderCommitmentGroupSmart.initialize(
_principalTokenAddress,
_collateralTokenAddress,
_marketId,
_maxLoanDuration,
_minInterestRate,
_maxInterestRate,
_liquidityThresholdPercent,
_loanToValuePercent,
_uniswapPoolFee,
_twapInterval
);
// assertFalse(isTrustedBefore, "Should not be trusted forwarder before");
// assertTrue(isTrustedAfter, "Should be trusted forwarder after");
}
// https://github.com/teller-protocol/teller-protocol-v1/blob/develop/contracts/lending/ttoken/TToken_V3.sol
function test_addPrincipalToCommitmentGroup() public {
//principalToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
//collateralToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
lenderCommitmentGroupSmart.set_mockSharesExchangeRate(1e36);
initialize_group_contract();
vm.prank(address(lender));
principalToken.approve(address(lenderCommitmentGroupSmart), 1000000);
vm.prank(address(lender));
uint256 sharesAmount_ = lenderCommitmentGroupSmart
.addPrincipalToCommitmentGroup(1000000, address(borrower));
uint256 expectedSharesAmount = 1000000;
//use ttoken logic to make this better
assertEq(
sharesAmount_,
expectedSharesAmount,
"Received an unexpected amount of shares"
);
}
function test_addPrincipalToCommitmentGroup_after_interest_payments()
public
{
principalToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
collateralToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
lenderCommitmentGroupSmart.set_mockSharesExchangeRate(1e36 * 2);
initialize_group_contract();
//lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(1000000);
//lenderCommitmentGroupSmart.set_totalInterestCollected(2000000);
vm.prank(address(lender));
principalToken.approve(address(lenderCommitmentGroupSmart), 1000000);
vm.prank(address(lender));
uint256 sharesAmount_ = lenderCommitmentGroupSmart
.addPrincipalToCommitmentGroup(1000000, address(borrower));
uint256 expectedSharesAmount = 500000;
//use ttoken logic to make this better
assertEq(
sharesAmount_,
expectedSharesAmount,
"Received an unexpected amount of shares"
);
}
function test_addPrincipalToCommitmentGroup_after_nonzero_shares()
public
{
principalToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
collateralToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
initialize_group_contract();
lenderCommitmentGroupSmart.set_totalInterestCollected(1e6 * 1);
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(1e6 * 1);
vm.prank(address(lender));
principalToken.approve(address(lenderCommitmentGroupSmart), 1000000);
vm.prank(address(lender));
uint256 sharesAmount_ = lenderCommitmentGroupSmart
.addPrincipalToCommitmentGroup(1000000, address(borrower));
uint256 expectedSharesAmount = 1000000;
//use ttoken logic to make this better
assertEq(
sharesAmount_,
expectedSharesAmount,
"Received an unexpected amount of shares"
);
}
function test_burnShares_simple() public {
principalToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
// collateralToken.transfer(address(lenderCommitmentGroupSmart),1e18);
initialize_group_contract();
lenderCommitmentGroupSmart.set_mockSharesExchangeRate( 1e36 ); //this means 1:1 since it is expanded
// lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(1000000);
// lenderCommitmentGroupSmart.set_totalInterestCollected(0);
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(
1000000
);
vm.prank(address(lender));
principalToken.approve(address(lenderCommitmentGroupSmart), 1000000);
vm.prank(address(lender));
uint256 sharesAmount = 1000000;
//should have all of the shares at this point
lenderCommitmentGroupSmart.mock_mintShares(
address(lender),
sharesAmount
);
vm.prank(address(lender));
uint256 receivedPrincipalTokens
= lenderCommitmentGroupSmart.burnSharesToWithdrawEarnings(
sharesAmount,
address(lender)
);
uint256 expectedReceivedPrincipalTokens = 1000000; // the orig amt !
assertEq(
receivedPrincipalTokens,
expectedReceivedPrincipalTokens,
"Received an unexpected amount of principaltokens"
);
}
function test_burnShares_simple_with_ratio_math() public {
principalToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
// collateralToken.transfer(address(lenderCommitmentGroupSmart),1e18);
initialize_group_contract();
lenderCommitmentGroupSmart.set_mockSharesExchangeRate( 2e36 ); //this means 1:1 since it is expanded
// lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(1000000);
// lenderCommitmentGroupSmart.set_totalInterestCollected(0);
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(
1000000
);
vm.prank(address(lender));
principalToken.approve(address(lenderCommitmentGroupSmart), 1000000);
vm.prank(address(lender));
uint256 sharesAmount = 500000;
//should have all of the shares at this point
lenderCommitmentGroupSmart.mock_mintShares(
address(lender),
sharesAmount
);
vm.prank(address(lender));
uint256 receivedPrincipalTokens
= lenderCommitmentGroupSmart.burnSharesToWithdrawEarnings(
sharesAmount,
address(lender)
);
uint256 expectedReceivedPrincipalTokens = 1000000; // the orig amt !
assertEq(
receivedPrincipalTokens,
expectedReceivedPrincipalTokens,
"Received an unexpected amount of principaltokens"
);
}
function test_burnShares_also_get_collateral() public {
principalToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
collateralToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
initialize_group_contract();
lenderCommitmentGroupSmart.set_mockSharesExchangeRate( 1e36 ); //the default for now
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(
1000000
);
vm.prank(address(lender));
principalToken.approve(address(lenderCommitmentGroupSmart), 1000000);
vm.prank(address(lender));
uint256 sharesAmount = 500000;
//should have all of the shares at this point
lenderCommitmentGroupSmart.mock_mintShares(
address(lender),
sharesAmount
);
vm.prank(address(lender));
uint256 receivedPrincipalTokens
= lenderCommitmentGroupSmart.burnSharesToWithdrawEarnings(
sharesAmount,
address(lender)
);
uint256 expectedReceivedPrincipalTokens = 500000; // the orig amt !
assertEq(
receivedPrincipalTokens,
expectedReceivedPrincipalTokens,
"Received an unexpected amount of principal tokens"
);
}
//test this thoroughly -- using spreadsheet data
function test_get_shares_exchange_rate_scenario_A() public {
initialize_group_contract();
lenderCommitmentGroupSmart.set_totalInterestCollected(0);
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(
5000000
);
uint256 rate = lenderCommitmentGroupSmart.super_sharesExchangeRate();
assertEq(rate , 1e36, "unexpected sharesExchangeRate");
}
function test_get_shares_exchange_rate_scenario_B() public {
initialize_group_contract();
lenderCommitmentGroupSmart.set_totalInterestCollected(1000000);
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(
1000000
);
lenderCommitmentGroupSmart.set_totalPrincipalTokensWithdrawn(
1000000
);
uint256 rate = lenderCommitmentGroupSmart.super_sharesExchangeRate();
assertEq(rate , 1e36, "unexpected sharesExchangeRate");
}
function test_get_shares_exchange_rate_scenario_C() public {
initialize_group_contract();
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(
1000000
);
lenderCommitmentGroupSmart.set_totalInterestCollected(1000000);
uint256 sharesAmount = 500000;
lenderCommitmentGroupSmart.mock_mintShares(
address(lender),
sharesAmount
);
uint256 poolTotalEstimatedValue = lenderCommitmentGroupSmart.getPoolTotalEstimatedValue();
assertEq(poolTotalEstimatedValue , 2 * 1000000, "unexpected poolTotalEstimatedValue");
uint256 rate = lenderCommitmentGroupSmart.super_sharesExchangeRate();
assertEq(rate , 4 * 1e36, "unexpected sharesExchangeRate");
/*
Rate should be 2 at this point so a depositor will only get half as many shares for their principal
*/
}
function test_get_shares_exchange_rate_after_default_liquidation_A() public {
initialize_group_contract();
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(
1000000
);
lenderCommitmentGroupSmart.set_totalInterestCollected(1000000);
lenderCommitmentGroupSmart.set_tokenDifferenceFromLiquidations(-1000000);
uint256 sharesAmount = 1000000;
lenderCommitmentGroupSmart.mock_mintShares(
address(lender),
sharesAmount
);
uint256 poolTotalEstimatedValue = lenderCommitmentGroupSmart.getPoolTotalEstimatedValue();
assertEq(poolTotalEstimatedValue , 1 * 1000000, "unexpected poolTotalEstimatedValue");
uint256 rate = lenderCommitmentGroupSmart.super_sharesExchangeRate();
assertEq(rate , 1 * 1e36, "unexpected sharesExchangeRate");
}
function test_get_shares_exchange_rate_after_default_liquidation_B() public {
initialize_group_contract();
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(
1000000
);
lenderCommitmentGroupSmart.set_tokenDifferenceFromLiquidations(-500000);
uint256 sharesAmount = 1000000;
lenderCommitmentGroupSmart.mock_mintShares(
address(lender),
sharesAmount
);
uint256 poolTotalEstimatedValue = lenderCommitmentGroupSmart.getPoolTotalEstimatedValue();
assertEq(poolTotalEstimatedValue , 1 * 500000, "unexpected poolTotalEstimatedValue");
uint256 rate = lenderCommitmentGroupSmart.super_sharesExchangeRate();
assertEq(rate , 1e36 / 2, "unexpected sharesExchangeRate");
}
function test_get_shares_exchange_rate_inverse() public {
lenderCommitmentGroupSmart.set_mockSharesExchangeRate(1000000);
uint256 rate = lenderCommitmentGroupSmart.super_sharesExchangeRateInverse();
}
/*
make sure both pos and neg branches get run, and tellerV2 is called at the end
*/
function test_liquidateDefaultedLoanWithIncentive() public {
initialize_group_contract();
principalToken.transfer(address(liquidator), 1e18);
uint256 originalBalance = principalToken.balanceOf(address(liquidator));
uint256 amountOwed = 100;
uint256 bidId = 0;
lenderCommitmentGroupSmart.set_mockAmountOwedForBid(amountOwed);
vm.warp(1000); //loanDefaultedTimeStamp ?
lenderCommitmentGroupSmart.set_mockBidAsActiveForGroup(bidId,true);
vm.prank(address(liquidator));
principalToken.approve(address(lenderCommitmentGroupSmart), 1e18);
lenderCommitmentGroupSmart.mock_setMinimumAmountDifferenceToCloseDefaultedLoan(2000);
int256 tokenAmountDifference = 4000;
vm.prank(address(liquidator));
lenderCommitmentGroupSmart.liquidateDefaultedLoanWithIncentive(
bidId,
tokenAmountDifference
);
uint256 updatedBalance = principalToken.balanceOf(address(liquidator));
int256 expectedDifference = int256(amountOwed) + tokenAmountDifference;
assertEq(originalBalance - updatedBalance , uint256(expectedDifference), "unexpected tokenDifferenceFromLiquidations");
//make sure lenderCloseloan is called
assertEq( _tellerV2.lenderCloseLoanWasCalled(), true, "lender close loan not called");
}
//complete me
function test_liquidateDefaultedLoanWithIncentive_negative_direction() public {
initialize_group_contract();
principalToken.transfer(address(liquidator), 1e18);
uint256 originalBalance = principalToken.balanceOf(address(liquidator));
uint256 amountOwed = 1000;
uint256 bidId = 0;
lenderCommitmentGroupSmart.set_mockAmountOwedForBid(amountOwed);
//time has advanced enough to now have a 50 percent discount s
vm.warp(1000); //loanDefaultedTimeStamp ?
lenderCommitmentGroupSmart.set_mockBidAsActiveForGroup(bidId,true);
vm.prank(address(liquidator));
principalToken.approve(address(lenderCommitmentGroupSmart), 1e18);
lenderCommitmentGroupSmart.mock_setMinimumAmountDifferenceToCloseDefaultedLoan(-500);
int256 tokenAmountDifference = -500;
vm.prank(address(liquidator));
lenderCommitmentGroupSmart.liquidateDefaultedLoanWithIncentive(
bidId,
tokenAmountDifference
);
uint256 updatedBalance = principalToken.balanceOf(address(liquidator));
require(tokenAmountDifference < 0); //ensure this test is set up properly
// we expect it to be amountOwned - abs(tokenAmountDifference ) but we can just test it like this
int256 expectedDifference = int256(amountOwed) + ( tokenAmountDifference);
assertEq(originalBalance - updatedBalance , uint256(expectedDifference), "unexpected tokenDifferenceFromLiquidations");
//make sure lenderCloseloan is called
assertEq( _tellerV2.lenderCloseLoanWasCalled(), true, "lender close loan not called");
}
/*
make sure we get expected data based on the vm warp
*/
function test_getMinimumAmountDifferenceToCloseDefaultedLoan() public {
initialize_group_contract();
uint256 bidId = 0;
uint256 amountDue = 500;
_tellerV2.mock_setLoanDefaultTimestamp(block.timestamp);
vm.warp(10000);
uint256 loanDefaultTimestamp = block.timestamp - 2000; //sim that loan defaulted 2000 seconds ago
int256 min_amount = lenderCommitmentGroupSmart.super_getMinimumAmountDifferenceToCloseDefaultedLoan(
amountDue,
loanDefaultTimestamp
);
int256 expectedMinAmount = 4220; //based on loanDefaultTimestamp gap
assertEq(min_amount,expectedMinAmount,"min_amount unexpected");
}
function test_getMinimumAmountDifferenceToCloseDefaultedLoan_zero_time() public {
initialize_group_contract();
uint256 bidId = 0;
uint256 amountDue = 500;
_tellerV2.mock_setLoanDefaultTimestamp(block.timestamp);
vm.warp(10000);
uint256 loanDefaultTimestamp = block.timestamp ; //sim that loan defaulted 2000 seconds ago
vm.expectRevert("Loan defaulted timestamp must be in the past");
int256 min_amount = lenderCommitmentGroupSmart.super_getMinimumAmountDifferenceToCloseDefaultedLoan(
amountDue,
loanDefaultTimestamp
);
}
function test_getMinimumAmountDifferenceToCloseDefaultedLoan_full_time() public {
initialize_group_contract();
uint256 bidId = 0;
uint256 amountDue = 500;
_tellerV2.mock_setLoanDefaultTimestamp(block.timestamp);
vm.warp(100000);
uint256 loanDefaultTimestamp = block.timestamp - 22000 ; //sim that loan defaulted 2000 seconds ago
int256 min_amount = lenderCommitmentGroupSmart.super_getMinimumAmountDifferenceToCloseDefaultedLoan(
amountDue,
loanDefaultTimestamp
);
int256 expectedMinAmount = 3220; //based on loanDefaultTimestamp gap
assertEq(min_amount,expectedMinAmount,"min_amount unexpected");
}
function test_getMinInterestRate() public {
lenderCommitmentGroupSmart.set_mock_getMaxPrincipalPerCollateralAmount(
100 * 1e18
);
principalToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
collateralToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
initialize_group_contract();
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(1000000);
uint256 principalAmount = 50;
uint256 collateralAmount = 50 * 100;
address collateralTokenAddress = address(
lenderCommitmentGroupSmart.collateralToken()
);
uint256 collateralTokenId = 0;
uint32 loanDuration = 5000000;
uint16 interestRate = 800;
uint256 bidId = 0;
uint16 poolUtilizationRatio = lenderCommitmentGroupSmart.getPoolUtilizationRatio(
);
assertEq(poolUtilizationRatio, 0);
// submit bid
uint16 minInterestRate = lenderCommitmentGroupSmart.getMinInterestRate(
);
assertEq(minInterestRate, 0);
}
function test_acceptFundsForAcceptBid() public {
lenderCommitmentGroupSmart.set_mock_getMaxPrincipalPerCollateralAmount(
100 * 1e18
);
principalToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
collateralToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
initialize_group_contract();
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(1000000);
uint256 principalAmount = 50;
uint256 collateralAmount = 50 * 100;
address collateralTokenAddress = address(
lenderCommitmentGroupSmart.collateralToken()
);
uint256 collateralTokenId = 0;
uint32 loanDuration = 5000000;
uint16 interestRate = 100;
uint256 bidId = 0;
// TellerV2SolMock(_tellerV2).setMarketRegistry(address(marketRegistry));
// submit bid
TellerV2SolMock(_tellerV2).submitBid(
address(principalToken),
0,
principalAmount,
loanDuration,
interestRate,
"",
address(this)
);
vm.prank(address(_smartCommitmentForwarder));
lenderCommitmentGroupSmart.acceptFundsForAcceptBid(
address(borrower),
bidId,
principalAmount,
collateralAmount,
collateralTokenAddress,
collateralTokenId,
loanDuration,
interestRate
);
}
function test_acceptFundsForAcceptBid_insufficientCollateral() public {
lenderCommitmentGroupSmart.set_mock_getMaxPrincipalPerCollateralAmount(
100 * 1e18
);
principalToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
collateralToken.transfer(address(lenderCommitmentGroupSmart), 1e18);
initialize_group_contract();
lenderCommitmentGroupSmart.set_totalPrincipalTokensCommitted(1000000);
uint256 principalAmount = 100;
uint256 collateralAmount = 0;
address collateralTokenAddress = address(
lenderCommitmentGroupSmart.collateralToken()
);
uint256 collateralTokenId = 0;
uint32 loanDuration = 5000000;
uint16 interestRate = 100;
uint256 bidId = 0;
vm.expectRevert("Insufficient Borrower Collateral");
vm.prank(address(_smartCommitmentForwarder));
lenderCommitmentGroupSmart.acceptFundsForAcceptBid(
address(borrower),
bidId,
principalAmount,
collateralAmount,
collateralTokenAddress,
collateralTokenId,
loanDuration,
interestRate
);
}
/*
improve tests for this
*/
function test_getCollateralTokensAmountEquivalentToPrincipalTokens_scenarioA() public {
initialize_group_contract();
uint256 principalTokenAmountValue = 9000;
uint256 pairPriceWithTwap = 1 * 2**96;
uint256 pairPriceImmediate = 2 * 2**96;
bool principalTokenIsToken0 = false;
uint256 amountCollateral = lenderCommitmentGroupSmart
.super_getCollateralTokensAmountEquivalentToPrincipalTokens(
principalTokenAmountValue,
pairPriceWithTwap,
pairPriceImmediate,
principalTokenIsToken0
);
uint256 expectedAmount = 4500;
assertEq(
amountCollateral,
expectedAmount,
"Unexpected getCollateralTokensPricePerPrincipalTokens"
);
}
function test_getCollateralTokensAmountEquivalentToPrincipalTokens_scenarioB() public {
initialize_group_contract();
uint256 principalTokenAmountValue = 9000;
uint256 pairPriceWithTwap = 1 * 2**96;
uint256 pairPriceImmediate = 2 * 2**96;
bool principalTokenIsToken0 = true;
uint256 amountCollateral = lenderCommitmentGroupSmart
.super_getCollateralTokensAmountEquivalentToPrincipalTokens(
principalTokenAmountValue,
pairPriceWithTwap,
pairPriceImmediate,
principalTokenIsToken0
);
uint256 expectedAmount = 9000;
assertEq(
amountCollateral,
expectedAmount,
"Unexpected getCollateralTokensPricePerPrincipalTokens"
);
}
function test_getCollateralTokensAmountEquivalentToPrincipalTokens_scenarioC() public {
initialize_group_contract();
uint256 principalTokenAmountValue = 9000;
uint256 pairPriceWithTwap = 1 * 2**96;
uint256 pairPriceImmediate = 60000 * 2**96;
bool principalTokenIsToken0 = false;
uint256 amountCollateral = lenderCommitmentGroupSmart
.super_getCollateralTokensAmountEquivalentToPrincipalTokens(
principalTokenAmountValue,
pairPriceWithTwap,
pairPriceImmediate,
principalTokenIsToken0
);
uint256 expectedAmount = 1;
assertEq(
amountCollateral,
expectedAmount,
"Unexpected getCollateralTokensPricePerPrincipalTokens"
);
}
/*
test for _getUniswapV3TokenPairPrice
*/
function test_getPriceFromSqrtX96_scenarioA() public {
initialize_group_contract();
uint160 sqrtPriceX96 = 771166083179357884152611;
uint256 priceX96 = lenderCommitmentGroupSmart
.super_getPriceFromSqrtX96(
sqrtPriceX96
);
uint256 price = priceX96 * 1e18 / 2**96;
uint256 expectedAmountX96 = 7506133033681329001;
uint256 expectedAmount = 94740718;
assertEq(
priceX96,
expectedAmountX96,
"Unexpected getPriceFromSqrtX96"
);
assertEq(
price,
expectedAmount,
"Unexpected getPriceFromSqrtX96"
);
}
}
contract User {}
contract SmartCommitmentForwarder {} |
import { Box, Flex, HelpIcon, Skeleton, Text, useMatchBreakpoints, useTooltip } from '@zoinks-swap/uikit'
import Balance from 'components/Balance'
import { useTranslation } from 'contexts/Localization'
import { useBUSDCakeAmount } from 'hooks/useBUSDPrice'
import React from 'react'
import { VaultKey } from 'state/types'
import { useIfoPoolCredit, useVaultPoolByKey } from 'state/pools/hooks'
import styled from 'styled-components'
import { getBalanceNumber } from 'utils/formatBalance'
import BaseCell, { CellContent } from './BaseCell'
interface AvgBalanceCellProps {
account: string
}
const StyledCell = styled(BaseCell)`
flex: 4.5;
${({ theme }) => theme.mediaQueries.sm} {
flex: 1 0 120px;
}
${({ theme }) => theme.mediaQueries.lg} {
flex: 2 0 100px;
}
`
const HelpIconWrapper = styled.div`
align-self: center;
`
const AvgBalanceCell: React.FC<AvgBalanceCellProps> = ({ account }) => {
const { t } = useTranslation()
const { isMobile } = useMatchBreakpoints()
const {
userData: { isLoading: userDataLoading },
} = useVaultPoolByKey(VaultKey.IfoPool)
const credit = useIfoPoolCredit()
const hasCredit = credit.gt(0)
const cakeAsNumberBalance = getBalanceNumber(credit)
const avgBalanceDollarValue = useBUSDCakeAmount(cakeAsNumberBalance)
const labelText = `${t('Average')} ${t('Pool Balance')}`
const { targetRef, tooltip, tooltipVisible } = useTooltip(
t(
'Max Zoinks entry for both IFO sale is capped by average pool balance in this pool. This is calculated by the average block balance in the IFO pool in the past blocks prior to cut-off block.',
),
{ placement: 'bottom' },
)
return (
<StyledCell role="cell">
<CellContent>
<Text fontSize="12px" color="textSubtle" textAlign="left">
{labelText}
</Text>
{userDataLoading && account ? (
<Skeleton width="80px" height="16px" />
) : (
<>
{tooltipVisible && tooltip}
<Flex>
<Box mr="8px" height="32px">
<Balance
mt="4px"
bold={!isMobile}
fontSize={isMobile ? '14px' : '16px'}
color={hasCredit ? 'primary' : 'textDisabled'}
decimals={hasCredit ? 5 : 1}
value={hasCredit ? cakeAsNumberBalance : 0}
/>
{hasCredit ? (
<Balance
display="inline"
fontSize="12px"
color="textSubtle"
decimals={2}
prefix="~"
value={avgBalanceDollarValue || 0}
unit=" USD"
/>
) : (
<Text mt="4px" fontSize="12px" color="textDisabled">
0 USD
</Text>
)}
</Box>
{hasCredit && !isMobile && (
<HelpIconWrapper ref={targetRef}>
<HelpIcon color="textSubtle" />
</HelpIconWrapper>
)}
</Flex>
</>
)}
</CellContent>
</StyledCell>
)
}
export default AvgBalanceCell |
package com.example.crud_sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DBHandler extends SQLiteOpenHelper {
// creating a constant variables for our database.
// below variable is for our database name.
private static final String DB_NAME = "goods";
// below int is our database version
private static final int DB_VERSION = 1;
// below variable is for our table name.
private static final String TABLE_NAME = "product";
// below variable is for our id column.
private static final String ID_COL = "id";
// below variable is for our product name column
private static final String NAME_COL = "name";
// below variable for our product description column.
private static final String DESCRIPTION_COL = "description";
// below variable id for our product price column.
private static final String PRICE_COL = "price";
// creating a constructor for our database handler.
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
// below method is for creating a database by running a sqlite query
@Override
public void onCreate(SQLiteDatabase db) {
// on below line we are creating
// an sqlite query and we are
// setting our column names
// along with their data types.
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COL + " TEXT,"
+ DESCRIPTION_COL + " TEXT,"
+ PRICE_COL + " TEXT)";
// at last we are calling a exec sql
// method to execute above sql query
db.execSQL(query);
}
// this method is use to add new product to our sqlite database.
public void addNewProduct(String productName, String productDescription, String productPrice) {
// on below line we are creating a variable for
// our sqlite database and calling writable method
// as we are writing data in our database.
SQLiteDatabase db = this.getWritableDatabase();
// on below line we are creating a
// variable for content values.
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, productName);
values.put(DESCRIPTION_COL, productDescription);
values.put(PRICE_COL, productPrice);
// after adding all values we are passing
// content values to our table.
db.insert(TABLE_NAME, null, values);
// at last we are closing our
// database after adding database.
db.close();
}
// we have created a new method for reading all the products.
public ArrayList<ProductModal> showProducts() {
// on below line we are creating a
// database for reading our database.
SQLiteDatabase db = this.getReadableDatabase();
// on below line we are creating a cursor with query to read data from database.
Cursor cursorProducts = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
// on below line we are creating a new array list.
ArrayList<ProductModal> productModalArrayList = new ArrayList<>();
// moving our cursor to first position.
if (cursorProducts.moveToFirst()) {
do {
// on below line we are adding the data from cursor to our array list.
productModalArrayList.add(new ProductModal(cursorProducts.getString(1),
cursorProducts.getString(2),
cursorProducts.getString(3)));
} while (cursorProducts.moveToNext());
// moving our cursor to next.
}
// at last closing our cursor
// and returning our array list.
cursorProducts.close();
return productModalArrayList;
}
// below is the method for updating our products
public void updateProduct(String originalProductName, String productName, String productDescription, String productPrice) {
// calling a method to get writable database.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, productName);
values.put(DESCRIPTION_COL, productDescription);
values.put(PRICE_COL, productPrice);
// on below line we are calling a update method to update our database and passing our values.
// and we are comparing it with name of our product which is stored in original name variable.
db.update(TABLE_NAME, values, "name=?", new String[]{originalProductName});
db.close();
}
// below is the method for deleting our product.
public void deleteProduct(String productName) {
// on below line we are creating
// a variable to write our database.
SQLiteDatabase db = this.getWritableDatabase();
// on below line we are calling a method to delete our
// product and we are comparing it with our product name.
db.delete(TABLE_NAME, "name=?", new String[]{productName});
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// this method is called to check if the table exists already.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
} |
import {
Controller,
Get,
Post,
Body,
Param,
InternalServerErrorException,
HttpStatus,
Res,
ParseArrayPipe,
} from '@nestjs/common';
import { Response } from 'express';
import { AuthorService } from 'src/author/author.service';
import { IBookWithAuthor } from './book.interface';
import { BookService } from './book.service';
import { CreateBookDto } from './dto/create-book.dto';
@Controller('book')
export class BookController {
constructor(
private readonly bookService: BookService,
private authorService: AuthorService,
) {}
@Post()
public async createBooks(
@Body(
new ParseArrayPipe({
items: CreateBookDto,
whitelist: true,
}),
)
createBookDto: CreateBookDto[],
@Res()
res: Response,
): Promise<Response> {
try {
const createdBooks: IBookWithAuthor[] = [];
for (const book of createBookDto) {
const { title, authorId } = book;
if (!title || !authorId) {
return res.status(HttpStatus.BAD_REQUEST).send({
message: 'Some book fields are missing or invalid',
});
}
const doesAuthorExists = await this.authorService.doesExists(
book.authorId,
);
if (!doesAuthorExists) {
return res.status(HttpStatus.CONFLICT).send({
message: 'Book author does not exist',
book,
});
}
const isSameBookTitleForAuthor =
await this.bookService.isSameBookTitleForAuthor(book);
if (isSameBookTitleForAuthor) {
return res.status(HttpStatus.CONFLICT).send({
message: 'Book title already exists for this author',
book,
});
}
const createdBook = await this.bookService.createBook(book);
createdBooks.push(createdBook);
}
return res.status(HttpStatus.OK).send({
message: `${
createdBooks.length > 1 ? 'Books have' : 'Book has'
} been created successfully`,
createdBooks,
});
} catch {
throw new InternalServerErrorException(
'It was not possible to create a new book',
);
}
}
@Get()
public async getBooks(@Res() res: Response): Promise<Response> {
try {
const books = await this.bookService.getBooks();
if (!books) {
return res
.status(HttpStatus.NOT_FOUND)
.send({ message: 'No books were found' });
}
return res.status(HttpStatus.OK).send(books);
} catch {
throw new InternalServerErrorException(
'It was not possible to get the books',
);
}
}
@Get(':id')
public async getBookById(
@Res() res: Response,
@Param('id') id: string,
): Promise<Response> {
try {
const book = await this.bookService.getBookById(id);
if (!book) {
return res
.status(HttpStatus.NOT_FOUND)
.send({ message: 'The book was not found' });
}
return res.status(HttpStatus.OK).send(book);
} catch {
throw new InternalServerErrorException(
'It was not possible to get the book',
);
}
}
} |
import { useCallback, useEffect, useRef, useState } from "react"
// Hook para criar um intervalo controlado
function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
tick(); // Chamamos a função imediatamente ao iniciar o intervalo
const intervalId = setInterval(tick, delay);
return () => clearInterval(intervalId);
}
}, [delay]);
}
const Slide = ({wallpapers,title}) => {
const [photo, setPhoto] = useState()
const changeWallpaper = useCallback(() => {
setPhoto(wallpapers[Math.floor(Math.random() * wallpapers.length)]);
}, [wallpapers]);
// Use o useInterval para acionar a troca de papel de parede a cada 10 segundos
useInterval(() => {
changeWallpaper();
}, 10000);
return (
<div className="w-full h-[75vh] relative">
<div className="absolute text-[5rem] z-10 top-[50%] text-white text-center w-full ">
<h1>{title}</h1>
</div>
{photo == null ?
(<section>
</section>
)
: (
<img
src={photo.urls.full}
className="w-full h-full opacity-80"
alt="slide"
loading="lazy"
/>
)
}
</div>
)
}
export default Slide; |
import tw from "twin.macro";
import React from "react";
import _image from "next/image";
import Head from "next/head";
import iBranche from "../../Interfaces/iBranche";
import Markdown from "../../components/Layout/Markdown";
import MemberList from "../../components/Airsoft/MemberList";
import Divider from "../../components/Elements/Divider";
import PartnerList from "../../components/Elements/Partner/PartnerList";
import Gallery from "../../components/Elements/Gallery";
import LeaderCard from "../../components/Elements/LeaderCard";
import {Link} from "../../components/Button";
import {apiFetch} from "../../lib/api";
import ImageWithLoader from "../../components/Layout/Image";
import LoLTeamList from "../../components/ESports/LoLTeamList";
const Header = tw.div`
relative
flex
justify-center
h-[60vh]
`;
const ContentWrapper = tw.div`
relative
bg-white
flex
flex-col
justify-center
items-center
mt-base
`;
const Content = tw.div`
max-w-screen-xl
px-small
flex
flex-col
gap-small
`;
const Image = tw(ImageWithLoader)`
object-cover
h-full
w-full
`;
const HeadlineWrapper = tw.div`
absolute
h-full
flex
flex-col
justify-center
items-center
`;
const LogoImage = tw(_image)`
w-72
`;
const Headline = tw.h1`
text-center
text-headline
text-white
uppercase
`;
const StickyWrapperRight = tw.div`
xl:absolute
top-base
right-base
z-20
h-full
mt-base
xl:mt-0
`;
const StickyWrapperLeft = tw.div`
hidden
lg:block
absolute
top-base
left-base
z-20
h-full
`;
type BranchProps = {
branch: iBranche;
}
function Branch({branch}: BranchProps) {
return (
<>
<Head>
<title> {branch.attributes.displayName} | Alles im Rudel e.V.</title>
<meta
name="description"
content={branch.attributes.slug === "airsoft" ? "Wir sind eines der größten und am meisten organisierten Airsoft-Teams im Norden Deutschlands. Mit Mitgliedern aus dem Raum Schleswig-Holstein, Hamburg, Niedersachsen und Mecklenburg-Vorpommern. Mit breit aufgestellten, kompetenten, lokalen Ansprechpartnern." : "Wir sind ein E-Sports-Team, das sich an allen möglichen Spielen versucht und sind dabei stets auf der Suche nach weiteren Spielern, die sowohl freundlich als auch teamplayfähig sind. Zwar steht bei uns der Spaß im Vordergrund, aber je nach Spiel nehmen wir auch kompetitiv an kleineren oder auch mal größeren Turnieren teil. Aktuell spielt die Mehrheit von uns vor allem League of Legends, aber auch Spiele wie Minecraft oder Hearts of Iron sind bei uns vertreten."}
/>
</Head>
<Header>
<Image
priority
src={branch.attributes.backgroundImage.data.attributes.url}
alt="Logo Alles im Rudel e.V."
width={1920}
height={1000}
/>
<HeadlineWrapper>
<LogoImage
src="/logos/logo-white-slim.png"
alt="Logo Alles im Rudel e.V."
width={150}
height={100}
/>
<Headline>
{branch.attributes.displayName}
</Headline>
</HeadlineWrapper>
</Header>
<ContentWrapper>
<StickyWrapperLeft>
<Link href="/join" css={tw`sticky top-base`}>
Join now
</Link>
</StickyWrapperLeft>
<Content>
<Markdown>
{branch.attributes.description}
</Markdown>
</Content>
<StickyWrapperRight>
<LeaderCard leader={branch.attributes.leader} />
</StickyWrapperRight>
{branch.attributes.airsoftTeam.length > 0 &&
<MemberList headline="Unser Team" memberList={branch.attributes.airsoftTeam} />}
{branch.attributes.lolTeams.length > 0 &&
<LoLTeamList teams={branch.attributes.lolTeams} />}
{branch?.attributes?.partners?.data && branch?.attributes?.partners?.data.length > 0 && <>
<Divider>
Unsere Partner
</Divider>
<PartnerList partners={branch.attributes.partners.data} />
</>}
{branch?.attributes?.gallery.data && branch?.attributes?.gallery.data.length > 0 && <>
<Divider>
Galerie
</Divider>
<Gallery gallery={branch.attributes.gallery.data} />
</>}
</ContentWrapper>
</>
)
}
export async function getStaticPaths() {
// Call an external API endpoint to get posts
const res = await apiFetch('/branches')
const {data} = await res
// Get the paths we want to pre-render based on posts
const paths = data.map((branch: iBranche) => ({
params: {slug: branch.attributes.slug},
}))
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return {paths, fallback: false}
}
type BranchParams = {
params: {
slug: string
}
}
export async function getStaticProps({params}: BranchParams) {
const responseBranche = await apiFetch(`/branches?filters[slug][$eq]=${params.slug}&populate[0]=*&populate[1]=backgroundImage.*&populate[2]=airsoftTeam.image&populate[3]=gallery.*&populate[4]=partners.logo&populate[5]=leader.image&populate[6]=airsoftTeam.playerBadges.image&populate[7]=lolTeams.*&populate[8]=lolTeams.teamMembers.lolLane&populate[9]=lolTeams.teamMembers.lolLane.image&populate[10]=lolTeams.teamMembers.image`);
const branche = await responseBranche;
return {
props: {
branch: branche.data[0],
},
revalidate: 30
};
}
export default Branch |
package com.api.kwhcalculator.controladores;
import com.api.kwhcalculator.dto.SectorGeneralDTO;
import com.api.kwhcalculator.servicios.SectorGeneralServicio;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*", methods= {RequestMethod.GET,RequestMethod.POST, RequestMethod.DELETE, RequestMethod.PUT, RequestMethod.OPTIONS})
@RequestMapping("/api/usuarios/{idUsuario}")
public class SectorGeneralControlador {
@Autowired
private SectorGeneralServicio sectorGeneralServicio;
//todas las peticiones devuelven DTO, ya que el objeto de transferencia realmente contiene un JSON (objetoDTO = JSON)
@PreAuthorize("hasRole('ADMIN')")
//Crear Sector General
@PostMapping("/sectoresGenerales")
public ResponseEntity<SectorGeneralDTO> crearSectorGeneral(@PathVariable(value = "idUsuario") long idUsuario, @RequestBody SectorGeneralDTO sectorGeneralDTO) {
return new ResponseEntity<>(sectorGeneralServicio.crearSectorGeneral(idUsuario, sectorGeneralDTO), HttpStatus.CREATED);
}
@PreAuthorize("hasRole('ADMIN')")
//Obtener lista de sectores generales asociados al ID de un usuario
@GetMapping("/sectoresGenerales")
public List<SectorGeneralDTO> listarSectoresGeneralesPorUsuarioId(@PathVariable(value = "idUsuario") long idUsuario) {
return sectorGeneralServicio.obtenerSectoresGeneralesPorUsuarioId(idUsuario);
}
@PreAuthorize("hasRole('ADMIN')")
//Obtener un sector general buscándolo por el ID del usuario y el ID del sector general
@GetMapping("/sectoresGenerales/{idSectorGeneral}")
public ResponseEntity<SectorGeneralDTO> obtenerSectorGeneralPorId(@PathVariable(value = "idUsuario") long idUsuario, @PathVariable(value = "idSectorGeneral") long idSectorGeneral) {
//retorna una respuesta de una entidad con HTTPStatus.OK
SectorGeneralDTO sectorGeneralDTO = sectorGeneralServicio.obtenerSectorGeneralPorUsuarioIdSectorGeneralId(idUsuario,idSectorGeneral);
return new ResponseEntity<>(sectorGeneralDTO, HttpStatus.OK);
}
@PreAuthorize("hasRole('ADMIN')")
//Modificar un sector general buscándolo por el ID del usuario y el ID del sector general
@PutMapping("/sectoresGenerales/{idSectorGeneral}")
public ResponseEntity<SectorGeneralDTO> modificarSectorGeneralPorId(@PathVariable(value = "idUsuario") long idUsuario,
@PathVariable(value = "idSectorGeneral") long idSectorGeneral,
@RequestBody SectorGeneralDTO sectorGeneralDTO) {
SectorGeneralDTO sectorGeneralRespuesta = sectorGeneralServicio.modificarSectorGeneral(idUsuario, idSectorGeneral, sectorGeneralDTO);
return new ResponseEntity<>(sectorGeneralRespuesta, HttpStatus.OK);
}
@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/sectoresGenerales/{idSectorGeneral}")
public ResponseEntity<String> eliminarSectorGeneral(@PathVariable(value = "idUsuario") long idUsuario, @PathVariable(value = "idSectorGeneral") long idSectorGeneral) {
sectorGeneralServicio.eliminarSectorGeneral(idUsuario, idSectorGeneral);
return new ResponseEntity<>("Sector general eliminado exitosamente", HttpStatus.OK);
}
} |
<div class="jumbotron p-4 my-1">
<div class="h1 display-4">Formulário</div>
<p class="lead m-1">Exemplo de alguns componentes de formulário</p>
</div>
<div class="mb5">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#/paginas/bemVindo.html">Home</a>
</li>
<li class="breadcrumb-item active">Formulário</li>
</ol>
</div>
<p class="lead">
<a href="https://getbootstrap.com/docs/4.0/components/forms/" target="_black">Documentação Oficial</a>
</p>
<!-- Formulário -->
<div class="card">
<div class="card-header">
<h5 class="mb-0">Exemplo de formulário</h5>
</div>
<div class="card-body">
<form action="" class="container-fluid">
<div class="form-row">
<div class="col-12 col-md-6">
<div class="form-group">
<label for="nome">Nome</label>
<input type="text" class="form-control" id="nome" placeholder="Informe seu nome">
</div>
</div>
</div>
<div class="form-row">
<div class="col-12 col-md-6">
<div class="form-group">
<label for="email">E-mail</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">@</span>
</div>
<input type="email" class="form-control" id="email" placeholder="Informe seu e-mail">
</div>
<small class="form-text text-muted">Enviaremos um e-mail para confirmar o cadastro</small>
</div>
</div>
<div class="col-12 col-md-6">
<div class="form-group">
<label for="linguagemPreferida">Linguagem</label>
<select class="form-control" id="linguagem-preferida">
<option value="">Selecione</option>
<option>JS</option>
<option>PHP</option>
<option>Python</option>
<option>C#</option>
<option>Java</option>
</select>
</div>
</div>
</div>
<hr>
<div class="form-row mb-0">
<div class="col-12">
<button class="btn btn-primary" type="submit">Salvar</button>
<button class="btn btn-secondary" type="reset">Cancelar</button>
</div>
</div>
</form>
</div>
</div> |
package com.maids.libms.main.service;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class EmailService {
private final JavaMailSender javaMailSender;
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Async
public void sendVerificationEmail(String to, String verificationCode) {
String subject = "Backend Quiz Verification Email";
String body = "Your verification code is " + verificationCode;
log.info("sending email " + to);
sendEmail(to, subject, body);
log.info("Email sent successfully" + to);
}
@Async
public void sendEmail(String to, String subject, String body) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(to);
mailMessage.setSubject(subject);
mailMessage.setText(body);
javaMailSender.send(mailMessage);
}
} |
const express = require("express");
const { auth } = require("../middlewares/auth");
const {ZoomRequestModel, validateZoomRequest} = require('../models/zoomRequestModel');
const {generateZoomLink} = require("../helpers/zoomInstance")
const router = express.Router();
// Random Zoom Meeting Endpoint with Joi validation
router.post("/startZoomMeeting", async (req, res) => {
try {
await validateZoomRequest(req.body);
const userId = req.body.userId;
// Check if there's an available partner in the pool
const partnerRequest = await ZoomRequestModel.findOne({ userId: { $ne: userId } });
if (partnerRequest) {
// If a partner is available, remove the request from the pool
await partnerRequest.remove();
// Return the Zoom meeting link to both users
res.json({ success: true, zoomLink: partnerRequest.zoomLink });
} else {
// Generate a new Zoom meeting link
const zoomLink =await generateZoomLink();
// Add a new request to the pool
const newRequest = new ZoomRequestModel({ userId, zoomLink });
await newRequest.save();
// Return the Zoom meeting link to the user
res.json({ success: true, zoomLink });
}
} catch (error) {
console.error("Error starting Zoom meeting:", error.message);
res.status(400).json({ success: false, error: error.message });
}
});
module.exports = router; |
package org.iplatform.example.service.service;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.iplatform.microservices.core.http.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@Configuration
@Service
@RestController
@RequestMapping("/api/v1")
public class IndexService {
private static final Logger LOG = LoggerFactory.getLogger(IndexService.class);
@PostConstruct
public void init() {
LOG.info("类实例化");
}
/**
* 仅演示用
*/
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public ResponseEntity<RestResponse<Map>> hello() {
RestResponse<String> response = new RestResponse<>();
try {
response.setData("Hi");
response.setSuccess(Boolean.TRUE);
return new ResponseEntity(response, HttpStatus.OK);
} catch (Exception ex) {
LOG.error("内部错误", ex);
response.setSuccess(Boolean.FALSE);
return new ResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
} |
/* Convert Celsius to Fahrenheit */
function convertToF(celsius) {
let fahrenheit;
// Celsius to Fahrenheit = Celsius * 9/5 + 32
fahrenheit = (celsius * 9) / 5 + 32;
return fahrenheit;
}
// console.log(convertToF(-10));
/* Reverse a String */
function reverseString(str) {
return str.split('').reverse().join('');
}
// console.log(reverseString('hello'));
/* Factorialize a Number */
/* Solution #1 */
function factorialize(num) {
let newNum = 1;
let count = 1;
while (count < num) {
newNum = newNum * (count + 1);
count++;
}
return newNum;
}
//console.log(factorialize(5));
/* Solution #2 */
// function factorialize(num) {
// if (num === 1 || num === 0) {
// return 1;
// }
// return num * factorialize(num - 1);
// }
// console.log(factorialize(5));
/* Find the Longest Word in a String */
function findLongestWordLength(str) {
console.log(str.split(' ').map(item => item.length));
const strArr = str
.split(' ')
.map(item => item.length)
.sort((a, b) => a - b);
return strArr[strArr.length - 1];
}
// console.log(
// findLongestWordLength(
// 'What if we try a super-long word such as otorhinolaryngology'
// )
// );
/* Return Largest Numbers in Arrays */
function largestOfFour(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
// console.log(arr[i].sort((a, b) => a - b))
let sortedArrs = arr[i].sort((a, b) => a - b);
console.log(sortedArrs[sortedArrs.length - 1]);
newArr.push(sortedArrs[sortedArrs.length - 1]);
}
return newArr;
}
// console.log(
// largestOfFour([
// [4, 5, 1, 3],
// [13, 27, 18, 26],
// [32, 35, 37, 39],
// [1000, 1001, 857, 1],
// ])
// );
/* Confirm the Ending */
// using variables in a regular expression
// https://reactgo.com/javascript-variable-regex/
/* Soution #1 */
// function confirmEnding(str, target) {
// let regexVar = target + '$';
// const regex = new RegExp(regexVar, 'i');
// return regex.test(str);
// }
/* Solution #2 */
function confirmEnding(str, target) {
return str.substring(str.length - target.length) === target ? true : false;
}
//console.log(confirmEnding('Connor', 'nor')); // should return true
/* Repeat a String Repeat a StringPassed */
/* Solution #1 */
// function repeatStringNumTimes(str, num) {
// let newStr = '';
// if (num <= 0) {
// return '';
// }
// for (let i = 0; i < num; i++) {
// newStr += str;
// }
// return newStr;
// }
/* Solution #2 */
function repeatStringNumTimes(str, num) {
let arr = [];
let count = 1;
while (count <= num) {
arr.push(str);
count++;
}
return arr.join('');
}
// console.log(repeatStringNumTimes('abc', 3));
/* Truncate a String */
/* Solution #1 */
// function truncateString(str, num) {
// if (num >= str.length) {
// return str.slice(0, num);
// } else {
// return str.slice(0, num) + '...';
// }
// }
/* Solution #2 */
function truncateString(str, num) {
if (str.length > num) {
return str.substring(0, num) + '...';
} else {
return str;
}
}
// console.log(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length));
/* Finders Keepers */
/* Solution #1 */
// function findElement(arr, func) {
// let num = 0;
// for (let i = 0; i < arr.length; i++) {
// if (func(arr[i]) === true) {
// return (num = arr[i]);
// } else {
// num = undefined;
// }
// }
// return num;
// }
/* Solution #2 */
function findElement(arr, func) {
for (let i = 0; i < arr.length; i++) {
if (func(arr[i])) {
return arr[i];
}
}
}
// console.log(findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }))
/* Title Case a Sentence */
/* Solution #1 */
// function titleCase(str) {
// const strToArray = str.toLowerCase().split(' ');
// let newArr = [];
// for (let i = 0; i < strToArray.length; i++) {
// //console.log(strToArray[i])
// newArr.push(strToArray[i][0].toUpperCase() + strToArray[i].substring(1));
// }
// return newArr.join(' ');
// }
/* Solution #2 */
function titleCase(str) {
let arr = str.split(' ');
return arr
.map(
word =>
word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()
)
.join(' ');
}
// console.log(titleCase("I'm a little tea pot"));
/* Slice and Splice */
function frankenSplice(arr1, arr2, n) {
let newArr = [...arr2];
newArr.splice(n, 0, ...arr1);
return newArr;
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
/* Falsey Bouncer */
/* Solution #1 */
function bouncer(arr) {
const filtered = arr.filter(item => {
if (item) return item;
});
return filtered;
}
// console.log(bouncer([7, 'ate', '', false, 9, NaN]));
// false, null, 0, "", undefined, and NaN
/* Solution #2 */
function bouncer2(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
console.log(typeof arr[i]);
// if statement checks for falsiness or truthiness
if (arr[i]) {
console.log(arr[i]);
newArr.push(arr[i]);
}
}
return newArr;
}
// console.log(bouncer2([7, "ate", "", false, 9, NaN, 0]));
/* Where Do I Belong */
/* Solution #1 */
// function getIndexToIns(arr, num) {
// arr.push(num);
// let newArr = [];
// const sorted = arr.sort((a, b) => a - b);
// for (let i = 0; i < sorted.length; i++) {
// // console.log(sorted[i] === num)
// if (sorted[i] === num) {
// newArr.push(i);
// }
// }
// return newArr[0];
// }
/* Solution #2 */
function getIndexToIns(arr, num) {
let sorted = [...arr, num].sort((a, b) => a - b);
return sorted.indexOf(num);
}
// console.log(getIndexToIns([10, 20, 30, 40, 50], 35));
/* Mutations */
// https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript
/* Solution #1 */
// function mutation(arr) {
// const array1 = arr[0].toLowerCase().split('');
// const array2 = arr[1].toLowerCase().split('');
// // console.log(array2)
// const mappedArray = array2.map(value => array1.includes(value));
// // console.log(mappedArray);
// // console.log(mappedArray.includes(false))
// if (mappedArray.includes(false)) {
// return false;
// } else {
// return true;
// }
// }
/* Solution #2 */
function mutation(arr) {
let str1 = arr[0].toLowerCase().split('').sort();
let str2 = arr[1].toLowerCase().split('').sort();
return str2.every(element => str1.includes(element));
}
// console.log(mutation(["Alien", "line"]));
/* Chunky Monkey */
function chunkArrayInGroups(arr, size) {
let tempArray = [];
for (let i = 0; i < arr.length; i += size) {
// console.log(arr.slice(i, i + size))
// console.log(tempArray);
tempArray.push(arr.slice(i, i + size));
}
// console.log(tempArray);
return tempArray;
}
console.log(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2));
// program to split array into smaller chunks
// https://www.programiz.com/javascript/examples/split-array
function splitIntoChunk(arr, chunk) {
for (i = 0; i < arr.length; i += chunk) {
let tempArray;
tempArray = arr.slice(i, i + chunk);
console.log(tempArray);
}
}
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const chunk = 2;
splitIntoChunk(array, chunk); |
"use client";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import axios from 'axios';
const Main = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [newTodo, setNewTodo] = useState('');
const [newDescription, setNewDescription] = useState('');
const [selectedTodo, setSelectedTodo]: any = useState(null);
const [filterStatus, setFilterStatus] = useState('');
const [filteredTodos, setFilteredTodos] = useState<Todo[]>([]);
interface Todo {
id: number;
taskName: string;
description: string;
status: string;
createdAt?: Date; // Optional field, as it seems to be nullable in your Prisma model
}
const fetchTodos = async () => {
try {
const response = await axios.get('http://localhost:4000/todos');
setTodos(response.data);
} catch (error) {
console.error('Error fetching todos:', error);
}
};
const fetchTodosByStatus = async () => {
try {
const response = await axios.get(`http://localhost:4000/todos/status/${filterStatus}`);
setFilteredTodos(response.data);
} catch (error) {
console.error('Error fetching todos by status:', error);
}
};
// const handleCreateTodo = async () => {
// try {
// await axios.post('http://localhost:4000/todos', { taskName: newTodo, description: '', status: 'incomplete' });
// fetchTodos();
// setNewTodo('');
// } catch (error) {
// console.error('Error creating todo:', error);
// }
// };
const handleCreateTodo = async () => {
try {
await axios.post('http://localhost:4000/todos', {
taskName: newTodo,
description: newDescription,
status: 'incomplete',
});
fetchTodos();
setNewTodo('');
setNewDescription('');
} catch (error) {
console.error('Error creating todo:', error);
}
};
const handleUpdateTodo = async () => {
if (!selectedTodo) return;
try {
await axios.put(`http://localhost:4000/todos/${selectedTodo.id}`, {
taskName: selectedTodo.taskName,
description: '',
status: 'complete',
});
fetchTodos();
setSelectedTodo(null);
} catch (error) {
console.error('Error updating todo:', error);
}
};
useEffect(() => {
fetchTodos();
}, []);
return (
<>
<div>
<h1>Todo List</h1>
<div className="bg-gray-900 m-2">
<div className="flex justify-end py-2 px-8">
<select className="w-1/2 border rounded p-2" value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)}>
<option value="incomplete">Incomplete</option>
<option value="complete">Complete</option>
<option value="all">All</option>
</select>
<button className="bg-yellow-500 text-white px-4 rounded" onClick={fetchTodosByStatus}>
Filter
</button>
</div>
<div className="flex justify-center py-2 px-8">
<ul className="bg-white shadow overflow-hidden sm:rounded-md w-2/3 mt-4">
{filterStatus ? (
filteredTodos.map((todo: any) => (
<li key={todo.id} onClick={() => setSelectedTodo(todo)}>
<div className="px-2 py-2">
<div className="flex items-center justify-between">
<h3 className="text-lg leading-6 font-medium text-gray-900">{todo.taskName}</h3>
<p className="mt-1 max-w-2xl text-sm text-gray-500">{todo.description}</p>
</div>
<div className="mt-4 flex items-center justify-between">
<p className="text-sm font-medium text-gray-500">Status: <span className={todo.status === 'done' ? 'text-green-600' : 'text-red-600'}>{todo.status}</span></p>
<a href="#" className="font-medium text-indigo-600 hover:text-indigo-500">Edit</a>
</div>
</div>
</li>
))
) : (
todos.map((todo: any) => (
<li key={todo.id} onClick={() => setSelectedTodo(todo)}>
<div className="px-2 py-2">
<div className="flex items-center justify-between">
<h3 className="text-lg leading-6 font-medium text-gray-900">{todo.taskName}</h3>
<p className="mt-1 max-w-2xl text-sm text-gray-500">{todo.description}</p>
</div>
<div className="mt-4 flex items-center justify-between">
<p className="text-sm font-medium text-gray-500">Status: <span className={todo.status === 'done' ? 'text-green-600' : 'text-red-600'}>{todo.status}</span></p>
<a href="#" className="font-medium text-indigo-600 hover:text-indigo-500">Edit</a>
</div>
</div>
</li>
))
)}
</ul>
</div>
</div>
{/* <div>
<label>Filter by Status:</label>
<input type="text" value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)} />
<button onClick={fetchTodosByStatus}>Filter</button>
</div>
{filterStatus && (
<ul>
{filteredTodos.map((todo:any) => (
<li key={todo.id} onClick={() => setSelectedTodo(todo)}>
{todo.taskName} - {todo.status}
</li>
))}
</ul>
)}
{!filterStatus && (
<ul>
{todos.map((todo:any) => (
<li key={todo.id} onClick={() => setSelectedTodo(todo)}>
{todo.taskName} - {todo.status}
</li>
))}
</ul>
)} */}
<div>
<h2>Create Todo</h2>
<label>Task Name:</label>
<input type="text" value={newTodo} onChange={(e) => setNewTodo(e.target.value)} />
<label>Description:</label>
<input type="text" value={newDescription} onChange={(e) => setNewDescription(e.target.value)} />
<button onClick={handleCreateTodo}>Create</button>
</div>
{selectedTodo && (
<div>
<h2>Update Todo</h2>
<p>{selectedTodo.taskName}</p>
<button onClick={handleUpdateTodo}>Mark as Complete</button>
</div>
)}
</div>
</>
);
};
export default Main; |
/**
* Copyright (C) 2022 VeriSilicon Holdings Co., Ltd.
* All rights reserved.
*
* @file soc_pinmux.h
* @brief SoC pinmux definition & API
*/
#ifndef __SOC_PINMUX_H__
#define __SOC_PINMUX_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#ifndef BIT
#define BIT(n) ((1ul) << (n))
#endif
/** @addtogroup SOC
* @brief SoC pinmux definition and API
* @ingroup BSP
*
* @{
*/
#define SOC_PAD(i, cfg) \
{ \
(i), (cfg) \
}
/* Pinmux bit set */
#define SW_DS(x) (x) /**< Pad drive strength control*/
#define SW_IN BIT(2) /**< Pad input force on */
#define SW_ST BIT(3) /**< Pad schmitt trigger enable */
#define SW_PD BIT(4) /**< Pad pull down enable */
#define SW_PU BIT(5) /**< Pad pull up enable */
#define SW_OD BIT(6) /**< Pad open drain enable */
#define SW_MUX(x) (x << 7) /**< Pad mux select */
#define SW_IOKEEP BIT(12) /**< IO keep enable */
typedef enum SocInterfaceDef {
SOC_IF_GPIO = 0,
SOC_IF_HOST_JTAG,
SOC_IF_BLE_JTAG,
SOC_IF_AUDIO_JTAG,
SOC_IF_UART,
SOC_IF_QSPI,
SOC_IF_SPI,
SOC_IF_I2C,
SOC_IF_I3C,
SOC_IF_PWM,
SOC_IF_USB,
SOC_IF_I2S,
SOC_IF_PDM,
SOC_IF_DAC_OUT,
SOC_IF_ADC_IN,
SOC_IF_MAX
} SocInterfaceDef;
/**
* @brief SoC Interface Info
* @note It's an unified definition for all kinds of interfaces
*/
typedef union SocIfInfo {
/** PWM interface info struct */
struct {
uint16_t device_id;
uint16_t channel;
} pwm;
/** Common interface port */
uint32_t port;
} SocIfInfo;
typedef struct GpioMuxCfg {
SocIfInfo info; /**< Port info */
uint32_t value; /**< Value of pin setting */
} GpioMuxCfg;
typedef struct SocPinCtl {
unsigned char idx; /* Pin control index or pin ID */
uint32_t cfg; /* Config register of pinmux */
} SocPinCtl;
/**
* @brief Init the SoC to default pinmux configuration
* @return VSD_SUCCESS for success, others for failure
*/
int soc_pinmux_init(void);
/**
* @brief Config pinmux for all necessary pins
* @param pin_ctl The control table of all pins
* @param pin_num Total pin numbers to control
* @return VSD_SUCCESS for success, others for failure
*/
int soc_pinmux_config(const SocPinCtl *pin_ctl, uint32_t pin_num);
/**
* @brief Configure pinmux for specific interface and port ID
*
* @param soc_if The interface ID, @see SocInterfaceDef
* @param info The pointer of interface info which is defined by @see
* SocIfInfo
* @param value By default, 1 for enable, 0 for disable. GPIO has special
* definition according to SoC pinmux design
* @return VSD_SUCCESS for success, others for failure
*/
int soc_pinmux_set(uint32_t soc_if, SocIfInfo *info, uint32_t value);
/** @} */
#ifdef __cplusplus
}
#endif
#endif |
<html
xmlns:th="https://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout.html}">
<head>
<title>Create article</title>
<script src="https://cdn.tiny.cloud/1/j26milfo1aew6x3bd3qxbkmm1zuiq9deftbapcchllv62guf/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
</head>
<body>
<section layout:fragment="content">
<form th:action="@{/admin/articles/create}" th:object="${articleForm}" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" th:field="*{title}" />
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea class="form-control" id="content" rows="3" th:field="*{content}" />
</div>
<div class="form-group">
<label for="category">Category</label>
<select class="form-select" th:field="*{categoryId}" id="category">
<option th:each="category : ${categories}" th:value="${category.id}" th:text="${category.name}" />
</select>
</div>
<br />
<button type="submit" class="btn btn-primary">Create</button>
</form>
<script>
tinymce.init({
selector: 'textarea#content',
plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table | align lineheight | numlist bullist indent outdent | emoticons charmap | removeformat',
});
</script>
</section>
</body>
</html> |
#pragma once
#include "SgpParam.h"
SGPSDK_STDC_START
/**
* @brief 初始化一个设备对象
* @param
* @return 返回设备对象
* @note
*/
SGP_API SGP_HANDLE SGP_InitDevice();
/**
* @brief 释放设备对象
* @param
* handle 输入参数,传入设备对象
* @return 无。
* @note
*/
SGP_API void SGP_UnInitDevice(SGP_HANDLE handle);
/**
* @brief 用户登录
* @param
* handle 输入参数,传入设备对象
* server 输入参数,设备服务地址
* username 输入参数,登录用户
* password 输入参数,登录密码
* port 输入参数,端口号(默认80端口)
* @return 成功返回SGP_OK,失败返回错误码
* @note 需要登录以后才能访问其他接口
*/
SGP_API int SGP_Login(SGP_HANDLE handle, const char *server, const char *username, const char *password, int port);
/**
* @brief 用户登出
* @param
* handle 输入参数,传入设备对象
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_Logout(SGP_HANDLE handle);
/**
* @brief 获取通用信息
* @param
* handle 输入参数,传入设备对象
* output 输出参数,获取通用信息
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetGeneralInfo(SGP_HANDLE handle, SGP_GENERAL_INFO *output);
/**
* @brief 开启可见光
* @param
* handle 输入参数,传入设备对象
* callback 输入参数,注册图像回调函数(RGB24数据)
* pUser 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_OpenVlVideo(SGP_HANDLE handle, SGP_RTSPCALLBACK callback, void *pUser);
/**
* @brief 开启红外
* @param
* handle 输入参数,传入设备对象
* callback 输入参数,注册图像回调函数(RGB24数据)
* pUser 输入参数
* @return 成功返回SGP_OK,失败返回错误码
*/
SGP_API int SGP_OpenIrVideo(SGP_HANDLE handle, SGP_RTSPCALLBACK callback,void *pUser);
/**
* @brief 关闭可见光视频
* @param
* handle 输入参数,传入设备对象
* @return 无
* @note 退出登录会自动关闭视频流
*/
SGP_API void SGP_CloseVlVideo(SGP_HANDLE handle);
/**
* @brief 关闭红外视频
* @param
* handle 输入参数,传入设备对象
* @return 无
* @note 退出登录会自动关闭视频流
*/
SGP_API void SGP_CloseIrVideo(SGP_HANDLE handle);
/**
* @brief 设置电子变倍,只对主码流有效
* @param
* handle 输入参数,传入设备对象
* type 输入参数,类型
* magnification 输入参数,1:红外原始,可见光原始 2:红外2倍,可见光4倍 3:红外3倍,可见光16倍
* @return 成功返回SGP_OK,失败返回错误码
*/
SGP_API int SGP_SetElectronicMagnification(SGP_HANDLE handle, SGP_VIDEO_PARAM_ENUM type, int magnification);
/**
* @brief 获取温度矩阵(医疗机芯有效)
* @param
* handle 输入参数,传入设备对象
* callback 输入参数,注册温度矩阵回调函数(Short数据,温度*100)
* pUser 输入参数
* @return 成功返回SGP_OK,失败返回错误码
*/
SGP_API int SGP_GetTempMatrix(SGP_HANDLE handle, SGP_TEMPCALLBACK callback, void *pUser);
/**
* @brief 温度矩阵旋转
* @param
* handle 输入参数,传入设备对象
* dst 输出参数,输出旋转后的温度矩阵
* src 输入参数,输入需要旋转的温度矩阵
* w 输入参数,输入src的宽
* h 输入参数,输入src的高
* rotation 输入参数,0:旋转90,1:旋转180°,2:旋转270°
* @return 成功返回SGP_OK,失败返回错误码
*/
SGP_API int SGP_GetTempMatriRotation(SGP_HANDLE handle, short *dst, short *src, int w, int h, int rotation);
/**
* @brief 修改密码
* @param
* handle 输入参数,传入设备对象
* username 输入参数,登录用户名
* oldpassword 输入参数,旧密码
* newpassword 输入参数,新密码
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_ChangePassword(SGP_HANDLE handle, const char *username, const char *oldpassword, const char *newpassword);
/**
* @brief 重置密码
* @param
* handle 输入参数,传入设备对象
* username 输入参数,登录用户名
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_ResetPassword(SGP_HANDLE handle, const char *username);
/**
* @brief 获取单点温度
* @param
* handle 输入参数,传入设备对象
* x 输入参数,横坐标,范围在1到图像宽之间。
* y 输入参数,纵坐标,范围在1到图像高之间。
* output 输出参数,点温度。
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetPointTemp(SGP_HANDLE handle, int x, int y, float *output);
/**
* @brief 获取系统版本信息
* @param
* handle 输入参数,传入设备对象
* output 输出参数,系统版本信息
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetVersionInfo(SGP_HANDLE handle, SGP_VERSION_INFO *output);
/**
* @brief 同步系统时间
* @param
* handle 输入参数,传入设备对象
* datetime 输入参数,同步时间"2020-05-21 12:22:33"
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SynchroTime(SGP_HANDLE handle, const char *datetime);
/**
* @brief 系统重启
* @param
* handle 输入参数,传入设备对象
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_RebootSystem(SGP_HANDLE handle);
/**
* @brief 录制(控制设备端录像)
* @param
* handle 输入参数,传入设备对象
* subtype 输入参数,录制选项 1:开始录制 2:停止录制
* record_stream 输入参数,录制流 1:单光可见光; 2:单光红外; 3:双光,同时录制
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_Record(SGP_HANDLE handle, int subtype,int record_stream);
/**
* @brief 开始录制(本地录像)
* @param
* handle 输入参数,传入设备对象
* type 输入参数,录像类型
* input 输入参数,保存文件路径+文件名+.mp4
* callback 输入参数,录像状态回调,例如自动停止录像
* pUser 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_StartRecord(SGP_HANDLE handle, SGP_VIDEO_TYPE type, const char *input, SGP_RECORDCALLBACK callback, void *pUser);
/**
* @brief 停止录制(本地录像)
* @param
* handle 输入参数,传入设备对象
* type 输入参数,录像类型
* @return 无
* @note
*/
SGP_API void SGP_StopRecord(SGP_HANDLE handle, SGP_VIDEO_TYPE type);
/**
* @brief 清理数据
* @param
* handle 输入参数,传入设备对象
* @return 成功返回SGP_OK,失败返回错误码
* @note 此接口用于清理磁盘缓存数据
*/
SGP_API int SGP_ClearData(SGP_HANDLE handle);
/**
* @brief 获取分析对象实时温度
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetAnalyticObjectsTemp(SGP_HANDLE handle, SGP_ANALYTIC_TEMPS *output);
/**
* @brief 获取热图
* @param
* handle 输入参数,传入设备对象
* input 输入参数,保存文件路径+文件名+.jpg
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetHeatMap(SGP_HANDLE handle, const char *input);
/**
* @brief 获取高压热图
* @param
* handle 输入参数,传入设备对象
* input 输入参数,保存文件路径+文件名+.fir
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetFirHeatMap(SGP_HANDLE handle, const char *input);
/**
* @brief 获取屏幕截图
* @param
* handle 输入参数,传入设备对象
* type 输入参数,
* input 输入参数,保存文件路径+文件名+.jpg
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetScreenCapture(SGP_HANDLE handle, SGP_IMAGE_TYPE type, const char *input);
/**
* @brief 快门操作
* @param
* handle 输入参数,设备对象
* type 输入参数,快门类型
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_DoShutter(SGP_HANDLE handle, SGP_SHUTTER_ENUM type);
/**
* @brief 获取温度矩阵
* @param
* handle 输入参数,传入设备对象
* output 输出参数,输出温度矩阵
* length 输入参数,output大小
* type 输入参数,返回的温度矩阵大小:0为推流红外分辨率,1为设备红外原始分辨率
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetImageTemps(SGP_HANDLE handle, float *output, int length, int type);
/**
* @brief 设置全局测温参数
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetThermometryParam(SGP_HANDLE handle, SGP_THERMOMETRY_PARAM input);
/**
* @brief 获取全局测温参数
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetThermometryParam(SGP_HANDLE handle, SGP_THERMOMETRY_PARAM *output);
/**
* @brief 设置全局测温开关
* @param
* handle 输入参数,传入设备对象
* input 输入参数,0关闭 1开启
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetThermometryFlag(SGP_HANDLE handle, int input);
/**
* @brief 设置色带号
* @param
* handle 输入参数,传入设备对象
* input 输入参数,色带号1~26
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetColorBar(SGP_HANDLE handle, int input);
/**
* @brief 设置色带显示
* @param
* handle 输入参数,传入设备对象
* input 输入参数,0关闭 1开启
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetColorBarShow(SGP_HANDLE handle, int input);
/**
* @brief 设置温度显示类型
* @param
* handle 输入参数,传入设备对象
* input 输入参数,温度显示方式:1 最高温 2 最低温 3 平均温 4 最高温 + 最低温 5 最高温 + 平均温 6 平均温 + 最低温 7 最高温 + 最低温 + 平均温 8不显示
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetTempShowMode(SGP_HANDLE handle, int input);
/**
* @brief 切换测温范围
* @param
* handle 输入参数,传入设备对象
* input 输入参数,0~2(部分设备只有1个档位,目前最多有3个档位,从SGP_GetGeneralInfo中获取当前设备支持档位)
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetRange(SGP_HANDLE handle, int input);
/**
* @brief 设置字符串叠加
* @param
* handle 输入参数,传入设备对象
* type 输入参数,是否使用字符叠加 1:关闭; 2,4,5:右下; 3:右上
IPT640M 1:关闭; 2:左上; 3:右上; 4:左下; 5:右下
* input 输入参数,字符串
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetStringShow(SGP_HANDLE handle, int type, const char *input);
/**
* @brief 设置分析对象温度显示类型
* @param
* handle 输入参数,传入设备对象
* input 输入参数,对象温度显示:1最高温;2最低温;3平均温;4仅名称;5不显示
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetThermometryRuleShowMode(SGP_HANDLE handle, int input);
/**
* @brief 添加分析对象
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_AddThermometryRule(SGP_HANDLE handle, SGP_RULE input);
/**
* @brief 更新分析对象
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_UpdateThermometryRule(SGP_HANDLE handle, SGP_RULE input);
/**
* @brief 删除分析对象
* @param
* handle 输入参数,传入设备对象
* input 输入参数,分析对象id
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_DeleteThermometryRule(SGP_HANDLE handle, int input);
/**
* @brief 删除全部分析对象
* @param
* handle 输入参数,传入设备对象
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_DeleteAllThermometryRule(SGP_HANDLE handle);
/**
* @brief 获取分析对象
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetThermometryRule(SGP_HANDLE handle, SGP_RULE_ARRAY *output);
/**
* @brief 设置红外图像效果参数
* @param
* handle 输入参数,传入设备对象
* type 输入参数,参数类型
* value 输入参数,参数值
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetIrImageEffectParam(SGP_HANDLE handle, SGP_IR_IMAGE_EFFECT_ENUM type, int value);
/**
* @brief 获取红外图像效果参数
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetIrImageEffectParam(SGP_HANDLE handle, SGP_IAMGE_EFFECT_PARAM_IR_CONFIG *output);
/**
* @brief 设置可见光图像效果参数
* @param
* handle 输入参数,传入设备对象
* type 输入参数,参数类型
* value 输入参数,参数值
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetVlImageEffectParam(SGP_HANDLE handle, SGP_VL_IMAGE_EFFECT_ENUM type, int value);
/**
* @brief 获取可见光图像效果参数
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetVlImageEffectParam(SGP_HANDLE handle, SGP_IAMGE_EFFECT_PARAM_VL_CONFIG *output);
/**
* @brief 设置图像融合
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetImageFusion(SGP_HANDLE handle, SGP_IMAGE_FUSION input);
/**
* @brief 获取图像融合
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetImageFusion(SGP_HANDLE handle, SGP_IMAGE_FUSION *output);
/**
* @brief 设置网络信息
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetNetInfo(SGP_HANDLE handle, SGP_NET_INFO input);
/**
* @brief 获取网络信息
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetNetInfo(SGP_HANDLE handle, SGP_NET_INFO *output);
/**
* @brief 设置端口信息
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetPortInfo(SGP_HANDLE handle, SGP_PORT_INFO input);
/**
* @brief 获取端口信息
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetPortInfo(SGP_HANDLE handle, SGP_PORT_INFO *output);
/**
* @brief 设置录制信息
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetRecordInfo(SGP_HANDLE handle, SGP_RECORD_INFO input);
/**
* @brief 获取录制信息
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetRecordInfo(SGP_HANDLE handle, SGP_RECORD_INFO *output);
/**
* @brief 设置屏蔽区域
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetShieldArea(SGP_HANDLE handle, SGP_SHIELD_AREA_INFO input);
/**
* @brief 获取屏蔽区域
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetShieldArea(SGP_HANDLE handle, SGP_SHIELD_AREA_INFO *output);
/**
* @brief 设置全局温度告警
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetColdHotTrace(SGP_HANDLE handle, SGP_COLD_HOT_TRACE_INFO input);
/**
* @brief 获取全局温度告警
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetColdHotTrace(SGP_HANDLE handle, SGP_COLD_HOT_TRACE_INFO *output);
/**
* @brief 设置分析对象告警
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetTempAlarm(SGP_HANDLE handle, SGP_TEMP_ALARM_INFO input);
/**
* @brief 获取分析对象告警
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetTempAlarm(SGP_HANDLE handle, SGP_TEMP_ALARM_INFO *output);
/**
* @brief 设置视频参数
* @param
* handle 输入参数,传入设备对象
* type 输入参数,参数类型
* value 输入参数,参数值
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetVideoParam(SGP_HANDLE handle, SGP_VIDEO_PARAM_ENUM type, SGP_VIDEO_PARAM input);
/**
* @brief 获取视频参数
* @param
* handle 输入参数,传入设备对象
* type 输入参数,视频类别
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetVideoParam(SGP_HANDLE handle, SGP_VIDEO_PARAM_ENUM type, SGP_VIDEO_PARAM *output);
/**
* @brief 设置网络异常
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetNetException(SGP_HANDLE handle, SGP_NET_EXCEPTION_INFO input);
/**
* @brief 获取网络异常
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetNetException(SGP_HANDLE handle, SGP_NET_EXCEPTION_INFO *output);
/**
* @brief 设置非法访问
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetAccessViolation(SGP_HANDLE handle, SGP_ACCESS_VIOLATION_INFO input);
/**
* @brief 获取非法访问
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetAccessViolation(SGP_HANDLE handle, SGP_ACCESS_VIOLATION_INFO *output);
/**
* @brief 设置邮件信息
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetEmilInfo(SGP_HANDLE handle, SGP_EMAIL_INFO input);
/**
* @brief 获取邮件信息
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetEmilInfo(SGP_HANDLE handle, SGP_EMAIL_INFO *output);
/**
* @brief 设置补光灯信息
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetFillLight(SGP_HANDLE handle, SGP_FILL_LIGHT_INFO input);
/**
* @brief 获取补光灯信息
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetFillLight(SGP_HANDLE handle, SGP_FILL_LIGHT_INFO *output);
/**
* @brief 设置融合状态
* @param
* handle 输入参数,传入设备对象
* input 输入参数,mode红外模式: 0:单光红外; 1:双光红外
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetInfraredMode(SGP_HANDLE handle, int input);
/**
* @brief 获取融合状态
* @param
* handle 输入参数,传入设备对象
* output 输出参数,mode红外模式: 0:单光红外; 1:双光红外
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetInfraredMode(SGP_HANDLE handle, int *output);
/**
* @brief 设置蜂鸣器状态
* @param
* handle 输入参数,传入设备对象
* input 输入参数,silent 0:非静音; 1:静音
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetSilentMode(SGP_HANDLE handle, int input);
/**
* @brief 获取蜂鸣器状态
* @param
* handle 输入参数,传入设备对象
* output 输出参数,silent 0:非静音; 1:静音
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetSilentMode(SGP_HANDLE handle, int *output);
/**
* @brief 设置报警输入
* @param
* handle 输入参数,传入设备对象
* input 输入参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetAlarmInput(SGP_HANDLE handle, SGP_ALARM_INPUT_INFO input);
/**
* @brief 获取报警输入
* @param
* handle 输入参数,传入设备对象
* output 输出参数
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetAlarmInput(SGP_HANDLE handle, SGP_ALARM_INPUT_INFO *output);
/**
* @brief 调焦
* @param
* handle 输入参数,传入设备对象
* type 输入参数
* value 位置
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SetFocus(SGP_HANDLE handle, SGP_FOCUS_TYPE type, int value);
/**
* @brief 获取电机位置
* @param
* handle 输入参数,传入设备对象
* output 输出参数,电机位置
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_GetMotorPosition(SGP_HANDLE handle, int *output);
/**
* @brief 恢复出厂设置
* @param
* handle 输入参数,传入设备对象
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_FactoryReset(SGP_HANDLE handle);
/**
* @brief 设置串口指令
* @param
* handle 输入参数,传入设备对象
* input 输入参数,串口指令
* @return 成功返回SGP_OK,失败返回错误码
* @note
*/
SGP_API int SGP_SendUart(SGP_HANDLE handle, const char *input);
/**
* @brief 注册温度告警回调函数
* @param
* handle 输入参数,传入设备对象
* callback 输入参数
* pUser 输入参数
* @return 无
* @note
*/
SGP_API void SGP_RegisterTempAlarmCallback(SGP_HANDLE handle, SGP_TEMPALARMCALLBACK callback, void *pUser);
/**
* @brief 注册内存已满回调函数
* @param
* handle 输入参数,传入设备对象
* callback 输入参数
* pUser 输入参数
* @return 无
* @note
*/
SGP_API void SGP_RegisterMemoryFullCallback(SGP_HANDLE handle, SGP_MEMORYFULLCALLBACK callback, void *pUser);
/**
* @brief 注册存储故障回调函数
* @param
* handle 输入参数,传入设备对象
* callback 输入参数
* pUser 输入参数
* @return 无
* @note
*/
SGP_API void SGP_RegisterStorageErrorCallback(SGP_HANDLE handle, SGP_STORAGEERRORCALLBACK callback, void *pUser);
/**
* @brief 注册推流异常回调函数
* @param
* handle 输入参数,传入设备对象
* callback 输入参数
* pUser 输入参数
* @return 无
* @note
*/
SGP_API void SGP_RegisterRtspErrorCallback(SGP_HANDLE handle, SGP_RTSPERRORCALLBACK callback, void *pUser);
/**
* @brief 注册非法访问回调函数
* @param
* handle 输入参数,传入设备对象
* callback 输入参数
* pUser 输入参数
* @return 无
* @note
*/
SGP_API void SGP_RegisterAccessViolationCallback(SGP_HANDLE handle, SGP_ACCESSVIOLATIONCALLBACK callback, void *pUser);
/**
* @brief 注册网络异常回调函数
* @param
* handle 输入参数,传入设备对象
* callback 输入参数
* pUser 输入参数
* @return 无
* @note
*/
SGP_API void SGP_RegisterNetworkErrorCallback(SGP_HANDLE handle, SGP_NETWORKERRORCALLBACK callback, void *pUser);
/**
* @brief 注册外部告警回调函数
* @param
* handle 输入参数,传入设备对象
* callback 输入参数
* pUser 输入参数
* @return 无
* @note
*/
SGP_API void SGP_RegisterAlarmInputCallback(SGP_HANDLE handle, SGP_ALARMINPUTCALLBACK callback, void *pUser);
SGPSDK_STDC_END |
<?php
/**
* Template part for displaying page content in page.php
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Magazine_Saga
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="entry-content">
<?php
if(has_post_thumbnail()){
echo '<div class="magazine-saga-ft-img">'.get_the_post_thumbnail(get_the_ID(),'full').'</div>';
}
the_content();
wp_link_pages( array(
'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'magazine-saga' ),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->
<?php if ( get_edit_post_link() ) : ?>
<footer class="entry-footer">
<?php
edit_post_link(
sprintf(
wp_kses(
/* translators: %s: Name of current post. Only visible to screen readers */
__( 'Edit <span class="screen-reader-text">%s</span>', 'magazine-saga' ),
array(
'span' => array(
'class' => array(),
),
)
),
get_the_title()
),
'<span class="edit-link">',
'</span>'
);
?>
</footer><!-- .entry-footer -->
<?php endif; ?>
</article><!-- #post-<?php the_ID(); ?> --> |
<?php
namespace Lunacms\Forums\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Lunacms\Forums\Tags\Models\Tag;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\Lunacms\Forums\Tags\Models\Tag>
*/
class TagFactory extends Factory
{
protected $model = Tag::class;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'name' => $this->faker->word,
'slug' => $this->faker->unique()->slug
];
}
} |
#include <iostream>
using namespace std;
class Super
{
private:
int private_field = 10;
protected:
int protected_field = 20;
public:
int public_field = 30;
// method to access private member
int getPrivateField()
{
return private_field;
}
};
class PublicSub : public Super
{
public:
// method to access protected member from Super class
int getProtectedField()
{
return protected_field;
}
};
int main()
{
PublicSub obj;
cout << "Private =" << obj.getPrivateField() << endl;
cout << "Protected =" << obj.getProtectedField() << endl;
cout << "Public = " << obj.public_field;
return 0;
} |
lista_original = [1,2,3,4]
id_or = id(lista_original)
lista_copia = lista_original
id_cop = id(lista_copia)
print(f"Lista original: {lista_original}")
print(f"Referencia lista original: {id_or}")
print(f"Tipo lista original: {type(lista_original)}")
print("*"*80)
print("\n")
print(f"Lista copia: {lista_copia}")
print(f"Referencia lista copia: {id_cop}")
print(f"Tipo lista copia: {type(lista_copia)}")
print("*"*80)
print("\n")
print("Son los id de ambas listas iguales ?")
if id_or == id_cop:
print("Si son iguales")
elif id_or != id_cop:
print("No son iguales")
print("*"*80)
print("\n")
print("Agregamos en ambas listas valores y comprobamos la relacion")
lista_original.append(5)
lista_copia.append(6)
print(f"Lista original: {lista_original}")
print(f"Referencia lista original: {id_or}")
print(f"Tipo lista original: {type(lista_original)}")
print("*"*80)
print("\n")
print(f"Lista copia: {lista_copia}")
print(f"Referencia lista copia: {id_cop}")
print(f"Tipo lista copia: {type(lista_copia)}")
print("*"*80)
print("\n")
print("Son los id de ambas listas iguales ?")
if id_or == id_cop:
print("Si son iguales")
elif id_or != id_cop:
print("No son iguales")
print("*"*80)
print("\n")
print("Ahora realizaremos el proceso con copy")
listacopy = lista_original.copy()
id_cop2 = id(listacopy)
print(f"Lista original: {lista_original}")
print(f"Referencia lista original: {id_or}")
print(f"Tipo lista original: {type(lista_original)}")
print("*"*80)
print("\n")
print(f"Lista copia mediante la funcion copy: {listacopy}")
print(f"Referencia lista copy: {id_cop2}")
print(f"Tipo lista mediante la funcion copy: {type(listacopy)}")
print("Son los id de ambas listas iguales ?")
if id_or == id_cop2:
print("Si son iguales")
elif id_or != id_cop2:
print("No son iguales")
comp = lista_original is lista_copia
print(f"Son la lista original y la lista copia iguales?: {comp}")
print("*"*80)
print("\n")
print("Prueba de modificacion entre la lista original y la lista generada con copy")
lista_original.append(7)
listacopy.append(8)
print(f"Lista original: {lista_original}")
print(f"Referencia lista original: {id_or}")
print(f"Tipo lista original: {type(lista_original)}")
print("*"*80)
print("\n")
print(f"Lista copia mediante la funcion copy: {listacopy}")
print(f"Referencia lista copy: {id_cop2}")
print(f"Tipo lista mediante la funcion copy: {type(listacopy)}")
print("Son los id de ambas listas iguales ?")
if id_or == id_cop2:
print("Si son iguales")
elif id_or != id_cop2:
print("No son iguales")
comp2 = lista_original is listacopy
print(f"Son la lista original y la lista generada con copy iguales: {comp2}")
print("*"*80)
print("\n")
print("Prueba usando slicing [copiado total]")
lista_slice = lista_original[:]
id_ls = id(lista_slice)
print(f"Lista original: {lista_original}")
print(f"Referencia lista original: {id_or}")
print(f"Tipo lista original: {type(lista_original)}")
print("*"*80)
print("\n")
print(f"Lista copia mediante la funcion slice: {lista_slice}")
print(f"Referencia lista copy: {id_ls}")
print(f"Tipo lista mediante la funcion slice: {type(lista_slice)}")
print("Son los id de ambas listas iguales ?")
if id_or == id_ls:
print("Si son iguales")
elif id_or != id_ls:
print("No son iguales")
comp3 = lista_original is lista_copia
print(f"Son la lista original y la lista slice iguales?: {comp3}")
print("*"*80)
print("\n")
print("Prueba usando slicing [copiado parcial]")
lista_slice = lista_original[1:4]
id_ls = id(lista_slice)
print(f"Lista original: {lista_original}")
print(f"Referencia lista original: {id_or}")
print(f"Tipo lista original: {type(lista_original)}")
print("*"*80)
print("\n")
print(f"Lista copia mediante la funcion slice: {lista_slice}")
print(f"Referencia lista copy: {id_ls}")
print(f"Tipo lista mediante la funcion slice: {type(lista_slice)}")
print("Son los id de ambas listas iguales ?")
if id_or == id_ls:
print("Si son iguales")
elif id_or != id_ls:
print("No son iguales")
comp3 = lista_original is lista_copia
print(f"Son la lista original y la lista slice iguales?: {comp3}")
print("*"*80)
print("\n")
print("Prueba usando deep copy")
import copy
lista_deepC = copy.deepcopy(lista_original)
id_deC = id(lista_deepC)
print(f"Lista original: {lista_original}")
print(f"Referencia lista original: {id_or}")
print(f"Tipo lista original: {type(lista_original)}")
print("*"*80)
print("\n")
print(f"Lista copia mediante la funcion deepCopy: {lista_deepC}")
print(f"Referencia lista deep copy: {id_deC}")
print(f"Tipo lista mediante la funcion deepCopy: {type(lista_deepC)}")
print("Son los id de ambas listas iguales ?")
if id_or == id_deC:
print("Si son iguales")
elif id_or != id_deC:
print("No son iguales")
comp4 = lista_original is lista_deepC
print(f"Son la lista original y la lista deepCopy iguales?: {comp4}")
print("*"*80)
print("\n")
# Ejemplos varios
# Asignacion directa, los cambios se reflejan en ambas
listaOriginal = [0,1,2,3,4]
listaCopia = listaOriginal
listaCopia[0] = 100
print(f"Lista original: {listaOriginal}")
print(f"Lista copia: {listaCopia}")
print("*"*80)
print("\n")
# Con la funcion copy, los cambios se reflejan en la lista donde se haga el cambio
listaCopia2 = listaOriginal.copy()
listaCopia2[1] = -1
print(f"Lista original: {listaOriginal}")
print(f"Lista alterada usando la funcion Copy: {listaCopia2}")
print("*"*80)
print("\n")
# Con slice, los cambios se reflejan en la lista donde se haga el cambio
listaCopia3 = listaOriginal[:]
listaCopia3[2] = -5
print(f"Lista original: {listaOriginal}")
print(f"Lista alterada usando slice: {listaCopia3}")
print("*"*80)
print("\n")
# Con el modulo Copy, los cambios se reflejan en la lista donde se haga el cambio
listaA = [[1,2],[3,4],[5,6]]
listaCopia4 = copy.deepcopy(listaA)
listaCopia4[0][1] = -8
print(f"Lista original: {listaA}")
print(f"Lista alterada usando el modulo Copy: {listaCopia4}")
print("*"*80)
print("\n") |
<?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Http\Requests\Memorandum\AddFormValidation;
use App\Http\Requests\Memorandum\EditFormValidation;
use App\Repositories\Memorandum\MemorandumInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class MemorandumController extends BaseController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
protected $base_route = 'dashboard.memorandum';
protected $view_path = 'dashboard.memorandum';
protected $panel = 'Memorandum Us';
protected $folder = 'memorandum';
protected $folder_path;
public function __construct(MemorandumInterface $memorandum)
{
$this->middleware('auth');
$this->middleware('super-admin');
$this->memorandum = $memorandum;
$this->folder_path = 'uploads'.DIRECTORY_SEPARATOR.$this->folder;
}
public function index()
{
$data = [];
$data['memoranda'] = $this->memorandum->all();
return view(parent::commonData($this->view_path.'.index'),compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view(parent::commonData($this->view_path.'.create'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(AddFormValidation $request)
{
$input = $request->all();
$input = parent::checkForDefaults($input);
$this->memorandum->save($input);
Session::flash('success',$this->panel.' created successfully');
return redirect()->route($this->base_route);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$data=[];
$data['memorandum'] = $this->memorandum->findById($id);
return view(parent::commonData($this->view_path.'.show'),compact('data'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$data= [];
$data['memorandum'] = $this->memorandum->findById($id);
return view(parent::commonData($this->view_path.'.edit'),compact('data'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(EditFormValidation $request, $id)
{
$input = $request->all();
$input = parent::checkForDefaults($input);
$this->memorandum->renew($id,$input);
Session::flash('success',$this->panel.' updated successfully');
return redirect()->route($this->base_route);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->memorandum->remove($id);
Session::flash('error',$this->panel.' deleted.');
return redirect()->route($this->base_route);
}
} |
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { createGlobalStyle } from 'styled-components';
import 'remixicon/fonts/remixicon.css';
import {
HashRouter,
Routes,
Route,
} from 'react-router-dom';
import { Products } from './pages/Products';
import { Cart } from './pages/Cart';
import { Provider } from 'react-redux';
import { store } from './redux/store';
export const GlobalStyle = createGlobalStyle`
:root {
--primary-color: #0a1d37;
--heading-fontSize: 2rem;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#shadow-host-companion {
display: none;
}
body {
font-family: "Montserrat", sans-serif;
}
h1,
h2,
h3,
h4,
h5,
h6,
p {
padding: 0;
margin: 0;
}
p {
color: var(--small-text-color);
font-size: 1rem;
}
h1,
h2 {
font-size: var(--heading-fontSize);
}
ul {
list-style: none;
}
a {
text-decoration: none;
color: unset;
}
img {
width: 100%;
}
section {
padding: 60px 0px;
@media only screen and (max-width: 768px) {
padding: 40px 0px;
}
}
.section__title {
color: var(--primary-color);
font-weight: 600;
}
`;
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<Provider store={store}>
<GlobalStyle />
<HashRouter>
<Routes>
<Route path="/" element={<App />}>
<Route index element={<Products />} />
<Route path="products" element={<Products />} />
<Route path="cart" element={<Cart />} />
</Route>
</Routes>
</HashRouter >
</Provider>
</React.StrictMode>
); |
const express = require("express");
const app = express();
require("dotenv").config();
const User = require("./models/user");
const accountController = require("./controllers/accountController");
const LocalStrategy = require("passport-local").Strategy;
const bodyParser = require("body-parser");
const passport = require("passport");
const bcrypt = require("bcrypt");
app.use(bodyParser.urlencoded({ extended: false }));
const mongoose = require("mongoose");
passport.use(
new LocalStrategy(async function verify(username, password, done) {
await User.findOne({ username: username })
.then((user) => {
if (!user)
return done(null, false, { message: "No user with that email" });
if (bcrypt.compareSync(password, user.password)) {
return done(null, user);
} else return done(null, false, { message: "wrong password" });
})
.catch((err) => {
done(err);
});
})
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((userId, done) => {
User.findById(userId)
.then((user) => {
done(null, user);
})
.catch((err) => done(err));
});
app.use(passport.initialize());
require("./middleware/auth.js")();
app.get("/", (req, res) => {
res.send("Introduction JWT Auth");
});
app.get(
"/profile",
passport.authenticate("jwt", { session: false }),
accountController.profile
);
app.post(
"/login",
passport.authenticate("local", {
session: false,
}),
accountController.login
);
app.post("/register", accountController.register);
mongoose.connect(process.env.DB_URI).then(() => {
console.log("Database connected successfully");
app.listen(4000, () => {
console.log("Server started.");
});
}); |
package com.cfbenchmarks.interview.manager;
import com.cfbenchmarks.interview.model.match.MatchResult;
import com.cfbenchmarks.interview.model.order.Order;
import com.cfbenchmarks.interview.model.order.Side;
import java.util.List;
import java.util.Optional;
// TODO: Not null params
/**
* All functions in this class should throw if given null parameters
*/
public interface OrderBookManager {
/**
* Add new order
*
* <p>Orders for the same instrument, on the same side, with the same price should be kept in the
* order as they arrive
*
* @param order new order to add <br>
* @return MatchResult the result of any matching that the order triggered
* @see Order
*/
MatchResult addOrder(Order order);
/**
* Delete an existing order. Returns false if no such order exists
*
* @param orderId unique identifier of existing order
* @return True if the order was successfully deleted, false otherwise
*/
boolean deleteOrder(String orderId);
/**
* Get the best price for the instrument and side.
*
* <p>For buy orders - the highest price For sell orders - the lowest price
*
* @param instrument identifier of an instrument
* @param side either buy or sell
* @return the best price, or Optional.empty() if there're no orders for the instrument on this
* side
*/
Optional<Long> getBestPrice(String instrument, Side side);
/**
* Get all orders for the instrument on given side with given price
*
* <p>Result should contain orders in the same order as they arrive
*
* @param instrument identifier of an instrument
* @param side either buy or sell
* @param price requested price level
* @return all orders, or empty list if there are no orders for the instrument on this side with
* this price
*/
List<Order> getOrdersAtLevel(String instrument, Side side, long price);
} |
import 'package:http/http.dart';
import 'dart:convert';
import 'package:intl/intl.dart';
class WorldTime {
String? location;
String? time;
String? flag;
String? url;
WorldTime({this.location, this.flag, this.url});
Future<void> getTime() async {
try{
Response response = await
get(Uri.parse('http://worldtimeapi.org/api/timezone/$url'));
Map timeData = jsonDecode(response.body);
String dateTime = timeData['datetime'];
String offset = timeData['utc_offset'];
String offsetHours = offset.substring(1, 3);
String offsetMinutes = offset.substring(4, 6);
DateTime currenttime = DateTime.parse(dateTime);
currenttime = currenttime.add(Duration(minutes:
int.parse(offsetMinutes), hours: int.parse(offsetHours)));
time = DateFormat.jm().format(currenttime);
}catch(e){
print("caught error : ${e}");
}
}
} |
import { useState } from "react";
import { useAsync, useFetchAndLoad } from "./";
import { OrderType } from "../models";
import { createBrandAdapter } from "../adapters";
import { SelectChangeEvent } from "@mui/material";
export const useFetchBrands = (axiosCallback: any) => {
const { loading, callEndpoint } = useFetchAndLoad();
const [brands, setBrands] = useState([]);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const [order, setOrder] = useState(OrderType.ASC);
const getBrandsData = async () => {
const result = await callEndpoint(axiosCallback(page, order));
return result;
};
const adaptBrands = (data: any) => {
if (data) {
const brands = data.data.brands.map((brand: any) =>
createBrandAdapter(brand)
);
const totalPages = data.data.totalPages;
setBrands(brands);
setTotalPages(totalPages);
}
};
const handleChangeBrandPage = (
_event: React.ChangeEvent<unknown>,
value: number
) => {
setPage(value);
};
const handleChangeBrandOrder = (event: SelectChangeEvent) => {
setOrder(event.target.value as OrderType);
};
useAsync(getBrandsData, adaptBrands, () => {}, [page, order]);
return {
isLoadingBrands: loading,
brands: brands,
brandTotalPages: totalPages,
brandPage: page,
brandOrder: order,
handleChangeBrandPage,
handleChangeBrandOrder,
};
}; |
import { Box, Grid, useColorModeValue } from '@chakra-ui/react';
import { Suspense, useRef } from 'react';
import { Outlet } from 'react-router-dom';
import useWindowDimensions from '../../hooks/useWindowDimensions';
import useBreakpointValue from '../../hooks/wrappers/useBreakpointValue';
import PortalRefContext from '../../store/ref-context';
import ImageFallback from '../misc/ImageFallback';
import NavBar from '../nav-bar/NavBar';
import OfflineAlert from './OfflineAlert';
const AppShell: React.FC = () => {
const { windowHeight } = useWindowDimensions();
const ref = useRef<HTMLDivElement>(null);
const portalRef = useRef<HTMLDivElement>(null);
const rootPortalRef = useRef<HTMLDivElement>(null);
const bg = useColorModeValue('white', 'black');
const isMobile = useBreakpointValue({ base: true, md: false });
const portalBoxStyle = {
pointerEvents: 'none',
gridArea: 'content',
gridTemplate: '100% / 100%',
position: 'relative',
'& > *': {
gridArea: '1 / 1',
},
};
const shellStyle = {
width: '100%',
height: `${windowHeight}px`,
overflow: 'hidden',
position: 'relative',
gridTemplateAreas: isMobile ? `"content" "navbar"` : `"navbar" "content"`,
gridTemplateRows: isMobile ? '1fr auto' : 'auto 1fr',
gridTemplateColumns: '100%',
};
return (
<Grid sx={shellStyle} ref={rootPortalRef}>
<PortalRefContext.Provider value={rootPortalRef}>
<NavBar ref={ref} />
</PortalRefContext.Provider>
<Box bgColor={bg} overflow="auto" gridArea="content">
<PortalRefContext.Provider value={portalRef}>
<OfflineAlert />
<Suspense fallback={<ImageFallback fill />}>
<Outlet />
</Suspense>
</PortalRefContext.Provider>
</Box>
<Grid sx={portalBoxStyle} ref={portalRef} />
</Grid>
);
};
export default AppShell; |
+++
title = "🔐Διαχειριστές κωδικών - Password Managers"
date = 2023-01-30T15:21:04+02:00
# weight = 1
# aliases = ["/first"]
tags = ["passwords", "security","password_manager","ασφάλεια","διαχειριστές κωδικών"]
# author = ["Me", "You"]
categories = ["Ασφάλεια"]
showToc = true
TocOpen = false
draft = false
hidemeta = false
comments = true
description = "Μια σύνοψη"
disableHLJS = false # to disable highlightjs
disableShare = false
hideSummary = false
searchHidden = false
ShowReadingTime = true
ShowBreadCrumbs = true
ShowPostNavLinks = true
ShowWordCount = true
ShowRssButtonInSectionTermList = true
UseHugoToc = true
[cover]
image = "https://images.unsplash.com/photo-1627019675516-5468b934815c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=605&q=80" # image path/url
# alt = "<alt text>"
caption = "Photo by [Jason Dent](https://unsplash.com/@jdent) on [Unsplash](https://unsplash.com/)"
# relative = false
# hidden = true
[editPost]
URL = "https://github.com/aggellos2001/aggellos2001.github.io/tree/main/content"
Text = "Προτείνετε αλλαγές" # edit text
appendFilePath = true # to append file path to Edit link
+++
> Διαχειριστές κωδικών γνωστοί και ως Password Managers στα αγγλικά.
## Γιατί;
Στις μέρες είναι συχνό φαινόμενο από πολλούς η επαναχρησιμοποίηση των ίδιων κωδικών πρόσβασης σε πολλές ιστοσελίδες κάτι το οποίο αποτελεί κακή πρακτική για την ασφάλεια.
Το 2016 έλαβα μια ειδοποίηση από την Google ότι κάποιος προσπαθεί να συνδεθεί με τον κωδικό μου στο email. Εκείνη την στιγμή συνειδητοποίησα ότι χρησιμοποιώ τον ίδιο κωδικό παντού και ότι πρέπει να δράσω άμεσα.
Για να μην βρεθεί κανείς στην αντίστοιχη θέση αποφάσισα να γράψω αυτό το (ελπίζω σύντομο) άρθρο μιας και γενικά στα Ελληνικά δεν υπάρχουν αρκετές πληροφορίες σχετικές με το θέμα.
Καταρχήν, οι διαχειριστές κωδικών είναι, όπως λέει το όνομα τους, λογισμικά που έχουν σαν σκοπό την ασφαλή διαχείριση των κωδικών πρόσβασης που χρησιμοποιούμε στις διάφορες υπηρεσίες όπως το e-banking ή το email για παράδειγμα.
Όπως προαναφέρθηκε, είναι επιτακτικό να χρησιμοποιούμε ξεχωριστούς και ασφαλείς κωδικούς σε κάθε διαφορετική υπηρεσία που χρησιμοποιούμε ώστε:
>Εφόσον παραβιαστεί η βάση δεδομένων ή ο λογαριασμός που κατέχει ο χρήστης σε μια ιστοσελίδα Α, δεν θα πρέπει να μπορεί να παραβιαστεί ένας λογαριασμός του χρήστη σε μια ιστοσελίδα Β με βάση την γνώση που προέκυψε από την ιστοσελίδα Α.
Δηλαδή με απλά λόγια αν παραβιαστεί το Facebook να μην μπορεί να παραβιαστεί και το Gmail.
Για παράδειγμα, ένας ασφαλής κωδικός μήκους 18 χαρακτήρων που δημιουργείται αυτόματα από ένα τέτοιο λογισμικό είναι ο εξής:
>h2f3tN^RXAdPNCZz5$
Αυτός ο κωδικός είναι ασφαλής γιατί έχει μεγάλη εντροπία (μεγάλη τυχαιότητα) σε αντίθεση με τον κωδικό πχ. 123456789. Αυτό σημαίνει ότι ένας hacker (κυβερνοεγκληματίας) δεν μπορεί να “μαντέψει "εύκολα τον κωδικό.
Από τα κυριότερα πλεονεκτήματα των διαχειριστών κωδικών πρόσβασης είναι ότι ο χρήστης πρέπει να θυμάται μόνο 1 κωδικό πρόσβασης τον λεγόμενο “κύριο κωδικό” ή “master password”. Με αυτόν τον κωδικό μπορεί να έχει πρόσβαση σε όλους τους υπόλοιπους κωδικούς.
Επιπλέον οι κωδικοί είναι διαθέσιμοι από πολλές συσκευές που κατέχει ο χρήστης οι οποίες συγχρονίζονται αυτόματα σε κάθε αλλαγή.
## Πώς;
Αφού είδαμε γιατί πρέπει να έχουμε ξεχωριστούς κωδικούς στα διάφορα website που χρησιμοποιούμε και τι μας προσφέρουν οι διαχειριστές κωδικών, είναι ώρα να δούμε τι επιλογές υπάρχουν στην αγορά.
Αρχικά έχουμε 2 δωρεάν προϊόντα από μεγάλες εταιρίες όπως η Google & Apple.
1. [Google Password Manager](https://support.google.com/accounts/answer/6197437) (Δωρεάν)
2. [Apple iCloud Keychain](https://support.apple.com/el-gr/HT204085) (Δωρεάν)
Στα παραπάνω link υπάρχουν πληροφορίες για το πώς κάποιος μπορεί να τα ενεργοποιήσει και να τα χρησιμοποιήσει στις συσκευές του.
Επίσης υπάρχουν και διάφορες εταιρίες που παρέχουν πιο εξελιγμένα προγράμματα που εκτός από την απλή αποθήκευση κωδικών, μπορούν να αποθηκεύσουν και χρεωστικές / πιστωτικές κάρτες, ταυτότητες, να κάνουν κοινή χρήση των κωδικών με τρίτους, και γενικά παρέχουν επιπρόσθετες υπηρεσίες που βελτιώνουν την εμπειρία των χρηστών.
Δύο από τις κορυφαίες εταιρίες στον χώρο με πληθώρα πιστοποιήσεων για την ασφάλεια που παρέχουν στα δεδομένα των χρηστών είναι οι εξής:
1. [Bitwarden](https://bitwarden.com/) (Δωρεάν ή ~10€/χρόνο)
2. [1Password](https://1password.eu/) (~40€ το χρόνο με ΦΠΑ)
Συνοπτικά, το Bitwarden, είναι λογισμικό ανοιχτού κώδικα και δωρεάν για απεριόριστους κωδικούς και συσκευές ενώ με ~10€ τον χρόνο ο χρήστης έχει επιπρόσθετες παροχές (πχ. μπορεί να προσθέσει 2FA tokens). Επίσης με περίπου 40€ διατίθεται και το οικογενειακό πλάνο για προσθήκη της οικογένειας έως 6 άτομα ώστε να υπάρχει εύκολος διαμοιρασμός κωδικών μεταξύ των μελών. Περισσότερα εδώ: https://bitwarden.com/pricing/.
Σε αντίθεση το 1Password, είναι περίπου 40€ τον χρόνο χωρίς να υπάρχει δωρεάν πλάνο για προσωπική χρήση ενώ περίπου 70€ για οικογένειες έως 6 άτομα σύνολο (1+5).
Υπάρχουν βίντεο που εμβαθύνουν στις διαφορές αυτών των προϊόντων στο YouTube και σε διάφορες σελίδες. Για απλή χρήση με μηδενικό κόστος συστήνω την δωρεάν έκδοση του Bitwarden.
## Συμπερασματικά
Η χρήση μοναδικών και ισχυρών κωδικών πρόσβασης στο διαδίκτυο είναι πολύ σημαντική, αλλά λόγω του μεγάλου πλήθους των υπηρεσιών που χρησιμοποιούνται καθημερινά και απαιτούν την δημιουργία λογαριασμών, η χρήση ισχυρών κωδικών είναι αδύνατη. Σε αυτό το πρόβλημα έρχονται να βοηθήσουν τα λογισμικά διαχείρισης κωδικών.
Επόμενο βήμα είναι χρήση 2FA (Two Factor Authentication) για περαιτέρω ενίσχυση της ασφάλειας μας.
Ευχαριστώ για τον χρόνο σας. |
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
/* Document
/**
* 1. Correct the line height in all browsers.
* 2. Prevent adjustments of font size after orientation changes in iOS.
*/
html {
line-height: 1.15;
/* 1 */
-webkit-text-size-adjust: 100%;
/* 2 */
}
/* Sections
/**
* Remove the margin in all browsers.
*/
body {
margin: 0;
}
/**
* Render the `main` element consistently in IE.
*/
main {
display: block;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/* Grouping content
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box;
/* 1 */
height: 0;
/* 1 */
overflow: visible;
/* 2 */
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
/* Text-level semantics
/**
* Remove the gray background on active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* 1. Remove the bottom border in Chrome 57-
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none;
/* 1 */
text-decoration: underline;
/* 2 */
text-decoration: underline dotted;
/* 2 */
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/* Embedded content
/**
* Remove the border on images inside links in IE 10.
*/
img {
border-style: none;
}
/* Forms
/**
* 1. Change the font styles in all browsers.
* 2. Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
/* 1 */
font-size: 100%;
/* 1 */
line-height: 1.15;
/* 1 */
margin: 0;
/* 2 */
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input {
/* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select {
/* 1 */
text-transform: none;
}
/**
* Correct the inability to style clickable types in iOS and Safari.
*/
button,
[type=button],
[type=reset],
[type=submit] {
-webkit-appearance: button;
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type=button]::-moz-focus-inner,
[type=reset]::-moz-focus-inner,
[type=submit]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type=button]:-moz-focusring,
[type=reset]:-moz-focusring,
[type=submit]:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* Correct the padding in Firefox.
*/
fieldset {
padding: 0.35em 0.75em 0.625em;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box;
/* 1 */
color: inherit;
/* 2 */
display: table;
/* 1 */
max-width: 100%;
/* 1 */
padding: 0;
/* 3 */
white-space: normal;
/* 1 */
}
/**
* Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
vertical-align: baseline;
}
/**
* Remove the default vertical scrollbar in IE 10+.
*/
textarea {
overflow: auto;
}
/**
* 1. Add the correct box sizing in IE 10.
* 2. Remove the padding in IE 10.
*/
[type=checkbox],
[type=radio] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type=number]::-webkit-inner-spin-button,
[type=number]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type=search] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
/**
* Remove the inner padding in Chrome and Safari on macOS.
*/
[type=search]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
/* Interactive
/*
* Add the correct display in Edge, IE 10+, and Firefox.
*/
details {
display: block;
}
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item;
}
/* Misc
/**
* Add the correct display in IE 10+.
*/
template {
display: none;
}
/**
* Add the correct display in IE 10.
*/
[hidden] {
display: none;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
body {
font-size: 0.75rem;
font-family: "Kumbh Sans", sans-serif;
}
h2 {
font-size: 1.2em;
font-weight: 400;
}
/*
This Class Helps with
Center The Flex item vertically
*/
.flex-center-vertical {
align-self: center;
}
/*
This Class Sets Fixed Width to any Element
*/
.fit-content {
width: fit-content;
}
@media (min-width: 991px) {
.fixed-width-300-medium {
width: 300px;
}
}
.align-right {
margin-left: auto;
text-align: right;
}
.align-left {
margin-right: auto;
text-align: left;
}
.align-center {
text-align: center;
margin-left: auto;
margin-right: auto;
}
/*
Prefixer Mixin
Mixin to add Vendor Prefixes to CSS Properties
*/
/*
Overlay Mixin
Mixin To add Basic Overlay properties
*/
/*
Flexbox Mixin
Mixin To Apply Flexbox Properties
*/
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
margin-left: auto;
margin-right: auto;
padding-top: 80px;
padding-bottom: 80px;
padding-left: 15px;
padding-right: 15px;
}
@media (min-width: 749px) {
.container {
padding-top: 0;
padding-bottom: 0;
}
}
.wrapper {
position: relative;
background-color: #fff;
padding-bottom: 30px;
border-radius: 20px;
}
@media (max-width: 749px) {
.wrapper {
background-image: url("../images/bg-pattern-mobile.svg");
background-repeat: no-repeat;
background-position: top center;
}
}
@media (min-width: 750px) {
.wrapper {
display: flex;
justify-content: space-between;
gap: 90px;
padding-top: 0;
padding-bottom: 0;
min-height: 550px;
width: 750px;
background-image: url("../images/illustration-woman-online-desktop.svg");
background-repeat: no-repeat;
background-position: -30% center;
}
}
@media (min-width: 576px) {
.container {
max-width: 540px;
}
}
@media (min-width: 768px) {
.container {
max-width: 720px;
}
}
@media (min-width: 992px) {
.container {
max-width: 960px;
}
}
@media (min-width: 1200px) {
.container {
max-width: 1140px;
}
}
@media (min-width: 1400px) {
.container {
max-width: 1320px;
}
}
.faq {
background-image: linear-gradient(#af67e9, #6565e7);
}
.faq .image-container {
position: relative;
width: 100%;
margin-left: auto;
margin-right: auto;
height: 70px;
transform: translateY(-60%);
}
@media (min-width: 750px) {
.faq .image-container {
flex: 1;
flex-direction: column;
}
}
.faq .women {
width: 237px;
display: block;
margin-left: auto;
margin-right: auto;
transform: translateY(-36%);
}
@media (min-width: 750px) {
.faq .women {
display: none;
}
}
.faq .box {
position: absolute;
top: 401%;
left: -37%;
}
@media (max-width: 749px) {
.faq .box {
display: none;
}
}
.faq .arrow {
position: absolute;
top: 50%;
right: 0;
transform: translate(0, -50%) rotate(180deg);
}
.faq .questions-section {
flex: 1;
padding-left: 15px;
padding-right: 15px;
padding-top: 60px;
}
.faq .questions-section > h1 {
color: #1d1e35;
text-align: center;
margin-top: 0;
margin-bottom: 1em;
}
@media (min-width: 750px) {
.faq .questions-section > h1 {
text-align: left;
}
}
.faq .questions-section li {
list-style: none;
border-bottom: 1px solid #e7e7e9;
}
.faq .questions-section h2 {
position: relative;
color: #1d1e35;
padding-right: 30px;
transition: color 0.5s;
cursor: pointer;
}
.faq .questions-section h2:not(.active):hover {
color: #f47c57;
}
.faq .questions-section p {
color: #787887;
line-height: 1.6;
transition: 0.5s;
max-height: 0px;
overflow: hidden;
}
.faq .questions-section .active {
font-weight: 700;
}
.faq .questions-section .active .arrow {
transform: translate(0, -50%) rotate(0deg);
}
.faq .questions-section .active + p {
max-height: 100px;
}
@media (min-width: 750px) {
.faq .questions-section {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding-top: 0;
}
}
/*# sourceMappingURL=main.css.map */ |
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth/auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
isSubmitted = false;
constructor(private authService: AuthService, private router: Router, private formBuilder: FormBuilder) { }
ngOnInit() {
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
}
get formControls() {
return this.loginForm.controls;
}
login() {
console.log(this.loginForm.value.username);
this.isSubmitted = true;
if(this.loginForm.invalid){
return;
}
this.authService.login(this.loginForm.value);
this.router.navigateByUrl('/home');
}
} |
import { Component } from '@angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { addDays, getHours, getMinutes } from 'date-fns';
import { ConfirmationService, MessageService } from 'primeng/api';
import {
distinctUntilChanged,
filter,
merge,
pipe,
skipWhile,
take,
} from 'rxjs';
import { Event } from 'src/app/api/interfaces/event.interface';
import { EventDay } from 'src/app/api/interfaces/eventDay.interface';
import { EventTag } from 'src/app/api/interfaces/eventTag.interface';
import { Group } from 'src/app/api/interfaces/group.interface';
import { User } from 'src/app/api/interfaces/user.interface';
import { EventService } from 'src/app/pages/admin/services/event.service';
import { Auditory } from '../../../api/interfaces/auditory.interface';
import { AuditoryService } from '../services/auditory.service';
import { EventTagService } from '../services/eventTag.service';
import { GroupService } from '../services/group.service';
import { UserService } from '../services/user.service';
@Component({
selector: 'app-events',
templateUrl: './events.component.html',
styleUrls: ['./events.component.css'],
})
export class AdminEventsComponent {
formDialog = false;
isEditing = false;
events: Event[] = [];
allEventTags: EventTag[] = [];
allAuditories: Auditory[] = [];
allGroups: Group[] = [];
allUsers: User[] = [];
idEditing = '';
form = new FormGroup({
eventTitle: new FormControl<string | null>('', [Validators.required]),
eventDescription: new FormControl<string | null>('', [Validators.required]),
eventOwner: new FormControl<User | null>(null, [Validators.required]),
eventPlaces: new FormControl<number | null>(1, [Validators.required]),
eventGroups: new FormControl<Group[] | null>(null, [Validators.required]),
eventTags: new FormControl<EventTag[] | null>(null, [Validators.required]),
eventPeopleWillCome: new FormControl<User[] | null>(null),
eventPeopleCame: new FormControl<User[] | null>(null),
eventImages: new FormControl<File[] | null>(null),
eventDays: new FormArray<
FormGroup<{
auditory: FormControl<Auditory | null>;
date: FormControl<Date | null>;
}>
>([], [Validators.required]),
});
getAllEventsResponce$ = this.eventService.getAllEventsResponce$;
deleteEventResponce$ = this.eventService.deleteEventResponce$;
updateEventResponce$ = this.eventService.updateEventResponce$;
createEventResponce$ = this.eventService.createEventResponce$;
eventRange: FormControl<Date[] | null>;
previewImagesUrls: SafeUrl[] | undefined;
constructor(
private readonly eventService: EventService,
private readonly userService: UserService,
private readonly auditoryService: AuditoryService,
private readonly eventTagsService: EventTagService,
private readonly groupsService: GroupService,
private messageService: MessageService,
private confirmationService: ConfirmationService,
private domSanitizer: DomSanitizer
) {
eventService.events$.subscribe((events) => {
this.events = events;
});
userService.allUsers$.subscribe((users) => {
this.allUsers = users;
});
auditoryService.auditories$.subscribe((auditories) => {
this.allAuditories = auditories;
});
eventTagsService.eventTags$.subscribe((eventTags) => {
this.allEventTags = eventTags;
});
groupsService.groups$.subscribe((groups) => {
this.allGroups = groups;
});
this.eventRange = new FormControl<[Date, Date] | null>(null, [
Validators.required,
]);
this.eventRange.valueChanges
.pipe(pipe(filter((value) => Boolean(value))))
.subscribe((dates) => {
if (dates === null) {
return;
}
this.form.controls.eventDays.clear();
dates.forEach((date) => {
this.form.controls.eventDays.push(
new FormGroup({
auditory: new FormControl<Auditory | null>(null, [
Validators.required,
]),
date: new FormControl<Date | null>(date, [Validators.required]),
})
);
});
});
merge(this.createEventResponce$, this.updateEventResponce$)
.pipe(distinctUntilChanged())
.subscribe((status) => {
if (status === 'pending') {
this.form.disable();
} else {
this.form.enable();
}
});
}
deleteEvent(event: Event) {
this.confirmationService.confirm({
message: 'Вы действительно хотите данные о мероприятии?',
accept: () => {
this.eventService.deleteEvent(event);
this.deleteEventResponce$
.pipe(
skipWhile((responce) => responce === 'pending'),
take(1)
)
.subscribe((responce) => {
if (responce === 'success') {
this.messageService.add({
severity: 'success',
summary: 'Данные о мероприятии удалены',
});
}
});
},
});
}
editEvent(event: Event) {
this.idEditing = event.id;
this.isEditing = true;
this.formDialog = true;
this.form.reset();
this.previewImagesUrls = event.images;
this.form.patchValue({
eventDays: [],
eventDescription: event.description,
eventGroups: event.groups,
eventOwner: this.allUsers.find((u) => u.id === event.owner.id),
eventPlaces: event.places,
eventTags: event.tags.map(
(t) => this.allEventTags.find((allT) => allT.id === t.id)!
),
eventTitle: event.title,
eventImages: null,
eventPeopleWillCome: event.peopleWillCome.map(
(u) => this.allUsers.find((allU) => allU.id === u.id)!
),
eventPeopleCame: event.peopleCame.map(
(u) => this.allUsers.find((allU) => allU.id === u.id)!
),
});
this.eventRange.setValue(event.days.map((d) => new Date(d.date)));
this.form.controls.eventDays.controls.forEach((control, index) => {
control.controls.auditory.patchValue(
this.allAuditories.find((a) => a.id === event.days[index].auditory.id)!
);
control.controls.date.patchValue(new Date(event.days[index].date));
});
}
getFormsControls(): FormArray {
return this.form.controls.eventDays as FormArray;
}
openAddDialog() {
this.formDialog = true;
this.isEditing = false;
this.form.reset();
}
closeDialog() {
this.formDialog = false;
}
handleFileChange(event: any) {
this.form.patchValue({ eventImages: Array.from(event.target.files) });
if (this.form.value.eventImages) {
this.previewImagesUrls = this.form.value.eventImages.map((f) =>
this.domSanitizer.bypassSecurityTrustUrl(URL.createObjectURL(f))
);
}
}
onSubmitForm() {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
const days: EventDay[] = [];
this.form.controls.eventDays.value.forEach((value, i) => {
days.push({
id: '',
date: value.date!,
auditory: value.auditory!,
});
});
const {
eventImages,
eventDescription,
eventGroups,
eventOwner,
eventPlaces,
eventTitle,
eventTags,
eventPeopleCame,
eventPeopleWillCome,
} = this.form.value;
if (this.isEditing) {
this.eventService.updateEvent(
this.idEditing,
eventImages!,
eventTitle!,
eventDescription!,
eventOwner!,
eventPlaces!,
eventGroups!,
days,
eventTags!,
eventPeopleCame!,
eventPeopleWillCome!
);
this.updateEventResponce$
.pipe(
skipWhile((responce) => responce === 'pending'),
take(1)
)
.subscribe((responce) => {
if (responce === 'success') {
this.formDialog = false;
this.messageService.add({
severity: 'success',
summary: 'Данные о мероприятии добавлены',
});
}
});
} else {
this.eventService.createEvent(
eventImages!,
eventTitle!,
eventDescription!,
eventOwner!,
eventPlaces!,
eventGroups!,
days,
eventTags!,
eventPeopleCame!,
eventPeopleWillCome!
);
this.createEventResponce$
.pipe(
skipWhile((responce) => responce === 'pending'),
take(1)
)
.subscribe((responce) => {
if (responce === 'success') {
this.formDialog = false;
this.messageService.add({
severity: 'success',
summary: 'Данные о мероприятии обновлены',
});
}
});
}
}
} |
<template>
<div>
<el-breadcrumb separator="/">
<el-breadcrumb-item :to="{ path: '/newhome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>>权限管理</el-breadcrumb-item>
<el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
<el-card class="box-card">
<el-row>
<el-col>
<el-button type="primary" @click="addUsersVisible = true"
>添加角色</el-button
>
</el-col>
</el-row>
<!-- 角色列表 -->
<el-table fit:false size="mini" :data="roleList" border>
<el-table-column type="expand">
<template v-slot="scope">
<el-row
v-for="item in scope.row.children"
:key="item.id"
style="border: 1px solid #eee"
class="divstyle"
>
<!-- 左侧蓝色第一列 -->
<el-col :span="4">
<el-tag
closable
@close="deleRightId(scope.row, item.id)"
style="margin: 8px"
>{{ item.authName }}</el-tag
>
<i class="el-icon-caret-right"></i>
</el-col>
<el-col :span="20">
<el-row
class="divstyle"
v-for="item1 in item.children"
:key="item1.id"
>
<el-col :span="5">
<el-tag
type="success"
style="margin: 8px"
closable
@close="deleRightId(scope.row, item1.id)"
>{{ item1.authName }}</el-tag
>
<i class="el-icon-caret-right"></i>
</el-col>
<el-col :span="19">
<!-- 最后一列标签 -->
<el-tag
style="margin: 8px"
v-for="item2 in item1.children"
:key="item2.id"
type="warning"
closable
@close="deleRightId(scope.row, item2.id)"
>{{ item2.authName }}</el-tag
>
</el-col>
</el-row>
</el-col>
</el-row>
<!-- <span>{{ scope.row }}</span> -->
</template>
</el-table-column>
<el-table-column type="index" label="#"> </el-table-column>
<el-table-column prop="roleName" label="角色名称"> </el-table-column>
<el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
<!-- 操作按钮 -->
<el-table-column label="操作" width="290px">
<template v-slot="scope">
<el-button size="mini" type="primary" icon="el-icon-edit"
>编辑</el-button
>
<el-button
size="mini"
type="danger"
icon="el-icon-delete"
@click="delusers(scope.row.id)"
>删除</el-button
>
<el-button
@click="showAssignPermissions(scope.row)"
size="mini"
type="warning"
icon="el-icon-setting"
>分配权限</el-button
>
</template>
</el-table-column>
</el-table>
<!-- 添加角色 -->
<el-dialog title="添加角色" :visible.sync="addUsersVisible" width="50%">
<el-form :model="addsuserForm" label-width="70px">
<el-form-item label="角色名称">
<el-input v-model="addsuserForm.rolename"></el-input>
</el-form-item>
<el-form-item label="角色描述">
<el-input v-model="addsuserForm.rolename"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="addUsersVisible = false">取 消</el-button>
<el-button type="primary" @click="addDialogVisible = false">
确 定
</el-button>
</span>
</el-dialog>
<!-- 分配权限的对话框 -->
<el-dialog
title="分配权限"
:visible.sync="showAssign"
width="50%"
@close="closeSting"
>
<!-- 树形列表 -->
<el-tree
:data="treeList"
show-checkbox
default-expand-all
node-key="id"
:default-checked-keys="treeListKeys"
:props="treeListProps"
>
</el-tree>
<!-- 底部按钮 -->
<span slot="footer" class="dialog-footer">
<el-button @click="showAssign = false">取 消</el-button>
<el-button type="primary" @click="showAssign = false"
>确 定</el-button
>
</span>
</el-dialog>
</el-card>
</div>
</template>
<script>
import { getRoles } from '@/api/user'
import { deletePowerUser, delRolesPower, getTreeList } from '@/api/jurisdiction'
export default {
created () {
this.getRoles()
},
data () {
return {
// tableData: [{
// date: '2016-05-02',
// name: '王小虎',
// address: '上海市普陀区金沙江路 1518 弄'
// }],
roleList: [],
addUsersVisible: false,
addsuserForm: {
rolename: '',
roleDesc: ''
},
showAssign: false,
treeList: [],
treeListProps: {
children: 'children',
label: 'authName'
},
treeListKeys: []
}
},
methods: {
async getRoles () {
try {
const res = await getRoles()
console.log(res)
this.roleList = res.data.data
console.log(this.roleList)
} catch (err) {
console.log(err)
}
},
async delusers (id) {
console.log(id)
try {
const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
console.log(res) // confirm
} catch (err) {
console.log(err) // cancel
if (err === 'cancel') {
return this.$message.info('已取消删除')
}
return err
// 删除用户
}
try {
const res1 = await deletePowerUser(id)
console.log(111)
console.log(res1)
this.$message.success('删除成功')
this.getRoles()
} catch (err) {
console.log(err)
}
},
// 添加角色
addDialogVisible () {
},
// 删除最后一列的标签
async deleRightId (roleId, rightId) {
try {
const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
try {
const res1 = await delRolesPower(roleId.id, rightId)
this.$message.success('删除成功')
roleId.children = res1.data.data
console.log(res1)
} catch (err) {
console.log(err)
}
console.log(res) // confirm
} catch (err) {
console.log(err) // cancel
if (err === 'cancel') {
return this.$message.info('已取消删除')
}
return err
// 删除用户
}
},
// 展示分配权限的对话框
async showAssignPermissions (user) {
this.showAssign = true
try {
const res = await getTreeList()
console.log(res)
this.treeList = res.data.data
this.getTreeListId(user, this.treeListKeys)
} catch (err) {
console.log(err)
}
},
// 获取子节点的id,添加到新数组中
getTreeListId (item, arr) {
if (!item.children) {
return arr.push(item.id)
}
item.children.forEach(item => {
this.getTreeListId(item, arr)
})
},
// 解决分配权限的缓存bug
closeSting () {
this.treeListKeys = []
}
},
computed: {},
watch: {},
filters: {},
components: {
}
}
</script>
<style scoped lang='less'>
.el-card {
margin: 20px 0 30px 0;
}
.el-row {
margin-bottom: 12px;
}
.supbtn {
margin-left: 18px;
}
.el-table {
margin-top: 10px;
}
.divstyle {
display: flex;
align-items: center;
}
</style> |
import cv2
import numpy as np
import tqdm
def convolution(image, kernel, stride=1):
image = np.array(image, dtype=float)
# [h, w, channel] = image.shape
h = image.shape[0]
w = image.shape[1]
k = kernel.shape[0]
r = int(k // 2)
# padding 0
image_padding = np.zeros([h + k - 1, w + k - 1], dtype=float)
image_padding[r:h + r, r:w + r] = image
result = np.zeros(image.shape)
for i in tqdm.tqdm(range(r, h + r, stride)):
for j in range(r, w + r, stride):
split = image_padding[i - r:i + r + 1, j - r:j + r + 1]
result[i - r, j - r] = np.sum(split * kernel)
return result
def gaussian_blur(image, kernel_size: int, sigma: float = 1.0):
kernel = np.outer(cv2.getGaussianKernel(kernel_size, sigma), cv2.getGaussianKernel(kernel_size, sigma))
# print("kernel=", kernel)
# result = convolution(image, kernel)
r = convolution(image[:, :, 0], kernel)
g = convolution(image[:, :, 1], kernel)
b = convolution(image[:, :, 2], kernel)
# 其實實際上是BGR
result = np.dstack((r,g,b))
return result
def toGray(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
return gray
def unsharp(image):
gray = toGray(image)
# print(gray)
kernel = np.array([[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]])
result = convolution(gray, kernel)
# print(result)
# cv2.imshow("unsharp", result)
# if cv2.waitKey(0) == 27: cv2.destroyAllWindows()
return result
# using sobel
def edgeDetection(image):
gray = toGray(image)
kernel = np.array([[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]])
result1 = convolution(gray, kernel)
kernel = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
result2 = convolution(gray, kernel)
result = np.sqrt(result1**2 + result2**2)
return result
def main():
image = cv2.imread("./柴犬飛飛.jpg")
# print(image)
if image is None:
print("No image 柴犬飛飛.jpg")
return -1
# 輸出圖片
cv2.imwrite("3x3.jpg", gaussian_blur(image, 3))
cv2.imwrite("7x7.jpg", gaussian_blur(image, 7))
cv2.imwrite("11x11.jpg", gaussian_blur(image, 11))
cv2.imwrite("sigma1.jpg", gaussian_blur(image, 3, 1))
cv2.imwrite("sigma10.jpg", gaussian_blur(image, 3, 10))
cv2.imwrite("sigma30.jpg", gaussian_blur(image, 3, 30))
# sharp
cv2.imwrite("unsharp.jpg", unsharp(image))
cv2.imwrite("unsharp_gaussian3.jpg", unsharp(cv2.imread("3x3.jpg")))
cv2.imwrite("unsharp_gaussian7.jpg", unsharp(cv2.imread("7x7.jpg")))
cv2.imwrite("unsharp_gaussian11.jpg", unsharp(cv2.imread("11x11.jpg")))
cv2.imwrite("edgeDetection.jpg", edgeDetection(image))
cv2.imwrite("edgeDetection_gaussian3.jpg", edgeDetection(cv2.imread("3x3.jpg")))
cv2.imwrite("edgeDetection_gaussian7.jpg", edgeDetection(cv2.imread("7x7.jpg")))
cv2.imwrite("edgeDetection_gaussian11.jpg", edgeDetection(cv2.imread("11x11.jpg")))
# PSNR
print(f'3x3.png PSNR: {cv2.PSNR(image, cv2.imread("3x3.jpg"))}')
print(f'7x7.png PSNR: {cv2.PSNR(image, cv2.imread("7x7.jpg"))}')
print(f'11x11.png PSNR: {cv2.PSNR(image, cv2.imread("11x11.jpg"))}')
print(f'sigma1.png PSNR: {cv2.PSNR(image, cv2.imread("sigma1.jpg"))}')
print(f'sigma10.png PSNR: {cv2.PSNR(image, cv2.imread("sigma10.jpg"))}')
print(f'sigma30.png PSNR: {cv2.PSNR(image, cv2.imread("sigma30.jpg"))}')
print(f'unsharp.png PSNR: {cv2.PSNR(image, cv2.imread("unsharp.jpg"))}')
print(f'edgeDetection.png PSNR: {cv2.PSNR(image, cv2.imread("edgeDetection.jpg"))}')
if __name__ == "__main__":
main() |
import { useRef, useState } from "react";
import ReactQuill, { Quill } from "react-quill";
import * as Emoji from "quill-emoji";
// import { markdownToHtml, htmlToMarkdown } from "./Parser";
import ImageResize from "quill-image-resize-module-react";
import "react-quill/dist/quill.snow.css";
import "quill-emoji/dist/quill-emoji.css";
Quill.register("modules/emoji", Emoji);
Quill.register("modules/imageResize", ImageResize);
const TOOLBAR_OPTIONS = [
[{ header: [1, 2, 3, false] }],
["bold", "italic", "underline", "strike", "blockquote", "link"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }],
[{ color: [] }], // Add color option here
["emoji"],
["clean"],
["image"],
];
const TOOLBAR_STYLES = {
backgroundColor: "blue",
display: "flex",
justifyContent: "space-between",
};
export default function Editor(props) {
const [value, setValue] = useState("");
const reactQuillRef = useRef(null);
const onChange = (content) => {
console.log({ content });
setValue(content);
if (props.onChange) {
props.onChange({
html: content,
// markdown: htmlToMarkdown(content),
});
}
};
return (
<ReactQuill
style={{ height: "250px" }}
ref={reactQuillRef}
theme="snow"
placeholder="Write your question"
modules={{
imageResize: {
modules: ["Resize", "DisplaySize", "Toolbar"],
displaySize: true,
size: {
width: "100",
height: "75",
},
style: "width: 100px; height: 75px;",
},
toolbar: {
container: TOOLBAR_OPTIONS,
style: TOOLBAR_STYLES,
},
"emoji-toolbar": true,
"emoji-textarea": false,
"emoji-shortname": true,
}}
value={value}
onChange={onChange}
/>
);
} |
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
import { StyledEngineProvider } from '@mui/material/styles';
import { Provider } from "react-redux";
import { configureStore } from "@reduxjs/toolkit";
import CartReducer from './store/cartSlice'
import { AuthProvider } from "./context/AuthProvider";
const root = ReactDOM.createRoot(document.getElementById("root"));
const store=configureStore({
reducer:{
CartReducer: CartReducer
}
})
root.render(
<StyledEngineProvider injectFirst>
<BrowserRouter>
<Provider store={store}>
<AuthProvider>
<App />
</AuthProvider>
</Provider>
</BrowserRouter>
</StyledEngineProvider>
); |
import React, { Fragment } from 'react';
import { useRouter } from 'next/router'
import blogs from '../../api/blogs'
import Link from 'next/link'
import PageTitle from '../../components/pagetitle';
import Navbar from '../../components/Navbar';
import Footer from '../../components/footer';
const submitHandler = (e) => {
e.preventDefault()
}
const BlogSingle = (props) => {
const router = useRouter()
const BlogDetails = blogs.find(item => item.slug === router.query.slug)
return (
<Fragment>
<Navbar />
<PageTitle pageTitle={BlogDetails?.title} pagesub="blog" />
<section className="wpo-blog-single-section section-padding">
<div className="container">
<div className="row">
<div className="col col-lg-10 offset-lg-1">
<div className="wpo-blog-content">
<div className="post format-standard-image">
<div className="entry-media">
<img src={BlogDetails?.blogSingleImg} alt="" />
</div>
<div className="entry-meta">
<ul>
<li><i className="fi flaticon-user"></i> By <Link href="/">{BlogDetails?.author}</Link> </li>
<li><i className="fi flaticon-comment-white-oval-bubble"></i> Comments {BlogDetails?.comment}</li>
<li><i className="fi flaticon-calendar"></i> {BlogDetails?.create_at}</li>
</ul>
</div>
<h2>{BlogDetails?.title}</h2>
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful.</p>
<blockquote>
Combined with a handful of model sentence structures, generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
</blockquote>
<p>I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself,</p>
<div className="gallery">
<div>
<img src='/images/blog/img-1.jpg' alt="" />
</div>
<div>
<img src='/images/blog/img-2.jpg' alt="" />
</div>
</div>
</div>
<div className="tag-share clearfix">
<div className="tag">
<span>Share: </span>
<ul>
<li><Link href="/">Planning</Link></li>
<li><Link href="/">Portfolio</Link></li>
<li><Link href="/">Creative</Link></li>
</ul>
</div>
</div>
<div className="tag-share-s2 clearfix">
<div className="tag">
<span>Share: </span>
<ul>
<li><Link href="/">facebook</Link></li>
<li><Link href="/">twitter</Link></li>
<li><Link href="/">linkedin</Link></li>
<li><Link href="/">pinterest</Link></li>
</ul>
</div>
</div>
<div className="author-box">
<div className="author-avatar">
<Link href="/" target="_blank"><img src='/images/blog-details/author.jpg' alt="" /></Link>
</div>
<div className="author-content">
<Link href="/" className="author-name">Author: Jenny Watson</Link>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis.</p>
<div className="socials">
<ul className="social-link">
<li><Link href="/"><i className="ti-facebook"></i></Link></li>
<li><Link href="/"><i className="ti-twitter-alt"></i></Link></li>
<li><Link href="/"><i className="ti-linkedin"></i></Link></li>
<li><Link href="/"><i className="ti-instagram"></i></Link></li>
</ul>
</div>
</div>
</div>
<div className="more-posts">
<div className="previous-post">
<Link href="/">
<span className="post-control-link">Previous Post</span>
<span className="post-name">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium.</span>
</Link>
</div>
<div className="next-post">
<Link href="/">
<span className="post-control-link">Next Post</span>
<span className="post-name">Dignissimos ducimus qui blanditiis praesentiu deleniti atque corrupti quos dolores</span>
</Link>
</div>
</div>
<div className="comments-area">
<div className="comments-section">
<h3 className="comments-title">Comments</h3>
<ol className="comments">
<li className="comment even thread-even depth-1" id="comment-1">
<div id="div-comment-1">
<div className="comment-theme">
<div className="comment-image"><img src='/images/blog-details/comments-author/img-1.jpg' alt="" /></div>
</div>
<div className="comment-main-area">
<div className="comment-wrapper">
<div className="comments-meta">
<h4>John Abraham <span className="comments-date">January 12,2022
At 9.00am</span></h4>
</div>
<div className="comment-area">
<p>I will give you a complete account of the system, and
expound the actual teachings of the great explorer of
the truth, </p>
<div className="comments-reply">
<Link href="/" className="comment-reply-link"><span>Reply</span></Link>
</div>
</div>
</div>
</div>
</div>
<ul className="children">
<li className="comment">
<div>
<div className="comment-theme">
<div className="comment-image"><img src='/images/blog-details/comments-author/img-2.jpg' alt="" /></div>
</div>
<div className="comment-main-area">
<div className="comment-wrapper">
<div className="comments-meta">
<h4>Lily Watson <span className="comments-date">January
12,2022 At 9.00am</span></h4>
</div>
<div className="comment-area">
<p>I will give you a complete account of the system,
and expound the actual teachings of the great
explorer of the truth, </p>
<div className="comments-reply">
<Link href="/" className="comment-reply-link"><span>Reply</span></Link>
</div>
</div>
</div>
</div>
</div>
<ul>
<li className="comment">
<div>
<div className="comment-theme">
<div className="comment-image"><img src='/images/blog-details/comments-author/img-3.jpg' alt="" /></div>
</div>
<div className="comment-main-area">
<div className="comment-wrapper">
<div className="comments-meta">
<h4>John Abraham <span className="comments-date">January
12,2022 At 9.00am</span></h4>
</div>
<div className="comment-area">
<p>I will give you a complete account of the
system, and expound the actual teachings
of the great explorer of the truth, </p>
<div className="comments-reply">
<Link href="/" className="comment-reply-link"><span>Reply</span></Link>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
</li>
</ul>
</li>
<li className="comment">
<div>
<div className="comment-theme">
<div className="comment-image"><img src='/images/blog-details/comments-author/img-1.jpg' alt="" /></div>
</div>
<div className="comment-main-area">
<div className="comment-wrapper">
<div className="comments-meta">
<h4>John Abraham <span className="comments-date">January 12,2022
At 9.00am</span></h4>
</div>
<div className="comment-area">
<p>I will give you a complete account of the system, and
expound the actual teachings of the great explorer of
the truth, </p>
<div className="comments-reply">
<Link href="/" className="comment-reply-link"><span>Reply</span></Link>
</div>
</div>
</div>
</div>
</div>
</li>
</ol>
</div>
<div className="comment-respond">
<h3 className="comment-reply-title">Post Comments</h3>
<form onSubmit={submitHandler} id="commentform" className="comment-form">
<div className="form-textarea">
<textarea id="comment" placeholder="Write Your Comments..."></textarea>
</div>
<div className="form-inputs">
<input placeholder="Website" type="url" />
<input placeholder="Name" type="text" />
<input placeholder="Email" type="email" />
</div>
<div className="form-submit">
<input id="submit" value="Post Comment" type="submit" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<Footer />
</Fragment>
)
};
export default BlogSingle; |
package top.coldsand.frozengate.tool;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import top.coldsand.frozengate.FrozenGate;
import top.coldsand.frozengate.data.yaml.Config;
/**
* SafePlayerLocation class
* 有关玩家安全位置搜索与传送的类
*
* @author Cold_sand
* @date 2023/8/27
*/
public class SafePlayerLocation {
/**
* 检查位置是否安全(所在位置与该位置上方方块可被穿过,位置下方不可被穿过)
*
* @param world 位置所在世界实例
* @param location 位置实例
*
* @return 位置是否安全
*/
public static boolean checkLocationSafe(World world, Location location) {
Block block = world.getBlockAt(location);
return block.getRelative(BlockFace.UP).isPassable() && block.isPassable() && !block.getRelative(BlockFace.DOWN).isPassable();
}
/**
* 在指定半径内查找安全位置
*
* @param player 玩家实例
* @param searchRadius 搜索半径
*
* @return 寻找到的安全位置,否则返回false
*/
private static boolean searchSafeLocation(Player player, int searchRadius) {
for (int x = -searchRadius; x <= searchRadius; x++) {
for (int y = -searchRadius; y <= searchRadius; y++) {
for (int z = -searchRadius; z <= searchRadius; z++) {
Location newLocation = player.getLocation().clone().add(x, y, z);
if (checkLocationSafe(player.getWorld(), newLocation)) {
player.teleport(newLocation);
player.sendMessage(ChatColor.GREEN + "已为您传送到安全位置");
return true;
}
}
}
}
return false;
}
/**
* 传送到搜素到的安全位置
*
* @param player 玩家实例
*/
public static void teleportPlayerToSafeLocation(Player player) {
if (Config.INSTANCE.getSearchSafeLocationBoolean()) {
if (searchSafeLocation(player, Config.INSTANCE.getSearchRadius())) {
return; //如果找到了安全位置,直接返回,不进行后续的传送操作
}
if (!searchSafeLocation(player, Config.INSTANCE.getSearchRadius())) {
try {
Location bedLocation = player.getBedSpawnLocation();
if (bedLocation != null) {
player.teleport(bedLocation);
player.sendMessage(ChatColor.GREEN + "已为您传送到床位置" );
} else {
player.teleport(Config.INSTANCE.getSpawnLocation());
player.sendMessage(ChatColor.GREEN + "已为您传送到管理员指定的位置");
}
} catch (IllegalArgumentException e) {
player.teleport(player.getWorld().getSpawnLocation());
player.sendMessage(ChatColor.YELLOW + "管理员未正确设置默认出生点或您的床位置不可用,已为您传送到世界出生点,请联系管理员修复此问题" );
FrozenGate.LOGGER.warning("您未正确设置默认出生点,请尽快修复,以免影响玩家体验");
}
}
}
}
} |
import CommandListExpression from './CommandListExpression';
import Context from './Context';
import { Expression } from './Expression';
class BeginExpression implements Expression {
private expression: CommandListExpression | null = null;
private _isRunnable = false;
get isRunnable() {
return this._isRunnable;
}
parse(context: Context): void {
if (!context.hasNext()) throw new Error('다음 token이 없습니다.');
const token = context.readNext();
if (token !== 'BEGIN') {
throw new Error(`'${token}'은(는) 'BEGIN'이 아닙니다.`);
}
this._isRunnable = true;
this.expression = new CommandListExpression();
this.expression.parse(context);
}
run(): void {
if (!this.isRunnable) throw new Error('BEGIN 실행할 수 없음');
if (this.expression === null) throw new Error('BeginExpression의 expression이 없습니다.');
this.expression.run();
}
}
export default BeginExpression; |
<div align="center">
# Heron
**マルチモーダルモデル学習ライブラリ**
[English](../README.md) | 日本語 | [中文](./README_CN.md)
</div>
Heronは、複数の画像/動画モデルと言語モデルをシームレスに統合するライブラリです。日本語のV&Lモデルをサポートしており、さらに様々なデータセットで学習された事前学習済みウェイトも提供します。
異なるLLMで構築されたマルチモーダルのデモページはこちらをご覧ください。(ともに日本語対応)
- [BLIP + Japanese StableLM Base Alpha](https://huggingface.co/spaces/turing-motors/heron_chat_blip)
- [GIT + ELYZA-japanese-Llama-2](https://huggingface.co/spaces/turing-motors/heron_chat_git)
<div align="center">
<img src="../images/heron_image.png" width="50%">
</div>
Heronでは、様々なモジュールを組み合わせた独自のV&Lモデルを構成することができます。Vision Encoder、Adopter、LLMを設定ファイルで設定できます。分散学習方法やトレーニングに使用するデータセットも簡単に設定できます。
<img src="../images/build_train_model.png" width="100%">
# インストール方法
## 1. リポジトリの取得
```bash
git clone https://github.com/turingmotors/heron.git
cd heron
```
## 2. Python環境のセットアップ
必要なパッケージのインストールには仮想環境を使用することを推奨します。グローバルにパッケージをインストールしたい場合は、代わりに `pip install -r requirements.txt` を使ってください。
### 2-a. Poetry (Recommended)
[pyenv](https://github.com/pyenv/pyenv)と[Poetry](https://python-poetry.org/)の場合、次の手順で必要なパッケージをインストールしてください。
```bash
# install pyenv environment
pyenv install 3.10
pyenv local 3.10
# install packages from pyproject.toml
poetry install
# install local package
pip install --upgrade pip # enable PEP 660 support
pip install -e .
# for development, install pre-commit
pre-commit install
``````
### 2-b. Anaconda
[Anaconda](https://www.anaconda.com/)の場合、次の手順で必要なパッケージをインストールしてください。
```bash
conda create -n heron python=3.10 -y
conda activate heron
pip install --upgrade pip # enable PEP 660 support
pip install -r requirements.txt
pip install -e .
# for development, install pre-commit
pre-commit install
```
## 3. Llama-2モデルの事前申請
Llama-2モデルを使用するには、アクセスの申請が必要です。
まず、[Hugging Face](https://huggingface.co/meta-llama/Llama-2-7b)と[Meta](https://ai.meta.com/resources/models-and-libraries/llama-downloads/)のサイトから、llama-2モデルへのアクセスをリクエストしてください。
リクエストが承認されたら、HaggingFaceのアカウントでサインインしてください。
```bash
huggingface-cli login
```
# 学習方法
学習を行う場合、`projects`ディレクトリ配下のyaml設定ファイルを使用します。<br>
例えば、[projects/opt/exp001.yml](../projects/opt/exp001.yml)の内容は次のようになっています。
```yaml
training_config:
per_device_train_batch_size: 2
gradient_accumulation_steps: 4
num_train_epochs: 1
dataloader_num_workers: 16
fp16: true
optim: "adamw_torch"
learning_rate: 5.0e-5
logging_steps: 100
evaluation_strategy: "steps"
save_strategy: "steps"
eval_steps: 4000
save_steps: 4000
save_total_limit: 1
deepspeed: ./configs/deepspeed/ds_config_zero1.json
output_dir: ./output/
report_to: "wandb"
model_config:
fp16: true
pretrained_path: # None or path to model weight
model_type: git_llm
language_model_name: facebook/opt-350m
vision_model_name: openai/clip-vit-base-patch16
num_image_with_embedding: 1 # if 1, no img_temporal_embedding
max_length: 512
keys_to_finetune:
- visual_projection
- num_image_with_embedding
keys_to_freeze: []
use_lora: true
lora:
r: 8
lora_alpha: 32
target_modules:
- q_proj
- k_proj
- v_proj
lora_dropout: 0.01
bias: none
task_type: CAUSAL_LM
dataset_config_path:
- ./configs/datasets/m3it.yaml
```
`training_config`では学習に関する設定を、`model_config`ではモデルに関する設定を、`dataset_config_path`ではデータセットに関する設定をそれぞれ行います。<br>
`model_type`に指定できるLLMモジュールとしては現在下記のものがサポートされています。今後も対応するモジュールを増やしていく予定です。
- [LLama-2](https://ai.meta.com/llama/)
- [MPT](https://github.com/mosaicml/llm-foundry)
- [OPT](https://huggingface.co/docs/transformers/model_doc/opt)
- [GPT-NeoX](https://github.com/EleutherAI/gpt-neox)
- [Japanese StableLM](https://huggingface.co/stabilityai/japanese-stablelm-base-alpha-7b)
- [ELYZA-japanese-Llama-2](https://huggingface.co/elyza/ELYZA-japanese-Llama-2-7b-fast)
学習を開始する場合は、次のコマンドを実行してください。
```bash
./scripts/run.sh
```
学習にはGPUが必要です。Ubuntu20.04, CUDA11.7で動作確認をしています。
# 利用方法
Hugging Face Hubから学習済みモデルをダウンロードすることができます: [turing-motors/heron-chat-git-ja-stablelm-base-7b-v0](https://huggingface.co/turing-motors/heron-chat-git-ja-stablelm-base-7b-v0)<br>
推論・学習の方法については[notebooks](./notebooks)も参考にしてください。
```python
import requests
from PIL import Image
import torch
from transformers import AutoProcessor
from heron.models.git_llm.git_llama import GitLlamaForCausalLM
device_id = 0
# prepare a pretrained model
model = GitLlamaForCausalLM.from_pretrained('turing-motors/heron-chat-git-ja-stablelm-base-7b-v0')
model.eval()
model.to(f"cuda:{device_id}")
# prepare a processor
processor = AutoProcessor.from_pretrained('turing-motors/heron-chat-git-ja-stablelm-base-7b-v0')
# prepare inputs
url = "https://www.barnorama.com/wp-content/uploads/2016/12/03-Confusing-Pictures.jpg"
image = Image.open(requests.get(url, stream=True).raw)
text = f"##Instruction: Please answer the following question concretely. ##Question: What is unusual about this image? Explain precisely and concretely what he is doing? ##Answer: "
# do preprocessing
inputs = processor(
text,
image,
return_tensors="pt",
truncation=True,
)
inputs = {k: v.to(f"cuda:{device_id}") for k, v in inputs.items()}
# set eos token
eos_token_id_list = [
processor.tokenizer.pad_token_id,
processor.tokenizer.eos_token_id,
]
# do inference
with torch.no_grad():
out = model.generate(**inputs, max_length=256, do_sample=False, temperature=0., eos_token_id=eos_token_id_list)
# print result
print(processor.tokenizer.batch_decode(out))
```
### 学習済みモデル一覧
|model|LLM module|adapter|size|
|:----:|:----|:----|:----|
|[heron-chat-blip-ja-stablelm-base-7b-v0](https://huggingface.co/turing-motors/heron-chat-blip-ja-stablelm-base-7b-v0)|Japanese StableLM Base Alpha|BLIP|7B|
|[heron-chat-git-ja-stablelm-base-7b-v0](https://huggingface.co/turing-motors/heron-chat-git-ja-stablelm-base-7b-v0)|Japanese StableLM Base Alpha|GIT|7B|
|[heron-chat-git-ELYZA-fast-7b-v0](https://huggingface.co/turing-motors/heron-chat-git-ELYZA-fast-7b-v0)|ELYZA|GIT|7B|
|[heron-preliminary-git-Llama-2-70b-v0](https://huggingface.co/turing-motors/heron-preliminary-git-Llama-2-70b-v0) *1|Llama-2|GIT|70B|
*1 アダプタの事前学習のみを実施したもの
### データセット
日本語に翻訳されたLLava-Instructデータセットです。<br>
[LLaVA-Instruct-150K-JA](https://huggingface.co/datasets/turing-motors/LLaVA-Instruct-150K-JA)
# 組織情報
[Turing株式会社](https://www.turing-motors.com/)
# ライセンス
[Apache License 2.0](../LICENSE) において公開されています。
# 参考情報
- [GenerativeImage2Text](https://github.com/microsoft/GenerativeImage2Text): モデルの構成方法の着想はGITに基づいています。
- [Llava](https://github.com/haotian-liu/LLaVA): 本ライブラリはLlavaプロジェクトを参考にしています。
- [GIT-LLM](https://github.com/Ino-Ichan/GIT-LLM) |
#include <stdio.h>
#include <stdlib.h>
#include "voter.h"
#include "hash_table.h"
#define M 4 // Initial number of buckets for the hash table
#define L 0.75 // Threshold
// Check if the memory is allocated and malloc didn't fail
#define CHECK_MALLOC_NULL(p) \
if ((p) == NULL) { \
printf("Cannot allocate memory!\n"); \
exit(1); \
};
extern long int num_bytes;
static void Insert_Bucket(Bucket **, Voter *, int);
static void Bucket_Split(HTptr ht, Bucket **, Bucket **);
// Create hash table
void Create_HT(HTptr *ht, int num_entries) {
int i;
CHECK_MALLOC_NULL((*ht) = malloc(sizeof(HT)));
num_bytes = num_bytes + sizeof(HT);
(*ht)->m = M;
(*ht)->p = 0;
(*ht)->num_buckets = M;
(*ht)->num_keys = 0;
(*ht)->bucketentries = num_entries;
CHECK_MALLOC_NULL((*ht)->buckets = malloc(M * sizeof(Bucket *)));
num_bytes = num_bytes + (M * sizeof(Bucket *));
for (i = 0; i < M; i++) {
(*ht)->buckets[i] = NULL;
}
}
// Insert a voter in the hash table
void Insert_HT(HTptr ht, Voter *voter) {
int i = voter->PIN % ht->m;
// The modulo points to a bucket that has splitted
if (i < ht->p) {
i = voter->PIN % (2 * (ht->m)); // Recalculate the index of the bucket
}
Insert_Bucket(&(ht->buckets[i]), voter, ht->bucketentries);
ht->num_keys++; // Added new voter
// Calculate threshold
float l = ((float)ht->num_keys) / (ht->num_buckets * ht->bucketentries);
// If l is greater than the threshold
if (l > L) {
ht->num_buckets++; // Create a new non-overflow bucket
ht->buckets = realloc(ht->buckets, ht->num_buckets * sizeof(Bucket *));
ht->buckets[ht->num_buckets - 1] = NULL;
Bucket_Split(ht, &(ht->buckets[ht->p]), &(ht->buckets[ht->num_buckets - 1]));
ht->p++; // p points to the next bucket that will split
// Complete round
if (ht->p == ht->m) {
ht->m = 2 * ht->m;
ht->p = 0;
}
}
}
// Insert a voter into a bucket
static void Insert_Bucket(Bucket **bucket, Voter *voter, int size) {
int i = 0;
// Create a bucket if it doesn't exist
if ((*bucket) == NULL) {
CHECK_MALLOC_NULL((*bucket) = malloc(sizeof(Bucket)));
num_bytes = num_bytes + sizeof(Bucket);
(*bucket)->next_bucket = NULL;
CHECK_MALLOC_NULL((*bucket)->voters = malloc(size * sizeof(Voter *)));
num_bytes = num_bytes + (size * sizeof(Voter *));
(*bucket)->count = 0;
for (i = 0; i < size; i++) {
(*bucket)->voters[i] = NULL;
}
}
// Insert to overflow bucket
if ((*bucket)->count == size) {
Insert_Bucket(&((*bucket)->next_bucket), voter, size);
}
// The bucket has space for a new voter
else {
(*bucket)->voters[(*bucket)->count] = voter;
(*bucket)->count++;
}
}
// Splits a bucket into 2 buckets
static void Bucket_Split(HTptr ht, Bucket **b1, Bucket **b2) {
int i;
Bucket *curr_bucket = (*b1);
Bucket *new_bucket = NULL, *temp_bucket;
while (curr_bucket != NULL) {
for (i = 0; i < curr_bucket->count; i++) {
// Voters for bucket b2 (new bucket from split)
if ((curr_bucket->voters[i]->PIN % (2 * ht->m)) == ht->num_buckets - 1) {
Insert_Bucket(b2, curr_bucket->voters[i], ht->bucketentries);
}
// Voters that will remain in bucket b1
else {
Insert_Bucket(&new_bucket, curr_bucket->voters[i], ht->bucketentries);
}
}
num_bytes = num_bytes - sizeof(curr_bucket->voters); // Free bytes
free(curr_bucket->voters);
temp_bucket = curr_bucket->next_bucket;
num_bytes = num_bytes - sizeof(curr_bucket); // Free bytes
free(curr_bucket);
curr_bucket = temp_bucket;
}
// The new bucket is a temp bucket for the entries that will remain in bucket b1
(*b1) = NULL;
temp_bucket = new_bucket;
while (temp_bucket != NULL) {
for (i = 0; i < temp_bucket->count; i++) {
Insert_Bucket(b1, temp_bucket->voters[i], ht->bucketentries);
}
temp_bucket = temp_bucket->next_bucket;
}
// Delete the temp bucket
while (new_bucket != NULL) {
num_bytes = num_bytes - sizeof(new_bucket->voters); // Free bytes
free(new_bucket->voters);
temp_bucket = new_bucket->next_bucket;
num_bytes = num_bytes - sizeof(new_bucket); // Free bytes
free(new_bucket);
new_bucket = temp_bucket;
}
}
// Searches if there is a voter with a given PIN
Voter* Search_HT(HTptr ht, int pin) {
int j;
int i1 = pin % ht->m; // Index of first bucket
int i2 = pin % (2 * ht->m); // Index of second bucket
Bucket *bucket1 = ht->buckets[i1]; // First bucket
Bucket *bucket2;
// Search the first bucket
while (bucket1 != NULL) {
for (j = 0; j < bucket1->count; j++) {
if (bucket1->voters[j]->PIN == pin) {
return bucket1->voters[j]; // Found pin, return pointer to the voter we want
}
}
bucket1 = bucket1->next_bucket;
}
// Search the second bucket
if (i2 <= ht->num_buckets - 1) {
bucket2 = ht->buckets[i2]; // Second bucket
while (bucket2 != NULL) {
for (j = 0; j < bucket2->count; j++) {
if (bucket2->voters[j]->PIN == pin) {
return bucket2->voters[j]; // Found pin, return pointer to the voter we want
}
}
bucket2 = bucket2->next_bucket;
}
}
// Pin was not found
return NULL;
}
// Delete hash table, free memory
void Delete_HT(HTptr *ht) {
int i, j;
Bucket *bucket, *temp_bucket;
Bucket **array_buckets = (*ht)->buckets;
for (i = 0; i < (*ht)->num_buckets; i++) {
bucket = array_buckets[i];
// Delete buckets
while (bucket != NULL) {
// Delete voters
for (j = 0; j < bucket->count; j++) {
free(bucket->voters[j]->first_name);
free(bucket->voters[j]->last_name);
free(bucket->voters[j]);
}
free(bucket->voters);
temp_bucket = bucket->next_bucket;
free(bucket);
bucket = temp_bucket;
}
}
free((*ht)->buckets);
free(*ht);
} |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('surname');
// $table->string('email')->unique(); // should delete
$table->string('phone_number')->unique();
$table->string('firebase_uid')->nullable()->unique();
$table->string('password');
$table->string('picture');
$table->timestamp('email_verified_at')->nullable();
$table->string("topic");
$table->string("active")->default("1");
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
} |
import argparse
import json
import logging
import os
import pickle
import time
import re
import boto3
import pandas as pd
from sklearn.preprocessing import LabelEncoder
logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d:%H:%M:%S',
level=logging.INFO)
########################################
# 从s3同步数据
########################################
def sync_s3(file_name_list, s3_folder, local_folder):
for f in file_name_list:
print("file preparation: download src key {} to dst key {}".format(os.path.join(
s3_folder, f), os.path.join(local_folder, f)))
s3client.download_file(bucket, os.path.join(
s3_folder, f), os.path.join(local_folder, f))
def write_to_s3(filename, bucket, key):
print("upload s3://{}/{}".format(bucket, key))
with open(filename, 'rb') as f: # Read in binary mode
# return s3client.upload_fileobj(f, bucket, key)
return s3client.put_object(
ACL='bucket-owner-full-control',
Bucket=bucket,
Key=key,
Body=f
)
def write_str_to_s3(content, bucket, key):
print("write s3://{}/{}, content={}".format(bucket, key, content))
s3client.put_object(Body=str(content).encode("utf8"), Bucket=bucket, Key=key, ACL='bucket-owner-full-control')
def prepare_df(item_path):
return pd.read_csv(item_path, sep="_!_", names=[
"program_id",
"program_type",
"program_name",
"release_year",
"director",
"actor",
"category_property",
"language",
"ticket_num",
"popularity",
"score",
"level",
"is_new"])
def get_actor(actor_str):
if not actor_str or str(actor_str).lower() in ['nan', 'nr', '']:
return [None]
actor_arr = actor_str.split('|')
return [item.strip().lower() for item in actor_arr]
def get_category(category_property):
if not category_property or str(category_property).lower() in ['nan', 'nr', '']:
return [None]
if not category_property:
return [None]
return [item.strip().lower() for item in category_property.split('|')]
def get_single_item(item):
if not item or str(item).lower().strip() in ['nan', 'nr', '']:
return [None]
return [str(item).lower().strip()]
parser = argparse.ArgumentParser(description="app inputs and outputs")
parser.add_argument("--bucket", type=str, help="s3 bucket")
parser.add_argument("--prefix", type=str, help="s3 input key prefix")
parser.add_argument("--region", type=str, help="aws region")
parser.add_argument("--method", type=str, default='customize', help="method name")
args, _ = parser.parse_known_args()
print("args:", args)
if args.region:
print("region:", args.region)
boto3.setup_default_session(region_name=args.region)
bucket = args.bucket
prefix = args.prefix
method = args.method
region = args.region
if prefix.endswith("/"):
prefix = prefix[:-1]
print(f"bucket:{bucket}, prefix:{prefix}")
print("region={}".format(region))
print("method={}".format(method))
s3 = boto3.client('s3')
personalize = boto3.client('personalize', args.region)
s3client = s3
sts = boto3.client('sts')
get_caller_identity_response = sts.get_caller_identity()
aws_account_id = get_caller_identity_response["Account"]
print("aws_account_id:{}".format(aws_account_id))
local_folder = 'info'
if not os.path.exists(local_folder):
os.makedirs(local_folder)
file_name_list = ['item.csv']
s3_folder = '{}/system/item-data/'.format(prefix)
sync_s3(file_name_list, s3_folder, local_folder)
df = prepare_df("info/item.csv")
movie_id_movie_property_data = {}
row_cnt = 0
for row in df.iterrows():
item_row = row[1]
program_id = str(item_row['program_id'])
program_dict = {
'director': get_single_item(item_row['director']),
'level': get_single_item(item_row['level']),
'year': get_single_item(item_row['release_year']),
'actor': get_actor(item_row['actor']),
'category': get_category(item_row['category_property']),
'language': get_single_item(item_row['language'])
}
row_content = []
row_content.append(str(item_row['program_id']))
row_content.append(program_dict['director'])
row_content.append(program_dict['level'])
row_content.append(program_dict['year'])
row_content.append(program_dict['actor'])
row_content.append(program_dict['category'])
row_content.append(program_dict['language'])
movie_id_movie_property_data['row_{}'.format(row_cnt)] = row_content
row_cnt = row_cnt + 1
raw_data_pddf = pd.DataFrame.from_dict(movie_id_movie_property_data, orient='index',
columns=['programId', 'director', 'level', 'year', 'actor', 'actegory',
'language'])
raw_data_pddf = raw_data_pddf.reset_index(drop=True)
# raw_data_pddf.head()
sample_data_pddf = raw_data_pddf
# generate lable encoding/ sparse feature
lbe = LabelEncoder()
sample_data_pddf['encode_id'] = lbe.fit_transform(sample_data_pddf['programId'])
raw_item_id_list = list(map(str, sample_data_pddf['programId'].values))
code_item_id_list = list(map(int, sample_data_pddf['encode_id'].values))
raw_embed_item_id_dict = dict(zip(raw_item_id_list, code_item_id_list))
embed_raw_item_id_dict = dict(zip(code_item_id_list, raw_item_id_list))
file_name = 'info/raw_embed_item_mapping.pickle'
output_file = open(file_name, 'wb')
pickle.dump(raw_embed_item_id_dict, output_file)
output_file.close()
write_to_s3(file_name, bucket, "{}/feature/action/{}".format(prefix, file_name.split('/')[-1]))
file_name = 'info/embed_raw_item_mapping.pickle'
output_file = open(file_name, 'wb')
pickle.dump(embed_raw_item_id_dict, output_file)
output_file.close()
write_to_s3(file_name, bucket, "{}/feature/action/{}".format(prefix, file_name.split('/')[-1]))
#创建ItemDatasetImportJob
ps_item_file_name_list = ['ps_item.csv']
ps_item_s3_folder = '{}/system/ps-ingest-data/item'.format(prefix)
sync_s3(ps_item_file_name_list, ps_item_s3_folder, local_folder)
ps_config_file_name = ['ps_config.json']
ps_config_s3_folder = '{}/system/ps-config'.format(prefix)
sync_s3(ps_config_file_name, ps_config_s3_folder, local_folder)
def get_ps_config_from_s3():
infile = open('info/ps_config.json')
ps_config = json.load(infile)
infile.close()
return ps_config
def get_dataset_group_arn(dataset_group_name):
response = personalize.list_dataset_groups()
for dataset_group in response["datasetGroups"]:
if dataset_group["name"] == dataset_group_name:
return dataset_group["datasetGroupArn"]
def get_dataset_arn(dataset_group_arn, dataset_name):
response = personalize.list_datasets(
datasetGroupArn=dataset_group_arn
)
for dataset in response["datasets"]:
if dataset["name"] == dataset_name:
return dataset["datasetArn"]
def create_item_dataset_import_job():
ps_config = get_ps_config_from_s3()
dataset_group_arn = get_dataset_group_arn(ps_config['DatasetGroupName'])
dataset_arn = get_dataset_arn(dataset_group_arn, ps_config['ItemDatasetName'])
response = personalize.create_dataset_import_job(
jobName="item-dataset-import-job-{}".format(int(time.time())),
datasetArn=dataset_arn,
dataSource={
'dataLocation': "s3://{}/{}/system/ps-ingest-data/item/ps_item.csv".format(bucket, prefix)
},
roleArn="arn:aws:iam::{}:role/gcr-rs-personalize-role-{}".format(aws_account_id, region)
)
item_dataset_import_job_arn = response['datasetImportJobArn']
print("item_dataset_import_job_arn:{}".format(item_dataset_import_job_arn))
# check status
max_time = time.time() + 3 * 60 * 60
while time.time() < max_time:
describe_dataset_import_job_response = personalize.describe_dataset_import_job(
datasetImportJobArn=item_dataset_import_job_arn
)
status = describe_dataset_import_job_response["datasetImportJob"]['status']
print("DatasetImportJob: {}".format(status))
if status == "ACTIVE":
print("ItemDatasetImportJob Create Successfully!")
break
elif status == "CREATE FAILED":
print("ItemDatasetImportJob Create failed!")
break
else:
time.sleep(60)
print("ItemDatasetImportJob Exceed Max Create Time!")
if "ps" in method:
create_item_dataset_import_job() |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>伪类选择器练习</title>
<style>
*{
padding: 0;
margin: 0;
}
ul{
width: 960px;
height: 40px;
margin: 100px auto;
}
ul li {
list-style: none;
width: 120px;
float: left;
text-align: center;
line-height: 40px;
}
/*
1.在企业开发中编写a标签的伪类选择器最好写在标签选择器后面
2.在企业开发中和a标签盒子相关的属性都写在标签选择器中(限时模式/宽度/高度)
3/在企业开发中和a标签文字/背景相关的都写在伪类选择器中
*/
ul li a{
display: inline-block;
width: 120px;
height: 40px;
}
ul li a:link{
background: pink;
color: white;
text-decoration: none;
}
ul li a:hover{
color: red;
}
ul li a:active{
color: yellow;
}
/*ul li a{*/
/*text-decoration: none;*/
/*}*/
</style>
</head>
<body>
<ul>
<li><a href="#">我是导航</a></li>
<li><a href="#">我是导航</a></li>
<li><a href="#">我是导航</a></li>
<li><a href="#">我是导航</a></li>
<li><a href="#">我是导航</a></li>
<li><a href="#">我是导航</a></li>
<li><a href="#">我是导航</a></li>
<li><a href="#">我是导航</a></li>
</ul>
</body>
</html> |
// MIT License
//
// Copyright (c) 2024 Eric Thiffeault
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <iostream>
#include "doctest.h"
#include <eti/eti.h>
using namespace eti;
namespace test_01
{
struct Foo {};
TEST_CASE("test_01")
{
std::string fooTypeName(GetTypeName<Foo>());
REQUIRE(fooTypeName == "test_01::Foo");
TypeId fooNameHash = ETI_HASH_FUNCTION(GetTypeName<Foo>());
TypeId fooTypeId = GetTypeId<Foo>();
REQUIRE(fooTypeId == fooNameHash);
}
}
namespace test_02
{
TEST_CASE("test_02")
{
const Type& type = TypeOf<int>();
REQUIRE(type.Name == "s32");
REQUIRE(type.Id != 0);
REQUIRE(type.Kind == Kind::Pod);
REQUIRE(type.Size == sizeof(int));
REQUIRE(type.Align == alignof(int));
REQUIRE(type.Parent == nullptr);
}
}
namespace test_03
{
struct Foo
{
ETI_STRUCT(Foo)
};
}
namespace test_03
{
TEST_CASE("test_03")
{
const Type& type = TypeOf<Foo>();
REQUIRE(type.Name == "test_03::Foo");
REQUIRE(type.Id != 0);
REQUIRE(type.Kind == Kind::Struct);
REQUIRE(type.Size == sizeof(Foo));
REQUIRE(type.Align == alignof(Foo));
REQUIRE(type.Parent == nullptr);
}
}
namespace test_04
{
class Object
{
ETI_BASE_EXT(Object, ETI_PROPERTIES(), ETI_METHODS())
public:
Object() {}
virtual ~Object() {}
};
TEST_CASE("test_04")
{
const Type& type = TypeOf<Object>();
REQUIRE(type.Name == "test_04::Object");
REQUIRE(type.Id != 0);
REQUIRE(type.Kind == Kind::Class);
REQUIRE(type.Size == sizeof(Object));
REQUIRE(type.Align == alignof(Object));
REQUIRE(type.Parent == nullptr);
}
}
namespace test_05
{
class Object
{
ETI_BASE_EXT(Object, ETI_PROPERTIES(), ETI_METHODS())
public:
Object() {}
virtual ~Object() {}
};
class Foo : public Object
{
ETI_CLASS_EXT(Foo, Object, ETI_PROPERTIES(), ETI_METHODS())
public:
Foo() {}
~Foo() override {}
};
TEST_CASE("test_05")
{
{
const Type& type = TypeOf<Object>();
REQUIRE(type.Name == "test_05::Object");
REQUIRE(type.Id != 0);
REQUIRE(type.Kind == Kind::Class);
REQUIRE(type.Size == sizeof(Object));
REQUIRE(type.Align == alignof(Object));
REQUIRE(type.Parent == nullptr);
}
{
const Type& type = TypeOf<Foo>();
REQUIRE(type.Name == "test_05::Foo");
REQUIRE(type.Id != 0);
REQUIRE(type.Kind == Kind::Class);
REQUIRE(type.Size == sizeof(Object));
REQUIRE(type.Align == alignof(Object));
REQUIRE(type.Parent != nullptr);
REQUIRE(*type.Parent == TypeOf<Object>());
}
{
Object o;
Foo f;
REQUIRE(IsA<Object>(o));
REQUIRE(IsA<Object>(f));
REQUIRE(!IsA<Foo>(o));
REQUIRE(IsA<Foo>(f));
}
{
REQUIRE(IsATyped<Object, Object>());
REQUIRE(IsATyped<Foo, Object>());
REQUIRE(!IsATyped<Object, Foo>());
REQUIRE(IsATyped<Foo, Foo>());
}
}
}
namespace test_06
{
int construct = 0;
int copyConstruct = 0;
int moveConstruct = 0;
int destruct = 0;
struct Foo
{
ETI_STRUCT(Foo)
static constexpr int IntValue = 1;
Foo()
{
++construct;
ptrInt = (int*)malloc(sizeof(int));
*ptrInt = IntValue;
}
Foo(const Foo& foo)
{
copyConstruct++;
ptrInt = (int*)malloc(sizeof(int));
*ptrInt = *foo.ptrInt;
}
Foo(Foo&& foo)
{
moveConstruct++;
ptrInt = foo.ptrInt;
foo.ptrInt = nullptr;
}
~Foo()
{
destruct++;
if (ptrInt != nullptr)
{
free(ptrInt);
ptrInt = nullptr;
}
}
int* ptrInt = nullptr;
};
TEST_CASE("test_06")
{
const Type& type = TypeOf<Foo>();
// standard behavior
{
construct = 0;
copyConstruct = 0;
moveConstruct = 0;
destruct = 0;
{
Foo foo1;
Foo foo2(std::move(foo1));
}
REQUIRE(construct == 1);
REQUIRE(copyConstruct == 0);
REQUIRE(moveConstruct == 1);
REQUIRE(destruct == 2);
}
// construct / destruct
{
construct = 0;
copyConstruct = 0;
moveConstruct = 0;
destruct = 0;
Foo* foo = (Foo*)malloc(type.Size);
memset(foo, 0, sizeof(Foo));
REQUIRE(construct == 0);
REQUIRE(destruct == 0);
REQUIRE(foo->ptrInt == nullptr);
type.Construct(foo);
REQUIRE(construct == 1);
REQUIRE(destruct == 0);
REQUIRE(foo->ptrInt != nullptr);
REQUIRE(*foo->ptrInt == Foo::IntValue);
type.Destruct(foo);
REQUIRE(construct == 1);
REQUIRE(destruct == 1);
REQUIRE(foo->ptrInt == nullptr);
free(foo);
REQUIRE(copyConstruct == 0);
REQUIRE(moveConstruct == 0);
}
// construct / copy construct / destruct
{
construct = 0;
copyConstruct = 0;
moveConstruct = 0;
destruct = 0;
Foo* foo1 = (Foo*)malloc(type.Size);
memset(foo1, 0, sizeof(Foo));
Foo* foo2 = (Foo*)malloc(type.Size);
memset(foo2, 0, sizeof(Foo));
type.Construct(foo1);
REQUIRE(foo1->ptrInt != nullptr);
REQUIRE(*foo1->ptrInt == Foo::IntValue);
type.CopyConstruct(foo1, foo2);
REQUIRE(*foo2->ptrInt == Foo::IntValue);
type.Destruct(foo1);
REQUIRE(foo1->ptrInt == nullptr);
type.Destruct(foo2);
REQUIRE(foo2->ptrInt == nullptr);
free(foo1);
free(foo2);
REQUIRE(construct == 1);
REQUIRE(copyConstruct == 1);
REQUIRE(moveConstruct == 0);
REQUIRE(destruct == 2);
}
// construct / move / destruct
{
construct = 0;
copyConstruct = 0;
moveConstruct = 0;
destruct = 0;
Foo* foo1 = (Foo*)malloc(type.Size);
memset(foo1, 0, sizeof(Foo));
Foo* foo2 = (Foo*)malloc(type.Size);
memset(foo2, 0, sizeof(Foo));
type.Construct(foo1);
REQUIRE(foo1->ptrInt != nullptr);
REQUIRE(*foo1->ptrInt == Foo::IntValue);
type.MoveConstruct(foo1, foo2);
REQUIRE(foo1->ptrInt == nullptr);
type.Destruct(foo1);
REQUIRE(foo1->ptrInt == nullptr);
type.Destruct(foo2);
REQUIRE(foo2->ptrInt == nullptr);
REQUIRE(construct == 1);
REQUIRE(copyConstruct == 0);
REQUIRE(moveConstruct == 1);
REQUIRE(destruct == 2);
free(foo1);
free(foo2);
}
}
}
namespace test_07
{
TEST_CASE("test_07")
{
int i;
int& iRef = i;
const int& iConstRef = i;
int* iPtr = nullptr;
const int* iConstPtr = nullptr;
int const* iPtrConst = nullptr;
std::string_view iName = GetTypeName<decltype(i)>();
std::string_view iRefName = GetTypeName<decltype(iRef)>();
std::string_view iConstRefName = GetTypeName<decltype(iConstRef)>();
std::string_view iPtrName = GetTypeName<decltype(iPtr)>();
std::string_view iConstPtrName = GetTypeName<decltype(iConstPtr)>();
std::string_view iPtrConstName = GetTypeName<decltype(iPtrConst)>();
REQUIRE(iName == "s32");
REQUIRE(iRefName == "s32");
REQUIRE(iConstRefName == "s32");
REQUIRE(iPtrName == "s32");
REQUIRE(iConstPtrName == "s32");
REQUIRE(iPtrConstName == "s32");
}
}
namespace test_08
{
struct Foo
{
ETI_STRUCT_EXT(Foo,
ETI_PROPERTIES
(
ETI_PROPERTY(i),
ETI_PROPERTY(f),
ETI_PROPERTY(ptr),
ETI_PROPERTY(fv)
),
ETI_METHODS()
)
int i = 0;
float f = 0.0f;
int* ptr = nullptr;
std::vector<float> fv;
};
TEST_CASE("test_08")
{
const Type& type = TypeOf<Foo>();
REQUIRE(type.Properties.size() == 4);
REQUIRE(type.Properties[0].Variable.Name == "i");
REQUIRE(type.Properties[0].Offset == 0);
REQUIRE(type.Properties[0].Variable.Declaration.IsPtr == false);
REQUIRE(type.Properties[0].Variable.Declaration.Type->Id == TypeOf<int>().Id);
REQUIRE(type.Properties[1].Variable.Name == "f");
REQUIRE(type.Properties[1].Offset == 4);
REQUIRE(type.Properties[1].Variable.Declaration.IsPtr == false);
REQUIRE(type.Properties[1].Variable.Declaration.Type->Id == TypeOf<float>().Id);
REQUIRE(type.Properties[2].Variable.Name == "ptr");
REQUIRE(type.Properties[2].Offset == 8);
REQUIRE(type.Properties[2].Variable.Declaration.IsPtr == true);
REQUIRE(type.Properties[2].Variable.Declaration.Type->Id == TypeOf<int>().Id);
REQUIRE(type.Properties[3].Variable.Name == "fv");
REQUIRE(type.Properties[3].Offset == 16);
REQUIRE(type.Properties[3].Variable.Declaration.IsPtr == false);
REQUIRE(type.Properties[3].Variable.Declaration.Type->Id == TypeOf<std::vector<float>>().Id);
}
}
namespace test_09
{
struct Foo
{
ETI_STRUCT_EXT(Foo,
ETI_PROPERTIES(),
ETI_METHODS(
ETI_METHOD(GetI),
ETI_METHOD(SetI)
))
int GetI()
{
return i;
}
void SetI(int value)
{
i = value;
}
int i = 3;
};
TEST_CASE("test_09")
{
{
const Method* method = TypeOf<Foo>().GetMethod("GetI");
REQUIRE(method != nullptr);
Foo foo;
int ret = 0;
method->Function(&foo, &ret, {});
REQUIRE(foo.i == ret);
}
{
const Method* method = TypeOf<Foo>().GetMethod("SetI");
REQUIRE(method != nullptr);
REQUIRE(method->Arguments.size() == 1);
REQUIRE(*method->Arguments[0].Declaration.Type == TypeOf<int>());
Foo foo;
std::vector<void*> args;
int value = 99;
args.push_back(&value);
method->Function(&foo, nullptr, args);
REQUIRE(foo.i == value);
}
}
}
namespace test_10
{
struct Foo
{
ETI_STRUCT_EXT(Foo,
ETI_PROPERTIES
(
ETI_PROPERTY(i, Accessibility(Access::Private)),
),
ETI_METHODS()
)
int i = 0;
};
TEST_CASE("test_09")
{
const Type& fooType = TypeOf<Foo>();
const Property* property = fooType.GetProperty("i");
REQUIRE(property != nullptr);
REQUIRE(property->Attributes.size() == 1);
REQUIRE(IsA<Accessibility>(*property->Attributes[0]));
REQUIRE(property->GetAttribute<Accessibility>() != nullptr);
}
}
namespace test_11
{
int construct = 0;
int copyConstruct = 0;
int moveConstruct = 0;
int destruct = 0;
void ResetCounters()
{
construct = 0;
copyConstruct = 0;
moveConstruct = 0;
destruct = 0;
}
struct Foo
{
ETI_STRUCT(Foo)
static constexpr int IntValue = 1;
Foo()
{
++construct;
}
Foo(const Foo&)
{
copyConstruct++;
}
Foo(Foo&&)
{
moveConstruct++;
}
~Foo()
{
destruct++;
}
int Int = 123;
};
TEST_CASE("test_11")
{
{
ResetCounters();
REQUIRE(construct == 0);
REQUIRE(copyConstruct == 0);
REQUIRE(moveConstruct == 0);
REQUIRE(destruct == 0);
Foo* foo = new Foo;
REQUIRE(foo != nullptr);
REQUIRE(foo->Int == 123);
delete(foo);
REQUIRE(construct == 1);
REQUIRE(copyConstruct == 0);
REQUIRE(moveConstruct == 0);
REQUIRE(destruct == 1);
}
{
ResetCounters();
REQUIRE(construct == 0);
REQUIRE(copyConstruct == 0);
REQUIRE(moveConstruct == 0);
REQUIRE(destruct == 0);
{
Foo foo1;
foo1.Int = 321;
Foo* foo2 = new Foo(foo1);
delete(foo2);
}
REQUIRE(construct == 1);
REQUIRE(copyConstruct == 1);
REQUIRE(moveConstruct == 0);
REQUIRE(destruct == 2);
}
}
}
namespace test_12
{
struct Foo
{
void MemberFunction() {}
static void StaticFunction() {}
};
TEST_CASE("test_09")
{
constexpr bool isMemberFunctionStatic = utils::IsMethodStatic<decltype(&Foo::MemberFunction)>;
constexpr bool isStaticFunctionStatic = utils::IsMethodStatic<decltype(&Foo::StaticFunction)>;
static_assert(isMemberFunctionStatic == false);
static_assert(isStaticFunctionStatic == true);
}
}
namespace test_13
{
struct Foo
{
ETI_STRUCT_EXT(
Foo,
ETI_PROPERTIES(),
ETI_METHODS(ETI_METHOD(MemberFunction)))
void MemberFunction() {}
};
TEST_CASE("test_13")
{
const Type& type = TypeOf<Foo>();
const Method* method = type.GetMethod("MemberFunction");
REQUIRE(method != nullptr);
REQUIRE(method->Return->Declaration.Type->Kind == Kind::Void);
}
}
namespace test_14
{
struct Foo
{
ETI_STRUCT_EXT(
Foo,
ETI_PROPERTIES
(
ETI_PROPERTY(intValue),
ETI_PROPERTY(intConstValue),
ETI_PROPERTY(intPtr),
ETI_PROPERTY(intConstPtr),
),
ETI_METHODS())
int intValue;
const int intConstValue;
int* intPtr;
const int* intConstPtr;
};
TEST_CASE("test_14")
{
{
const Property* p = TypeOf<Foo>().GetProperty("intValue");
const Declaration& decl = p->Variable.Declaration;
REQUIRE(decl.IsValue == true);
REQUIRE(decl.IsConst == false);
REQUIRE(decl.IsPtr == false);
REQUIRE(decl.IsRef == false);
}
{
const Property* p = TypeOf<Foo>().GetProperty("intConstValue");
const Declaration& decl = p->Variable.Declaration;
REQUIRE(decl.IsValue == true);
REQUIRE(decl.IsConst == true);
REQUIRE(decl.IsPtr == false);
REQUIRE(decl.IsRef == false);
}
{
const Property* p = TypeOf<Foo>().GetProperty("intPtr");
const Declaration& decl = p->Variable.Declaration;
REQUIRE(decl.IsValue == false);
REQUIRE(decl.IsConst == false);
REQUIRE(decl.IsPtr == true);
REQUIRE(decl.IsRef == false);
}
{
const Property* p = TypeOf<Foo>().GetProperty("intConstPtr");
const Declaration& decl = p->Variable.Declaration;
REQUIRE(decl.IsValue == false);
REQUIRE(decl.IsConst == true);
REQUIRE(decl.IsPtr == true);
REQUIRE(decl.IsRef == false);
}
}
}
namespace test_15
{
struct Foo
{
ETI_STRUCT_EXT(
Foo,
ETI_PROPERTIES
(
ETI_PROPERTY(intValue),
ETI_PROPERTY(intConstValue),
ETI_PROPERTY(intPtr),
ETI_PROPERTY(intConstPtr),
),
ETI_METHODS())
int intValue = 0;
const int intConstValue = 1;
int* intPtr = nullptr;
const int* intConstPtr = nullptr;
};
TEST_CASE("test_15")
{
int intValue = 1;
int intConstValue = 1;
int* intPtr = nullptr;
const int* intConstPtr = nullptr;
int someValue = 101;
Foo foo = { intValue, intConstValue, intPtr, intConstPtr };
{
const Property* p = TypeOf<Foo>().GetProperty("intValue");
void* ptr = p->UnSafeGetPtr(&foo);
REQUIRE(ptr == &foo.intValue);
p->Set(foo, 12);
REQUIRE(foo.intValue == 12);
}
{
const Property* p = TypeOf<Foo>().GetProperty("intConstValue");
void* ptr = p->UnSafeGetPtr(&foo);
REQUIRE(ptr == &foo.intConstValue);
p->Set(foo, 12);
REQUIRE(foo.intConstValue == 12);
}
{
const Property* p = TypeOf<Foo>().GetProperty("intPtr");
void* ptr = p->UnSafeGetPtr(&foo);
REQUIRE(ptr == &foo.intPtr);
p->Set(foo, &someValue);
REQUIRE(*foo.intPtr == someValue);
}
{
const Property* p = TypeOf<Foo>().GetProperty("intConstPtr");
void* ptr = p->UnSafeGetPtr(&foo);
REQUIRE(ptr == &foo.intConstPtr);
p->Set(foo, &someValue);
REQUIRE(*foo.intConstPtr == someValue);
}
}
}
namespace test_16
{
class Foo;
class Doo;
class Object
{
ETI_BASE_EXT(Object, ETI_PROPERTIES
(
ETI_PROPERTY(ObjectPtr),
ETI_PROPERTY(FooPtr),
ETI_PROPERTY(DooPtr),
),
ETI_METHODS())
public:
Object* ObjectPtr = nullptr;
Foo* FooPtr = nullptr;
Doo* DooPtr = nullptr;
Object() {}
virtual ~Object() {}
};
class Foo : public Object
{
ETI_CLASS(Foo, Object)
};
class Doo : public Object
{
ETI_CLASS(Foo, Object)
};
TEST_CASE("test_16")
{
Object object;
Foo foo;
Doo doo;
const Type& objectType = Object::GetTypeStatic();
const Property* objectPtrProperty = objectType.GetProperty("ObjectPtr");
objectPtrProperty->Set(object, &object);
REQUIRE(object.ObjectPtr == &object);
Object* obj;
objectPtrProperty->Get(object, obj);
REQUIRE(obj == object.ObjectPtr);
objectPtrProperty->Set(object, &foo);
REQUIRE(object.ObjectPtr == &foo);
objectPtrProperty->Get(object, obj);
REQUIRE(obj == object.ObjectPtr);
objectPtrProperty->Set(object, &doo);
REQUIRE(object.ObjectPtr == &doo);
objectPtrProperty->Get(object, obj);
REQUIRE(obj == object.ObjectPtr);
}
}
namespace test_17
{
class Foo;
class Doo;
class Object
{
ETI_BASE_EXT
(
Object,
ETI_PROPERTIES(ETI_PROPERTY(I)),
ETI_METHODS
(
ETI_METHOD(GetName),
ETI_METHOD(Add),
ETI_METHOD(GetIPtr, Accessibility(Access::Public))
),
Accessibility(Access::Public)
)
public:
virtual ~Object() {}
static double Add(int n0, float n1) { return n0 + n1; }
int* GetIPtr() { return &I; }
int I = 12;
protected:
virtual std::string_view GetName() { return "my name is Object"; }
};
class Foo : public Object
{
ETI_CLASS_EXT
(
Foo, Object,
ETI_PROPERTIES(),
ETI_METHODS()
)
public:
~Foo() override {}
protected:
std::string_view GetName() override { return "my name is Foo"; }
};
class Doo : public Object
{
ETI_CLASS_EXT
(
Doo, Object,
ETI_PROPERTIES(),
ETI_METHODS()
)
public:
~Doo() override {}
protected:
std::string_view GetName() override { return "my name is Doo"; }
};
TEST_CASE("test_17")
{
Object obj;
Foo foo;
Doo doo;
{
const Method* getNameMethod = TypeOf<Object>().GetMethod("GetName");
std::string_view name;
getNameMethod->CallMethod(obj, &name);
REQUIRE(name == "my name is Object");
getNameMethod->CallMethod(foo, &name);
REQUIRE(name == "my name is Foo");
getNameMethod->CallMethod(doo, &name);
REQUIRE(name == "my name is Doo");
}
{
const Method* addMethod = TypeOf<Object>().GetMethod("Add");
double result = 0.0f;
float p1 = 2.0f;
addMethod->CallStaticMethod(&result, 1, p1);
REQUIRE((int)result == 3);
}
{
const Method* getIPtrMethod = TypeOf<Object>().GetMethod("GetIPtr");
int* getIPtr = nullptr;
getIPtrMethod->CallMethod(foo, &getIPtr);
int* iPtr = &foo.I;
REQUIRE(iPtr == getIPtr);
*getIPtr = 3;
REQUIRE(foo.I == 3);
const Accessibility* accessibility= getIPtrMethod->GetAttribute<Accessibility>();
REQUIRE(accessibility != nullptr);
REQUIRE(accessibility->Access == Access::Public);
}
{
const Type& objType = TypeOf<Object>();
const Accessibility* accessibility = objType.GetAttribute<Accessibility>();
REQUIRE(accessibility != nullptr);
REQUIRE(accessibility->Access == Access::Public);
}
}
}
namespace third_party
{
struct Point
{
float GetX() { return X; }
float GetY() { return Y; }
void SetX(float value) { X = value; }
void SetY(float value) { Y = value; }
float X = 0.0f;
float Y = 0.0f;
};
class Base
{
public:
virtual ~Base(){}
std::string_view GetName() { return "My name is Base"; }
};
class Foo
{
public:
std::string_view GetName() { return "My name is Foo"; }
};
}
ETI_STRUCT_EXTERNAL(::third_party::Point, ETI_PROPERTIES(ETI_PROPERTY(X), ETI_PROPERTY(Y)), ETI_METHODS(ETI_METHOD(GetX), ETI_METHOD(SetX)), eti::Accessibility(eti::Access::Public))
ETI_BASE_EXTERNAL(::third_party::Base, ETI_PROPERTIES(), ETI_METHODS());
ETI_CLASS_EXTERNAL(::third_party::Foo, ::third_party::Base, ETI_PROPERTIES(), ETI_METHODS(ETI_METHOD(GetName)));
namespace test_18
{
using namespace eti;
using namespace third_party;
TEST_CASE("test_18")
{
const Type& type = TypeOf<Point>();
REQUIRE(type.Name == "third_party::Point");
REQUIRE(type.GetProperty("X") != nullptr);
REQUIRE(type.GetProperty("Y") != nullptr);
REQUIRE(type.GetMethod("GetX") != nullptr);
REQUIRE(type.GetMethod("SetX") != nullptr);
Point p;
type.GetProperty("X")->Set(p, 1.0f);
REQUIRE(p.X == 1.0f);
type.GetMethod("SetX")->CallMethod(p, NoReturn, 2.0f);
REQUIRE(p.X == 2.0f);
float x;
type.GetMethod("GetX")->CallMethod(p, &x);
REQUIRE(p.X == 2.0f);
REQUIRE(type.Attributes.size() == 1);
REQUIRE(type.GetAttribute<::eti::Accessibility>() != nullptr);
REQUIRE(type.GetAttribute<::eti::Accessibility>()->Access == ::eti::Access::Public);
// note: IsA not available on external defined type since cannot add virtual method (will not compile)
// but IsATyped is available
REQUIRE(IsATyped<Foo, Base>());
REQUIRE(TypeOf<Foo>().GetMethod("GetName") != nullptr);
Foo foo;
std::string_view name;
TypeOf<Foo>().GetMethod("GetName")->CallMethod(foo, &name);
REQUIRE(name == "My name is Foo");
}
}
namespace test_20
{
// const methods test
struct Point
{
ETI_STRUCT_EXT(Point, ETI_PROPERTIES(), ETI_METHODS( ETI_METHOD(GetX) ) )
int GetX() const { return X; }
int X = 0;
};
TEST_CASE("test_20")
{
Point p;
int x = -1;
TypeOf<Point>().GetMethod("GetX")->CallMethod(p, &x);
REQUIRE(x == 0);
}
}
namespace test_21
{
using namespace eti;
struct Foo
{
ETI_STRUCT_EXT(Foo,
ETI_PROPERTIES
(
ETI_PROPERTY(Values)
),
ETI_METHODS())
std::vector<int> Values;
};
void AddValue(const Property* property, void* foo, int value)
{
const Type& propertyType = *property->Variable.Declaration.Type;
if (propertyType.Kind == Kind::Class &&
propertyType.Templates.size() == 1 &&
*propertyType.Templates[0].Type == TypeOf<int>() &&
propertyType == TypeOf<std::vector<int>>())
{
// ok to cast here, we validated type
std::vector<int>* vector = (std::vector<int>*)property->UnSafeGetPtr(foo);
vector->push_back(value);
}
}
TEST_CASE("test_21")
{
Foo foo;
AddValue(TypeOf<Foo>().GetProperty("Values"), &foo, 123);
REQUIRE(foo.Values.size() == 1);
REQUIRE(foo.Values[0] == 123);
}
}
namespace test_22
{
ETI_ENUM
(
std::uint8_t, Day,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
)
struct Time
{
ETI_STRUCT_EXT(Time,
ETI_PROPERTIES
(
ETI_PROPERTY(Day)
), ETI_METHODS())
Day Day = Day::Friday;
};
TEST_CASE("test_22")
{
Time time;
Day day;
TypeOf<Time>().GetProperty("Day")->Get(time, day);
REQUIRE(day == Day::Friday);
TypeOf<Time>().GetProperty("Day")->Set(time, Day::Monday);
REQUIRE(time.Day == Day::Monday);
}
}
ETI_ENUM_IMPL(test_22::Day)
namespace test_23
{
struct Time
{
ETI_ENUM
(
std::uint8_t, Day,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
)
ETI_STRUCT_EXT(Time,
ETI_PROPERTIES
(
ETI_PROPERTY(CurrentDay)
), ETI_METHODS())
Day CurrentDay = Day::Friday;
};
TEST_CASE("test_23")
{
Time time;
Time::Day day;
TypeOf<Time>().GetProperty("CurrentDay")->Get(time, day);
REQUIRE(day == Time::Day::Friday);
TypeOf<Time>().GetProperty("CurrentDay")->Set(time, Time::Day::Monday);
REQUIRE(time.CurrentDay == Time::Day::Monday);
}
}
ETI_ENUM_IMPL(test_23::Time::Day)
namespace test_24
{
// all kind of return args
struct Foo
{
ETI_STRUCT_EXT
(
Foo,
ETI_PROPERTIES(),
ETI_METHODS
(
ETI_METHOD(Get),
ETI_METHOD(Set),
ETI_METHOD(GetRef),
ETI_METHOD(GetPtr),
ETI_METHOD(GetValueRef),
ETI_METHOD(SetValueRef),
ETI_METHOD(GetValuePtr),
ETI_METHOD(SetValuePtr),
ETI_METHOD(GetValuePtrPtr)
)
)
int Get() { return Value; }
void Set(int v) { Value = v; }
int& GetRef() { return Value; }
int* GetPtr() { return &Value; }
void GetValueRef(int& v)
{
v = Value;
}
void SetValueRef(const int& v) { Value = v; }
void GetValuePtr(int* v)
{
*v = Value;
}
void SetValuePtr(const int* v) { Value = *v; }
void GetValuePtrPtr(int** v)
{
*v = &Value;
}
int Value = 1;
};
TEST_CASE("test_24")
{
{
// int Get() { return Value; }
Foo foo;
int value = 0;
const Method* method = TypeOf<Foo>().GetMethod("Get");
method->CallMethod(foo, &value);
REQUIRE(value == 1);
}
{
// void Set(int v) { Value = v; }
Foo foo;
const Method* method = TypeOf<Foo>().GetMethod("Set");
method->CallMethod(foo, NoReturn, 2);
REQUIRE(foo.Value == 2);
}
{
// int& GetRef() { return Value; }
Foo foo;
int* value = nullptr;
const Method* method = TypeOf<Foo>().GetMethod("GetRef");
method->CallMethod(foo, &value);
REQUIRE(*value == 1);
*value = 2;
REQUIRE(foo.Value == 2);
}
{
// int& GetPtr() { return Value; }
Foo foo;
int* value = nullptr;
const Method* method = TypeOf<Foo>().GetMethod("GetPtr");
method->CallMethod(foo, &value);
REQUIRE(*value == 1);
*value = 2;
REQUIRE(foo.Value == 2);
}
{
//void GetValueRef(int& v) { v = Value; }
Foo foo;
int value = 9;
const Method* method = TypeOf<Foo>().GetMethod("GetValueRef");
method->CallMethod(foo, NoReturn, &value);
REQUIRE(value == 1);
}
{
//void SetValueRef(const int& v) { Value = v; }
Foo foo;
int value = 9;
const Method* method = TypeOf<Foo>().GetMethod("SetValueRef");
method->CallMethod(foo, NoReturn, &value);
REQUIRE(foo.Value == 9);
}
{
//void GetValuePtr(int* v) { *v = Value; }
Foo foo;
int value = 9;
const Method* method = TypeOf<Foo>().GetMethod("GetValuePtr");
method->CallMethod(foo, NoReturn, &value);
REQUIRE(value == 1);
}
{
//void SetValuePtr(const int* v) { Value = *v; }
Foo foo;
int value = 9;
const Method* method = TypeOf<Foo>().GetMethod("SetValuePtr");
method->CallMethod(foo, NoReturn, &value);
REQUIRE(foo.Value == 9);
}
{
// void GetValuePtrPtr(int** v)
Foo foo;
int* ptr = nullptr;
const Method* method = TypeOf<Foo>().GetMethod("GetValuePtrPtr");
method->CallMethod(foo, NoReturn, &ptr);
REQUIRE(*ptr == 1);
*ptr = 12;
REQUIRE(foo.Value == 12);
}
}
// vector
TEST_CASE("test_25")
{
const Type& type = TypeOf<std::vector<int>>();
{
std::vector<int> vector;
vector.push_back(1);
vector.push_back(2);
const Method* m = type.GetMethod("GetSize");
size_t size = 0;
m->CallMethod(vector, &size);
REQUIRE(size == 2);
}
{
std::vector<int> vector;
vector.push_back(1);
vector.push_back(2);
const Method* m = type.GetMethod("GetAt");
int* value;
m->CallMethod(vector, &value, (size_t)1);
REQUIRE(*value == 2);
*value = 3;
REQUIRE(vector[1] == 3);
}
{
std::vector<int> vector;
vector.push_back(1);
vector.push_back(2);
const Method* m = type.GetMethod("Add");
int three = 3;
int four = 4;
m->CallMethod(vector, NoReturn, &three);
m->CallMethod(vector, NoReturn, &four);
REQUIRE(vector.size() == 4);
REQUIRE(vector[2] == 3);
REQUIRE(vector[3] == 4);
}
{
std::vector<int> vector;
vector.push_back(1);
vector.push_back(2);
const Method* m = type.GetMethod("AddAt");
int three = 3;
int four = 4;
m->CallMethod(vector, NoReturn, (size_t)0, &three);
m->CallMethod(vector, NoReturn, (size_t)1, &four);
REQUIRE(vector.size() == 4);
REQUIRE(vector[0] == 3);
REQUIRE(vector[1] == 4);
}
{
std::vector<int> vector;
vector.push_back(1);
vector.push_back(2);
const Method* m = type.GetMethod("Contains");
int one = 1;
int three = 3;
bool result;
m->CallMethod(vector, &result, &one);
REQUIRE(result == true);
m->CallMethod(vector, &result, &three);
REQUIRE(result == false);
}
{
std::vector<int> vector;
vector.push_back(1);
vector.push_back(2);
const Method* m = type.GetMethod("Remove");
int one = 1;
int three = 3;
bool result;
m->CallMethod(vector, &result, &one);
REQUIRE(result == true);
REQUIRE(vector.size() == 1);
m->CallMethod(vector, &result, &three);
REQUIRE(result == false);
}
{
std::vector<int> vector;
vector.push_back(1);
vector.push_back(2);
const Method* m = type.GetMethod("Clear");
m->CallMethod(vector, NoReturn);
REQUIRE(vector.size() == 0);
}
}
// map
TEST_CASE("test_26")
{
{
std::map<std::string, int> map;
map["1212"] = 1212;
const Type& type = TypeOf<std::map<std::string, int>>();
const Method* sizeMethod = type.GetMethod("GetSize");
size_t size;
sizeMethod->CallMethod(map, &size);
REQUIRE(size == 1);
}
{
std::map<std::string, int> map;
map["1212"] = 1212;
const Type& type = TypeOf<std::map<std::string, int>>();
const Method* sizeMethod = type.GetMethod("GetValue");
int* value;
std::string key = "1212";
sizeMethod->CallMethod(map, &value, &key);
REQUIRE(*value == 1212 );
*value = 3434;
REQUIRE(map["1212"] == 3434);
}
{
std::map<std::string, int> map;
map["1212"] = 1212;
const Type& type = TypeOf<std::map<std::string, int>>();
const Method* sizeMethod = type.GetMethod("Contains");
bool result;
std::string key = "1212";
sizeMethod->CallMethod(map, &result, &key);
REQUIRE(result == true );
std::string key2 = "3434";
sizeMethod->CallMethod(map, &result, &key2);
REQUIRE(result == false );
}
{
const Type& type = TypeOf<std::map<std::string, int>>();
const Method* method = type.GetMethod("Insert");
std::map<std::string, int> map;
std::string key = "1212";
int value = 1212;
int* result;
method->CallMethod(map, &result, &key, &value);
REQUIRE(map.size() == 1);
REQUIRE(map.find(key) != map.end());
REQUIRE(map[key] == value);
*result = 3434;
REQUIRE(map[key] == 3434);
}
{
const Type& type = TypeOf<std::map<std::string, int>>();
const Method* method = type.GetMethod("InsertOrGet");
std::map<std::string, int> map;
map["1212"] = 9999;
std::string key = "1212";
int value = 1212;
int* result;
method->CallMethod(map, &result, &key, &value);
REQUIRE(map.size() == 1);
REQUIRE(map.find(key) != map.end());
REQUIRE(map[key] == 9999);
*result = 3434;
REQUIRE(map[key] == 3434);
}
{
const Type& type = TypeOf<std::map<std::string, int>>();
const Method* method = type.GetMethod("Remove");
std::map<std::string, int> map;
map["1212"] = 1212;
map["3434"] = 3434;
bool result;
std::string key = "1212";
method->CallMethod(map, &result, &key);
REQUIRE(result == true);
REQUIRE(map.size() == 1);
method->CallMethod(map, &result, &key);
REQUIRE(result == false);
}
{
const Type& type = TypeOf<std::map<std::string, int>>();
const Method* method = type.GetMethod("Clear");
std::map<std::string, int> map;
map["1212"] = 1212;
method->CallMethod(map, NoReturn);
REQUIRE(map.size() == 0);
}
{
const Type& type = TypeOf<std::map<std::string, int>>();
const Method* method = type.GetMethod("GetKeys");
std::map<std::string, int> map;
map["1212"] = 1212;
std::vector<std::string> keys;
method->CallMethod(map, NoReturn, &keys);
REQUIRE(keys.size() == 1);
REQUIRE(keys[0] == "1212");
}
}
}
namespace test_27
{
struct Foo
{
ETI_STRUCT_EXT
(Foo,
ETI_PROPERTIES(),
ETI_METHODS
(
ETI_METHOD_LAMBDA(Test, [](Foo& foo) { return foo.X; }),
ETI_METHOD_LAMBDA(Test2, [](Foo&, int x, int y) { return x + y; })
)
)
int X = 1;
};
TEST_CASE("test_27")
{
Foo foo;
const Type& type = TypeOf<Foo>();
const Method* m = type.GetMethod("Test");
int ret = 0;
m->CallMethod(foo, &ret);
REQUIRE(ret == 1);
const Method* m2 = type.GetMethod("Test2");
ret = 0;
m2->CallMethod(foo, &ret, 1,2);
REQUIRE(ret == 3);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Moteeullah Azmi</title>
</head>
<body style="background-color: #212121; color:#ffff;" >
<ul class="language">
<li>JavaScript</li>
</ul>
</body>
<script>
function addLanguage(langName){
const li = document.createElement('li');
li.innerHTML = `${langName}`
document.querySelector('.language').appendChild(li)
}
addLanguage("python")
addLanguage("TypeScript")
// Optimize best Approach
function addOptiLang(langName){
const li = document.createElement('li');
li.appendChild(document.createTextNode(langName));
document.querySelector('.language').appendChild(li)
}
addOptiLang('golang');
// edit -1
const secondlang = document.querySelector('li:nth-child(2)');
// secondlang.innerHTML = "Mojo";
// best approach
const newli = document.createElement('li')
newli.textContent = "Mojo"
secondlang.replaceWith(newli); //replace
// edit-2
const firstlang = document.querySelector('li:first-child');
firstlang.outerHTML = '<li>TypeScript</li>'
// remove
const lastLang= document.querySelector('li:last-child');
lastLang.remove()
</script>
</html> |
import React, { useState, useEffect, useCallback, useContext } from "react";
//libraries
import { Button, Input, Radio, Tabs, Modal, Form, message } from "antd";
import { BsRobot } from "react-icons/bs";
import { FaHashtag } from "react-icons/fa6";
//Hooks
import useAssistantFileUpload from "../../../Hooks/useAssistantFileUpload";
//Components
import AssistantForm from "./AssistantForm";
import { getUserID } from "../../../Utility/service";
import { AssistantContext } from "../../../contexts/AssistantContext";
import FunctionCallingAssistantForm from "./FunctionCallingAssistantForm";
const { TabPane } = Tabs;
const CreateAssistantModal = ({ data }) => {
const {
assistantData,
setAssistantData,
assistantFunctionCallData,
setAssistantFunctionCallData,
showModal,
handleClose,
editMode,
isAdmin,
handleFetchUserCreatedAssistants,
handleFetchAllAssistants,
handleFetchFunctionCallingAssistants,
isFunctionCallingAssistant,
activeKey,
setActiveKey,
} = data;
const [form] = Form.useForm();
const [deleteFileIds, setDeleteFileIds] = useState([]);
const [selectedTools ,setSelectedTools] = useState([]);
const { triggerRefetchAssistants } = useContext(AssistantContext);
//----Callback----//
const handleDeleteFileId = useCallback(
(index) => {
const fileId = assistantData.file_ids[index];
setDeleteFileIds((prev) => [...prev, fileId]);
},
[assistantData.file_ids, setDeleteFileIds]
);
const getInitialFiles = useCallback(() => assistantData?.fileNames || [], [assistantData?.fileNames]);
//--Side Effects---//
useEffect(() => {
form.setFieldsValue(assistantData);
const newSelectedTools = assistantData?.tools?.map((tool) => tool) || [];
setSelectedTools(newSelectedTools);
//cleanup
return () => {
setDeleteFileIds([]);
}
}, [assistantData, form]);
//------Hooks Declaration ------//
const {
fileList,
setFileList,
isUploading,
handleCreateOrUpdateAssistantWithFiles,
handleRemoveFile,
handleAddFile,
} = useAssistantFileUpload(
handleDeleteFileId,
selectedTools,
getInitialFiles
);
//------Api calls --------//
const handleUploadFileAndCreateAssistant = async () => {
try {
const formData = new FormData();
const formValues = form.getFieldsValue();
if(!formValues.assistantId && !editMode) {
await form.validateFields();
}
fileList.forEach((file) => {
formData.append("files", file);
});
if (deleteFileIds.length > 0) {
formData.append("deleted_files", JSON.stringify(deleteFileIds));
}
if (!editMode) {
formData.append("userId", getUserID());
}
if (!isAdmin) {
formData.append("category", "PERSONAL");
}
Object.entries(formValues).forEach(([key, value]) => {
if (key === "tools") {
formData.append("tools", JSON.stringify(value));
} else if (key === "static_questions") {
formData.append("staticQuestions", JSON.stringify(value));
} else {
formData.append(key, value);
}
});
const success = await handleCreateOrUpdateAssistantWithFiles(
formData,
editMode,
assistantData?.assistant_id
);
if (success) {
console.log("success");
handleClose();
handleFetchUserCreatedAssistants();
if (editMode) {
// update assistant list
triggerRefetchAssistants();
}
if (isAdmin) {
handleFetchAllAssistants(1);
}
}
} catch (error) {
message.error("Please correct the errors in the form before proceeding.");
}
};
//----Local Functions--------//
const handleFormChange = (changedValues, allValues) => {
setAssistantData((prevData) => ({
...prevData,
...changedValues,
}));
};
const handleFunctionCallingFormChange =(changedValues, allValues)=>{
setAssistantFunctionCallData((prevData)=> ({
...prevData,
...changedValues,
}));
};
const handleSwitchChange = (tool, checked) => {
const tools = form.getFieldValue("tools") || [];
const updatedTools = checked
? [...tools, tool]
: tools.filter((existingTool) => existingTool !== tool);
form.setFieldsValue({ tools: updatedTools });
setSelectedTools([updatedTools])
setAssistantData((prevData) => ({
...prevData,
tools: updatedTools
}));
};
function handleTabChange(key) {
setActiveKey(key);
}
return (
<>
<Modal
title={editMode ? "" : "Create Assistant"}
open={showModal}
onCancel={handleClose}
afterClose={() => setActiveKey("unoptimized-data")}
okButtonProps={{
disabled: true,
}}
cancelButtonProps={{
disabled: true,
}}
width={700}
footer={null}
>
<Tabs
defaultActiveKey="unoptimized-data"
activeKey={activeKey}
onChange={handleTabChange}
className="mb-3 custom-tab"
tabBarStyle={{ justifyContent: "space-around" }}
centered
>
{(editMode && isFunctionCallingAssistant ===false) || !editMode?(<TabPane
key="unoptimized-data"
tab={
<div
style={{
display: "flex",
gap: ".6rem",
justifyContent: "center",
alignItems: "center",
}}
>
{editMode ? "" : <BsRobot />}
<span>{editMode ? "Update Assistant" : "New Assistant"}</span>
</div>
}
>
<AssistantForm
data={{
form,
handleFormChange,
handleSwitchChange,
isAdmin,
handleUploadFileAndCreateAssistant,
fileList,
isUploading,
handleRemoveFile,
handleAddFile,
assistantData,
setAssistantData,
editMode,
}}
/>
</TabPane>): null}
{isAdmin && ((editMode && isFunctionCallingAssistant === true) || !editMode)? (<TabPane
key="create-assistant-by-functionCalling"
tab={
<div
style={{
display: "flex",
gap: ".6rem",
justifyContent: "center",
alignItems: "center",
}}
>
{editMode ? "" : <BsRobot />}
<span>{editMode ? "Update Function Calling Assistant" : "New Function Calling Assistant"}</span>
</div>
}
>
<FunctionCallingAssistantForm
data={{
form,
handleFunctionCallingFormChange,
handleSwitchChange,
isAdmin,
fileList,
isUploading,
handleRemoveFile,
handleAddFile,
handleFetchFunctionCallingAssistants,
assistantData,
setAssistantData,
editMode,
assistantFunctionCallData,
setAssistantFunctionCallData,
handleClose,
}}
/>
</TabPane>): null}
{editMode ? null : (
<TabPane
key={"optimized-data"}
tab={
<div
style={{
display: "flex",
gap: ".6rem",
justifyContent: "center",
alignItems: "center",
}}
>
<FaHashtag />
<span>New Assistant by ID</span>
</div>
}
>
<Form
form={form}
layout="vertical"
style={{
width: "100%",
}}
>
<Form.Item style={{ width: '100%' }} label="Assistant ID" name="assistantId">
<Input placeholder="Enter assistant ID" />
</Form.Item>
{isAdmin && (
<Form.Item
label="Select type"
name="category"
rules={[
{
required: true,
message: "Please Select the type of assistant",
},
]}
>
<Radio.Group>
<Radio value="ORGANIZATIONAL">Organizational</Radio>
<Radio value="PERSONAL">Personal</Radio>
</Radio.Group>
</Form.Item>
)}
<Form.Item label=" " colon={false}>
<Button
style={{ display: 'block', marginLeft: 'auto' }}
type="primary"
onClick={handleUploadFileAndCreateAssistant}
>
Create Assistant
</Button>
</Form.Item>
</Form>
</TabPane>
)}
</Tabs>
</Modal>
</>
);
};
export default CreateAssistantModal; |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.ejb3.timer.schedule;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.ejb.ScheduleExpression;
/**
* Represents the value of a day in a month, constructed out of a {@link ScheduleExpression#getDayOfMonth()}
*
* <p>
* A {@link DayOfMonth} can hold an {@link Integer} or a {@link String} as its value.
* value. The various ways in which a
* {@link DayOfMonth} value can be represented are:
* <ul>
* <li>Wildcard. For example, dayOfMonth = "*"</li>
* <li>Range. Examples:
* <ul>
* <li>dayOfMonth = "1-10"</li>
* <li>dayOfMonth = "Sun-Tue"</li>
* <li>dayOfMonth = "1st-5th"</li>
* </ul>
* </li>
* <li>List. Examples:
* <ul>
* <li>dayOfMonth = "1, 12, 20"</li>
* <li>dayOfMonth = "Mon, Fri, Sun"</li>
* <li>dayOfMonth = "3rd, 1st, Last"</li>
* </ul>
* </li>
* <li>Single value. Examples:
* <ul>
* <li>dayOfMonth = "Fri"</li>
* <li>dayOfMonth = "Last"</li>
* <li>dayOfMonth = "10"</li>
* </ul>
* </li>
* </ul>
* </p>
*
* @author Jaikiran Pai
* @version $Revision: $
*/
public class DayOfMonth extends MixedValueTypeExpression
{
/**
* The maximum allowed value for the {@link DayOfMonth}
*/
public static final Integer MAX_DAY_OF_MONTH = 31;
/**
* The minimum allowed value for the {@link DayOfMonth}
*/
public static final Integer MIN_DAY_OF_MONTH = -7;
/**
* A {@link DayOfMonth} can be represented as a {@link String} too (for example "1st", "Sun" etc...).
* Internally, we map all allowed {@link String} values to their {@link Integer} equivalents.
* This map holds the {@link String} name to {@link Integer} value mapping.
*/
private static final Map<String, Integer> DAY_OF_MONTH_ALIAS = new HashMap<String, Integer>();
static
{
DAY_OF_MONTH_ALIAS.put("1st", 1);
DAY_OF_MONTH_ALIAS.put("2nd", 2);
DAY_OF_MONTH_ALIAS.put("3rd", 3);
DAY_OF_MONTH_ALIAS.put("4th", 4);
DAY_OF_MONTH_ALIAS.put("5th", 5);
DAY_OF_MONTH_ALIAS.put("Last", 31);
DAY_OF_MONTH_ALIAS.put("Sun", Calendar.SUNDAY);
DAY_OF_MONTH_ALIAS.put("Mon", Calendar.MONDAY);
DAY_OF_MONTH_ALIAS.put("Tue", Calendar.TUESDAY);
DAY_OF_MONTH_ALIAS.put("Wed", Calendar.WEDNESDAY);
DAY_OF_MONTH_ALIAS.put("Thu", Calendar.THURSDAY);
DAY_OF_MONTH_ALIAS.put("Fri", Calendar.FRIDAY);
DAY_OF_MONTH_ALIAS.put("Sat", Calendar.SATURDAY);
}
/**
* A sorted set of valid values for days of month, created out
* of a {@link ScheduleExpression#getDayOfMonth()}
*/
private SortedSet<Integer> daysOfMonth = new TreeSet<Integer>();
/**
* The type of the expression, from which this {@link DayOfMonth} was
* constructed.
*
* @see ScheduleExpressionType
*/
private ScheduleExpressionType expressionType;
/**
* Creates a {@link DayOfMonth} by parsing the passed {@link String} <code>value</code>
* <p>
* Valid values are of type {@link ScheduleExpressionType#WILDCARD}, {@link ScheduleExpressionType#RANGE},
* {@link ScheduleExpressionType#LIST} or {@link ScheduleExpressionType#SINGLE_VALUE}
* </p>
* @param value The value to be parsed
*
* @throws IllegalArgumentException If the passed <code>value</code> is neither a {@link ScheduleExpressionType#WILDCARD},
* {@link ScheduleExpressionType#RANGE}, {@link ScheduleExpressionType#LIST},
* nor {@link ScheduleExpressionType#SINGLE_VALUE}.
*/
public DayOfMonth(String value)
{
// check the type of value
this.expressionType = ScheduleExpressionTypeUtil.getType(value);
Set<Integer> days = null;
switch (this.expressionType)
{
case RANGE :
RangeValue range = new RangeValue(value);
// process the range value and get the integer
// values out of it
days = this.processRangeValue(range);
// add them to our sorted set
this.daysOfMonth.addAll(days);
break;
case LIST :
ListValue list = new ListValue(value);
// process a list value and get the integer
// values out of it
days = this.processListValue(list);
// add them to our sorted set
this.daysOfMonth.addAll(days);
break;
case SINGLE_VALUE :
SingleValue singleValue = new SingleValue(value);
// process the single value and get the integer value
// out of it
Integer day = this.processSingleValue(singleValue);
// add this to our sorted set
this.daysOfMonth.add(day);
break;
case WILDCARD :
// a wildcard is equivalent to "all possible" values. So
// nothing to do here.
break;
case INCREMENT :
throw new IllegalArgumentException(
"Increment type expression is not allowed for day-of-month value. Invalid value: " + value);
default :
throw new IllegalArgumentException("Invalid value for day of month: " + value);
}
}
/**
* A {@link DayOfMonth} like any other {@link MixedValueTypeExpression} can
* hold both {@link String} and {@link Integer} values. Ultimately, a {@link String}
* value (like "Sun") is mapped back to an {@link Integer} value. This method
* return a {@link Map} which contains that mapping.
*
* {@inheritDoc}
*/
@Override
protected Map<String, Integer> getAliases()
{
return DAY_OF_MONTH_ALIAS;
}
/**
* Returns the maximum allowed value for a {@link DayOfMonth}
*
* @see DayOfMonth#MAX_DAY_OF_MONTH
*/
@Override
protected Integer getMaxValue()
{
return MAX_DAY_OF_MONTH;
}
/**
* Returns the minimum allowed value for a {@link DayOfMonth}
*
* @see DayOfMonth#MIN_DAY_OF_MONTH
*/
@Override
protected Integer getMinValue()
{
return MIN_DAY_OF_MONTH;
}
public Calendar getNextDayOfMonth(Calendar current)
{
if (this.expressionType == ScheduleExpressionType.WILDCARD)
{
return current;
}
Calendar next = new GregorianCalendar(current.getTimeZone());
next.setTime(current.getTime());
next.setFirstDayOfWeek(current.getFirstDayOfWeek());
Integer currentDayOfMonth = current.get(Calendar.DAY_OF_MONTH);
Integer nextDayOfMonth = this.daysOfMonth.first();
for (Integer dayOfMonth : this.daysOfMonth)
{
if (currentDayOfMonth.equals(dayOfMonth))
{
nextDayOfMonth = currentDayOfMonth;
break;
}
if (dayOfMonth.intValue() > currentDayOfMonth.intValue())
{
nextDayOfMonth = dayOfMonth;
break;
}
}
if (nextDayOfMonth < currentDayOfMonth)
{
// advance to next month
next.add(Calendar.MONTH, 1);
}
int maximumPossibleDateForTheMonth = next.getActualMaximum(Calendar.DAY_OF_MONTH);
while (nextDayOfMonth > maximumPossibleDateForTheMonth)
{
//
next.add(Calendar.MONTH, 1);
maximumPossibleDateForTheMonth = next.getActualMaximum(Calendar.DAY_OF_MONTH);
}
next.set(Calendar.DAY_OF_MONTH, nextDayOfMonth);
return next;
}
} |
<?php
namespace App\Controller;
use App\Entity\Recruteur;
use App\Form\RegistrationRecruterFormType;
use App\Security\EmailRecruteurVerifier;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\Address;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
class RegistrationRecruterController extends AbstractController
{
private $emailVerifier;
public function __construct(EmailRecruteurVerifier $emailVerifier)
{
$this->emailVerifier = $emailVerifier;
}
/**
* @Route("/registerRecruter", name="app_register_recruteur")
*/
public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
{
$user = new Recruteur();
$form = $this->createForm(RegistrationRecruterFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$form->get('plainPassword')->getData()
)
);
$user->setRoles(['ROLE_RECRUTEUR']);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
// generate a signed url and email it to the user
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
(new TemplatedEmail())
->from(new Address('contactUs@equaly.com', 'BotEqualy'))
->to($user->getEmail())
->subject('Please Confirm your Email')
->htmlTemplate('registration/confirmation_email.html.twig')
);
// do anything else you need here, like send an email
return $this->redirectToRoute('app_register_recruteur');
}
return $this->render('registration/registerRecruteur.html.twig', [
'registrationForm' => $form->createView(),
]);
}
/**
* @Route("/verify/email", name="app_verify_email")
*/
public function verifyUserEmail(Request $request): Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
// validate email confirmation link, sets User::isVerified=true and persists
try {
$this->emailVerifier->handleEmailConfirmation($request, $this->getUser());
} catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash('verify_email_error', $exception->getReason());
return $this->redirectToRoute('app_register_recruteur');
}
// @TODO Change the redirect on success and handle or remove the flash message in your templates
$this->addFlash('success', 'Your email address has been verified.');
return $this->redirectToRoute('app_login');
}
} |
package com.example.examapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class CurrentParticipants extends AppCompatActivity {
ListView CP_LV;
TextView CPTIG,CPA_Text;
String Group_ID;
ProgressBar CP_P;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_participants);
Intent intent=getIntent();
Group_ID=intent.getStringExtra("GROUP_ID");
CPA_Text=findViewById(R.id.CPA_Text);
CPTIG=findViewById(R.id.CPTIG);
CP_P=findViewById(R.id.CP_P);
CP_LV=findViewById(R.id.CP_LV);
CPTIG.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
CP_P.setVisibility(View.VISIBLE);
PopulateList();
}
public void PopulateList(){
DatabaseReference JoiningReference = FirebaseDatabase.getInstance().getReference("Groups").child(Group_ID);
// Listener to retrieve the groups
JoiningReference.child("Current Participants").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<ParticipantDetails> ParticipantList = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ParticipantDetails Participants = snapshot.getValue(ParticipantDetails.class);
if (Participants != null) {
ParticipantList.add(Participants);
}
}
if (ParticipantList.isEmpty()) {
// If there are no groups, display the message TextView and hide the ListView
CPA_Text.setVisibility(View.VISIBLE);
CP_LV.setVisibility(View.GONE);
CP_P.setVisibility(View.GONE);
} else {
// If there are groups, display the ListView and hide the message TextView
CPA_Text.setVisibility(View.GONE);
CP_LV.setVisibility(View.VISIBLE);
// Now, you have groupsList containing the groups data
// You can use this data to populate your ListView
// For instance, set up an ArrayAdapter with the ListView
GJRLV adapter = new GJRLV(CurrentParticipants.this, R.layout.gjrlv, ParticipantList);
// Assuming you have a ListView with the ID listViewGroups in your layout
CP_LV.setAdapter(adapter);
CP_P.setVisibility(View.GONE);
CP_LV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the selected group from the adapter
ParticipantDetails selectedParticipant = (ParticipantDetails) parent.getItemAtPosition(position);
showAlertDialog(JoiningReference,selectedParticipant);
}
});
}
}
@Override
public void onCancelled (@NonNull DatabaseError databaseError){
}
});
}
private void showAlertDialog (DatabaseReference JoiningReference,ParticipantDetails selectedParticipant) {
//Setup the Alert Builder
AlertDialog.Builder builder=new AlertDialog.Builder(CurrentParticipants.this);
builder.setTitle("Remove Participant");
builder.setMessage("Do You want to Remove this Participant from the Group?");
//Open email apps i User clicks/taps Continue button
builder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
JoiningReference.child("Current Participants").child(selectedParticipant.UserID).removeValue().addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(CurrentParticipants.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
});
DatabaseReference newGroup = FirebaseDatabase.getInstance().getReference("Registered Users").child(selectedParticipant.UserID).child("Groups").child(Group_ID);
newGroup.removeValue();
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
//create the AlertDialog
AlertDialog alertDialog=builder.create();
//show the alert dialog
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.red));
}
});
alertDialog.show();
}
} |
/* eslint-disable react-hooks/exhaustive-deps */
import { toHumaneValue } from "@/utils";
import _debounce from "lodash/debounce";
import { useSelector } from "@xstate/react";
import { Dec } from "@terra-money/feather.js";
import { useTranslation } from "react-i18next";
import TokenSelect from "@/components/TokenSelect";
import { IoMdArrowRoundBack } from "react-icons/io";
import {
Box,
Text,
Icon,
Stack,
Input,
Button,
Flex,
Spinner,
} from "@chakra-ui/react";
import { SwapMachineContext, TokenMachineContext } from "@/machine";
import { useContext, useState, useEffect, useMemo, useCallback } from "react";
import WrapWallet from "@/components/WrapWallet";
import { useTokenBalance } from "@/hooks/useTokenBalance";
import { useNavigate } from "react-router-dom";
export const AddLiquidity = () => {
const { t } = useTranslation();
const [inputAddress, setInputAddress] = useState("");
const [outputAddress, setOutputAddress] = useState("");
const [inputAmount, setInputAmount] = useState("");
const [outputAmount, setOutputAmount] = useState("");
const { tokenActor } = useContext(TokenMachineContext);
const { swapActor } = useContext(SwapMachineContext);
const tokenList = useSelector(tokenActor, state => state.context.tokenList);
const {
isLoading,
isReady,
isNoLiquidity,
isNoPair,
inputTokenReserve,
outputTokenReserve,
} = useSelector(swapActor, state => {
return {
isReady:
state.matches("ready") ||
state.matches("no_liquidity") ||
state.matches("no_pair"),
isLoading: state.hasTag("loading"),
isNoLiquidity: state.matches("no_liquidity"),
isNoPair: state.matches("no_pair"),
inputTokenReserve: state.context.pairInfo?.token1_reserve ?? "0",
outputTokenReserve: state.context.pairInfo?.token2_reserve ?? "0",
};
});
const { tokenBalance: inputTokenBalance, isLoading: inputIsLoading } =
useTokenBalance(inputAddress);
const { tokenBalance: outputTokenBalance, isLoading: outputIsLoading } =
useTokenBalance(outputAddress);
useEffect(() => {
if (inputAddress === outputAddress) {
setOutputAddress("");
}
}, [inputAddress]);
useEffect(() => {
if (outputAddress === inputAddress) {
setInputAddress("");
}
}, [outputAddress]);
const inputTokenMeta = useMemo(() => {
return tokenList.find(item => item.address === inputAddress);
}, [inputAddress, tokenList]);
const outputTokenMeta = useMemo(() => {
return tokenList.find(item => item.address === outputAddress);
}, [outputAddress, tokenList]);
const computeOutput = useCallback(
_debounce((inputTokenAmount: string) => {
if (!inputTokenMeta || !outputTokenMeta) return;
if (isNoLiquidity || isNoPair) return;
if (!inputTokenAmount) return;
const inputAmount = new Dec(inputTokenAmount).mul(
Math.pow(10, inputTokenMeta.info.decimals),
);
const output = inputAmount
.mul(new Dec(outputTokenReserve))
.div(new Dec(inputTokenReserve))
.add(1);
setOutputAmount(toHumaneValue(output, outputTokenMeta.info.decimals));
}, 500),
[
inputTokenMeta,
outputTokenMeta,
inputTokenReserve,
outputTokenReserve,
isNoLiquidity,
isNoPair,
],
);
useEffect(() => {
if (!inputTokenMeta || !outputTokenMeta) return;
// prevent using native token as token2
if (outputTokenMeta.isNative && !inputTokenMeta.isNative) {
const temp = inputAddress;
setInputAddress(outputAddress);
setOutputAddress(temp);
return;
}
swapActor.send({
type: "LOAD_PAIR",
value: [inputTokenMeta, outputTokenMeta],
});
}, [inputTokenMeta, outputTokenMeta]);
const isAllValueFilled = !!inputAmount && !!outputAmount;
const onSubmit = async () => {
if (isNoPair) {
swapActor.send({
type: "CREATE_PAIR",
value: {
token1Amount: new Dec(inputAmount).mul(
Math.pow(10, inputTokenMeta!.info.decimals),
),
token2Amount: new Dec(outputAmount).mul(
Math.pow(10, outputTokenMeta!.info.decimals),
),
token1Meta: inputTokenMeta!,
token2Meta: outputTokenMeta!,
},
});
} else {
swapActor.send({
type: "ADD_LIQUIDITY",
value: {
token1Amount: new Dec(inputAmount).mul(
Math.pow(10, inputTokenMeta?.info.decimals ?? 0),
),
maxToken2Amount: new Dec(outputAmount).mul(
Math.pow(10, outputTokenMeta?.info.decimals ?? 0),
),
},
});
}
};
const onMaxInputClicked = () => {
setInputAmount(inputTokenBalance);
};
const onMaxOutputClicked = () => {
setOutputAmount(outputTokenBalance);
};
const navigate = useNavigate();
return (
<Box
bgColor="navy.700"
border={"2px solid #A4A4BE"}
borderRadius="20"
w={{ base: "100%", md: "100%", lg: "50%" }}
position={"relative"}
mt={{ base: "5rem", md: "none" }}
>
<Box display="flex" alignItems="center" p="1rem">
<Box display="flex" alignContent="center" alignItems="center">
<Icon
as={IoMdArrowRoundBack}
color="yellow"
aria-label="back"
cursor="pointer"
mr={5}
w={6}
h={6}
_hover={{
cursor: "pointer",
}}
onClick={() => navigate("/swap")}
/>
<Text fontWeight="700" fontSize="xl">
{t("swap.addLiquidity.title")}
</Text>
</Box>
</Box>
<Box p="1rem">
<Box bgColor="navy.500" p="1rem" rounded="xl" mb="10">
<Text color="brand.400">{t("swap.addLiquidity.tip")}</Text>
</Box>
<Text textTransform="uppercase" fontWeight="bold">
{t("swap.addLiquidity.DepositAmount")}
</Text>
<Stack mt="1rem">
<Stack
direction="row"
bgColor="white"
p={1}
rounded="xl"
width="full"
align="center"
h={16}
>
<TokenSelect value={inputAddress} onChange={setInputAddress} />
<Box flex="1">
<Input
color="navy.700"
fontWeight={"700"}
type="number"
_focusVisible={{
border: "unset",
}}
border="unset"
px={0}
fontSize={18}
h={"20px"}
required
value={inputAmount}
onChange={e => {
setInputAmount(e.currentTarget.value);
computeOutput(e.currentTarget.value);
}}
/>
<Flex gap={1} align={"center"}>
<Text color={"gray"} fontSize={10}>
Balance :
</Text>
{inputIsLoading ? (
<Spinner color="gray" w={2} h={2} />
) : (
<Text color={"gray"} fontSize={10}>
{inputTokenBalance}
</Text>
)}
</Flex>
</Box>
<Button
bg={"brand.400"}
color={"navy.700"}
_hover={{
bg: "brand.500",
}}
p={1}
mr={3}
h={7}
fontSize={12}
fontWeight={700}
onClick={onMaxInputClicked}
>
Max
</Button>
</Stack>
<Stack
direction="row"
bgColor="white"
p={1}
rounded="xl"
width="full"
align="center"
h={16}
>
<TokenSelect value={outputAddress} onChange={setOutputAddress} />
<Box flex="1">
<Input
color="navy.700"
fontWeight={"700"}
type="number"
_focusVisible={{
border: "unset",
}}
border="unset"
px={0}
fontSize={18}
h={"20px"}
required
value={outputAmount}
onChange={e => {
setOutputAmount(e.currentTarget.value);
}}
/>
<Flex gap={1} align={"center"}>
<Text color={"gray"} fontSize={10}>
Balance :
</Text>
{outputIsLoading ? (
<Spinner color="gray" w={2} h={2} />
) : (
<Text color={"gray"} fontSize={10}>
{outputTokenBalance}
</Text>
)}
</Flex>
</Box>
<Button
bg={"brand.400"}
color={"navy.700"}
_hover={{
bg: "brand.500",
}}
p={1}
mr={3}
h={7}
fontSize={12}
onClick={onMaxOutputClicked}
fontWeight={700}
>
Max
</Button>
</Stack>
</Stack>
</Box>
<Box px={5}>
<WrapWallet>
<Button
bgColor={"brand.400"}
w={"100%"}
mb={10}
borderRadius={12}
color={"black"}
fontWeight={"700"}
isDisabled={
!isReady || !inputAddress || !outputAddress || !isAllValueFilled
}
isLoading={isLoading}
onClick={() => onSubmit()}
>
{isNoPair
? "CREATE PAIR"
: isNoLiquidity
? "PROVIDE LIQUIDITY"
: "ADD LIQUIDITY"}
</Button>
</WrapWallet>
</Box>
</Box>
);
}; |
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebStudio</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap"
rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css"
integrity="sha512-wpPYUAdjBVSE4KJnH1VR1HeZfpl1ub8YT/NKx4PuQ5NmX2tKuGu6U/JRp5y+Y8XG2tV+wKQpNHVUX03MfMFn9Q=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<header class="page-header">
<div class="header-container container">
<a class="logo" href="./index.html" lang="en"><span class="logo-web">Web</span>Studio</a>
<nav class="nav-main">
<ul class="nav-list list">
<li class="nav-list-item"><a href="./index.html" class="nav-link current">Студия</a></li>
<li class="nav-list-item"><a href="./portfolio.html" class="nav-link">Портфолио</a></li>
<li class="nav-list-item"><a href="#contacts" class="nav-link">Контакты</a></li>
</ul>
</nav>
<ul class="contact-list list">
<li class="contact-list-item"><a class="contact-link header" href="mailto:info@devstudio.com">info@devstudio.com</a></li>
<li class="contact-list-item"><a class="contact-link header" href="tel:+380961111111">+38 096 111 11 11</a></li>
</ul>
</div>
</header>
<main>
<!--Герой-->
<section class="hero">
<h1 class="hero-title">Эффективные решения для вашего бизнеса</h1>
<button class="button primary" type="button">Заказать услугу</button>
</section>
<!--Особенности-->
<section class="section">
<div class="container">
<h2 class="visually-hidden">Особенности</h2>
<ul class="features-list list">
<li class="features-item">
<h3 class="title">Внимание к деталям</h3>
<p class="features-content">Идейные соображения, а также начало повседневной работы по формированию позиции.</p>
</li>
<li class="features-item">
<h3 class="title">Пунктуальность</h3>
<p class="features-content">Задача организации, в особенности же рамки и место обучения кадров влечет за собой.</p>
</li>
<li class="features-item">
<h3 class="title">Планирование</h3>
<p class="features-content">Равным образом консультация с широким активом в значительной степени обуславливает.</p>
</li>
<li class="features-item">
<h3 class="title">Современные технологии</h3>
<p class="features-content">Значимость этих проблем настолько очевидна, что реализация плановых заданий.</p>
</li>
</ul>
</div>
</section>
<!--Чем мы занимаемся-->
<section class="section-service">
<div class="container">
<h2 class="section-title">Чем мы занимаемся</h2>
<ul class="service-list list">
<li class="service-item">
<img src="./img/img1.jpg" alt="Планшет и клавиатура на столе" width="370">
</li>
<li class="service-item">
<img src="./img/img2.jpg" alt="Смартфон в руках на фоне ноутбука" width="370">
</li>
<li class="service-item">
<img src="./img/img3.jpg" alt="На планшете показана раскладка цветов" width="370">
</li>
</ul>
</div>
</section>
<!--Наша команда-->
<section class="section team">
<div class="container">
<h2 class="section-title">Наша команда</h2>
<ul class="team-list list">
<li class="team-item">
<img class="team-img" src="./img/photo-igor.jpg" alt="Игорь Демьяненко" width="270">
<div class="team-name">
<h3 class="title">Игорь Демьяненко</h3>
<p class="team-item-profile" lang="en">Product Designer</p>
</div>
</li>
<li class="team-item">
<img class="team-img" src="./img/photo-olga.jpg" alt="Ольга Репина" width="270">
<div class="team-name">
<h3 class="title">Ольга Репина</h3>
<p class="team-item-profile" lang="en">Frontend Developer</p>
</div>
</li>
<li class="team-item">
<img class="team-img" src="./img/photo-nikolaj.jpg" alt="Николай Тарасов" width="270">
<div class="team-name">
<h3 class="title">Николай Тарасов</h3>
<p class="team-item-profile" lang="en">Marketing</p>
</div>
</li>
<li class="team-item">
<img class="team-img" src="./img//photo-mike.jpg" alt="Михаил Ермаков" width="270">
<div class="team-name">
<h3 class="title">Михаил Ермаков</h3>
<p class="team-item-profile" lang="en">UI Designer</p>
</div>
</li>
</ul>
</div>
</section>
</main>
<footer id="contacts">
<div class="container">
<a class="logo footer-logo" href="./index.html" lang="en"><span class="logo-web">Web</span>Studio</a>
<address>
<ul class="footer-list list">
<li><a class="address-link" href="https://goo.gl/maps/L3QvmrdTpUSkbaW27" target="_blank"
rel="noopener noreferrer">г. Киев, пр-т Леси Украинки, 26</a></li>
<li><a class="contact-link footer" href="mailto:info@example.com">info@example.com</a></li>
<li><a class="contact-link footer" href="tel:+380991111111">+38 099 111 11 11</a></li>
</ul>
</address>
</div>
</footer>
</body>
</html> |
<script lang="ts">
import {
ProgressRadial,
getToastStore,
popup,
type ToastSettings,
type PopupSettings
} from '@skeletonlabs/skeleton';
import type { PageData } from './$types';
import { enhance } from '$app/forms';
import type { ActionResult } from '@sveltejs/kit';
import { invalidateAll } from '$app/navigation';
export let data: PageData;
const toastStore = getToastStore();
function toastHandler(result: ActionResult) {
let resultToast: ToastSettings;
if (result.type == 'success') {
resultToast = {
message: `${result.data?.message}` || '',
background: 'variant-filled-success'
};
} else if (result.type == 'failure') {
resultToast = {
message: `${result.data?.message}` || '',
background: 'variant-filled-error'
};
} else {
resultToast = {
message: 'Unknown form result',
background: 'variant-filled'
};
}
toastStore.trigger(resultToast);
}
const quotePopup: PopupSettings = {
event: 'focus-blur',
target: 'quotePopup',
placement: 'bottom'
};
</script>
{#await data.result}
<div class="flex items-center justify-center h-full w-full">
<ProgressRadial />
</div>
{:then result}
<h1 class="h1 self-center text-center pt-4">
{#if data.isSudo}
Your <em class="italic">Impersonated</em> Profile
{:else}
Your Profile
{/if}
</h1>
<div class="p-2">
<form
class="card p-8 flex flex-col space-y-4 m-4"
method="post"
use:enhance={() => {
return async ({ result, update }) => {
update();
toastHandler(result);
};
}}
>
<h2 class="h2 self-center text-center">Public Directory Entry</h2>
<label class="label">
<span>Title</span>
<input class="input" type="text" name="title" disabled value={result.title} />
</label>
<label class="label">
<span>First Name</span>
<input class="input" type="text" name="firstname" disabled value={result.firstname} />
</label>
<label class="label">
<span>Last Name</span>
<input class="input" type="text" name="lastname" disabled value={result.lastname} />
</label>
<label class="label">
<span>Room</span>
<input class="input" type="text" name="room" disabled value={result.room} />
</label>
{#if result.phone2 && result.phone2 != ''}
<label>
<span>Phone</span>
<select class="select" name="phone">
<option value={result.phone} selected={result.phone == result.phone1}
>{result.phone1}</option
>
<option value={result.phone2} selected={result.phone == result.phone2}
>{result.phone2}</option
>
</select></label
>
{:else}
<label class="label">
<span>Phone</span>
<input class="input" type="text" name="phone" disabled value={result.phone} />
</label>
{/if}
<label class="label">
<span>Homepage</span>
<input class="input" type="url" name="homepage" value={result.homepage} />
</label>
<label class="label">
<span>Cellphone</span>
<input class="input" type="text" name="cellphone" value={result.cellphone} />
</label>
<label class="label">
<span>Home City</span>
<input class="input" type="text" name="home_city" value={result.home_city} />
</label>
<label class="label">
<span>Home State</span>
<input class="input" type="text" name="home_state" value={result.home_state} />
</label>
<label class="label">
<span>Home Country</span>
<input class="input" type="text" name="home_country" value={result.home_country} />
</label>
<label>
<span>Quote</span>
<div class="card p-4 variant-filled max-w-xl" data-popup="quotePopup">
<p>
Quotes now support markdown, which means you can add rich text and images/gifs in your
quotes. Goto <a class="anchor" href="https://stackedit.io/editor"
>https://stackedit.io/editor</a
> to format your quote and then paste the markdown text (the code on the left column on that
website) here in the quote box.
</p>
<div class="arrow variant-filled"></div>
</div>
<textarea
class="textarea font-mono"
name="quote"
rows="4"
value={result.quote}
use:popup={quotePopup}
></textarea>
</label>
<label>
<span>My favorite...</span>
<div class="input-group input-group-divider grid-cols-[1fr_auto_1fr]">
<input
class="input"
type="text"
name="favorite_category"
value={result.favorite_category}
placeholder="Color"
/>
<div class="input-group-shim">is</div>
<input
class="input"
type="text"
name="favorite_value"
value={result.favorite_value}
placeholder="Blue"
/>
</div>
</label>
<label>
<span>Reminders</span>
<p>
When I have reminders, I want to
<select class="select w-fit" name="showreminders">
<option value={true} selected={result.showreminders}>show</option>
<option value={false} selected={!result.showreminders}>hide</option>
</select>
the yellow reminders box.
</p>
</label>
<div class="grid grid-cols-[1fr_1fr] gap-4">
<input type="submit" class="btn variant-filled-success" value="Save it away, boss!" />
<!-- svelte bug, cant use type="reset" (https://github.com/sveltejs/svelte/issues/8220) -->
<input
type="button"
class="btn variant-filled-error"
value="Undo changes"
on:click={invalidateAll}
/>
</div>
</form>
</div>
<div class="flex items-center justify-center flex-col pb-4">
<h2 class="h2 text-center p-2">Automatic Reminders</h2>
{#if Object.keys(data.reminders).length > 0}
<ul class="list-disc list-outside ml-6 py-2">
{#each data.reminders.value as reminder}<li>{reminder}</li>{/each}
</ul>
{:else}
<strong class="font-bold">
<em class="italic">You do not currently have any reminders.</em>
</strong>
{/if}
</div>
{/await} |
<?php
namespace Tests\Feature;
use App\Models\User;
use Tests\TestCase;
class RowControllerTest extends TestCase
{
/**
* A basic feature test example.
*
* @return void
*/
public function testRowGetUnauthenticated()
{
$response = $this->getJson(route('rows.index'));
$response->assertUnauthorized();
$response->assertJsonStructure([
'message'
]);
}
/**
* A basic feature test example.
*
* @return void
*/
public function testRowGetSuccess()
{
$response = $this->actingAs(User::factory()->create())->getJson(route('rows.index'));
$response->assertSuccessful();
$response->assertJsonStructure(['errors', 'message', 'data']);
}
} |
import { useState, useEffect } from "preact/hooks";
import { DesktopNav } from "./DesktopNav";
import { MenuButton } from "./MenuButton";
import { MobileMenu } from "./MobileMenu";
export const Nav = () => {
const [prevScrollPos, setPrevScrollPos] = useState(0);
const [visible, setVisible] = useState(true);
const [isOpen, setIsOpen] = useState(false);
const handleScroll = () => {
const currentScrollPos = window.scrollY;
if (currentScrollPos > prevScrollPos) {
setVisible(false);
} else {
setVisible(true);
}
setPrevScrollPos(currentScrollPos);
};
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
});
return (
<header
class={`fixed left-0 right-0 z-50 flex items-center justify-between bg-primary-glass/70 py-4 drop-shadow-header backdrop-blur transition duration-300 ${
visible ? "top-0" : "-translate-y-48"
} px-10 `}
>
<h3>Andrii S.</h3>
<DesktopNav />
<MenuButton isOpen={isOpen} setIsOpen={setIsOpen} />
<MobileMenu isOpen={isOpen} setIsOpen={setIsOpen} />
</header>
);
}; |
#+title: Subscribe: a web interface for subscribing to mailing lists
ℹ️ *The development repository is hosted on [[https://git.sr.ht/~bzg/subscribe][SourceHut]].*
If you use [[https://www.mailgun.com/][mailgun.com]], [[https://www.mailjet.com][mailjet.com]] or [[https://www.sendinblue.com/][sendinblue.com]] to manage
contacts/mailing lists but do not want your users to share data with
an third-party sign-up form, =Subscribe= can help.
If you have several mailing lists (possibly handled by several
different providers among mailgun.com, mailjet.com or sendinblue.com)
and want to list various list subscription options on a single page,
=Subscribe= can help.
[[file:subscribe.png]]
* Features
- Support [[https://www.mailgun.com/][mailgun.com]], [[https://www.mailjet.com][mailjet.com]] or [[https://www.sendinblue.com/][sendinblue.com]] mailing lists
- Include/exclude mailing lists one by one or with regular expressions
- Let the admin of a list receive an email every =x= subscriptions
- Customize the HTML header and footer of the web interface
- Use your own stylesheet (as long as it's based on [[https://bulma.io][bulma.io]])
- UI and transactional emails in english and french
* Configure
Configuring =subscribe= is done in two steps: you first need to set
environment variables for global options (including the default
credentials for transactional emails), then to edit the =config.edn=
file for mailing lists.
** 1. Set up environment variables
Application variables:
: export SUBSCRIBE_PORT=3000
: export SUBSCRIBE_BASEURL="http://yourdomain.com"
Email credentials:
: export SUBSCRIBE_SMTP_LOGIN="postmaster@xxx"
: export SUBSCRIBE_SMTP_PASSWORD="your-password"
: export SUBSCRIBE_SMTP_HOST="smtp.mailgun.org"
: export SUBSCRIBE_SMTP_PORT=587
Backend-specific variables:
: # To handle mailgun.com mailing lists:
: export MAILGUN_API_BASEURL="https://api.mailgun.net/v3" # or "https://api.eu.mailgun.net/v3" for EU domains
: export MAILGUN_API_KEY="your-key"
:
: # To handle sendinblue.com mailing lists:
: export SENDINBLUE_API_KEY="your-key"
:
: # To handle mailjet.com mailing lists:
: export MAILJET_API_KEY="your-key"
: export MAILJET_API_SECRET="your-password"
Note that only mailjet.com requires both an API key /and password/,
mailgun.com and sendinblue.com only requires an API key.
** 2. Define options in ~config.edn~
Copy ~config_example.edn~ to ~config.edn~ and edit it.
The mandatory configuration options are ~:admin-email~ and ~:backends~.
* Test
: ~$ git clone https://git.sr.ht/~bzg/subscribe
: ~$ cd subscribe/
: ... [Set up your environment variables and config.edn]
: ~$ clj -M:test
* Run
** With ~clj -M:run~
: ... [Set up environment variables]
: ~$ git clone https://git.sr.ht/~bzg/subscribe
: ~$ cd subscribe/
: ... [Edit config.edn to configure mailing lists]
: ~$ clj -M:run
Then go to http://localhost:3000 or to your custom base URL.
** With =java -jar=
: ... [Set up environment variables]
: ~$ git clone https://git.sr.ht/~bzg/subscribe
: ~$ cd subscribe/
: ... [Edit config.edn to configure mailing lists]
: ~$ clj -M:uberdeps
: ~$ java -cp target/subscribe.jar clojure.main -m core
** With docker
Assuming your environments variables are stored in =~/.subscribe_envs=
and you want to expose the 3000 port:
: ~$ git clone https://git.sr.ht/~bzg/subscribe
: ~$ cd subscribe/
: ... [Edit config.edn to configure mailing lists]
: ~$ docker build -t subscribe .
: ~$ docker run -it -p 3000:3000 --env-file=~/.subscribe_envs subscribe
Then go to http://localhost:3000.
* Contribute
Contributions are welcome. You can send feedback and patches to
[[mailto:~bzg/dev@lists.sr.ht][~bzg/dev@lists.sr.ht]]. For patches, please configure your local copy
of the repository to add a prefix to the subject line of your emails:
: ~$ git config format.subjectPrefix 'PATCH subscribe'
* Support the Clojure ecosystem
If you like Clojure(script), please consider supporting maintainers by
donating to [[https://www.clojuriststogether.org][clojuriststogether.org]].
* License
© 2019-2023 Bastien Guerry
=subscribe= is licensed under the [[http://www.eclipse.org/legal/epl-v10.html][Eclipse Public License 2.0]]. |
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
sequelize.define('activity', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoincrement: true,
allowNull: false
},
name: {
type: DataTypes.STRING,
allowNull: false
},
dificultad: {
type: DataTypes.ENUM('1', '2', '3', '4', '5'),
validate: {
min: 1,
max: 5
},
allowNull: false,
},
duración: {
type: DataTypes.INTEGER,
validate: {
min: 1,
max: 96
},
allowNull: true
},
temporada: {
type: DataTypes.ARRAY(DataTypes.ENUM('Verano', 'Otoño', 'Invierno', 'Primavera')),
allowNull: false
},
}, {
timestamps: false,
freezeTableName: true,
})
}; |
---
title: "\"[Updated] In 2024, How to Make a YouTube Subscribe Link - Easy\""
date: 2024-06-06T14:14:17.399Z
updated: 2024-06-07T14:14:17.399Z
tags:
- ai video
- ai youtube
categories:
- ai
- youtube
description: "\"This Article Describes [Updated] In 2024, How to Make a YouTube Subscribe Link - Easy\""
excerpt: "\"This Article Describes [Updated] In 2024, How to Make a YouTube Subscribe Link - Easy\""
keywords: "Subscribe Link Guide,Create YouTube Subscribe Page,Easy Subscribe Button Code,YouTube Subscription Process,Build YouTube Subscribe Link,Video Subscriber Growth,Simple Subscribe Tool"
thumbnail: https://thmb.techidaily.com/c48a785cefdb0843c6e76d439ab755593afd7522af39269117f83ccabe84316f.png
---
## Guide to Streamlined Subscription Links for Video Channels
# How to Make a YouTube Subscribe Link - Easy

##### Richard Bennett
Oct 26, 2023• Proven solutions
[0](#commentsBoxSeoTemplate)
If you want to increase the total number of subscribers that you have on your YouTube page it is important that your page is easy to subscribe to.
A subscribe link is a link to your channel page which takes the person who clicks it to the same view of the page they would have if they had already clicked to subscribe. It triggers a pop-up asking them to confirm their subscription. If they were already interested enough to click the link and check out your channel they may confirm the subscription in the window, whereas they may forget to subscribe if they aren’t prompted.
A YouTube subscribe link is one of the best ways to share a link on your website, in social media posts, or anywhere you mention your channel.
## How to Get a YouTube Subscribe Link
YouTube subscribe links aren’t some kind of exclusive perk – anyone can have one!
**Step 1:** Go to your YouTube channel page and click into the address bar so you can edit the URL.
**Step 2:** Add the following to the end of your channel URL:
?sub\_confirmation=1
**Step 3:** Copy the entire URL including the part you added and paste it into a word document to save. Any time you share a link to your channel, make sure it is this link.
This will work both with channels that have custom URLs and channels which do not. Here’s an example:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w>_
That's a link for Wondershare Filmora Video Editor's YouTube channel. With the modifier it looks like this:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w?sub\_confirmation=1>_
Getting subscribers is tough, but you’ll get more if you ask and this is just another way of asking. The process for creating a YouTube subscribe link is easy and accessible to everyone.
### Touch Up Your YouTube Videos with Filmora
[Filmora](https://tools.techidaily.com/wondershare/filmora/download/) features lots of video and audio editing tools that enables you to cut, trim and touch up the video clip easily. There are plentiful texts templates and elements, which can be used to create attractive call-outs.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## Engaging Audiences on Multiple Digital Landscapes
# How to Stream to YouTube, Facebook, Twitch and Over 30 Platforms

<span class="atpl-alsoreadstyle">Also read:</span>
<div><ul>
<li><a href="https://eaxpv-info.techidaily.com/new-in-2024-full-spectrum-review-exploring-digital-performances-evolution/"><u>[New] In 2024, Full Spectrum Review Exploring Digital Performance's Evolution</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/new-elevate-streams-to-next-level-with-av1-on-youtube-for-2024/"><u>[New] Elevate Streams to Next Level with AV1 on YouTube for 2024</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/new-2024-approved-foundations-first-what-to-invest-in-for-youtubing/"><u>[New] 2024 Approved Foundations First What To Invest In for YouTubing</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/new-game-changing-streaming-apps-for-gamers-for-2024/"><u>[New] Game-Changing Streaming Apps for Gamers for 2024</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/new-2024-approved-giggles-galore-7-entertaining-video-sets-for-chuckleheads/"><u>[New] 2024 Approved Giggles Galore 7 Entertaining Video Sets for Chuckleheads</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/new-2024-approved-free-to-learn-4-youtube-channels-unlocking-the-secrets-of-background-substitution/"><u>[New] 2024 Approved Free-to-Learn 4 YouTube Channels Unlocking the Secrets of Background Substitution</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/new-2024-approved-harness-the-power-of-keywords-top-selection-software-unveiled/"><u>[New] 2024 Approved Harness the Power of Keywords Top Selection Software Unveiled</u></a></li>
<li><a href="https://ios-location-track.techidaily.com/in-2024-two-ways-to-track-my-boyfriends-apple-iphone-8-without-him-knowing-drfone-by-drfone-virtual-ios/"><u>In 2024, Two Ways to Track My Boyfriends Apple iPhone 8 without Him Knowing | Dr.fone</u></a></li>
<li><a href="https://ai-video-apps.techidaily.com/new-unlimited-free-video-storage-top-10-hosting-sites-for-you/"><u>New Unlimited Free Video Storage Top 10 Hosting Sites for You</u></a></li>
<li><a href="https://ai-video-tools.techidaily.com/updated-2024-approved-top-rated-free-avi-video-editor-options/"><u>Updated 2024 Approved Top-Rated Free AVI Video Editor Options</u></a></li>
<li><a href="https://screen-activity-recording.techidaily.com/in-2024-strategic-mastery-pinpointing-top-7-total-war-battles/"><u>In 2024, Strategic Mastery Pinpointing Top 7 Total War Battles</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/starting-stronger-exploring-the-best-15-video-intros-for-2024/"><u>Starting Stronger Exploring the Best 15 Video Intros for 2024</u></a></li>
<li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-creative-commons-legalities-explained-simply/"><u>[Updated] 2024 Approved Creative Commons Legalities Explained Simply</u></a></li>
<li><a href="https://youtube-clips.techidaily.com/elevating-the-cold-with-five-cozy-cinematic-elements-for-2024/"><u>Elevating the Cold with Five Cozy Cinematic Elements for 2024</u></a></li>
<li><a href="https://some-knowledge.techidaily.com/in-2024-in-depth-analysis-the-essence-of-the-google-podcast-application/"><u>In 2024, In-Depth Analysis The Essence of the Google Podcast Application</u></a></li>
<li><a href="https://extra-lessons.techidaily.com/essential-displays-for-picture-perfect-editing-choices/"><u>Essential Displays for Picture Perfect Editing [Choices]</u></a></li>
</ul></div> |
import { JwtService } from '@nestjs/jwt';
import { BadRequestException, Injectable, InternalServerErrorException, Logger, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { CreateUserDto, UpdateUserDto, LoginUserDto} from './dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { JwtPayload } from './interfaces/jwt.payload.interface';
import { PaginationDto } from 'src/common/dtos/pagination.dto';
import { isUUID } from 'class-validator';
@Injectable()
export class AuthService {
private readonly logger = new Logger('AuthService');
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
private readonly jwtService: JwtService,
) {}
async create(createUserDto: CreateUserDto) {
try {
const { password, ...userData } = createUserDto;
const user = this.userRepository.create({
...userData,
password: bcrypt.hashSync(password, 10)
});
await this.userRepository.save(user);
delete user.password;
return {...user,
token: this.getJwtToken({id: user.id})
};
} catch (error) {
this.handleDBExceptions(error);
}
}
findAll(paginationDto: PaginationDto) {
const { limit = 10, offset = 0 } = paginationDto;
return this.userRepository.find({
take: limit,
skip: offset,
relations: ['playlists']
});
}
async findOne(term: string) {
let user: User;
if (isUUID(term)) {
user = await this.userRepository.findOne({ where: { id: term }, relations: ['playlists'] });
} else {
user = await this.userRepository.findOne({ where: { email: term.toLowerCase() }, relations: ['playlists'] });
}
if (!user) throw new BadRequestException(`Usuario con ${term} no encontrado`);
return user;
}
async update(id: string, updateUserDto: UpdateUserDto) {
const user = await this.userRepository.preload({
id: id,
...updateUserDto
});
user.updatedAt = new Date();
if (!user) throw new NotFoundException(`Usuario con id ${id} no encontrado`);
try {
await this.userRepository.save(user);
return user;
} catch (error) {
this.handleDBExceptions(error);
}
}
async remove(id: string) {
const user = await this.findOne(id);
await this.userRepository.remove(user);
}
private getJwtToken(payload: JwtPayload){
const token = this.jwtService.sign(payload);
return token;
}
async login(loginUserDto: LoginUserDto) {
const {email,password} = loginUserDto;
const user = await this.userRepository.findOne({
where: {
email
},
select: {email: true, password: true, id: true}
});
if (!user) throw new UnauthorizedException('El email es inválido');
if (!bcrypt.compareSync(password, user.password)) throw new UnauthorizedException('La contraseña es inválida');
return {id: user.id ,email: user.email,
token: this.getJwtToken({id: user.id})
};
//TODO: Retornar el JWT de acceso
}
private handleDBExceptions(error: any): never {
if (error.code === '23505') {
throw new BadRequestException(error.detail);
}
this.logger.error(error);
throw new InternalServerErrorException("Error inesperado, Revisa los logs del servidor");
}
} |
import React, { forwardRef, ReactNode, SelectHTMLAttributes } from 'react';
import clsx from 'clsx';
import theme from '../../theme/default';
import SelectOption, { TSelectOption } from './SelectOption';
import SelectOptionGroup, { TSelectOptionGroup } from './SelectOptionGroup';
export type TSelect = Omit<SelectHTMLAttributes<HTMLSelectElement>, 'size'> & {
children?: ReactNode;
className?: string;
custom?: boolean;
disabled?: boolean;
invalid?: boolean;
rounded?: boolean;
rtl?: boolean;
size?: 'sm' | 'md' | 'lg';
success?: boolean;
};
type SelectComponent = React.ForwardRefExoticComponent<
TSelect & React.RefAttributes<HTMLSelectElement>
> & {
Option: React.ForwardRefExoticComponent<
TSelectOption & React.RefAttributes<HTMLOptionElement>
>;
OptionGroup: React.ForwardRefExoticComponent<
TSelectOptionGroup & React.RefAttributes<HTMLOptGroupElement>
>;
};
export const Select = forwardRef<HTMLSelectElement, TSelect>((props, ref) => {
const {
children,
className,
custom,
disabled,
invalid,
rounded,
rtl,
size,
success,
...attrs
} = props;
const classes = clsx(
'sui--select w-full appearance-none',
!custom && [
'py-0 px-2',
theme.form.base,
invalid
? theme.form.invalid
: success
? theme.form.success
: theme.form.default,
{ 'h-7 text-xs': size === 'sm' },
{ 'h-8 text-sm': size === 'md' || !size },
{ 'h-10 text-base': size === 'lg' },
disabled && theme.disabled,
rounded ? 'rounded-full' : 'rounded',
],
className
);
return (
<select
ref={ref}
className={classes}
disabled={disabled}
dir={rtl ? 'rtl' : 'auto'}
{...attrs}
>
{children}
</select>
);
}) as SelectComponent;
Select.displayName = 'Select';
Select.Option = SelectOption;
Select.OptionGroup = SelectOptionGroup;
Select.defaultProps = {
disabled: false,
size: 'md',
};
export default Select; |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shape_shifter_fitness_application/screens/musicplayer_screen.dart';
import '../data/playlists.dart';
import '../modules/playlist_info.dart';
import '../screens/music_player_screen.dart';
class PlaylistSet extends StatefulWidget {
const PlaylistSet({Key? key}) : super(key: key);
@override
_PlaylistSetState createState() => _PlaylistSetState();
}
class _PlaylistSetState extends State<PlaylistSet> {
List<Playlist> playlists = allPlaylists;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: playlists.length,
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0,horizontal: 10.0),
child: Material(
color: Colors.white70,
elevation: 10,
borderRadius: BorderRadius.circular(18),
clipBehavior: Clip.antiAliasWithSaveLayer,
child: InkWell(
splashColor: Colors.black26,
onTap: (){
goToNewPage(context);
},
child: Row(
children: [
Padding(
padding: const EdgeInsets.all(0.0),
child: Ink.image(
image: NetworkImage(playlists[index].urlImage),
height: 150,
width: MediaQuery.of(context).size.width-20,
fit: BoxFit.cover,
child: Center(
child: Text(
playlists[index].playlistName,
style: const TextStyle(
fontFamily: "HeadingFont",
fontSize: 35,
color: Colors.white,
fontWeight: FontWeight.w700)
),
),
),
),
],
),
),
),
);
/*return Padding(
padding: const EdgeInsets.symmetric(vertical: 15.0),
child: Column(
children: [
Container(
height: 150,
width: MediaQuery.of(context).size.width*0.9,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
color: Colors.black54,
image: DecorationImage(
image: AssetImage("assets/images/workout_image.jpg"),),
shape: BoxShape.rectangle
),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.transparent,
onPrimary: Colors.white,
shadowColor: Colors.black,
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0)),
minimumSize: Size(100, 40), //////// HERE
),
onPressed: () {
goToNewPage(context);
},
child: Text('Playlist Name'),
),
),
],
),
);*/
},
);
}
void goToNewPage(BuildContext ctx) {
//Navigator.of(ctx).pushNamed(MusicPlayer.routeName);
Navigator.of(ctx).pushNamed(MusicPlayerScreen.routeName);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.