text
stringlengths 184
4.48M
|
|---|
package com.example.week3_lab.ui.view
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.text.isDigitsOnly
import com.example.week3_lab.R
@Composable
fun BMICalculator() {
var weight by remember { mutableStateOf("") }
var height by remember { mutableStateOf("") }
var dialog by remember { mutableStateOf(false) }
Column(
modifier = Modifier
.padding(36.dp)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
painter = painterResource(id = R.drawable.baseline_face_24),
contentDescription = "Face Icon",
tint = Color.Blue,
modifier = Modifier.size(100.dp)
)
OutlinedTextField(
value = weight,
onValueChange = {
if (it.isEmpty() || it.isDigitsOnly()) {
weight = it
}
},
modifier = Modifier.fillMaxWidth(),
label = {
Text(
text = "Weight in kg",
color = Color.Blue
)
},
shape = RoundedCornerShape(40.dp),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = Color.Blue,
unfocusedBorderColor = Color.Blue,
textColor = Color.Blue
),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
if (weight.isEmpty()) {
Text(
text = "Please enter a valid weight greater than 0",
color = Color.Red,
fontSize = 16.sp,
modifier = Modifier.padding(8.dp)
)
}
Spacer(modifier = Modifier.height(12.dp))
OutlinedTextField(
value = height,
onValueChange = {
if (it.isEmpty() || it.isDigitsOnly()) {
height = it
}
},
modifier = Modifier.fillMaxWidth(),
label = {
Text(
text = "Height in cm ",
color = Color.Blue
)
},
shape = RoundedCornerShape(40.dp),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = Color.Blue,
unfocusedBorderColor = Color.Blue,
textColor = Color.Blue
),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
if (height.isEmpty()) {
Text(
text = "Please enter a valid weight greater than 0",
color = Color.Red,
fontSize = 16.sp,
modifier = Modifier.padding(8.dp)
)
}
Button(
onClick = {dialog = true},
enabled = weight.isNotEmpty() && height.isNotEmpty(),
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 24.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Color.Cyan,
contentColor = Color.Black
)
) {
Text(text = "Calculate BMI")
}
if(weight.isNotEmpty() && height.isNotEmpty() && dialog) {
var result: Double = weight.toDouble() / ((height.toDouble() / 100) * (height.toDouble() / 100))
var BMI: String
if (result < 18.5) {
BMI = "Underweight"
} else if (result > 18.5 && result < 24.9) {
BMI = "Normal"
} else if (result > 25 && result < 29.9) {
BMI = "Overweight"
} else {
BMI = "Obese"
}
AlertDialog(
onDismissRequest = {dialog = false},
title = {
Text(text = "Your BMI Analysis")
},
text = {
Text(text = """
Your Height : ${height.toDouble() / 100} m
Your Weight : ${weight.toDouble()} kg
Your BMI Score : ${String.format("%.2f", result)}
You are $BMI
""".trimIndent())
},
confirmButton = {
Button(onClick = {dialog = false}) {
Text(text = "OK")
}
}
)
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun BMIPreview() {
BMICalculator()
}
|
### Electric Vehicles vs Charging Stations in France
This project is an interactive dashboard built with Streamlit, Folium, and Plotly. It visualizes the progress of electric vehicle charging points across France.
[Link to the app](https://ev-plug-in-france.streamlit.app/) on Streamlit community cloud.
#### Features:
Interactive map of France showing the distribution of electric vehicle charging points and electric vehicles.
Bar charts showing the cumulative number of charging points and electric vehicles per department.
Sidebar for selecting a specific year and department.
Metrics showing the number of electric vehicles per charging point, total electric vehicles, and total charging points for the selected department.
#### How to Run the App locally:
After cloning this repository to your local machine ensure that python virtual environment is activated, and all the necessary Python libraries installed. These include pandas, numpy, streamlit, folium, altair, json, and plotly.
You can run the folowing in activated venv to install the necessary libraries given in the requirements.txt file:
```bash
python -m pip install -r requirements.txt
```
#### Run the Streamlit application:
```bash
streamlit run map_dashboard.py
```
This might open the default web browser and display the application. If not, you can open your web browser and visit the local URL displayed in your terminal (usually http://localhost:8501).
#### The data used in this application includes:
The initial datasets can be found [here](https://defis.data.gouv.fr/defis/65a923a083cf5f728c9934b3/).
The resulting, cleaned datasets can be found in the `data` folder. They are as follows:
`epoints_pivot.csv`: Contains data about electric charging points. Each row represents the number of charging points in a department for a specific year.
`epoints_pivot_cumsum.csv`: Contains cumulative data about electric charging points with the same structure.
`evs_pivot.csv`: Contains data about electric vehicles. Each row represents the number of electric vehicles in a department for a specific year.
`evs_pivot_cumsum.csv`: Contains cumulative data about electric vehicles with the same structure.
`france_departments.geojson`: GeoJSON file containing the geographical boundaries of French departments.
#### Code Overview
For better organization and readability, the code of the application is broken down into several functions.
So, the `map_dashboard.py` file contains several functions:
`load_datasets()`: Loads the CSV data files and adjusts the data structure as needed for the analysis. Also creates another dataset with ratios of electric vehicles to charging points.
`ft_sidebar()`: Creates the sidebar with year and department selection.
`create_choropleth()`: Creates a choropleth map with the selected data. The GEOJSON file is modified here to include the additional data for each department to be displayed on the map as a tooltip.
`render_map()`: Renders the map on the Streamlit app. This is where the map object is created and displayed with the help of Folium and choropleth function.
`plot_barchart()`: Plots a bar chart of each dataset. The bar chart shows the cumulative number of charging points and electric vehicles per department.
`calculate_delta()`: Calculates the change in values between the selected year and the previous year which is displayed in the metrics section as increase or decrease.
`main()`: The main function where all the logic of the Streamlit app is implemented.
For more detailed information about the project and how I did it, please visit this repository : [evs-charging-france-dashboard](https://github.com/svvoii/evs-charging-france-dashboard).
This project was finished on 25.05.2024 by [svvoii](https://github.com/svvoii)
|
package controllers
import (
"encoding/json"
"fmt"
"go_training/chapter8/models"
"go_training/chapter8/services"
"io/ioutil"
"net/http"
"strconv"
)
type EmployeeController struct {
employeeService *services.EmployeeService
}
func NewEmployeeController(employeeService *services.EmployeeService) *EmployeeController {
return &EmployeeController{
employeeService: employeeService,
}
}
func (h *EmployeeController) GetEmployeeList(w http.ResponseWriter, r *http.Request) {
var employeeList []models.Employee
var err error
query := r.URL.Query()
posStr := query.Get("position")
idPos, _ := strconv.Atoi(posStr)
employeeList, err = h.employeeService.GetEmployees(idPos)
fmt.Println(employeeList)
if err != nil {
fmt.Printf("ERROR - %s", err)
}
json.NewEncoder(w).Encode(employeeList)
}
func (h *EmployeeController) GetEmployee(w http.ResponseWriter, r *http.Request) {
var employee *models.Employee
var err error
query := r.URL.Query()
idStr := query.Get("id")
idInt, _ := strconv.Atoi(idStr)
employee, err = h.employeeService.GetSingleEmployee(idInt)
if err != nil {
fmt.Printf("ERROR - %s", err)
}
json.NewEncoder(w).Encode(employee)
}
func (h *EmployeeController) CreateEmployee(w http.ResponseWriter, r *http.Request) {
var employeeToCreate models.Employee
var err error
reqBody, _ := ioutil.ReadAll(r.Body)
json.Unmarshal(reqBody, &employeeToCreate)
created, err := h.employeeService.InsertEmployee(&employeeToCreate)
if err != nil {
fmt.Printf("ERROR - %s", err)
}
if created {
fmt.Println("Saved Employee Successfully")
}
json.NewEncoder(w).Encode(employeeToCreate)
}
func (h *EmployeeController) UpdateEmployee(w http.ResponseWriter, r *http.Request) {
var employeeToUpdate models.Employee
var err error
reqBody, _ := ioutil.ReadAll(r.Body)
json.Unmarshal(reqBody, &employeeToUpdate)
updated, err := h.employeeService.UpdateEmployee(&employeeToUpdate)
if err != nil {
fmt.Printf("ERROR - %s", err)
}
if updated {
fmt.Println("Updated Employee Successfully")
}
json.NewEncoder(w).Encode(employeeToUpdate)
}
|
package com.example.firebase
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.preference.PreferenceManager
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import android.widget.ImageView
import android.widget.TextView
import androidx.core.app.NotificationCompat
import androidx.core.content.getSystemService
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
class CartaReservadaAdaptador(
var lista_cartas_reservadas: MutableList<CartaReservada>,
var contentResolver: ContentResolver
):
RecyclerView.Adapter<CartaReservadaAdaptador.CartaReservadaViewHolder>(), Filterable,
CoroutineScope {
private lateinit var contexto: Context
private lateinit var sharedPreferences: SharedPreferences
private lateinit var rol_usuario: String
private lateinit var db_ref: DatabaseReference
private lateinit var storage_ref: StorageReference
var canalId:Int = 0
private var url_carta: Uri? = null
private var lista_filtrada = lista_cartas_reservadas
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): CartaReservadaAdaptador.CartaReservadaViewHolder {
val vista_item =
LayoutInflater.from(parent.context).inflate(R.layout.item_carta_reservada, parent, false)
contexto = parent.context
return CartaReservadaAdaptador.CartaReservadaViewHolder(vista_item)
}
override fun onBindViewHolder(
holder: CartaReservadaAdaptador.CartaReservadaViewHolder,
position: Int
) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(contexto)
// val item_actual = lista_filtrada[position]
// holder.id_c_reservada.text = item_actual.id_reserva_carta
// holder.idcarta.text = item_actual.id_carta
// holder.idusuario.text = item_actual.id_usuario
// holder.estado_c.text = item_actual.estado
rol_usuario = sharedPreferences.getString("usuario", "administrador").toString()
if (rol_usuario == "cliente") {
holder.accept.setVisibility(View.INVISIBLE)
} else {
holder.accept.setVisibility(View.VISIBLE)
}
holder.accept.setOnClickListener {
if (holder.estado_c.text != "Preparado") {
mostrar_notificacion(contexto)
sharedPreferences.edit().putString("estado", "Preparado").apply()
// var id_generado: String? = db_ref.child("tienda").child("cartas compradas").push().key
var id_generado = sharedPreferences.getString("id_carta_reservada", "1r").toString()
var id_carta = sharedPreferences.getString("id_carta", "1c").toString()
var id_usuario = sharedPreferences.getString("id_usuario", "1u").toString()
var estado = "Preparado"
// sharedPreferences.edit().putString("id_carta_reservada", id_generado).apply()
val item_actual = lista_filtrada[position]
holder.user.text = item_actual.userComprador
holder.estado_c.text = "Preparado"
val URL: String? = when (item_actual.imagen) {
"" -> null
else -> item_actual.imagen
}
Glide.with(contexto)
.load(URL)
.apply(Utilidades.opcionesGlide(contexto))
.transition(Utilidades.transicion)
.into(holder.miniatura)
// val activity2 = Intent(contexto, Mi_cesta::class.java)
// activity2.putExtra("carta_comprada", item_actual)
}
}
}
override fun getItemCount(): Int = lista_filtrada.size
class CartaReservadaViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val miniatura: ImageView = itemView.findViewById(R.id.imagen_defecto)
val user: TextView = itemView.findViewById(R.id.user_comprador)
val estado_c: TextView = itemView.findViewById(R.id.estado)
val accept: ImageView = itemView.findViewById(R.id.icono_aceptar)
}
fun mostrar_notificacion(contexto: Context){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
canalId += 1
var canalNombre = "canal" + canalId.toString()
val notificationChannel = NotificationChannel(canalId.toString(), canalNombre, NotificationManager.IMPORTANCE_DEFAULT)
contexto.getSystemService<NotificationManager>()?.createNotificationChannel(notificationChannel)
}
// val intento = Intent(contexto, MainActivity::class.java)
// val pendingIntent = PendingIntent.getActivity(contexto, 0, intento, PendingIntent.FLAG_UPDATE_CURRENT)
val intento_boton = Intent(contexto, Ver_cartas::class.java)
val pendingIntent_boton = PendingIntent.getActivity(contexto, 0, intento_boton, PendingIntent.FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(contexto, canalId.toString())
.setSmallIcon(R.drawable.notification_icon_124899)
.setContentTitle("Notificacion")
.setContentText("El pedido ya está preparado. Mi id es "+canalId)
// .setContentIntent(pendingIntent)
.addAction(R.drawable.notification_icon_124899,"Ir al catalogo", pendingIntent_boton)
with(contexto.getSystemService<NotificationManager>()){
this?.notify(1,builder.build())
}
}
override fun getFilter(): Filter {
TODO("Not yet implemented")
}
override val coroutineContext: CoroutineContext
get() = TODO("Not yet implemented")
}
|
var assert = require('assert');
var nefUtils = require('nef/utils');
var testHelpers = require('nef/testHelpers');
module.exports = function test() {
var self = this;
describe('v=1.0', function() {
it('should find props for ver = 1.0', function(done) {
findAssert({
apiVersion: '1.0',
expectNames: ['compatV10'],
expectMissedNames: ['compatV11'],
expectPublicNames: ['test.compat'],
expectMissingPublicNames: ['test.newCompat'],
}, done);
});
it('should get v1.0 prop by publicName', function(done) {
self.worker.getProperty({
publicName: 'test.compat',
apiVersion: '1.0'
}, (err, res) => {
assert.ifError(err);
assert.equal(res, 'v1.0');
done();
});
});
it('should not get v1.1 prop by id', function(done) {
self.worker.getProperty({
id: 'test.compatV11',
apiVersion: '1.0'
}, (err, res) => {
assert.errorIs('ENOENT', err);
done();
});
});
it('should not get v1.2 prop by publicName', function(done) {
self.worker.getProperty({
publicName: 'test.newCompat',
apiVersion: '1.0'
}, (err, res) => {
assert.errorIs('ENOENT', err);
done();
});
});
it('should be able to update old prop', function(done) {
self.worker.setProperty({
publicName: 'test.compat',
apiVersion: '1.0',
value: 'someValue'
}, done);
});
it('should not be able to update new props', function(done) {
self.worker.setProperty({
publicName: 'test.newCompat',
apiVersion: '1.0',
value: 'someValue'
}, (err, res) => {
assert.errorIs('ENOENT', err);
done();
});
});
});
for (apiVer of ['1.1', '1.2', undefined]) {
describe(`v=${apiVer}`, function() {
it(`should find props for ver = ${apiVer}`, function(done) {
findAssert({
apiVersion: apiVer,
expectNames: ['compatV11'],
expectMissedNames: ['compatV10'],
expectPublicNames: ['test.newCompat'],
expectMissingPublicNames: ['test.compat'],
}, done);
});
it('should NOT get v1.0 prop by publicName', function(done) {
self.worker.getProperty({
publicName: 'test.compat',
apiVersion: apiVer
}, (err, res) => {
assert.errorIs('ENOENT', err);
done();
});
});
it('should get v1.1 prop by id', function(done) {
self.worker.getProperty({
id: 'test.compatV11',
apiVersion: apiVer
}, (err, res) => {
assert.ifError(err);
assert.equal(res, 'v1.1');
done();
});
});
it('should get v1.1 prop by publicName', function(done) {
self.worker.getProperty({
publicName: 'test.newCompat',
apiVersion: apiVer
}, (err, res) => {
assert.ifError(err);
assert.equal(res, 'v1.1');
done();
});
});
it('should be able to update old prop', function(done) {
self.worker.setProperty({
publicName: 'test.compat',
apiVersion: apiVer,
value: 'someValue'
}, (err, res) => {
assert.errorIs('ENOENT', err);
done();
});
});
it('should not be able to update new props', function(done) {
self.worker.setProperty({
publicName: 'test.newCompat',
apiVersion: apiVer,
value: 'someValue'
}, done);
});
});
}
//
// Helpers
//
function findAssert(opts, done) {
self.worker.findProperties({
where: {
module: 'test'
},
apiVersion: opts.apiVersion,
}, (err, res) => {
assert.ifError(err);
shouldBeThere(opts.expectNames,
res, 'name');
shouldBeThere(opts.expectPublicNames,
res, 'publicName');
shouldNotBeThere(opts.expectMissedNames,
res, 'name');
shouldNotBeThere(opts.expectMissingPublicNames,
res, 'publicName');
done();
});
}
function shouldBeThere(expected, result, key) {
if (!expected) {
return;
}
var weHave = nefUtils.arrayToDict(result, key);
for (el of expected) {
assert(el in weHave, `property with ${key}=${el} ` +
'should be in result');
}
}
function shouldNotBeThere(expected, result, key) {
if (!expected) {
return;
}
var weHave = nefUtils.arrayToDict(result, key);
for (el of expected) {
assert(!(el in weHave), `property with ${key}=${el} ` +
'should NOT be in result');
}
}
};
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="row">
<!-- mas satrya -->
<div class="col-lg-4">
<div class="text-center card-box rounded-4">
<div class="member-card pt-2 pb-2">
<img src="img/Satrya.jpg" class="img-thumbnail mb-4" alt="profile-image">
<h4 class="card-title">Satrya Tangguh Puruhita</h4>
<p class="text-muted">Front End Developer</p>
<ul class="social-links list-inline">
<li class="list-inline-item"><a href="https://github.com/satryatangguh"><i
class="ri-github-fill"></i></a></li>
<li class="list-inline-item"><a href="https://www.linkedin.com/in/satryatangguh/"><i
class="ri-linkedin-fill"></i></a></li>
</ul>
<button type="button" class="btn btn-primary mt-3 btn-rounded waves-effect w-md waves-light"
data-bs-toggle="modal" data-bs-target="#satrya">View Profile</button>
</div>
</div>
</div>
<!-- dion -->
<div class="col-lg-4">
<div class="text-center card-box rounded-4">
<div class="member-card pt-2 pb-2">
<img src="img/yustinus.png" class="img-thumbnail mb-4" alt="profile-image">
<h4 class="card-title">Yustinus Novandion Koten</h4>
<p class="text-muted">Front End Developer</p>
<ul class="social-links list-inline">
<li class="list-inline-item"><a href="https://github.com/evgenyciko"><i
class="ri-github-fill"></i></a></li>
<li class="list-inline-item"><a href="#"><i class="ri-linkedin-fill"></i></a></li>
</ul>
<button type="button" class="btn btn-primary mt-3 btn-rounded waves-effect w-md waves-light"
data-bs-toggle="modal" data-bs-target="#dion">View Profile</button>
</div>
</div>
</div>
<!-- maurits -->
<div class="col-lg-4">
<div class="text-center card-box rounded-4">
<div class="member-card pt-2 pb-2">
<img src="img/asdf.gif" class="img-thumbnail mb-4" alt="profile-image">
<h4 class="card-title">Maurits Hudaibi</h4>
<p class="text-muted">Front End Developer</p>
<ul class="social-links list-inline">
<li class="list-inline-item"><a href="https://github.com/mauritshdb"><i
class="ri-github-fill"></i></a></li>
<li class="list-inline-item"><a href="#"><i class="ri-linkedin-fill"></i></a></li>
</ul>
<button type="button" class="btn btn-primary mt-3 btn-rounded waves-effect w-md waves-light"
data-bs-toggle="modal" data-bs-target="#maurits">View Profile</button>
</div>
</div>
</div>
<!-- Juan -->
<div class="col-lg-4">
<div class="text-center card-box rounded-4">
<div class="member-card pt-2 pb-2">
<img src="img/juan.jpg" class="img-thumbnail mb-4" alt="profile-image">
<h4 class="card-title">Juan Eleazar Manongko</h4>
<p class="text-muted">Front End Developer</p>
<ul class="social-links list-inline">
<li class="list-inline-item"><a href="https://github.com/JMngko"><i
class="ri-github-fill"></i></a></li>
<li class="list-inline-item"><a href="#"><i class="ri-linkedin-fill"></i></a></li>
</ul>
<button type="button" class="btn btn-primary mt-3 btn-rounded waves-effect w-md waves-light"
data-bs-toggle="modal" data-bs-target="#juan">View Profile</button>
</div>
</div>
</div>
<!-- Jerry -->
<div class="col-lg-4">
<div class="text-center card-box rounded-4">
<div class="member-card pt-2 pb-2">
<img src="img/jerry.jpeg" class="img-thumbnail mb-4" alt="profile-image">
<h4 class="card-title">Jerryanti Tandi Rau</h4>
<p class="text-muted">Front End Developer</p>
<ul class="social-links list-inline">
<li class="list-inline-item"><a href="https://github.com/jtandirau"><i
class="ri-github-fill"></i></a></li>
<li class="list-inline-item"><a href="#"><i class="ri-linkedin-fill"></i></a></li>
</ul>
<button type="button" class="btn btn-primary mt-3 btn-rounded waves-effect w-md waves-light"
data-bs-toggle="modal" data-bs-target="#jerry">View Profile</button>
</div>
</div>
</div>
<!-- Yusup -->
<div class="col-lg-4">
<div class="text-center card-box rounded-4">
<div class="member-card pt-2 pb-2">
<img src="img/yusup2.jpg" class="img-thumbnail mb-4" alt="profile-image">
<h4 class="card-title">Yusup C Dermawan</h4>
<p class="text-muted">Front End Developer</p>
<ul class="social-links list-inline">
<li class="list-inline-item"><a href="https://github.com/yusuppm"><i class="ri-github-fill"></i></a></li>
<li class="list-inline-item"><a href="https://www.linkedin.com/in/yusup-c-drmwn"><i class="ri-linkedin-fill"></i></a></li>
</ul>
<button type="button" class="btn btn-primary mt-3 btn-rounded waves-effect w-md waves-light" data-bs-toggle="modal" data-bs-target="#yusup">View Profile</button>
</div>
</div>
</div>
<!-- Copy Paste col diatas dan ganti nama disini -->
</div>
</div>
<!-- Modal Satrya -->
<div class="modal fade" id="satrya" tabindex="-1" role="dialog" aria-labelledby="profile" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 880px;">
<div class="modal-content">
<div class="row g-3 m-2 mt-0">
<div class="col-lg-3">
<img src="img/Satrya.jpg" class="img-fluid rounded-2 mb-2" alt="...">
<h4 class="card-title text-center">Satrya Tangguh Puruhita</h4>
<p class="text-muted text-center">Front End Developer</p>
<h4 class="card-title text-center">Contact Me</h4>
<p class="text-start mb-0 d-flex align-items-center"><i class="ri-mail-fill me-2"
style="font-size: 15px; color: #000;"></i> satryatp@gmail.com</p>
<p class="text-start d-flex align-items-center"><i class="ri-phone-fill me-2"
style="font-size: 15px; color: #000;"></i> 083849151166</p>
</div>
<div class="col-lg-9">
<div class="card-body">
<div class="summary mb-3">
<h5 class="card-title mb-2">Summary</h5>
<p class="card-text">Passionate in front-end development, love writing quality code,
learning new tools, and solving interesting problems. I'm currently enrolling in a
front-end web development bootcamp to improve my front-end programming skill.</p>
</div>
<div class="skill mb-3">
<h5 class="card-title mb-2">Skill</h5>
<p class="card-text">HTML, CSS, Javascript, Bootstrap, JQuery, ReactJS, NodeJS, and Git
</p>
</div>
<div class="experience mb-3">
<h5 class="card-title mb-2">Professional Experience</h5>
<li>PT Ferron Par Pharmaceuticals, Production Technician (2021)</li>
</div>
<div class="bootcamp mb-3">
<h5 class="card-title mb-2">Bootcamp Experience</h5>
<li>dibimbing.id, Front End Web Development Bootcamp (2022-2023)</li>
</div>
<div class="education mb-3">
<h5 class="card-title mb-2">Education Background</h5>
<li>Politeknik Elektronika Negeri Surabaya, Bachelor of Mechatronics Engineering
(2016-2020)</li>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal dion -->
<div class="modal fade" id="dion" tabindex="-1" role="dialog" aria-labelledby="profile" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 880px;">
<div class="modal-content">
<div class="row g-3 m-2 mt-0">
<div class="col-lg-3">
<img src="img/yustinus.png" class="img-fluid rounded-2 mb-2" alt="...">
<h4 class="card-title text-center">Yustinus Novandion Koten</h4>
<p class="text-muted text-center">Front End Developer</p>
<h4 class="card-title text-center">Contact Me</h4>
<p class="text-start mb-0 d-flex align-items-center"><i class="ri-mail-fill me-2"
style="font-size: 15px; color: #000;"></i> dion.tkj3@gmail.com</p>
<p class="text-start d-flex align-items-center"><i class="ri-phone-fill me-2"
style="font-size: 15px; color: #000;"></i> 081395591904</p>
</div>
<div class="col-lg-9">
<div class="card-body">
<div class="summary mb-3">
<h5 class="card-title mb-2">Summary</h5>
<p class="card-text">Passionate in front-end development, love writing quality code,
learning new tools, and solving interesting problems. I'm currently enrolling in a
front-end web development bootcamp to improve my front-end programming skill.</p>
</div>
<div class="skill mb-3">
<h5 class="card-title mb-2">Skill</h5>
<p class="card-text">Sleeping on the floor</p>
</div>
<div class="experience mb-3">
<h5 class="card-title mb-2">Professional Experience</h5>
<li>-</li>
</div>
<div class="bootcamp mb-3">
<h5 class="card-title mb-2">Bootcamp Experience</h5>
<li>dibimbing.id, Front End Web Development Bootcamp (2022-2023)</li>
</div>
<div class="education mb-3">
<h5 class="card-title mb-2">Education Background</h5>
<li>-</li>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal maurits -->
<div class="modal fade" id="maurits" tabindex="-1" role="dialog" aria-labelledby="profile" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 880px;">
<div class="modal-content">
<div class="row g-3 m-2 mt-0">
<div class="col-lg-3">
<img src="img/asdf.gif" class="img-fluid rounded-2 mb-2" alt="...">
<h4 class="card-title text-center">Maurits Hudaibi</h4>
<p class="text-muted text-center">Front End Developer</p>
<h4 class="card-title text-center">Contact Me</h4>
<p class="text-start mb-0 d-flex align-items-center"><i class="ri-mail-fill me-2"
style="font-size: 15px; color: #000;"></i> mauritshudaibi@gmail.com</p>
<p class="text-start d-flex align-items-center"><i class="ri-phone-fill me-2"
style="font-size: 15px; color: #000;"></i> 081318615077</p>
</div>
<div class="col-lg-9">
<div class="card-body">
<div class="summary mb-3">
<h5 class="card-title mb-2">Summary</h5>
<p class="card-text">Passionate in front-end development, love writing quality code,
learning new tools, and solving interesting problems. I'm currently enrolling in a
front-end web development bootcamp to improve my front-end programming skill.</p>
</div>
<div class="skill mb-3">
<h5 class="card-title mb-2">Skill</h5>
<li>HTML, CSS, Javascript, NodeJS, ReactJS and Git </li>
</div>
<div class="experience mb-3">
<h5 class="card-title mb-2">Professional Experience</h5>
<li>-</li>
</div>
<div class="bootcamp mb-3">
<h5 class="card-title mb-2">Bootcamp Experience</h5>
<li>dibimbing.id, Front End Web Development Bootcamp (2022-2023)</li>
</div>
<div class="education mb-3">
<h5 class="card-title mb-2">Education Background</h5>
<li>-</li>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal Juan -->
<div class="modal fade" id="juan" tabindex="-1" role="dialog" aria-labelledby="profile" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 880px;">
<div class="modal-content">
<div class="row g-3 m-2 mt-0">
<div class="col-lg-3">
<img src="img/juan.jpg" class="img-fluid rounded-2 mb-2" alt="...">
<h4 class="card-title text-center">Juan Eleazar Manongko</h4>
<p class="text-muted text-center">Front End Developer</p>
<h4 class="card-title text-center">Contact Me</h4>
<p class="text-start mb-0 d-flex align-items-center"><i class="ri-mail-fill me-2"
style="font-size: 15px; color: #000;"></i> juan.manongko@gmail.com</p>
<p class="text-start d-flex align-items-center"><i class="ri-phone-fill me-2"
style="font-size: 15px; color: #000;"></i> 081356692552</p>
</div>
<div class="col-lg-9">
<div class="card-body">
<div class="summary mb-3">
<h5 class="card-title mb-2">Summary</h5>
<p class="card-text">Enjoying work in front-end development and data management with passion to make a website for solving an everyday problem</p>
</div>
<div class="skill mb-3">
<h5 class="card-title mb-2">Skill</h5>
<p class="card-text">HTML, CSS, Javascript, Bootstrap, ReactJS, NodeJS, Git, and Native PHP
</p>
</div>
<div class="experience mb-3">
<h5 class="card-title mb-2">Professional Experience</h5>
<li>North Sulawesi Government Office as IT Experts assistant </li>
</div>
<div class="bootcamp mb-3">
<h5 class="card-title mb-2">Bootcamp Experience</h5>
<li>dibimbing.id, Front End Web Development Bootcamp (2022-2023)</li>
</div>
<div class="education mb-3">
<h5 class="card-title mb-2">Education Background</h5>
<li>Information System, Sam Ratulangi University Manado (2017-2022)</li>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal Jerry -->
<div class="modal fade" id="jerry" tabindex="-1" role="dialog" aria-labelledby="profile" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 880px;">
<div class="modal-content">
<div class="row g-3 m-2 mt-0">
<div class="col-lg-3">
<img src="img/jerry.jpeg" class="img-fluid rounded-2 mb-2" alt="...">
<h4 class="card-title text-center">Jerryanti Tandi Rau</h4>
<p class="text-muted text-center">Front End Developer</p>
<h4 class="card-title text-center">Contact Me</h4>
<p class="text-start mb-0 d-flex align-items-center"><i class="ri-mail-fill me-2"
style="font-size: 15px; color: #000;"></i> jtandirau@gmail.com</p>
<p class="text-start d-flex align-items-center"><i class="ri-phone-fill me-2"
style="font-size: 15px; color: #000;"></i> 0652784752</p>
</div>
<div class="col-lg-9">
<div class="card-body">
<div class="summary mb-3">
<h5 class="card-title mb-2">Summary</h5>
<p class="card-text">Passionate in front-end development, love writing quality code,
learning new tools, and solving interesting problems. I'm currently enrolling in a
front-end web development bootcamp to improve my front-end programming skill. </p>
</div>
<div class="skill mb-3">
<h5 class="card-title mb-2">Skill</h5>
<p class="card-text">HTML, CSS, Javascript, Bootstrap, ReactJS, NodeJS, Git, and Native PHP
</p>
</div>
<div class="experience mb-3">
<h5 class="card-title mb-2">Professional Experience</h5>
<li> Tourism Group International - Amsterdam </li>
</div>
<div class="bootcamp mb-3">
<h5 class="card-title mb-2">Bootcamp Experience</h5>
<li>dibimbing.id, Front End Web Development Bootcamp (2022-2023)</li>
</div>
<div class="education mb-3">
<h5 class="card-title mb-2">Education Background</h5>
<li>Information Technology, Politeknik Negeri Jakarta (2008-2011)</li>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal Yusup -->
<div class="modal fade" id="yusup" tabindex="-1" role="dialog" aria-labelledby="profile" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 880px;">
<div class="modal-content">
<div class="row g-3 m-2 mt-0">
<div class="col-lg-3">
<img src="img/yusup.jpeg" class="img-fluid rounded-2 mb-2" alt="...">
<h4 class="card-title text-center">Yusup C Dermawan</h4>
<p class="text-muted text-center">Front End Developer</p>
<h4 class="card-title text-center">Contact Me</h4>
<p class="text-start mb-0 d-flex align-items-center"><i class="ri-mail-fill me-2" style="font-size: 15px; color: #000;"></i> yusupcdrmwn@gmail.com</p>
<p class="text-start d-flex align-items-center"><i class="ri-phone-fill me-2" style="font-size: 15px; color: #000;"></i> 082252812885</p>
</div>
<div class="col-lg-9">
<div class="card-body">
<div class="summary mb-3">
<h5 class="card-title mb-2">Summary</h5>
<p class="card-text">Passionate in front-end development, likes to editing photos and videos from multiple
apps, interested in learning tools and apps I've never tried, and solving interesting problems.
I'm currently enrolling in a front-end web development bootcamp to improve my front-end programming
skills.</p>
</div>
<div class="skill mb-3">
<h5 class="card-title mb-2">Skills</h5>
<p class="card-text">HTML, CSS, Javascript, Bootstrap, Lightroom, Photoshop, Picsart, Filmora, Handling Event, etc.</p>
</div>
<div class="experience mb-3">
<h5 class="card-title mb-2">Experience</h5>
<li>Head Of Event Comitee In BEC</li>
</div>
<div class="bootcamp mb-3">
<h5 class="card-title mb-2">Bootcamp Experience</h5>
<li>dibimbing.id, Front End Web Development Bootcamp (2022-2023)</li>
</div>
<div class="education mb-3">
<h5 class="card-title mb-2">Education Background</h5>
<li>SMA BUDI UTOMO (2018-2021) &Basic English Course (march-august)</li>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Copas Modal kalian disini -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
</html>
|
'use client';
import '../assets/scss/input.scss'
import RichTextEditor from '../Components/RichTextEditor'
import React, { useContext, useState } from 'react'
import { unstable_noStore as noStore } from 'next/cache';
import Tag from '../Components/Tag';
import { UserProfileCtx } from '../context/userprofile'
import { toast } from 'react-toastify';
function Page() {
noStore()
const { userProfile } = useContext(UserProfileCtx)
console.log('userProfile', userProfile);
const [tag, setTag] = useState()
const [blogDetails, setblogDetails] = useState({
title: '',
desc: 'check',
previewDesc: '',
tags: [],
image: '',
date: new Date().toISOString().slice(0, 10),
})
console.log(blogDetails);
const publish = async () => {
console.log(JSON.stringify(blogDetails));
const formData = new FormData()
if (blogDetails.title, blogDetails.desc, blogDetails.previewDesc, blogDetails.tags, blogDetails.image) {
formData.append('title', blogDetails.title)
formData.append('desc', blogDetails.desc)
formData.append('previewDesc', blogDetails.previewDesc)
formData.append('tags', blogDetails.tags)
formData.append('image', blogDetails.image)
formData.append('date', blogDetails.date)
formData.append('author', userProfile.name)
const result = await fetch('/api', {
method: 'POST',
body: formData,
})
console.log(result);
const res = await result.json()
console.log(res);
res.status === 200 ? toast.success(res.msg, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
}) : toast.error(res.msg, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
})
} else {
toast.error('Please fill all the fields', {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
})
}
}
return (
<div className='text-2xl'>
<div className="inputContainer px-3 pb-5 flex items-center flex-col">
<div className="form__group group field">
<input type="input" onChange={(e) => {
setblogDetails({
...blogDetails,
title: e.target.value
})
}} className="text-xl font-light form__field" placeholder="Name" name="name" id='name' required />
<label htmlFor="name" className="form__label text-sm font-light">Title</label>
</div>
<div className="previewContainer relative flex w-full mt-3">
<input onChange={(e) => {
setblogDetails({
...blogDetails,
previewDesc: e.target.value
})
}} type="text" name="previewDesc" id="previewDesc" className='w-full py-2 border-b border-gray-400 peer outline-none text-base font-light mt-3' required />
<label htmlFor="previewDesc" className='transition ease-in-out left-0 absolute bottom-4 text-sm font-light peer-focus:-translate-y-5 peer-valid:-translate-y-5 text-gray-400'>Short Description</label>
</div>
<div className="previewContainer relative flex w-full mt-10">
<input onChange={(e) => {
setblogDetails({
...blogDetails,
image: e.target.files[0],
})
// console.log(1);
}} type="file" name="previewImage" id="previewImage" className='w-2/6 py-2 border-b border-gray-400 peer outline-none text-base font-light' required />
<label htmlFor="previewImage" className='transition ease-in-out left-0 absolute text-sm font-light text-gray-400 bottom-12'>Preview Image</label>
</div>
<div className='relative mt-5 flex flex-col sm:flex-row group w-full mr-auto'>
<div className="tagInputContainer relative flex">
<input onChange={(e) => {
setTag(e.target.value)
}} type="text" name="tags" id="tags" className='w-full sm:w-auto py-2 border-b border-gray-400 peer outline-none text-base font-light mt-3' required />
<label htmlFor="tags" className='transition ease-in-out left-0 absolute bottom-4 text-sm font-light peer-focus:-translate-y-5 peer-valid:-translate-y-5 text-gray-400'>Tags</label>
<button onClick={() => {
if (blogDetails.tags.length < 4 && !blogDetails.tags.includes(tag)) {
setblogDetails(prev => {
const tempTag = [...prev.tags]
tempTag.push(tag)
return {
...prev,
tags: tempTag
}
})
}
}} className={`ml-3 mt-3 transition ease-in-out duration-200 text-base rounded-full w-fit h-fit py-1.5 px-3 border-2 border-2 ${blogDetails.tags.length === 4 ? 'cursor-not-allowed bg-gray-300' : 'bg-aquamarine border-teal-400 hover:border-teal-600 active:bg-teal-300'}`}>
+
</button>
</div>
<div className="sm:mx-4 my-4 sm:my-0 sm:mt-0 tags-list-container flex flex-wrap flex-col sm:flex-row items-center">
{
blogDetails.tags.map((eachTag, index) => {
const id = Date.now()
return (
<Tag {...{ setblogDetails, eachTag, blogDetails, id, index }} key={index} />
)
})
}
</div>
</div>
<div className='h-fit'>
<button className="rounded bg-aquamarine px-5 py-3 text-sm" onClick={publish}>Publish</button>
</div>
</div>
<div className='quillContainer'>
<RichTextEditor setBlogDetails={setblogDetails} blogDetails={blogDetails} />
</div>
</div>
)
}
export default Page
// export const dynamic = 'force-dynamic';
|
<?php
namespace App\Controller;
use App\Entity\Comment;
use App\Entity\MicroPost;
use App\Form\CommentType;
use App\Form\MicroPostType;
use App\Repository\CommentRepository;
use App\Repository\MicroPostRepository;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class MicroPostController extends AbstractController
{
#[Route('/micro-post', name: 'app_micro_post')]
public function index(MicroPostRepository $posts, EntityManagerInterface $entityManager): Response
{
return $this->render('micro_post/index.html.twig', [
'posts' => $posts->findAllWithComments(),
]);
}
#[Route('/micro-post/{post}', name: 'app_micro_post_show')]
#[IsGranted(MicroPost::VIEW, 'post')]
public function showOne(MicroPost $post): Response
{
return $this->render('micro_post/show.html.twig', [
'post' => $post,
]);
}
#[Route(
'micro-post/add',
name: 'app_micro_post_add',
priority: 2
)]
#[IsGranted('ROLE_WRITER')]
public function add(
Request $request,
MicroPostRepository $posts,
EntityManagerInterface $entityManager
): Response {
$form = $this->createForm(
MicroPostType::class,
new MicroPost()
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$post = $form->getData();
$post->setAuthor($this->getUser());
$entityManager->persist($post);
$entityManager->flush();
// Add a flash message
$this->addFlash('success', 'Your micro post has been added.');
// Redirect
return $this->redirectToRoute('app_micro_post');
}
return $this->renderForm(
'micro_post/add.html.twig',
[
'form' => $form
]
);
}
#[Route('micro-post/{post}/edit', name: 'app_micro_post_edit')]
#[IsGranted(MicroPost::EDIT, 'post')]
public function edit(MicroPost $post, Request $request, MicroPostRepository $posts, EntityManagerInterface $entityManager): Response
{
$form = $this->createForm(MicroPostType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$post = $form->getData();
$entityManager->persist($post);
$entityManager->flush();
// Add a flash message
$this->addFlash('success', 'Your micro post has been updated.');
// Redirect
return $this->redirectToRoute('app_micro_post');
}
return $this->renderForm(
'micro_post/edit.html.twig',
[
'form' => $form,
'post' => $post
]
);
}
#[Route('micro-post/{post}/comment', name: 'app_micro_post_comment')]
#[IsGranted('ROLE_COMMENTER')]
public function addComment(MicroPost $post, Request $request, CommentRepository $comments, EntityManagerInterface $entityManager): Response
{
$form = $this->createForm(CommentType::class, new Comment());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$comment = $form->getData();
$comment->setPost($post);
$comment->setAuthor($this->getUser());
$entityManager->persist($comment);
$entityManager->flush();
// Add a flash message
$this->addFlash('success', 'Your comment has been updated.');
// Redirect
return $this->redirectToRoute(
'app_micro_post_show',
['post' => $post->getId()]
);
}
return $this->renderForm(
'micro_post/comment.html.twig',
[
'form' => $form,
'post' => $post
]
);
}
}
|
require 'nokogiri'
module GData
module Atom
class ElementWithId < Base
elements 'atom:id'
elements 'atom:title', 'atom:author*' => Author, 'atom:category*' => Category
elements 'atom:contributor*', 'atom:summary?'
elements 'atom:updated' => DateTime, 'atom:link*' => Link
def exists?
!self.id.empty?
end
def link_to_self
found = link.find { |l| l.rel == 'self' }
return nil unless found
found.href
end
def from_hash(hash)
hash.delete("link_to_self") if hash
super(hash)
end
def to_hash
result = super
result.merge "link_to_self" => link_to_self
end
def to_xml
super self.class.xml_tag
end
def self.from_xml(xml)
logger.info("reading #{xml_tag} from xml...")
xml_node = Nokogiri::XML(xml)
result = from_xml_node(xml_node, xml_tag, xml_node.namespaces["xmlns"])
logger.info("reading #{xml_tag} from xml - done.")
result
end
def self.xml_tag
raise NoMethodError
end
end
end
end
|
<?php
namespace AppBundle\Entity;
use Vich\UploaderBundle\Entity\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* Contributor
* @Vich\Uploadable
*/
class Contributor
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $firstName;
/**
* @var string
*/
private $lastName;
/**
* @var string
*/
private $role;
/**
* @var string|null
*/
private $githubLink;
/**
* @var string|null
*/
private $linkedinLink;
/**
* @var string|null
*/
private $behanceLink;
/**
* @var string|null
*/
private $email;
/**
* @var File
* @Vich\UploadableField(mapping="image", fileNameProperty="photoPath")
*/
private $photo;
/**
* @var string
*/
private $photoPath;
/**
* @var \DateTime
*/
private $lastUpdate;
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set firstName.
*
* @param string $firstName
*
* @return Contributor
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName.
*
* @return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName.
*
* @param string $lastName
*
* @return Contributor
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName.
*
* @return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set role.
*
* @param string $role
*
* @return Contributor
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Get role.
*
* @return string
*/
public function getRole()
{
return $this->role;
}
/**
* Set githubLink.
*
* @param string|null $githubLink
*
* @return Contributor
*/
public function setGithubLink($githubLink = null)
{
$this->githubLink = $githubLink;
return $this;
}
/**
* Get githubLink.
*
* @return string|null
*/
public function getGithubLink()
{
return $this->githubLink;
}
/**
* Set linkedinLink.
*
* @param string|null $linkedinLink
*
* @return Contributor
*/
public function setLinkedinLink($linkedinLink = null)
{
$this->linkedinLink = $linkedinLink;
return $this;
}
/**
* Get linkedinLink.
*
* @return string|null
*/
public function getLinkedinLink()
{
return $this->linkedinLink;
}
/**
* Set behanceLink.
*
* @param string|null $behanceLink
*
* @return Contributor
*/
public function setBehanceLink($behanceLink = null)
{
$this->behanceLink = $behanceLink;
return $this;
}
/**
* Get behanceLink.
*
* @return string|null
*/
public function getBehanceLink()
{
return $this->behanceLink;
}
/**
* Set email.
*
* @param string|null $email
*
* @return Contributor
*/
public function setEmail($email = null)
{
$this->email = $email;
return $this;
}
/**
* Get email.
*
* @return string|null
*/
public function getEmail()
{
return $this->email;
}
/**
* Set photo.
*
* @param $photo
* @return Contributor
*/
public function setPhoto($photo)
{
$this->photo = $photo;
if ($photo) {
$this->lastUpdate = new \DateTime();
}
return $this;
}
/**
* Get photo.
*
* @return File
*/
public function getPhoto()
{
return $this->photo;
}
/**
* @param $photoPath
*
* @return Contributor
*/
public function setPhotoPath($photoPath)
{
$this->photoPath = $photoPath;
return $this;
}
/**
* Get photoPath.
*
* @return string
*/
public function getPhotoPath()
{
return $this->photoPath;
}
}
|
/*
* Copyright 2021 MAS Veritas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.veritas.assessment.system.constant;
import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public enum ConfigPropertyKeyEnum {
DEFAULT_EMAIL_SUFFIX("default_email_suffix", ConfigTypeEnum.DEFAULT_VALUE),
DEFAULT_GROUP_LIMIT("default_limit_group", ConfigTypeEnum.DEFAULT_VALUE),
DEFAULT_PROJECT_LIMIT("default_limit_project", ConfigTypeEnum.DEFAULT_VALUE),
DEFAULT_USER_PASSWORD("default_user_password", ConfigTypeEnum.DEFAULT_VALUE),
REGISTER_SUPPORTED("register_supported", ConfigTypeEnum.CONFIG),
MODIFY_ACCOUNT_SUPPORTED("modify_account_supported", ConfigTypeEnum.CONFIG),
;
@Getter
@EnumValue
private final String name;
@Getter
private final ConfigTypeEnum type;
ConfigPropertyKeyEnum(String name, ConfigTypeEnum type) {
this.name = name;
this.type = type;
}
public static ConfigPropertyKeyEnum findByName(String name) {
for (ConfigPropertyKeyEnum value : values()) {
if (StringUtils.equals(value.getName(), name)) {
return value;
}
}
return null;
}
public static List<ConfigPropertyKeyEnum> findByType(ConfigTypeEnum configType) {
return Arrays.stream(values())
.filter(e -> e.type == configType)
.collect(Collectors.toList());
}
}
|
// Copyright (C) 2013 Brett R. Jones
// Issued to MIT style license by Brett R. Jones in 2017
//
// You may use, copy, modify, merge, publish, distribute, sub-license, and/or sell this software
// provided this Copyright is not modified or removed and is included all copies or substantial portions of the Software
//
// This code 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.
//
// bjones.engineer@gmail.com
// http://www.nolimitconnect.com
#ifndef MATHVEC2F_H
#define MATHVEC2F_H
#include <CoreLib/config_corelib.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
class Vec2f
{
public:
union
{
struct //stucture for cartesian format
{
float x;
float y;
};
float v[2];
};
//=== Constructors ===//
//for speed sake the variables are not initialized with default constructor
Vec2f (){};
Vec2f(const float _x, const float _y) : x(_x), y(_y) {};
Vec2f(const Vec2f& vec) : x(vec.x), y(vec.y) {};
Vec2f( float f[2] ){ x = f[0]; y = f[1]; }
Vec2f( float f ){x = f; y = f;}
// Vec2f( float _x, float _y) : x(_x), y(_y) {};
// Vec2f(Vec2f & v){ x = v.x, y = v.y;}
// Vec2f( float *p ) : x(p[0]), y(p[1]) {};
//=== Access grants ===//
//BUGBUG dont do this operator this way
//compiler bug happens when times vector * matrix
//float operator[](int index){ return v[index]; }
VXMATH_INLINE float operator[](int index){ return (&x)[index]; }
//=== operators ===//
VXMATH_INLINE Vec2f& operator+=(const Vec2f& v0)
{
x += v0.x;
y += v0.y;
return *this;
};
VXMATH_INLINE Vec2f& operator-=(const Vec2f& v0)
{
x -= v0.x;
y -= v0.y;
return *this;
};
VXMATH_INLINE Vec2f& operator*=(const float s)
{
x *= s;
y *= s;
return *this;
};
VXMATH_INLINE Vec2f& operator/=(const float s)
{
x /= s;
y /= s;
return *this;
};
VXMATH_INLINE bool operator==( const Vec2f& v0 )
{
if (x == v0.x && y == v0.y)
{
return true;
}
else
{
return false;
}
};
//=== methods ===//
bool IsZero();
bool IsZero( float fTol );
void Normalize(void);
void Set( const float x1, const float y1 );
void Set( const Vec2f v0 );
void SetToOrigin( void );
float Len(void);
bool IsEqualTo(const Vec2f& v0 );
bool IsEqualTo(const Vec2f& v0, const float& fTolerance);
void Reset( void );
};
// Vec2f macros
//
// these macros in general generate smaller code and much faster than member functions
//
#define Vec2fSetToMax(v) (v.x = MAX_F32, v.y = MAX_F32 )
#define Vec2fSetToMin(v) (v.x = MIN_F32, v.y = MIN_F32 )
#define Vec2fAbs(a, b) (b.x=(a.x>=0.0f)?a.x:-a.x,b.y=(a.y>=0.0f)?a.y:-a.y )
#define Vec2fSet(f, g, v) (v.x =(f),v.y=(g));
#define Vec2fNegate(a,b) (b.x=-a.x,b.y=-a.y)
#define Vec2fCopy(a,b) ((b).x=(a).x,(b).y=(a).y)
#define Vec2fSub(a,b,c) (c.x=a.x-b.x,c.y=a.y-b.y)
#define Vec2fAdd(a,b,c) (c.x=a.x+b.x,c.y=a.y+b.y)
#define Vec2fMult(a,b,c) (c.x=a.x*b.x,c.y=a.y*b.y)
#define Vec2fComb(A,a,B,b,c) (c.x=(A)*a.x+(B)*b.x,c.y=(A)*a.y+(B)*b.y)
#define Vec2fScale(A,a,b) (b.x=(A)*a.x,b.y=(A)*a.y)
#define Vec2fScaleAdd(A,a,b,c) (c.x=(A)*a.x+b.x,c.y=(A)*a.y+b.y)
#define Vec2fClear(v) (v.x=0.0f,v.y=0.0f)
#define Vec2fLen(a) (sqrt(a.x*a.x+a.y*a.y))
#define Vec2fLenSquared(a) (a.x*a.x+a.y*a.y)
#define Vec2fEqual(a,b) ((a.x==b.x && a.y==b.y)?1:0)
#define Vec2fIsZero(v) ((v.x==0.0f && v.y==0.0f)?1:0)
#define Vec2fMin( a,b,o) (o.x = MIN(a.x,b.x),o.y=MIN(a.y,b.y))
#define Vec2fMax( a,b,o) (o.x = MAX(a.x,b.x),o.y=MAX(a.y,b.y))
#define Vec2fClampAngle( v ) (ClampAngle(v.x), ClampAngle(v.y))
// Vec2f operators
//add operator
VXMATH_INLINE Vec2f operator+(const Vec2f& v0, const Vec2f& v1)
{
return Vec2f(v0.x+v1.x, v0.y+v1.y);
};
//subtract operator
VXMATH_INLINE Vec2f operator-(const Vec2f& v0, const Vec2f& v1)
{
return Vec2f(v0.x-v1.x, v0.y-v1.y);
};
//multiply operator
VXMATH_INLINE Vec2f operator*(const Vec2f& v0, const Vec2f& v1)
{
return Vec2f(v0.x*v1.x, v0.y*v1.y);
};
//multiply operator
VXMATH_INLINE Vec2f operator*( const float s, const Vec2f& v0)
{
return Vec2f(v0.x*s, v0.y*s);
};
//multiply operator
VXMATH_INLINE Vec2f operator*(const Vec2f& v0, const float s)
{
return Vec2f(v0.x*s, v0.y*s);
};
//divide operator
VXMATH_INLINE Vec2f operator/(const Vec2f& v0, const float s)
{
return Vec2f(v0.x/s, v0.y/s);
};
//negate operator
VXMATH_INLINE Vec2f operator-(const Vec2f& v)
{
return Vec2f(-v.x,-v.y);
};
// Vec2f methods
VXMATH_INLINE bool Vec2f::IsZero()
{
return((x==0.0f && y==0.0f )?1:0);
} // return true if x, y, and z is zero
VXMATH_INLINE bool Vec2f::IsZero( float fTol )
{
if( FastFabs( x ) > fTol )
{
return false;
}
else if ( FastFabs( y ) > fTol )
{
return false;
}
return true;
} // return true if x, y, and z is zero
VXMATH_INLINE void Vec2f::Set( const float x1, const float y1 )
{
x = x1;
y = y1;
};//initialize the vector with new params
VXMATH_INLINE void Vec2f::Set( const Vec2f v0 )
{
x = v0.x;
y = v0.x;
};//initialize the vector with new params
VXMATH_INLINE void Vec2f::SetToOrigin( void )
{
x = 0.0f;
y = 0.0f;
};
VXMATH_INLINE float Vec2f::Len(void)
{
return (float) sqrt(x*x+y*y);
};
VXMATH_INLINE void Vec2f::Normalize(void)
{
float l = Len();
if (l > TINY)
{
x /= l;
y /= l;
}
else
{
x = 0.0f;
y = 1.0f;
}
};
VXMATH_INLINE bool Vec2f::IsEqualTo(const Vec2f& v0 )
{
return((x==v0.x && y==v0.x )?1:0);
}
//which is faster ?
VXMATH_INLINE bool Vec2f::IsEqualTo(const Vec2f& v0, const float& fTol)
{
if( FastFabs(v0.x-x) > fTol )
{
return false;
}
else if ( FastFabs( v0.y-y ) > fTol )
{
return false;
}
return true;
};
/*
VXMATH_INLINE bool Vec2f::IsEqualTo(const Vec2f& v0, const float& fTol)
{
if (x < v0.x + fTol &&
x > v0.x - fTol &&
y < v0.y + fTol &&
y > v0.y - fTol)
{
return true;
}
else
{
return false;
}
};*/
/*
VXMATH_INLINE bool Vec2f::IsEqualTo(const Vec2f& v, const float tol)
{
float dx = n_abs(v.x-x);
float dy = n_abs(v.y-y);
if (dx > tol)
{
return false;
}
else if (dy > tol)
{
return false;
}
return true;
};*/
VXMATH_INLINE void Vec2f::Reset( void )
{
x = 0.0f;
y = 0.0f;
}
#endif //MATHVEC2F
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* MateriaSource.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zhlim <zhlim@student.42kl.edu.my> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/31 14:55:46 by zhlim #+# #+# */
/* Updated: 2023/11/01 13:10:06 by zhlim ### ########.fr */
/* */
/* ************************************************************************** */
#pragma once
# include "IMateriaSource.hpp"
class MateriaSource: public IMateriaSource {
private:
AMateria *slots[4];
int i;
public:
MateriaSource();
MateriaSource(MateriaSource &rhs);
~MateriaSource();
AMateria *getSlots(int i) const;
AMateria *const *getSlots() const;
int getI() const;
void learnMateria(AMateria*);
AMateria *createMateria(std::string const & type);
MateriaSource &operator=(MateriaSource &rhs);
};
|
// JSON data for locations on Earth
let geojson = {
type: 'FeatureCollection',
features: []
};
// Declare the map object
let map;
// Creates a new marker
function addMarker(coordinates, title, description, className) {
let el = document.createElement("div");
el.className = className;
new mapboxgl.Marker(el)
.setLngLat(coordinates)
.setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
.setHTML("<h3>" + title + "</h3><p>" + description + "</p>"))
.addTo(map);
}
// Loads the markers for RIT coffee shops
function loadMarkers() {
const coffeeShops = [
{
latitude: 43.084156,
longitude: -77.67514,
title: "Artesano Bakery & Cafe"
},
{
latitude: 43.083866,
longitude: -77.66901,
title: "Beanz"
},
{
latitude: 43.082520,
longitude: -77.67980,
title: "Starbucks"
},
{
latitude: 43.086678,
longitude: -77.669014,
title: "The College Grind"
},
{
latitude: 43.082634,
longitude: -77.68004,
title: "The Cafe & Market at Crossroads"
},
{
latitude: 43.08382,
longitude: -77.674805,
title: "RITZ Sports Zone"
},
{
latitude: 43.086502,
longitude: -77.66912,
title: "The Commons"
},
{
latitude: 43.08324,
longitude: -77.68105,
title: "The Market at Global Village"
},
{
latitude: 43.08384,
longitude: -77.67457,
title: "Brick City Cafe"
},
{
latitude: 43.084904,
longitude: -77.6676,
title: "Corner Store"
},
{
latitude: 43.08464,
longitude: -77.680145,
title: "CTRL ALT DELi"
},
{
latitude: 43.08359,
longitude: -77.66921,
title: "Gracie's"
}
];
// now convert this data to GeoJSON
for (let shop of coffeeShops) {
// An "empty" GeoJSON feature
const newFeature = {
type: "Feature",
geometry: {
type: "Point",
coordinates: []
},
properties: {
title: "",
description: "A place to get coffee!"
}
};
// Add some properties for the current coffee shop
newFeature.geometry.coordinates[0] = shop.longitude;
newFeature.geometry.coordinates[1] = shop.latitude;
newFeature.properties.title = shop.title;
// Push it into the "geojson" array
geojson.features.push(newFeature);
}
console.log(geojson.features);
}
// Creates the map object
function initMap() {
mapboxgl.accessToken = 'pk.eyJ1IjoiY2F0b2dyYXBoZXIiLCJhIjoiY2x1ZzFucGE5MjdkdTJrbWZqaWI1ODNveSJ9.U2o3E6ioE1zRpGEmwF5-9Q';
map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v11',
center: [-77.67454147338866, 43.08484339838443],
zoom: 15.5
});
// Allow buildings to be rendered in 3D
map.on('style.load', () => {
// Insert the layer beneath any symbol layer.
const layers = map.getStyle().layers;
const labelLayerId = layers.find((layer) => layer.type === 'symbol' && layer.layout['text-field']).id;
// The 'building' layer in the Mapbox Streets
// vector tileset contains building height data
// from OpenStreetMap.
map.addLayer(
{
'id': 'add-3d-buildings',
'source': 'composite',
'source-layer': 'building',
'filter': ['==', 'extrude', 'true'],
'type': 'fill-extrusion',
'minzoom': 15,
'paint': {
'fill-extrusion-color': '#aaa',
// Use an 'interpolate' expression to
// add a smooth transition effect to
// the buildings as the user zooms in.
'fill-extrusion-height': [
'interpolate',
['linear'],
['zoom'],
15,
0,
15.05,
['get', 'height']
],
'fill-extrusion-base': [
'interpolate',
['linear'],
['zoom'],
15,
0,
15.05,
['get', 'min_height']
],
'fill-extrusion-opacity': 0.6
}
},
labelLayerId
);
});
}
// Creates and adds the markers to the map and popups to the markers
function addMarkersToMap() {
// add markers to map
for (const feature of geojson.features) {
addMarker(feature.geometry.coordinates, feature.properties.title, feature.properties.description, "marker");
}
}
// Flies to the passed-in location
function flyTo(center = [0, 0]) {
// https://docs.mapbox.com/mapbox-gl-js/api/#map#flyto
map.flyTo({ cetner: center });
}
// Sets the zoom of the map to the specified value
function setZoomLevel(value = 0) {
// https://docs.mapbox.com/help/glossary/zoom-level/
map.setZoom(value);
}
// Sets the pitch and bearing values of the view of the map to the passed-in values
function setPitchAndBearing(pitch = 0, bearing = 0) {
// https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/
// https://docs.mapbox.com/mapbox-gl-js/example/set-perspective/
map.setPitch(pitch);
map.setBearing(bearing);
}
// Export the functions for creating the map, loading the RIT coffee shop markers, setting up the markers and popups, controlling the view of the map, and creating markers
export { initMap, loadMarkers, addMarkersToMap, flyTo, setZoomLevel, setPitchAndBearing, addMarker };
|
import {
Controller,
Delete,
Get,
Patch,
Post,
Param,
ValidationPipe,
UseGuards,
} from '@nestjs/common';
import { RecipientService } from '../services/recipient.service';
import { CreateRecipientDto } from '../dtos/create-recipient.dto';
import { UpdateRecipientDto } from '../dtos/update-recipient.dto';
import { customDecoratorsValidationOptions } from '../../config/validation.config';
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
import { CurrentUser } from 'src/auth/decorators/current-user.decorator';
import { User } from 'src/user/entities/user.entity';
import { CustomBody } from 'src/common/decorators/custom-body.decorator';
@Controller('companies/recipients')
@UseGuards(JwtAuthGuard)
export class RecipientController {
constructor(private readonly recipientService: RecipientService) {}
@Get()
async index(@CurrentUser() user: User) {
return {
message: 'Get recipients.',
data: await this.recipientService.index(user),
};
}
@Post()
async store(
@CurrentUser() user: User,
@CustomBody(new ValidationPipe(customDecoratorsValidationOptions))
createRecipientDto: CreateRecipientDto,
) {
return {
message: 'Recipient created successfully.',
data: await this.recipientService.store(user, createRecipientDto),
};
}
@Get(':recipient')
async show(@CurrentUser() user: User, @Param('recipient') recipient: string) {
return {
message: 'Get recipient.',
data: await this.recipientService.show(user, recipient),
};
}
@Patch(':recipient')
async update(
@CurrentUser() user: User,
@Param('recipient') recipient: string,
@CustomBody(
'recipient',
new ValidationPipe(customDecoratorsValidationOptions),
)
updateRecipientDto: UpdateRecipientDto,
) {
return {
message: 'Recipient updated successfully.',
data: await this.recipientService.update(
user,
recipient,
updateRecipientDto,
),
};
}
@Delete(':recipient')
async delete(
@CurrentUser() user: User,
@Param('recipient') recipient: string,
) {
return {
message: 'Recipient deleted successfully.',
data: await this.recipientService.delete(user, recipient),
};
}
}
|
#pragma once
#include "i_http_client.h"
#include <squick/core/i_module.h>
class IHttpClientModule : public IModule {
public:
virtual ~IHttpClientModule(){};
template <typename BaseType>
bool DoGet(const std::string &strUri, BaseType *pBase,
void (BaseType::*handleReceiver)(const Guid id, const int state_code, const std::string &strRespData)) {
HTTP_RESP_FUNCTOR_PTR pd(new HTTP_RESP_FUNCTOR(std::bind(handleReceiver, pBase, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)));
return DoGet(strUri, std::map<std::string, std::string>(), pd);
}
bool DoGet(const std::string &strUri, HTTP_RESP_FUNCTOR functor) {
HTTP_RESP_FUNCTOR_PTR pd(new HTTP_RESP_FUNCTOR(functor));
return DoGet(strUri, std::map<std::string, std::string>(), pd);
}
template <typename BaseType>
bool DoGet(const std::string &strUri, const std::map<std::string, std::string> &xHeaders, BaseType *pBase,
void (BaseType::*handleReceiver)(const Guid id, const int state_code, const std::string &strRespData)) {
HTTP_RESP_FUNCTOR_PTR pd(new HTTP_RESP_FUNCTOR(std::bind(handleReceiver, pBase, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)));
return DoGet(strUri, xHeaders, pd);
}
bool DoGet(const std::string &strUri, const std::map<std::string, std::string> &xHeaders, HTTP_RESP_FUNCTOR functor) {
HTTP_RESP_FUNCTOR_PTR pd(new HTTP_RESP_FUNCTOR(functor));
return DoGet(strUri, xHeaders, pd);
}
template <typename BaseType>
bool DoPost(const std::string &strUri, const std::string &strPostData, BaseType *pBase,
void (BaseType::*handleReceiver)(const Guid id, const int state_code, const std::string &strRespData, const std::string &strMemo),
const std::string &strMemo = "") {
HTTP_RESP_FUNCTOR_PTR pd(new HTTP_RESP_FUNCTOR(
std::bind(handleReceiver, pBase, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)));
return DoPost(strUri, std::map<std::string, std::string>(), strPostData, pd, strMemo);
}
bool DoPost(const std::string &strUri, const std::string &strPostData, HTTP_RESP_FUNCTOR functor, const std::string &strMemo = "") {
HTTP_RESP_FUNCTOR_PTR pd(new HTTP_RESP_FUNCTOR(functor));
return DoPost(strUri, std::map<std::string, std::string>(), strPostData, pd, strMemo);
}
template <typename BaseType>
bool DoPost(const std::string &strUri, const std::string &strPostData, const std::map<std::string, std::string> &xHeaders, BaseType *pBase,
void (BaseType::*handleReceiver)(const Guid id, const int state_code, const std::string &strRespData), const std::string &strMemo = "") {
HTTP_RESP_FUNCTOR_PTR pd(new HTTP_RESP_FUNCTOR(std::bind(handleReceiver, pBase, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)));
return DoPost(strUri, xHeaders, strPostData, pd, strMemo);
}
bool DoPost(const std::string &strUri, const std::string &strPostData, const std::map<std::string, std::string> &xHeaders, HTTP_RESP_FUNCTOR functor,
const std::string &strMemo = "") {
HTTP_RESP_FUNCTOR_PTR pd(new HTTP_RESP_FUNCTOR(functor));
return DoPost(strUri, xHeaders, strPostData, pd, strMemo);
}
// actually, sync post method
// WebStatus
virtual int Post(const std::string &strUri, const std::string &strData, std::string &strResData) = 0;
virtual int Post(const std::string &strUri, const std::map<std::string, std::string> &xHeaders, const std::string &strData, std::string &strResData) = 0;
// actually, sync get method
// WebStatus
virtual int Get(const std::string &strUri, std::string &strResData) = 0;
virtual int Get(const std::string &strUri, const std::map<std::string, std::string> &xHeaders, std::string &strResData) = 0;
protected:
virtual bool DoGet(const std::string &strUrl, const std::map<std::string, std::string> &xHeaders, HTTP_RESP_FUNCTOR_PTR pCB) = 0;
virtual bool DoPost(const std::string &strUrl, const std::map<std::string, std::string> &xHeaders, const std::string &strPostData,
HTTP_RESP_FUNCTOR_PTR pCB, const std::string &strMemo) = 0;
};
|
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.16;
import "lib/openzeppelin-contracts/contracts/utils/Counters.sol";
import "lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol";
import "lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol";
import "lib/openzeppelin-contracts-upgradeable/contracts/security/PausableUpgradeable.sol";
import "lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
// import "../node_modules/hardhat/console.sol";
/// @title RAFT Contract
/// @author Otterspace
/// @notice The RAFT NFT gives the owner the ability to create a DAO within Otterspace
/// @dev Inherits from ERC721Enumerable so that we can access useful functions for
/// querying owners of tokens from the web app.
contract Raft is
ERC721EnumerableUpgradeable,
UUPSUpgradeable,
OwnableUpgradeable,
PausableUpgradeable
{
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
mapping(uint256 => string) private _tokenURIs;
mapping(uint256 => mapping(address => bool)) private _admins;
event MetadataUpdate(uint256 indexed tokenId);
event AdminUpdate(
uint256 indexed tokenId,
address indexed admin,
bool isAdded
);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(
address nextOwner,
string memory name_,
string memory symbol_
) public initializer {
__ERC721Enumerable_init();
__ERC721_init(name_, symbol_);
__UUPSUpgradeable_init();
__Ownable_init();
// Passing in the owner's address allows an EOA to deploy and set a multi-sig as the owner.
transferOwnership(nextOwner);
// pause the contract by default
_pause();
}
function mint(address recipient, string memory uri)
public
virtual
returns (uint256)
{
// owners can always mint tokens
// non-owners can only mint when the contract is unpaused
require(msg.sender == owner() || !paused(), "mint: unauthorized to mint");
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
require(recipient != address(0), "cannot mint to zero address");
_mint(recipient, newItemId);
_tokenURIs[newItemId] = uri;
return newItemId;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
// we are basically implementing the functionality of ERC721URIStorage ourselves here
function setTokenURI(uint256 tokenId, string memory uri)
public
virtual
onlyOwner
{
require(_exists(tokenId), "setTokenURI: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
emit MetadataUpdate(tokenId);
}
function setAdmin(
uint256 tokenId,
address admin,
bool isActive
) public virtual {
require(_exists(tokenId), "addAdmin: tokenId does not exist");
require(ownerOf(tokenId) == msg.sender, "addAdmin: unauthorized");
_admins[tokenId][admin] = isActive;
emit AdminUpdate(tokenId, admin, isActive);
}
function isAdminActive(uint256 tokenId, address admin)
public
view
virtual
returns (bool)
{
return _admins[tokenId][admin];
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
return _tokenURIs[tokenId];
}
function _authorizeUpgrade(address) internal override onlyOwner {}
}
|
import {Component, EventEmitter, ViewChild} from '@angular/core';
import {of, Subscription, zip} from 'rxjs';
import {NavService} from '@app/services/nav/nav.service';
import {SqliteService} from '@app/services/sqlite/sqlite.service';
import {LoadingService} from '@app/services/loading.service';
import {map, mergeMap} from 'rxjs/operators';
import {Dispatch} from '@entities/dispatch';
import {CardListConfig} from '@common/components/card-list/card-list-config';
import {CardListColorEnum} from '@common/components/card-list/card-list-color.enum';
import {MainHeaderService} from '@app/services/main-header.service';
import {SelectItemComponent} from "@common/components/select-item/select-item.component";
import {ToastService} from '@app/services/toast.service';
import {NavPathEnum} from '@app/services/nav/nav-path.enum';
import {Translations} from '@entities/translation';
import {TranslationService} from '@app/services/translations.service';
import {StorageService} from "@app/services/storage/storage.service";
import {FormPanelParam} from "@common/directives/form-panel/form-panel-param";
import {FormPanelComponent} from "@common/components/panel/form-panel/form-panel.component";
import {Status} from "@entities/status";
import {FormPanelInputComponent} from "@common/components/panel/form-panel/form-panel-input/form-panel-input.component";
import {ApiService} from "@app/services/api.service";
import {ViewWillEnter, ViewWillLeave} from "@ionic/angular";
import {StorageKeyEnum} from "@app/services/storage/storage-key.enum";
import * as bcrypt from 'bcryptjs';
import * as moment from "moment";
import {User} from "@entities/user";
import {Emplacement} from "@entities/emplacement";
import {DispatchPack} from "@entities/dispatch-pack";
import {DispatchReference} from "@entities/dispatch-reference";
@Component({
selector: 'wii-dispatch-grouped-signature-finish',
templateUrl: './dispatch-grouped-signature-finish.page.html',
styleUrls: ['./dispatch-grouped-signature-finish.page.scss'],
})
export class DispatchGroupedSignatureFinishPage implements ViewWillEnter, ViewWillLeave {
@ViewChild('formPanelComponent', {static: false})
public formPanelComponent: FormPanelComponent;
public selectItemComponent: SelectItemComponent;
private loadingSubscription?: Subscription;
public loading: boolean;
public firstLaunch: boolean;
public resetEmitter$: EventEmitter<void>;
public offlineMode?: boolean;
public labelFrom?: string;
public labelTo?: string;
public selectedStatus: Status;
public from?: {
id: number,
text: string
};
public to?: {
id: number,
text: string
};
public dispatchesToSignListConfig: Array<CardListConfig>;
public readonly dispatchesListColor = CardListColorEnum.GREEN;
public dispatchesToSign: Array<Dispatch>;
public bodyConfig: Array<FormPanelParam>;
public constructor(private sqliteService: SqliteService,
private toastService: ToastService,
private loadingService: LoadingService,
private mainHeaderService: MainHeaderService,
private translationService: TranslationService,
private storageService: StorageService,
private apiService: ApiService,
private navService: NavService) {
this.resetEmitter$ = new EventEmitter<void>();
this.loading = true;
this.firstLaunch = true;
}
public ionViewWillEnter(): void {
this.resetEmitter$.emit();
this.translationService.get(`Demande`, `Acheminements`, `Champs fixes`).subscribe((translations: Translations) => {
this.labelFrom = TranslationService.Translate(translations, 'Emplacement de prise');
this.labelTo = TranslationService.Translate(translations, 'Emplacement de dépose');
this.selectedStatus = this.navService.param('status');
this.from = this.navService.param('from');
this.to = this.navService.param('to');
this.dispatchesToSign = this.navService.param('dispatches');
this.dispatchesToSignListConfig = this.dispatchesToSign
.map((dispatch: Dispatch) => {
return {
title: {label: 'Statut', value: dispatch.statusLabel},
customColor: dispatch.groupedSignatureStatusColor || dispatch.color,
content: [
{label: 'Numéro', value: dispatch.number || ''},
{label: 'Type', value: dispatch.typeLabel || ''},
{
label: this.labelFrom,
value: dispatch.locationFromLabel || ''
},
{
label: this.labelTo,
value: dispatch.locationToLabel || ''
},
{
label: 'Références (quantité)',
value: dispatch.quantities || ''
},
].filter((item) => item && item.value),
};
});
this.bodyConfig = [
{
item: FormPanelInputComponent,
config: {
label: 'Trigramme signataire',
name: 'signatoryTrigram',
value: '',
inputConfig: {
required: true,
type: 'text',
disabled: false
},
}
},
{
item: FormPanelInputComponent,
config: {
label: 'Code signataire',
name: 'signatoryPassword',
value: '',
inputConfig: {
required: true,
type: 'password',
disabled: false
},
}
},
{
item: FormPanelInputComponent,
config: {
label: 'Commentaire',
name: 'comment',
value: '',
inputConfig: {
required: Boolean(this.selectedStatus.commentNeeded),
type: 'text',
disabled: false
},
}
},
];
});
this.storageService.getRight(StorageKeyEnum.DISPATCH_OFFLINE_MODE)
.subscribe((offlineMode: boolean) => {
this.offlineMode = offlineMode;
});
}
public ionViewWillLeave(): void {
this.unsubscribeLoading();
if (this.selectItemComponent) {
this.selectItemComponent.unsubscribeZebraScan();
}
}
private unsubscribeLoading(): void {
if (this.loadingSubscription) {
this.loadingSubscription.unsubscribe();
this.loadingSubscription = undefined;
}
}
public checkSignatureAndUpdateStatuses(signatoryPassword: string, signatory?: User) {
const success = signatory && signatory.signatoryPassword && bcrypt.compareSync(signatoryPassword, signatory.signatoryPassword);
return (this.offlineMode && success || !this.offlineMode)
? this.sqliteService.update(
'dispatch',
[{
values: {
statusId: this.selectedStatus.id,
statusLabel: this.selectedStatus.label,
partial: this.selectedStatus.state === 'partial' ? 1 : 0,
treatedStatusId: this.selectedStatus.state === 'treated' ? this.selectedStatus.id : null,
groupedSignatureStatusColor: this.selectedStatus.groupedSignatureColor,
},
where: [`localId IN (${this.dispatchesToSign.map((dispatch: Dispatch) => dispatch.localId).join(',')})`],
}])
: of(undefined)
}
public checkSignatureAndInsertProcesses(signatoryPassword: string, operator: string | null, signatory?: User, comment?: string) {
return this.sqliteService.findBy('dispatch_pack', [`localDispatchId IN (${this.dispatchesToSign.map((dispatch) => dispatch.localId).join(',')})`])
.pipe(
mergeMap((dispatchPacks) => {
return dispatchPacks.length > 0
? this.sqliteService
.findBy('dispatch_reference', [`localDispatchPackId IN (${dispatchPacks.map(({localId}) => localId).join(',')})`])
.pipe(map((dispatchReferences) => {
return dispatchReferences.map(({localDispatchPackId, ...remaining}: DispatchReference) => {
const dispatchPack = dispatchPacks.find(({localId}: DispatchPack) => localDispatchPackId === localId);
return {
...remaining,
localDispatchId: dispatchPack.localDispatchId,
};
});
}))
: of([])
}),
mergeMap((dispatchReferences) => {
const allDispatchCanBeSigned = this.dispatchesToSign.every((dispatch) => (
dispatchReferences
.filter(({localDispatchId}) => dispatch.localId === localDispatchId)
.length > 0
));
if (!allDispatchCanBeSigned) {
return of({
success: false,
msg: 'Erreur : tous les acheminements doivent contenir au moins une référence',
})
} else if (signatory) {
let location;
if (this.from && this.selectedStatus.groupedSignatureType === 'Enlèvement') {
location = this.from.id;
} else if (this.to && this.selectedStatus.groupedSignatureType === 'Livraison') {
location = this.to.id;
}
return location
? this.sqliteService.findOneById('emplacement', location)
.pipe(
mergeMap((location?: Emplacement) => {
const signatoriesIds = location?.signatories
? location.signatories.split(';').filter((element) => element)
: [];
const success = signatory
&& signatory.signatoryPassword
&& location
&& signatoriesIds.includes(`${signatory.id}`)
&& bcrypt.compareSync(signatoryPassword, signatory.signatoryPassword);
if (success) {
return this.sqliteService.insert('grouped_signature_history', this.dispatchesToSign.map((dispatch: Dispatch) => ({
groupedSignatureType: this.selectedStatus.groupedSignatureType,
location,
signatory: signatory.id,
operateur: operator,
statutFrom: this.dispatchesToSign[0].statusId,
statutTo: this.selectedStatus.id,
signatureDate: moment().format(),
dispatchId: dispatch.id,
localDispatchId: dispatch.localId,
comment
}))).pipe(map(() => ({
success: true,
msg: 'Signature groupée effectuée',
})));
}
return of({
success: false,
msg: 'Informations invalides',
});
}))
: of({
success: false,
msg: 'Informations invalides',
});
} else {
return of({
success: false,
msg: 'Informations invalides',
});
}
}));
}
public finishGroupedSignature() {
if(!this.to?.id && !this.from?.id) {
this.toastService.presentToast(`Aucun emplacement n'a été trouvé dans la signature groupée.`)
} else {
const {signatoryTrigram, signatoryPassword, comment} = this.formPanelComponent.values;
if (signatoryTrigram && signatoryPassword && (!Boolean(this.selectedStatus.commentNeeded) || comment)) {
this.loadingService.presentLoadingWhile({
event: () => {
return this.sqliteService.findOneBy('user', {username: signatoryTrigram})
.pipe(
mergeMap((signatory) => {
return this.checkSignatureAndUpdateStatuses(signatoryPassword, signatory);
}),
mergeMap(() => {
if (this.offlineMode) {
return zip(
this.sqliteService.findOneBy('user', {username: signatoryTrigram}),
this.storageService.getString(StorageKeyEnum.OPERATOR_ID)
).pipe(
mergeMap(([signatory, operator]) => {
return this.checkSignatureAndInsertProcesses(signatoryPassword, operator, signatory, comment);
}));
} else {
return this.apiService.requestApi(ApiService.FINISH_GROUPED_SIGNATURE, {
params: {
from: this.from ? this.from.id : null,
to: this.to ? this.to.id : null,
status: this.selectedStatus.id,
signatoryTrigram,
signatoryPassword,
comment,
dispatchesToSign: this.dispatchesToSign.map((dispatch: Dispatch) => dispatch.id).join(','),
}
})
}
})
)
}
}).subscribe((response) => {
this.toastService.presentToast(response.msg).subscribe(() => {
if (response.success) {
if (this.offlineMode) {
this.navService.pop({
path: NavPathEnum.DISPATCH_REQUEST_MENU
})
} else {
this.navService.setRoot(NavPathEnum.MAIN_MENU);
}
}
});
});
} else {
if (!signatoryTrigram && !signatoryPassword) {
this.toastService.presentToast('Veuillez saisir un trigramme signataire et un code signataire.');
} else if (!signatoryTrigram) {
this.toastService.presentToast('Veuillez saisir un trigramme signataire.');
} else if (!signatoryPassword) {
this.toastService.presentToast('Veuillez saisir un code signataire.');
} else if (Boolean(this.selectedStatus.commentNeeded) && !comment) {
this.toastService.presentToast('Veuillez saisir un commentaire.');
}
}
}
}
}
|
//
// MotionAnimationView.swift
// AfricaApp
//
// Created by Thomas Cowern on 7/11/23.
//
import SwiftUI
struct MotionAnimationView: View {
// MARK: - Properties
@State private var randomCircle = Int.random(in: 12...16)
@State private var isAnimating: Bool = false
// random coordinate
func randomCoordinate(max: CGFloat) -> CGFloat {
return CGFloat.random(in: 0...max)
}
// random size
func randomSize() -> CGFloat {
return CGFloat.random(in: 10...300)
}
// random scale
func randomScale() -> CGFloat {
return CGFloat(Double.random(in: 0.1...2.0))
}
// random speed
func randomSpeed() -> Double {
return Double.random(in: 0.025...1.0)
}
// random delay
func randomDelay() -> Double {
return Double.random(in: 0...2)
}
// MARK: - Body
var body: some View {
GeometryReader { geometry in
ZStack {
ForEach(0...randomCircle, id: \.self) { item in
Circle()
.foregroundColor(Color.gray)
.opacity(0.15)
.frame(width: randomSize(), height: randomSize(), alignment: .center)
.scaleEffect(randomScale())
.position(
x: randomCoordinate(max: geometry.size.width),
y: randomCoordinate(max: geometry.size.height)
)
.animation(Animation.interpolatingSpring(stiffness: 0.5, damping: 0.5).repeatForever().speed(randomSpeed()).delay(randomDelay()), value: isAnimating)
.onAppear {
isAnimating = true
}
} //: End of ForEach
} //: End of ZStack
.drawingGroup()
} //: end of geometry reader
}
}
// MARK: - Preview
struct MotionAnimationView_Previews: PreviewProvider {
static var previews: some View {
MotionAnimationView()
}
}
|
import { Box, IconButton, useTheme } from "@mui/material";
import { Typography } from "@mui/material/";
import { tokens } from "./../../theme";
import * as React from "react";
import Breadcrumbs from "@mui/material/Breadcrumbs";
import Link from "@mui/material/Link";
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
import InputBase from "@mui/material/InputBase";
import SearchIcon from "@mui/icons-material/Search";
import TimelineIcon from "@mui/icons-material/Timeline";
import FilterAltIcon from "@mui/icons-material/FilterAlt";
import AddIcon from "@mui/icons-material/Add";
import FormDialog from "../FormDialog";
import PropTypes from 'prop-types';
// import StatsCard from "./StatsCard";
// function handleClick(event) {
// event.preventDefault();
// console.info("You clicked a breadcrumb.");
// }
const InvoiceHeader = ({
handleFormSubmit,
hideStatCard,
searchValue,
setSearchValue,
}) => {
const theme = useTheme();
const colors = tokens(theme.palette.mode);
const [open, setOpen] = React.useState(false);
const handleClickOpen = () => {
setOpen(true);
};
// const handleClose = () => {
// setOpen(false);
// };
return (
<Box>
<Box
display="flex"
justifyContent="space-between"
alignItems="center"
sx={{
[theme.breakpoints.down("md")]: {
display: "grid",
},
}}
>
<Box
sx={{
[theme.breakpoints.down("md")]: {
pb: 4,
mt: "50px",
},
}}
>
<Typography variant="h3" color={colors.blueAccent[400]}>
Invoices
</Typography>
<Box>
<Breadcrumbs
aria-label="breadcrumb"
separator={<NavigateNextIcon fontSize="small" />}
>
<Link underline="hover" color="inherit" href="#">
HOME
</Link>
<Link underline="hover" color="inherit" href="#">
SALES
</Link>
<Link
underline="hover"
color="text.primary"
href="#"
aria-current="page"
>
INVOICES
</Link>
</Breadcrumbs>
</Box>
</Box>
<Box display="flex" justifyContent="center">
<Box
display="flex"
backgroundColor={colors.primary[400]}
borderRadius="3px"
>
<InputBase
sx={{ ml: 2, width: 80 }}
placeholder="Search"
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
/>
<IconButton type="button" sx={{ p: 1 }}>
<SearchIcon />
</IconButton>
</Box>
<Box
width="40px"
hieght="30px"
display="flex"
justifyContent="center"
alignItems="center"
backgroundColor={colors.grey[800]}
ml="10px"
borderRadius="3px"
>
<IconButton onClick={hideStatCard}>
<TimelineIcon />
</IconButton>
</Box>
<Box
width="40px"
hieght="30px"
display="flex"
justifyContent="center"
alignItems="center"
backgroundColor={colors.grey[800]}
ml="10px"
borderRadius="3px"
>
<IconButton>
<FilterAltIcon />
</IconButton>
</Box>
<Box
width="40px"
hieght="40px"
display="flex"
justifyContent="center"
alignItems="center"
backgroundColor={colors.redAccent[500]}
ml="10px"
borderRadius="50%"
>
<IconButton onClick={handleClickOpen}>
<AddIcon />
</IconButton>
</Box>
</Box>
<Box open={open} position="absolute">
<FormDialog
open={open}
setOpen={setOpen}
handleFormSubmit={handleFormSubmit}
/>
</Box>
</Box>
<Box>{/* <StatsCard /> */}</Box>
</Box>
);
};
InvoiceHeader.propTypes = {
handleFormSubmit: PropTypes.func.isRequired,
hideStatCard: PropTypes.bool.isRequired,
searchValue: PropTypes.string.isRequired,
setSearchValue: PropTypes.func.isRequired,
};
export default InvoiceHeader;
|
import type { NextPage } from "next";
import Head from "next/head";
import mImage from "../images/M.png";
import Header from "../components/Header";
import { sanityClient, urlFor } from "../sanity";
import { Post } from "../typings";
import Link from "next/link";
interface Props {
posts: [Post];
}
const Home: NextPage<Props> = ({ posts }) => {
// console.log(posts);
return (
<div className="max-w-4xl mx-auto">
<Head>
<title>Medium</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<div className="flex justify-between items-center bg-yellow-400 border-y border-black py-10 lg:py-0">
<div className="px-10 space-y-5">
<h1 className="text-7xl max-w-xl font-serif">
<span className="underline decoration-black decoration-4">
Medium
</span>{" "}
is a place to write, read and connect
</h1>
<h2>
It's easy and free to post your thinking on any topic
and connect with millions of readers
</h2>
</div>
<img
className="hidden md:inline-flex h-24 lg:h-32"
src={mImage.src}
alt="M"
/>
</div>
{/* Posts */}
<div
className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3
md:gap-6 p-2 md:p-6"
>
{posts.map((post) => (
<Link key={post._id} href={`/post/${post.slug.current}`}>
<div className="border rounded-lg group cursor-pointer overflow-hidden">
{post.mainImage && (
<img
className="h-60 w-full object-cover group-hover:scale-105 transition-transform duration-200 ease-in-out"
src={urlFor(post.mainImage).url()}
alt="post"
/>
)}
<div className="flex justify-between p-5 bg-white">
<div>
<p className="text-lg font-bold">
{post.title}
</p>
<p className="text-sm font-light">
{post.description} by {post.author.name}
</p>
</div>
{post.author.image && (
<img
className="h-12 w-12 rounded-full"
src={urlFor(post.author.image).url()}
alt={post.author.name}
/>
)}
</div>
</div>
</Link>
))}
</div>
</div>
);
};
export default Home;
export const getServerSideProps = async () => {
const query = `*[_type == "post"]{
_id,
title,
author -> {
name,
image
},
description,
mainImage,
slug
}`;
const posts = await sanityClient.fetch(query);
return {
props: {
posts,
},
};
};
|
import React, {useEffect, useState} from 'react';
import { View, Text, TextInput, Button, TouchableOpacity, StyleSheet, KeyboardAvoidingView, Platform } from 'react-native';
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { collection, getDocs, addDoc, query, where } from "firebase/firestore";
import { launchImageLibrary } from 'react-native-image-picker';
import RNPickerSelect from 'react-native-picker-select';
import AsyncStorage from "@react-native-async-storage/async-storage";
const firebaseConfig = {
apiKey: "AIzaSyCX2PhLpEJX_n39XVit_bjCz-XFiQaIn-Y",
authDomain: "seniordesign-ae10f.firebaseapp.com",
projectId: "seniordesign-ae10f",
storageBucket: "seniordesign-ae10f.appspot.com",
messagingSenderId: "230961872715",
appId: "1:230961872715:web:6e830a80f457c42770b2ce",
measurementId: "G-H4KWB4XWGK",
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const colRef = collection(db, "users");
const checkUser = async (uName) => {
const [users, setUsers] = useState([]);
useEffect(() => {
// Fetch users from Firestore
const fetchUsers = async () => {
try {
const querySnapshot = await getDocs(colRef);
const userData = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
setUsers(userData);
console.log(userData); // Print users data to the console
} catch (error) {
console.error('Error fetching users:', error);
}
};
fetchUsers()
.catch(error => console.error('Error fetching users:', error));
}, []); // Empty dependency array to ensure this effect runs only once
}
const SignUp = ({ navigation }) => {
const [currentUserLocation, setCurrentUserLocation] = useState(null); // State to store current user's location
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [pronouns, setPronouns] = useState('');
const [birthday, setBirthday] = useState('');
const [profession, setProfession] = useState('');
const [interests, setInterests] = useState('');
const [aboutMe, setAboutMe] = useState('');
const [location, setLocation] = useState('');
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const createAccount = async () => {
// Check if username is empty
if (!username.trim()) {
alert("Username cannot be empty.");
return; // Exit the function if username is empty
}
const colRef = collection(db, "users")
const querySnapshot = await getDocs(query(collection(db, "users"), where("username", "==", username)));
if (!querySnapshot.empty) {
// Username already exists, display message to the user
alert("Username already exists. Please choose a different username.");
return; // Exit the function without adding the user
}
try {
const newUser = {
username: username,
password: password,
name: name,
pronouns: pronouns,
birthday: birthday,
profession: profession,
interests: interests,
aboutMe: aboutMe,
location: location,
};
const docRef = await addDoc(colRef, newUser);
console.log("New user added with ID: ", docRef.id);
// Reset input fields after successful user creation
setUsername('');
setPassword('');
setName('');
setPronouns('');
setBirthday('');
setProfession('');
setInterests('');
setAboutMe('');
setLocation('');
const userID = docRef.id;
//const username = newUser.username;
const userLocation = newUser.location;
setCurrentUserLocation(newUser.location);
await AsyncStorage.setItem('userID', userID); // Store user information in AsyncStorage
console.log(await AsyncStorage.getItem('userID'))
await AsyncStorage.setItem('username', username);
navigation.replace('Home', { currentUserLocation: userLocation});
} catch (error) {
console.error('Error creating account:', error);
}
};
const [selectedCity, setSelectedCity] = useState(setLocation);
const handleLocationChange = (itemValue) => {
setSelectedCity(itemValue);
setLocation(itemValue);
};
const toggleShowPassword = () => {
setIsPasswordVisible(!isPasswordVisible);
};
const [avatarUri, setAvatarUri] = useState(null);
// Function to handle the selection of an avatar
const handleChoosePhoto = () => {
const options = { noData: true, mediaType: 'photo' };
launchImageLibrary(options, response => {
if (response.uri) {
setAvatarUri(response.uri);
}
});
};
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={{ flex: 1 }}
>
<View style={styles.container}>
<Text style={styles.name}>UniLink</Text>
<Text style={styles.slogin}>The App That Brings Us Together</Text>
<TouchableOpacity onPress={handleChoosePhoto} style={styles.avatarPlaceholder}>
{avatarUri ? (
<Image source={{ uri: avatarUri }} style={styles.avatar} />
) : (
<Text style={styles.avatarPlaceholderText}>Choose Photo</Text>
)}
</TouchableOpacity>
<TextInput
style={styles.input}
placeholder="Username"
value={username}
onChangeText={setUsername}
/>
<TextInput
style={styles.input}
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry={!isPasswordVisible}
/>
<View style={styles.checkboxContainer}>
{/*
<Box
value={isPasswordVisible}
onValueChange={toggleShowPassword}
/>
*/}
<Text>Show Password</Text>
</View>
<TextInput
style={styles.input}
placeholder="Name"
value={name}
onChangeText={setName}
/>
<TextInput
style={styles.input}
placeholder="Pronouns"
value={pronouns}
onChangeText={setPronouns}
/>
<TextInput
style={styles.input}
placeholder="Birthday (January 1, 2000)"
value={birthday}
onChangeText={setBirthday}
/>
<TextInput
style={styles.input}
placeholder="Profession"
value={profession}
onChangeText={setProfession}
/>
<TextInput
style={styles.input}
placeholder="Interests (seperate by ',')"
value={interests}
onChangeText={setInterests}
/>
<TextInput
style={styles.input}
placeholder="Bio"
value={aboutMe}
onChangeText={setAboutMe}
/>
<View style={styles.input}>
<RNPickerSelect
onValueChange={(setLocation)}
items={[
{ label: 'Des Moines, IA', value: 'Des Moines, IA' },
{ label: 'Chicago, IL', value: 'Chicago, IL' },
{ label: 'Minneapolis, MN', value: 'Minneapolis, MN' },
]}
style={pickerSelectStyles}
useNativeAndroidPickerStyle={false}
placeholder={{
label: 'Select a city...',
value: "",
}}
value={location}
/>
</View>
<Button title="Create Account" onPress={createAccount} />
</View>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
input: {
width: '100%',
height: 40,
marginVertical: 10,
borderWidth: 1,
padding: 10,
borderRadius: 5,
},
checkboxContainer: {
flexDirection: 'row',
alignItems: 'center',
},
signupPrompt: {
flexDirection: 'row',
marginTop: 20,
},
signupText: {
fontWeight: 'bold',
color: 'blue',
},
name: {
fontWeight: 'bold',
color: '#561d98',
fontSize: 48,
},
slogin: {
fontWeight: 'bold',
color: '#815cac',
fontSize: 20,
},
inputPicker: {
width: '100%',
height: 40,
marginVertical: 10,
borderWidth: 1,
padding: 10,
borderRadius: 5,
justifyContent: 'center',
overflow: 'hidden',
},
picker: {
height: undefined,
backgroundColor: 'transparent',
justifyContent: 'center',
},
avatarPlaceholder: {
width: 120,
height: 135,
borderRadius: 65,
backgroundColor: '#cfb8ec',
justifyContent: 'center',
alignItems: 'center',
marginTop: 10,
},
avatarPlaceholderText: {
color: '#000',
textAlign: 'center',
},
avatar: {
width: 120,
height: 135,
borderRadius: 65,
backgroundColor: '#cfb8ec',
},
});
const pickerSelectStyles = StyleSheet.create({
inputIOS: {
fontSize: 16,
paddingVertical: 12,
color: 'black',
paddingRight: 30,
},
inputAndroid: {
fontSize: 16,
paddingVertical: 8,
color: 'black',
paddingRight: 30,
},
});
export default SignUp;
|
import PropTypes from 'prop-types';
import css from './FeedbackOptions.module.css';
export const FeedbackOptions = ({ onButtonAction }) => {
return (
<div className={css.buttonBox}>
<button
type="button"
className={css.good}
name="good"
onClick={onButtonAction}
>
Good
</button>
<button
type="button"
className={css.neutral}
name="neutral"
onClick={onButtonAction}
>
Neutral
</button>
<button
type="button"
className={css.bad}
name="bad"
onClick={onButtonAction}
>
Bad
</button>
</div>
);
};
FeedbackOptions.propTypes = {
onButtonAction: PropTypes.func.isRequired,
};
|
#!/usr/bin/python
#
# Copyright (c) 2018 Zim Kalinowski, <zikalino@microsoft.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_adhybridhealthserviceaddsservicesuserpreference_facts
version_added: "2.8"
short_description: Get Azure Adds Services User Preference facts.
description:
- Get facts of Azure Adds Services User Preference.
options:
service_name:
description:
- The name of the service.
required: True
name:
description:
- The name of the feature.
required: True
extends_documentation_fragment:
- azure
author:
- "Zim Kalinowski (@zikalino)"
'''
EXAMPLES = '''
- name: Get instance of Adds Services User Preference
azure_rm_adhybridhealthserviceaddsservicesuserpreference_facts:
service_name: service_name
name: feature_name
'''
RETURN = '''
adds_services_user_preference:
description: A list of dictionaries containing facts for Adds Services User Preference.
returned: always
type: complex
contains:
'''
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
from azure.mgmt.adhybridhealthservice import ADHybridHealthService
from msrest.serialization import Model
except ImportError:
# This is handled in azure_rm_common
pass
class AzureRMAddsServicesUserPreferenceFacts(AzureRMModuleBase):
def __init__(self):
# define user inputs into argument
self.module_arg_spec = dict(
service_name=dict(
type='str',
required=True
),
name=dict(
type='str',
required=True
)
)
# store the results of the module operation
self.results = dict(
changed=False
)
self.mgmt_client = None
self.service_name = None
self.name = None
super(AzureRMAddsServicesUserPreferenceFacts, self).__init__(self.module_arg_spec, supports_tags=False)
def exec_module(self, **kwargs):
for key in self.module_arg_spec:
setattr(self, key, kwargs[key])
self.mgmt_client = self.get_mgmt_svc_client(ADHybridHealthService,
base_url=self._cloud_environment.endpoints.resource_manager)
self.results['adds_services_user_preference'] = self.get()
return self.results
def get(self):
response = None
results = []
try:
response = self.mgmt_client.adds_services_user_preference.get(service_name=self.service_name,
feature_name=self.name)
self.log("Response : {0}".format(response))
except CloudError as e:
self.log('Could not get facts for Adds Services User Preference.')
if response is not None:
results.append(self.format_response(response))
return results
def format_response(self, item):
d = item.as_dict()
d = {
'resource_group': self.resource_group,
}
return d
def main():
AzureRMAddsServicesUserPreferenceFacts()
if __name__ == '__main__':
main()
|
import React from "react";
import { HiArrowNarrowRight } from "react-icons/hi";
import tableBG from "../../../assets/images/table-bg.png";
const PriceCard = ({ classCount, price, features, duration }) => {
const bg = {
backgroundImage: `url(${tableBG})`,
};
return (
<div
data-aos="fade-down"
data-aos-easing="linear"
data-aos-duration={duration}
className={`group bg-white hover:bg-slate-950 dark:bg-slate-900 p-10 flex flex-col justify-between hover:bg-priceCardBG dark:text-white `}
>
<div>
<div className="border-b pb-8">
<h3 className="text-xl uppercase font-semibold text-gray-700 dark:text-white group-hover:text-white">
{classCount} Class A Week
</h3>
<p className="text-gray-600 group-hover:text-white dark:text-white ">
Billed annually or ${parseInt(price / 12)} monthly
</p>
<h1 className="text-4xl text-slate-700 group-hover:text-white dark:text-white font-semibold ">
${price} /<span className="text-lg">Year</span>
</h1>
</div>
<ul className="my-8 space-y-3">{features}</ul>
</div>
<button className=" w-full text-white text-xl bg-violet-600 hover:bg-violet-700 hover:transition-all hover:duration-150 transition-all duration-300 flex items-center justify-center gap-2 py-2 group">
Enroll Now{" "}
<HiArrowNarrowRight className=" transition-all duration-300 " />
</button>
</div>
);
};
export default PriceCard;
|
import React, { useState } from "react";
import "./App.css";
function App() {
const [altura, setAltura] = useState("");
const [peso, setPeso] = useState("");
const [resultado, setResultado] = useState(null);
const calcularIMC = () => {
const alturaMetros = altura / 100; // Convertendo altura para metros
const imc = peso / (alturaMetros * alturaMetros);
setResultado(imc);
};
const getClassificacao = () => {
if (resultado < 18.5) {
return "Abaixo do peso";
} else if (resultado < 24.9) {
return "Peso normal";
} else if (resultado < 29.9) {
return "Sobrepeso";
} else if (resultado < 34.9) {
return "Obesidade Grau I";
} else if (resultado < 39.9) {
return "Obesidade Grau II";
} else {
return "Obesidade Grau III";
}
};
return (
<div className="App">
<h1>Calculadora de IMC</h1>
<div>
<label>Altura (cm):</label>
<input
type="number"
value={altura}
onChange={(e) => setAltura(e.target.value)}
/>
</div>
<div>
<label>Peso (kg):</label>
<input
type="number"
value={peso}
onChange={(e) => setPeso(e.target.value)}
/>
</div>
<button onClick={calcularIMC}>Calcular IMC</button>
{resultado && (
<div>
<h2>Seu IMC é: {resultado.toFixed(2)}</h2>
<p>Classificação: {getClassificacao()}</p>
</div>
)}
<div className="tabela-imc">
<h2>Tabela de Classificação de IMC</h2>
<table>
<thead>
<tr>
<th>IMC</th>
<th>Classificação</th>
</tr>
</thead>
<tbody>
<tr>
<td>< 18.5</td>
<td>Abaixo do peso</td>
</tr>
<tr>
<td>18.5 - 24.9</td>
<td>Peso normal</td>
</tr>
<tr>
<td>25.0 - 29.9</td>
<td>Sobrepeso</td>
</tr>
<tr>
<td>30.0 - 34.9</td>
<td>Obesidade Grau I</td>
</tr>
<tr>
<td>35.0 - 39.9</td>
<td>Obesidade Grau II</td>
</tr>
<tr>
<td>>= 40.0</td>
<td>Obesidade Grau III</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
export default App;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Start your development with Meyawo landing page.">
<meta name="author" content="Devcrud">
<title>JollyM Landing page | Free Bootstrap 4.3.x landing page</title>
<!-- font icons -->
<link rel="stylesheet" href="assets/vendors/themify-icons/css/themify-icons.css">
<!-- Bootstrap + Meyawo main styles -->
<link rel="stylesheet" href="assets/css/meyawo.css">
</head>
<body data-spy="scroll" data-target=".navbar" data-offset="40" id="home">
<!-- Page Navbar -->
<nav class="custom-navbar" data-spy="affix" data-offset-top="20">
<div class="container">
<a class="logo" href="#">JollyM</a>
<ul class="nav">
<li class="item">
<a class="link" href="#home">Home</a>
</li>
<li class="item">
<a class="link" href="#about">About</a>
</li>
<li class="item">
<a class="link" href="#portfolio">Portfolio</a>
</li>
<li class="item">
</li>
<li class="item">
<a class="link" href="#contact">Contact</a>
</li>
<li class="item ml-md-3">
<a href="components.html" class="btn btn-primary">Components</a>
</li>
</ul>
<a href="javascript:void(0)" id="nav-toggle" class="hamburger hamburger--elastic">
<div class="hamburger-box">
<div class="hamburger-inner"></div>
</div>
</a>
</div>
</nav><!-- End of Page Navbar -->
<!-- page header -->
<header id="home" class="header">
<div class="overlay"></div>
<div class="header-content container">
<h1 class="header-title">
<span class="up">HELLOW!</span>
<span class="down">I am THANDORH</span>
</h1>
<p class="header-subtitle">SOFTWARE DEVELOPER</p>
<button class="btn btn-primary">See My Works</button>
</div>
</header><!-- end of page header -->
<!-- about section -->
<section class="section pt-0" id="about">
<!-- container -->
<div class="container text-center">
<!-- about wrapper -->
<div class="about">
<div class="about-img-holder">
<img src="assets/imgs/NOTHANDOM.jpg" class="about-img" alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page">
</div>
<div class="about-caption">
<p class="section-subtitle">Who Am I ?</p>
<h2 class="section-title mb-3">About Me</h2>
<p>Welcome to my personal portfolio! i'm Nothando and i'm your software developer. Iam passionate at what am doing and love challenges because it pushes me outside my comfort zone and encourage personal growth.
<br> <p><h3 class="section-title mb-3">MY SKILLS</h3></p>
</p>
<P>HTML<br>
Css<br>
Project management<br>
Java script<br>
Python<br>
SQL
</P>
<button class="btn-rounded btn btn-outline-primary mt-4">Download CV</button>
</div>
</div><!-- end of about wrapper -->
</div><!-- end of container -->
</section> <!-- end of about section -->
<!-- service section -->
<section class="section" id="service">
<div class="container text-center">
<p class="section-subtitle">What I Do ?</p>
<h6 class="section-title mb-6">Service</h6>
<!-- row -->
<div class="row">
<div class="col-md-6 col-lg-3">
<div class="service-card">
<div class="body">
<img src="assets/imgs/productlisting.webp" alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page" class="icon">
<h6 class="title">PRODUCT LISTING</h6>
<p class="subtitle">Labore velit culpa adipisci excepturi consequuntur itaque in nam molestias dolorem iste quod.</p>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3">
<div class="service-card">
<div class="body">
<img src="assets/imgs/checklist.png" alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page" class="icon">
<h6 class="title">SHOPPING CART AND CHECKOUT</h6>
<p class="subtitle">Labore velit culpa adipisci excepturi consequuntur itaque in nam molestias dolorem iste quod.</p>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3">
<div class="service-card">
<div class="body">
<img src="assets/imgs/gateway.jpg" alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page" class="icon">
<h6 class="title">PAYMENT GATEWAY INTERGRATION</h6>
<p class="subtitle">Labore velit culpa adipisci excepturi consequuntur itaque in nam molestias dolorem iste quod.</p>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3">
<div class="service-card">
<div class="body">
<img src="assets/imgs/discounts.jpg" alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page" class="icon">
<h6 class="title">PROMOTIONS</h6>
<p class="subtitle">Labore velit culpa adipisci excepturi consequuntur itaque in nam molestias dolorem iste quod.</p>
</div>
</div>
</div>
</div><!-- end of row -->
</div>
</section><!-- end of service section -->
<!-- portfolio section -->
<section class="section" id="portfolio">
<div class="container text-center">
<p class="section-subtitle">What I Did ?</p>
<h6 class="section-title mb-6">Portfolio</h6>
<!-- row -->
<div class="row">
<div class="col-md-4">
<a href="#" class="portfolio-card">
<img src="assets/imgs/online.jpg" class="portfolio-card-img" alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page">
<span class="portfolio-card-overlay">
<span class="portfolio-card-caption">
<h4>system developer</h5>
<p class="font-weight-normal">Category: Web Templates</p>
</span>
</span>
</a>
</div>
<div class="col-md-4">
<a href="#" class="portfolio-card">
<img class="portfolio-card-img" src="assets/imgs/websites.jpg" class="img-responsive rounded" alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page">
<span class="portfolio-card-overlay">
<span class="portfolio-card-caption">
<h4>system developer</h5>
<p class="font-weight-normal">Category: Web Templates</p>
</span>
</span>
</a>
</div>
<div class="col-md-4">
<a href="#" class="portfolio-card">
<img class="portfolio-card-img" src="assets/imgs/delivery.jpg" class="img-responsive rounded" alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page">
<span class="portfolio-card-overlay">
<span class="portfolio-card-caption">
<h4>system developer</h5>
<p class="font-weight-normal">Category: Web Templates</p>
</span>
</span>
</a>
</div>
</div><!-- end of row -->
</div><!-- end of container -->
</section> <!-- end of portfolio section -->
<!-- section -->
<section class="section-sm bg-primary">
<!-- container -->
<div class="container text-center text-sm-left">
<!-- row -->
<div class="row align-items-center">
<div class="col-sm offset-md-1 mb-4 mb-md-0">
<h6 class="title text-light">Want to work with me?</h6>
<p class="m-0 text-light">Always feel Free to Contact & Hire me</p>
</div>
<div class="col-sm offset-sm-2 offset-md-3">
<button class="btn btn-lg my-font btn-light rounded">Hire Me</button>
</div>
</div> <!-- end of row -->
</div> <!-- end of container -->
</section> <!-- end of section -->
<!-- contact section -->
<section class="section" id="contact">
<div class="container text-center">
<p class="section-subtitle">How can you communicate?</p>
<h6 class="section-title mb-5">Contact Me</h6>
<!-- contact form -->
<form action="" class="contact-form col-md-10 col-lg-8 m-auto">
<div class="form-row">
<div class="form-group col-sm-6">
<input type="text" size="50" class="form-control" placeholder="Nothando Happiness Msomi" required>
</div>
<div class="form-group col-sm-6">
<input type="email" class="form-control" placeholder="tnothando182@gmail.com"requried>
</div>
<div class="form-group col-sm-12">
<textarea name="comment" id="comment" rows="6" class="form-control" placeholder="whether you have a question or you want to discuss a project or you simply want to say Hellow, i'm always happy to hear from you. feel free to reachout via email or connect with me on social media i am to respond to all inquiries promptly.
let connect and explore how wecan work together to achieve our goals! "></textarea>
</div>
<div class="form-group col-sm-12 mt-3">
<input type="submit" value="Send Message" class="btn btn-outline-primary rounded">
</div>
</div>
</form><!-- end of contact form -->
</div><!-- end of container -->
</section><!-- end of contact section -->
<!-- footer -->
<div class="container">
<footer class="footer">
<p class="mb-0">Designed by Thandorh <script>document.write(new Date().getFullYear())</script> © <a href="http://www.devcrud.com"></a></p>
<div class="social-links text-right m-auto ml-sm-auto">
<a href="javascript:void(0)" class="link"><i class="ti-facebook"></i></a>
<a href="javascript:void(0)" class="link"><i class="ti-twitter-alt"></i></a>
<a href="javascript:void(0)" class="link"><i class="ti-google"></i></a>
<a href="javascript:void(0)" class="link"><i class="ti-pinterest-alt"></i></a>
<a href="javascript:void(0)" class="https://instagram.com/nothando8198?igshid=MjEwN2lyYWYwyw=="><i class="ti-instagram"></i></a>
<a href="javascript:void(0)" class="link"><i class="ti-rss"></i></a>
</div>
</footer>
</div> <!-- end of page footer -->
<!-- core -->
<script src="assets/vendors/jquery/jquery-3.4.1.js"></script>
<script src="assets/vendors/bootstrap/bootstrap.bundle.js"></script>
<!-- bootstrap 3 affix -->
<script src="assets/vendors/bootstrap/bootstrap.affix.js"></script>
<!-- Meyawo js -->
<script src="assets/js/meyawo.js"></script>
</body>
</html>
|
import { setLimit } from '@store/accountQuerySlice';
import { setIsActive, setIsStaff, setPage, setSearch } from '@store/userQuerySlice';
import setQueryParams from '@utils/setQueryParams';
import { useDispatch } from 'react-redux';
function useUserQueryDispatch() {
const dispatch = useDispatch();
const dispatchIsActive = (isActive: string) => {
dispatch(setIsActive(isActive));
setQueryParams({ is_active: isActive });
};
const dispatchIsStaff = (isStaff: string) => {
dispatch(setIsStaff(isStaff));
setQueryParams({ is_staff: isStaff });
};
const dispatchPage = (page: number) => {
dispatch(setPage(page));
setQueryParams({ page });
};
const dispatchSearch = (search: string) => {
dispatch(setSearch(search.trim()));
setQueryParams({ search: search.trim() });
};
const dispatchLimit = (limit: number) => {
dispatch(setLimit(limit));
setQueryParams({ limit });
};
return { dispatchIsActive, dispatchIsStaff, dispatchPage, dispatchSearch, dispatchLimit };
}
export default useUserQueryDispatch;
|
# UF2 Seguretat en Serveis
Fecha: 24 de enero de 2024
Hecho: No
Asignatura: MP17 Seguretat en sistemes, xarxes i serveis (https://www.notion.so/MP17-Seguretat-en-sistemes-xarxes-i-serveis-a6a6996f62f94764936f4a9aea58316f?pvs=21)
Propietario: Examen
# Introducció a la seguretat en serveis
Els **atacs informàtics** solen constar de cinc fases:
1. **Reconeixement** → Recopolació per part de l’atacant, de la informació a comprometre → Recerques a internet i sniffing de la xarxa
2. **Escaneig →** Ús de la informació obtinguda per tal de buscar vulnerabilitats → Nmap i tracerroute
3. **Accés al sistema →** Fase efectiva de l’atac aprofitant les vulnerabilitats → Crackeig de contrasenyes
4. **Manteniment accés** → Intentar preservar la possibilitat d’accedir un altre cop en el futur → Malware per monitoritzar accions i codi maliciós
5. **Esborrat empremtes** → Esborrar les empremptes del que s’ha fet al sistema → Fitxers de registre i eborrar pistes de les possibles eines utilitzades
# Vulnerabilitats
Es necessari conèixer, emmagatzemar i gestionar les vulnerabilitats que es descobreixen per a:
- Comprovar ràpidament si es coneix alguna vulnerabilitat per alguna plataforma
- Identificar exploits a partir de les vulnerabilitats
## Gestió CPE
- Common Platform Enumeration
- Nom “estàndard” que s’assigna a un producte software, o sistema
- Permet identificar-lo de manera única
## Gestió CVE
- Common vulnerabilities and Exposures
- Identificador que s’assigna a una vulnerabilitat
- Llista d’entrades, on cadascun conté un nombre identificador, una descripció i almenys una referència pública
## Gestió CVSS
- Pretén identificar i avaluar les vulnerabilitats
- Intenta assignar puntuacions de severitat a vulnerabilitats, permetent prioritzar respostes i recursos segons l’amenaça
- La puntuació oscil·la de 0 a 10
- Es composa de tres grups principals: Base, Temporal i d’Entorn
## OpenVAS
- Eina que permet escanejar una infraestructura, detectar els serveis que ofereix i automatitzar la seva explotació
- Open source sita llicència GNU General Public License (GNU GPL)
### GVM
- Gestor de vulnerabilitat de Greenbone
- Servei central que consolida l’exploració de les vulnerabilitats en una solució completa de gestió de la vulnerabilitat
- El servei té un sistema d’execució intern per a tasques programades i altres esdeveniments
### Scanner
- És un motor d’escaneig de funcions completes que executa un feed actualitzat i ampliat contínuament
### GVM-Tools
- Complementari a la interfície web
- Format per clients interactius i no interactius
- Una col·lecció de scripts ofereix exemples per a casos típics d’ús
## Gestió NVD
- Disposa d’una base de dades amb totes les vulnerabilitats que han aparegut desde 2002
- Permet la consulta directa o bé descarregar totes les dades en format XML
- S’actualitza diàriament
---
# El servei DNS
## Introducció
- Domain Name System (DNS)
- Conté una base de dades dinàmica que associa direccions IP de hosts, serveis…
- Soporta ipv4 i ipv6
- Resource Records (RR), la informació es guarda en format de registres
- La informació s’agrupa en zones
- DNS tradueix direccions IP de recursos de xarxa a noms, i a l’inversa
- **Components principals que integren el DNS**
- **Espai de dominis de noms**
Estructura jeràrquica d’arbre on cada node té 0 o més registres (RR) amb la informació del domini
- **Servidor de noms**
Hi ha els servidor autoritzats de zona, i altres servidors que guarden conjunts de registres de diferents zones/dominis que obtenen consultant als servidors autoritatius
- **Resolvers**
Servidors caché o programes client que generen les consultes necessàries i obtenen la infomracion sol·licitada per oferir-la a qui la necessite
**Format genèric** d’un missatge de DNS:
| SECCIÓN | DESCRIPCIÓN |
| --- | --- |
| HEADER | Contiene información sobre el tipo de mensaje |
| QUESTION | Contiene una o más solicitudes de información que se envían al servidor DNS |
| ANSWER | Contiene uno o más registros que responden a las solicitudes |
| AUTHORITY | Contiene uno o más registros que apuntan al servidor autoritativo del dominio en cuestión |
| ADDITIONAL | Registro con información adicional no necesaria para responder a la query |
El **header d’un missatge DNS** consta de **16 bytes** que es divideixen en diversos camps
Les **transaccions DNS** més comunes son:
- **Consultes i respostes:** DNS (Queries)
- **Transferències de Zona:** Replicació de fitxers de zona entre servidors
- **Actualitzacions Dinàmiques:** Per actualitzar els fitxers de zona d’un servidor DNS
- **Notificacions:** Per part d’un servidor autoritatiu per notificar canvis de dades de zones
## Seguretat en el servei DNS. Anàlisi de vulnerabilitats
| Tipus d’atac | Amenaça | Contramesura |
| --- | --- | --- |
| Locals | Mesures i polítiques de seguretat en la xarxa interna | Mecanismes anti-spoofing, IDS/IPS. Protecció de l’accés als servidors
i arxius |
| Servidor-Servidor | Es centralitza
l’administració de les dades a través de DDNS | Utilitzar un canal
restringit de comunicació o implementar TSIG. |
| Servidor Master-Esclau | Transferències de zona | Xifratge amb una clau. Es pot utilitzar
també SSL/TLS. |
| Servidor Master-Client Caché/Resolver | Aleatorietat en el port
origen de la consulta, i en els identificadors de missatge | DNSSEC |
| Servidor-Client | Atacs locals per interceptar dades i spoofing per
suplantar al servidor DNS | DNSSEC |
Què fa que el servei DNS sigui insegur
- Utilitza **UDP** com a **protocol de transport →** Vulnerable a **IP Spoffing**
- Ús del servei DNS per executar atacs de **DoS,** utilitzant peticions DNS en les que la direccio IP origen s’ha substituït per la del servidor víctima per a que les respostes vagin dirigides a ell
- Atacs de **Man-in-the-Middle**
- La majoria d’atacs es basen en la **suplantació de les direccions IP**
- No utilitza **mecanismes bàsics com autentiticació, xifrat i/o integritat**
## Explotació de vulnerabilitats. Atacs a DNS.
### DNS cache poisoning
L'enverinament de la memòria DNS és una tècnica d'atac cibernètic que implica corrompre o inserir informació falsa a la memòria cache del DNS
En un atac de cache poisoning l'atacant busca manipular la informació emmagatzemada al cau del resolutor de DNS. L'objectiu és redirigir el trànsit legítim a llocs web o servidors maliciosos, permetent a l'atacant realitzar diverses activitats malicioses, que poden ser:
- **Enviant sol·licituds malicioses**
- **Actualitzant la memòria cau**
- **Redirigint el trànsit**
Es pot mitigar aquestos atacs amb aquestes contramesures:
- **ID de transacció aleatori**
- **DNSSEC**
- **Aleatorització del port d'origen**
- **Limitació de taxa**
### DNS spoofing
Consisteix en la suplantació del servidor DNS
Permet generar **respostes DNS des d’un servidor maliciós** per consultes DNS que anaven dirigides al servidor DNS legítim, de forma que es manipula el seu contingut
Usa **tècniques** de **Man-in-the-middle** o manipulació dels protocols d’enrutament dinàmic
Es pot mitigar aquestos atacs amb aquestes contramesures:
- **Verificació de Registre:** Han de tenir un mètoda de verificació per garantir l’autenticitat del sol·licitant
- **Fortificació del sistema d’autentificació:** Implementar polítiques i mecanismes de fiabilitat o per mitja de VPN o SSL
- **Multiplicitat de punts de contacte:** Tenir diversos contactes per proporcionar major seguretat sobre les accions a realitzar
- **Política de renovació:**
### DNS tunneling
Tunelització del tràfic dintre del protocol DNS
El objectiu és establir un canal de comunicacions per filtrar informació o per disposar del control remot dels recursos involucrats
### DoS DNS amplification attack
Atacs de denegació de serveis mitjançant amplificació DNS
S’utilitza el servei DNS per **atacar amb contínues respostes a un servidor víctima remot**
Es **suplanta** la direcció **IP origen del servidor víctima** (IP spoofing) des d’un resolver (client DNS) per **enviar moltes consultes o peticions a servidors DNS intermitjos públics**
Els resolvers envien les respostes al servidor víctima saturant l’ample de banda
|
<?php
namespace app\controllers;
use Yii;
use app\models\Scanlocation;
use app\models\ScanlocationSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* ScanlocationController implements the CRUD actions for Scanlocation model.
*/
class ScanlocationController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Scanlocation models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new ScanlocationSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Scanlocation model.
* @param integer $scan_id
* @param string $scan_ip
* @return mixed
*/
public function actionView($scan_id, $scan_ip)
{
return $this->render('view', [
'model' => $this->findModel($scan_id, $scan_ip),
]);
}
/**
* Creates a new Scanlocation model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Scanlocation();
if ($model->load(Yii::$app->request->post())){
$model->last_update = date('Y-m-d H:i:s');
if($model->save()) {
Yii::$app->getSession()->setFlash('alert',[
'body'=>'เรียบร้อย! บันทึกข้อมูลเรียบร้อย...',
'options'=>['class'=>'alert-success']
]);
return $this->redirect(['create']);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Scanlocation model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $scan_id
* @param string $scan_ip
* @return mixed
*/
public function actionUpdate($scan_id, $scan_ip)
{
$model = $this->findModel($scan_id, $scan_ip);
if ($model->load(Yii::$app->request->post())){
//$model->last_update = date('Y-m-d H:i:s');
if($model->save()) {
Yii::$app->getSession()->setFlash('alert',[
'body'=>'เรียบร้อย! แก้ไขข้อมูลเรียบร้อย...',
'options'=>['class'=>'alert-success']
]);
return $this->redirect(['update','scan_id' => $model->scan_id, 'scan_ip' => $model->scan_ip]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Scanlocation model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $scan_id
* @param string $scan_ip
* @return mixed
*/
public function actionDelete($scan_id, $scan_ip)
{
$this->findModel($scan_id, $scan_ip)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Scanlocation model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $scan_id
* @param string $scan_ip
* @return Scanlocation the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($scan_id, $scan_ip)
{
if (($model = Scanlocation::findOne(['scan_id' => $scan_id, 'scan_ip' => $scan_ip])) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
|
# 音标
- 英 `/ɒd/`
- 美 `/ɑd/`
# 词义
adj. 奇数的;单只的
`a number that cannot be divided exactly by two, for example 1, 3, 5, 7 etc`
奇奇(odd)相加(add)为偶
# 同义
adj. [数]奇数的;古怪的;剩余的;临时的;零散的
`remaining` `extraordinary` `temporary` `surplus` `residual`
n. [数]奇数;怪人;奇特的事物
`put` `wack`
# 同根
- adj. `oddish` 有点怪的
- adv. `oddly` 古怪地;奇妙地;单数地
- n. `oddity` 奇异;古怪;怪癖
- n. `oddment` 零头;碎屑;零碎物件;奇特的东西
- n. `oddness` 奇怪;奇妙
# 短语
- `odd number` 奇数
- `odd couple` 出人意料互不相配的一对
- `at odd` 争执;奇数
- `odd one out` 剔除一个;格格不入
- `odd lot` 散股;零星交易
# 例句
The odd numbers are on the left as you walk up the street.
你沿这条街走时,单号在左边。
|
import 'dart:convert';
import 'package:airpay/src/constants/app.dart';
import 'package:airpay/src/models/user_model.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
class ProfileService{
static var _token;
static getToken() async{
final _storage = FlutterSecureStorage();
_token = await _storage.read(key: 'token');
}
static _headers() => {
'Accept' : 'application/json',
'Authorization': 'Bearer $_token'
};
static Future<User> fetchProfile() async{
await getToken();
final response = await http.get(
Uri.parse(AppConstant.url+'request/profile'),
headers: _headers()
);
if(response.statusCode == 200){
final res = new User.fromJson(jsonDecode(response.body));
return res;
}else {
throw Exception('Data not found');
}
}
}
|
package com.fantechs.common.base.general.entity.mes.sfc;
import cn.afterturn.easypoi.excel.annotation.Excel;
import com.alibaba.fastjson.annotation.JSONField;;
import com.fantechs.common.base.support.ValidGroup;;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 生产管理-产品包箱表
* mes_sfc_product_carton
* @author bgkun
* @date 2021-05-08 09:44:47
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "mes_sfc_product_carton")
public class MesSfcProductCarton extends ValidGroup implements Serializable {
/**
* 产品包箱表ID
*/
@ApiModelProperty(name="productCartonId",value = "产品包箱表ID")
@Excel(name = "产品包箱表ID", height = 20, width = 30,orderNum="")
@Id
@Column(name = "product_carton_id")
private Long productCartonId;
/**
* 包箱号
*/
@ApiModelProperty(name="cartonCode",value = "包箱号")
@Excel(name = "包箱号", height = 20, width = 30,orderNum="")
@Column(name = "carton_code")
private String cartonCode;
/**
* 当前包装规格数量
*/
@ApiModelProperty(name="cartonCode",value = "当前包装规格数量")
@Excel(name = "当前包装规格数量", height = 20, width = 30,orderNum="")
@Column(name = "now_package_spec_qty")
private BigDecimal nowPackageSpecQty;
/**
* 工单ID
*/
@ApiModelProperty(name="workOrderId",value = "工单ID")
@Excel(name = "工单ID", height = 20, width = 30,orderNum="")
@Column(name = "work_order_id")
private Long workOrderId;
/**
* 产品ID
*/
@ApiModelProperty(name="materialId",value = "产品ID")
@Excel(name = "产品ID", height = 20, width = 30,orderNum="")
@Column(name = "material_id")
private Long materialId;
/**
* 工位ID
*/
@ApiModelProperty(name="stationId",value = "工位ID")
@Excel(name = "工位ID", height = 20, width = 30,orderNum="")
@Column(name = "station_id")
private Long stationId;
/**
* 关箱状态(0-未关闭 1-已关闭)
*/
@ApiModelProperty(name="closeStatus",value = "关箱状态(0-未关闭 1-已关闭)")
@Excel(name = "关箱状态(0-未关闭 1-已关闭)", height = 20, width = 30,orderNum="")
@Column(name = "close_status")
private Byte closeStatus;
/**
* 关箱人员ID
*/
@ApiModelProperty(name="closeCartonUserId",value = "关箱人员ID")
@Excel(name = "关箱人员ID", height = 20, width = 30,orderNum="")
@Column(name = "close_carton_user_id")
private Long closeCartonUserId;
/**
* 关箱人员时间
*/
@ApiModelProperty(name="closeCartonTime",value = "关箱人员时间")
@Excel(name = "关箱人员时间", height = 20, width = 30,orderNum="",exportFormat ="yyyy-MM-dd HH:mm:ss")
@JSONField(format ="yyyy-MM-dd HH:mm:ss")
@Column(name = "close_carton_time")
private Date closeCartonTime;
/**
* 备注
*/
@ApiModelProperty(name="remark",value = "备注")
@Excel(name = "备注", height = 20, width = 30,orderNum="")
private String remark;
/**
* 组织id
*/
@ApiModelProperty(name="orgId",value = "组织id")
@Excel(name = "组织id", height = 20, width = 30,orderNum="")
@Column(name = "org_id")
private Long orgId;
/**
* 创建人ID
*/
@ApiModelProperty(name="createUserId",value = "创建人ID")
@Excel(name = "创建人ID", height = 20, width = 30,orderNum="")
@Column(name = "create_user_id")
private Long createUserId;
/**
* 创建时间
*/
@ApiModelProperty(name="createTime",value = "创建时间")
@Excel(name = "创建时间", height = 20, width = 30,orderNum="",exportFormat ="yyyy-MM-dd HH:mm:ss")
@JSONField(format ="yyyy-MM-dd HH:mm:ss")
@Column(name = "create_time")
private Date createTime;
/**
* 修改人ID
*/
@ApiModelProperty(name="modifiedUserId",value = "修改人ID")
@Excel(name = "修改人ID", height = 20, width = 30,orderNum="")
@Column(name = "modified_user_id")
private Long modifiedUserId;
/**
* 修改时间
*/
@ApiModelProperty(name="modifiedTime",value = "修改时间")
@Excel(name = "修改时间", height = 20, width = 30,orderNum="",exportFormat ="yyyy-MM-dd HH:mm:ss")
@JSONField(format ="yyyy-MM-dd HH:mm:ss")
@Column(name = "modified_time")
private Date modifiedTime;
/**
* 逻辑删除(0、删除 1、正常)
*/
@ApiModelProperty(name="isDelete",value = "逻辑删除(0、删除 1、正常)")
@Excel(name = "逻辑删除(0、删除 1、正常)", height = 20, width = 30,orderNum="")
@Column(name = "is_delete")
private Byte isDelete;
private String option1;
private String option2;
private String option3;
private static final long serialVersionUID = 1L;
}
|
import numeral from 'numeral'
Vue.component('subscribe-button', {
props: {
// will get the channel of the current user
channel: {
type: Object,
required: true,
default: () => ([])
},
initialSubscriptions: {
type: Array,
required: true,
default: () => []
},
},
data: function () {
return {
subscriptions: this.initialSubscriptions
}
},
computed: {
subscribed() {
// If user not authenticated or the channel is for current logged user, then
// do not allow subscribe/unsubscribe
if (!__auth() || this.owner)
return false;
// The !! will return boolean
return !!this.subscription
},
owner() {
return !!(__auth() && this.channel.user_id === __auth().id);
},
subscription() {
if (!__auth())
return null;
return this.subscriptions.find(subscription => subscription.user_id === __auth().id)
},
count() {
// Format to million (1M), thousand (1K), ...
return numeral(this.subscriptions.length).format('0a')
}
},
methods: {
toggleSubscription() {
if (!__auth()) {
return alert('Please login to subscribe.')
}
if (this.owner) {
return alert('You cannot subscribe to your channel.')
}
if (this.subscribed) {
axios.delete(`/channels/${this.channel.id}/subscriptions/${this.subscription.id}`)
.then(() => {
this.subscriptions = this.subscriptions.filter(s => s.id !== this.subscription.id)
})
} else {
axios.post(`/channels/${this.channel.id}/subscriptions`)
.then(response => {
this.subscriptions = [
// ... will spread all of the existing data and add the new
...this.subscriptions,
response.data
]
})
}
}
}
});
|
const setDate = () => {
const dateDayElement = document.querySelector('.date-day');
const monthNameElement = document.getElementById('monthName');
const yearElement = document.querySelector('.date-month-year > span:last-of-type');
const nameOfDayElement = document.querySelector('.date-day-name');
let dayOfWeek = new Date().getDate();
const year = new Date().getFullYear();
const monthName = new Date().toLocaleDateString('en-en', { month: 'short' });
const dayName = new Date().toLocaleDateString('en-en', { weekday: 'long' });
if (dayOfWeek < 10) {
dayOfWeek = `0${dayOfWeek}`;
};
dateDayElement.innerText = dayOfWeek;
yearElement.innerText = year;
monthNameElement.innerText = monthName;
nameOfDayElement.innerText = dayName;
}
setDate();
let tasksList = [];
const toggleModal = () => {
const modalElement = document.querySelector('.modal-overlay');
modalElement.classList.toggle('hidden');
}
const displayModalBtnElement = document.querySelector('.add-task-btn');
displayModalBtnElement.addEventListener('click', toggleModal);
const closeBtnElement = document.querySelector('.close-modal-btn');
closeBtnElement.addEventListener('click', toggleModal);
const addTaskBtnContainer = document.querySelector('.add-task-btn-container');
const errorMessageParagraph = document.createElement('p');
const addTaskBtn = document.getElementById('addTask');
const setTaskCompleted = (taskId) =>{
tasksList = tasksList.map((task) =>{
if (task.id === taskId){
task.isCompleted = !task.isCompleted;
}
return task;
} )
}
const renderTask = (task) => {
// get element from HTML
const taskListElement = document.querySelector('.tasks-list');
// create element in JS
const taskContainer = document.createElement('div');
const taskContainerWithDelete = document.createElement('div');
const deleteBtnContainer = document.createElement('span');
const taskParagraph = document.createElement('p');
const checkBtn = document.createElement('button');
const checkIcon = document.createElement('i');
const deleteBtn = document.createElement('button');
const deleteIcon = document.createElement('i');
taskContainerWithDelete.classList.add('task-conteiner-with-delete');
deleteBtnContainer.classList.add('task-conteiner-with-delete-span');
taskContainer.classList.add('task-container');
deleteBtn.classList.add('delete-btn')
taskParagraph.classList.add('task-container');
checkBtn.classList.add('check-btn');
checkIcon.classList.add('fas', 'fa-check');
deleteIcon.classList.add('far', 'fa-trash-alt');
if (task.isCompleted){
taskContainer.classList.add('completed');
deleteBtnContainer.classList.add('completed');
}
checkBtn.addEventListener('click', () =>{
setTaskCompleted(task.id);
taskDatasetId = taskContainer.dataset.id;
taskDoneIndex = getIntexDoneTask(taskDatasetId);
arraymove(taskDoneIndex);
renderTasks();
})
taskParagraph.innerText = task.name;
taskContainer.setAttribute('data-id',task.id);
// created elements added to HTML
taskListElement.appendChild(taskContainerWithDelete);
taskContainerWithDelete.appendChild(deleteBtnContainer);
deleteBtnContainer.appendChild(deleteBtn);
deleteBtnContainer.appendChild(taskParagraph);
taskContainerWithDelete.appendChild(taskContainer);
// taskContainer.appendChild(taskParagraph);
taskContainer.appendChild(checkBtn);
checkBtn.appendChild(checkIcon);
deleteBtn.appendChild(deleteIcon);
// let taskDatasetId;
taskParagraph.addEventListener('focus',()=>{
deleteBtnContainer.classList.add('task-conteiner-with-delete-span:hover');
})
deleteBtn.addEventListener('click',()=>{
taskDatasetId = taskContainer.dataset.id;
deleteTask(taskDatasetId);
})
}
deleteTask = (taskId) => {
for(let i=0; i<tasksList.length; i++){
if(taskId === tasksList[i].id){
tasksList.splice(i,1);
}
}
renderTasks();
}
function arraymove(fromIndex) {
var element = tasksList[fromIndex];
tasksList.splice(fromIndex, 1);
tasksList.push(element);
}
function getIntexDoneTask(taskId){
for(let i=0; i<tasksList.length; i++){
if(taskId === tasksList[i].id){
return i;
}
}
}
const renderTasks = () => {
// to reset previous state
document.querySelector('.tasks-list').innerHTML = null
tasksList.forEach((task) => {
renderTask(task);
})
}
const validateTask = (taskName) => {
if (!taskName.trim()) {
return 'Task name is required'
}
if (taskName.length < 4) {
return 'Min 3 characters'
}
return;
}
const addTaskToModel = (taskInput) => {
const task = {
name: taskInput.value,
isCompleted: false,
id: Math.random().toString()
};
tasksList.unshift(task);
taskInput.value = '';
}
function addErrorMessage(message){
errorMessageParagraph.innerText = message;
addTaskBtn.before(errorMessageParagraph);
addTaskBtnContainer.classList.add('add-task-btn-container-error')
}
function clearErrorMessage(){
errorMessageParagraph.innerText = '';
}
let errParExists = false;
const addTaskBtnElement = document.getElementById('addTask');
addTaskBtnElement.addEventListener('click', () => {
const taskNameInputElement = document.getElementById('taskName');
if (validateTask(taskNameInputElement.value)) {
taskNameInputElement.classList.add('input-error');
let message = (validateTask(taskNameInputElement.value));
if((!errParExists) || (message!==errorMessageParagraph.innerText)){
addErrorMessage(message);
errParExists = true;
}
return;
}
addTaskToModel(taskNameInputElement);
renderTasks();
taskNameInputElement.classList.remove('input-error')
clearErrorMessage();
errParExists = false;
toggleModal();
})
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stddef.h>
#include <iostream>
#include <math.h>
typedef double MatrixItem;
class Matrix {
private:
size_t cols;
size_t rows;
MatrixItem *data;
public:
Matrix() : cols(0), rows(0), data(nullptr) {};
Matrix(const size_t cols, const size_t rows);
Matrix(const size_t cols, const size_t rows, const MatrixItem *values);
Matrix(Matrix& A);
Matrix(Matrix&& A);
~Matrix();
public:
void print();
public:
Matrix& operator=(const Matrix& A);
Matrix& operator=(Matrix&& A);
Matrix& operator+(const Matrix& A);
Matrix& operator-(const Matrix& A);
Matrix& operator*(const Matrix& A);
Matrix& transposition();
MatrixItem determinant();
Matrix& exponent();
Matrix& set_zero();
Matrix& set_one();
Matrix& operator*(const MatrixItem A);
};
class MatrixExeption : public std::exception {
private:
std::string msg;
public:
MatrixExeption(std::string msg) : msg{msg} {};
};
void print_determinant(const MatrixItem a)
{
printf("\nMatrix determinant = %4.2lf\n", a);
}
Matrix::Matrix(const size_t cols, const size_t rows)
: cols(cols), rows(rows)
{
if (rows >= SIZE_MAX / sizeof(MatrixItem) / cols)
throw MatrixExeption("too large object");
data = new MatrixItem[rows * cols];
}
Matrix::Matrix(const size_t cols, const size_t rows, const MatrixItem *values)
: cols(cols), rows(rows)
{
if (rows >= SIZE_MAX / sizeof(MatrixItem) / cols)
throw MatrixExeption("too large object");
data = new MatrixItem[rows * cols];
memcpy(data, values, rows * cols * sizeof(MatrixItem));
}
Matrix::~Matrix()
{
if (data != nullptr) {
delete[] data;
}
}
Matrix::Matrix(Matrix& A)
{
rows = A.rows;
cols = A.cols;
data = new MatrixItem[rows * cols];
memcpy(data, A.data, rows * cols * sizeof(MatrixItem));
}
Matrix::Matrix(Matrix&& A)
{
rows = A.rows;
cols = A.cols;
data = A.data;
A.rows = 0;
A.cols = 0;
A.data = nullptr;
}
void Matrix::print()
{
printf("\n");
for (size_t col = 0; col < rows; ++col) {
printf("[ ");
for (size_t row = 0; row < cols; ++row) {
printf(" %4.2f", data[row + col * cols ]);
}
printf("]\n");
}
}
// C = A
Matrix& Matrix::operator=(const Matrix& A)
{
if (&A == this) return *this;
delete[] data;
cols = A.cols;
rows = A.rows;
data = new MatrixItem[A.cols * A.rows];
memcpy(this->data, A.data, rows * cols * sizeof(MatrixItem));
return *this;
}
// C = A
Matrix& Matrix::operator=(Matrix&& A)
{
cols = A.cols;
rows = A.rows;
data = A.data;
A.rows = 0;
A.cols = 0;
A.data = nullptr;
return *this;
}
// C = A + B
Matrix& Matrix::operator+(const Matrix& A)
{
if (A.cols != this->cols || A.rows != this->rows)
throw MatrixExeption("Matrix A and B are not proportional");
Matrix *C = new Matrix(A.cols, A.rows);
for (size_t idx = 0; idx < A.cols * A.rows; ++idx)
C->data[idx] = A.data[idx] + this->data[idx];
return *C;
}
// C = A - B
Matrix& Matrix::operator-(const Matrix& A)
{
if (A.cols != this->cols || A.rows != this->rows)
throw MatrixExeption("Matrix A and B are not proportional");
Matrix *C = new Matrix(A.cols, A.rows);
for (size_t idx = 0; idx < A.cols * A.rows; ++idx)
C->data[idx] = A.data[idx] - this->data[idx];
return *C;
}
// C = A * B
Matrix& Matrix::operator*(const Matrix& A)
{
if (A.cols != this->rows)
throw MatrixExeption("The rows of the matrix A are not equal to the columns of matrix B");
Matrix *C = new Matrix(this->rows, A.cols);
for (size_t C_col = 0; C_col < this->rows; ++C_col) {
for (size_t C_row = 0; C_row < A.cols; ++C_row) {
C->data[C_row + C_col * A.cols] = 0;
for (size_t idx = 0; idx < this->cols; ++idx) {
C->data[C_row + C_col * A.cols] += this->data[idx + (C_col * this->cols)]
* A.data[idx * A.cols + C_row];
};
};
};
return *C;
}
Matrix& Matrix::operator*(const MatrixItem A)
{
Matrix *C = new Matrix(rows, cols);
for (unsigned int idx = 0; idx < cols * rows; ++idx)
C->data[idx] = this->data[idx] / A;
return *C;
}
// C = A^T
Matrix& Matrix::transposition()
{
Matrix *C = new Matrix(rows, cols);
for (size_t C_row = 0; C_row < cols; ++C_row) {
for (size_t C_col = 0; C_col < rows; ++C_col) {
C->data[C_col + C_row * rows] = data[C_col * cols + C_row];
};
};
return *C;
}
// C = |A| (A[1x1], A[2x2], A[3x3])
MatrixItem Matrix::determinant()
{
if (cols != rows)
throw MatrixExeption ("the numbers of columns and rows of the matrix do not match");
MatrixItem C;
switch (rows)
{
case 1:
C = data[0];
return C;
break;
case 2:
C = data[0] * data[3] - data[1] * data[2];
return C;
break;
case 3:
C =
+ data[0] * data[4] * data[8]
+ data[6] * data[1] * data[5]
+ data[3] * data[7] * data[2]
- data[2] * data[4] * data[6]
- data[5] * data[7] * data[0]
- data[3] * data[1] * data[8];
return C;
break;
default:
throw MatrixExeption ("valid matrix size 1x1, 2x2, 3x3") ;
break;
};
}
Matrix& Matrix::set_zero()
{
memset(this->data, 0, sizeof(MatrixItem) * rows * cols);
return *this;
}
Matrix& Matrix::set_one()
{
for (size_t idx = 0; idx < rows * cols; idx += cols + 1) this->data[idx] = 1;
return *this;
}
// C = e^A
Matrix& Matrix::exponent()
{
if (cols != rows)
throw MatrixExeption ("the numbers of columns znd rows of the matrix do not match");
Matrix *previous_step = new Matrix(rows, cols);
previous_step->set_zero();
previous_step->set_one();
previous_step->operator+(*this);
Matrix *exp = new Matrix(rows, cols);
for (unsigned int k = 2; k <= 5; ++k) {
*exp = (*previous_step * *this) * (MatrixItem)(1. / k);
memcpy(previous_step->data, exp->data, rows * cols * sizeof(MatrixItem));
};
return *previous_step;
}
int main () {
MatrixItem values[] = {24., 15., 2., 40.,
5., 7., 1., 33.,
21., 20., 51., 1.};
MatrixItem values2[] = {24., 15., 2.,
40., 5., 7.,
1., 33., 21.,
4., 13., 23.};
MatrixItem values3[] = {24., 15., 2.,
40., 5., 7.,
1., 33., 21.};
Matrix A(4, 3, values);
Matrix B(A);
Matrix C(4, 3);
Matrix D(4, 3);
Matrix E(3, 4, values2);
Matrix F(3, 3);
Matrix G(3, 4);
Matrix I(3, 3, values3);
MatrixItem a;
Matrix H(3, 3);
C = A + B;
D = A - B;
F = A * E;
G = A.transposition();
a = I.determinant();
H = I.exponent();
A.print();
B.print();
C.print();
D.print();
E.print();
F.print();
G.print();
I.print();
print_determinant(a);
H.print();
return 0;
}
|
//
// TopMenuView.swift
// SuperFarmer
//
// Created by Dominik Kowalewski on 30/11/2022.
//
import SwiftUI
struct TopMenuView: View {
@EnvironmentObject var model: GameModel
@State var openned = false
@State var help = false
@State var offset: CGFloat = 0
@State var endingOffset: CGFloat = 0
@State var startingY: CGFloat = UIScreen.main.bounds.height
var body: some View {
GeometryReader { geo in
ZStack {
//MARK: Background
RoundedRectangle(cornerRadius: 15)
.fill(model.game.lowSpec ? .ultraThickMaterial : .ultraThinMaterial)
.animation(.easeInOut(duration: 0.7), value: openned)
.ignoresSafeArea()
.frame(width: openned ? UIScreen.main.bounds.width : 45, height: openned ? UIScreen.main.bounds.height : 45)
.padding(openned ? 0 : 20)
.offset(x: openned ? 0 : -160, y: openned ? 0 : -350)
//MARK: Buttons
VStack (spacing: 20){
Text("Continue")
.font(.title2)
.bold()
.foregroundColor(.white)
.frame(width: 220, height: 40)
.background(.green)
.cornerRadius(20)
.shadow(radius: 10)
Text("Help")
.font(.title2)
.bold()
.foregroundColor(.white)
.frame(width: 220, height: 40)
.background(.orange)
.cornerRadius(20)
.shadow(radius: 10)
.onTapGesture {
help = true
}
Toggle("Low Spec Mode", isOn: $model.game.lowSpec)
.padding(.horizontal)
.bold()
.foregroundColor(.white)
.frame(width: 220, height: 40)
.background(.orange)
.cornerRadius(20)
.shadow(radius: 10)
Text("Exit")
.font(.title2)
.bold()
.foregroundColor(.white)
.frame(width: 220, height: 40)
.background(.red)
.cornerRadius(20)
.shadow(radius: 10)
.onTapGesture {
exit(0)
}
}
.opacity(openned ? 1 : 0)
.animation(!openned ? .easeInOut(duration: 0.2) : .easeInOut(duration: 0.5).delay(0.2), value: openned)
//MARK: Menu/Close Button
VStack {
RoundedRectangle(cornerRadius: 20)
.fill(openned ? .red : model.game.lowSpec ? .black : .white)
.frame(width: 30, height: 4)
.rotationEffect(Angle(degrees: openned ? -45 : 0))
.offset(x: openned ? -1 : 0, y: openned ? 6 : 0)
RoundedRectangle(cornerRadius: 20)
.fill(openned ? .red : model.game.lowSpec ? .black : .white)
.frame(width: 30, height: 4)
.rotationEffect(Angle(degrees: openned ? 45 : 0))
.offset(x: openned ? -1 : 0, y: openned ? -6 : 0)
}
.shadow(radius: 5)
.offset(x: openned ? 160 : -160, y: openned ? -400 : -350)
.animation(.easeInOut(duration: 0.7), value: openned)
.onTapGesture {
help = false
openned.toggle()
}
//MARK: Help Card
ZStack {
Rectangle()
.fill(.white)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height
- 90)
.ignoresSafeArea()
.shadow(radius: 10)
VStack (spacing: 10) {
Text("Swipe down to close")
.foregroundColor(.black)
.font(.caption)
.offset(y: -40)
.padding(.top, 80)
Text("How to play?")
.font(.title2)
.bold()
Text("Each round you can roll dices once and trade animals multiple times. If you finish your turn just click Next Round button.")
.multilineTextAlignment(.center)
.font(.caption)
Text("Goal of the game")
.font(.title2)
.bold()
Text("The goal of the game is to have all types of animals at your farm. You can collect them by rolling dices and trading. But be careful, fox 🦊 or wolf 🐺 can eat your animals😱")
.multilineTextAlignment(.center)
.font(.caption)
Text("How to collect animals?")
.font(.title2)
.bold()
Text("Hold more animals to collect them faster. After each roll of the dices you get as many drawn animals as you have pairs of them at your farm and on dices. For examle if you have 3 sheeps 🐑🐑🐑 and you roll a sheep 🐑, you will recieve 2 new sheeps 🐑🐑. Explanation: 🐑🐑🐑 from your farm + 🐑 from dice = 2 pairs in total.")
.multilineTextAlignment(.center)
.font(.caption)
Text("How to protect your animals?")
.font(.title2)
.bold()
Text("Small dog 🦮 will protect your farm from fox 🦊 atack. Big dog 🐕🦺 will protect your farm from wolf 🐺. You will see a shield next to your animal, which is protected. After fox or wolf attack, your dog will be automatically taken.")
.multilineTextAlignment(.center)
.font(.caption)
Spacer()
}
.padding()
}
.offset(y: startingY)
.offset(y: help ? offset-840 : offset)
.offset(y: endingOffset)
.gesture(
DragGesture()
.onChanged{ value in
offset = value.translation.height
}
.onEnded { value in
if offset < 150 {
endingOffset -= startingY
} else if endingOffset != 0 && offset > 150 {
endingOffset = 0
}
offset = 0
help = false
})
.animation(.spring(), value: help)
}
}
}
}
struct TopMenuView_Previews: PreviewProvider {
static var previews: some View {
TopMenuView()
}
}
|
---
title: readme.hcl reference
---
# `readme.hcl` reference
The configuration file is made up of several blocks
* Version
* Title
* Quickstart
* Examples
* Footer
## Version
This allows you to set the version of the module on release in the documentation
```terraform
version = "v1.0.0"
```
## Title
Allow you to omit the title or override it
```terraform
title {
enabled = true
override = ""
}
```
If you wish to override the title (So not pulling it from the action file) you can put it in the `override` section
## Quickstart
This section allows you to render a quickstart section at the top of the readme, allowing people to get on with their use very quickly.
This section is linking path to a file, based on the current directory of the command invocation
```terraform
quickstart {
path = "docs/quickstart.md"
}
```
## Examples
This section allows you to include multiple examples.
The end result is rendered in the `README.md` so you can use any markdown or HTML that your source control system will render
```terraform
examples {
example {
enabled = true
name = "Example 1"
path = "docs/example1.md"
}
}
```
??? tip "How to add multiple examples"
Just repeat the `example` sections
```hcl
examples {
example {
enabled = true
name = "Example 1"
path = "docs/example1.md"
}
example {
enabled = true
name = "Example 2"
path = "docs/example2.md"
}
}
```
## Footer
This section allows you to prepend stuff to the bottom of the file, like `Made By` or legal stuff
```terraform
footer {
footer_from = "docs/footer.md"
}
```
## Full Reference
```terraform
version = "v1.0.0"
title {
enabled = true
override = ""
}
quickstart {
path = "docs/quickstart.md"
}
examples {
example {
enabled = true
name = "Example 1"
path = "docs/example1.md"
}
}
footer {
footer_from = "docs/footer.md"
}
```
|
var userClickedPattern = [];
var gamePattern = [];
var buttonColors = ["red", "blue", "green", "yellow"];
var started = false;
var level = 0;
$(document).keypress(() => {
if (!started) {
$("h1").text("Level " + level);
nextSequence();
started = true;
}
});
$("h1").click(() => {
if (!started) {
$("h1").text("Level " + level);
nextSequence();
started = true;
}
});
$(".btn").click(function () {
var userChosenColour = $(this).attr("id");
userClickedPattern.push(userChosenColour);
playSound(userChosenColour);
animatePress(userChosenColour);
checkAnswer(userClickedPattern.length - 1);
});
function nextSequence() {
userClickedPattern = [];
level++;
$("h1").text("Level " + level);
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$("#" + randomChosenColor)
.fadeIn(100)
.fadeOut(100)
.fadeIn(100);
playSound(randomChosenColor);
}
function playSound(name) {
var audio = new Audio("./Assets/sounds/" + name + ".mp3");
audio.play();
}
function animatePress(currentColour) {
$("#" + currentColour).addClass("pressed");
setTimeout(() => {
$("#" + currentColour).removeClass("pressed");
}, 100);
}
function checkAnswer(currentLevel) {
if (userClickedPattern[currentLevel] === gamePattern[currentLevel]) {
if (userClickedPattern.length === gamePattern.length) {
setTimeout(() => {
nextSequence();
}, 1000);
}
} else {
playSound("wrong");
$("body").addClass("game-over");
$("h1").text("Game Over, Press Any Key or Click to Restart");
setTimeout(() => {
$("body").removeClass("game-over");
}, 200);
startOver();
}
}
function startOver() {
level = 0;
gamePattern = [];
started = false;
}
const date = new Date();
const year = date.getFullYear();
$("footer").text(`© ${year} Manisha Bose`);
|
%pip install pandas
%pip install sqlalchemy
import os
import pandas as pd
import psycopg2
import io
import csv
import json
import datetime
import decimal
import sqlalchemy
from sqlalchemy import create_engine, MetaData, inspect, event, text
from collections import deque
from queue import Queue
from collections import deque
import pandas as pd
# Database connection parameters
# Database connection parameters are now retrieved from environment variables
db_params = {
'host': os.getenv('DB_HOST5', 'partner-prod-temp.postgres.database.azure.com'),
'dbname': os.getenv('DB_NAME5', 'impactpartners'),
'user': os.getenv('DB_USER5', 'partnerproductionpsqlmanager@partner-prod-temp'),
'password': os.getenv('DB_PASSWORD5', 'uH1fSuHsnUnF44GD?5t/6zOQ'),
'port': int(os.getenv('DB_PORT', '5432')) # Default port number if not specified
}
def get_table_columns(engine, schema_name, table_name, excluded_columns):
"""
Retrieve column names for a given table excluding certain columns.
"""
query = sqlalchemy.text("""
SELECT column_name
FROM information_schema.columns
WHERE table_schema = :schema_name AND table_name = :table_name;
""")
with engine.connect() as conn:
result = conn.execute(query, {'schema_name': schema_name, 'table_name': table_name})
columns = [row[0] for row in result.fetchall() if row[0] not in excluded_columns]
return columns
def construct_select_clause(schema_name, table_name, columns):
"""
Construct a SELECT clause for a given table.
"""
return ', '.join([f'"{schema_name}"."{table_name}"."{col}"' for col in columns])
# Adjusted construct_join_query function to include previous joins and where clause
def construct_join_query(schema_name, starting_table, joined_table, starting_table_column, joined_table_column, key_value, previous_joins, where_clause):
"""
Construct a full JOIN query with all columns from the joined table, incorporating the schema name, previous joins, and where clause.
Ensure each table is only joined once.
"""
# Construct the new join condition
new_join_condition = f'LEFT JOIN \"{schema_name}\".\"{joined_table}\" ON \"{schema_name}\".\"{starting_table}\".\"{starting_table_column}\" = \"{schema_name}\".\"{joined_table}\".\"{joined_table_column}\"'
# Combine previous joins with the new join condition
combined_joins = f"{previous_joins} {new_join_condition}"
# Construct the full join query string
full_join_query_str = f"SELECT DISTINCT \"{schema_name}\".\"{joined_table}\".* FROM \"{schema_name}\".\"{starting_table}\" {combined_joins} {where_clause}"
return text(full_join_query_str)
# Establishing the connection
db_url = f"postgresql+psycopg2://{db_params['user']}:{db_params['password']}@{db_params['host']}:{db_params['port']}/{db_params['dbname']}"
engine = create_engine(db_url)
# Set the schema for this session
schema_name = os.getenv('DB_SCHEMA5', 'partner') # Retrieve schema name from environment variable
@event.listens_for(engine, "connect")
def set_search_path(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute(f"SET search_path TO {schema_name};")
cursor.close()
# Define a default JSON object for fields that are None
default_json = {} # Update this with a suitable default JSON object
empty_placeholder = "\\N" # Placeholder for empty fields in .dump file
with engine.connect() as conn:
print("Successfully connected to the database!")
conn.execute(text(f"SET search_path TO {schema_name};"))
def export_table_data(query, params, connections, common_dump_file_name, schema_name, table_name, export_format='text', export_path='/app/outputs', log_file_name='query_log.txt',tables_file='tables_log.txt', CHUNK_SIZE=10000):
if not os.path.exists(export_path):
os.makedirs(export_path)
log_file_path = os.path.join(export_path, log_file_name)
dump_file_path = os.path.join(export_path, f"{common_dump_file_name}.csv")
tables_file_path = os.path.join(export_path, tables_file)
with open(log_file_path, 'a', encoding='utf-8') as log_file:
# Convert the query object to a string
query_str = str(query)
param_value = repr(params['key_value']) if isinstance(params['key_value'], str) else str(params['key_value'])
query_str_with_params = query_str.replace(":key_value", param_value)
# Write the modified query to the log file
log_file.write(f"Table: {table_name}\n{query_str_with_params}\n")
with open(tables_file_path, 'a', encoding='utf-8') as tables_file:
# Write the modified query to the log file
tables_file.write(f"Table: {table_name}\n")
with engine.connect() as connection:
try:
first_chunk = True
print(f"running for table -> {table_name} chunks with params {params} ----the query {query}")
for chunk in pd.read_sql_query(query, connection, params=params, chunksize=CHUNK_SIZE):
if first_chunk:
# Write column names and COPY command only for the first chunk
column_names = '\t '.join(chunk.columns)
header_str = f"{schema_name}.{table_name}\n{column_names}\n" # Removed the closing parenthesis
first_chunk = False
else:
header_str = ''
chunk.dropna(how='all', inplace=True)
# Convert the DataFrame to a CSV formatted string
csv_string = chunk.to_csv(sep='\t', index=False, header=False)
# Append the header and CSV string to the dump file
with open(dump_file_path, 'a', encoding='utf-8') as dump_file:
dump_file.write(header_str + csv_string)
# # Write the end-of-data marker
with open(dump_file_path, 'a', encoding='utf-8') as dump_file:
dump_file.write("\n")
except Exception as e:
print(f"An error occurred: {e}")
print(f"Data appended to {dump_file_path} with query logged in {log_file_path}")
def generate_truncate_sql(export_path, related_tables):
truncate_file_path = os.path.join(export_path, "truncate_tables.sql")
with open(truncate_file_path, 'w', encoding='utf-8') as truncate_file:
for table in related_tables:
truncate_file.write(f"TRUNCATE TABLE {schema_name}.{table} restart identity cascade;\n")
print(f"Truncate script created at {truncate_file_path}")
def get_key_value(table, column, value, connection):
"""
Fetch the corresponding key value from a table based on a column and its value.
"""
query = f"SELECT {column} FROM {table} WHERE {column} = %s;"
with connection.cursor() as cur:
cur.execute(query, [value])
result = cur.fetchone()
return result[0] if result else None
# Usage example
common_dump_file_name = "brands_dump"
# Retrieve script parameters from environment variables
def get_related_tables2(engine, table_name, excluded_tables, excluded_columns):
related_tables = []
foreign_key_query = """
SELECT DISTINCT
tc.table_name AS primary_table,
kcu.column_name AS primary_column,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE
tc.constraint_type = 'FOREIGN KEY' AND
(tc.table_name = :current_table OR ccu.table_name = :current_table);
"""
with open("/app/outputs/get_related_tables_output.txt", "a") as file:
with engine.connect() as conn:
result = conn.execute(sqlalchemy.text(foreign_key_query), {'current_table': table_name})
rows = result.fetchall()
for row in rows:
file.write(f"Row: {row}\n") # Log each row
primary_table, primary_column, foreign_table_name, foreign_column = row
if primary_column in excluded_columns or foreign_column in excluded_columns:
continue
if primary_table == table_name and foreign_table_name not in excluded_tables:
related_tables.append((foreign_table_name, primary_column, foreign_column))
elif foreign_table_name == table_name and primary_table not in excluded_tables:
related_tables.append((primary_table, foreign_column, primary_column))
file.write(f"RETURNING : {related_tables}\n") # Log each row
return related_tables #dame na filaoume tse to column...tse sto traverse na ta filai swsta sto path.
#kai meta na kamoume ta left joins swsta san kinoumaste sto path sto combine
#return list(set(related_tables))
def bfs_traverse(engine,relationships_dict, start_table, schema_name, key_column, key_value, bfs_output_file, excluded_tables, excluded_columns):
if excluded_tables is None:
excluded_tables = set()
if excluded_columns is None:
excluded_columns = set()
queue = deque([(start_table, [])])
paths = {}
visited_paths = set() # Track visited paths to avoid cycles
with open(bfs_output_file, 'w') as file:
while queue:
current_table, path = queue.popleft()
# Create a new path to include the current table
new_path = path + [current_table]
# Skip if the path has been visited
path_tuple = tuple(new_path)
if path_tuple in visited_paths:
continue
# Add the new path to visited paths and paths dictionary
visited_paths.add(path_tuple)
paths.setdefault(current_table, []).append(new_path)
# Process related tables
for related_table_info in relationships_dict.get(current_table, []):
related_table, primary_column, foreign_column = related_table_info
# Check for exclusions
if related_table in excluded_tables or primary_column in excluded_columns or foreign_column in excluded_columns:
continue
# Build the join condition
join_condition = f'LEFT JOIN \"{schema_name}\".\"{related_table}\" ON \"{schema_name}\".\"{current_table}\".\"{primary_column}\" = \"{schema_name}\".\"{related_table}\".\"{foreign_column}\"'
# Append related table and join condition to the path and queue
queue.append((related_table, new_path + [(related_table, join_condition)]))
# Log the path for each table
file.write(f"Table: {current_table}, Path: {new_path}\n")
file.write(f"RETURNING PATHS : {paths}\n")
return paths
def combine_union_queries(engine,relationships_dict, start_table, start_table_key_column, key_value, schema_name, bfs_output_file, excluded_tables=None, excluded_columns=None):
paths = bfs_traverse(engine,relationships_dict, start_table, schema_name, start_table_key_column, key_value, bfs_output_file, excluded_tables, excluded_columns)
with open("/app/outputs/combine_union_queries_output.txt", "w") as file:
for table, table_paths in paths.items():
table_queries = []
for path in table_paths:
join_part = " ".join(path)
query = f"SELECT DISTINCT \"{schema_name}\".\"{table}\".* FROM \"{schema_name}\".\"{start_table}\" {join_part} WHERE \"{schema_name}\".\"{start_table}\".\"{start_table_key_column}\" = '{key_value}' AND \"{schema_name}\".\"{table}\".\"id\" IS NOT NULL"
table_queries.append(query)
final_query = " UNION ".join(table_queries) if len(table_queries) > 1 else table_queries[0]
# Execute the query and export the data
with engine.connect() as conn:
export_table_data(final_query, {'key_value': key_value}, conn, common_dump_file_name, schema_name, table, export_format='text')
# Logging
file.write(f"Table: {table}, Query: {final_query}\n")
#print(f"Table: {table}, Query: {final_query}\n")
db_params = {
'host': os.getenv('DB_HOST', 'default_host'),
'dbname': os.getenv('DB_NAME', 'default_db_name'),
'user': os.getenv('DB_USER', 'default_user'),
'password': os.getenv('DB_PASSWORD', 'default_password'),
'port': int(os.getenv('DB_PORT', '5432')) # Default port number if not specified
}
def extract_relationships():
relationships = []
foreign_key_query = """
SELECT DISTINCT
tc.table_name AS primary_table,
kcu.column_name AS primary_column,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE
tc.constraint_type = 'FOREIGN KEY';
"""
with engine.connect() as conn:
result = conn.execute(sqlalchemy.text(foreign_key_query))
for row in result:
primary_table = row[0] # primary_table
primary_column = row[1] # primary_column
foreign_table = row[2] # foreign_table_name
foreign_column = row[3] # foreign_column
relationships.append((primary_table, primary_column, foreign_table, foreign_column))
return relationships
def generate_relationships_dict(relationships):
relationships_dict = {}
for primary_table, primary_column, foreign_table, foreign_column in relationships:
if primary_table not in relationships_dict:
relationships_dict[primary_table] = []
relationships_dict[primary_table].append((foreign_table, primary_column, foreign_column))
return relationships_dict
def generate_sql_queries(relationships_dict, schema_name):
starting_table = os.getenv('STARTING_TABLE', 'tenant') # Default to 'tenant'
starting_key_column = os.getenv('STARTING_KEY_COLUMN', 'id') # Default to 'id'
# For 'key_value', handle different data types (string/int)
key_value_str = os.getenv('KEY_VALUE', 'default_value_for_key_value')
try:
key_value = int(key_value_str)
except ValueError:
key_value = key_value_str # Use the string value if it's not an integer
excluded_tables_str = os.getenv('EXCLUDED_TABLES', '')
excluded_tables = set(excluded_tables_str.split(',')) if excluded_tables_str else set()
excluded_columns = {'modified_by_id', 'created_by_id', 'symbol_id'}
def construct_query(table, path):
join_parts = []
current_table = starting_table
for rel_table, primary_col, foreign_col in path:
if rel_table in excluded_tables or foreign_col in excluded_columns or primary_col in excluded_columns:
continue
join_condition = f'LEFT JOIN "{schema_name}"."{rel_table}" ON "{schema_name}"."{current_table}"."{primary_col}" = "{schema_name}"."{rel_table}"."{foreign_col}"'
join_parts.append(join_condition)
current_table = rel_table
return f'SELECT DISTINCT "{schema_name}"."{table}".* FROM "{schema_name}"."{starting_table}" ' + ' '.join(join_parts) + f' WHERE "{schema_name}"."{starting_table}"."{starting_key_column}" = \'{key_value}\' AND "{schema_name}"."{table}"."id" IS NOT NULL'
def find_paths(start_table, target_table, visited, path):
if start_table == target_table:
yield path
return
if start_table in visited:
return
visited.add(start_table)
for related_table_info in relationships_dict.get(start_table, []):
for next_path in find_paths(related_table_info[0], target_table, visited.copy(), path + [related_table_info]):
yield next_path
queries = {}
for table in relationships_dict.keys():
if table not in excluded_tables:
paths = list(find_paths(starting_table, table, set(), []))
table_queries = [construct_query(table, path) for path in paths]
queries[table] = ' UNION '.join(table_queries) if len(table_queries) > 1 else (table_queries[0] if table_queries else None)
return queries
# Extract relationships from the database
relationships = extract_relationships()
# Generate the relationships dictionary
relationships_dict = generate_relationships_dict(relationships)
# Printing relationships_dict for demonstration
with open("/app/outputs/relationships.txt", "w") as file:
for table, connected_tables in relationships_dict.items():
file.write(f"{table}: {connected_tables}\n")
starting_table = os.getenv('STARTING_TABLE', 'default_value_for_starting_table')
starting_key_column = os.getenv('STARTING_KEY_COLUMN', 'default_value_for_starting_key_column')
# For 'key_value', handle different data types (string/int)
key_value_str = os.getenv('KEY_VALUE', 'default_value_for_key_value')
try:
key_value = int(key_value_str)
except ValueError:
key_value = key_value_str # Use the string value if it's not an integer
# Split the excluded tables into a list if they are provided as a comma-separated string
excluded_tables_str = os.getenv('EXCLUDED_TABLES', '')
excluded_tables = excluded_tables_str.split(',') if excluded_tables_str else []
excluded_columns = {'modified_by_id', 'created_by_id', 'symbol_id'}
# Global chunk size for data processing
CHUNK_SIZE = 10000 # You can adjust this value as needed
queries = generate_sql_queries(relationships_dict, schema_name)
#combine_union_queries(engine,relationships_dict, starting_table, starting_key_column, key_value, schema_name, '/app/outputs/bfs_output.txt', excluded_tables, excluded_columns)
with open("/app/outputs/queires.txt", "w") as file:
for table, query in queries.items():
if query:
file.write(f"Table: {table}, Query: {query}\n")
# Specify the file path where you want to save the output
#output_file_path = '/app/exports/related_tables_output.txt'
|
<script lang='ts'>
import { beforeUpdate, getContext, onMount } from 'svelte';
import type { Writable } from 'svelte/store';
import type { InventorySizesContext, InventorySlotsProps } from '../../lib/models';
import { sizeKey } from './Inventory.svelte';
import { deserialize, serialize } from '../../lib/utils/JsonUtil';
import { InventorySlotPropsSchema, InventorySlotsPropsSchema, MAX_SLOT_X, MAX_SLOT_Y } from '../../lib/models';
import Slot from './InventorySlotsSlot.svelte';
export let height: number = MAX_SLOT_Y;
export let data: string;
const { subscribe }: Writable<InventorySizesContext> = getContext<Writable<InventorySizesContext>>(sizeKey);
let size: number = 0;
let slots: ReadonlyArray<InventorySlotsProps> = [];
beforeUpdate(() => {
slots = deserialize(InventorySlotsPropsSchema)(data);
});
onMount(() => subscribe(({ slot }) => size = slot));
</script>
<svelte:options immutable />
<div class='container'>
<div
class='grid'
style='--size: {size}px; --width: {MAX_SLOT_X}; --height: {height};'
>
{#each slots as { id, data } (id)}
<Slot {size} data={serialize(InventorySlotPropsSchema)(data)} />
{/each}
</div>
</div>
<style lang='scss'>
.container {
background-color: rgba(23, 23, 23, .85);
backdrop-filter: blur(2px);
.grid {
$size: var(--size);
$width: var(--width);
$height: var(--height);
$border: 1px solid rgba(111, 111, 111, .4);
width: calc($width * $size);
height: calc($height * $size);
display: grid;
grid-template: repeat($height, $size) / repeat($width, $size);
}
}
</style>
|
import React from "react";
import "./App.css";
import { Routes, Route, Outlet, useLocation } from "react-router-dom";
import HomePage from "./pages/HomePage/HomePage";
import ProductsPage from "./pages/ProductsPage/ProductsPage";
import ContactPage from "./pages/ContactPage/ContactPage";
import CareersPage from "./pages/CareersPage/CareersPage";
import NewsPage from "./pages/NewsPage/NewsPage";
import ServicesPage from "./pages/ServicesPage/ServicesPage";
import DetailedProductPage from "./pages/DetailedProductPage/DetailedProductPage";
import NotFoundPage from "./pages/NotFoundPage/NotFoundPage";
import Header from "./components/Header/Header";
import Footer from "./components/Footer/Footer";
import DetailedCareerPage from "./pages/DetailedCareerPage/DetailedCareerPage";
import DetailedServicePage from "./pages/DetailedServicePage/DetailedServicePage";
import HomeDashboardPage from "./dashboard/pages/HomeDashboardPage/HomeDashboardPage";
const App = () => {
const location = useLocation();
const isDashboardRoute = location.pathname.startsWith("/dashboard");
return (
<div className="w-full absolute">
{!isDashboardRoute && <Header />}
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/products" element={<Outlet />}>
<Route index element={<ProductsPage />} />
<Route path=":id" element={<DetailedProductPage />} />
</Route>
<Route path="/contact" element={<ContactPage />} />
<Route path="/careers" element={<Outlet />}>
<Route index element={<CareersPage />} />
<Route path=":id" element={<DetailedCareerPage />} />
</Route>
<Route path="/services" element={<Outlet />}>
<Route index element={<ServicesPage />} />
<Route path=":id" element={<DetailedServicePage />} />
</Route>
<Route path="/news" element={<NewsPage />} />
<Route path="/dashboard" element={<Outlet />}>
<Route index element={<HomeDashboardPage />} />
</Route>
<Route path="*" element={<NotFoundPage />} />
</Routes>
{!isDashboardRoute && <Footer />}
</div>
);
};
export default App;
|
const router = require('express').Router();
const { User, Course } = require('../models/model');
const {JWT_password} = require('../config');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const z = require('zod');
const { verifyUser } = require('../middleware/users');
const userSchema = {
email: z.string().email(),
username: z.string().max(20),
password: z.string().min(8)
}
router.post('/signup', async (req, res) => {
const { email, username, password } = req.body;
try {
const parsedEmail = userSchema.email.parse(email);
const parsedUsername = userSchema.username.parse(username);
const parsedPassword = userSchema.password.parse(password);
if (!email || !username || !password) {
return res.status(400).json({ error: 'Please provide all required fields (email, username, password).' });
}
const existingEmail = await User.findOne({ email });
if (existingEmail) {
return res.status(400).json({ error: 'User with this email already exists.' });
}
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(400).json({ error: 'User with this username already exists.' });
}
// Hash the password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const newUser = new User({ email, username, password: hashedPassword });
await newUser.save();
// Generate JWT token
const token = jwt.sign({ userId: newUser._id, username: newUser.username }, JWT_password, { expiresIn: '1h' });
// localStorage.setItem('token', token);
console.log('User created successfully');
res.status(201).json({ message: 'User created successfully', token });
} catch (error) {
console.error('Error creating user:', error.message);
res.status(500).json({ error: error.message });
}
});
router.post('/signin' ,async (req, res, next) => {
// sign in logic and add the jwt token in the local storage
const {email , username , password} = req.body;
const parsedEmail = userSchema.email.parse(email)
const parsedUsername = userSchema.username.parse(username)
const parsedPassword = userSchema.password.parse(password)
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(parsedPassword, salt);
const existingEmail = User.findOne(email);
const existingUser = User.findOne(username);
if (existingEmail || existingUser){
const token = jwt.sign({ userId: email, username: username }, JWT_password, { expiresIn: '1h' });
// localStorage.setItem('token', token);
res.json({token : token});
}
})
router.get('/products',verifyUser , (req, res, next) => {
// add products logic
})
router.get('/products/:pid', (req, res, next) => {
// edit product logic
})
router.post('/add-cart', (req, res, next) => {
// add logic for
})
router.post('/purchase-course', (req, res, next) => {
// add purchase course logic for cart
})
router.get('/cart', (req, res, next) => {
// add get cart logic
})
router.get('/purchased-products', (req, res, next) => {
// add view purchased products in admin side logic
})
router.get('/view-profile', (req, res, next) => {
// add view profile data in admin side logic
})
module.exports = router;
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../controller/cart_controller.dart';
import '../../../core/constant/color.dart';
import 'buttoncart.dart';
import 'custombuttoncoupon.dart';
class BottomNavgationBarCart extends GetView<CartController> {
final String price;
final String discount;
final String shipping;
final String totalprice;
final TextEditingController controllercoupon;
final void Function()? onApplyCoupon;
const BottomNavgationBarCart(
{super.key,
required this.price,
required this.discount,
required this.shipping,
required this.totalprice,
required this.controllercoupon,
this.onApplyCoupon});
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
GetBuilder<CartController>(
builder: (controller) => controller.couponname == null
? Container(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Row(children: [
Expanded(
flex: 2,
child: TextFormField(
controller: controllercoupon,
decoration: const InputDecoration(
isDense: true,
contentPadding: EdgeInsets.symmetric(
vertical: 8, horizontal: 10),
hintText: "Coupon Code",
border: OutlineInputBorder()),
)),
const SizedBox(width: 5),
Expanded(
flex: 1,
child: CustomButtonCoupon(
textbutton: "apply",
onPressed: onApplyCoupon,
))
]))
: Text(
"Coupon Code ${controller.couponname!}",
style: const TextStyle(
color: AppColor.primaryColor,
fontWeight: FontWeight.bold),
)),
Container(
margin: const EdgeInsets.all(10),
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(color: AppColor.primaryColor, width: 1),
borderRadius: BorderRadius.circular(10)),
child: Column(children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: const Text("price", style: TextStyle(fontSize: 16))),
Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child:
Text("$price \$", style: const TextStyle(fontSize: 16)))
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child:
const Text("discount", style: TextStyle(fontSize: 16))),
Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Text("$discount ",
style: const TextStyle(fontSize: 16)))
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child:
const Text("shipping", style: TextStyle(fontSize: 16))),
Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Text("$shipping ",
style: const TextStyle(fontSize: 16)))
],
),
const Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: const Text("Total Price",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: AppColor.primaryColor))),
Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Text("$totalprice \$",
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: AppColor.primaryColor)))
],
),
]),
),
const SizedBox(height: 10),
CustomButtonCart(
textbutton: "Place Order",
onPressed: controller.goToPageCheckout,
)
],
);
}
}
|
import static java.lang.Integer.parseInt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
* [S1] 백준 13335 트럭
* 메모리 : 11988KB
* 시간 : 104ms
* 코드 길이 : 1393B
*
* @author 김민주
* @see <a href="https://www.acmicpc.net/problem/13335"/>
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
// 초기 다리 값
int n = parseInt(st.nextToken());
int w = parseInt(st.nextToken());
int L = parseInt(st.nextToken());
Queue<Integer> trucks = new LinkedList<>();
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
trucks.offer(parseInt(st.nextToken()));
}
Queue<Integer> bridge = new ArrayDeque<>();
// 다리의 길이만큼 미리 0으로 채워두기
for (int i = 0; i < w; i++) {
bridge.offer(0);
}
int time = 0;
int weight = 0;
// 한 번 반복할 때마다 단위시간 1증가
while (!bridge.isEmpty()) {
time++;
weight -= bridge.poll();
if (trucks.isEmpty())
continue;
// 새로운 트럭의 무게가 들어올 수 있다면 추가
if (weight + trucks.peek() <= L) {
weight += trucks.peek();
bridge.add(trucks.poll());
} else {
// 만약 새로운 트럭이 들어올 수 없다면 0 추가
bridge.add(0);
}
}
System.out.println(time);
}
}
|
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import sys
import os
import pdb
import argparse
import time
from collections import OrderedDict, defaultdict
import logging
from PIL import Image
from isc.io import write_hdf5_descriptors
import torch
import torchvision
import torchvision.transforms
from torch import nn
from torch.utils.data import Dataset
import faiss
import tempfile
import numpy as np
import h5py
import dino_vit
import mae_vit
def load_model(args):
if args.model == "dino_base_patch16":
model = dino_vit.__dict__['vit_base'](patch_size=args.patch_size, num_classes=0)
print(f"Model {args.model} {args.patch_size}x{args.patch_size} built.")
ckpt = torch.load(args.checkpoint, map_location=torch.device('cpu'))
model.load_state_dict(ckpt)
model.eval()
return model
if args.model == "mae_base_patch16":
model = mae_vit.__dict__['vit_base_patch16'](
num_classes=0,
drop_path_rate=0.0,
# global_pool=args.global_pool,
)
print(f"Model {args.model} {args.patch_size}x{args.patch_size} built.")
ckpt = torch.load(args.checkpoint, map_location=torch.device('cpu'))
model.load_state_dict(ckpt['model'])
model.eval()
return model
assert False
def gem_npy(x, p=3, eps=1e-6):
x = np.clip(x, a_min=eps, a_max=np.inf)
x = x ** p
x = x.mean(axis=0)
return x ** (1. / p)
class ImageList(Dataset):
def __init__(self, image_list, imsize=None, transform=None):
Dataset.__init__(self)
self.image_list = image_list
self.transform = transform
self.imsize = imsize
def __len__(self):
return len(self.image_list)
def __getitem__(self, i):
x = Image.open(self.image_list[i])
x = x.convert("RGB")
if self.imsize is not None:
x.thumbnail((self.imsize, self.imsize), Image.ANTIALIAS)
if self.transform is not None:
x = self.transform(x)
return x
def main():
parser = argparse.ArgumentParser()
def aa(*args, **kwargs):
group.add_argument(*args, **kwargs)
group = parser.add_argument_group('feature extraction options')
aa('--transpose', default=-1, type=int, help="one of the 7 PIL transpose options ")
aa('--train_pca', default=False, action="store_true", help="run PCA training")
aa('--pca_file', default="", help="File with PCA descriptors")
aa('--pca_dim', default=1500, type=int, help="output dimension for PCA")
aa('--device', default="cuda:0", help='pytroch device')
aa('--batch_size', default=64, type=int, help="max batch size to use for extraction")
aa('--num_workers', default=20, type=int, help="nb of dataloader workers")
group = parser.add_argument_group('model options')
aa('--model', default='dino_base_patch16', choices=['dino_base_patch16', 'mae_base_patch16'], help="model to use")
aa('--patch_size', default=16, type=int, help="patch size")
aa('--checkpoint', default='./models/dino_vitbase16_pretrain.pth', help='override default checkpoint')
aa('--GeM_p', default=7.0, type=float, help="Power used for GeM pooling")
aa('--scales', default="1.0", help="scale levels")
aa('--imsize', default=512, type=int, help="max image size at extraction time")
group = parser.add_argument_group('dataset options')
aa('--file_list', default="list_files/dev_queries", required=False, help="CSV file with image filenames")
aa('--image_dir', default="images/dev_queries", help="search image files in these directories")
aa('--n_train_pca', default=10000, type=int, help="nb of training vectors for the PCA")
aa('--i0', default=0, type=int, help="first image to process")
aa('--i1', default=-1, type=int, help="last image to process + 1")
group = parser.add_argument_group('output options')
aa('--o', default="/tmp/desc.hdf5", help="write trained features to this file")
args = parser.parse_args()
args.scales = [float(x) for x in args.scales.split(",")]
print("args=", args)
print("reading image names from", args.file_list)
if args.device == "cpu":
if 'Linux' in platform.platform():
os.system(
'echo hardware_image_description: '
'$( cat /proc/cpuinfo | grep ^"model name" | tail -1 ), '
'$( cat /proc/cpuinfo | grep ^processor | wc -l ) cores'
)
else:
print("hardware_image_description:", platform.machine(), "nb of threads:", args.nproc)
else:
print("hardware_image_description:", torch.cuda.get_device_name(0))
image_list = [l.strip() for l in open(args.file_list, "r")]
if args.i1 == -1:
args.i1 = len(image_list)
image_list = image_list[args.i0:args.i1]
# add jpg suffix if there is none
image_list = [
fname if "." in fname else fname + ".jpg"
for fname in image_list
]
# full path name for the image
image_dir = args.image_dir
if not image_dir.endswith('/'):
image_dir += "/"
image_list = [image_dir + fname for fname in image_list]
print(f" found {len(image_list)} images")
if args.train_pca:
rs = np.random.RandomState(123)
image_list = [
image_list[i]
for i in rs.choice(len(image_list), size=args.n_train_pca, replace=False)
]
print(f"subsampled {args.n_train_pca} vectors")
# transform without resizing
mean, std = [0.485, 0.456, 0.406],[0.229, 0.224, 0.225]
transforms = [
torchvision.transforms.Resize((224, 224)), #wilee 230405 추가
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean, std)
]
if args.transpose != -1:
transforms.insert(TransposeTransform(args.transpose), 0)
transforms = torchvision.transforms.Compose(transforms)
im_dataset = ImageList(image_list, transform=transforms, imsize=args.imsize)
print("loading model")
model = load_model(args)
args.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
if torch.cuda.device_count() > 1:
print(f'Using {torch.cuda.device_count()} GPUs')
model = nn.DataParallel(model)
model.to(args.device)
print("computing features")
t0 = time.time()
with torch.no_grad():
if args.batch_size == 1:
all_desc = []
for no, x in enumerate(im_dataset):
x = x.to(args.device)
print(f"im {no}/{len(im_dataset)} ", end="\r", flush=True)
x = x.unsqueeze(0)
feats = []
for s in args.scales:
xs = nn.functional.interpolate(x, scale_factor=s, mode='bilinear', align_corners=False)
feat = model(xs)
o = feat.cpu().numpy() # B, C, H, W
o = o[0].reshape(o.shape[1], -1).T
feats.append(o)
feats = np.vstack(feats)
gem = gem_npy(feats, p=args.GeM_p)
all_desc.append(gem)
else:
all_desc = [None] * len(im_dataset)
ndesc = [0]
buckets = defaultdict(list)
def handle_bucket(bucket):
ndesc[0] += len(bucket)
x = torch.stack([xi for no, xi in bucket])
x = x.to(args.device)
print(f"ndesc {ndesc[0]} / {len(all_desc)} handle bucket of shape {x.shape}\r", end="", flush=True)
# print(f'input.shape is {x.shape}\n')
feats = []
for s in args.scales:
xs = nn.functional.interpolate(x, scale_factor=s, mode='bilinear', align_corners=False)
if args.model == "dino_base_patch16":
feat = model(xs)
elif args.model == "mae_base_patch16":
feat = model.module.forward_features(xs)
# print(f'feat.shape is {feat.shape}\n')
o = feat.cpu().numpy() # B, C, H, W
feats.append(o)
for i, (no, _) in enumerate(bucket):
feats_i = np.vstack([f[i].reshape(f[i].shape[0], -1).T for f in feats])
gem = gem_npy(feats_i, p=args.GeM_p)
all_desc[no] = gem
max_batch_size = args.batch_size
dataloader = torch.utils.data.DataLoader(
im_dataset, batch_size=1, shuffle=False,
num_workers=args.num_workers
)
for no, x in enumerate(dataloader):
x = x[0] # don't batch
buckets[x.shape].append((no, x))
if len(buckets[x.shape]) >= max_batch_size:
handle_bucket(buckets[x.shape])
del buckets[x.shape]
for bucket in buckets.values():
handle_bucket(bucket)
all_desc = np.vstack(all_desc)
t1 = time.time()
print()
print(f"image_description_time: {(t1 - t0) / len(image_list):.5f} s per image")
if args.train_pca:
d = all_desc.shape[1]
pca = faiss.PCAMatrix(d, args.pca_dim, -0.5)
print(f"Train PCA {pca.d_in} -> {pca.d_out}")
pca.train(all_desc)
print(f"Storing PCA to {args.pca_file}")
faiss.write_VectorTransform(pca, args.pca_file)
elif args.pca_file:
print("Load PCA matrix", args.pca_file)
pca = faiss.read_VectorTransform(args.pca_file)
print(f"Apply PCA {pca.d_in} -> {pca.d_out}")
all_desc = pca.apply_py(all_desc)
print("normalizing descriptors")
faiss.normalize_L2(all_desc)
if not args.train_pca:
print(f"writing descriptors to {args.o}")
write_hdf5_descriptors(all_desc, image_list, args.o)
if __name__ == "__main__":
main()
|
import * as React from 'react';
import clsx from 'clsx';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import { withStyles } from '@material-ui/core/styles';
import PenIcon from '../svg-icons/Pen';
import CalendarIcon from '../svg-icons/Calendar';
import ClockIcon from '../svg-icons/Clock';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
export var styles = function styles(theme) {
return {
root: {
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
justifyContent: 'space-between',
padding: theme.spacing(2, 3)
},
toolbarLandscape: {
height: 'auto',
maxWidth: 160,
padding: 16,
justifyContent: 'flex-start',
flexWrap: 'wrap'
},
dateTitleContainer: {
flex: 1
}
};
};
var _ref = /*#__PURE__*/_jsx(ClockIcon, {
color: "inherit"
});
var _ref2 = /*#__PURE__*/_jsx(CalendarIcon, {
color: "inherit"
});
var getViewTypeIcon = function getViewTypeIcon(viewType) {
return viewType === 'clock' ? _ref : _ref2;
};
function defaultGetKeyboardInputSwitchingButtonText(isKeyboardInputOpen, viewType) {
return isKeyboardInputOpen ? "text input view is open, go to ".concat(viewType, " view") : "".concat(viewType, " view is open, go to text input view");
}
var _ref3 = /*#__PURE__*/_jsx(PenIcon, {
color: "inherit"
});
var PickerToolbar = function PickerToolbar(props) {
var children = props.children,
classes = props.classes,
className = props.className,
_props$getMobileKeybo = props.getMobileKeyboardInputViewButtonText,
getMobileKeyboardInputViewButtonText = _props$getMobileKeybo === void 0 ? defaultGetKeyboardInputSwitchingButtonText : _props$getMobileKeybo,
isLandscape = props.isLandscape,
isMobileKeyboardViewOpen = props.isMobileKeyboardViewOpen,
_props$landscapeDirec = props.landscapeDirection,
landscapeDirection = _props$landscapeDirec === void 0 ? 'column' : _props$landscapeDirec,
penIconClassName = props.penIconClassName,
toggleMobileKeyboardView = props.toggleMobileKeyboardView,
toolbarTitle = props.toolbarTitle,
_props$viewType = props.viewType,
viewType = _props$viewType === void 0 ? 'calendar' : _props$viewType;
return /*#__PURE__*/_jsxs("div", {
className: clsx(classes.root, className, isLandscape && classes.toolbarLandscape),
children: [/*#__PURE__*/_jsx(Typography, {
color: "textSecondary",
variant: "overline",
children: toolbarTitle
}), /*#__PURE__*/_jsxs(Grid, {
container: true,
justifyContent: "space-between",
className: classes.dateTitleContainer,
direction: isLandscape ? landscapeDirection : 'row',
alignItems: isLandscape ? 'flex-start' : 'flex-end',
children: [children, /*#__PURE__*/_jsx(IconButton, {
onClick: toggleMobileKeyboardView,
className: penIconClassName,
color: "inherit",
"aria-label": getMobileKeyboardInputViewButtonText(isMobileKeyboardViewOpen, viewType),
children: isMobileKeyboardViewOpen ? getViewTypeIcon(viewType) : _ref3
})]
})]
});
};
export default withStyles(styles, {
name: 'MuiPickersToolbar'
})(PickerToolbar);
|
import React, { useRef, useEffect, useState } from 'react'
import styles from '../styles/Auth.module.css'
const LogInBox = ({ isOpen, onClose }) => {
const modalRef = useRef(null);
const [isHidden, setIsHidden] = useState(true);
const [isAnimate, setIsAnimate] = useState(true);
const handleClose = () => {
setTimeout(() => setIsHidden(true));
setTimeout(() => setIsAnimate(true));
setTimeout(() => onClose(), 500);
};
useEffect(() => {
const handleClickOutside = (event) => {
if (modalRef.current && !modalRef.current.contains(event.target)) {
setTimeout(() => setIsHidden(true));
setTimeout(() => setIsAnimate(true));
setTimeout(() => onClose(), 500);
}
};
if (isOpen) {
setTimeout(() => setIsHidden(false));
setTimeout(() => setIsAnimate(false));
}
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [onClose]);
const authToken = () => {
const email = document.getElementById('inputEmail').value;
const password = document.getElementById('inputPassword').value;
if(email == 'dasha.bobrovich@gmail.com' && password == 'zxcursed'){
localStorage.setItem('authEmail', email);
onClose();
}
}
return (
<>
{isOpen && (
<div className={`${styles.container} ${isHidden ? styles.hidden : ''}`}>
<div ref={modalRef} className={`${styles.content} ${isAnimate ? styles.animate : ''}`}>
<button className={styles.close_button} onClick={handleClose}>CLOSE</button>
<div className={styles.main_content}>
<h2 className={styles.text}>LOG IN TO YOUR<br/>ACCOUNT</h2>
<input placeholder='Enter your email address' className={styles.input} id="inputEmail" />
<input placeholder='Enter your password' className={styles.input} type="password" id="inputPassword" />
<button className={styles.button} onClick={authToken}>CONTINUE</button>
</div>
<div className={styles.substrate}></div>
</div>
</div>
)}
</>
)
}
export default LogInBox;
|
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
#include <future>
#include <mutex>
#include <algorithm>
class Vehicle {
public:
Vehicle(int id) : id_(id) {}
int getID() const { return id_; }
private:
int id_;
};
class WaitingVehicles {
public:
WaitingVehicles() = default;
void printIDs() {
std::lock_guard<std::mutex> locker(mutex_);
for (auto& v : vehicles_) {
std::cout << "\tVehicle #" << v.getID() << " is now waiting in the queue\n";
}
}
void pushBack(Vehicle&& v) {
std::lock_guard<std::mutex> locker(mutex_);
std::cout << "\tVehicle #" << v.getID() << " will be added to the queue\n";
vehicles_.emplace_back(v);
// simulate some work
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
private:
std::vector<Vehicle> vehicles_;
std::mutex mutex_; // to protect the resource - vehicles_;
};
int main()
{
std::shared_ptr<WaitingVehicles> queue = std::make_shared<WaitingVehicles>();
// spawning threads
std::cout << "Spawning threads ..." << std::endl;
std::vector<std::future<void>> futrs;
for (int i = 0; i < 10; ++i) {
// create a new vehicle instance and move it into the queue
Vehicle v(i);
futrs.push_back(std::async(std::launch::async, &WaitingVehicles::pushBack, queue, std::move(v)));
}
// wait for finishing
std::for_each(futrs.begin(), futrs.end(), [](std::future<void>& futr){
futr.wait();
});
std::cout << "Collecting result ...\n";
queue->printIDs();
return 0;
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:c="http://java.sun.com/jsp/jstl/core">
<ui:component>
<header>
<nav class="navbar navbar-expand-lg navbar-dark bg-panda">
<h:link class="navbar-brand nav-link-white" value="PANDA" outcome="index" />
<div class="collapse navbar-collapse d-flex justify-content-between" id="navbarNav">
<ul class="navbar-nav">
</ul>
<c:choose>
<c:when test="#{session.getAttribute('role') == 'Admin'}">
<li class="nav-item">
<a class="nav-link nav-link-white active" href="/pending">Pending</a>
</li>
<li class="nav-item">
<a class="nav-link nav-link-white active" href="/shipped">Shipped</a>
</li>
<li class="nav-item">
<a class="nav-link nav-link-white active" href="/delivered">Delivered</a>
</li>
<li class="nav-item">
<h:link class="nav-link nav-link-white active" outcome="create-package"
value="Package"/>
</li>
</c:when>
</c:choose>
<ul class="navbar-nav">
<li class="nav-item">
<h:link class="nav-link nav-link-white active" value="Home" outcome="index"/>
</li>
<c:choose>
<c:when test="#{session.getAttribute('username') == null}">
<li class="nav-item">
<h:link class="nav-link nav-link-white active" value="Login" outcome="login"/>
</li>
<li class="nav-item">
<h:link class="nav-link nav-link-white active" value="Register" outcome="register"/>
</li>
</c:when>
<c:otherwise>
<li class="nav-item">
<a class="nav-link nav-link-white active" href="/my-receipts">Receipts</a>
</li>
<li class="nav-item">
<h:form>
<h:commandButton class="nav-link nav-link-white active" action="#{userLogoutBean.logout}" value="Logout"/>
</h:form>
</li>
</c:otherwise>
</c:choose>
</ul>
</div>
</nav>
</header>
</ui:component>
</html>
|
# -*- coding:utf-8 -*-
# Copyright xmuspeech (Author: Leo 2023-04-11)
# modified from Lightning-AI
# https://github.com/Lightning-AI/lightning/blob/master/src/lightning/pytorch/cli.py
import inspect
import os
from typing import List, Type, Union, cast
from jsonargparse import Namespace
from lightning.fabric.utilities.cloud_io import get_filesystem
from lightning.pytorch import Callback, LightningDataModule, LightningModule, Trainer
from lightning.pytorch.utilities.model_helpers import is_overridden
from egrecho.core.parser import CommonParser
from egrecho.utils.constants import DEFAULT_TRAIN_FILENAME
class LightningParser(CommonParser):
"""
A convenient argument parser for pytorch lighting:
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_cfg_flag()
self.callback_keys: List[str] = []
self.trainer_class = None
def add_pl_module_args(
self,
pl_class: Union[
Type[LightningModule], Type[LightningDataModule], Type[Callback]
],
nested_key: str,
subclass_mode: bool = False,
**kwargs,
):
"""Adds pl module {LightningModule, LightningDataModule, Callback} arguments.
Args:
pl_class: Subclass of {LightningModule, LightningDataModule, Callback}.
nested_key: Name of the nested namespace to store arguments.
subclass_mode: Whether allow any subclass of the given class.
"""
if pl_class is None:
return
if inspect.isclass(pl_class) and issubclass(
cast(type, pl_class),
(LightningModule, LightningDataModule, Callback),
):
if issubclass(cast(type, pl_class), Callback):
self.callback_keys.append(nested_key)
return self.add_class_args(
pl_class, nested_key, subclass_mode=subclass_mode, **kwargs
)
raise TypeError(
f"Cannot add arguments from: {pl_class}. You should provide either a callable or a subclass of: "
"LightningModule, LightningDataModule, or Callback."
)
def add_trainer_args(
self,
pl_trainer_class: Type[Trainer] = Trainer,
nested_key: str = "trainer",
**kwargs,
):
"""Adds pl trainer arguments.
Args:
pl_trainer_class: class of lightning trainer.
nested_key: Name of the nested namespace to store arguments.
"""
self.trainer_class = pl_trainer_class
return self.add_class_arguments(
pl_trainer_class,
nested_key,
fail_untyped=False,
instantiate=False,
**kwargs,
)
class SaveConfigCallback(Callback):
"""Saves a LightningCLI config to the log_dir when training starts.
Args:
parser: The parser object used to parse the configuration.
config: The parsed configuration that will be saved.
config_filename: Filename for the config file.
overwrite: Whether to overwrite an existing config file.
skip_none: whether skip null while saving.
multifile: When input is multiple config files, saved config preserves this structure.
save_to_log_dir: Whether to save the config to the log_dir.
Raises:
RuntimeError: If the config file already exists in the directory to avoid overwriting a previous run
"""
def __init__(
self,
parser: CommonParser,
config: Namespace,
config_filename: str = DEFAULT_TRAIN_FILENAME,
overwrite: bool = True,
skip_none: bool = True,
multifile: bool = False,
save_to_log_dir: bool = True,
) -> None:
self.parser = parser
self.config = config
self.config_filename = config_filename
self.overwrite = overwrite
self.skip_none = skip_none
self.multifile = multifile
self.save_to_log_dir = save_to_log_dir
self.already_saved = False
if not save_to_log_dir and not is_overridden(
"save_config", self, SaveConfigCallback
):
raise ValueError(
"`save_to_log_dir=False` only makes sense when subclassing SaveConfigCallback to implement "
"`save_config` and it is desired to disable the standard behavior of saving to log_dir."
)
def setup(self, trainer: Trainer, pl_module: LightningModule, stage: str) -> None:
if self.already_saved:
return
if self.save_to_log_dir:
log_dir = trainer.log_dir # this broadcasts the directory
assert log_dir is not None
config_path = os.path.join(log_dir, self.config_filename)
fs = get_filesystem(log_dir)
if not self.overwrite:
# check if the file exists on rank 0
file_exists = (
fs.isfile(config_path) if trainer.is_global_zero else False
)
# broadcast whether to fail to all ranks
file_exists = trainer.strategy.broadcast(file_exists)
if file_exists:
raise RuntimeError(
f"{self.__class__.__name__} expected {config_path} to NOT exist. Aborting to avoid overwriting"
" results of a previous run. You can delete the previous config file,"
" set `overwrite=True` to to overwrite the config file."
)
if trainer.is_global_zero:
# save only on rank zero to avoid race conditions.
# the `log_dir` needs to be created as we rely on the logger to do it usually
# but it hasn't logged anything at this point
fs.makedirs(log_dir, exist_ok=True)
self.parser.save(
self.config,
config_path,
skip_none=self.skip_none,
overwrite=self.overwrite,
multifile=self.multifile,
)
if trainer.is_global_zero:
self.save_config(trainer, pl_module, stage)
self.already_saved = True
# broadcast so that all ranks are in sync on future calls to .setup()
self.already_saved = trainer.strategy.broadcast(self.already_saved)
def save_config(
self, trainer: Trainer, pl_module: LightningModule, stage: str
) -> None:
"""Implement to save the config in some other place additional to the standard log_dir.
Example:
def save_config(self, trainer, pl_module, stage):
if isinstance(trainer.logger, Logger):
config = self.parser.dump(self.config, skip_none=False) # Required for proper reproducibility
trainer.logger.log_hyperparams({"config": config})
Note:
This method is only called on rank zero. This allows to implement a custom save config without having to
worry about ranks or race conditions. Since it only runs on rank zero, any collective call will make the
process hang waiting for a broadcast. If you need to make collective calls, implement the setup method
instead.
"""
|
"use client";
import React, { useContext, useState } from "react";
import Link from "next/link";
import AnimatedComponent from "@/components/AnimatedComponent";
import { motion } from "framer-motion";
import { signInWithGoogle } from "@/services/authServices";
import { UserAuthContext } from "@/context/UserAuthContext";
import { message } from "antd";
import { signInWithEmailAndPassword } from "firebase/auth";
import { auth } from "@/firebase/config";
import { IUser } from "@/interface/IUser";
import { userInfo } from "os";
function Login() {
const { setUser } = useContext(UserAuthContext);
const [messageApi, contextHolder] = message.useMessage();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
// Sign in with google email account
const handleGoogleSignIn = () => {
signInWithGoogle()
.then((userInfo) => {
console.clear();
// const currentUser = {
// uid: userInfo.user.uid,
// displayName: userInfo.user.displayName,
// photoURL: userInfo.user.photoURL,
// };
success("User successfully login!");
setUser(userInfo.user);
})
.catch((err) => {
error(err);
});
};
// Sign in with email and password
const handleSignin = () => {
console.log(email, password);
signInWithEmailAndPassword(auth, email, password)
.then((userCred) => {
// const currentUser: IUser = {
// uid: userCred.user.uid,
// displayName: userCred.user.displayName,
// photoURL: userCred.user.photoURL,
// };
success("User Sucessfully Login");
setUser(userCred.user);
})
.catch((err) => error(err.message));
};
// Antd error message
const error = (msg: string) => {
messageApi.open({
type: "error",
content: msg,
});
};
// Antd success message
const success = (msg: string) => {
messageApi.open({
type: "success",
content: msg,
});
};
return (
<div className="login flex h-[90vh] items-center mx-16">
{contextHolder}
<section className="w-[50%]">
<header className="text-center">
<AnimatedComponent>
<h1 className="text-3xl font-bold mb-3">Sign in</h1>
</AnimatedComponent>
<AnimatedComponent _delay={1.1}>
<p className="text-[#a4a3a3] font-extralight text-sm">
Lorem ipsum dolor sit amet consectetur adipisicing.
</p>
</AnimatedComponent>
</header>
{/* Google sign in */}
<AnimatedComponent _delay={1.2}>
<div
className="google-login border-[1px] w-[300px] mx-auto my-4 text-sm rounded-full py-2 flex justify-center"
onClick={handleGoogleSignIn}
>
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Google_%22G%22_logo.svg/768px-Google_%22G%22_logo.svg.png"
alt=""
width={20}
height={20}
/>
<span className="ml-3">Login with Google</span>
</div>
</AnimatedComponent>
{/* Hr */}
<AnimatedComponent _delay={1.3}>
<div className="hr flex items-center justify-center">
<div className="hr-line h-[1px] w-[210px] bg-[#eee]"></div>
<div className="mx-3">OR</div>
<div className="hr-line hr-line h-[1px] w-[210px] bg-[#eee]"></div>
</div>
</AnimatedComponent>
{/* Form */}
<form action={handleSignin} className="mx-auto w-[500px] py-4 mt-4">
<AnimatedComponent _delay={1.4}>
<label htmlFor="email" className="mb-2 block">
Email <span className="text-[red]">*</span>
</label>
<input
type="email"
placeholder="Enter your email"
className="block w-100 font-light border-[1px] w-[100%] py-3 px-4 rounded-full text-sm"
autoComplete="new-password"
onChange={(e) => setEmail(e.target.value)}
required
/>
</AnimatedComponent>
<AnimatedComponent _delay={1.5}>
<label htmlFor="Password" className="mb-2 block mt-4">
Password <span className="text-[red]">*</span>
</label>
<input
type="password"
placeholder="Enter your password"
className="block w-100 font-light border-[1px] w-[100%] py-3 px-4 rounded-full text-sm"
autoComplete="off"
onChange={(e) => setPassword(e.target.value)}
required
/>
</AnimatedComponent>
<AnimatedComponent _delay={1.6}>
<input
type="submit"
value={"Sign in"}
className="btn-primary rounded-full mt-6 w-[100%] hover:bg-[#333] cursor-pointer"
/>
</AnimatedComponent>
</form>
{/* <AnimatedComponent _delay={1.7}> */}
<div className="text-center text-sm mt-4">
Don't have an Account?{" "}
<Link href="signup" className="text-[blue]">
Sign up
</Link>
</div>
{/* </AnimatedComponent> */}
</section>
{/* Image */}
<motion.section
initial={{
transform: "scale(.7)",
opacity: 0,
}}
animate={{
transform: "scale(1)",
opacity: 1,
}}
transition={{
stiffness: 100,
delay: 2,
type: "spring",
}}
className="w-[50%] bg-cover bg-center h-[90%] rounded-2xl"
style={{
backgroundImage: `url(https://images.unsplash.com/photo-1501441858156-e505fb04bfbc?q=80&w=1000&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Mnx8d29tYW4lMjBzdW5nbGFzc2VzfGVufDB8fDB8fHww)`,
}}
></motion.section>
</div>
);
}
export default Login;
|
package client
import (
"github.com/sirupsen/logrus"
"gnp/pkg/message"
"gnp/pkg/util"
"net"
"sync"
)
type UDPTunnel struct {
*Tunnel
}
func NewUDPTunnel(tunnel *Tunnel) *UDPTunnel {
return &UDPTunnel{
Tunnel: tunnel,
}
}
func (t *UDPTunnel) NewTunnel() {
t.newTunnelConnF = t.newTunnelConn
t.newLocalConnF = t.newLocalConn
t.tunnelToUserF = t.tunnelToLocal
t.localToTunnelF = t.localToTunnel
t.process()
}
func (t *UDPTunnel) newTunnelConn() bool {
if t.ctlMsg.GetSessionID() == "" {
logrus.Errorf("[%s] sessionID is empty", t.ctlMsg.GetServiceID())
return false
}
tunnelConn, err := util.CreateDialUDP(net.JoinHostPort(t.Config.ServerHost, t.ctlMsg.GetService().GetProxyPort()))
if err != nil {
logrus.Errorf("[%s] tunnel conn connect %v", t.ctlMsg.GetServiceID(), err)
return false
}
t.tunnelConn = tunnelConn
msg := &message.ControlMessage{
Ctl: message.NewTunnel,
Service: t.ctlMsg.GetService(),
ServiceID: t.ctlMsg.GetServiceID(),
SessionID: t.ctlMsg.GetSessionID(),
Token: t.ctlMsg.GetToken(),
}
err = message.WriteUDP(msg, t.tunnelConn)
if err != nil {
logrus.Errorf("[%s] send ctl message %v", t.ctlMsg.GetServiceID(), err)
return false
}
return true
}
func (t *UDPTunnel) newLocalConn() bool {
var err error
t.localConn, err = util.CreateDialUDP(t.ctlMsg.Service.LocalAddr)
if err != nil {
logrus.Errorf("[%s] local connect %v", t.ctlMsg.GetServiceID(), err)
return false
}
return true
}
func (t *UDPTunnel) tunnelToLocal(wg *sync.WaitGroup) {
defer wg.Done()
defer t.Close()
for {
msg, err := message.ReadUDP(t.tunnelConn)
if err != nil {
logrus.Tracef("[%s] tunnel to user %v", t.ctlMsg.GetServiceID(), err)
return
}
if msg.GetCtl() != message.NewDataConn || msg.GetServiceID() != t.ctlMsg.GetServiceID() || msg.GetSessionID() != t.ctlMsg.GetSessionID() {
logrus.Warnf("[%s] tunnel data invalid", t.ctlMsg.GetServiceID())
continue
}
_, err = t.localConn.Write(msg.Data)
if err != nil {
logrus.Tracef("[%s] tunnel to user %v", t.ctlMsg.GetServiceID(), err)
return
}
t.ResetTimeout()
}
}
func (t *UDPTunnel) localToTunnel(wg *sync.WaitGroup) {
defer wg.Done()
defer t.Close()
for {
buf := make([]byte, message.BufDataSize)
n, err := t.localConn.Read(buf)
if err != nil {
logrus.Tracef("[%s] user to tunnel %v", t.ctlMsg.GetServiceID(), err)
return
}
err = message.WriteUDP(&message.ControlMessage{
Ctl: message.NewDataConn,
ServiceID: t.ctlMsg.GetServiceID(),
SessionID: t.ctlMsg.GetSessionID(),
Data: buf[:n],
}, t.tunnelConn)
if err != nil {
logrus.Tracef("[%s] user to tunnel %v", t.ctlMsg.GetServiceID(), err)
return
}
t.ResetTimeout()
}
}
|
<?php
namespace App\Http\Controllers;
use App\Models\Slider;
use Illuminate\Http\Request;
class SliderController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$sliders = Slider::all();
return view('slider.index', compact('sliders'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
return view('slider.create');
}
/**
* Store a newly created resource in storage.
*
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
'image' => 'required|image'
]);
$input = $request->all();
if($image = $request->file('image')) {
$destinationPath = 'image/';
$imageName = uniqid().".".$image->getClientOriginalExtension();
$image->move($destinationPath, $imageName);
$input['image'] = $imageName;
}
Slider::create($input);
return redirect('/sliders')->with('message','Data Berhasil Ditambahkan');
}
/**
* Display the specified resource.
*/
public function show(Slider $slider)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Slider $slider)
{
return view('slider.edit', compact('slider'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Slider $slider)
{
$request->validate([
'title' => 'required',
'description' => 'required',
'image' => 'image'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$imageName = uniqid() . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $imageName);
$input['image'] = $imageName;
}
else {
unset($input['image']);
}
$slider->update($input);
return redirect('/sliders')->with('message', 'Data Berhasil Diedit');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Slider $slider)
{
$slider->delete();
return redirect('/sliders')->with('message', 'Data Berhasil Dihapus');
}
}
|
<div align="center">
<p style="text-align:center;">
<img src="images/pyunitgen.png">
</p>
</div>
# `Pyunitgen`
Creating a software application or program is an easy task, howerver a great functional software application is a task that require you to master different level of the SDLC, this, my friend is the haderst task for you as a software developer. One of the area that most software developer lake expertize is the ability to write a `unittest`. A unit testing is another application within your application, is like a `RY(Repeat Yourself)` principale. But we do that often when it comes to unittesting our code. `unittest` is the driver of any software application, failed to do that, make your software look like a water basket with unseen hole, when looking into the basket, there is no way you can tell whether the basket has a hole or not, but when trying pouring water into it, you will know that the basket is not in the great shape, so it is your software application. Believe it or not , most of us do a `unittest`, either manually or using a python `unittest tools`, but the question we will ask is , which one is efficient and can proove to other team member, that your code works well.
Some developers want to write the unittest code, but they lake time due to the deadline. Others use manually testing, which in one hand a lot of time consumming, again Others prefer use of `TDD` approach which is double the time of the application delivery. With all that different approaches, do you think that the user cares ?, at the end of the day the `unittest` is made for developers to developers and no one has time to read all your `unittest` codes. So if no one has time to read all your `unittest` codes, can developers fake `unittest`?, yes they can. To make your life easier and solve all above problems, I came up with `pyunitgen`, the first python automatic `unittest` generator that allow you to focus on your actual features. With `pyunitgen`, you are forcing the developer to describe/comment his code and `pyunitgen` will take care of the `unittest`.
## `Requirement`
---
- `Environment`
- `Operating System` : GNU/Linux Ubuntu 18.04
- `Software packages`
| **Packages** | **Version** |
|:-------------|:--------------------------------|
| python | 3.5+ |
## `How it works`
---
`pyunitgen` allows you to describe the type of data you need to generate for your `unittest` using a docstring annotation.
## `Installation Guide`
---
- `Automatic installation`
Download the installation script following the below command.
```sh
~$ sudo curl -L "https://raw.githubusercontent.com/eirtdev/shell/master/pyunitgen" -o pyunitgen && sudo chmod +x pyunitgen && sudo ./pyunitgen
```
Now go ahead and run the below command and wait.
```sh
~$ pyunitgen --help
```
## `Pyunitgen command line`
---
The below table describe the information needed by `pyunitgen` to create the unittest data. The option unlosed with '`[]`' defined the optional option to provide to `pyunitgen`.
| **Option** | **Description** |**Default**|
|:-----------|:------------------|:----------|
| `module` | The module directory/fileto use for the unittest compilation. This can be a single file as a directories of directories|
| `[-F]` | File to use as a footer template.|
|`[-H]`| File to use as a header template.|
|`[-X]`| Add a child directory name to exclude.|
|`[-f]`|Force files to be generated, even if they already exist.|
|`[-i]`|Include internal classes and methods starting with a _.|
|`[-m]`|The path of the test module to generate.|test|
|`[-p]`|The prefix for test files.|test_|
|`[-t]`|The width of a tab in spaces (default actual tabs).|
|`[-nw]`|Tell `pyunitgen` not to watch the module directory or file whenever the file has been modified. Running `pyunitgen` without this option, will make `pyunitgen` watch the module argument for any changes.|
- Watch module folder with `pyunitgen`
Let us run `pyunitgen` on a module folder called `module_folder`
```sh
$> pyunitgen module_folder -f
```
The above command tell `pyunitgen` to watch the "module_folder" directory, whenever any file has been change in that directory and rerun the unittest for that file.
## `Getting Start`
---
- `@apiParam`
```py
@apiParam [{type=typeOfData}] [field=defaultValue]
```
Describe a parameter passed to your Function/Method.
Usage: @apiParam {Number} id
| **Name** | **Description** |
|:---------|:----------------|
| `{type}` | Parameter type, e.g. {Boolean}, {Number}, {String}, {Object}, {List} ,{Dict}, ...|
| `=typeOfData`|The parameters typeOfData e.g =Email, =first_name, =name, =street_address and so on|
| `[field]` | Fieldname. |
| `field` | Fieldname with brackets define the Variable as optional. |
|`=defaultValue`| The parameters default value. |
- `Examples`
```py
def ask_first_name(first_name):
'''
@apiParam {String} first_name
'''
if isinstance(first_name, str):
return True
return None
class MyClass:
def test_unit_with_email(self, test1):
'''
@apiParam {String=Email} [test1]
'''
def test_unit_with_default_test2_value_and_string(self, test1, test2):
'''
@apiParam {String=first_Name} [test1]
@apiParam {String} test2="Another String parameter"
'''
def test_unit_with_number_and_string(self, test1, test2):
'''
@apiParam {String=first_Name} [test1]
@apiParam {Number} test2
'''
```
- `Supported type`
| **Name** | **Description** |
|:---------|:----------------|
| `Number` | |
| `String` | |
| `Boolean` | |
| `Dict` | |
| `List` | |
- `typeOfData`
This data value represents python `Fake` module data method.
- `Example`
To create a fake data in python , we use the below code.
```py
fake=Fake()
email_address=fake.email()
```
in `pyunitgen` you write `{type=email}`
```py
{String=email}
```
More examples about the `@apiParam` can be found on the `@apiReturn` section.
- `@apiReturn`
```py
@apiReturn {type} [value]
```
Describe the return value of your Function/Method. There is a difference between testing a return for a function and testing the return value for an object. This has to be put in mind when using the return annotation.
Usage: @apiParam {Number} id
| **Name** | **Description** |
|:---------|:----------------|
| `{type}` | Parameter type, e.g. {Boolean}, {Number}, {String}, {Object}, {List} ,{Dict}, {apiParam}...|
| `[value]` | The return value of the function.This can be any atomic string , boolean, list, dict , number,self or class_name in lower case with another method name |
- `Example`
Create a folder called `sample` where all, the codes will be located.
Create all the below files with their content.
```py
#file: sample/pet_main.py
from sample.pet import Pet as AnimalPet, Dog
from sample.pet import Pet
from sample.animal import Animal
def create_pet(name, species, age=0):
'''
@apiParam {String} [name]
@apiParam {String} [species]
@apiParam {Number=random_int} [age]
@apiReturn {Object} [Pet(apiParam.name,apiParam.species)]
'''
return Pet(name, species).get_name()
def create_pet_with_empty_return_object(name, species, age=0):
'''
@apiReturn {Object}
'''
return Pet(name, species)
def create_pet_return_true(name, species, age=0):
'''
@apiReturn {String}
'''
return Pet(name, species).getSpecies()
def create_animal(species):
'''
@apiReturn {Object}
'''
return Animal(species)
def create_pet_return_false(name, species, age=0):
'''
@apiReturn {Boolean} [False]
'''
Pet(name, species)
return False
def create_pet_return_none(name, species, age=0):
'''
@apiReturn {Boolean} [False]
'''
Pet(name, species)
```
- `All Examples`
```py
#file: sample/animal.py
class Animal(object):
def __init__(self, species):
self.species = species
def getSpecies(self):
return self.species
```
```py
#file: sample/pet.py
from sample.animal import Animal
class Pet(Animal):
def __init__(self, name, *args):
'''
@apiParam {String} [name]
@apiParam {String} [args]
'''
Animal.__init__(self, *args)
self._name = name
def get_name(self):
'''
The below declaration make sure that the function return match the value return. This only allow when the class has the init function
@apiReturn {String}
'''
return self._name
@staticmethod
def lower(s):
'''
@apiParam {String} [s]
@apiReturn {String}
'''
return s.lower()
def __str__(self):
return '%s is a %s aged %d' % (
self.get_name(),
Pet.lower(self.get_species()), self.get_age()
)
class Dog(Pet):
pass
```
```py
#file: sample/pet_main.py
from sample.pet import Pet as AnimalPet, Dog
from sample.pet import Pet
from sample.animal import Animal
def create_pet(name, species, age=0):
'''
@apiParam {String} [name]
@apiParam {String} [species]
@apiParam {Number=random_int} [age]
@apiReturn {Object} [Pet(apiParam.name,apiParam.species)]
'''
return Pet(name, species).get_name()
def create_pet_with_empty_return_object(name, species, age=0):
'''
@apiParam {String} [name]
@apiParam {String} [species]
@apiParam {Number=random_int} [age]
@apiReturn {Object}
'''
return Pet(name, species)
def create_pet_return_true(name, species, age=0):
'''
@apiParam {String} [name]
@apiParam {String} [species]
@apiParam {Number=random_int} [age]
@apiReturn {String}
'''
return Pet(name, species).getSpecies()
def create_animal(species):
'''
@apiParam {String} [species]
@apiReturn {Object}
'''
return Animal(species)
def create_pet_return_false(name, species, age=0):
'''
@apiParam {String} [name]
@apiParam {String} [species]
@apiParam {Number=random_int} [age]
@apiReturn {Boolean} [False]
'''
Pet(name, species)
return False
def create_pet_return_none(name, species, age=0):
'''
@apiParam {String} [name]
@apiParam {String} [species]
@apiParam {Number} [age]
@apiReturn {Boolean} [False]
'''
Pet(name, species)
```
- `Output`
```py
from sample.pet_main import create_pet,create_pet_with_empty_return_object,create_pet_return_true,create_animal,create_pet_return_false,create_pet_return_none
from sample.pet import Pet as AnimalPet
from sample.pet import Dog
from sample.pet import Pet
from sample.animal import Animal
import unittest
class pet_mainTest(unittest.TestCase):
"""
Tests for functions in the "pet_main" file.
"""
@classmethod
def setUpClass(cls):
pass #TODO
@classmethod
def tearDownClass(cls):
pass #TODO
def setUp(self):
pass #TODO
def tearDown(self):
pass #TODO
def test_create_pet(self):
pet_main = create_pet(name='Erika Perkins',species='Charlene Torres',age=9858)
self.assertEqual(pet_main, Pet('Erika Perkins','Charlene Torres'))
def test_create_pet_with_empty_return_object(self):
pet_main = create_pet_with_empty_return_object(name='Lynn Russell',species='Jonathan Boyd',age=7279)
self.assertIsInstance(pet_main, Pet)
def test_create_pet_return_true(self):
pet_main = create_pet_return_true(name='Christopher Campbell',species='Mia Robertson',age=9057)
self.assertEqual(pet_main, 'Christopher Campbell')
def test_create_animal(self):
pet_main = create_animal(species='Malik Holloway')
self.assertIsInstance(pet_main, Animal)
def test_create_pet_return_false(self):
pet_main = create_pet_return_false(name='Joshua Johnson',species='Christopher Jackson',age=4464)
self.assertFalse(pet_main,False)
def test_create_pet_return_none(self):
pet_main = create_pet_return_none(name='Ashley Aguilar',species='Richard Taylor',age=910676837)
self.assertFalse(pet_main,False)
```
```py
# file: sample/func.py
username = None
def name():
'''
@apiReturn {String} [Evarist]
'''
return "Evarist"
def set_username(name):
'''
@apiParam {String} [name]
@apiReturn {Boolean} [True]
'''
global username
username = name
return True
def get_username():
global username
return username
def test_boolean_true(first_name):
'''
@apiParam {String} first_name
@apiReturn {Boolean} [True]
'''
if isinstance(first_name, str):
return True
return None
def test_boolean_false(first_name):
'''
@apiParam {String} first_name
@apiReturn {Boolean} [False]
'''
if not isinstance(first_name, str):
return False
```
- `output`
```py
from sample.func import name,set_username,get_username,test_boolean_true,test_boolean_false
import unittest
class funcTest(unittest.TestCase):
"""
Tests for functions in the "func" file.
"""
@classmethod
def setUpClass(cls):
pass #TODO
@classmethod
def tearDownClass(cls):
pass #TODO
def setUp(self):
pass #TODO
def tearDown(self):
pass #TODO
def test_name(self):
func = name()
self.assertEqual(func, 'Evarist')
def test_set_username(self):
func = set_username(name='Rebecca Mccall')
self.assertTrue(func,True)
def test_test_boolean_true(self):
func = test_boolean_true(first_name='Brett Holt')
self.assertTrue(func,True)
def test_test_boolean_false(self):
func = test_boolean_false(first_name='Jessica Morrison')
self.assertFalse(func,False)
```
```py
# file: sample/person.py
class Person:
name = []
def set_name(self, user_name):
'''
@apiParam {String} [user_name]
@apiReturn {apiParam.user_name} [self.get_name(0)]
'''
self.name.append(user_name)
return len(self.name) - 1
def get_name(self, user_id):
'''
@apiParam {Number} [user_id=1]
@apiReturn {String} [There is no such user]
'''
if user_id >= len(self.name):
return 'There is no such user'
else:
return self.name[user_id]
```
- `output`
```py
from sample.person import Person
import unittest
class PersonTest(unittest.TestCase):
"""
Tests for methods in the Person class.
"""
@classmethod
def setUpClass(cls):
pass #TODO
@classmethod
def tearDownClass(cls):
pass #TODO
def setUp(self):
pass #TODO
def tearDown(self):
pass #TODO
def test_set_name(self):
person = Person()
person_set_name=person.set_name(user_name='Maureen Simpson')
self.assertEqual('Maureen Simpson', person.get_name(0))
def test_get_name(self):
person = Person()
person_get_name=person.get_name(user_id=1)
self.assertEqual(person_get_name, 'There is no such user')
```
```py
# file: sample/test.py
from .server import Server
class AnchorPeer:
def __init__(self, name, org_name=None):
self.name = name
self.org_name = org_name
self.server = Server()
def dump(self):
if self.org_name.lower() not in self.server.host:
self.server.host = "{}.{}".format(
self.org_name.lower(), self.server.host)
return "\n\n\n\t\t\t- Host: {}.{}\n\t\t\t Port: {}".format(self.name, self.server.host, self.server.port)
def test_unit_that_return_dict(self):
'''
@apiReturn {Number} [{"name":4}]
'''
print("hi there ")
return
def test_unit_that_return_dict_with_a_dictionary_type(self):
'''
@apiReturn {Dict} [{"name":4}]
'''
print("hi there ")
return
def test_unit_with_email(self, test1):
'''
@apiParam {String=Email} [test1]
@apiReturn {Boolean} [True]
'''
def test_unit_with_default_test2_value_and_string(self, test1, test2):
'''
@apiParam {String=first_Name} [test1]
@apiParam {String} test2="Fangnikoue Evarist"
@apiReturn {Boolean} [True]
'''
def test_unit_with_number_and_string(self, test1, test2):
'''
@apiParam {String=first_Name} [test1]
@apiParam {Number} test2
@apiReturn {Boolean} [True]
'''
def test_unit_with_address(self, address):
'''
@apiParam {String=street_address} [address]
@apiReturn {Boolean} [True]
'''
def test_unit_with_boolean_and_string(self, test1, test2):
'''
@apiParam {String} [test1]
@apiParam {Boolean} [test2]
@apiReturn {Boolean} [True]
'''
def test_unit_that_return_a_list(self, test1, test2):
'''
@apiReturn {Number} [1,2,3,4]
'''
def test_unit_that_return_a_list_with_a_list_type(self, test1, test2):
'''
@apiReturn {List} [1,2,3,4]
'''
def test_unit_3(self, test1, test2):
'''
'''
def test_unit_4(self, test1, test2):
pass
```
- `output`
```py
from sample.test import AnchorPeer
import unittest
class AnchorPeerTest(unittest.TestCase):
"""
Tests for methods in the AnchorPeer class.
"""
@classmethod
def setUpClass(cls):
pass #TODO
@classmethod
def tearDownClass(cls):
pass #TODO
def setUp(self):
pass #TODO
def tearDown(self):
pass #TODO
def test_dump(self):
anchorpeer = AnchorPeer()
anchorpeer_dump = anchorpeer.dump()
self.assertIsNone(anchorpeer_dump)
def test_test_unit_that_return_dict(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_that_return_dict = anchorpeer.test_unit_that_return_dict()
self.assertEqual(anchorpeer_test_unit_that_return_dict, {"name":4})
def test_test_unit_that_return_dict_with_a_dictionary_type(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_that_return_dict_with_a_dictionary_type = anchorpeer.test_unit_that_return_dict_with_a_dictionary_type()
self.assertEqual(anchorpeer_test_unit_that_return_dict_with_a_dictionary_type, {"name":4})
def test_test_unit_with_email(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_with_email=anchorpeer.test_unit_with_email(test1='marcus24@davis.com')
self.assertTrue(anchorpeer_test_unit_with_email,True)
def test_test_unit_with_default_test2_value_and_string(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_with_default_test2_value_and_string=anchorpeer.test_unit_with_default_test2_value_and_string(test1='John',test2='Fangnikoue')
self.assertTrue(anchorpeer_test_unit_with_default_test2_value_and_string,True)
def test_test_unit_with_number_and_string(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_with_number_and_string=anchorpeer.test_unit_with_number_and_string(test1='Kimberly',test2=594)
self.assertTrue(anchorpeer_test_unit_with_number_and_string,True)
def test_test_unit_with_address(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_with_address=anchorpeer.test_unit_with_address(address='691 Knox Hill Apt. 408')
self.assertTrue(anchorpeer_test_unit_with_address,True)
def test_test_unit_with_boolean_and_string(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_with_boolean_and_string=anchorpeer.test_unit_with_boolean_and_string(test1='Timothy Powell',test2=True)
self.assertTrue(anchorpeer_test_unit_with_boolean_and_string,True)
def test_test_unit_that_return_a_list(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_that_return_a_list = anchorpeer.test_unit_that_return_a_list()
self.assertEqual(anchorpeer_test_unit_that_return_a_list, ['1', '2', '3', '4'])
def test_test_unit_that_return_a_list_with_a_list_type(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_that_return_a_list_with_a_list_type = anchorpeer.test_unit_that_return_a_list_with_a_list_type()
self.assertEqual(anchorpeer_test_unit_that_return_a_list_with_a_list_type, ['1', '2', '3', '4'])
def test_test_unit_3(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_3 = anchorpeer.test_unit_3()
self.assertIsNone(anchorpeer_test_unit_3)
def test_test_unit_4(self):
anchorpeer = AnchorPeer()
anchorpeer_test_unit_4 = anchorpeer.test_unit_4()
self.assertIsNone(anchorpeer_test_unit_4)
```
## `Note for the users`
---
- ### Add Description to the @api[Param|Return]
At this earlier stage of `pyunitgen`, we recommand the user to put the comment description on the next line when the `pyunitgen` annotation has been used.
|
import firebase from '@react-native-firebase/app';
import '@react-native-firebase/functions';
import '@react-native-firebase/auth';
import firestore from '@react-native-firebase/firestore'
import { getIngredientQuantity } from './inventory';
export async function resetPopularItems() {
let query;
let isSuccess = true;
await firebase.firestore().collection('Menu').get()
.then(snapshot => {
query = snapshot.docs.map(doc => doc.data());
})
.catch (error => {
console.log('Error getting documents', error);
isSuccess = false;
});
if (!isSuccess) {
return false;
}
for (i in query) {
if (query[i].popular) {
query[i].popular = false;
await firebase.firestore().collection('Menu').doc(query[i].name).set(query[i])
.then(snapshot => {
console.log('Successfully updated document.');
})
.catch (error => {
console.log('Error getting documents', error);
isSuccess = false;
});
}
}
if (!isSuccess) {
return false;
}
return true;
}
export async function setPopularItems(type) {
let query;
let isSuccess = true;
// let month = new Date();
// month = month.getMonth();
// await firebase.firestore().collection('Menu').where('month', '==', month).get()
// .then(snapshot => {
// if (snapshot.exists()) {
// query = snapshot.docs.map(doc => doc.data());
// }
// else {
// query = null;
// }
// })
// .catch (error => {
// console.log('Error getting documents', error);
// isSuccess = false;
// });
// if (!isSucess) {
// return false;
// }
// if (query == null) {
// await firebase.firestore().collection('Menu').doc('CurrentMonth').set({month: month})
// .then(snapshot => {
// console.log('Success updated month', error);
// })
// .catch (error => {
// console.log('Error getting documents', error);
// isSuccess = false;
// });
// //need to reset orderTotal
// }
await firebase.firestore().collection('Menu').where('type','==',type).orderBy('orderTotal', 'desc').get()
.then(snapshot => {
query = snapshot.docs.map(doc => doc.data());
})
.catch (error => {
console.log('Error getting documents', error);
query = null;
});
if (query == null) {
return false;
}
for (let i = 0; i < 3; i++) {
query[i].popular = true;
await firebase.firestore().collection('Menu').doc(query[i].name).set(query[i])
.then(snapshot => {
console.log('Succesfully updated document.');
})
.catch (error => {
console.log('Error getting documents', error);
query = null;
});
}
if (query == null) {
return false;
}
return true;
}
//this function is used to get the items on the menu based on their type
//the functions parameter is a string which is the menu type i.e, getMenu('entree')
export async function getMenu(type) {
let query;
await firebase.firestore().collection('Menu').where('type', '==', type).get()
.then(snapshot => {
query = snapshot.docs.map(doc => doc.data());
})
.catch (error => {
console.log('Error getting documents', error);
query = null;
});
let items = [];
for (i in query) {
let isAvailable = true;
for (j in query[i].ingredients) {
await getIngredientQuantity(query[i].ingredients[j])
.then((quantity) => {
if (quantity == 0) {
isAvailable = false;
}
})
.catch (error => {
console.log('Error getting documents', error);
});
if (!isAvailable) {
break;
}
}
if (isAvailable) {
items.push(query[i]);
}
}
return items;
}
//this function is used to add Menu item
//the functions parameter is a item object.
//for example:
/*let item = {
allergen: ['Egg' , 'Milk'],
calories: 750,
ingredients: ['cheese', 'tomato sauce', 'pepperoni'],
name: 'Pizza',
price: 6.99,
type: 'entree',
uri: 'image link'
}*/
//then pass item to the function i.e, addToMenu(item)
export async function addToMenu(item) {
let isSuccess;
firebase.firestore().collection('Menu').doc(item.name).set(item)
.then(() => {
console.log("Successfully added item to the menu.");
isSuccess = true;
})
.catch((error) => {
alert("Error adding item to menu: ", error);
isSuccess = false;
});
return isSuccess;
}
//this function is used to delete a Menu item from the database
//the functions parameter is a string which is the menu item name i.e., deleteFromMenu('Pizza') will delete the menu item who's name is Pizza
export async function deleteFromMenu(itemName) {
let isSuccess;
firebase.firestore().collection('Menu').doc(itemName).delete()
.then(() => {
console.log("Successfully deleted item from the menu.");
isSuccess = true;
})
.catch((error) => {
alert("Error deleting item from menu: ", error);
isSuccess = false;
});
return isSuccess;
}
//this function is used to update menu item information to the database
//the functions parameter is a item object.
//for example:
/*let item = {
allergen: ['Egg', 'Milk'],
calories: 850,
ingredients: ['blue cheese', 'tomato sauce', 'pineapple'],
name: 'Pizza',
price: 7.99,
type: 'entree',
uri: 'image link'
}*/
//then pass item to the function i.e, updateMenuItem(item)
//this will update the the Pizza menu item's calories to 850,
//the ingredients array will be changed to have the values ['blue cheese', 'tomato sauce', 'pineapple']
//the name will remain the same
//the price will be changed to be 7.99
//the type will remain entree
//the uri can be changed to whatever image link you want
//updateMenuItem(item)
export async function updateMenuItem(item) {
let isSuccess;
await firebase.firestore().collection('Menu').doc(item.name).update(item)
.then(() => {
isSuccess = true;
})
.catch((error) => {
console.error("Error updating item in menu: ", error);
isSuccess = false;
});
return isSuccess;
}
//this function is used to get menu information from the database
//the functions parameter is a string which is the menu item name i.e., getItemDetails('Pizza') will get the menu item data for the menu item who's named is Pizza
export async function getItemDetails(itemName) {
let query;
await firebase.firestore().collection('Menu').where('name', '==', itemName).get()
.then((snapshot) => {
query = snapshot.docs.map(doc => doc.data());
})
.catch ((error) => {
console.log('Error getting document', error);
query = null;
});
return query;
}
//this function is used to check a particular items inventory is not empty
//the parameter for this function is a string which is the name of the item i.e., checkInventory('Sugar')
export async function checkInventory(name) {
let query;
await firebase.firestore().collection('Inventory').where('ingredientName', '==', name).get()
.then(snapshot => {
query = snapshot.docs.map(doc => doc.data());
})
.catch(error => {
console.log('Error getting documents', error);
query = null;
});
if (query == null) {
return null;
}
if (query[0].ingredientQuantity == 0) {
return 0;
} else
return 1;
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Grouping</title>
<style>
/* From extension vscode.github */
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.vscode-dark img[src$=\#gh-light-mode-only],
.vscode-light img[src$=\#gh-dark-mode-only] {
display: none;
}
</style>
<link rel="stylesheet" href="../assets/css/markdown.min.css">
<link rel="stylesheet" href="../assets/css/highlight.min.css">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe WPC', 'Segoe UI', system-ui, 'Ubuntu', 'Droid Sans', sans-serif;
font-size: 14px;
line-height: 1.6;
}
</style>
<style>
.task-list-item {
list-style-type: none;
}
.task-list-item-checkbox {
margin-left: -20px;
vertical-align: middle;
pointer-events: none;
}
</style>
</head>
<body class="vscode-body vscode-light">
<h1 id="grouping">Grouping</h1>
<h2 id="group-by">GROUP BY</h2>
<ul>
<li>Kadang saat melakukan aggregate, kita ingin datanya di grouping berdasarkan kriteria tertentu</li>
<li>Misal kita ingin melihat rata-rata harga product, tapi ingin per category</li>
<li>Atau kita ingin melihat total semua product, tapi per category</li>
<li>Hal ini bisa dilakukan di MySQL dengan menggunakan GROUP BY clause</li>
<li>GROUP BY clause ini hanya bisa digunakan jika kita menggunakan aggregate function</li>
<li><a href="https://dev.mysql.com/doc/refman/8.0/en/group-by-modifiers.html">https://dev.mysql.com/doc/refman/8.0/en/group-by-modifiers.html</a></li>
</ul>
<hr>
<h2 id="menggunakan-group-by">Menggunakan GROUP BY</h2>
<pre><code class="language-sql"><span class="hljs-keyword">SELECT</span> category, <span class="hljs-built_in">COUNT</span>(id) <span class="hljs-keyword">AS</span> <span class="hljs-string">'Total Products'</span>
<span class="hljs-keyword">FROM</span> products
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> category;
</code></pre>
<p><strong>Hasil :</strong></p>
<p><img src="..\assets\img\29\1.PNG" alt="1"></p>
<hr>
<h2 id="having-clause">HAVING Clause</h2>
<ul>
<li>Kadang kita ingin melakukan filter terhadap data yang sudah kita grouping</li>
<li>Misal kita ingin menampilkan rata-rata harga per kategori, tapi yang harganya diatas 10.000 misalnya</li>
<li>Jika menggunakan WHERE di SELECT, hal ini tidak bisa dilakukan</li>
<li>Untuk memfilter hasil aggregate function, kita harus menggunakan HAVING clause</li>
</ul>
<hr>
<h2 id="menggunakan-having-clause">Menggunakan HAVING Clause</h2>
<pre><code class="language-sql"><span class="hljs-keyword">SELECT</span> category, <span class="hljs-built_in">COUNT</span>(id) <span class="hljs-keyword">AS</span> total
<span class="hljs-keyword">FROM</span> products
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> category
<span class="hljs-keyword">HAVING</span> total <span class="hljs-operator">></span> <span class="hljs-number">2</span>;
</code></pre>
<p><strong>Hasil :</strong></p>
<p><img src="..\assets\img\29\2.png" alt="2"></p>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Run Buddy</title>
<link rel="stylesheet" href="./assets/css/style.css" />
</head>
<body>
<!--navigation-->
<header>
<h1>
<a href= "./index.html">RUN BUDDY</a>
</h1>
<nav>
<!--Unordered list element-->
<ul>
<!--List item element-->
<li>
<!--Anchor element-->
<a href="#what-we-do">What We Do</a>
</li>
<li>
<a href="#what-you-do">What You Do</a>
</li>
<li>
<a href="#your-trainers">Your Trainers</a>
</li>
<li>
<a href="#reach-out">Reach Out</a>
</li>
</ul>
</nav>
</header>
<!--hero/jumbotron-->
<section class="hero">
<div class="hero-cta">
<h2>Start Building Habits.</h2>
<p>seitan heirloom post-ironic pop-up iPhone mlkshk hella selfies fashion axe occupy readymade put a bird on it
messenger bag Wes Anderson Schlitz plaid Bushwick church-key lo-fi skateboard slow-carb hashtag trust fund
Williamsburg biodiesel fixie farm-to-table 8-bit banjo XOXO Banksy chillwave bicycle rights retro cliche
tattooed bespoke irony mumblecore Shoreditch deep v polaroid McSweeney's bitters cray gentrify tofu Marfa you
probably haven't heard of them yr banh mi asymmetrical art party selvage letterpress High Life.</p>
</div>
<!--Form element-->
<form class="hero-form">
<h3>Get Started Today</h3>
<p>Fill out this form and one of our trainers will schedule a consult</p>
<label for="name">Enter full name:</label>
<input type="text" placeholder="Your Name" name="name" id="name" class="form-input"/>
<label for="email">Enter email address:</label>
<input type="email" placeholder="Email Address" name="email" id="email" class="form-input"/>
<label for="phone">Enter telephone number:</label>
<input type="tel" placeholder="Phone Number" name="phone" id="phone" class="form-input"/>
<p>
Have you worked out with a trainer before?
<span class="radio-wrapper">
<input type="radio" name="trainer-confirm" id="trainer-yes" />
<label for="trainer-yes">Yes</label>
</span>
<span class="radio-wrapper">
<input type="radio" name="trainer-confirm" id="trainer-no" />
<label for="trainer-no">No</label>
</span>
</p>
<p>
<span class="checkbox-wrapper">
<input type="checkbox" name="age-confirm" id="checkbox" />
<label for="checkbox">I acknowledge that I am at least 18 years of age</label>
</span>
</p>
<button type="submit">
Get running!
</button>
</form>
</section>
<!--End Hero Section-->
<!--"What We Do" section-->
<section id="what-we-do" class="intro">
<div class="flex-row">
<h2 class="section-title primary-border">What We Do</h2>
</div>
<div class="flex-row">
<p>butcher selfies chambray shabby chic gentrify readymade yr Echo Park XOXO Tumbler normcore Banksy direct trade Blue Bottle chillwave you probably haven't heard of them single-origin coffee Vice fanny pack fixie Odd Future Austin fingerstache pickled twee synth Wes Anderson Thundercats viral bitters flannel meggings narwhal Marfa Schlitz sustainable Intelligentsia umami deep v craft</p>
</div>
</section>
<!--"What You Do" section-->
<section id="what-you-do" class="steps">
<div class="flex-row">
<h2 class="section-title secondary-border">What You Do</h2>
</div>
<div class="step">
<h3>Step 1: </h3>
<div class="step-info">
<div class="step-img">
<img src="./assets/images/01-04-svgs/step-1.svg" alt="" />
</div>
<div class="step-text">
<h4>Fill Out the Form Above</h4>
<p>You're already here, so why not?</p>
</div>
</div>
</div>
<div class="step">
<h3> Step 2:</h3>
<div class="step-info">
<div class="step-img">
<img src="./assets/images/01-04-svgs/step-2.svg" alt="" />
</div>
<div class="step-text">
<h4>Consult With One of Our Trainers</h4>
<p>Are you here to build muscle, lose weight, or just feel good?</p>
</div>
</div>
</div>
<div class="step">
<h3>Step 3:</h3>
<div class="step-info">
<div class="step-img">
<img src="./assets/images/01-04-svgs/step-3.svg" alt="" />
</div>
<div class="step-text">
<h4>Get Running</h4>
<p>Hit the ground running (literally) once your trainer lays out your plan.</p>
</div>
</div>
</div>
<div class="step">
<h3>Step 4:</h3>
<div class="step-info">
<div class="step-img">
<img src="./assets/images/01-04-svgs/step-4.svg" alt="" />
</div>
<div class="step-text">
<h4>See Results</h4>
<p>Bi-weekly checkins with your trainer rwill keep you focused</p>
</div>
</div>
</div>
</section>
<!--"Meet the Trainers" section-->
<section id="your-trainers">
<div class="flex-row">
<h2 class="section-title primary-border">Meet The Trainers</h2>
</div>
<div class="trainers">
<article class="trainer">
<img src="./assets/images/01-05-trainers/trainer-1.jpg" alt="Arron Stephens in his workout clothes, ready to pump iron" />
<div class="trainer-bio">
<h3 class="trainer-name">Arron Stephens</h3>
<h4 class="trainer-role">Speed / Strength</h4>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Itaque fuga corporis et reprehenderit? Eligendi dicta unde aut pariatur mollitia in eaque ratione? Rerum, sapiente unde quam labore et qui minus?</p>
</div>
</article>
<article class="trainer">
<img src="./assets/images/01-05-trainers/trainer-2.jpg" alt="Joanna Gill cooling off after a workout" />
<div class="trainer-bio">
<h3 class="trainer-name">Joanna Gill</h3>
<h4 class="trainer-role">Endurance</h4>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Itaque fuga corporis et reprehenderit? Eligendi dicta unde aut pariatur mollitia in eaque ratione? Rerum, sapiente unde quam labore et qui minus?</p>
</div>
</article>
<article class="trainer">
<img src="./assets/images/01-05-trainers/trainer-3.jpg" alt="Harry Smith wearing a headband and lifting comically small pink weights" />
<div class="trainer-bio">
<h3 class="trainer-name">Harry "the Headband" Smith</h3>
<h4 class="trainer-role">Strength</h4>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Itaque fuga corporis et reprehenderit? Eligendi dicta unde aut pariatur mollitia in eaque ratione? Rerum, sapiente unde quam labore et qui minus?</p>
</div>
</article>
</div>
</section>
<!--"Reach Out" section-->
<section id="reach-out" class="contact">
<div class="flex-row"></div>
<h2 class="section-title secondary-border">Reach Out</h2>
</div>
<div class="contact-info">
<div>
<h3>Run Buddy</h3>
<p>
Any questions or concerns signing up?
<br/>
Let us know and we'll be happy to talk to you!
</p>
<address>
55 Main Street<br/>
Some Town, Ca<br/>
12345<br/>
P: 555.RUN.BUDZ (555.786.2839)<br/>
E: <a href="mailto:info@runbuddy.io">info@runbuddy.io</a>
</address>
</div>
<div class="contact-form">
<h3>Contact Us</h3>
<form>
<label for="contact-name">Your Name</label>
<input type="text" id="contact-name" placeholder="Your Name"/>
<label for="contact-message">Message</label>
<textarea id="contact-message" placeholder="Message"></textarea>
<button type="submit">Submit</button>
</form>
</div>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3149.546040872629!2d-120.43435208680309!3d37.870911079742065!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8090db7cda478e35%3A0xe12336ef8ade41b1!2sMain%20St%2C%20California%2095327!5e0!3m2!1sen!2sus!4v1653522056691!5m2!1sen!2sus"
style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade">
</iframe>
</div>
</section>
<!--Footer-->
<footer>
<h2> ❤️ Made with love by Run Buddy.</h2>
<div>
<a href="./privacy-policy.html">Read Our Privacy Policy</a><br />
© 2019 Run Buddy, Inc.
</div>
</footer>
</body>
</html>
|
from pathlib import Path
from oauth2client.service_account import ServiceAccountCredentials
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
import logs
from config import AppConfig
def upload_recording(config: AppConfig, path: Path):
if config.drive_service_account_path is None:
return
scope = ["https://www.googleapis.com/auth/drive"]
gauth = GoogleAuth()
gauth.auth_method = 'service'
gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
config.drive_service_account_path, scope
)
drive = GoogleDrive(gauth)
logs.log_info(f"Authenticated as {logs.C_HEADER}{drive.GetAbout()['name']}")
file = drive.CreateFile({
"title": path.name,
"parents": [{
"id": config.drive_parent_folder_id
}] if config.drive_parent_folder_id is not None else []
})
file.SetContentFile(path)
file.Upload()
logs.log_info(f"Google Drive upload completed")
if not config.drive_keep_local_copy:
path.unlink(missing_ok=True)
logs.log_info("Local file removed")
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Start your development with Meyawo landing page.">
<meta name="author" content="Devcrud">
<title>Olamide Portfolio</title>
<!-- font icons -->
<link rel="stylesheet" href="assets/vendors/themify-icons/css/themify-icons.css">
<!-- Bootstrap + Meyawo main styles -->
<link rel="stylesheet" href="assets/css/meyawo.css">
</head>
<body data-spy="scroll" data-target=".navbar" data-offset="40" id="home">
<!-- Page Navbar -->
<nav class="custom-navbar" data-spy="affix" data-offset-top="20">
<div class="container">
<a class="logo" href="#">Olamide</a>
<ul class="nav">
<li class="item">
<a class="link" href="#home">Home</a>
</li>
<li class="item">
<a class="link" href="#about">About</a>
</li>
<li class="item">
<a class="link" href="#portfolio">Portfolio</a>
</li>
<li class="item">
<a class="link" href="#testmonial">Testmonial</a>
</li>
<li class="item">
<a class="link" href="#blog">Blog</a>
</li>
<li class="item">
<a class="link" href="#contact">Contact</a>
</li>
<li class="item ml-md-3">
<a href="components.html" class="btn btn-primary">Components</a>
</li>
</ul>
<a href="javascript:void(0)" id="nav-toggle" class="hamburger hamburger--elastic">
<div class="hamburger-box">
<div class="hamburger-inner"></div>
</div>
</a>
</div>
</nav><!-- End of Page Navbar -->
<!-- page header -->
<header id="home" class="header">
<div class="overlay"></div>
<div class="header-content container">
<h1 class="header-title">
<span class="up">HI!</span>
<span class="down">I am Olamide</span>
</h1>
<p class="header-subtitle">BACKEND WEB DEVELOPER</p>
<button class="btn btn-primary">Visit My Works</button>
</div>
</header><!-- end of page header -->
<!-- about section -->
<section class="section pt-0" id="about">
<!-- container -->
<div class="container text-center">
<!-- about wrapper -->
<div class="about">
<div class="about-img-holder">
<img src="assets/imgs/profile_pic.jpg" class="about-img"
alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page">
</div>
<div class="about-caption">
<p class="section-subtitle">Who Am I ?</p>
<h2 class="section-title mb-3">About Me</h2>
<p>
I am a backend software engineer with about two years of exprience.
<br>
I have worked with different technologies like Python, Flask, Node and Express.
</p>
<button class="btn-rounded btn btn-outline-primary mt-4">Download CV</button>
</div>
</div><!-- end of about wrapper -->
</div><!-- end of container -->
</section> <!-- end of about section -->
<!-- portfolio section -->
<section class="section" id="portfolio">
<div class="container text-center">
<p class="section-subtitle">What I Did ?</p>
<h6 class="section-title mb-6">Portfolio</h6>
<!-- row -->
<div class="row">
<div class="col-md-6">
<a href="https://github.com/Olyray/AfroBeatStats" class="portfolio-card">
<img src="assets/imgs/Afrobeatstats.png" class="portfolio-card-img"
alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page">
<span class="portfolio-card-overlay">
<span class="portfolio-card-caption">
<h4>AfroBeatStats</h5>
</span>
</span>
</a>
</div>
<div class="col-md-6">
<a href="https://github.com/Olyray/PodSnipsAPI" class="portfolio-card">
<img class="portfolio-card-img" src="assets/imgs/PodSnipsAPI.png" class="img-responsive rounded"
alt="Download free bootstrap 4 landing page, free boootstrap 4 templates, Download free bootstrap 4.1 landing page, free boootstrap 4.1.1 templates, meyawo Landing page">
<span class="portfolio-card-overlay">
<span class="portfolio-card-caption">
<h4>PodSnipsAPI</h5>
</span>
</span>
</a>
</div>
</div><!-- end of row -->
</div><!-- end of container -->
</section> <!-- end of portfolio section -->
<!-- section -->
<section class="section-sm bg-primary">
<!-- container -->
<div class="container text-center text-sm-left">
<!-- row -->
<div class="row align-items-center">
<div class="col-sm offset-md-1 mb-4 mb-md-0">
<h6 class="title text-light">Want to work with me?</h6>
<p class="m-0 text-light">Always feel Free to Contact & Hire me</p>
</div>
<div class="col-sm offset-sm-2 offset-md-3">
<button class="btn btn-lg my-font btn-light rounded">Hire Me</button>
</div>
</div> <!-- end of row -->
</div> <!-- end of container -->
</section> <!-- end of section -->
<!-- contact section -->
<section class="section" id="contact">
<div class="container text-center">
<p class="section-subtitle">How can you communicate?</p>
<h6 class="section-title mb-5">Contact Me</h6>
<!-- contact form -->
<form action="" class="contact-form col-md-10 col-lg-8 m-auto">
<div class="form-row">
<div class="form-group col-sm-6">
<input type="text" size="50" class="form-control" placeholder="Your Name" required>
</div>
<div class="form-group col-sm-6">
<input type="email" class="form-control" placeholder="Enter Email" requried>
</div>
<div class="form-group col-sm-12">
<textarea name="comment" id="comment" rows="6" class="form-control"
placeholder="Write Something"></textarea>
</div>
<div class="form-group col-sm-12 mt-3">
<input type="submit" value="Send Message" class="btn btn-outline-primary rounded">
</div>
</div>
</form><!-- end of contact form -->
</div><!-- end of container -->
</section><!-- end of contact section -->
<!-- footer -->
<div class="container">
<footer class="footer">
<p class="mb-0">Copyright
<script>document.write(new Date().getFullYear())</script> © <a
href="http://www.devcrud.com">DevCRUD</a> Distribution <a
href="https://themewagon.com">ThemeWagon</a>
</p>
<div class="social-links text-right m-auto ml-sm-auto">
<a href="javascript:void(0)" class="link"><i class="ti-facebook"></i></a>
<a href="javascript:void(0)" class="link"><i class="ti-twitter-alt"></i></a>
<a href="javascript:void(0)" class="link"><i class="ti-google"></i></a>
<a href="javascript:void(0)" class="link"><i class="ti-pinterest-alt"></i></a>
<a href="javascript:void(0)" class="link"><i class="ti-instagram"></i></a>
<a href="javascript:void(0)" class="link"><i class="ti-rss"></i></a>
</div>
</footer>
</div> <!-- end of page footer -->
<!-- core -->
<script src="assets/vendors/jquery/jquery-3.4.1.js"></script>
<script src="assets/vendors/bootstrap/bootstrap.bundle.js"></script>
<!-- bootstrap 3 affix -->
<script src="assets/vendors/bootstrap/bootstrap.affix.js"></script>
<!-- Meyawo js -->
<script src="assets/js/meyawo.js"></script>
</body>
</html>
|
import {shallowEquals} from '@alorel/commons-shallow-equals';
import {signal, useComputed, useSignal} from '@preact/signals';
import type {VNode} from 'preact';
import {h} from 'preact';
import {memo} from 'preact/compat';
import {useCallback, useMemo} from 'preact/hooks';
import type {OptionDefinition, OptionRenderEditCtx} from '../../../../lib/define-option.mjs';
import {OPTION_REGISTRY} from '../../../../lib/registries/option-registry.mjs';
import {validateNodeOption} from '../../../../lib/util/validate-workflow.mjs';
import type {NodeOption, NodeOptionBase} from '../../../../public_api';
import useTippy from '../../../hooks/tippy.mjs';
import Td from '../../td';
import {ProvideNodeValidationCtx} from './node-option-validation-ctx';
const RenderNodeOption = memo<OptionRenderEditCtx<any, any>>(function RenderNodeOption({option: opt, ...rest}) {
const spec = OPTION_REGISTRY.get(opt.type);
return (
<tr>
{spec
? <Inner spec={spec} option={opt} {...rest}/>
: <Err type={opt.type}/>
}
</tr>
);
});
export default RenderNodeOption;
interface InnerProps extends OptionRenderEditCtx<any, any> {
spec: OptionDefinition<any, any>;
}
function Inner({option: opt, otherValues, spec, value, onChange: onChangeOut}: InnerProps): VNode {
const errors = useMemo(() => signal(validateNodeOption(value, spec, opt, otherValues)), []);
const touched = useSignal(false);
const invalid = useComputed(() => errors.value.length !== 0);
const onChange = useCallback((v?: any): void => {
onChangeOut(v);
const newErrors = validateNodeOption(v, spec, opt, otherValues);
if (!shallowEquals(newErrors, errors.peek())) {
errors.value = newErrors;
}
}, [otherValues, spec, opt, onChangeOut]);
const hasLabel = spec.hasLabel ?? true;
return (
<ProvideNodeValidationCtx errors={errors} touched={touched} invalid={invalid}>
{hasLabel && h(Label, opt)}
{/* eslint-disable-next-line @typescript-eslint/no-magic-numbers */}
<Td colSpan={hasLabel ? 1 : 2} class={touched.value ? 'ActionWorkflowsCore-touched' : ''}>
<div class={invalid.value ? 'ActionWorkflowsCore-f-invalid' : ''}>
{h(spec.renderEdit, {onChange, option: opt, otherValues, value})}
</div>
{invalid.value && <Errors errors={errors.value}/>}
</Td>
</ProvideNodeValidationCtx>
);
}
Inner.displayName = 'RenderNodeOptionInner';
function Label(opt: NodeOption): VNode {
return (
<Td>
{opt.description && <NodeOptionDesc description={opt.description}/>}
{(opt as Partial<NodeOptionBase>).required && <span class={'mr-1'}>{'*'}</span>}
<span>{opt.label}</span>
</Td>
);
}
Label.displayName = 'RenderNodeOptionLabel';
function Errors({errors}: {errors: string[]}): VNode {
return (
<div class={'text-danger ActionWorkflowsCore-err-render'}>
{errors.map((e, idx) => <div key={idx}>{e}</div>)}
</div>
);
}
Errors.displayName = 'RenderNodeOptionErrors';
export function NodeOptionDesc({description}: Pick<NodeOption, 'description'>): VNode {
const el = useTippy(description);
return (<i ref={el} class={'fa fa-question-circle mr-1'}/>);
}
function Err({type}: Pick<NodeOption, 'type'>): VNode {
return (<td colSpan={2} class={'text-danger'}>{`Unregistered option type: ${String(type)}`}</td>);
}
Err.displayName = 'RenderNodeOptionErr';
|
package com.dgomes.financas.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;
import java.time.LocalDate;
@Entity //Defino que essa classe representa uma entidade no banco de dados
@Table(name = "usuario", schema = "financas")
@Data //Define todos os métodos padrão para operações
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Usuario {
@Column @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String nome;
@Column
private String email;
@Column
private String senha;
@Column
@Convert(converter = Jsr310JpaConverters.LocalDateConverter.class) //necessário para traduzir o localdate do java para um formato aceito pelo BD
private LocalDate data_cadastro;
}
|
#pragma once
#include <string_view>
using namespace std::string_view_literals;
// https://cloud.tencent.com/developer/article/1347876
namespace cpp17::fold_expression
{
/**
* 一元左折叠(unary left fold)
* ( ... op pack )
* 一元左折叠(... op E)展开之后变为 ((E1 op E2) op ...) op En
*
* 一元右折叠(unary right fold)
* ( pack op ... )
* 一元右折叠(E op ...)展开之后变为 E1 op (... op (EN-1 op En))
*
* 二元左折叠(binary left fold)
* ( init op ... op pack )
* 二元左折叠(I op ... op E)展开之后变为 (((I op E1) op E2) op ...) op En
*
* 二元右折叠(binary right fold)
* ( pack op ... op init )
* 二元右折叠(E op ... op I)展开之后变为 E1 op (... op (EN−1 op (EN op I)))
*
* 支持一下32种操作符:
* + - * / % ^ & | = < > << >> += -= *= /= %= ^= &= |= <<= >>= == != <= >= && || , .* ->*
*/
// 一元左/右折叠
// 参数包...在操作符左边为左折叠
template <typename... Args>
constexpr auto sub_val_left(Args&&... args)
{
return (... - args);
}
template <typename... Args>
constexpr auto sub_val_right(Args&&... args)
{
return (args - ...);
}
template <typename... Args>
constexpr auto sub_one_left(Args&&... args)
{
return (1 - ... - args);
}
template <typename... Args>
constexpr auto sub_one_right(Args&&... args)
{
return (args - ... - 1);
}
template <typename... Args>
auto printer1(Args&&... args)
{
((cout << args << " "), ...) << endl;
}
template <typename... Args>
auto printer2(Args&&... args)
{
(cout << ... << args) << endl;
}
auto main()
{
constexpr auto r1 = sub_val_left(2, 3, 4); // ((2-3)-4) = -5
constexpr auto r2 = sub_val_right(2, 3, 4); // (2-(3-4)) = 3
constexpr auto r3 = sub_one_left(2, 3, 4); // (((1-2)-3)-4) = -8
constexpr auto r4 = sub_one_right(2, 3, 4); // (2-(3-(4-1)) = 2
printer1("name"sv, "yeting"sv, "age"sv, 18); // (cout << "name" << " "), ("yeting"), ("age"), (18)
printer2("name"sv, "yeting"sv, "age"sv, 18);
}
}
|
<template>
<form @submit.prevent="createUser">
<h2>Create User</h2>
<input type="text" placeholder="First Name" required v-model="firstName">
<input type="text" placeholder="Last Name" required v-model="lastName">
<button>Submit</button>
</form>
<hr>
<p v-for="user in users" :key="user.firstName">
{{user.firstName}} {{user.lastName}}
</p>
</template>
<script>
import { collection, addDoc, onSnapshot } from 'firebase/firestore'
import {db} from './firebase/init';
export default {
data() {
return {
firstName: '',
lastName: '',
users: []
}
},
created() {
this.createUser();
this.getUsers();
},
methods: {
async createUser() {
const dataObj = {firstName: this.firstName, lastName: this.lastName}
await addDoc(collection(db, 'users'), dataObj)
},
async getUsers() {
onSnapshot(collection(db, 'users'), snap => {
this.users = []
snap.forEach(doc => this.users.push(doc.data()))
})
}
}
}
</script>
|
/*
* Copyright (C) 2017-2018 Tauri JayD <https://www.>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __XUI_UI_LAYOUT_DOCK_LAYOUT_ANCHOR_SIDE_H__
#define __XUI_UI_LAYOUT_DOCK_LAYOUT_ANCHOR_SIDE_H__
#include "UI/LayoutDock/Layouts/LayoutGroup.h"
#include "UI/LayoutDock/Layouts/LayoutAnchorGroup.h"
namespace XUI::UI
{
class LayoutAnchorSide : public LayoutGroup<LayoutAnchorGroup>
{
private:
AnchorSide _side = AnchorSide::Top;
void UpdateSide();
public:
LayoutAnchorSide();
virtual ~LayoutAnchorSide();
PROPERTY_(AnchorSide, Side);
AnchorSide GetSide() const { return _side; }
void SetSide(AnchorSide side)
{
_side = side;
NotifyPropertyChanged::RaisePropertyChanged("Side");
}
// Inherited via LayoutGroup
virtual bool GetVisibility() override;
protected:
void OnParentChanged(LayoutContainer* oldValue, LayoutContainer* newValue) override
{
LayoutGroup<LayoutAnchorGroup>::OnParentChanged(oldValue, newValue);
UpdateSide();
}
};
}
#endif //!__XUI_UI_LAYOUT_DOCK_LAYOUT_ANCHOR_SIDE_H__
|
import React, { FC } from 'react'
import { Container, Text } from '@components/ui'
import { IoArrowForward } from 'react-icons/io5'
import s from './Hero.module.css'
import Link from 'next/link'
interface HeroProps {
className?: string
headline: string
description: string
}
const Hero: FC<HeroProps> = ({ headline, description }) => {
return (
<div className="bg-accent-1 border-y ">
<Container>
<div className={s.root}>
<Text className={s.title} variant="pageHeading">
{headline}
</Text>
<div className={s.description}>
<Text variant="body">{description}</Text>
<Link href="/services">
<a className="flex items-center text-accent-9 pt-3 font-bold hover:underline cursor-pointer w-max-content">
En savoir plus
<IoArrowForward width="20" height="20" className="ml-1" />
</a>
</Link>
</div>
</div>
</Container>
</div>
)
}
export default Hero
|
package int256
import (
"gno.land/p/demo/uint256"
)
// Or sets z = x | y and returns z.
func (z *Int) Or(x, y *Int) *Int {
if x.neg == y.neg {
if x.neg {
// (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
x1 := new(uint256.Uint).Sub(x.abs, one)
y1 := new(uint256.Uint).Sub(y.abs, one)
z.abs = z.abs.Add(z.abs.And(x1, y1), one)
z.neg = true // z cannot be zero if x and y are negative
return z
}
// x | y == x | y
z.abs = z.abs.Or(x.abs, y.abs)
z.neg = false
return z
}
// x.neg != y.neg
if x.neg {
x, y = y, x // | is symmetric
}
// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
y1 := new(uint256.Uint).Sub(y.abs, one)
z.abs = z.abs.Add(z.abs.AndNot(y1, x.abs), one)
z.neg = true // z cannot be zero if one of x or y is negative
return z
}
// And sets z = x & y and returns z.
func (z *Int) And(x, y *Int) *Int {
if x.neg == y.neg {
if x.neg {
// (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
x1 := new(uint256.Uint).Sub(x.abs, one)
y1 := new(uint256.Uint).Sub(y.abs, one)
z.abs = z.abs.Add(z.abs.Or(x1, y1), one)
z.neg = true // z cannot be zero if x and y are negative
return z
}
// x & y == x & y
z.abs = z.abs.And(x.abs, y.abs)
z.neg = false
return z
}
// x.neg != y.neg
// REF: https://cs.opensource.google/go/go/+/refs/tags/go1.22.1:src/math/big/int.go;l=1192-1202;drc=d57303e65f00b84b528ee682747dbe1fd3316d30
if x.neg {
x, y = y, x // & is symmetric
}
// x & (-y) == x & ^(y-1) == x &^ (y-1)
y1 := new(uint256.Uint).Sub(y.abs, uint256.One())
z.abs = z.abs.AndNot(x.abs, y1)
z.neg = false
return z
}
// Rsh sets z = x >> n and returns z.
// OBS: Different from original implementation it was using math.Big
func (z *Int) Rsh(x *Int, n uint) *Int {
if !x.neg {
z.abs.Rsh(x.abs, n)
z.neg = x.neg
return z
}
// REF: https://cs.opensource.google/go/go/+/refs/tags/go1.22.1:src/math/big/int.go;l=1118-1126;drc=d57303e65f00b84b528ee682747dbe1fd3316d30
t := NewInt(0).Sub(FromUint256(x.abs), NewInt(1))
t = t.Rsh(t, n)
_tmp := t.Add(t, NewInt(1))
z.abs = _tmp.Abs()
z.neg = true
return z
}
// Lsh sets z = x << n and returns z.
func (z *Int) Lsh(x *Int, n uint) *Int {
z.abs.Lsh(x.abs, n)
z.neg = x.neg
return z
}
|
%%loading of ECG signal through dataset
load('100m.mat')
base = 0;
gain = 200;
fs = 200; %sampling frequency
val = (val-base)/gain; %converting a raw ECG signal into normal signal
t = 0:1/fs:(length(val)-1)/fs; %sampling
figure(1)
plot(t,val)
title('Original Raw ECG Signal');
%%%High Pass Filter
fpass = 0.5; %cut-off frequency
y = highpass(val(1,:),fpass,fs);%High Pass Filter
figure(2)
plot(t,y)
title('High Pass Filtered Signal');
%%%Notch Filter
Fs = 1000;
%Notch Filter Designing
d = designfilt('bandstopiir','FilterOrder',2, ...
'HalfPowerFrequency1',59,'HalfPowerFrequency2',61, ...
'DesignMethod','butter','SampleRate',Fs);
%Notch Filtering
buttLoop = filtfilt(d,y);
figure(3)
plot(t,y,t,buttLoop)
title('Notch Filtered Signal');
legend('Unfiltered','Filtered')
%%QRS Peak Detection
%Using Statistical False Peak Elimination
%
% 1st denoising with median filter 100 ms sliding window
ECG = buttLoop;
s_win1 = 0:1/fs:0.01; % 1st sliding window = 100ms
mf1 = medfilt1(ECG, length(s_win1)-1); % apply median filter
% 2nd denoising with median filter (200ms sliding window)
s_win2 = 0:1/fs:0.02; %sliding window 2 = 200 ms
mf2 = medfilt1(ECG, length(s_win2)-1); % apply median filter
figure(4);
plot(t, mf2);title('Denoised ECG with median filter of 200ms sliding window ');
xlabel("Time (s)")
ylabel("ECG Amplitude (mV)")
%% Initialize
qrs_c = zeros(1,0); %amplitude of R % TMW add, was qrs_c = [];
qrs_i = zeros(1,0); %amplitude of R % TMW add, was qrs_i = [];
coder.varsize('qrs_c','qrs_i'); % TMW add
SIG_LEV = 0;
nois_c =[];
nois_i =[];
delay = 0;
skip = 0; % becomes one when a T wave is detected
not_nois = 0; % it is not noise when not_nois = 1
selected_RR =[]; % Selected RR intervals
m_selected_RR = 0;
mean_RR = 0;
qrs_i_raw =[];
qrs_amp_raw=[];
ser_back = 0;
test_m = 0;
SIGL_buf = [];
NOISL_buf = [];
THRS_buf = [];
SIGL_buf1 = [];
NOISL_buf1 = [];
THRS_buf1 = [];
%% Noise cancelation(Filtering) % Filters (Filter in between 5-15 Hz)
if fs == 200
%% Low Pass Filter H(z) = ((1 - z^(-6))^2)/(1 - z^(-1))^2
b = [1 0 0 0 0 0 -2 0 0 0 0 0 1];
a = [1 -2 1];
h_l = filter(b,a,[1 zeros(1,12)]);
ecg_l = conv (mf2 ,h_l);
ecg_l = ecg_l/ max( abs(ecg_l));
delay = 9;
%% High Pass filter H(z) = (-1+32z^(-16)+z^(-32))/(1+z^(-1))
b = [-1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 -32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1];
a = [1 -1];
h_h = filter(b,a,[1 zeros(1,32)]);
ecg_h = conv (ecg_l ,h_h);
ecg_h = ecg_h/ max( abs(ecg_h));
delay = delay + 11;
else
%% bandpass filter for Noise cancelation of other sampling frequencies(Filtering)
fs = 400; % TMW add: butter's inputs must be constants
f1=5; %cuttoff low frequency to get rid of baseline wander
f2=15; %cuttoff frequency to discard high frequency noise
Wn=[f1 f2]*2/fs; % cutt off based on fs
N = 3; % order of 3 less processing
[a,b] = butter(N,Wn); %bandpass filtering
ecg_h = filtfilt(a,b,mf2);
ecg_h = ecg_h/ max( abs(ecg_h));
end
%% derivative filter H(z) = (1/8T)(-z^(-2) - 2z^(-1) + 2z + z^(2))
h_d = [-1 -2 0 2 1]*(1/8);%1/8*fs
ecg_d = conv (ecg_h ,h_d);
ecg_d = ecg_d/max(ecg_d);
delay = delay + 2;
%% Squaring nonlinearly enhance the dominant peaks
ecg_s = ecg_d.^2;
%% Moving average Y(nt) = (1/N)[x(nT-(N - 1)T)+ x(nT - (N - 2)T)+...+x(nT)]
ecg_m = conv(ecg_s ,ones(1 ,round(0.150*fs))/round(0.150*fs));
delay = delay + 15;
figure(5);
plot(ecg_m);title('moving average filtered output');
figure(6);
findpeaks(ecg_m,'MinPeakProminence',0.1)
figure(7);
% Show all peaks in the original ecg signal
findpeaks(ECG,'MinPeakProminence',0.5)
xlabel('Samples')
ylabel('Amplitude')
title('Detecting Peaks')
|
<!---
Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
# Official Hugging Face Accelerate Docker Images
Accelerate publishes a variety of docker versions as part of our CI that users can also use. These are stable images that Accelerate can run off of which comes with a variety of different setup configurations, all of which are officially hosted on [Docker Hub](https://hub.docker.com/r/huggingface/accelerate).
A breakdown of each are given below
## Naming Conventions
Accelerate docker images follow a tagging convention of:
```bash
huggingface/accelerate:{accelerator}-{nightly,release}
```
`accelerator` in this instance is one of many applical pre-configured backend supports:
* `gpu`: Comes compiled off of the `nvidia/cuda` image and includes everything such as `deepspeed`, `bitsandbytes`, etc.
* `cpu`: Comes compiled off of `python:3.8-slim` and is designed for non-CUDA based workloads.
* More to come soon
## Nightlies vs Releases
Each release a new build is pushed with a version number included in the name. For a GPU-supported image of version 0.28.0 for instance, it would look like the following:
```bash
huggingface/accelerate:gpu-release-0.28.0
```
Nightlies contain two different image tags. There is a general `nightly` tag which is built each night, and a `nightly-YYYY-MM-DD` which corresponds to a build from a particular date.
For instance, here is an example nightly CPU image from 3/14/2024
```bash
huggingface/accelerate:cpu-nightly-2024-03-14
```
## Running the images
Each image comes compiled with `conda` and an `accelerate` environment contains all of the installed dependencies.
To pull down the latest nightly run:
```bash
docker pull huggingface/accelerate:gpu-nightly
```
To then run it in interactive mode with GPU-memory available, run:
```bash
docker container run --gpus all -it huggingface/accelerate:gpu-nightly
```
## DEPRECATED IMAGES
CPU and GPU docker images were hosted at `huggingface/accelerate-gpu` and `huggingface/accelerate-cpu`. These builds are now outdated and will not receive updates.
The builds at the corresponding `huggingface/accelerate:{gpu,cpu}` contain the same `Dockerfile`, so it's as simple as changing the docker image to the desired ones from above. We will not be deleting these images for posterity, but they will not be receiving updates going forward.
|
// Ravelry Connector - to help connecting with the Ravelry API: https://www.ravelry.com/api
// (C) 2022 by Marco Nissen
import Foundation
import OAuthSwift
public extension RavelryEnvironment {
func addFavoriteToBundle(username: String,
identifier: Int,
bundle_id: Int,
completedRequest: @escaping (_ json: [String: Any]?) -> Void) {
var parameters = OAuthSwift.Parameters()
parameters["bundle_id"] = bundle_id
postSimpleRequest(url: "\(baseURI)/people/\(username)/favorites/\(identifier)/add_to_bundle.json", parameters: parameters, completedRequest: completedRequest, failure: { (err) in
if err != nil { print ("error in post request: \(err!.description)") }
})
}
func createFavorite(username: String,
data: OAuthSwift.Parameters,
completedRequest: @escaping (_ json: [String: Any]?) -> Void) {
postSimpleRequest(url: "\(baseURI)/people/\(username)/favorites/create.json", parameters: data, completedRequest: completedRequest, failure: { (err) in
if err != nil { print ("error in post request: \(err!.description)") }
})
}
func deleteFavorite(username: String, identifier: Int, completedRequest: @escaping (_ json: [String: Any]?) -> Void) {
deleteSimpleRequest(url: "\(baseURI)/people/\(username)/favorites/\(identifier).json", completedRequest: completedRequest)
}
func getFavoriteList(username: String, types: [String], query: String, deep_search: Bool, page: Int, page_size: Int,
completedRequest: @escaping (_ json: [[String: Any]]?, _ pageCount: Int, _ page: Int, _ pageSize: Int, _ lastPage: Int, _ results: Int) -> Void) {
var parameters = OAuthSwift.Parameters()
parameters["types"] = types.joined(separator: " ")
parameters["query"] = query
parameters["deep_search"] = deep_search
parameters["page"] = page
parameters["page_size"] = page_size
getPaginatedRequest(resultsKey: "favorites", url: "\(baseURI)/people/\(username)/favorites/list.json", parameters: parameters, username: username, completedRequest: completedRequest)
}
func getFavoriteList(username: String, types: [String], deep_search: Bool, tag: String, page: Int, page_size: Int,
completedRequest: @escaping (_ json: [[String: Any]]?, _ pageCount: Int, _ page: Int, _ pageSize: Int, _ lastPage: Int, _ results: Int) -> Void) {
var parameters = OAuthSwift.Parameters()
parameters["types"] = types.joined(separator: " ")
parameters["deep_search"] = deep_search
parameters["tag"] = tag
parameters["page"] = page
parameters["page_size"] = page_size
getPaginatedRequest(resultsKey: "favorites", url: "\(baseURI)/people/\(username)/favorites/list.json", parameters: parameters, username: username, completedRequest: completedRequest)
}
func removeFavoriteFromBundle(username: String,
identifier: Int,
bundle_id: Int,
completedRequest: @escaping (_ json: [String: Any]?) -> Void) {
var parameters = OAuthSwift.Parameters()
parameters["bundle_id"] = bundle_id
postSimpleRequest(url: "\(baseURI)/people/\(username)/favorites/\(identifier)/remove_from_bundle.json", parameters: parameters, completedRequest: completedRequest, failure: { (err) in
if err != nil { print ("error in post request: \(err!.description)") }
})
}
func showFavorite(username: String, identifier: Int,
completedRequest: @escaping (_ json: [String: Any]?) -> Void) {
getSimpleRequest(url: "\(baseURI)/people/\(username)/favorites/\(identifier).json",
completedRequest: completedRequest)
}
func updateFavorite(username: String,
identifier: Int,
data: OAuthSwift.Parameters,
completedRequest: @escaping (_ json: [String: Any]?) -> Void) {
postSimpleRequest(url: "\(baseURI)/people/\(username)/favorites/\(identifier).json", parameters: data, completedRequest: completedRequest, failure: { (err) in
if err != nil { print ("error in post request: \(err!.description)") }
})
}
}
|
import { useEffect, useState } from 'react';
import GuestLayout from '@/Layouts/GuestLayout';
import InputError from '@/Components/InputError';
import InputLabel from '@/Components/InputLabel';
import PrimaryButton from '@/Components/PrimaryButton';
import TextInput from '@/Components/TextInput';
import { Head, Link, useForm } from '@inertiajs/react';
export default function Register({ blocked, remainingTime }) {
const { data, setData, post, processing, errors, reset } = useForm({
name: '',
email: '',
password: '',
password_confirmation: '',
});
const [isBlocked, setIsBlocked] = useState(blocked);
const [timeLeft, setTimeLeft] = useState(remainingTime);
useEffect(() => {
let timer;
if (isBlocked && timeLeft > 0) {
timer = setInterval(() => {
setTimeLeft((prevTime) => {
if (prevTime <= 1) {
setIsBlocked(false);
return 0;
}
return prevTime - 1;
});
}, 1000);
}
return () => clearInterval(timer);
}, [isBlocked, timeLeft]);
useEffect(() => {
// If remainingTime prop changes, we need to reset the timer
if (blocked && remainingTime > 0) {
setIsBlocked(true);
setTimeLeft(remainingTime);
}
}, [blocked, remainingTime]);
useEffect(() => {
return () => {
reset('password', 'password_confirmation');
};
}, []);
const submit = (e) => {
e.preventDefault();
post(route('register'));
};
return (
<GuestLayout>
<Head title="Register" />
{isBlocked ? (
<div className="text-red-500">
Too many attempts. Please try again in {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')} minutes.
</div>
) : (
<form onSubmit={submit}>
<div>
<InputLabel htmlFor="name" value="Name" />
<TextInput
id="name"
name="name"
value={data.name}
className="mt-1 block w-full"
autoComplete="name"
isFocused={true}
onChange={(e) => setData('name', e.target.value)}
required
disabled={isBlocked}
/>
<InputError message={errors.name} className="mt-2" />
</div>
<div className="mt-4">
<InputLabel htmlFor="email" value="Email" />
<TextInput
id="email"
type="email"
name="email"
value={data.email}
className="mt-1 block w-full"
autoComplete="username"
onChange={(e) => setData('email', e.target.value)}
required
disabled={isBlocked}
/>
<InputError message={errors.email} className="mt-2" />
</div>
<div className="mt-4">
<InputLabel htmlFor="password" value="Password" />
<TextInput
id="password"
type="password"
name="password"
value={data.password}
className="mt-1 block w-full"
autoComplete="new-password"
onChange={(e) => setData('password', e.target.value)}
required
disabled={isBlocked}
/>
<InputError message={errors.password} className="mt-2" />
</div>
<div className="mt-4">
<InputLabel htmlFor="password_confirmation" value="Confirm Password" />
<TextInput
id="password_confirmation"
type="password"
name="password_confirmation"
value={data.password_confirmation}
className="mt-1 block w-full"
autoComplete="new-password"
onChange={(e) => setData('password_confirmation', e.target.value)}
required
disabled={isBlocked}
/>
<InputError message={errors.password_confirmation} className="mt-2" />
</div>
<div className="flex items-center justify-end mt-4">
<Link
href={route('login')}
className="underline text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800"
>
Already registered?
</Link>
<PrimaryButton className="ms-4" disabled={processing || isBlocked}>
Register
</PrimaryButton>
</div>
</form>
)}
</GuestLayout>
);
}
|
public class TestWithJUnit {
/* Method withoutTen:
* Return a version of the given array where all
* the 10's have been removed.
* The remaining elements should shift left
* towards the start of the array as needed,
* and the empty spaces a the end of the array
* should be 0.
* So {1, 10, 10, 2} yields {1, 2, 0, 0}.
* {1, 10, 10, 2, 10, 3, 10} yields {1, 2, 3, 0, 0, 0, 0}.
*/
public int[] withoutTen(int[] A) {
int[] result = new int[A.length];
int index = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] != 10) {
result[index] = A[i];
index++;
}
}
for (int i = index; i < result.length; i++)
result[i] = 0;
return result;
}
/* Method bigArray:
* Given an integer n, bigArray creates and returns a 1D array
* that contains {1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, ... n}
* For instance, bigArray(4) = {1, 1, 2, 1, 2, 3, 1, 2, 3, 4}
* bigArray(2) = {1, 1, 2}
*/
public int[] bigArray(int n) {
int[] result = new int[n*(n+1)/2];
int index = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
result[index] = j;
index++;
}
}
return result;
}
}
|
package com.kh.spring.shop.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kh.spring.shop.repository.ProductRepository;
import com.kh.spring.shop.vo.Product;
import jakarta.transaction.Transactional;
@Service
public class ProductService {
//멤버(필드)변수
private final ProductRepository productRepository;
@Autowired
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
//상품 전체 조회 서비스
public List<Product> getAllProducts(){
return productRepository.findAll();
}
//상품 상세 조회 by Id
public Optional<Product> getProductById(Long id){
return productRepository.findById(id);
}
//상품 정보 수정(저장) 서비스
@Transactional
public Product saveProduct(Product product) {
return productRepository.save(product);
}
//상품 삭제 서비스
public void deleteProductById(Long id) {
productRepository.deleteById(id);
}
}
|
package com.bearxyz.controller;
import com.bearxyz.common.DataTable;
import com.bearxyz.common.PaginationCriteria;
import com.bearxyz.domain.po.business.Goods;
import com.bearxyz.domain.po.business.Purchasing;
import com.bearxyz.domain.po.business.Replenishment;
import com.bearxyz.domain.po.business.ReplenishmentItem;
import com.bearxyz.domain.po.sys.User;
import com.bearxyz.service.business.GoodsService;
import com.bearxyz.service.business.ReplenishmentService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
/**
* Created by bearxyz on 2017/9/2.
*/
@Controller
@RequestMapping("/replenishment")
@SessionAttributes("replenishment")
public class ReplenishmentController {
@Autowired
private ReplenishmentService service;
@Autowired
private GoodsService goodsService;
@Autowired
private TaskService taskService;
@RequestMapping(value = "/complete")
public String complete(@RequestParam("bid") String bid, @RequestParam("tid") String tid, @RequestParam("applyer") String applyer, Model model) {
Replenishment purchasing = service.getOneById(bid);
for (ReplenishmentItem item : purchasing.getItems()) {
Goods goods = goodsService.getById(item.getGoodsId());
item.setGoods(goods);
}
String memo = "";
model.addAttribute("replenishment", purchasing);
model.addAttribute("applyer", applyer);
Task task = taskService.createTaskQuery().taskId(tid).singleResult();
if (!task.getTaskDefinitionKey().equals("deptLeader")&&taskService.getVariable(task.getId(), "deptLeaderMemo") != null)
memo = taskService.getVariable(task.getId(), "deptLeaderMemo").toString();
model.addAttribute("taskId", tid);
model.addAttribute("taskKey", task.getTaskDefinitionKey());
model.addAttribute("memo", memo);
return "/replenishment/complete";
}
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "/replenishment/index";
}
@ResponseBody
@RequestMapping(value = "/index", method = RequestMethod.POST)
public String getList(@RequestBody PaginationCriteria req) throws JsonProcessingException {
User user = (User) SecurityUtils.getSubject().getPrincipal();
DataTable<Replenishment> purchasing = service.getReplenishment(user.getId(), null, req);
purchasing.setDraw(req.getDraw());
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(purchasing);
}
@RequestMapping(value = "/apply", method = RequestMethod.GET)
public String create(Model model) {
model.addAttribute("replenishment", new Replenishment());
return "/replenishment/apply";
}
@RequestMapping(value = "/apply", method = RequestMethod.POST)
@ResponseBody
public String doCreate(@ModelAttribute("replenishment") Replenishment replenishment, SessionStatus status) {
service.apply(replenishment);
status.setComplete();
return "{success: true}";
}
@RequestMapping(value = "/reApply/{id}", method = RequestMethod.GET)
public String reApply(@PathVariable("id") String id, Model model) {
Replenishment replenishment = service.getOneById(id);
for (ReplenishmentItem item : replenishment.getItems()) {
Goods goods = goodsService.getById(item.getGoodsId());
item.setGoods(goods);
}
String deptMemo = "";
String managerMemo = "";
Task task = taskService.createTaskQuery().processInstanceBusinessKey(id).singleResult();
if (taskService.getVariable(task.getId(), "deptLeaderMemo") != null)
deptMemo = taskService.getVariable(task.getId(), "deptLeaderMemo").toString();
if (taskService.getVariable(task.getId(), "managerMemo") != null)
managerMemo = taskService.getVariable(task.getId(), "managerMemo").toString();
model.addAttribute("replenishment", replenishment);
model.addAttribute("taskId", task.getId());
model.addAttribute("deptMemo", deptMemo);
model.addAttribute("managerMemo", managerMemo);
return "/replenishment/reApply";
}
@RequestMapping(value = "/reApply", method = RequestMethod.POST)
@ResponseBody
public String doReApply(@ModelAttribute("replenishment") Replenishment replenishment, SessionStatus status) {
service.save(replenishment);
status.setComplete();
return "{success: true}";
}
@RequestMapping(value = "/del", method = RequestMethod.POST)
@ResponseBody
public String delete(String id) {
service.deleteItemById(id);
return "{success: true}";
}
}
|
import {
Body,
Delete,
Post,
Put,
Query,
Request,
UseGuards,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { Controller, Get, Param } from '@nestjs/common';
import { messageError } from 'src/common/utils/error';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
import { OrderService } from './order.service';
import { AddOrderDTO } from './dto/add-order.dto';
import { UpdateOrderDTO } from './dto/update-product.dto';
import { Roles } from 'src/auth/roles.decorator';
import { JwtAuthGuard } from 'src/auth/guard/jwt-auth.guard';
import { RolesGuard } from 'src/auth/guard/roles.guard';
import { Role } from 'src/common/enum/filter.enum';
@Controller('api/order')
@UsePipes(
new ValidationPipe({
skipMissingProperties: true,
forbidNonWhitelisted: true,
whitelist: true,
}),
)
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.Admin)
export class OrderController {
constructor(private orderService: OrderService) {}
@Post()
async create(@Request() req, @Body() orderDTO: AddOrderDTO) {
try {
const result = await this.orderService.create(orderDTO);
return {
message: 'Create Order successfully',
data: result,
};
} catch (error) {
messageError(error);
}
}
@Get()
async getList(@Request() req, @Query() queryDto: PaginationQueryDto) {
try {
const result = await this.orderService.getList(queryDto);
return result;
} catch (error) {
messageError(error);
}
}
@Get('/:orderId')
async getDetail(@Request() req, @Param('orderId') orderId: string) {
try {
const result = await this.orderService.getDetail(orderId);
return { data: result };
} catch (error) {
messageError(error);
}
}
@Delete('/:orderId')
async delete(@Request() req, @Param('orderId') orderId: string) {
try {
await this.orderService.delete(orderId);
return { message: 'Delete Order successfully' };
} catch (error) {
messageError(error);
}
}
// Make Order (Customer, Product, Quantity)
@Put('/:orderId')
async update(
@Request() req,
@Body() orderDTO: UpdateOrderDTO,
@Param('orderId') orderId: string,
) {
try {
const result = await this.orderService.update(orderId, orderDTO);
return {
message: 'Update Order successfully',
data: result,
};
} catch (error) {
messageError(error);
}
}
}
|
package eleMentalClinic::Client::AssessmentTemplate::Field;
use strict;
use warnings;
=head1 NAME
eleMentalClinic::Client::AssessmentTemplate::Field
=head1 SYNOPSIS
A user-configurable template system
=head1 METHODS
=cut
use base qw(eleMentalClinic::DB::Object);
use eleMentalClinic::Util;
sub primary_key { 'rec_id' }
sub table { 'assessment_template_fields' }
# Documentation for this special 'fields' declaration is in 000db.t
# Essentially it acts as a normal 'fields' declaration except on initial object insert.
sub fields {
my $self = shift;
my ( $insert_queries ) = @_;
return [qw/rec_id label position field_type assessment_template_section_id choices/]
unless $insert_queries;
return {
position => {
insert_query => 'SELECT (MAX(position) + 1) FROM '.
eleMentalClinic::Client::AssessmentTemplate::Field->table .
' WHERE assessment_template_section_id = ?',
default => 0,
params => [ $self->assessment_template_section_id ],
}
};
}
sub get_one_by_position_in_section {
my $self = shift;
my ( $position, $section ) = @_;
$section = $section->rec_id if ref $section;
return unless $section and defined $section;
my $results = $self->db->select_one(
[ $self->primary_key ],
$self->table,
[
'position = ? AND assessment_template_section_id = ?',
$position || 0, $section
]
);
return unless $results;
return $self->retrieve( $results->{ $self->primary_key });
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=head2 clone( section_id )
Object method.
Clone this field into the specified section
=cut
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
sub clone {
my $self = shift;
my $class = ref $self;
my ( $id ) = @_;
my $new = $class->new({
label => $self->label,
choices => $self->choices,
position => $self->position,
field_type => $self->field_type,
assessment_template_section_id => $id,
});
$new->save;
return $class->retrieve( $new->rec_id );
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=head2 list_choices()
Object method.
List available choices.
=cut
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
sub list_choices {
my $self = shift;
return ['', split(/\s*,\s*/, $self->choices || "" )];
}
'eleMental';
__END__
=head1 AUTHORS
=over 4
=item Chad Granum L<chad@opensourcery.com>
=item Erik Hollensbe L<erikh@opensourcery.com>
=item Randall Hansen L<randall@opensourcery.com>
=back
=head1 BUGS
We strive for perfection but are, in fact, mortal. Please see
L<https://prefect.opensourcery.com:444/projects/elementalclinic/report/1> for
known bugs.
=head1 SEE ALSO
=over 4
=item Project web site at: L<http://elementalclinic.org>
=item Code management site at: L<https://prefect.opensourcery.com:444/projects/elementalclinic/>
=back
=head1 COPYRIGHT
Copyright (C) 2004-2007 OpenSourcery, LLC
This file is part of eleMental Clinic.
eleMental Clinic is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option) any
later version.
eleMental Clinic is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
Street, Fifth Floor, Boston, MA 02110-1301 USA.
eleMental Clinic is packaged with a copy of the GNU General Public License.
Please see docs/COPYING in this distribution.
=cut
|
# 基本概念
## 表格和键
举例:

这样一个表,一行表示一条数据,一列代表一个属性。

主键(primary key):这个属性可以唯一的表示每一条记录。
外键(foreign key):对应其他表格中的主键。不但可以对应到别的表格,也可以对应回自己的表格。
一个实际的例子

这里的Works_With表存在两个主键,因为这三个属性,不论是哪个属性都不能表示同一条记录,所以此时可以设定两个及以上的主键。这表示,只要把这两个主键属性看在一起,就可以唯一的表示每一条记录。
这两个主键还同样都是外键,都对应其他表格的主键。
## 基本的SQL指令
创建一个数据库
```mysql
CREATE DATABASE `sql_tutorial`;
```
显示所有的数据库
```mysql
SHOW DATABASES;
```
删除特定数据库
```mysql
DROP DATABASE `sql_tutorial`;
```
选择使用的数据库
```mysql
USE `sql_tutorial`;
```
创建数据库中的表格
- 创建表格时需要设定每个属性的数据形态;最常见的6种如下。
INT --整数
DECIMAL(m,n) --有小敷黜的敷(两个参数,第一个参数m表示总共有几位数,第二个参数n代表小数点部分占了几位)
VARCHAR(n) --字符串(1个参数,最多传入几个字节)
BLOB -- (Binary Large Object) 主要用于存放二进制数据的。例如图片 影片 档案...
DATE -- 'YYYY-MM-DD’ 主要用于记录日期;例如2021-08-08
TIMESTAMP -- "YYYY-MM-DD HH : MM: SS’ 主要用于记录时间
假设创建一个STUDENT的表格。
```mysql
CREATE TABLE `student`(
`student_id` INT PRIMARY KEY,
`name` VARCHAR(20),
`major` VARCHAR(20)
);
```
主键的另外一种写法:
```mysql
CREATE TABLE `student`(
`student_id` INT,
`name` VARCHAR(20),
`major` VARCHAR(20),
PRIMARY KEY(`student_id`)
);
```
查看表格
```mysql
DESCRIBE `student`;
```
删除表格
```mysql
DROP TABLE `student`;
```
新增一个GPA的属性
```mysql
ALTER TABLE `student` ADD gpa DECIMAL(3,2);
```
删除一个表格中的GPA的属性
```mysql
ALTER TABLE `student` DROP COLUMN gpa;
```
## 如何存入数据
存入数据。例如,我们想要存入一位学生。id是1,名字是“小白”,主修“历史”。
```mysql
INSERT INTO `student` VALUES(1, "小白", "历史");
```
这句语句表示存入一条记录,到`student`表格里面,三个属性分别是1,小白,历史。
```mysql
INSERT INTO `student` VALUES(2, "小黑", NULL);
```
**注意,INSERT时,PRIMARY KEY不能重复。否则会报错。**
列出所有的数据
```mysql
SELECT * FROM `student`;
```
这句语句表示 搜寻`student`表格里面的所有数据。*表示全部。
自定义填入属性的顺序
```mysql
INSERT INTO `student`(`name`, `major`, `student_id`) VALUES("小蓝", "英语", 4);
```
或者:
```mysql
INSERT INTO `student`(`major`, `student_id`) VALUES("英语", 5);
```
若不指定属性,则默认填充为NULL。
## 约束、限制
在创建表格的时候可以为属性添加约束,例如:
```mysql
CREATE TABLE `student`(
`student_id` INT,
`name` VARCHAR(20) NOT NULL,
`major` VARCHAR(20) UNIQUE,
PRIMARY KEY(`student_id`)
);
```
NOT NULL表示这个属性值不可为空,
UNIQUE表示这个属性值不可以重复,唯一。
AUTO_INCREMENT自动增加 可用于ID,
亦可以为DEFAULT指定预设值:
```mysql
CREATE TABLE `student`(
`student_id` INT AUTO_INCREMENT,
`name` VARCHAR(20),
`major` VARCHAR(20) DEFAULT '历史', # 这里用单引号双引号都可以
PRIMARY KEY(`student_id`)
);
```
这样,就可以在新增一条记录时自动将`student_id`属性+1,同时,若不指定`major`属性值则默认为`历史`。
## 修改、删除数据
先把workbench预设的更新模式关闭
```mysql
SET SQL_SAFE_UPDATES = 0;
```
将表格中`major`属性为生物和化学的属性名都改为`生化`。(生物、化学系合并)
```mysql
UPDATE `student`
SET `major` = '生化'
WHERE `major` = '生物' OR `major` = '化学';
```
也可以改变多个属性
```mysql
UPDATE `student`
SET `name` = '小灰', `major` = '物理'
WHERE `student_id` = 1;
```
如果不指定WHERE增加条件,而是:
```mysql
UPDATE `student`
SET `major` = '物理';
```
则会把表格中所有`major`属性改为"物理"。
删除数据的写法和新增的写法类似。
要删除表格`student`中`student_id`为4的数据。
```mysql
DELETE FROM `student`
WHERE `student_id` = 4;
```
同样地。条件也可以是多个:
```mysql
DELETE FROM `student`
WHERE `name` = '小灰' AND `major` = '物理';
```
或者,删除分数小于60的记录:
```mysql
DELETE FROM `student`
WHERE `score` < 60;
```
这里的运算符可以是:
```
> 大于
< 小于
>=/<= 大于等于/小于等于
= 等于
<> 不等于
```
若不指定条件:
```mysql
DELETE FROM `student`;
```
则默认把`student`表格里的所有数据都删除。
## 搜索数据
取得表格`student`中所有数据:
```mysql
SELECT * FROM `student`;
```
这里的*表示所有的属性的意思。

只想取得特定的`name`属性:
```mysql
SELECT `name` FROM `student`;
```


### ORDER BY 获取并排序
可以在获取数据的时候对数据进行排序。
例如,根据学生的成绩排序:
```mysql
SELECT *
FROM `student`
ORDER BY `score`;
```

此时,ORDER BY后面默认省略了 ASC,
若想反向排序,使用DESC:
```mysql
SELECT *
FROM `student`
ORDER BY `score` DESC;
```

ORDER BY后面可以加多个属性,例如:
```mysql
SELECT *
FROM `student`
ORDER BY `score`, `student_id`;
```
意思是,先根据score进行排序,若score属性值相等,再根据student_id属性来排序。
### LIMIT 限定传回条数
如果我们觉得使用SELECT获取数据时,回传回来的数据太多了,不想要那么多条,
我们可以使用LIMIT限定传回的数据条数。

LIMIT也可以和ORDER BY一起使用:

### WHERE 限定获取数据的条件

也可以使用IN关键字:

以上两句作用等同。
### DISTINCT 去重

# 创建一个公司部门的数据库

## 创建所有表格
创建 员工 表格
```mysql
CREATE TABLE `employee`(
`emp_id` INT PRIMARY KEY,
`name` VARCHAR(20),
`birth_date` DATE,
`sex` VARCHAR(1),
`salary` INT,
`branch_id` INT,
`sup_id` INT
);
```
创建 部门 表格
```mysql
CREATE TABLE `branch`(
`branch_id` INT PRIMARY KEY,
`name` VARCHAR(20),
`manager_id` INT,
FOREIGN KEY(`manager_id`) REFERENCES `employee`(`emp_id`) ON DELETE SET NULL
);
```
补充刚刚 员工 表格 中少设定的foreign key
```mysql
ALTER TABLE `employee`
ADD FOREIGN KEY(`branch_id`)
REFERENCES `branch`(`branch_id`)
ON DELETE SET NULL;
ALTER TABLE `employee`
ADD FOREIGN KEY(`sup_id`)
REFERENCES `employee`(`emp_id`)
ON DELETE SET NULL;
```
创建 客户 表格
```mysql
CREATE TABLE `client`(
`client_id` INT PRIMARY KEY,
`client_name` VARCHAR(20),
`phone` VARCHAR(20)
);
```
创建 Works With 表格
```mysql
CREATE TABLE `works_with`(
`emp_id` INT,
`client_id` INT,
`total_sales` INT,
PRIMARY KEY(`emp_id`, `client_id`),
FOREIGN KEY(`emp_id`) REFERENCES `employee`(`emp_id`) ON DELETE CASCADE,
FOREIGN KEY(`client_id`) REFERENCES `client`(`client_id`) ON DELETE CASCADE
);
```
## 向表格中填充数据
由于employee表格和branch表格互相都有外键,所以可以先将外键的部分填为NULL,再做连接。
向 部门 表格中添加数据
```mysql
INSERT INTO `branch` VALUES(1, '研发', NULL);
INSERT INTO `branch` VALUES(2, '行政', NULL);
INSERT INTO `branch` VALUES(3, '资讯', NULL);
```
新增 5条 员工 的数据
```mysql
INSERT INTO `employee` VALUES(206, '小黄', '1998-10-08', 'F', 50000, 1, NULL);
INSERT INTO `employee` VALUES(207, '小绿', '1985-09-16', 'M', 29000, 2, 206);
INSERT INTO `employee` VALUES(208, '小黑', '2000-12-19', 'M', 35000, 3, 206);
INSERT INTO `employee` VALUES(209, '小白', '1997-01-22', 'F', 39000, 3, 207);
INSERT INTO `employee` VALUES(210, '小蓝', '1925-11-10', 'F', 84000, 1, 207);
```
把 部门 表格的 manager_id 改回来
```mysql
UPDATE `branch`
SET `manager_id` = 208
WHERE `branch_id` = 3;
```
新增 客户 数据
```mysql
INSERT INTO `client` VALUES(400, '阿狗', '254354335');
INSERT INTO `client` VALUES(401, '阿猫', '234242423');
INSERT INTO `client` VALUES(402, '旺来', '45234234');
INSERT INTO `client` VALUES(403, '露西', '5312343424');
INSERT INTO `client` VALUES(404, '艾瑞克', '1423432423');
```
新增 works_with 数据
```mysql
INSERT INTO `works_with` VALUES(206, 400, '70000');
INSERT INTO `works_with` VALUES(207, 401, '24000');
INSERT INTO `works_with` VALUES(208, 402, '9800');
INSERT INTO `works_with` VALUES(209, 403, '24000');
INSERT INTO `works_with` VALUES(210, 404, '87940');
```
至此。一个公司的数据库已经获取完毕。
# 练习
练习一下刚刚学习的SQL语句。
1. 取得所有员工资料
2. 取得所有客户资料
3. 按薪水从低到高取得员工资料
4. 取得薪水前3高的员工
5. 取得所有员工的名字
6. 取得所有员工的性别(不重复)
解:
```mysql
SELECT * FROM `employee`;
```
```mysql
SELECT * FROM `client`;
```
```mysql
SELECT *
FROM `employee`
ORDER BY `salary`;
```
```mysql
SELECT *
FROM `employee`
ORDER BY `salary` DESC
LIMIT 3;
```
```mysql
SELECT `name`
FROM `employee`
```
```mysql
SELECT DISTINCT `sex` FROM `employee`;
```
# 聚合函数
可以更方便的获取数据库中的数据。
1. 获取员工人数
2. 获取所有出生于1970-01-01之后的女性员工人数
3. 获取所有员工的平均薪水
4. 获取所有员工薪水的总和
5. 获取薪水最高的员工
6. 获取薪水最低的员工
实现方式如下
1 获取员工人数
```mysql
SELECT COUNT(*) FROM `employee`;
```
这条语句表示,去`employee`这张表格里看有几条记录。
若不使用*而是具体的属性:
```mysql
SELECT COUNT(`sup_id`) FROM `employee`;
```
表示`employee`表格中有这个`sup_id`属性的数据共有几条**(NULL不计数)**。
2 获取所有出生于1970-01-01之后的女性员工人数
```mysql
SELECT COUNT(*)
FROM `employee`
WHERE `birth-date` > '1970-01-01' AND `sex` = 'F';
```
3 获取所有员工的平均薪水
```mysql
SELECT AVG(`salary`) FROM `employee`;
```
这样会算`salary`属性所有值的平均数。
4 获取所有员工薪水的总和
```mysql
SELECT SUM(`salary`) FROM `employee`;
```
5 获取薪水最高的员工
```mysql
SELECT MAX(`salary`) FROM `employee`;
```
6 获取薪水最低的员工
```mysql
SELECT MIN(`salary`) FROM `employee`;
```
# wildcards 通配符
```
% 代表多个字节
_ 代表一个字节
```
1. 获得电话号码尾数是335的客户;
2. 获得姓艾的客户;
3. 获得生日在12月的员工。
实现方式如下:
1 获得电话号码尾数是335的客户;
```mysql
SELECT * FROM `client` WHERE `phone` LIKE `%335`;
```
其中,LIKE是模糊查询。
2 获得姓艾的客户;
```mysql
SELECT * FROM `client` WHERE `client_name` LIKE `艾%`;
```
3 获得生日在12月的员工。
```mysql
SELECT * FROM `client` WHERE `birth_date` LIKE `_____12%`;
```
当然,这里的匹配字符也可以是`%-12-%`等等,根据需求来确定就好。
# union 并集
1. 员工名字 union 客户名字
2. 员工id + 员工名字 union 客户id + 客户名字
3. 员工薪水 union 销售金额
实现方式如下:
1 员工名字 union 客户名字
```mysql
SELECT `name`
FROM `employee`
UNION
SELECT `client_name`
FROM `client`;
```
这样可以把两个查询的结果结合到一起。**相当于UNION把SELECT的合并到一列。**
也可以结合2个以上的多个。
注意:合并时,属性的形态(数据类型)和个数要一致。
2 员工id + 员工名字 union 客户id + 客户名字
```mysql
SELECT `emp_id`, `name`
FROM `employee`
UNION
SELECT `client_id`, `client_name`
FROM `client`;
```
这时回传的属性名称是用的第一个回传的名称。可以使用AS修改回传的属性名:
```mysql
SELECT `emp_id` AS `total_id`, `name` AS `total_name`
FROM `employee`
UNION
SELECT `client_id`, `client_name`
FROM `client`;
```
3 员工薪水 union 销售金额
```mysql
SELECT `salary` AS `total_money`
FROM `employee`
UNION
SELECT `total_sales`
FROM `works_with`;
```
# join 连接
1. 获得所有部门经理的名字
branch表格中,只有部门经理的id,没有名字。因此,可以考虑先拼接表格再获取。
实现方式如下:
```mysql
SELECT *
FROM `employee`
JOIN `branch`
ON `emp_id` = `manager_id`;
```

可是我们需要的只是经理的名字,不需要这么多数据。
```mysql
SELECT `emp_id`, `name`, `branch_name`
FROM `employee`
JOIN `branch`
ON `emp_id` = `manager_id`;
```
如果,存在不同的表格中有相同的属性名,需要用`.`来区分不同的属性来自哪张表:
```mysql
SELECT `emp_id`, `employee`.`name`, `branch`.`name`
FROM `employee`
JOIN `branch`
ON `employee`.`emp_id` = `branch`.`manager_id`;
```
这时,可以用LEFT JOIN:
```mysql
SELECT `emp_id`, `employee`.`name`, `branch`.`name`
FROM `employee` LEFT JOIN `branch`
ON `employee`.`emp_id` = `branch`.`manager_id`;
```
LEFT JOIN的意思是,当我们连接的时候,不管ON后面的条件成不成立,**左边的表格都会回传给我们**,只有当右边的表格只有当条件成立才传回,不成立的地方回传NULL。
RIGHT JOIN同理。
# subquery 子查询
可以在一个查询语句里面使用另外一个查询语句的结果。
可以使用括号。
1. 找出研发部门的经理名字;
2. 找出对单一客户销售金额超过50000的员工名字。
实现方式如下:
1 找出研发部门的经理名字;
```mysql
SELECT `name`
FROM `employee`
WHERE `emp_id` = (
SELECT `manager_id`
FROM `branch`
WHERE `branch_name` = '研发'
);
```
2 找出对单一客户销售金额超过50000的员工名字。
```mysql
SELECT `name`
FROM `employee`
WHERE `emp_id` IN (
SELECT `emp_id`
FROM `works_with`
WHERE `total_sales` > 50000
);
```
这里应当用IN,因为子查询返回了多个结果。
# ON DELETE
之前创建表格的时候使用了ON DELETE,作用是什么?
先看刚刚创建时使用了ON DELETE的例子:
1. 创建部门表格
```mysql
CREATE TABLE `branch`(
`branch_id` INT PRIMARY KEY,
`name` VARCHAR(20),
`manager_id` INT,
FOREIGN KEY(`manager_id`) REFERENCES `employee`(`emp_id`) ON DELETE SET NULL
);
```
2. 创建works_with表格
```mysql
CREATE TABLE `works_with`(
`emp_id` INT,
`client_id` INT,
`total_sales` INT,
PRIMARY KEY(`emp_id`, `client_id`),
FOREIGN KEY(`emp_id`) REFERENCES `employee`(`emp_id`) ON DELETE CASCADE,
FOREIGN KEY(`client_id`) REFERENCES `client`(`client_id`) ON DELETE CASCADE
);
```


上述两个指令分别创建了外键指向employee表格的两个表格,一个是branch,一个是works_with。
设想如下情形:当员工小绿离职了,即从employee中删除了emp_id=207,nam=小绿的这条数据,branch表和works_with表分别会做什么?这取决于创建时ON DELETE设定。
ON DELETE CASCADE表示删除时一起删掉,ON DELETE SET NULL表示删除时设为NULL。
也就是说,由于创建时制定了branch的外键是ON DELETE SET NULL,当employee表格中删除了小绿,branch中对应branch_id=2也就是小绿的manager_id的值就会设为NULL;works_with表中207一行会被删除。
**注意:Works_With表中的emp_id对应的ON DELETE不能设置为NULL!(否则会报错!)因为emp_id同时作为works_with表的主键,主键不可以是NULL。**
我们删除试试看:
```mysql
DELETE FROM `employee`
WHERE `emp_id` = 207;
```
```mysql
SELECT *
FROM `branch`;
```

可以看到,manager_id下对应的值为NULL了。
# python连接MySQL
需要安装依赖:
```bash
pip install mysql-connector-python
```
基本使用就是用cursor来执行sql指令。
例如:
```python
import mysql.connector
connection = mysql.connector.connect(host='localhost',
port='3306',
user='root',
password='zyl12345',
database='sql_tutorial'
)
cursor = connection.cursor()
# 获取部门表格所有数据
cursor.execute('SELECT * FROM `branch`;')
records = cursor.fetchall()
for r in records:
print(r)
cursor.close()
connection.close()
```
## connection.commit()
当需要修改数据库资料的,比如新增、修改、删除,需要他增加一句:
```python
connection.commit()
```
**只有使用了commit()才会提交出去,修改操作才会生效!**
例如:
```python
import mysql.connector
connection = mysql.connector.connect(host='localhost',
port='3306',
user='root',
password='zyl12345',
database='sql_tutorial'
)
cursor = connection.cursor()
# 新增
cursor.execute("INSERT INTO `branch` VALUES(5, 'qq', NULL);")
# 修改
cursor.execute("UPDATE `branch` SET `manager_id` = NULL WHERE `branch_id` = 4;")
# 删除
cursor.execute("DELETE FROM `branch` WHERE `branch_id` = 5;")
cursor.close()
connection.commit()
connection.close()
```
**只有使用了commit()才会提交出去,修改操作才会生效!**
完结。
|
# 策略模式
假设现在需要你开发一个获取用户列表的方法getUser,要求是可以对用户列表进行排序,排序方式要支持姓名、创建时间和所属部门的升降排序,现在先花一分钟时间思考下,如何实现这个getUser方法呢,getUser方法的参数是什么?
从需求来看,getUser应该需要两个参数:排序字段sortKey(name|createTime|department)、排序方式sortDirection(asc|desc),我们先按这个思路实现下。
```javascript
function getUser(sortKey, sortDirection){
//忽略通过请求获取用户数据相关代码
let users = [
{name: '用户1', createTime: '2023-10-1', department: '前端部'},
{name: '用户2', createTime: '2023-10-2', department: '后端部'},
];
switch (sortKey){
case 'name':
if(sortDirection === 'asc'){
//按照名称升序排序
}else{
//按照名称降序排序
}
break;
case 'createTime':
if(sortDirection === 'asc'){
//按照创建时间升序排序
}else{
//按照创建时间降序排序
}
break;
case 'department':
if(sortDirection === 'asc'){
//按照部门升序排序
}else{
//按照部门降序排序
}
break;
}
return users;
}
getUser('name', 'asc'); //按照名称升序获取用户
getUser('createTime', 'desc'); //按照创建时间降序获取用户
```
这样实现可以满足需求,但是也存在一些可读性和可维护性方面的问题
首先是这样的代码可读性较差,体现在两个方面,第一个点是getUser函数中充斥着大量的分支语句(switch、if),每个分支都会增加阅读的成本,分支越多,嵌套分支越深,理解起来就越困难;第二个点是排序部分所占的代码比重在getUser函数中过高,有点头轻脚重的感觉,代码不够结构化。
在可维护性方面,后续如果要增加一些新的排序方式,你就必须要先理解getUser方法的实现原理,然后再修改getUser方法中关于排序的实现,别小看这个修改,虽然你只是想修改排序部分,但是难保不会引入新的bug,毕竟你是在修改同一个函数。
能不能将排序实现抽出去呢?不同的排序可以看成不同的算法或者策略,我们在调用getUser方法时传递想要的排序策略不就可以了吗,按照这个思路修改下:
```javascript
const nameAscStrategy = function (users){ }; //按照名称升序排序
const nameDescStrategy = function (users){ }; //按照名称降序排序
const createTimeAscStrategy = function (users){ }; //按照创建时间升序排序
const createTimeDescStrategy = function (users){ }; //按照创建时间降序排序
const departmentAscStrategy = function (users){ }; //按照部门升序排序
const departmentDescStrategy = function (users){ }; //按照部门降序排序
function getUser(sortStrategy){
//忽略通过请求获取用户数据相关代码
let users = [
{name: '用户1', createTime: '2023-10-1', department: '前端部'},
{name: '用户2', createTime: '2023-10-2', department: '后端部'},
];
return sortStrategy(users);
}
getUser(nameAscStrategy); //按照名称升序获取用户
getUser(createTimeDescStrategy); //按照创建时间降序获取用户
```
现在我们再来看看getUser方法的实现,是不是瞬间清爽了很多!里面不再有让人讨厌的分支语句了,可以说非常地优雅~~后续再有新的排序方式,也不需要修改getUser方法,只需要创建一个新的排序策略即可。
为了让策略更加高内聚,我们可以将所有策略集中放到一个对象下。
```javascript
const SORT_STRATEGY = {
nameAsc: function (users){},
nameDesc: function (users){},
createTimeAsc: function (users){},
createTimeDesc: function (users){},
departmentAsc: function (users){},
departmentDesc: function (users){}
}
function getUser(sortStrategy){
//忽略通过请求获取用户数据相关代码
let users = [
{name: '用户1', createTime: '2023-10-1', department: '前端部'},
{name: '用户2', createTime: '2023-10-2', department: '后端部'},
];
return sortStrategy(users);
}
getUser(SORT_STRATEGY.nameAsc); //按照名称升序获取用户
getUser(SORT_STRATEGY.createTimeDesc); //按照创建时间降序获取用户
```
上述这种优化方式,就是一种策略模式,接下来我们看下策略模式的定义。
## 策略模式定义
> 策略模式(Strategy Pattern)允许在**运行时**根据不同的情况选择不同的算法或策略。该模式将算法或策略封装起来,使得它们可以**相互替换**,此模式可以让算法的变化**隔离于**使用算法的客户之外。
在这个定义中,我们重点关注几个关键词:
- 运行时:运行时意味着可以动态替换策略,比如上述getUser方法,你可以根据情况使用不同的策略,而不是提前固定好的。
```javascript
getUser(SORT_STRATEGY[sortMethod])
```
- 相互替换:多个策略遵循相同的接口,如果策略是一种类,那就有相同的属性和方法;如果策略是个函数,那么就有相同的形参和返回值。
- 隔离变化:策略模式的目的就是隔离算法的变化,将变化的算法抽取到策略中,将不变的部分留在调用策略的客户中。
在策略模式中,通常会定义一个抽象策略接口,所有具体策略类都实现该接口。客户端通过调用策略接口的方法来执行具体的算法。在运行时,可以根据需要动态地切换不同的策略,而不需要修改客户端的代码。
在前端实际开发中,可能很少用到接口,我们可以理解为将策略抽取到一个策略对象当中,每个策略函数遵循同样的参数和返回值规范。这种规范,就可以理解为后端的接口interface。
## 策略模式示例
策略模式的应用很广泛,比如咱们经常用的数组的sort、filter方法等,是不是都把排序策略和过滤策略抽象出来交给用户自行实现,通过这种方式大大提高了数组方法的适用场景。
为了加深对策略模式的理解,我们再举两个示例。
假设现在需要你实现一个搜索功能,要求是要将搜索结果进行缓存,以便于后续快速返回。
先来分析下这个需求,需求中提到了缓存,那使用何种缓存方式呢,内存、localStorage、sessionStorage还是IndexedDB,需求中没有明确说,假设都要支持,那如何设计呢?
我们可以将缓存方式设计成为一种策略,在搜索功能中配置某一种策略,这样即可轻松应对需求变化。
前面我们提到了,策略模式要求每个策略遵循同样的接口,作为缓存策略,我们很容易想到,每个策略应该至少包含以下几个方法:
```typescript
interface CacheStrategy {
getCache(key: string): any | undefined;
setCache(key: string, data: any): void;
has(key: string): boolean;
}
```
接下来我们使用localStorage来实现这个接口
```typescript
class LocalStorageCacheStrategy implements CacheStrategy {
getCache(key: string): any | undefined {
const data = localStorage.getItem(key);
if (data) {
return JSON.parse(data);
}
return undefined;
}
setCache(key: string, data: any): void {
localStorage.setItem(key, JSON.stringify(data));
}
has(key: string): boolean {
return localStorage.getItem(key) !== null;
}
}
```
通过内存进行存储的策略实现:
```typescript
class MemoryCacheStrategy implements CacheStrategy {
private cache: { [key: string]: any } = {};
getCache(key: string): any | undefined {
return this.cache[key];
}
setCache(key: string, data: any): void {
this.cache[key] = data;
}
has(key: string): boolean {
return key in this.cache;
}
}
```
接下来实现一个搜索类,在搜索类构造函数中接收一个存储策略,在搜索时调用先调用存储策略的has方法,看看搜索的关键词是否存在,存在则通过get方法获取缓存;如果搜索关键词不存在缓存中则进行搜索,并调用存储策略的set方法将搜索结果缓存。
```typescript
class Search {
private cacheStrategy: CacheStrategy;
constructor(cacheStrategy: CacheStrategy) {
this.cacheStrategy = cacheStrategy;
}
search(query: string): void {
// 检查缓存中是否存在搜索记录
if (this.cacheStrategy.has(query)) {
// 从缓存中获取搜索结果
const results = this.cacheStrategy.getCache(query);
return results;
} else {
// 执行搜索操作,获取搜索结果
const results = this.performSearch(query);
// 将搜索结果存储到缓存中
this.cacheStrategy.setCache(query, results);
return results;
}
}
private performSearch(query: string): string[] {
// 模拟搜索操作,返回搜索结果
return [`Result 1 for ${query}`, `Result 2 for ${query}`, `Result 3 for ${query}`];
}
}
```
后续实例化搜索类时,可以根据需要传递不同的存储策略。
```typescript
// 实例化使用内存策略的搜索类
const memoryCacheSearch = new Search(new MemoryCacheStrategy());
memoryCacheSearch.search("apple");
memoryCacheSearch.search("banana");
memoryCacheSearch.search("apple"); // 从缓存中获取搜索结果
// 实例化使用 localStorage 策略的搜索类
const localStorageSearch = new Search(new LocalStorageCacheStrategy());
localStorageSearch.search("apple");
localStorageSearch.search("banana");
localStorageSearch.search("apple"); // 从缓存中获取搜索结果
```
这样就将搜索功能和缓存策略隔离开来了,后续想增加IndexedDB存储,只需要新建一个策略即可,搜索类无需任何改动。
我们再看一个前端开发中,非常常见的页签功能实现。

在上述图中,我们可以通过切换页签查看不同类型的成员,不同成员的表格展示项也不完全相同,每个类型的成员都有删除操作,但是调用的接口不同。
如果没有使用策略模式,我们可能的实现如下(为了更清楚的看到策略模式的结构,我们忽略UI相关的代码,只写核心逻辑)。
```javascript
function getUsers(type){
if(type === 'ordinaryUser'){
//获取普通用户数据
}else if(type === 'vip'){
//获取Vip用户数据
}else if(type === 'blackList'){
//获取黑名单用户数据
}
}
function deleteUser(type, userInfo){
if(type === 'ordinaryUser'){
//调用删除普通用户接口
}else if(type === 'vip'){
//调用删除Vip用户接口
}else if(type === 'blackList'){
//调用删除黑名单用户接口
}
}
```
我们经常看到这种丑陋的代码,在多个函数中都进行某种类型判断,然后执行不同逻辑的代码,感觉非常的繁琐,能不能把这些分支判断去掉呢?当然了,我们可以通过策略模式来进行优化。
每个类型的用户策略中可以提供相应的getUsers和deleteUser方法,在业务中根据用户类型动态选择相应的策略,然后调用策略提供的方法。
```javascript
const userStrategy = {
ordinary: {
getUsers: function (){},
deleteUser: function (userInfo){}
},
vip: {
getUsers: function (){},
deleteUser: function (userInfo){}
},
blackList:{
getUsers: function (){},
deleteUser: function (userInfo){}
}
}
function getUsers(type){
userStrategy[type].getUsers();
}
function deleteUser(type, userInfo){
userStrategy[type].deleteUser(userInfo);
}
```
可以看到,用策略模式重构后的代码依然十分优雅,不同用户的操作内聚在一起,而且业务代码中消除了类型判断,无论是可读性还是可维护性都大大提升。
## 总结
- 当代码中充斥着大量重复的分支判断的时候,可以考虑试试策略模式
- 策略模式中的每个策略需要遵循相同的接口,策略之间可以互相替换
- 策略模式允许在运行时中动态分配策略
- 策略模式将策略的变化和调用方隔离开来,可以很方便地扩展策略,符合开闭原则
- 策略模式可以提升代码的可读性和可维护性,是一种非常常见的有效的设计模式
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define PROMPT ">>"
int InputInt()
{
int num;
while (scanf("%d", &num) != 1)
{
while (getchar() != '\n');
}
while (getchar() != '\n');
return num;
}
typedef struct
{
int key;
int value;
} Item;
void PrintItems(Item items[], int size)
{
for (int i = 0; i < size; ++i)
{
printf("%d: %d\n", items[i].key, items[i].value);
}
printf("\n");
}
int CompareItems(const void* first, const void* second)
{
return ((Item*)first)->key - ((Item*)second)->key;
}
const Item* SequentialSearch(const Item items[], const int size, const int key)
{
for (int i = 0; i < size; ++i)
{
if (items[i].key == key)
{
return &items[i];
}
}
return NULL;
}
const Item* BinarySearch(const Item items[], const int size, const int key)
{
int first = 0;
int last = size - 1;
int pivot = (first + last) / 2;
while (first <= last)
{
pivot = (first + last) / 2;
if (items[pivot].key == key)
{
return &items[pivot];
}
else if (items[pivot].key > key)
{
last = pivot - 1;
}
else
{
first = pivot + 1;
}
}
return NULL;
}
int main(void)
{
/* Assume that there is no duplicated items */
Item items[] = {
{1, 11},
{6, 16},
{4, 14},
{8, 18},
{2, 12},
{9, 19},
{0, 10},
{5, 15},
{3, 13},
{7, 17},
};
int n = sizeof(items) / sizeof(items[0]);
PrintItems(items, n);
qsort(items, n, sizeof(Item), CompareItems);
PrintItems(items, n);
while (1)
{
int key = 0;
printf("Input key\n");
printf("%s ", PROMPT);
key = InputInt();
if (key == -1)
{
break;
}
//const Item* found = SequentialSearch(items, n, key);
const Item* found = BinarySearch(items, n, key);
if (found)
{
printf("%d: %d\n\n", found->key, found->value);
}
else
{
printf("Not in the list.\n\n");
}
}
return 0;
}
|
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:nano/model/product/product.dart';
import 'package:nano/utils/images.dart';
import 'package:nano/utils/theme_color.dart';
import 'package:solid_bottom_sheet/solid_bottom_sheet.dart';
class BottomSheetWidget extends StatelessWidget {
Product product;
SolidController controllerBottomSheet;
BottomSheetWidget(
{Key? key, required this.product, required this.controllerBottomSheet})
: super(key: key);
@override
Widget build(BuildContext context) {
return SolidBottomSheet(
controller: controllerBottomSheet,
maxHeight: MediaQuery.of(context).size.height * 0.3,
headerBar: GestureDetector(
onTap: () {},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
offset: const Offset(0, 0),
blurRadius: 15,
color: HexColor('#6b7f99').withOpacity(0.25),
),
],
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(35), topRight: Radius.circular(35))),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [SvgPicture.asset(Images.arrowDown)],
),
const SizedBox(height: 15),
Row(
children: [
Container(
width: 54,
height: 54,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
offset: const Offset(0, 0),
blurRadius: 15,
color: HexColor('#6b7f99').withOpacity(0.25),
),
],
borderRadius: BorderRadius.circular(20),
color: Colors.white),
child: Center(child: SvgPicture.asset(Images.share)),
),
const SizedBox(width: 20),
Expanded(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: ColorsFave.primaryColor,
elevation: 0,
padding: const EdgeInsets.symmetric(vertical: 18),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(43)),
),
onPressed: () {},
child: FittedBox(
child: Text('Order Now',
textAlign: TextAlign.center,
style: GoogleFonts.openSans(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Colors.white)),
),
),
)
],
),
],
),
),
),
body: Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
color: Colors.white,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 15),
Text(
'Description',
style: GoogleFonts.openSans(
fontWeight: FontWeight.w300,
fontSize: 12,
color: ColorsFave.titleProductColor),
),
const SizedBox(height: 7),
Text(
product.description!,
style: GoogleFonts.openSans(
fontWeight: FontWeight.w400,
fontSize: 14,
color: ColorsFave.descriptionColor),
),
const SizedBox(height: 7),
Container(
padding:
const EdgeInsets.symmetric(vertical: 10, horizontal: 5),
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: HexColor('#F1F1F1'),
borderRadius: BorderRadius.circular(8)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Reviews (${product.rating.count!})',
style: GoogleFonts.openSans(
fontWeight: FontWeight.w600,
fontSize: 15,
color: ColorsFave.titleProductColor),
),
const SizedBox(height: 7),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Row(
children: [
Expanded(
child: Text(
product.rating.rate!,
style: GoogleFonts.openSans(
fontWeight: FontWeight.w600, fontSize: 32),
),
),
RatingBar.builder(
initialRating: double.parse(product.rating.rate!),
minRating: 1,
direction: Axis.horizontal,
allowHalfRating: true,
itemCount: 5,
itemPadding:
const EdgeInsets.symmetric(horizontal: 4.0),
itemBuilder: (context, _) => SvgPicture.asset(
Images.star,
color: ColorsFave.starColor,
),
unratedColor: HexColor('#E4E4E4'),
onRatingUpdate: (rating) {},
itemSize: 22,
),
],
),
),
],
),
),
const SizedBox(height: 7),
],
),
),
),
);
}
}
|
import {BrowserRouter} from 'react-router-dom';
import {fireEvent, render, screen} from '@testing-library/react';
import {AppProvider} from 'shared/context';
import {useCart} from 'shared/hooks';
import {productsInCart} from 'tests/mock';
import Cart from '.';
const mockedUsedNavigate = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockedUsedNavigate,
useLocation: jest.fn(),
}));
jest.mock('shared/hooks', () => ({
useCart: jest.fn(),
}));
const mockedUseCart = useCart as jest.Mock;
describe('Cart', () => {
it('should render products length is greater than zero', () => {
mockedUseCart.mockImplementation(() => ({
cartTotalPrice: 400,
products: productsInCart,
cartQuantity: 3,
addProduct: jest.fn(),
removeProduct: jest.fn(),
deleteProduct: jest.fn(),
}));
const {container} = render(
<BrowserRouter>
<AppProvider>
<Cart />
</AppProvider>
</BrowserRouter>,
);
expect(screen.getByText(/Your bag/i)).toBeInTheDocument();
expect(screen.getByText(/Product 1/i)).toBeInTheDocument();
expect(screen.getByText(/Product 2/i)).toBeInTheDocument();
expect(screen.getByText(/Qty/i)).toBeInTheDocument();
expect(screen.getByText(/Price/i)).toBeInTheDocument();
expect(container).toBeInTheDocument();
expect(container).toMatchSnapshot();
fireEvent.click(screen.getByTestId('add-product-1'));
expect(screen.getAllByText(/2/i)[0]).toBeInTheDocument();
fireEvent.click(screen.getByTestId('remove-product-1'));
expect(screen.getAllByText(/1/i)[0]).toBeInTheDocument();
fireEvent.click(screen.getByTestId('delete-product-2'));
expect(screen.getByText(/Product 1/i)).toBeInTheDocument();
});
it('should render products length is equal to zero', () => {
mockedUseCart.mockImplementation(() => ({
cartTotalPrice: 0,
products: [],
cartQuantity: 0,
}));
const {container} = render(
<BrowserRouter>
<AppProvider>
<Cart />
</AppProvider>
</BrowserRouter>,
);
expect(screen.getByText(/Your bag/i)).toBeInTheDocument();
expect(screen.getByText(/Your bag is empty/i)).toBeInTheDocument();
expect(screen.getByText(/Return to home/i)).toBeInTheDocument();
fireEvent.click(screen.getByText(/Return to home/i));
expect(container).toBeInTheDocument();
});
});
|
using Microsoft.EntityFrameworkCore;
using WebDev_Labb2.DataAccess;
using WebDev_Labb2.DataAccess.Entities;
using WebDev_Labb2.Shared.DTOs;
namespace WebDev_Labb2.API.Extentions;
public static class OrderEndpointExtensions
{
public static WebApplication MapOrderEndpoints(this WebApplication app)
{
// "/orders" GET NONE Order[] 200, 404
app.MapGet("/orders", GetAllOrders);
// "/orders/{orderID}" GET int ID Order 200, 404
app.MapGet("/orders/{id:int}", GetAllOrdersById);
// "/orders" POST Order NONE 200, 400
app.MapPost("/orders", AddOrder);
// "/orders/{id}" PATCH int ID NONE 200, 400, 404
app.MapPatch("/orders/{id}", ReplaceOrder);
// "/orders/{id}" DELETE int ID NONE 200, 404
app.MapDelete("/orders/{id}", RemoveOrder);
return app;
}
private static async Task<IResult> RemoveOrder(OrderRepository repo, int id)
{
await repo.RemoveOrder(id);
return Results.Ok("Order removed");
}
private static async Task<IResult> ReplaceOrder(OrderRepository repo, int id)
{
var existingOrder = await repo.GetOrderById(id);
if (existingOrder is null)
{
return Results.BadRequest($"Order with id {id} does not excist");
}
await repo.UpdateOrderStatus(id);
return Results.Ok("Order updated");
}
private static async Task<IResult> GetAllOrdersById(OrderRepository repo, int id)
{
var order = await repo.GetOrderById(id);
if (order is null)
{
return Results.NotFound($"Order with ID {id} was not found");
}
return Results.Ok(order);
}
private static async Task<DbSet<Order>> GetAllOrders(OrderRepository repo)
{
return await repo.GetAllOrders();
}
private static void AddOrder(OrderRepository repo, OrderDTO dto)
{
repo.AddOrder(dto.CustomerID, dto.Products);
}
}
|
//
// ContentView.swift
// FirstWatchApp Watch App
//
// Created by Karl Mellinger on 12/27/23.
//
import SwiftUI
import WatchKit
import SwiftUI_Apple_Watch_Decimal_Pad
struct ContentView: View {
@State private var timerActive = false
@State private var timeRemaining = 30 * 60 // 30 minutes in seconds
@State private var tallyCount = 0 // Tally count
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
NavigationView{
VStack {
Text("Drink Count: \(String(tallyCount))")
.font(.system(size:24))
.padding()
Button(action: {
self.startTimer()
}) {
Image(timerActive ? "StopClock" : "Cocktail")
.resizable()
.frame(width: 75, height: 75)
.foregroundColor(.white)
.clipShape(Circle())
}
.buttonStyle(PlainButtonStyle())
.padding()
if timerActive {
Text("\(timeString(time: timeRemaining))")
.font(.title2)
.onReceive(timer) { _ in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
} else {
self.timerActive = false
self.triggerHapticFeedback()
}
}
}
else {
// Navigation link to ResetCountView
NavigationLink(destination: ResetCountView(tallyCount: $tallyCount)) {
Text("Reset Tally")
}
.padding()
}
}
}
}
func startTimer() {
if timerActive {
timerActive = false
} else {
timeRemaining = 30 * 60
timerActive = true
tallyCount += 1
}
}
func timeString(time: Int) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
}
func triggerHapticFeedback() {
WKInterfaceDevice.current().play(.success)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
# Matrix inversion for TFHE ZAMA concrete
## Installation
```bash
poetry install
```
## Run
```bash
poetry shell
python matrix_inversion/main.py
```
## Dev
### Running tests
```bash
poetry shell
python tests/test_qfloat.py
python tests/test_qfloat_fhe.py
python matrix_inversion/qfloat_matrix_inversion.py
```
### Contributing
see TODO in `qfloat.py` and `qfloat_matrix_inversion.py` and `base_p_arrays.py`
## About
<div style="text-align: justify">
### QFloats to quantize floats in FHE
- The **QFloat** class allows to quantize float numbers as FHE compatible arrays of integers, and to make operations between them like additions, multiplications, etc.
The array can be made in any given base (for instance, in base 2 which is binary) and with any precision (the longer the array and the greater the base, the more precise the **QFloat** representation).
- The array is split between an integer part and a decimal part (after the decimal point). For instance, 34.42 = 34 + 0.32. The length of the integer part must be provided along with the total length of the array to create a QFloat. The longer the integer part is, the higher the **QFloat** can go to encode a number, and the longer the total length is (hence the decimal part is) the more precise it can get.
<center>
**Internal representation of a QFloat**
</center>

This representation allows to make any operations on the QFloats in FHE, but has a limited range of values. The usual unencrypted float representation that uses an exponent (like 3.442 e-1), cannot be made in FHE to run operations (mostly additions) without disproportionally huge computations.
- Along with the **QFloat** class, the **SignedBinary** and **Zero** classes can be used to limit the computations when we know values are binary numbers or are equal to zero. They are compatible with QFloats.
- QFloats were designed for the matrix inversion problem but can be used for (almost) any other float computations in FHE !
### Why using QFloats is required for matrix inversion
- To compute the inverse of a float matrix in FHE, one must inevitably run computations on representations of floats in FHE, with a data structure keeping a minimal precision of the initial floats which are 32 to 64 bits. Hence, a class like **QFloat** is absolutely required here, with enough precision provided.
### Why the inversion from LU decomposition was chosen
- The algorithm used for inverting the **QFloat** matrix is called **inversion from LU decomposition**. It is a perfect algorithm, not an approximate one. Approximate algorithms were investigated (ones that use convergence to estimate the inverse) but they all require constraints on the input matrix, which cannot be verified or guessed within FHE. The **LU decomposition** algorithm is perfect and works for all invertible matrices.
Furthermore, these algorithms require a lot of matrix products which are expensive to compute, and it is not clear whether they would be faster than a perfect algorithm in FHE (provided they could be done somehow).
- For matrices of size 2x2, a simpler formula has been implemented. Unfortunately, this formula applied to larger matrices is more expensive than the inversion from LU decomposition algorithm.
### How to set QFloats for the algorithm
- QFloats are created with 3 custom parameters:
- `qfloat_base`: The base (base 2 is binary).
- `qfloat_len`: The total length of the integer array. The greater it is, the more precise the QFloats get.
- `qfloat_ints`: The length of the integer part of the float. The greater it is, the higher the **QFloat** can go.
- The `qfloat_base` seems to be optimal with value 2 which corresponds to a binary encoding. Higher bases reduce the size of the QFloat encoding arrays and thus the size of the many loops in QFloats computing, but they also increase the bit width and thus slow down the computations more than the size reduction speeds it up.
- Any desired precision can be obtained if setting the QFloats with more precision (longer length), but the computation will be significantly slower.
### Further notice
- Running the computations in pure python can be useful to assess the correctness of the output, see `qfloat_matrix_inversion.py` in the test main part.
- The inversion algorithm could be optimized to be faster for the specific task of inverting matrices of floats in range ~0-100, but it was kept more general here.
### Benchmarking
The inversion algorithm has been benchmarked in both precision and speed.
#### Precision benchmarking
FHE computing is so slow that it makes the algorithm impossible to run on large matrices or with good precision parameters. However, there has been no evidence that the results are any different in FHE than in pure python for the small matrices and low precision, so we can expect that a precision benchmarking done with python is representative of the behavior in FHE.
This benchmarking consists in running 10.000 matrix inversions ( *normal(0,100)* matrix sampler), and calculate the error in comparison to the standard `scipy.linalg` matrix inversion algorithm. For each matrix size, we computed the **mean error** over the 10.000 runs, and we also counted the percentage of results with a huge error (bigger than 1) that we can consider totally erroneous (see **big error rate**).
<center>
**Table 1: precision benchmarking**
| Error \ Precision | Low | Medium | Medium+ | High |
|:----------|:----------|:----------|:----------|:----------|
| n=2 : mean error | 8.19 e-2 | 7.6 e-3 | 7.64 e-4 | 5.03 e-4 |
| n=2 : big error rate | 0.04 % | 0.02 % | 0.01 % | 0.0 % |
| n=3 : mean error | 9.93 e-2 | 4.43 e-2 | 2.6 e-3 | 7.8 e-6 |
| n=3 : big error rate | 1.34 % | 0.4 % | 0.03 % | 0.0 % |
| n=4 : mean error | 2.04 e-1 | 2.34 e-2 | 2.778 e-1 | 8.6 e-6 |
| n=4 : big error rate | 3.08 % | 0.24 % | 0.11 % | 0.0 % |
| n=5 : mean error | 3.14 e-1 | 5.59 e-2 | 9.37 e-2 | 1.40 e-6 |
| n=5 : big error rate | 6.36 % | 0.23 % | 0.23 % | 0.0 % |
| n=10 : mean error | 1.29 e-0 | 6.87 e-1 | 2.57 e-0 | 1.2 e-4 |
| n=10 : big error rate | 31.3 % | 0.44 % | 0.75 % | 0.0 % |
</center>
The values of the precision parameters are listed below :
<center>
**Table 2: precision parameters**
| Precision \ Values | Array length | Integer digits | True division |
|:----------|:----------|:----------|:----------|
| Low | 23 | 9 | False |
| Medium | 31 | 16 | False |
| Medium+ | 31 | 16 | True |
| High | 40 | 20 | True |
</center>
After investigation of the algorithm (see function `debug_qfloat_inverse_python`), we noticed that the errors came from two different factors:
- The size of the integer part **ints**: Most of the big errors come simply from the fact that some QFloats in the matrix (lower right cells in LU decomposition) may overflow, getting values above the maximum possible value authorized by the integer `ints` part of the QFloat. By simply increasing this maximum possible value, we get less and less (eventually none) such big errors (read the table from left to right on the **big error** lines).
- The size of the decimal part, after the decimal point: The rest of the errors come from the errors accumulating during the computations coming from the precision of decimal part. The more digits we use after the comma, the more precise the operations (additions, multiplications, divisions) get, and the less the precision error accumulate overtime. That's why in the table the errors decrease from left to right (same matrix size but more precision), but increase from top to bottom (same precision but more error accumulation with larger matrices).
Note that for **n=2** the algorithm is different than for other values of **n**, and that this results may show some statistical oddities.
#### Computation time benchmarking
To benchmark the FHE computation time (see function `time_benchmark` in `qfloat_matrix_inversion.py`), we ran 3 **compilation / encryption / run** in **low precision** on a 64 cores computing instance, we kept the times and computed the average. We repeated this for `n=2`, `n=3` and also for parameter `tensorize` set to `True` and `False` (`True` adds a bit more tensorization in the inverse algorithm than there is when set to `False`). We could not test higher sizes of matrices or higher precision due to current computational time limitations in FHE.
Note: The benchmarking was done on `concrete-numpy 2.1.0` because the `2.2.0`and `2.3.0` did not work for compiling with `n>=3`.
<center>
**Table 3: time benchmarking**
| Computation \ n | 2 | 2 | 3 | 3 |
|:----------|:----------|:----------|:----------|:----------|
| Tensorize | Yes | No | Yes | No |
| Compilation | 41 | 42 | **4255** | 5487 |
| FHE Run (1 run) | 85 | 85 | 1768 | **1349** |
| Total (with encryption, 1 run) | 126 | 127 | **6024** | 6837 |
| Total estimated (3 runs) | 296 | 297 | 9562 | **9537** |
</center>
We see that the algorithm used when `n=2` does not seem to change speed with or without tensorization.
However, the algorithm for `n>=3` took more time to compile **without** tensorization, but more time to run **with** tensorization. Overall, for one run (with encryption), setting `tensorize=True` was faster, but we can expect that for 3 runs or more, setting `tensorize=False` would be faster.
Given this result, the `tensorize` parameter was given a `False` default value.
</div>
|
package com.paetus.animaCharCreator.character_creation.attributes.magic.spells.spellbook
import com.paetus.animaCharCreator.R
import com.paetus.animaCharCreator.enumerations.Element
import com.paetus.animaCharCreator.character_creation.attributes.magic.spells.Spell
import com.paetus.animaCharCreator.character_creation.attributes.magic.spells.SpellType
/**
* List of spells associated with the dark element.
*/
class DarkBook{
private val createDark = Spell(
R.string.createDark,
Element.Dark,
true,
2,
20,
R.string.createDarkDesc,
R.string.createDarkEff,
20,
10,
true,
listOf(SpellType.Effect)
)
private val induceFear = Spell(
R.string.induceFear,
Element.Dark,
true,
6,
40,
R.string.induceFearDesc,
R.string.induceFearEff,
10,
null,
false,
listOf(SpellType.Spiritual)
)
private val seeInDarkness = Spell(
R.string.seeInDark,
Element.Dark,
true,
8,
40,
R.string.seeInDarkDesc,
R.string.seeInDarkEff,
10,
10,
true,
listOf(SpellType.Effect)
)
private val darkShield = Spell(
R.string.darkShield,
Element.Dark,
false,
10,
50,
R.string.darkShieldDesc,
R.string.darkShieldEff,
20,
10,
false,
listOf(SpellType.Defense)
)
private val shadow = Spell(
R.string.shadow,
Element.Dark,
false,
12,
50,
R.string.shadowDesc,
R.string.shadowEff,
20,
10,
false,
listOf(SpellType.Effect)
)
private val darkArmor = Spell(
R.string.darkArmor,
Element.Dark,
true,
16,
60,
R.string.darkArmorDesc,
R.string.darkArmorEff,
10,
20,
false,
listOf(SpellType.Effect)
)
private val banishLight = Spell(
R.string.banLight,
Element.Dark,
true,
18,
60,
R.string.banLightDesc,
R.string.banLightEff,
10,
10,
false,
listOf(SpellType.Spiritual, SpellType.Effect)
)
private val hideMagic = Spell(
R.string.hideMag,
Element.Dark,
false,
20,
50,
R.string.hideMagDesc,
R.string.hideMagEff,
20,
10,
true,
listOf(SpellType.Effect)
)
private val darkBeam = Spell(
R.string.darkBeam,
Element.Dark,
true,
22,
50,
R.string.darkBeamDesc,
R.string.darkBeamEff,
10,
null,
false,
listOf(SpellType.Attack)
)
private val darkzone = Spell(
R.string.darkZone,
Element.Dark,
true,
26,
60,
R.string.darkZoneDesc,
R.string.darkZoneEff,
20,
20,
false,
listOf(SpellType.Effect)
)
private val darkBond = Spell(
R.string.darkBond,
Element.Dark,
true,
28,
60,
R.string.darkBondDesc,
R.string.darkBondEff,
10,
10,
false,
listOf(SpellType.Attack)
)
private val controlDark = Spell(
R.string.controlDark,
Element.Dark,
true,
30,
50,
R.string.controlDarkDesc,
R.string.controlDarkEff,
20,
10,
false,
listOf(SpellType.Spiritual, SpellType.Effect)
)
private val concealment = Spell(
R.string.concealment,
Element.Dark,
false,
32,
60,
R.string.concealmentDesc,
R.string.concealmentEff,
20,
10,
true,
listOf(SpellType.Effect)
)
private val obfuscate = Spell(
R.string.obfuscate,
Element.Dark,
true,
36,
100,
R.string.obfuscateDesc,
R.string.obfuscateEff,
20,
5,
true,
listOf(SpellType.Effect)
)
private val enrage = Spell(
R.string.enrage,
Element.Dark,
true,
38,
60,
R.string.enrageDesc,
R.string.enrageEff,
10,
10,
false,
listOf(SpellType.Spiritual)
)
private val banishPositiveEmotions = Spell(
R.string.banPosEmote,
Element.Dark,
true,
40,
80,
R.string.banPosEmoteDesc,
R.string.banPosEmoteEff,
20,
null,
false,
listOf(SpellType.Spiritual)
)
private val night = Spell(
R.string.night,
Element.Dark,
true,
42,
80,
R.string.nightDesc,
R.string.nightEff,
20,
10,
false,
listOf(SpellType.Effect)
)
private val darkSphere = Spell(
R.string.darkSphere,
Element.Dark,
true,
46,
120,
R.string.darkSphereDesc,
R.string.darkSphereEff,
20,
10,
false,
listOf(SpellType.Attack)
)
private val concealZone = Spell(
R.string.concealZone,
Element.Dark,
true,
48,
140,
R.string.concealZoneDesc,
R.string.concealZoneEff,
20,
20,
true,
listOf(SpellType.Detection)
)
private val enterNightmare = Spell(
R.string.enterNightmare,
Element.Dark,
true,
50,
120,
R.string.enterNightmareDesc,
R.string.enterNightmareEff,
20,
50,
true,
listOf(SpellType.Spiritual)
)
private val darkForm = Spell(
R.string.darkForm,
Element.Dark,
true,
52,
100,
R.string.darkFormDesc,
R.string.darkFormEff,
10,
10,
false,
listOf(SpellType.Effect)
)
private val perdition = Spell(
R.string.perdition,
Element.Dark,
true,
56,
100,
R.string.perditionDesc,
R.string.perditionEff,
20,
20,
false,
listOf(SpellType.Automatic)
)
private val createNegativeFeelings = Spell(
R.string.createNegEmote,
Element.Dark,
true,
58,
100,
R.string.createNegEmoteDesc,
R.string.createNegEmoteEff,
20,
10,
true,
listOf(SpellType.Spiritual)
)
private val eliminateTraces = Spell(
R.string.eliminateTrace,
Element.Dark,
true,
60,
100,
R.string.eliminateTraceDesc,
R.string.eliminateTraceEff,
20,
10,
true,
listOf(SpellType.Effect)
)
private val shieldFromPositive = Spell(
R.string.shieldPositive,
Element.Dark,
true,
62,
140,
R.string.shieldPositiveDesc,
R.string.shieldPositiveEff,
20,
10,
true,
listOf(SpellType.Automatic)
)
private val devouringDark = Spell(
R.string.darkDevour,
Element.Dark,
false,
66,
120,
R.string.darkDevourDesc,
R.string.darkDevourEff,
20,
20,
false,
listOf(SpellType.Defense)
)
private val devastate = Spell(
R.string.devastate,
Element.Dark,
true,
68,
100,
R.string.devastateDesc,
R.string.devastateEff,
20,
10,
false,
listOf(SpellType.Spiritual)
)
private val markOfFear = Spell(
R.string.fearMark,
Element.Dark,
true,
70,
140,
R.string.fearMarkDesc,
R.string.fearMarkEff,
20,
50,
false,
listOf(SpellType.Automatic)
)
private val catastrophicDarkness = Spell(
R.string.darkCatastrophe,
Element.Dark,
true,
72,
120,
R.string.darkCatastropheDesc,
R.string.darkCatastropheEff,
20,
null,
false,
listOf(SpellType.Attack)
)
private val darkMaterialObjects = Spell(
R.string.darkMatObj,
Element.Dark,
true,
76,
150,
R.string.darkMatObjDesc,
R.string.darkMatObjEff,
20,
10,
false,
listOf(SpellType.Effect)
)
private val shadowTravel = Spell(
R.string.shadowTravel,
Element.Dark,
true,
78,
250,
R.string.shadowTravelDesc,
R.string.shadowTravelEff,
30,
null,
false,
listOf(SpellType.Spiritual, SpellType.Effect)
)
private val nightmareLord = Spell(
R.string.nightmareLord,
Element.Dark,
true,
80,
300,
R.string.nightmareLordDesc,
R.string.nightmareLordEff,
20,
5,
true,
listOf(SpellType.Spiritual, SpellType.Effect)
)
private val createDarkBeing = Spell(
R.string.darkBeing,
Element.Dark,
true,
82,
250,
R.string.darkBeingDesc,
R.string.darkBeingEff,
30,
5,
true,
listOf(SpellType.Effect)
)
private val concealmentFromMagic = Spell(
R.string.concealFromMag,
Element.Dark,
false,
86,
200,
R.string.concealFromMagDesc,
R.string.concealFromMagEff,
20,
10,
true,
listOf(SpellType.Effect)
)
private val darknessKingdom = Spell(
R.string.darkKingdom,
Element.Dark,
true,
88,
200,
R.string.darkKingdomDesc,
R.string.darkKingdomEff,
30,
20,
false,
listOf(SpellType.Automatic)
)
private val undetectable = Spell(
R.string.undetectable,
Element.Dark,
true,
90,
380,
R.string.undetectableDesc,
R.string.undetectableEff,
30,
5,
true,
listOf(SpellType.Effect)
)
private val prisonOfDarkness = Spell(
R.string.darkPrison,
Element.Dark,
true,
92,
200,
R.string.darkPrisonDesc,
R.string.darkPrisonEff,
20,
5,
true,
listOf(SpellType.Spiritual)
)
private val oneWithDarkness = Spell(
R.string.darkOne,
Element.Dark,
true,
96,
100,
R.string.darkOneDesc,
R.string.darkOneEff,
20,
null,
false,
listOf(SpellType.Effect)
)
private val darkAscension = Spell(
R.string.darkAscension,
Element.Dark,
true,
98,
300,
R.string.darkAscensionDesc,
R.string.darkAscensionEff,
30,
10,
true,
listOf(SpellType.Effect)
)
private val darkHolocaust = Spell(
R.string.holoDark,
Element.Dark,
true,
100,
600,
R.string.holoDarkDesc,
R.string.holoDarkEff,
50,
null,
false,
listOf(SpellType.Attack, SpellType.Spiritual)
)
val fullBook = listOf(
createDark,
null,
induceFear,
seeInDarkness,
darkShield,
shadow,
null,
darkArmor,
banishLight,
hideMagic,
darkBeam,
null,
darkzone,
darkBond,
controlDark,
concealment,
null,
obfuscate,
enrage,
banishPositiveEmotions,
night,
null,
darkSphere,
concealZone,
enterNightmare,
darkForm,
null,
perdition,
createNegativeFeelings,
eliminateTraces,
shieldFromPositive,
null,
devouringDark,
devastate,
markOfFear,
catastrophicDarkness,
null,
darkMaterialObjects,
shadowTravel,
nightmareLord,
createDarkBeing,
null,
concealmentFromMagic,
darknessKingdom,
undetectable,
prisonOfDarkness,
null,
oneWithDarkness,
darkAscension,
darkHolocaust
)
}
|
from __future__ import annotations
import os
PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INPUT_PATH = os.path.join(PROJECT_PATH, "src", "input", "day_07.txt")
class Hand:
def __init__(self, cards: str, bid: int, strength: int, joker_rule: bool = False):
self.cards = cards
self.bid = bid
self.strength = strength
self.joker_rule = joker_rule
def card_to_number(self, card: str) -> int:
if card.isdigit():
return int(card)
return {
"J": 1 if self.joker_rule else 11,
"T": 10,
"Q": 12,
"K": 13,
"A": 14,
}[card]
def __lt__(self, other: Hand) -> bool:
if self.strength != other.strength:
return self.strength < other.strength
for card_self, card_other in zip(self.cards, other.cards):
if card_self != card_other:
return self.card_to_number(card_self) < self.card_to_number(card_other)
return False
def get_counts_with_joker(hand_cards: str, counts: list[int]) -> list[int]:
joker_count = hand_cards.count("J")
joker_map: dict[int, dict] = {
4: {"default": [5]},
3: {(3, 2): [5], "default": [4, 1]},
2: {(3, 2): [5], (2, 2, 1): [4, 1], "default": [3, 1, 1]},
1: {
(4, 1): [5],
(3, 1, 1): [4, 1],
(2, 2, 1): [3, 2],
(2, 1, 1, 1): [3, 1, 1],
"default": [2, 1, 1, 1],
},
}
if joker_count in joker_map:
return joker_map[joker_count].get(
tuple(counts), joker_map[joker_count]["default"]
)
return counts
def parse_hand(line: str, joker_rule: bool = False) -> Hand:
hand_cards, hand_bid = line.split()[0], int(line.split()[1])
counts = [hand_cards.count(card) for card in set(hand_cards)]
counts.sort(reverse=True)
if joker_rule:
counts = get_counts_with_joker(hand_cards, counts)
hand_map = {
(5,): 7,
(4, 1): 6,
(3, 2): 5,
(3, 1, 1): 4,
(2, 2, 1): 3,
(2, 1, 1, 1): 2,
(1, 1, 1, 1, 1): 1,
}
if tuple(counts) in hand_map:
return Hand(hand_cards, hand_bid, hand_map[tuple(counts)], joker_rule)
raise ValueError(f"Unknown hand type: {counts}, {hand_cards=}")
def total_winnings(lines: list[str], joker_rule: bool = False) -> None:
hands = [parse_hand(line, joker_rule) for line in lines]
hands.sort()
total_winnings = sum(hand.bid * (i + 1) for i, hand in enumerate(hands))
print(total_winnings)
if __name__ == "__main__":
with open(INPUT_PATH) as f:
lines = [line.strip() for line in f.readlines()]
total_winnings(lines)
total_winnings(lines, joker_rule=True)
|
import React, { useState, useEffect } from 'react';
import { gql, useQuery, useMutation } from '@apollo/client';
type QuizProps = {
id: string;
}
type Choice = {
text: string;
correct: boolean;
}
type Question = {
text: string;
choices: Choice[];
}
// type QuestionInput = {
// body: string,
// mustSelectAllCorrectChoices: boolean,
// choices: [
// ]
// }
function Quiz(props: QuizProps) {
const [title, setTitle] = useState("")
const [questions, setQuestions] = useState<Question[]>([]);
const [answers, setAnswers] = useState<number[]>([]);
const get_quiz_query = gql`
query {
Pages(identifiers: ["${props.id}"]) {
__typename
... on QuizPage {
title
questions {
body
choices {
value
correct
}
}
}
}
}
`
const { data: quiz_data } = useQuery(get_quiz_query, {
variables: { identifiers: props.id }
});
if (quiz_data) {
const response = quiz_data.Pages[0].questions
let questionsData: Question[] = []
let newQuestion: Question;
for (let i = 0; i < response.length; i++) {
let choicesData: Choice[] = []
let newChoice: Choice;
for (let i2 = 0; i2 < response[i].choices.length; i2++) {
newChoice = {
text: response[i].choices[i2].value,
correct: response[i].choices[i2].correct
}
choicesData.push(newChoice)
}
newQuestion = {
text: response[i].body,
choices: choicesData
}
questionsData.push(newQuestion)
}
useEffect(() => {
setTitle(quiz_data.Pages[0].title)
setQuestions(questionsData)
let answersData: number[] = []
for (let i = 0; i < quiz_data.Pages[0].questions.length; i++) {
answersData.push(-1)
}
setAnswers(answersData)
}, [])
}
let answerItems;
const questionItems = questions.map((question, index) => {
// let answersData
answerItems = question.choices.map((answer, index_2) => {
return <h2
key={`key-${index_2}`}
className={`hover:bg-slate-100 rounded-lg m-2 px-3 hover:cursor-pointer
${ answers[index] === index_2 ? 'bg-green-200' : 'bg-slate-200'}`}
onClick={() => {
let oldAnswers = answers
oldAnswers[index] = index_2
setAnswers([...oldAnswers])
}}
>{answer.text}</h2>
})
return <div className='p-4' key={`key-${index}`}>
<h1
className='text-xl'>{question.text}</h1>
{answerItems}
</div>
})
let questionInputs = [];
//console.log(questions)
if (questions.length != 0 && answers.length != 0) {
for (let i = 0; i < questions.length; i++) {
let choices
if (answers[i] == -1) {
choices = [{
valueArray: [questions[i].choices[0].text],
correct: questions[i].choices[0].correct
}]
} else {
choices = [{
valueArray: [questions[i].choices[answers[i]].text],
correct: questions[i].choices[answers[i]].correct
}]
}
let questionInput = {
body: questions[i].text,
mustSelectAllCorrectChoices: true,
choices: choices
}
questionInputs.push(questionInput)
}
}
const submit_quiz_mutation = gql`
mutation {
CreateAssessmentAttempt(
courseId: "b6c00977-99b4-4663-9d0e-7c39385cfc49"
topicId: "872bfd0a-aeec-4b97-b7f1-24878f55323f",
questions: []
)
}`
const [submitQuiz, { data: submitData }] = useMutation(submit_quiz_mutation);
return (
<div>
<h1
className='t text-xl'
>{title}</h1>
{questionItems}
<div className='flex flex-row justify-center'>
<h1
className='hover:bg-slate-100 bg-slate-400 rounded-lg
m-2 px-3 hover:cursor-pointer w-72 text-xl text-center'
onClick={() => {
// console.log(questionInputs)
// submitQuiz({ variables: { id: props.id } })
let newAnswers = []
for (let i = 0; i < answers.length; i++) {
newAnswers.push(-1)
}
setAnswers(newAnswers)
}}
>Submit Quiz</h1>
</div>
</div>
);
}
export { Quiz };
|
import { Effect } from "./effect"
export interface CardOptions<StackNames extends string> {
/**
* The name of the card.
*/
name: () => string
/**
* The description of the card.
*/
description: () => string
/**
* The effects of the card.
*/
effects: Effect<StackNames>[]
}
/**
* A card.
*/
export class Card<StackNames extends string> {
constructor(public readonly options: CardOptions<StackNames>) {}
}
|
import React, { ReactElement } from 'react';
import { ActivityIndicator } from 'react-native';
import { useSelector } from 'react-redux';
import styled from 'styled-components/native';
import { LotId } from '../../../store/lots/models';
import { ApplicationState } from '../../../store/reducers';
import { selectInvoicesDataLoading } from '../../../store/invoices/selectors';
import { Typography } from '../../../components/Typography';
import { InvoiceTickets } from './InvoiceTickets';
import { selectInvoicesByLotId } from '../../../store/invoices/selectors';
interface MyTicketsProps {
lotId: LotId;
}
export const MyTickets = ({ lotId }: MyTicketsProps): ReactElement => {
const loading = useSelector(selectInvoicesDataLoading);
// we use invoices to group the tickets
const invoices = useSelector((state: ApplicationState) =>
selectInvoicesByLotId(state, lotId),
);
return (
<Container>
<Typography bold>My Tickets</Typography>
{loading ? (
<ActivityIndicator size="small" />
) : invoices.length ? (
invoices.map(invoice => (
<InvoiceTickets key={invoice.id} {...invoice} />
))
) : (
<Typography>You have no tickets, shame on you!</Typography>
)}
</Container>
);
};
const Container = styled.View``;
|
package com.emplk.go4lunch.workmanager;
import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.hilt.work.HiltWorker;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.emplk.go4lunch.R;
import com.emplk.go4lunch.domain.notification.GetNotificationEntityUseCase;
import com.emplk.go4lunch.domain.notification.NotificationEntity;
import com.emplk.go4lunch.ui.restaurant_detail.RestaurantDetailActivity;
import java.time.Clock;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.List;
import dagger.assisted.Assisted;
import dagger.assisted.AssistedInject;
@HiltWorker
public class NotificationWorker extends Worker {
private static final int NOTIFICATION_ID = 0;
private static final String CHANNEL_ID = "channel_id";
private static final CharSequence CHANNEL_NAME = "channel_name";
private final Context context;
@NonNull
private final Clock clock;
@NonNull
private final GetNotificationEntityUseCase getNotificationEntityUseCase;
@AssistedInject
public NotificationWorker(
@Assisted Context context,
@Assisted WorkerParameters workerParams,
@NonNull Clock clock,
@NonNull GetNotificationEntityUseCase getNotificationEntityUseCase
) {
super(context, workerParams);
this.context = context;
this.clock = clock;
this.getNotificationEntityUseCase = getNotificationEntityUseCase;
}
@NonNull
@Override
public Result doWork() {
DayOfWeek dayOfWeek = LocalDate.now(clock).getDayOfWeek();
// No notification scheduled on weekends :)
if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
return Result.success();
}
NotificationEntity notificationEntity = getNotificationEntityUseCase.invoke();
if (notificationEntity != null) {
displayNotification(notificationEntity);
} else {
return Result.success();
}
return Result.success();
}
@SuppressLint("MissingPermission")
private void displayNotification(
@NonNull NotificationEntity notificationEntity
) {
StringBuilder contentText = new StringBuilder();
List<String> workmates = notificationEntity.getWorkmates();
String restaurantName = notificationEntity.getRestaurantName();
String restaurantVicinity = notificationEntity.getRestaurantVicinity();
if (workmates != null &&
!workmates.isEmpty() &&
restaurantName != null &&
restaurantVicinity != null
) {
contentText.append(context.getString(R.string.notification_content_start));
if (workmates.size() == 1) {
contentText.append(context.getString(R.string.notification_content_and)).append(workmates.get(0));
} else if (workmates.size() == 2) {
contentText.append(", ").append(workmates.get(0))
.append(context.getString(R.string.notification_content_and)).append(workmates.get(1));
} else {
for (int i = 0; i < workmates.size() - 1; i++) {
contentText.append(", ").append(workmates.get(i));
}
contentText.append(context.getString(R.string.notification_content_last_and)).append(workmates.get(workmates.size() - 1));
}
contentText.append(context.getString(R.string.notification_content_going_to_eat_at))
.append(restaurantName)
.append(context.getString(R.string.notification_content_located_at))
.append(restaurantVicinity);
} else {
contentText.append(context.getString(R.string.notification_content_solo_user))
.append(restaurantName)
.append(context.getString(R.string.notification_content_located_at))
.append(restaurantVicinity);
}
Intent intent = RestaurantDetailActivity.navigate(context, notificationEntity.getRestaurantId())
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
int flag;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flag = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
} else {
flag = PendingIntent.FLAG_UPDATE_CURRENT;
}
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 0, intent, flag);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.baseline_restaurant_24)
.setContentTitle(context.getString(R.string.notification_content_title))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(contentText.toString()))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
|
# Diálogo HTML para Módulos
Bienvenido al día 19. Hoy tenemos la suerte de jugar con un elemento HTML poco conocido que es absolutamente genial cuando se trata de construir modales. El elemento `<dialog>`. Si tienes prisa por la magnificencia de los modales, puedes saltar más adelante para engancharte al marcado final y al controlador Stimulus. Pero te prometo que el viaje de hoy va a ser divertido.
Abre `templates/voyage/index.html.twig`. En `h1`, voy a pegar algo de contenido nuevo:
[[[ code('57e3c054e3') ]]]
Esto añade un botón "Nuevo viaje".
En la parte inferior, eliminaré el botón antiguo. Este nuevo código no tiene nada de especial: es sólo... un botón. Y cuando vayamos a la página correcta... ¡ahí está! Pero todavía no hace nada.
## Hola `<dialog>`
De vuelta en la plantilla, justo después del botón, añade un elemento `<dialog>`. Dentro proclamaré "Soy un diálogo". Añade también un atributo `open`:
[[[ code('6065f2c526') ]]]
Pulsa actualizar y contempla el elemento `dialog`. Es... interesante. El `dialog` está absolutamente posicionado en la página, centrado horizontalmente y cerca, pero no arriba verticalmente. Eso es porque el elemento `<dialog>` está diseñado para modales... o realmente para cualquier diálogo, como una alerta desechable o cualquier subventana. Es un elemento HTML normal, pero con un montón de superpoderes que vamos a experimentar.
## Hacer un diálogo bonito
Pero primero, tenemos que hacerlo más bonito. De vuelta a la plantilla, pegaré encima ese diálogo:
[[[ code('5466d3a737') ]]]
Esto es una adaptación de Flowbite con algo de ayuda de la IA. Y un diseñador podría crear esto sin problemas. Porque, no hay nada especial: seguimos teniendo un `dialog`, sigue siendo `open`... e incluso las clases Tailwind son bastante aburridas. Establezco una anchura... y redondeo las esquinas. Pero la mayoría de los detalles de posicionamiento ya están incorporados en el elemento. Y la mayor parte del código es contenido modal ficticio para empezar.
El resultado... es impresionante. Aunque... ¡el botón de cerrar aún no hace su trabajo! No te preocupes: ¡ésta es una gran oportunidad para mostrar uno de los superpoderes de diálogo!
Busca el botón de cerrar. A su alrededor, añade un `<form method="dialog">`:
[[[ code('2c2bfb5a3b') ]]]
Este es un botón normal: naturalmente enviará el formulario cuando lo pulsemos, pero el botón no tiene nada especial.
Pero ahora, cuando hagamos clic en X... ¡se cerrará!
## Abrir con un Controlador de Stimulus modal
Para hacer brillar realmente el elemento `<dialog>`, necesitamos un poco de JavaScript.
Dirígete a `assets/controllers/` y crea un nuevo archivo llamado `modal_controller.js`. Haré trampas, robaré algo de contenido de otro controlador... y lo limpiaré. Este controlador será sencillo. Empieza añadiendo un `static targets = ['dialog']`para que podamos encontrar rápidamente el elemento `<dialog>`. A continuación, añade un método `open`. Aquí, digamos `this.dialogTarget.show()`:
[[[ code('bf34ee43f4') ]]]
Éste es otro superpoder del elemento `<dialog>` ¡tiene un método `show()`! Integrada en el elemento `<dialog>` está esta idea central de mostrar y ocultar.
Para utilizar el nuevo controlador, en `index.html.twig`, busca el `div` que contiene el `button` y el `dialog` y añade `data-controller="modal"`. Luego, en el botón, di `data-action="modal#open"`:
[[[ code('8ffa6f2ed2') ]]]
Por último, tenemos que establecer el `<dialog>` como objetivo. Elimina el atributo `open` para que empiece cerrado y sustitúyelo por `data-modal-target="dialog"`:
[[[ code('eb521d9e03') ]]]
¡Me gusta! Aquí empieza cerrado. Y cuando hagamos clic, ¡abre! Cerrar, abrir, ¡cerrar!
## Abrir como modal
Un elemento `<dialog>` tiene dos modos: el modo normal que hemos estado utilizando y un modo modal... que es mucho más útil. Para utilizar el modo modal, en lugar de `show()`, utiliza `showModal()`:
[[[ code('5e680c4cf5') ]]]
Ahora, cuando hacemos clic, se sigue abriendo, pero hay algunas diferencias sutiles. La primera es que podemos cerrarlo pulsando `Esc`. ¡Genial! La segunda es que tiene un fondo. Observa: cuando haga clic, la pantalla se oscurecerá un poco. ¿Lo has visto? Esto también me impide interactuar con el resto de la página. Y esto nos sale gratis gracias a `<dialog>`. Eso es enorme.
## Estilizar el telón de fondo
Inspecciona y busca el elemento `<dialog>` - ahí está. El telón de fondo se añade a través de un pseudoelemento llamado `backdrop`. Así que se encarga de añadirlo por nosotros... pero es un elemento real al que se le puede aplicar estilo. ¡Y quiero darle estilo!
De vuelta a la plantilla, busca el elemento `dialog`. Gracias a Tailwind, podemos aplicar estilo directamente al pseudoelemento telón de fondo. Añade `backdrop:bg-slate-600` y`backdrop:opacity-80`:
[[[ code('e881c041d7') ]]]
Observa el efecto. Esto empieza a ser muy, muy suave.
## Eliminar el desplazamiento de página de fondo
Una cosa que el elemento `dialog` no maneja automáticamente es que... la página del fondo sigue desplazándose. No afecta a nada... pero no es el comportamiento que esperamos.
Para solucionarlo, en el método `open()`, di `document.body` para obtener el elemento body, `.classList.add('overflow-hidden')`:
[[[ code('a5df7ec1bf') ]]]
Y ahora... ¡eso es lo que queremos!
## Limpieza al cerrar
Aunque... si cerramos, ¡todavía no puedo desplazarme! Tenemos que eliminar esa clase.
Para ello, copia el método `open()`, pégalo y llámalo `close()`. Para cerrar el diálogo, llama a `close()`... y luego elimina `overflow-hidden`:
[[[ code('f41a52c94b') ]]]
¡Me gusta! Sólo hay un pequeño problema: ¡no estamos llamando al método `close()`! Si pulsamos X o Esc, el diálogo se cierra, sí, pero sigo sin poder desplazarme porque nada llama a este método `close()` en nuestro controlador.
Afortunadamente, el elemento `dialog` nos cubre las espaldas. Cada vez que un elemento `dialog` se cierra -por cualquier motivo-, envía un evento llamado `close`. Podemos escucharlo.
En el elemento `<dialog>`, añade un conjunto `data-action` a `close->modal#close`:
[[[ code('b5f516bd65') ]]]
Así, independientemente de cómo se cierre `dialog` -presionaré Escape-, ahora podemos desplazarnos porque se ha llamado al método `close()` de nuestro controlador.
## Difuminar el fondo
***TIP
Gracias a la ayuda de Rob Meijer, puedes hacer esto en CSS puro. En el elemento `<dialog>` utiliza `backdrop:bg-opacity-80` en lugar de `backdrop:opacity-80` y luego añade `backdrop:backdrop-blur-sm`. ¡No necesitas JS!
***
Vale, estoy emocionado. ¿Qué más podemos hacer? ¿Qué tal difuminar el fondo? Puedes intentar hacerlo difuminando el fondo. Yo lo he intentado... pero no he conseguido que funcione. No pasa nada. Lo que podemos desenfocar es el cuerpo. Añade una clase más: `blur-sm` y elimina la `blur-sm` en `close()`:
[[[ code('317bb81836') ]]]
Veamos cómo queda. ¡Esto sí que mola!
## Cerrar al hacer clic fuera
Pero si intento hacer clic fuera del modal, no se cierra. Esa es otra cosa que el elemento `dialog` no maneja. Afortunadamente, hay una solución rápida.
Arriba, en el elemento raíz de nuestro controlador... En realidad, podemos ponerlo aquí abajo, en el elemento `dialog`. Añade una nueva acción: `click->modal#clickOutside`:
[[[ code('325c02d4fe') ]]]
Apuesto a que parece raro -se llamará cada vez que hagamos clic en cualquier parte del diálogo-, así que vamos a escribir ese método. Digamos `clickOutside()`, dale un argumento `event`, luego si `event.target === this.dialogTarget`, `this.dialogTarget.close()`:
[[[ code('df205cb52c') ]]]
***TIP
Para que el "clic fuera" funcione perfectamente, en lugar de añadir relleno directamente a `dialog`, añade un elemento dentro y dale el relleno. Ya lo hemos hecho, pero es un detalle importante.
***
`event.target` será el elemento real que ha recibido el clic. Resulta que la única forma de hacer clic exactamente en el propio elemento `dialog` es si haces clic en el fondo. Si haces clic en cualquier otro lugar del interior, `event.target` será uno de estos elementos. Así que son tres ingeniosas líneas de código, pero el resultado es perfecto. Haz clic aquí, sin problemas. Haz clic ahí, cerrado.
## Animación CSS para el fundido de entrada
Llegados a este punto, ¡estoy contento! Pero este tutorial no trata de hacer cosas buenas, sino cosas geniales. Siguiente paso: Quiero que el elemento `dialog` se desvanezca. Podríamos hacerlo con una transición CSS. Pero otra opción es una animación CSS. Lo sé, transiciones, animaciones... CSS tiene muchas.
Una animación es algo que aplicas a un elemento y... simplemente... hará esa animación para siempre. O puedes hacer que se anime sólo una vez. Por ejemplo, podemos hacer que este botón se anime arriba y abajo para siempre. Una de las cosas buenas de las animaciones es que puedes hacer que una animación sólo ocurra una vez... y no empezará hasta que el elemento se haga visible en la página. Por ejemplo, podríamos crear una animación de opacidad 0 a opacidad 100, que se ejecutaría en cuanto nuestro `dialog` se hiciera visible.
Tailwind tiene algunas animaciones incorporadas, pero no una para el desvanecimiento. Así que la añadiremos. Abajo, en `tailwind.config.js`, pegaré sobre la tecla `theme`:
[[[ code('502c1a6c08') ]]]
Esto es principalmente material de animación CSS: añade una nueva llamada `fade-in` que pasará de opacidad 0 a 100 en 1/2 segundo.
Para utilizarlo, busca el elemento `dialog` y añade `animate-fade-in`:
[[[ code('21f4765878') ]]]
Pruébalo. ¡Precioso! ¿Podríamos desvanecerlo? Claro, pero en realidad me gusta que se cierre inmediatamente. Así que voy a omitirlo.
## Módulos y caché de página turbo
Vale, tengo un último detalle antes de despedirte por hoy. Cuando añadimos las transiciones de vista, en `app.js`, desactivamos una función de Turbo llamada caché de página... porque aparentemente no siempre funciona bien con las transiciones de vista. Cuando las transiciones de vista sean estándar en Turbo 8, supongo que esto no será un problema.
De todos modos, cuando la caché está activada
[[[ code('72f086c743') ]]]
en el momento en que haces clic fuera de una página, Turbo toma una instantánea de la página antes de navegar fuera. Cuando volvemos a hacer clic, es instantáneo: ¡boom! En lugar de hacer una petición a la red, utiliza la versión en caché de esta página. Hay más cosas, pero captas la idea.
Con el almacenamiento en caché activado, una cosa de la que tenemos que preocuparnos es de eliminar cualquier elemento temporal de la página antes de que se tome la instantánea, como mensajes tostados o modales. Porque, cuando hagas clic en "Atrás", no querrás que haya una notificación tostada aquí arriba.
La forma en que solemos resolver esto, por ejemplo en `_flashes.html.twig`, es añadir un atributo `data-turbo-temporary`:
[[[ code('071fafff5c') ]]]
Que le dice a Turbo que elimine este elemento antes de tomar la instantánea.
Probemos a añadir esto a nuestro `dialog` para que no aparezca en la instantánea. Para ver qué ocurre, abre el modal y haz clic atrás. Eso acaba de tomar una instantánea de la página anterior. Ahora haz clic hacia adelante. Vaya. Estamos en un estado extraño. Parece que el diálogo ha desaparecido... pero no podemos desplazarnos y la página está borrosa.
Eso es porque necesitamos hacer algo más que ocultar el `dialog`: necesitamos eliminar estas clases del cuerpo. Básicamente, antes de que Turbo tome la instantánea, ¡necesitamos algo que llame al método `close()`!
¡Y podemos hacerlo! En `index.html.twig`, en el elemento controlador raíz -aunque esto podría ir en cualquier sitio- añade un `data-action=""`. Justo antes de que Turbo tome su instantánea, envía un evento llamado `turbo:before-cache`. Podemos escucharlo y luego llamar a `modal#close`. El único detalle es que el evento `turbo:before-cache` no se envía a un elemento específico. Así que escucharlo en este elemento no funcionará. Se envía por encima de nosotros, a la ventana. Es un evento global.
Afortunadamente, Turbo nos proporciona una forma sencilla de escuchar los eventos globales añadiendo`@window`:
[[[ code('67c7f4b82f') ]]]
Es un poco técnico, pero con este único arreglo, podemos abrir el modal, retroceder, avanzar, y la página queda preciosa.
¡Guau! Hoy ha sido un día enorme, ¡pero mira lo que hemos conseguido! Un bonito sistema modal sobre el que tenemos un control total. Mañana va a ser igual de grande, ya que daremos vida a este modal con contenido y formularios dinámicos reales. Hasta entonces.
|
# using f-strings to display multiple variables
# prints both the first name and the last name
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
# using f-strings inside a print statement to compose complete messages using information
# associated with a variable
# prints hello with the first name and the last name
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}!")
# using f-strings to compose a message, and then assign the entire message to a variable
# prints the message
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
message = f"Hello, {full_name.title()}!"
print(message)
|
/**
*
*/
package com.marswork.fulltext.extdict;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.wltea.analyzer.dic.DictSegment;
import com.marswork.core.minitools.object.BasicUtils;
import com.marswork.fulltext.term.WordCache;
/**
* <p>
* 字典值数据源
* <p>
* 字典的数据源有两种<br>
* 一种是来自配置文件,这种数据源会被制作成输入流载入到字典库中<br>
* 一种来来自程序接口,这种数据源以字符串集合形式被载入
*
* @author MarsDJ
* @since 2012-1-4
* @version 1.0
*/
public class DictDataSource {
private InputStream is;
private List<String> ls;
/**
* 构造函数,以输入流形式载入
*
* @param is
* 包含字典值的输入流
*/
public DictDataSource(InputStream is) {
this.is = is;
}
/**
* 构造函数,以字符串集合形式载入
*
* @param ls
* 包含字典值的字符串集合
*/
public DictDataSource(List<String> ls) {
this.ls = ls;
}
public void fillSegment(DictSegment dictSegment) {
fillSegment(dictSegment, 1);
}
public void fillSegment(DictSegment dictSegment, float weight) {
try {
if (is != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 512);
String theWord = null;
do {
theWord = br.readLine();
if (!BasicUtils.isTrimBlank(theWord)) {
dictSegment.fillSegment(theWord.trim().toCharArray());
WordCache.cacheWord(theWord, weight);
}
} while (theWord != null);
} else if (ls != null) {
for (String theWord : ls) {
if (!BasicUtils.isTrimBlank(theWord)) {
dictSegment.fillSegment(theWord.trim().toCharArray());
WordCache.cacheWord(theWord, weight);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
CREATE TABLE COURSE (
CourseID number(10) NOT NULL,
CourseTitle varchar2(15),
TutionFee number(10),
PRIMARY KEY (CourseID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE COURSE_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER COURSE_seq_tr
BEFORE INSERT ON COURSE FOR EACH ROW
WHEN (NEW.CourseID IS NULL)
BEGIN
SELECT COURSE_seq.NEXTVAL INTO :NEW.CourseID FROM DUAL;
END;
/
CREATE TABLE STUDENT (
StudentID number(10) NOT NULL,
SectionID number(10),
FirstName varchar2(50),
LastName varchar2(50),
PhoneNumber varchar2(15),
PhoneType varchar2(15),
AddressID number(10),
DepartmentID number(10),
ProgarmID number(10),
PRIMARY KEY (StudentID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE STUDENT_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER STUDENT_seq_tr
BEFORE INSERT ON STUDENT FOR EACH ROW
WHEN (NEW.StudentID IS NULL)
BEGIN
SELECT STUDENT_seq.NEXTVAL INTO :NEW.StudentID FROM DUAL;
END;
/
CREATE TABLE PROGRAM (
ProgarmID number(10) NOT NULL,
ProgarmTitle varchar2(15) DEFAULT 'Data Science',
PRIMARY KEY (ProgarmID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE PROGRAM_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER PROGRAM_seq_tr
BEFORE INSERT ON PROGRAM FOR EACH ROW
WHEN (NEW.ProgarmID IS NULL)
BEGIN
SELECT PROGRAM_seq.NEXTVAL INTO :NEW.ProgarmID FROM DUAL;
END;
/
CREATE TABLE PROVINCE (
ProvinceID number(10) NOT NULL,
ProvinceName varchar2(15),
PRIMARY KEY (ProvinceID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE PROVINCE_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER PROVINCE_seq_tr
BEFORE INSERT ON PROVINCE FOR EACH ROW
WHEN (NEW.ProvinceID IS NULL)
BEGIN
SELECT PROVINCE_seq.NEXTVAL INTO :NEW.ProvinceID FROM DUAL;
END;
/
CREATE TABLE DEPARTMENT (
DepartmentID number(10) NOT NULL,
DepartmentName varchar2(30),
PRIMARY KEY (DepartmentID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE DEPARTMENT_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER DEPARTMENT_seq_tr
BEFORE INSERT ON DEPARTMENT FOR EACH ROW
WHEN (NEW.DepartmentID IS NULL)
BEGIN
SELECT DEPARTMENT_seq.NEXTVAL INTO :NEW.DepartmentID FROM DUAL;
END;
/
CREATE TABLE ADDRESS (
AddressID number(10) NOT NULL,
Address varchar2(50),
AddressType varchar2(15),
CityID number(10),
ProvinceID number(10),
CountryID number(10),
PRIMARY KEY (AddressID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE ADDRESS_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER ADDRESS_seq_tr
BEFORE INSERT ON ADDRESS FOR EACH ROW
WHEN (NEW.AddressID IS NULL)
BEGIN
SELECT ADDRESS_seq.NEXTVAL INTO :NEW.AddressID FROM DUAL;
END;
/
CREATE TABLE COUNTRY (
CountryID number(10) NOT NULL,
CountryName varchar2(15),
PRIMARY KEY (CountryID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE COUNTRY_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER COUNTRY_seq_tr
BEFORE INSERT ON COUNTRY FOR EACH ROW
WHEN (NEW.CountryID IS NULL)
BEGIN
SELECT COUNTRY_seq.NEXTVAL INTO :NEW.CountryID FROM DUAL;
END;
/
CREATE TABLE CITY (
CityID number(10) NOT NULL,
CityName varchar2(15),
PRIMARY KEY (CityID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE CITY_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER CITY_seq_tr
BEFORE INSERT ON CITY FOR EACH ROW
WHEN (NEW.CityID IS NULL)
BEGIN
SELECT CITY_seq.NEXTVAL INTO :NEW.CityID FROM DUAL;
END;
/
CREATE TABLE SECTION (
SectionID number(10) NOT NULL,
SectionName varchar2(50),
PRIMARY KEY (SectionID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE SECTION_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER SECTION_seq_tr
BEFORE INSERT ON SECTION FOR EACH ROW
WHEN (NEW.SectionID IS NULL)
BEGIN
SELECT SECTION_seq.NEXTVAL INTO :NEW.SectionID FROM DUAL;
END;
/
CREATE TABLE STUDENT_COURSE (
StudentID number(10),
CourseID number(10),
ProfessorID number(10),
PercentGrade NUMBER(4,1),
LetterGrade NUMBER(4,1),
PRIMARY KEY (StudentID, CourseID)
);
CREATE TABLE PROFESSOR (
ProfessorID number(10) NOT NULL,
Salutation varchar2(50) DEFAULT 'Dr',
FirstName varchar2(50),
LastName varchar2(50),
DepartmentID number(10),
PRIMARY KEY (ProfessorID)
);
-- Generate ID using sequence and trigger
CREATE SEQUENCE PROFESSOR_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER PROFESSOR_seq_tr
BEFORE INSERT ON PROFESSOR FOR EACH ROW
WHEN (NEW.ProfessorID IS NULL)
BEGIN
SELECT PROFESSOR_seq.NEXTVAL INTO :NEW.ProfessorID FROM DUAL;
END;
/
CREATE TABLE PROGRAM_COURSE (
ProgarmID number(10),
CourseID number(10),
PRIMARY KEY (ProgarmID, CourseID)
);
ALTER TABLE ADDRESS
ADD FOREIGN KEY (CityID) REFERENCES CITY(CityID),
ADD FOREIGN KEY (ProvinceID) REFERENCES PROVINCE(ProvinceID),
ADD FOREIGN KEY (CountryID) REFERENCES COUNTRY(CountryID);
ALTER TABLE STUDENT
ADD FOREIGN KEY (SectionID) REFERENCES SECTION(SectionID),
ADD FOREIGN KEY (AddressID) REFERENCES ADDRESS(AddressID),
ADD FOREIGN KEY (DepartmentID) REFERENCES DEPARTMENT(DepartmentID),
ADD FOREIGN KEY (ProgarmID) REFERENCES PROGRAM(ProgarmID);
ALTER TABLE STUDENT_COURSE
ADD FOREIGN KEY (StudentID) REFERENCES STUDENT(StudentID),
ADD FOREIGN KEY (CourseID) REFERENCES COURSE(CourseID),
ADD FOREIGN KEY (ProfessorID) REFERENCES PROFESSOR(ProfessorID);
ALTER TABLE PROGRAM_COURSE
ADD FOREIGN KEY (ProgarmID) REFERENCES PROGRAM(ProgarmID),
ADD FOREIGN KEY (CourseID) REFERENCES COURSE(CourseID);
ALTER TABLE PROFESSOR
ADD FOREIGN KEY (DepartmentID) REFERENCES DEPARTMENT(DepartmentID);
|
import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
function ResetPasswordPage() {
const [input, setInput] = useState('');
const [error, setError] = useState(false);
const validateEmail = (email) => {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
const handleInputChange = (e) => {
const email = e.target.value;
if (validateEmail(email)) {
console.log("Email is valid");
setError(false);
} else {
console.log("Email is invalid");
setError(true);
}
setInput(email);
}
const navigate = useNavigate();
const handleSendEmail = async () => {
if (error) {
alert('請輸入正確的Email');
return;
}
try {
const response = await axios.post('http://125.228.62.164:5006/send_email_reset', {
email: input
});
if (response.data.status === '信件已寄出' && response.data.success === true) {
console.log('驗證碼發送成功:', response.data);
localStorage.setItem('email', input);
navigate('/verifycode');
} else {
console.log('驗證碼發送失敗:', response.data);
}
} catch (error) {
console.error('驗證碼發送請求出錯:', error);
}
}
return (
<div className="flex justify-center items-center w-screen h-screen car bg-center bg-no-repeat bg-cover">
<div className="w-[343px] sm:w-[540px] h-[544px] relative">
<div className="w-[343px] sm:w-[540px] h-[544px] bg-white bottom-mark relative z-10 rounded-[25px]">
<div className="flex flex-col px-10 pt-7 relative">
<p className="text-[28px] text-pr font-medium">重設密碼</p>
<p className="text-base text-pr mt-1 mb-7">我們將發送驗證碼至您的信箱。</p>
<p className='text-sc text-lg mb-1'>Email</p>
<input className={`w-full h-14 pl-5 checkout-name rounded-xl border-[1px] border-[#dedede] text-base mb-[184px]
focus:border-[1px] focus:border-[#4339e4] focus:outline-none focus:ring-4 focus:ring-[rgba(67,57,228,0.2)] text-[#545454]
${error ? 'border-[#ff5b60]' : ''}`}
placeholder="mail@example.com"
type="text"
name="email"
value={input}
onChange={handleInputChange}
/>
{error && <div className="text-[#ff5b60] absolute top-[218px]">
請輸入正確的電子信箱
</div>}
<button className={`rounded-full w-full py-4 text-lg font-medium ${input.length > 0 ? 'bg-[#4339e4] text-white hover:bg-[#2e26a3]' : 'bg-[#f0f0f0] text-[#b0b0b0]'}`}
onClick={handleSendEmail}>取得驗證碼</button>
<div className="flex justify-center py-7">
<p className="text-sc">取消重設密碼?</p>
<Link to='/login'>
<button className="text-[#20c374] font-medium underline underline-offset-2">返回登入頁</button>
</Link>
</div>
</div>
</div>
</div>
</div>
)
}
export default ResetPasswordPage;
|
const { AudioPlayerStatus,
createAudioPlayer,
joinVoiceChannel,
NoSubscriberBehavior
} = require('@discordjs/voice')
const { ButtonStyle,
ButtonBuilder,
ActionRowBuilder,
StringSelectMenuBuilder,
EmbedBuilder
} = require('discord.js')
const ytdl = require('ytdl-core')
const wait = require('util').promisify(setTimeout)
const getResource = require('../../../util/getYoutubeResource')
const { withTimeoutResolve } = require('../../../util/timeoutPromise')
const controlButtons = {
stop: new ButtonBuilder()
.setCustomId(JSON.stringify({ behavior: 'stop' }))
.setStyle(ButtonStyle.Danger)
.setLabel('再生停止')
.setEmoji('⏹'),
pause: new ButtonBuilder()
.setCustomId(JSON.stringify({ behavior: 'pause' }))
.setStyle(ButtonStyle.Primary)
.setLabel('一時停止')
.setEmoji('⏸'),
play: new ButtonBuilder()
.setCustomId(JSON.stringify({ behavior: 'play' }))
.setStyle(ButtonStyle.Success)
.setLabel('再生')
.setEmoji('▶'),
}
const getVolumeMenu = () => {
const selectMenu = new StringSelectMenuBuilder()
.setCustomId(JSON.stringify({ behavior: 'volume' }))
.setPlaceholder('音量を選択...')
const volumes = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1].reverse()
volumes.forEach(i => {
selectMenu
.addOptions({
label: `${i * 100}%`,
value: `${i}`,
})
})
return selectMenu
}
const getStatusEmbed = ({ audioName, isLoop, volume, status }) => {
const statuses = {
playing: '再生中',
paused: '一時停止中',
stopped: '再生終了'
}
const embed = new EmbedBuilder()
.setTitle(`${audioName}`)
.addFields(
{ name: '音量', value: `${volume * 100}%`, inline: true },
{ name: 'ループ再生', value: isLoop ? 'オン' : 'オフ', inline: true },
{ name: 'ステータス', value: statuses[status], inline: true }
)
.setAuthor({ name: 'Youtube' })
.setColor('Red')
.setTimestamp()
return embed
}
module.exports.execute = async interaction => {
await interaction.deferReply({ ephemeral: interaction.options.getString('messagetype') === 'message' ? false : true })
const playAudioUrl = interaction.options.getString('url')
if (!ytdl.validateURL(playAudioUrl)) {
interaction.editReply({
content: 'URLが正しくありません',
ephemeral: true,
})
return
}
const playAudioName = (await withTimeoutResolve(ytdl.getBasicInfo(playAudioUrl), 3000, {}))?.videoDetails?.title ?? '不明'
let isLoop = interaction.options.getString('loop') === 'true' ? true : false
let volume = interaction.options.getString('volume') ? Number(interaction.options.getString('volume')) : '0.7'
let status = 'playing'
const member = interaction.member
const channel = member.voice.channel
if (!channel) {
interaction.editReply({
content: '接続先のボイスチャンネルが見つかりません。',
ephemeral: true,
})
return
}
try {
const connection = joinVoiceChannel({
adapterCreator: channel.guild.voiceAdapterCreator,
channelId: channel.id,
guildId: channel.guild.id,
selfDeaf: true,
selfMute: false,
})
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
})
const connectionSubscribe = connection.subscribe(player)
const resource = await getResource(ytdl.getURLVideoID(playAudioUrl))
resource.volume.setVolume(volume)
player.play(resource)
player.on(AudioPlayerStatus.Idle, async () => {
await wait(1000)
player.stop()
status = 'stopped'
if (isLoop == true) {
const resource = await getResource(ytdl.getURLVideoID(playAudioUrl))
player.play(resource)
return
}
interaction.editReply({ content: `${playAudioUrl} を再生停止しました\nコマンドのサジェスト: </playmusic youtube:1063729380888682547>,</playmusic youtubeplaylist:1063729380888682547>`, ephemeral: true, components: [], embeds: [] })
connectionSubscribe.unsubscribe()
connection.destroy()
})
const message = await interaction.editReply({
content: `${playAudioUrl} を再生中`,
ephemeral: true,
components: [
new ActionRowBuilder()
.addComponents(controlButtons.stop, controlButtons.pause),
new ActionRowBuilder()
.addComponents(getVolumeMenu())
],
embeds: [
getStatusEmbed({ isLoop, volume, status, audioName: playAudioName })
]
})
const collector = await message.createMessageComponentCollector({ time: 12 * 60 * 60 * 1000 /*12時間*/ })
collector.on('collect', collectorInteraction => {
const interactionData = JSON.parse(collectorInteraction.customId)
try {
switch (interactionData.behavior) {
case 'stop':
isLoop = false
player.stop()
status = 'stopped'
connectionSubscribe.unsubscribe()
connection.destroy()
collectorInteraction.update({
content: `${playAudioUrl} を停止しました\nコマンドのサジェスト: </playmusic youtube:1063729380888682547>,</playmusic youtubeplaylist:1063729380888682547>`,
ephemeral: true,
components: [],
embeds: []
})
break
case 'pause':
player.pause()
status = 'paused'
collectorInteraction.update({
content: `${playAudioUrl} を一時停止中`,
ephemeral: true,
components: [
new ActionRowBuilder()
.addComponents(controlButtons.stop, controlButtons.play),
new ActionRowBuilder()
.addComponents(getVolumeMenu())
],
embeds: [
getStatusEmbed({ isLoop, volume, status, audioName: playAudioName })
]
})
break
case 'play':
player.unpause()
status = 'playing'
collectorInteraction.update({
content: `${playAudioUrl} を再生中`,
ephemeral: true,
components: [
new ActionRowBuilder()
.addComponents(controlButtons.stop, controlButtons.pause),
new ActionRowBuilder()
.addComponents(getVolumeMenu())
],
embeds: [
getStatusEmbed({ isLoop, volume, status, audioName: playAudioName })
]
})
break
case 'volume': {
volume = Number(collectorInteraction.values[0])
resource.volume.setVolume(volume)
collectorInteraction.update({
content: `${playAudioUrl} を再生中`,
ephemeral: true,
components: [
new ActionRowBuilder()
.addComponents(controlButtons.stop, controlButtons.pause),
new ActionRowBuilder()
.addComponents(getVolumeMenu())
],
embeds: [
getStatusEmbed({ isLoop, volume, status, audioName: playAudioName })
]
})
break
}
default:
break
}
} catch (e) {
collectorInteraction.reply({
content: 'エラーが発生しました' + e,
ephemeral: true
})
}
})
} catch (e) {
await interaction.editReply({
content: `エラーが発生しました: ${e}`,
ephemeral: true
})
}
}
|
import { useState } from 'react';
import { AimDistanceMark, CalculatedMarks, Status } from '../../types';
const calcBallisticsParams = (body: AimDistanceMark) => {
return fetch('https://calculate-aim.azurewebsites.net/api/archerAim?task=CalcBallisticsPars', {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(body),
});
};
const useBallisticsParams = () => {
const [status, setStatus] = useState<Status>(Status.Idle);
const [error, setError] = useState<any | null>(null);
const calculateBallisticsParams = async (body: AimDistanceMark): Promise<CalculatedMarks | undefined> => {
try {
setStatus(Status.Pending);
setError(null);
const result = await calcBallisticsParams(body);
if (result.ok) {
return result.json();
}
} catch (error) {
setStatus(Status.Error);
setError(error);
} finally {
setStatus(Status.Idle);
}
};
return {
status,
error,
calculateBallisticsParams,
};
};
export default useBallisticsParams;
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
//Enums: user defined data types, have so many choices
// compare with booleans, 1 or 0, although it has only two choices
//imagine you have an ecommerce site
//pending or shipped: accept or not
//cancelled or not
//perks: 1. maintanance of smartcontracts increases
// 2. readablity
// 3. required**
// 4. reduces bugs
contract enumsCont{
enum Status{
Pending,//0th index
Shipped,//1st
Accepted,//2nd
Rejected,//3rd
Cancel//4th
}
Status status;
function getStatus() public view returns(Status){
return status;
}
function setStatus(Status _status) public{
status=_status;
}
function rej() public{
status = Status.Rejected;
}
function reset() public{
delete status;
}
}
|
package com.example.projektmunka.adapter
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.example.projektmunka.databinding.ListItemBinding
import com.example.projektmunka.uiData.TourItem
class TourAdapter(context: Context, private val tourList: ArrayList<TourItem>) :
ArrayAdapter<TourItem>(context, 0, tourList) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val binding = ListItemBinding.inflate(LayoutInflater.from(context), parent, false)
val currentTourItem = tourList[position]
// Set data to the views using ViewBinding
binding.tourPic.setImageResource(currentTourItem.imageId)
binding.tourName.text = currentTourItem.name
binding.tourDescription.text = currentTourItem.description
return binding.root
}
}
|
import { faChevronRight, faHome, faPeopleGroup } from '@fortawesome/free-solid-svg-icons'
import React, { useEffect, useState } from 'react'
import { getDataFromMongo } from '../api'
import Breadcrumbs from '../components/Breadcrumbs'
import Header from '../components/Header'
import SearchBar from '../components/SearchBar'
const Sexo = () => {
const [search, setSearch] = useState('')
const [sexo, setSexo] = useState([])
useEffect(() => {
getDataFromMongo('sexo')
.then((data) => {
setSexo(data)
}).catch(err => {
console.error(err);
});
}, [search])
const filteredSexo = sexo.filter(collection => {
const lowerCaseSearch = search.toLowerCase();
return (
collection.Codigo.toLowerCase().includes(lowerCaseSearch) ||
collection.Nombre.toLowerCase().includes(lowerCaseSearch)
);
});
const handleSearch = event => {
setSearch(event.target.value);
};
const items = [
{
label: 'Inicio',
to: '/',
icon: faHome
},
{
label: 'Sexo',
icon: faChevronRight
}
]
return (
<>
<Breadcrumbs items={items}/>
<Header
icon={faPeopleGroup}
iconBgColor={'bg-indigo-50'}
iconTextColor={'text-indigo-600'}
title="Sexo"
description="Tabla de Referencia Sexo de SISPRO"
updateDate="2021-08-13"
numberRegisters="3"
/>
<SearchBar
value={search}
handleChange={handleSearch}
/>
{filteredSexo.map(collection => (
<div
className='border rounded bg-white border-indigo-200 mt-2 py-1 px-4'
key={collection._id}
>
<div className='flex py-2'>
<div className='mr-2 font-semibold'>{collection.Codigo}</div>
<div>{collection.Nombre}</div>
</div>
</div>
))}
</>
)
}
export default Sexo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.