text
stringlengths 184
4.48M
|
|---|
# Load required libraries
library(ggplot2)
# Given data
genes <- c("psbA", "psbD", "pmoC", "katG", "ahbD", "gpx", "cobS", "cobT", "nadE", "cysC", "cysD", "cysH", "cysK")
percentages <- data.frame(
Genes = factor(genes, levels = genes),
`A75-100` = c(91.5, 94.2, 89.3, 86.7, 85.4, 89.3, 85.9, 89.8, 100, 91.7, 98.3, 92.7, 92.7),
`B50-75` = c(82.6, 81.6, 58.3, 63.6, 82.3, 80.2, 77.8, 78.7, 91.5, 89.4, 68.4, 84.7, 82.9)
)
# Convert data to long format for ggplot2
percentages_long <- tidyr::gather(percentages, Range, Percentage, -Genes)
# Create the bar plot
bar_plot <- ggplot(percentages_long, aes(x = Genes, y = Percentage, fill = Range)) +
geom_bar(stat = "identity", position = "dodge", width = 0.85, color = "white") +
scale_fill_manual(values = c("#20B2AA", "#ADD8E6")) +
labs(title = "Gene Expression Percentages",
x = "Genes",
y = "Percentage") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
axis.title.x = element_text(size = 12, face = "bold"),
axis.title.y = element_text(size = 12, face = "bold"),
plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
legend.title = element_blank(),
legend.text = element_text(size = 10),
legend.position = "bottom",
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"),
legend.background = element_rect(fill = "white", size = 0.5),
legend.box.background = element_rect(color = "black", size = 0.5))
# Print the plot
print(bar_plot)
|
//{ Driver Code Starts
// C++ program to remove recurring digits from
// a given number
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/*
Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is a leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader.
*/
class Solution{
//Function to find the leaders in the array.
public:
vector<int> leaders(int a[], int n){
// Code here
vector<int> res;
int currMax=a[n-1];
res.emplace_back(currMax);
for(int iter=n-2; iter>=0; iter--){
if(a[iter] >= currMax){
currMax = a[iter];
res.emplace_back(currMax);
}
}
reverse(res.begin(), res.end());
return res;
}
};
//{ Driver Code Starts.
int main()
{
long long t;
cin >> t;//testcases
while (t--)
{
long long n;
cin >> n;//total size of array
int a[n];
//inserting elements in the array
for(long long i =0;i<n;i++){
cin >> a[i];
}
Solution obj;
//calling leaders() function
vector<int> v = obj.leaders(a, n);
//printing elements of the vector
for(auto it = v.begin();it!=v.end();it++){
cout << *it << " ";
}
cout << endl;
}
}
// } Driver Code Ends
|
# getGenesis
### How to use it
```typescript
// Import required libraries and modules from Tatum SDK
import { TatumSDK, AlgorandAlgod, Network } from '@tatumio/tatum';
// Initialize the Tatum SDK for Algorand
const tatum = await TatumSDK.init<AlgorandAlgod>({ network: Network.ALGORAND_ALGOD });
// Retrieve the genesis information
const genesisInfo = await tatum.rpc.getGenesis();
// Log the genesis information
console.log('Algorand Genesis:', genesisInfo);
// Always destroy the Tatum SDK instance when done to stop any background processes
await tatum.destroy();
```
### Overview
The `getGenesis` method allows you to retrieve the entire genesis file in JSON format.
### Example Use Cases
1. **Genesis Information**: Developers can use this method to retrieve the genesis information of the Algorand network, including details about the network configuration.
### Request Parameters
The `getGenesis` method does not require any parameters.
### Return Object
The method returns a string representing the entire genesis file in JSON format.
Please note that the structure of the returned object may change in different Algorand RPC versions.
|
---
layout: container
name: "quay.io/biocontainers/bioconductor-hgu95dprobe"
maintainer: "@vsoch"
github: "https://github.com/singularityhub/shpc-registry/blob/main/quay.io/biocontainers/bioconductor-hgu95dprobe/container.yaml"
config_url: "https://raw.githubusercontent.com/singularityhub/shpc-registry/main/quay.io/biocontainers/bioconductor-hgu95dprobe/container.yaml"
updated_at: "2023-01-13 03:05:13.147419"
latest: "2.18.0--r42hdfd78af_11"
container_url: "https://biocontainers.pro/tools/bioconductor-hgu95dprobe"
versions:
- "2.18.0--r41hdfd78af_9"
- "2.18.0--r41hdfd78af_10"
- "2.18.0--r42hdfd78af_11"
description: "shpc-registry automated BioContainers addition for bioconductor-hgu95dprobe"
config: {"url": "https://biocontainers.pro/tools/bioconductor-hgu95dprobe", "maintainer": "@vsoch", "description": "shpc-registry automated BioContainers addition for bioconductor-hgu95dprobe", "latest": {"2.18.0--r42hdfd78af_11": "sha256:dc05a993d26b30e9240a8787dab033303a3f799f62c22c2f0d36e08d93650f83"}, "tags": {"2.18.0--r41hdfd78af_9": "sha256:7e8762028c0a8ee1945a16c59db526b50dce534d65e99b4bf80709224e2ee4a9", "2.18.0--r41hdfd78af_10": "sha256:0703fd11cc57c7ca5ed4b1724d67bd16591073c0f3de820f79df0b6693a2aa65", "2.18.0--r42hdfd78af_11": "sha256:dc05a993d26b30e9240a8787dab033303a3f799f62c22c2f0d36e08d93650f83"}, "docker": "quay.io/biocontainers/bioconductor-hgu95dprobe"}
---
This module is a singularity container wrapper for quay.io/biocontainers/bioconductor-hgu95dprobe.
shpc-registry automated BioContainers addition for bioconductor-hgu95dprobe
After [installing shpc](#install) you will want to install this container module:
```bash
$ shpc install quay.io/biocontainers/bioconductor-hgu95dprobe
```
Or a specific version:
```bash
$ shpc install quay.io/biocontainers/bioconductor-hgu95dprobe:2.18.0--r42hdfd78af_11
```
And then you can tell lmod about your modules folder:
```bash
$ module use ./modules
```
And load the module, and ask for help, or similar.
```bash
$ module load quay.io/biocontainers/bioconductor-hgu95dprobe/2.18.0--r42hdfd78af_11
$ module help quay.io/biocontainers/bioconductor-hgu95dprobe/2.18.0--r42hdfd78af_11
```
You can use tab for auto-completion of module names or commands that are provided.
<br>
### Commands
When you install this module, you will be able to load it to make the following commands accessible.
Examples for both Singularity, Podman, and Docker (container technologies supported) are included.
#### bioconductor-hgu95dprobe-run:
```bash
$ singularity run <container>
$ podman run --rm -v ${PWD} -w ${PWD} <container>
$ docker run --rm -v ${PWD} -w ${PWD} <container>
```
#### bioconductor-hgu95dprobe-shell:
```bash
$ singularity shell -s /bin/sh <container>
$ podman run --it --rm --entrypoint /bin/sh -v ${PWD} -w ${PWD} <container>
$ docker run --it --rm --entrypoint /bin/sh -v ${PWD} -w ${PWD} <container>
```
#### bioconductor-hgu95dprobe-exec:
```bash
$ singularity exec <container> "$@"
$ podman run --it --rm --entrypoint "" -v ${PWD} -w ${PWD} <container> "$@"
$ docker run --it --rm --entrypoint "" -v ${PWD} -w ${PWD} <container> "$@"
```
#### bioconductor-hgu95dprobe-inspect:
Podman and Docker only have one inspect type.
```bash
$ podman inspect <container>
$ docker inspect <container>
```
#### bioconductor-hgu95dprobe-inspect-runscript:
```bash
$ singularity inspect -r <container>
```
#### bioconductor-hgu95dprobe-inspect-deffile:
```bash
$ singularity inspect -d <container>
```
#### bioconductor-hgu95dprobe
```bash
$ singularity run <container>
$ podman run --rm -v ${PWD} -w ${PWD} <container>
$ docker run --rm -v ${PWD} -w ${PWD} <container>
```
In the above, the `<container>` directive will reference an actual container provided
by the module, for the version you have chosen to load. An environment file in the
module folder will also be bound. Note that although a container
might provide custom commands, every container exposes unique exec, shell, run, and
inspect aliases. For anycommands above, you can export:
- SINGULARITY_OPTS: to define custom options for singularity (e.g., --debug)
- SINGULARITY_COMMAND_OPTS: to define custom options for the command (e.g., -b)
- PODMAN_OPTS: to define custom options for podman or docker
- PODMAN_COMMAND_OPTS: to define custom options for the command
<br>
### Install
You can install shpc locally (for yourself or your user base) as follows:
```bash
$ git clone https://github.com/singularityhub/singularity-hpc
$ cd singularity-hpc
$ pip install -e .
```
Have any questions, or want to request a new module or version? [ask for help!](https://github.com/singularityhub/singularity-hpc/issues)
|
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
from products.models import Product
from .utils import generate_key
class Checking(models.Model):
product = models.ForeignKey(
Product,
on_delete=models.CASCADE,
related_name="products",
blank=True, null=True
)
bar_code = models.CharField(max_length=50, unique=True)
serial_number = models.CharField(max_length=50, unique=True)
def __str__(self):
return str(self.serial_number)
@receiver(post_save, sender=Product)
def create_checking_for_product(sender, instance, *args, **kwargs):
check = Checking.objects.filter(product=instance)
difference = abs(check.count() - instance.quantity)
if instance and instance.quantity and difference > 0:
for _ in range(difference):
Checking.objects.create(
product=instance,
bar_code=generate_key(5),
serial_number=generate_key(7)
)
|
package inheritance;
import java.util.ArrayList;
import java.util.List;
public class Theater implements Reviewable {
private String name;
private List<String> movies;
private List<Review> reviews;
private int rating;
public Theater(String name, List<String> movies) {
this.name = name;
this.movies = movies;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getMovies() {
return movies;
}
public void setMovies(List<String> movies) {
this.movies = movies;
}
public void addMovie (String movie){
this.movies.add(movie);
}
public void removeMovie (String movie){
this.movies.remove(movie);
}
public List<Review> getReviews() {
return reviews;
}
public int getRating() {
return rating;
}
@Override
public String toString() {
return "Theater{" +
"name='" + name + '\'' +
", movies=" + movies +
'}';
}
public void addReview(Review review){
if (this.reviews==null)
reviews = new ArrayList<>();
this.reviews.add(review);
calculateRating();
}
@Override
public void addMultipleReviews(List<Review> reviews) {
if (this.reviews==null)
this.reviews = new ArrayList<>(reviews);
else this.reviews.addAll(reviews);
calculateRating();
}
public void calculateRating() {
int sum = 0;
int rate = 0;
for (Review rev : this.reviews) {
sum += rev.getNumberOfStars();
}
rate = sum / this.reviews.size();
this.rating = rate;
}
}
|
/**
* Copyright (c) Christine Abernathy.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import SwiftUI
import SwiftData
struct MainTabView: View {
@Environment(\.modelContext) private var modelContext
static var currentScriptureFetchDescriptor: FetchDescriptor<Scripture> {
var descriptor = FetchDescriptor<Scripture>(
predicate: #Predicate<Scripture> { !$0.completed },
sortBy: [SortDescriptor(\Scripture.createdAt, order: .forward)])
descriptor.fetchLimit = 1
return descriptor
}
@Query(currentScriptureFetchDescriptor) private var currentScripture: [Scripture]
@Query(filter: #Predicate<Scripture> { $0.completed },
sort: \Scripture.createdAt, order: .forward) private var completedScriptures: [Scripture]
@SceneStorage("MainTabView.SelectedTab") private var selectedTab: Int = 1
@State private var savedScriptures: [Scripture] = []
let shouldSwitchToHomeTab = NotificationManager.shared.shouldSwitchToHomeTab
var body: some View {
TabView(selection: $selectedTab) {
ScripturesListView(scriptures: completedScriptures)
.tabItem {
Label("Review", systemImage: "checkmark.rectangle.stack.fill")
}
.tag(0)
ScriptureRevealView(scriptures: currentScripture)
.tabItem {
Label("Memorize", systemImage: "book.fill")
}
.tag(1)
SettingsView()
.tabItem {
Label("Settings", systemImage: "gearshape.fill")
}
.tag(2)
}
.onChange(of: shouldSwitchToHomeTab) {
if shouldSwitchToHomeTab {
selectedTab = 1
}
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
handleScriptureSchedule()
}
}
private func handleScriptureSchedule() {
// Check if the day and scripture needs to be updated
let refrshScripture = ScheduleManager.shared.updateCheck()
if refrshScripture && currentScripture.count > 0 {
// Mark the scripture as complete
withAnimation(.smooth) {
currentScripture[0].completed = true
}
}
}
}
#Preview {
MainTabView()
}
|
package dev.yogizogi.domain.user.service;
import static dev.yogizogi.global.common.model.constant.Format.DONE;
import dev.yogizogi.domain.meokprofile.repository.MeokProfileRepository;
import dev.yogizogi.domain.user.exception.AlreadyUsePasswordException;
import dev.yogizogi.domain.user.exception.NotExistPhoneNumberException;
import dev.yogizogi.domain.user.exception.NotExistUserException;
import dev.yogizogi.domain.user.model.dto.response.CreateUserProfileOutDto;
import dev.yogizogi.domain.user.model.dto.response.FindPasswordOutDto;
import dev.yogizogi.domain.user.model.entity.User;
import dev.yogizogi.domain.user.repository.UserRepository;
import dev.yogizogi.global.common.code.ErrorCode;
import dev.yogizogi.global.common.status.BaseStatus;
import dev.yogizogi.global.common.status.MessageStatus;
import dev.yogizogi.infra.coolsms.CoolSmsService;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@RequiredArgsConstructor
public class UserService {
private final CoolSmsService coolSmsService;
private final PasswordEncoder passwordEncoder;
private final UserRepository userRepository;
private final MeokProfileRepository meokProfileRepository;
@Transactional(readOnly = true)
public boolean isUsedNickname(String nickname) {
return userRepository.findByProfileNicknameAndStatus(nickname, BaseStatus.ACTIVE).isPresent();
}
@Transactional(readOnly = true)
public boolean isUsedPhoneNumber(String phoneNumber) {
return userRepository.findByPhoneNumberAndStatus(phoneNumber, BaseStatus.ACTIVE).isPresent();
}
@Transactional(readOnly = true)
public FindPasswordOutDto findPassword(String phoneNumber) {
User findUser = userRepository.findByPhoneNumberAndStatus(phoneNumber, BaseStatus.ACTIVE)
.orElseThrow(() -> new NotExistUserException(ErrorCode.NOT_EXIST_USER));
coolSmsService.sendOne(phoneNumber);
return FindPasswordOutDto.of(
MessageStatus.SUCCESS, findUser.getPhoneNumber()
);
}
public String updatePassword(String phoneNumber, String password) {
User findUser = userRepository.findByPhoneNumberAndStatus(phoneNumber, BaseStatus.ACTIVE)
.orElseThrow(() -> new NotExistUserException(ErrorCode.NOT_EXIST_USER));
if (passwordEncoder.matches(password, findUser.getPassword())) {
throw new AlreadyUsePasswordException(ErrorCode.ALREADY_USE_PASSWORD);
}
findUser.updatePassword(passwordEncoder.encode(password));
return DONE;
}
public CreateUserProfileOutDto createProfile(UUID id, String nickname, String imageUrl, String introduction) {
User findUser = userRepository.findByIdAndStatus(id, BaseStatus.ACTIVE)
.orElseThrow(() -> new NotExistUserException(ErrorCode.NOT_EXIST_USER));
findUser.setProfile(nickname, imageUrl, introduction);
return CreateUserProfileOutDto.of(
findUser.getProfile().getNickname(),
findUser.getProfile().getImageUrl(),
findUser.getProfile().getIntroduction()
);
}
public String deleteUser(String phoneNumber) throws NotExistPhoneNumberException {
User deleteUser = userRepository.findByPhoneNumberAndStatus(phoneNumber, BaseStatus.ACTIVE)
.orElseThrow(() -> new NotExistUserException(ErrorCode.NOT_EXIST_USER));
deleteUser.inactive();
// meokProfileRepository.delete(deleteUser.getMeokProfile());
userRepository.delete(deleteUser);
return DONE;
}
}
|
<div class="modal fade modal-quantity" id="another_quantity" tabindex="-1" aria-labelledby="another_quantity" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="another_quantity">Ingrese la cantidad deseada</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<%= form.label :requested_money, 'Ingrese la cantidad a retirar', class: "form-label"%></br>
<%= form.number_field :requested_money, class: "form-control", placeholder: "Ej: 2500", id: 'number-field'%>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<%= form.submit 'Retirar', class: "btn btn-outline-primary", id: "button-number"%>
</div>
</div>
</div>
</div>
<script>
var numberField = document.querySelector("#number-field");
var modalContainer = document.querySelector(".modal-body");
var buttonSubmit = document.querySelector("#button-number");
numberField.addEventListener('blur', function () {
if (numberField.value === "" || parseInt(numberField.value) % 50 !== 0) {
var alert = document.querySelectorAll(".alert-danger");
if (alert.length == 1) {
alert[0].remove();
}
createAlert(modalContainer, "No puedes retirar billetes que no sean de 50, 100, 200 o 500")
buttonSubmit.disabled = true;
return;
}else if(parseInt(numberField.value) > 6000){
var alert = document.querySelectorAll(".alert-danger");
if (alert.length == 1) {
alert[0].remove();
}
createAlert(modalContainer, "No se permite retirar cantidades mayores a 6000")
buttonSubmit.disabled = true;
return;
}
else{
var alert = document.querySelector(".alert-danger");
alert.remove();
buttonSubmit.disabled = false;
}
})
function createAlert(modal, msg){
var div = document.createElement('div')
var text = document.createElement('p');
text.textContent = msg;
div.classList.add("alert");
div.classList.add("alert-danger")
div.classList.add("mt-3")
div.appendChild(text);
modal.append(div);
}
</script>
|
// First line of code
export {}
let message = "Welcome Back";
console.log(message);
// variable types
let isBeginner: boolean = true;
let total: number = 0;
let name: string = "Gabriel";
let sentence: string = `My name is ${name},
I am a beginner in Typescript`;
console.log(sentence);
// More types
let n: null = null;
let u: undefined = undefined;
// Declaring arrays
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
let person1: [string, number] = ["chris", 33];
enum Color { Red, Green, Blue };
let c: Color = Color.Blue;
console.log(c);
// any variable type
let myVariable: any = 10;
// unknown variable type
let myVariable1: unknown = 10
function hasName(obj: any): obj is { name: string } {
return !! obj &&
typeof obj === "object" &&
"name" in obj
}
if (hasName(myVariable1)) {
console.log(myVariable1.name)
}
//(myVariable as string).toUpperCase();
// Functions
function add(num1: number, num2: number = undefined): number {
if (num2) return num1 + num2;
else return num1;
}
console.log(add(5));
console.log(add(5, 10));
// Interfaces
interface Person {
firstName: string;
lastName?: string;
};
function fullName(person: Person) {
console.log(`${person.firstName} ${person.lastName}`);
}
let p = {
firstName: "Gabriel",
lastName: "Nweke"
}
fullName(p);
// Classes
class Employee {
public employeeName: string;
constructor(name: string) {
this.employeeName = name;
}
greet() {
console.log(`Good Day ${this.employeeName}`);
}
}
let emp1 = new Employee("Gabriel");
console.log(emp1.employeeName)
emp1.greet();
class Manager extends Employee {
constructor(managerName: string) {
super(managerName);
}
delegateWork() {
console.log("Manager delegating tasks");
}
}
let m1 = new Manager("Bruce");
console.log(); console.log(m1.employeeName);
m1.greet();
m1.delegateWork()
// Access Modifiers
|
import { PlaylistSettings } from "../../utils/types.ts";
export default function PlaylistSettingsView({
playlistSettings,
setPlaylistSettings,
setPlaylist,
}: {
playlistSettings: PlaylistSettings;
setPlaylistSettings: React.Dispatch<React.SetStateAction<PlaylistSettings>>;
setPlaylist: React.Dispatch<any>;
}) {
const updatePlaylistName = (e: React.ChangeEvent<HTMLInputElement>) => {
setPlaylistSettings({
...playlistSettings,
name: e.target.value,
});
};
const updatePlaylistPrivacy = (e: React.ChangeEvent<HTMLInputElement>) => {
setPlaylistSettings({
...playlistSettings,
public: !playlistSettings.public,
});
};
const createPlaylist = async (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
const trackIds = playlistSettings.tracks.map((track) => track.uri);
const body = {
name: playlistSettings.name,
public: playlistSettings.public,
tracks: trackIds,
description: playlistSettings.description,
};
console.log(body);
const createPlaylist = await (
await fetch("/api/playlist", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
})
).json();
setPlaylist(createPlaylist);
};
let submittable = false;
if (playlistSettings.name.length > 0 && playlistSettings.tracks.length > 0) {
submittable = true;
}
// lock icon JSX
const lock = <i className="bi bi-lock-fill"></i>;
const unlock = <i className="bi bi-unlock-fill"></i>;
let icon = null;
if (playlistSettings.public) {
icon = unlock;
} else {
icon = lock;
}
return (
<div className="row mb-3">
<h3>Playlist Settings</h3>
<p className="fs-7">
Create a playlist with the tracks you've selected. To create the
playlist, you must provide it with a name. You may optionally decide to
make the playlist public or private.
</p>
<div className="mb-3">
<input
type="text"
className="form-control"
id="playlist-name"
placeholder="Name"
onChange={updatePlaylistName}
/>
</div>
<div className="form-check mb-3">
<input
className="form-check-input"
type="checkbox"
value=""
id="private-playlist"
onChange={updatePlaylistPrivacy}
/>
<label className="form-check-label" htmlFor="private-playlist">
Privacy
</label>{" "}
(Currently: {icon})
</div>
{playlistSettings.tracks.length > 0 && (
<>
<strong>Tracks</strong>
<ul>
{playlistSettings.tracks.map((track) => {
return (
<li key={track.id}>
<a target="_blank" href={track.external_urls?.spotify}>
{track.name}
</a>
</li>
);
})}
</ul>
</>
)}
<button
className="btn btn-primary"
disabled={!submittable}
onClick={(e) => createPlaylist(e)}
>
Create Playlist
</button>
</div>
);
}
|
const knex = require('../conexao');
const listarProdutos = async (req, res) => {
const { usuario } = req;
const { categoria } = req.query;
try {
const produtos = await knex('produtos')
.where({ usuario_id: usuario.id })
.where(query => {
if (categoria) {
return query.where('categoria', 'ilike', `%${categoria}%`).debug();
}
});
return res.status(200).json(produtos);
} catch (error) {
return res.status(400).json(error.message);
}
}
const obterProduto = async (req, res) => {
const { usuario } = req;
const { id } = req.params;
try {
const consultarProduto = await knex('produtos').where({ id: id, usuario_id: usuario.id }).returning('*').debug();
if (consultarProduto.length === 0) {
return res.status(404).json('Produto não encontrado');
}
return res.status(200).json(consultarProduto[0]);
} catch (error) {
return res.status(400).json(error.message);
}
}
const cadastrarProduto = async (req, res) => {
const { usuario } = req;
const { nome, estoque, preco, categoria, descricao, imagem } = req.body;
if (!nome) {
return res.status(404).json('O campo nome é obrigatório');
}
if (!estoque) {
return res.status(404).json('O campo estoque é obrigatório');
}
if (!preco) {
return res.status(404).json('O campo preco é obrigatório');
}
if (!descricao) {
return res.status(404).json('O campo descricao é obrigatório');
}
try {
const produto = await knex('produtos').insert(
{
usuario_id: usuario.id,
nome,
estoque,
preco,
categoria,
descricao,
imagem
})
.returning('*')
.debug();
if (produto.length === 0) {
return res.status(400).json('O produto não foi cadastrado');
}
return res.status(200).json(produto[0]);
} catch (error) {
return res.status(400).json(error.message);
}
}
const atualizarProduto = async (req, res) => {
const { usuario } = req;
const { id } = req.params;
const { nome, estoque, preco, categoria, descricao, imagem } = req.body;
if (!nome && !estoque && !preco && !categoria && !descricao && !imagem) {
return res.status(404).json('Informe ao menos um campo para atualizaçao do produto');
}
try {
const consultarProduto = await knex('produtos').where({ id: id, usuario_id: usuario.id }).returning('*').debug();
if (consultarProduto.length === 0) {
return res.status(404).json('Produto não encontrado');
}
const produtoAtualizado = await knex('produtos')
.update({ nome, estoque, preco, categoria, descricao, imagem })
.where({ id: id, usuario_id: usuario.id })
.returning('*')
.debug();
if (produtoAtualizado.length === 0) {
return res.status(400).json("O produto não foi atualizado");
}
return res.status(200).json(produtoAtualizado[0]);
} catch (error) {
return res.status(400).json(error.message);
}
}
const excluirProduto = async (req, res) => {
const { usuario } = req;
const { id } = req.params;
try {
const consultarProduto = await knex('produtos').where({ id: id, usuario_id: usuario.id }).returning('*').debug();
if (consultarProduto.length === 0) {
return res.status(404).json('Produto não encontrado');
}
const produtoExcluido = await knex('produtos').delete().where({ id }).returning('*').debug();
if (produtoExcluido.length === 0) {
return res.status(400).json("O produto não foi excluido");
}
return res.status(200).json(produtoExcluido[0]);
} catch (error) {
return res.status(400).json(error.message);
}
}
module.exports = {
listarProdutos,
obterProduto,
cadastrarProduto,
atualizarProduto,
excluirProduto
}
|
```cxx
template <typename T>
struct BinaryTreeNode {
T data;
shared_ptr<BinaryTreeNode<T>> left;
shared_ptr<BinaryTreeNode<T>> right;
BinaryTreeNode() { }
BinaryTreeNode(T data, shared_ptr<BinaryTreeNode<T>> left, shared_ptr<BinaryTreeNode<T>> right) {
this->data = data;
this->left = left;
this->right = right;
}
};
struct Interval {
int left;
int right;
};
#include <memory>
#include <vector>
using std::shared_ptr;
using std::vector;
class Solution {
public:
vector<int> rangeLookupInBst(const shared_ptr<BinaryTreeNode<int>> &tree,
const Interval &interval) {
vector<int> result;
rangeLookupInBSTHelper(tree, interval, &result);
return result;
}
private:
void rangeLookupInBSTHelper(const shared_ptr<BinaryTreeNode<int>> &tree,
const Interval &interval, vector<int> *result) {
if (tree == nullptr) {
return;
}
if (interval.left <= tree->data && tree->data <= interval.right) {
// tree->data lies in the interval.
rangeLookupInBSTHelper(tree->left, interval, result);
result->emplace_back(tree->data);
rangeLookupInBSTHelper(tree->right, interval, result);
} else if (interval.left > tree->data) {
rangeLookupInBSTHelper(tree->right, interval, result);
} else { // interval.right > tree->data
rangeLookupInBSTHelper(tree->left, interval, result);
}
}
};
```
|
import { useEffect, useState } from "react";
import { diffWords } from "diff";
export function SlidePlay({ slideRef, slides, current, language }) {
const [selectedSlide, setSelectedSlide] = useState(current);
const [diffedWords, setDiffedWords] = useState<any>([]);
useEffect(() => {
const handleKeyDown = (event) => {
if (event.key === "ArrowRight") {
handleForward();
} else if (event.key === "ArrowLeft") {
handleBackward();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [selectedSlide]);
useEffect(() => {
const diffedWords = diffWords("", slides[selectedSlide].content);
setDiffedWords(diffedWords);
}, []);
const handleForward = () => {
if (selectedSlide === slides.length - 1) return;
let next = Math.min(slides.length - 1, selectedSlide + 1);
setSelectedSlide(next);
const diffedWords = diffWords(
slides[selectedSlide].content,
slides[next].content,
);
setDiffedWords(diffedWords);
};
const handleBackward = () => {
if (selectedSlide === 0) return;
let prev = Math.max(0, selectedSlide - 1);
setSelectedSlide(prev);
const diffedWords = diffWords(
slides[selectedSlide].content,
slides[prev].content,
);
setDiffedWords(diffedWords);
};
return (
<div
ref={slideRef}
className="border-1 border-1 absolute inset-0 -z-10 rounded-md border border-slate-500 bg-slate-900 p-4 font-code"
>
<div>
<pre
style={{ backgroundColor: "transparent" }}
className="bg-transparent font-code"
>
<code className="font-code">
{diffedWords.map((part, index) => {
return (
<span
key={index}
className={`${part.added ? "animate-fade-up" : ""} ${part.removed ? "animate-fade-out fill-mode-forwards" : ""}`}
>
<span>{part.value}</span>
</span>
);
})}
</code>
</pre>
</div>
</div>
);
}
|
import os
import fitz # pip install PyMuPDF
from tkinter import Tk, filedialog # inbuilt
import time # inbuilt
class PDFReader():
"""
Class used to extract data from the PDF and prepare it for further implementation.
Attributes:
- __file_location (str): File location of the PDF receipt file.
- __header_rows (int): Number of rows in the receipt used for the header.
- __extracted_total (float): Extracted total from the PDF receipt.
- __everyday_extra_discount (float): Everyday Extra Discount applied to the receipt.
- __prepped_item_data (dict): Prepped data of grocery items extracted from the PDF.
- __digi_receipt (Receipt): Receipt object created from the extracted data.
Methods:
- read_file: Extracts text data from the PDF and identifies items and discounts.
- identify_item: Identifies a single object (item or discount) in the receipt.
- discount_handling: Handles discounts in the unprocessed item list.
- get_extracted_total: Retrieves the extracted total from the PDF receipt.
- set_extracted_total: Sets the extracted total.
- extract_discount: Extracts the discount value from a line.
- set_digi_receipt: Sets the Digi Receipt object.
- get_digi_receipt: Retrieves the Digi Receipt object.
- extract_price_or_discount: Extracts the price value from a line.
- data_prep: Prepares data by extracting items and prices.
- create_item_dict: Creates a dictionary of grocery items from the identified data.
- set_file_location: Sets the file location of the PDF receipt file.
- get_file_location: Retrieves the file location of the PDF receipt file.
- set_header_rows: Sets the number of rows in the receipt used for the header.
- get_header_rows: Retrieves the number of rows occupied by the header.
- get_prepped_item_data: Retrieves the prepped data of grocery items.
- set_prepped_item_data: Sets the prepped data of grocery items.
- get_everyday_extra_discount: Retrieves the Everyday Extra Discount applied to the receipt.
- set_everyday_extra_discount: Sets the Everyday Extra Discount.
- __str__: Returns a user-friendly string representation of the contents of the PDF File.
- __repr__: Returns a list of the items identified within the list.
"""
def __init__(self, file_location=None, header_rows=4): # 4 is the header space for woolworths digi recipets
"""
Initializes the PDFReader object.
Parameters:
- file_location (str): File location of the PDF receipt file.
- header_rows (int): Number of rows in the receipt used for the header.
"""
self.__file_location = file_location
self.__header_rows = header_rows
self.__extracted_total = 0.0
self.__everyday_extra_discount = 0.0
self.__prepped_item_data = None
self.__digi_receipt = None
def read_file(self):
"""
Reads and extracts text data from the PDF file. Identifies items and discounts, then passes the data to the `identify_item` method.
Note:
This method updates the internal state by identifying items and discounts from the PDF text.
"""
doc = fitz.open(self.get_file_location())
for page in doc:
text = page.get_text("text")
# Split the text into lines
lines = text.split('\n')
# Identify the items and discounts
self.identify_item(lines)
def identify_item(self, unsorted_data_list):
"""
Identifies a single object in the receipt from the given unsorted data list.
Args:
- unsorted_data_list (list): List of strings containing unsorted data from the PDF.
Note:
This method updates the internal state by setting the extracted total and performs discount handling.
"""
found_total = False
items_and_price_list = []
current_item = ""
# Identifying the items and price
for line in unsorted_data_list[self.get_header_rows():]:
# Break the loop if the line starts with "^Promotional Price" or "SUBTOTAL"
if "SUBTOTAL" in line or "^Promotional Price" in line:
break
# Check if the line ends with spaces and is not a price reduced line
if line.endswith(" ") and not line.strip().startswith("PRICE REDUCED"):
current_item = line.strip() # Set the current item
# Check if the line starts with "PRICE REDUCED"
elif line.strip().startswith("PRICE REDUCED"):
pass
# If the line doesn't end with spaces, it is a new item
else:
# If current_item is not empty, it means there's a preceding item
if current_item:
# Concatenate the item and line and append to items_and_price_list
items_and_price_list.append(current_item + " " + line.strip())
# Reset current_item
current_item = ""
# If it's not a continuation, directly add the line
else:
items_and_price_list.append(line.strip())
# Check if there's any remaining data in current_item
if current_item:
items_and_price_list.append(current_item)
# Search for the receipt total
for line in unsorted_data_list[self.get_header_rows():]:
if " TOTAL " in line and not found_total:
total = self.extract_price_or_discount(line)
found_total = True
self.set_extracted_total(total)
# Perform discount handling
self.discount_handling(items_and_price_list)
def discount_handling(self, unprocessed_item_list):
"""
Processes and adjusts item prices based on discounts found in the unprocessed item list.
Args:
- unprocessed_item_list (list): A list of strings containing unprocessed item information.
Note:
This method modifies the input list by adjusting item prices based on discounts. It also updates the everyday extra discount.
"""
index = 0
item_line_to_remove = []
# Loop through the list
while index < len(unprocessed_item_list):
item_line = unprocessed_item_list[index]
# Logic if line only contains additional pricing data and not item data
if item_line.startswith("Member Price Saving") or item_line.startswith("Everyday Extra Discount") or "OFFER" in item_line:
# Extract the discount value
discount = self.extract_price_or_discount(item_line)
# Add the current index to the list of indices to remove
item_line_to_remove.append(index)
# Logic for 'members price saving' or 'OFFER'
if item_line.startswith("Member Price Saving") or "OFFER" in item_line:
# Adjust the previous item's price
if index > 0:
previous_item_line = unprocessed_item_list[index - 1]
original_price = self.extract_price_or_discount(previous_item_line)
# If the previous item's price is successfully extracted, adjust it
if original_price is not None:
new_price = original_price + discount
unprocessed_item_list[
index - 1] = f"{previous_item_line[:-len(str(original_price)) - 1].rstrip()}{' ' * 6}{new_price:.2f}"
# Logic for 'Everyday Extra Discount'
elif item_line.startswith("Everyday Extra Discount"):
self.set_everyday_extra_discount(discount)
index += 1
# After the loop, remove the lines with "Member Price Saving" in reverse order
for remove_index in sorted(item_line_to_remove, reverse=True):
unprocessed_item_list.pop(remove_index)
# Remove the lines with "Everyday Extra Discount"
self.data_prep(unprocessed_item_list)
def get_extracted_total(self):
"""Returns the extracted total."""
return self.__extracted_total
def set_extracted_total(self, total):
"""Sets the extracted total"""
self.__extracted_total = total
def extract_discount(self, line):
"""Extracts the line discount"""
return float(line.split()[-1])
def set_digi_receipt(self):
"""Sets the Digi Receipt object."""
# Extract the nessassary parameters for the Receipt object
item_data = self.get_prepped_item_data()
receipt_total = self.get_extracted_total()
discount = self.get_everyday_extra_discount()
# Create the Receipt object
self.__digi_receipt = Receipt(item_data, receipt_total, discount)
def get_digi_receipt(self):
"""Returns the Digi Receipt object."""
if self.__digi_receipt is None:
print("Receipt not set. Receipt is set to NONE.")
return self.__digi_receipt
def extract_price_or_discount(self, line):
"""
Extracts the price/discount value from a line.
Parameters:
- line (str): Line of text containing price information.
Returns:
- float: Extracted price value.
"""
# Extract the price from the line
try:
return float(line.split()[-1].strip("$"))
except ValueError:
return None
def data_prep(self, items_and_prices):
"""
Processes raw item data and creates a dictionary of GroceryItem objects.
Args:
- items_and_prices (list): A list of strings containing raw item information.
Note:
This method extracts item names and prices from the input list and creates GroceryItem objects.
The resulting dictionary is set as the prepped item data for further processing.
"""
items_found = []
# Extract the item name and price from each line
for line in items_and_prices:
# i need to capture the item in the line, item == line until 1st " "
space_char_count = 0
item_name = ""
item_start = False
# To extract the item from the line of text
for char in line:
# To check if the item has started
if item_start:
if char == " ":
space_char_count += 1
else:
space_char_count = 0
if space_char_count == 3:
break
item_name += char
# To check if the item has started
elif char.isalnum() or char.isspace():
if char.isalpha() or char.isdigit():
item_start = True
if item_start:
item_name += char
item_name = item_name.strip() # Remove leading and trailing whitespaces
# to extract the price of the item from the line of text.
temp_line = ""
for char in reversed(line):
if char.isdigit() or char == '.':
temp_line += char
else:
break
# Reverse the string and convert to float
item_price = float(temp_line[::-1])
# Append the item name and price to the list
items_found.append([item_name, item_price])
# Create a dictionary of GroceryItem objects
self.create_item_dict(items_found)
def create_item_dict(self, items_found):
"""
Creates a dictionary of grocery items from the identified data.
Parameters:
- items_found (list): List of identified grocery items.
"""
items_dict = {}
item_key = 1
# Create a dictionary of GroceryItem objects
for item in items_found:
items_dict[item_key] = GroceryItem(item[0], item[1])
item_key += 1
# Set the prepped item data
self.set_prepped_item_data(items_dict)
def set_file_loaction(self, file_location):
"""Sets the file location of the PDF receipt file."""
self.__file_location = file_location
def get_file_location(self):
"""Retrieves the file location of the PDF receipt file."""
return self.__file_location
def set_header_rows(self, header_rows: int):
"""Sets the number of rows in the receipt used for the header."""
self.__header_rows = header_rows
def get_header_rows(self):
"""Retrieves the number of rows occupied by the header."""
return self.__header_rows
def get_prepped_item_data(self):
"""Retrieves the prepped data of grocery items."""
return self.__prepped_item_data
def set_prepped_item_data(self, item_dict):
"""Sets the prepped data of grocery items."""
self.__prepped_item_data = item_dict
def get_everyday_extra_discount(self):
"""Retrieves the Everyday Extra Discount applied to the receipt."""
return self.__everyday_extra_discount
def set_everyday_extra_discount(self, discount):
"""Sets the Everyday Extra Discount."""
self.__everyday_extra_discount = discount
def __str__(self):
'''Returns a user-friendly string representation of the contents of the PDF File.'''
return f"PDFReader(file_location={self.get_file_location()}, header_rows={self.get_header_rows()}, " \
f"extracted_total={self.get_extracted_total()}, everyday_extra_discount={self.get_everyday_extra_discount()})"
def __repr__(self):
"""Returns a list of the items identified within the list."""
item_data = self.get_prepped_item_data()
items_repr = [f"{item.get_name()}: ${item.get_price():.2f}" for item in item_data.values()] if item_data else "None"
return f"PDFReader(items={items_repr})"
class GroceryItem():
"""
Class used to store data extracted from a PDF file.
Attributes:
- next_id (int): Class variable to assign unique IDs to grocery items.
- __id_num (int): ID number of the grocery item.
- __item_name (str): Name of the grocery item.
- __item_price (float): Price of the grocery item.
Methods:
- get_id_num: Get the ID number of the grocery item.
- get_item_name: Get the name of the grocery item.
- get_item_price: Get the price of the grocery item.
- set_item_price: Adjust the price of the grocery item.
- __str__: Return an interface-friendly string of the item.
- __repr__: Return the data associated with the item.
"""
# Class variable to assign unique IDs to grocery items
next_id = 1
def __init__(self, item_name: str, item_price: float):
"""
Initialize the GroceryItem object.
Parameters:
- item_name (str): Name of the grocery item.
- item_price (float): Price of the grocery item.
"""
# Assign a unique ID to the grocery item
self.__id_num = GroceryItem.next_id
GroceryItem.next_id += 1
self.__item_name = item_name
self.__item_price = item_price
def get_id_num(self):
"""Returns the itemID of the item."""
return self.__id_num
def get_item_name(self):
"""Returns the name of the item."""
return self.__item_name
def get_item_price(self):
""""Returns the price of the item."""
return self.__item_price
def set_item_price(self, new_price):
"""Sets the price of the grocery item."""
self.__item_price = new_price
def __str__(self):
'''Return an interface-friendly string of the item.'''
grocery_item_str = f"Product:\t{self.get_item_name()}\nPrice: \t\t" + \
f"${self.get_item_price():.2f}\n"
return grocery_item_str
def __repr__(self):
'''Return the data associated with the item.'''
grocery_item_repr = f"GroceryItem({self.get_id_num()}, '{self.get_item_name()}', {self.get_item_price()})"
return grocery_item_repr
class Receipt():
"""
Class storing data extracted from a PDF file for further processing.
Attributes:
- __receipt_items (dict): Dictionary of receipt items.
- __receipt_total (float): Total cost of items in the receipt.
- __everyday_extra_discount (float): Extra discount applied to items if specified.
Methods:
- recalculate_receipt_total: Recalculate the total cost of items in the receipt.
- get_everyday_extra_discount: Get the everyday extra discount applied.
- __str__: Return a friendly representation of the Receipt class.
- __repr__: Return a string representation of the Receipt class.
"""
def __init__(self, receipt_items, receipt_total, applied_discount=False):
"""
Initialize the Receipt object.
Parameters:
- receipt_items (dict): Dictionary of receipt items.
- receipt_total (float): Total cost of items in the receipt.
- applied_discount (float): Extra discount applied to items if specified.
"""
self.__receipt_items = receipt_items
self.__receipt_total = receipt_total
# Checks to see if a discount was applied to the receipt
if applied_discount == False:
self.__everyday_extra_discount = 0.0
# If a discount was applied, it is set
else:
print("Discount found!")
self.__everyday_extra_discount = applied_discount
# Apply the discount to the receipt items
for item in self.get_receipt_items().values():
# Checks to see if the item is a giftcard
if "Giftcard" not in item.get_item_name():
discounted_price = float("%.2f" % (item.get_item_price() * 0.9))
item.set_item_price(discounted_price)
def get_receipt_items(self):
"""Returns the items inside the receipt."""
return self.__receipt_items
def get_receipt_total(self):
"""Returns the receipt total."""
return self.__receipt_total
def get_everyday_extra_discount(self):
"""Get the everyday extra discount applied."""
return self.__everyday_extra_discount
def recalculate_receipt_total(self):
"""Recalculate the total cost of items in the receipt.
Returns:
- str: Formatted total cost of items in the receipt."""
# Recalculate the receipt total
receipt_total = 0.0
for item, obj in self.__receipt_items.items():
receipt_total += obj.get_item_price()
formatted_total = f"{receipt_total:.2f}"
return formatted_total
def __str__(self):
'''
Returns a friendly representation of the Receipt Class.
'''
item_num = 1
return_str = f"\n{boarder*2}\n"
return_str += f"Number of items in receipt: {len(self.get_receipt_items())}\n"
# Loop through the receipt items and add them to the return string
for item, obj in self.get_receipt_items().items():
return_str += f"\nItem number: {item_num}\n"
return_str += str(obj)
item_num += 1
return_str += f"\nTotal: ${float('%.2f' % (self.get_receipt_total()-self.get_everyday_extra_discount()))}\n"
# Check if an everyday extra discount was applied, and alters sting accordingly
if self.get_everyday_extra_discount() != 0.0:
return_str += f"\nAfter Everyday Extra Discount of ${-self.get_everyday_extra_discount()} is applied, " +\
f"new total is: ${self.recalculate_receipt_total()}.\n"
return_str += f"{boarder*2}"
return return_str
def __repr__(self):
'''
Return a string representation of the Receipt class.
'''
# Loop through the receipt items and add them to the return string
return_str = f"{len({self.get_receipt_items()})}, " + \
f"{', '.join(item.get_item_name() for item in self.get_receipt_items())}, " + \
f"{self.get_receipt_total()}"
# Check if an everyday extra discount was applied, and alters sting accordingly
if self.get_everyday_extra_receipt() != 0.0:
return_str += f", {self.get_everyday_extra_receipt()}, " +\
f"{self.get_receipt_total()-self.get_everyday_extra_receipt()}"
return return_str
class Shopper():
'''
Class representing a shopper with a stake in dividing a receipt.
Attributes:
- __name (str): The name of the shopper.
- __personal_cart_items (list): List of grocery items in the shopper's personal cart.
- __paid (bool): Indicates if the shopper has paid their share.
- __cart_total (float): Total cost of items in the shopper's cart.
- __main_shopping_cart (bool): Flag indicating if the cart is the main shopping cart.
- __spending_tracker (float): Tracker for the shopper's spending.
Methods:
- add_to_personal_cart: Add a grocery item to the shopper's personal cart.
- remove_from_personal_cart: Remove an item from the personal cart or reset the cart if specified.
- calculate_cart_total: Calculate the total cost of items in the shopper's cart.
- calculate_new_spending_tracker_value: Calculate the updated spending tracker value.
- __str__: Return a string representation of the shopper.
'''
def __init__(self, name, spending_tracker=0.0, main_shopping_cart=False, cart_items=None):
'''Initialize the Shopper object.'''
self.__name = name
self.__personal_cart_items = cart_items or []
self.__paid = False
self.__cart_total = 0.0
self.__main_shopping_cart = main_shopping_cart
self.__spending_tracker = spending_tracker or 0.0
def get_name(self):
'''Returns the name of the shopper.'''
return self.__name
def get_paid(self):
'''Returns the paid boolean of the shopper.'''
return self.__paid
def set_paid(self, paid=False):
'''Sets the paid boolean of the shopper.'''
self.__paid = paid
def get_cart_total(self):
'''Returns the cart total of the shopper.'''
return self.__cart_total
def set_cart_total(self, cart_total):
'''Sets the cart total of the shopper.'''
self.__cart_total = cart_total
def get_personal_cart_items(self):
'''Returns the cart items allocated to the shopper.'''
return self.__personal_cart_items
def add_to_personal_cart(self, item_obj):
'''
Add a grocery item to the shopper's personal cart.
Parameters:
- item_obj: Grocery item object to be added.
'''
# Adds the passed item to the personal shoppers cart
self.__personal_cart_items.append(item_obj)
print(f"{item_obj.get_item_name()} was added to {self.get_name()}'s cart.")
def remove_from_personal_cart(self, item_obj):
'''
Remove an item from the personal cart or reset the cart if specified.
Parameters:
- item_obj: Grocery item object to be removed.
If "x" is passed, the personal cart is reset.
'''
# Handles the scenario when the item is found
if item_obj in self.__personal_cart_items:
removed_item = item_obj
self.__personal_cart_items.remove(item_obj)
print(f"{removed_item.get_item_name()} was removed from {self.get_name().capitalize()}'s cart.")
# Handles the scenario when the item is not found
elif item_obj not in self.__personal_cart_items:
print(f"{item_obj.get_item_name()} was not found in {self.get_name().capitalize()}'s cart")
# This grants the developer to ability to reset the cart list if they wish to do so.
elif item_obj == "x":
self.__personal_cart_items = []
else:
print("error")
def calculate_cart_total(self, setter="n"):
'''
Calculate the total cost of items in the shopper's cart.
Parameters:
- setter (str): If set to "y", the cart total is stored.
Returns:
- float: Total cost of items in the shopper's cart.
'''
current_cart_total = 0.0
# Loop through the shoppers cart and add the price of each item to the current cart total
for item in self.__personal_cart_items:
current_cart_total += item.get_item_price()
# If the setter is set to "y", the cart total is stored
if setter == "y":
self.set_cart_total(current_cart_total)
return current_cart_total
def get_spending_tracker(self):
'''Returns the spending tracker of the shopper.'''
return self.__spending_tracker
def set_spending_tracker(self, spending_tracker):
'''Sets the spending tracker of the shopper.'''
self.__spending_tracker = spending_tracker
def calculate_new_spending_tracker_value(self, setter="n"):
'''
Calculate the updated spending tracker value.
Parameters:
- setter (str): If set to "y", the spending tracker is updated.
Returns:
- float: Updated spending tracker value.
'''
updated_value = self.get_spending_tracker() + self.get_cart_total()
return updated_value
def __str__(self):
'''
Return a string representation of the shopper.
Returns:
- str: String representation of the shopper.
'''
shopper_str = f"Name: {self.get_name()}"
shopper_str += f"Number of items in cart: {len(self.get_personal_cart_items())}"
for item in self.get_personal_cart_items():
shopper_str += f"{item.get_item_name()} | {item.get_item_price()}"
def __str__(self):
'''
Return a string representation of the shopper.
Returns:
- str: String representation of the shopper.
'''
# Basic information about the shopper
shopper_info = f"Shopper: {self.get_name()}\n"
# Personal cart items
cart_items_info = "Personal Cart Items:\n"
for item in self.get_personal_cart_items():
cart_items_info += f"{item.get_item_name()} | ${item.get_item_price():.2f}\n"
# Cart total and spending tracker
cart_total_info = f"Cart Total: ${self.calculate_cart_total():.2f}\n"
spending_tracker_info = f"Spending Tracker: ${self.calculate_new_spending_tracker_value():.2f}"
# Constructing the final representation string
shopper_str = f"{shopper_info}{cart_items_info}{cart_total_info}{spending_tracker_info}"
return shopper_str
def __repr__(self):
'''
Returns a string representation of the shopper.
Returns:
- str: String representation of the shopper.
'''
# Creating a list of strings, each representing a grocery item in the personal cart
cart_items_repr = [f"{item.get_item_name()} | {item.get_item_price()}" for item in self.get_personal_cart_items()]
# Joining the list items with a newline for better readability
cart_items_str = "\n".join(cart_items_repr)
# Constructing the final representation string
shopper_repr = f"Shopper(name={self.get_name()}, spending_tracker={self.get_spending_tracker()}, " \
f"main_shopping_cart={self.__main_shopping_cart}, paid={self.__paid}, " \
f"cart_total={self.__cart_total})\nPersonal Cart Items:\n{cart_items_str}"
return shopper_repr
class ReceiptDivider():
'''Class for managing the division of a receipt among registered shoppers.
Attributes:
- __registered_shoppers (dict): Dictionary to store registered shoppers.
- __shoppers_in_receipt (dict): Dictionary to store shoppers in the current receipt.
- __receipt_file_location (str): File location of the current receipt.
- __receipt: Digital receipt object.
Methods:
- display_menu: Display the main menu and handle user input for various options.
- request_receipt_loaction: Open a file dialog to request the location of a receipt file.
- greeting: Print a friendly greeting for the user.
- retreive_existing_shoppers: Retrieve and load existing shopper data from a file.
- create_new_shopper: Create a new shopper and add them to the list of registered shoppers.
- scan_receipt: Scan a receipt file and set the digital receipt for further processing.
- divide_receipt: Divide the items in the current receipt among the shoppers.
- calculate_owings: Calculate the amount owed by each shopper and display the results.
- show_registered_shoppers: Display the list of registered shoppers.
- store_shoppers_details: Store the details of registered shoppers in a file.
- run: Run the main program, including greetings, data retrieval, and displaying the menu.
- quit_program: Quit the program and store shopper details before exiting.
'''
def __init__(self):
'''Initialize the ReceiptDivider object.'''
self.__registered_shoppers = {}
self.__shoppers_in_receipt = {}
self.__receipt_file_location = ""
self.__receipt = None
def display_menu(self):
'''Display the main menu and handle user input for various options.'''
# Dictionary of menu options
display_options = {"d": "Divide Receipt",
"r": "Register Shopper",
"l": "Show Registered Shoppers",
"s": "Scan Receipt",
"q": "Quit Program"}
### Private functions for display Menu
# Prombt for and scan the selected receipt
def select_and_scan_receipt():
'''Display Menu private function - Prombts for and scans the selected receipt.'''
print("Please select digital receipt.")
time.sleep(0.25)
self.scan_receipt(self.request_receipt_loaction())
print("Receipt Scanned.")
# Prombt for how many shoppers to divide the receipt with, an returns a int value.
def select_number_of_shoppers():
'''Display Menu private function - Prombts for how many shoppers to divide the receipt with, an returns a int value.'''
correct_input = False
while not correct_input:
# Min of 2 shoppers is required
if len(self.get_registered_shoppers()) == 2:
return 2
# If more then 2 shoppers are registered, the user is prombted to select how many shoppers to split receipt.
else:
print(f"How many shoppers are splitting this receipt: 2-{len(self.get_registered_shoppers())}")
try:
user_input = int(input(">"))
except Exception as e:
print(e, "Incorrect entry, please use digits only and try again.")
try:
if user_input > len(self.get_registered_shoppers()) or user_input <= 1:
raise Exception
else:
correct_input = True
except Exception as e:
print(e, "Number of entered shoppers is out of range.")
return user_input
# Prombt for shoppers names and adds them to the receipt.
def select_shoppers_names(num_of_shoppers):
'''Display Menu private function - Prombts for shoppers names.'''
print("Enter the shoppers names.")
for shopper_num in range(num_of_shoppers):
correct_input = False
while not correct_input:
print(f"Shopper #{shopper_num + 1}")
try:
shopper_name = input(">").lower().strip()
if shopper_name not in self.get_registered_shoppers():
raise Exception
else:
correct_input = True
except Exception as e:
print("Shopper not found in registered shoppers.", e)
# Adds the shopper to the receipt
self.add_shopper_to_receipt(self.get_registered_shoppers()[shopper_name])
### Build and Display Menu
run = True
while run:
# Build menu options
print("Please select from the following options:")
for option, desc in display_options.items():
# Condition if not enough registered shoppers to divid receipt, min 2.
if option == "d" and len(self.get_registered_shoppers()) <= 1:
print(f'\t({option}) {desc} (*Requires at least 2 registered shoppers*)')
else:
print(f'\t({option}) {desc}')
try:
# prombt for option
selection = input("> ").lower().strip()
# Raise execption if user input doesnt match any of the provided options.
if selection.lower() not in display_options:
raise Exception("INCORRECT_INPUT", "Please enter for one of the options provided.")
except Exception as e:
print(e, "\n")
else:
# Show registered shoppers
if selection == "l":
self.show_registered_shoppers()
# Create and register new shopper
elif selection == "r":
self.create_new_shopper()
# Quit Program
elif selection == "q":
run = False
self.quit_program()
# Scan receipt
elif selection == "s":
select_and_scan_receipt()
print(self.get_receipt())
# Divide receipt
elif selection == "d":
# set user input parameters
correct_input_parameters = ["y", "n", "x"]
# Confims that correct receipt has been seleceted
correct_receipt = False
while not correct_receipt:
select_and_scan_receipt()
print(self.get_receipt())
print("Is this the correct receipt? (y/n) or (x) to return to menu.")
# creates a while loop to ensure correct input
correct_input = False
while not correct_input:
try:
user_input = input(">").lower().strip()
if user_input not in correct_input_parameters:
raise ValueError("Invalid input. Please enter 'y' or 'x'.")
if user_input == "y":
correct_receipt = True
correct_input = True
elif user_input == "x":
break
else:
correct_input = True
except ValueError as e:
print(str(e))
# if incorrect receipt was colleted, the user is prombted to select another receipt.
if user_input == "n":
try:
print("Would you like to select another receipt? (y) or (n/x) to return to menu.")
user_input = input(">")
if user_input not in correct_input_parameters:
raise ValueError("Invalid input. Please enter 'y', 'n' or 'x'.")
if user_input == "y":
continue
# if the user wished to break the receipt selection loop and return to menu
else:
user_input = "x"
break
except ValueError as e:
print(str(e))
# if correct receipt was selected, the user is prombted to select how many shoppers to split the receipt with.
if user_input != "x":
number_of_shoppers = select_number_of_shoppers()
select_shoppers_names(number_of_shoppers)
else:
pass
# prombt to continue to divide receipt
total_shopping_cart = True
self.create_new_shopper(total_shopping_cart)
self.divide_receipt()
def request_receipt_loaction(self):
'''Open a file dialog to request the location of a receipt file.'''
root = Tk()
root.withdraw() # Hide the main window
downloads_path = os.path.expanduser("~/Downloads")
# Open a file dialog to request the location of a receipt file
path = filedialog.askopenfilename(initialdir=downloads_path, title="Select a file",
filetypes=(("PDF files", "*.pdf"), ("All files", "*.*")))
return path
def set_receipt(self, digi_receipt):
'''Set the digital receipt for further processing.'''
self.__receipt = digi_receipt
def get_receipt(self):
'''Get the currently set digital receipt.'''
return self.__receipt
def get_receipt_file_loaction(self):
'''Get the receipt file location.'''
return self.__receipt_file_location
def set_receipt_file_location(self, file_address):
'''Set the receipt file location.'''
self.__receipt_file_location = file_address
def get_registered_shoppers(self):
'''Get the dictionary of registered shoppers.'''
return self.__registered_shoppers
def set_registered_shoppers(self, shopper_dict):
'''Set the dictionary of registered shoppers.'''
self.__registered_shoppers = shopper_dict
def add_registered_shopper(self, shopper):
'''Add a new shopper to the list of registered shoppers.'''
self.__registered_shoppers[shopper.get_name()] = shopper
def get_shoppers_in_receipt(self):
'''Get the dictionary of shoppers in the current receipt.'''
return self.__shoppers_in_receipt
def add_shopper_to_receipt(self, shopper):
'''Add a shopper to the list of shoppers in the current receipt.'''
self.__shoppers_in_receipt[shopper.get_name()] = shopper
def set_shoppers_dict_in_receipt(self, shopper_dict):
'''Set the dictionary of shoppers in the current receipt. If "x" passed a paremeter, the dictionary will be reset.'''
if shopper_dict == "x":
self.__shoppers_in_receipt = {}
else:
self.__shoppers_in_receipt = shopper_dict
def remove_shopper_from_receipt(self, shopper):
'''Remove a shopper from the list of shoppers in the current receipt.'''
self.__shoppers_in_receipt.pop(shopper)
def greeting(self):
'''Prints a friendly greeting for the user.'''
# Print a greeting
print("\nWelcome to the Receipt Divider!")
print("Designed and Produced by Joshua Scattini.\n")
def retreive_existing_shoppers(self, file_name="shoppers.txt"):
'''
Retrieve and load existing shopper data from a file.
Parameters:
- file_name (str): The name of the file containing shopper data.
'''
# Check if the file exists
try:
with open(file_name, 'r') as file:
for line in file:
shopper_data = line.strip("\n").split(',')
# Add the shopper to the list of registered shoppers
self.add_registered_shopper(
Shopper(str(shopper_data[0]), # Using the Shopper class, the shopper name is set
float(shopper_data[1]))) # Using the Shopper class, the shopper spending tracker is set
# If the file does not exist, create a new file
except Exception as e:
self.set_shoppers_dict_to_receipt("x")
print("CORRUPT_SHOPPER_DATA: The saved shopper was unable to be retrieved.")
def create_new_shopper(self, receipt_cart=False):
'''
Create a new shopper and add them to the list of registered shoppers.
Parameters:
- receipt_cart (bool): Flag indicating if the shopper is for the current receipt combined cart.
'''
# Check if the shopper is for the current receipt combined cart
if receipt_cart == False:
# Prompt the user to enter the shopper's name
valid_input = False
while not valid_input:
print("\nPlease enter new shopper's name:\n*'x' to return to menu.*\n")
user_input = input("<").lower().strip()
# Check if the shopper already exists
if user_input in self.get_registered_shoppers():
print("Shopper with that name already exists.")
# Check if the user wishes to return to the menu
elif user_input == 'x':
valid_input = True
# Create a new shopper
else:
self.add_registered_shopper(Shopper(user_input))
print(f"Welcome, {user_input.capitalize()}!")
valid_input = True
# If the shopper is for the current receipt combined cart
else:
self.add_shopper_to_receipt(Shopper("Combined", None, True, list(self.get_receipt().get_receipt_items().values())))
def scan_receipt(self, file_location):
'''
Scan a receipt file and set the digital receipt for further processing.
Parameters:
- file_location (str): The file location of the receipt to be scanned.
'''
# Set the file location of the receipt
scanner = PDFReader()
scanner.set_file_loaction(file_location)
# Read the file and set the digital receipt
scanner.read_file()
scanner.set_digi_receipt()
digi_receipt = scanner.get_digi_receipt()
# Assign the generated receipt to the ReceiptDivider object
self.set_receipt(digi_receipt)
def divide_receipt(self):
'''
Divide the items in the current receipt among the shoppers.
The function guides the user to assign items to specific shoppers and calculates the amount owed by each shopper.
'''
# Create a dictionary of shoppers in the current receipt
def find_current_item_and_cart(while_index):
# Loop through the shoppers in the current receipt
for shopper_obj in self.get_shoppers_in_receipt().values():
for grocery_obj in shopper_obj.get_personal_cart_items():
# Check if the item is in the shopper's cart
if receipt.get_receipt_items()[while_index] == grocery_obj:
return shopper_obj, grocery_obj
# Create a dictionary of shoppers in the current receipt
shopper_dict = {}
receipt = self.get_receipt()
receipt_len = len(receipt.get_receipt_items())
# Setting up user input parameters
user_input_parameters = ["q","w","x","v","e","a","s","d","f","g"]
# Setting up top_str
f"\n(x) to exit back to menu, (v) submit and calculate owings.\n" +\
f"(q) to go to previous item, (w) to go to next item.\n"
# Setting up shopper_dict
for i, shopper_obj in enumerate(self.get_shoppers_in_receipt().values(), start=1):
if shopper_obj.get_name() == "Combined":
i = 0
shopper_dict[user_input_parameters[i+4]] = shopper_obj
# modifying the user_input_parameters based on number of shoppers
shopper_str = ""
# modifyin the user_input_parameters based on number of shoppers
num_items_to_remove = 5 - (len(shopper_dict)-1)
user_input_parameters = user_input_parameters[:-num_items_to_remove]
# Building the shopper_str
for i, shopper_obj in shopper_dict.items():
shopper_str += f"({i}) {shopper_obj.get_name().capitalize()}\t"
print(f"({i}) {shopper_obj.get_name()}")
print(shopper_str)
while_index = 1
# Loop through the items in the receipt
submit = False
while not submit:
# Find the current item and shopper
item_owner, grocery_item = find_current_item_and_cart(while_index)
print(top_str)
# Display the current item and shopper
print(f"Item {while_index} of {receipt_len}")
print(f"{grocery_item}")
# Checks to see who's cart the item currently belongs to
print(f"Currently in {item_owner.get_name().capitalize()}'s cart.")
print("\nWho will take this item?")
print(shopper_str)
selection = input(">")
# Checks to see if the user input is valid
if selection not in user_input_parameters:
print("Please select of the options below")
# performs the action based on the user input
else:
index_modifier = 1
# Takes the user back to the previous item or next item based on input
if selection == "q" or selection == "w":
if selection == "q":
index_modifier *= -1
while_index += index_modifier
if while_index <= 0:
while_index = 1
elif while_index >= receipt_len:
while_index = receipt_len
# Takes the user back to the menu or submits the current selections
elif selection == "x" or selection == "v":
if selection == "v":
submit = True
else:
break
# Adds the item to the selected shoppers cart
else:
item_owner.remove_from_personal_cart(grocery_item)
# Add item to selections cart
shopper_dict[selection].add_to_personal_cart(receipt.get_receipt_items()[while_index])
while_index +=1
if while_index > receipt_len:
while_index = receipt_len
# Calculate the cart total for each shopper
for shopper in shopper_dict.values():
shopper.calculate_cart_total("y")
# Calculate the amount owed by each shopper
self.calculate_owings(shopper_dict)
# Prombt to confirm and update personal spending tracker
print("Confirm and update personal spending tracker? (y/n)")
# Loop to ensure correct input
submit = False
while not submit:
confirm = input(">")
# if the user wishes to update the spending tracker
if confirm == "y":
for shopper in shopper_dict.values():
shopper.set_spending_tracker(float('%.2f' % (shopper.get_spending_tracker() + shopper.get_cart_total())))
submit = True
# if the user wishes to return to the menu
elif confirm == "n":
break
else:
print("Please select whether to record change in spending tracker. (y/n)")
def calculate_owings(self, shopper_dict):
'''
Calculate the amount owed by each shopper and display the results.
Parameters:
- shopper_dict (dict): A dictionary containing shoppers and their assigned items.
'''
### Split Combined Costs
# Calculate the split cart and remove the 'Combined' Shopper obj from the dictionary
split_cart_cost = float('%.2f' % (shopper_dict["e"].get_cart_total() / (len(self.get_shoppers_in_receipt())-1)))
shopper_dict.pop("e")
# Apply the csplit combined cart toat to each shopper in receipt
for shopper in shopper_dict.values():
shopper.set_cart_total(float('%.2f' % (shopper.get_cart_total() + split_cart_cost)))
### Who Paid
# Prombt for who made the payement
print("Which shoppper made the payment?")
# Build the string of 'who paid' options to display
who_paid_str = ""
for input_sel, shopper in shopper_dict.items():
who_paid_str += f"({input_sel}) {shopper.get_name().capitalize()}\n"
# print the built string and capture input
valid_input = False
while not valid_input:
print(who_paid_str)
shopper_paid = input(">")
# if selection is valid
if shopper_paid in shopper_dict:
# Set the selcted Shopper self.__paid to TRUE
shopper_dict[shopper_paid].set_paid(True)
valid_input = True
else:
print("Invalid selection. Please enter the corresponding letter to the shopper who made the payment.")
### Build Owing-String
owings_str = ""
# Build 'Shopper x' is owed
for shopper in shopper_dict.values():
if shopper.get_paid() == True:
owings_str += f"{shopper.get_name()} is owed: \n"
# Build 'amount from "shopper y,z,% etc."'
for shopper in shopper_dict.values():
if shopper.get_paid() == False:
owings_str += f"${shopper.get_cart_total()} from {shopper.get_name()}.\n"
# Display Owing-String
print(owings_str)
def show_registered_shoppers(self):
'''Display the list of registered shoppers.'''
shopper_index = 1
# Check if there are any registered shoppers and prints message if no shoppers found
if len(self.get_registered_shoppers()) == 0:
print("There are no registered shoppers.")
# Display the list of registered shoppers and their spending tracker
else:
print("\nRegistered Shoppers: ")
for shopper in self.get_registered_shoppers().values():
print(f"{shopper_index}. {shopper.get_name().capitalize()}\t\tTotal Spent: ${shopper.get_spending_tracker()}")
shopper_index += 1
print('')
def store_shoppers_details(self, file_name="shoppers.txt"):
'''
Store the details of registered shoppers in a file.
Parameters:
- file_name (str): The name of the file to store shopper details.
'''
# Check if there are any registered shoppers
if len(self.get_registered_shoppers()) != 0:
with open(file_name, 'w') as file:
# Loop through the registered shoppers and store their details
for name, shopper_obj in self.get_registered_shoppers().items():
file.write(f'{name},' \
f'{shopper_obj.get_spending_tracker()}\n')
def run(self):
'''Run the main program, including greetings, data retrieval, and displaying the menu.'''
# Opening functions to run upon start-up
self.greeting()
self.retreive_existing_shoppers()
self.display_menu()
def quit_program(self):
'''Quit the program and store shopper details before exiting.'''
# Closing functions to run upon exiting
self.store_shoppers_details()
print("Good Bye!")
if __name__ == "__main__":
# Create an instance of the ReceiptDivider class
receipt_divider = ReceiptDivider()
# Run the program
receipt_divider.run()
|
var app = angular.module('bloggerApp', ['ngRoute']);
app.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: 'pages/home.html',
controller: 'HomeController',
controllerAs: 'vm'
})
.when('/blogadd', {
templateUrl: 'pages/blogAdd.html',
controller: 'AddBlogController',
controllerAs: 'ab'
})
.when('/bloglist', {
templateUrl: 'pages/blogList.html',
controller: 'BlogListController',
controllerAs: 'bl'
})
.when('/blogedit/:id', {
templateUrl: 'pages/blogEdit.html',
controller: 'BlogEditController',
controllerAs: 'eb'
})
.when('/blogdeletion/:id', {
templateUrl: 'pages/blogDeletion.html',
controller: 'BlogDeletionController',
controllerAs: 'bd'
})
.when('/signup', {
templateUrl: 'pages/signup.html',
controller: 'SignUpController',
controllerAs: 'su'
})
.when('/signin', {
templateUrl: 'pages/signin.html',
controller: 'SignInController',
controllerAs: 'si'
})
.when('/games', {
templateUrl: 'pages/games.html',
controller: 'GamesController',
controllerAs: 'pg'
})
.otherwise({redirectTo: '/'});
});
/** API CONTROLLERS **/
function getAllBlogs($http) {
return $http.get('/api/blogs')
.then(function(response) {
return response.data;
})
.catch(function(error) {
throw error;
});
}
function getABlog($http, id) {
return $http.get('/api/blogs/' + id)
.then(function(response) {
return response.data;
})
.catch(function(error) {
throw error;
});
}
function updateBlog($http, authentication, id, data) {
return $http.put('/api/blogs/' + id, data, {headers : { Authorization: 'Bearer ' + authentication.getToken()}})
.then(function(response) {
return response.data;
})
.catch(function(error) {
throw error;
});
}
function postBlog($http, authentication, data) {
return $http.post('/api/blogs', data, {headers : { Authorization: 'Bearer ' + authentication.getToken()}})
.then(function(response) {
return response.data;
})
.catch(function(error) {
throw error;
});
}
function deleteBlog($http, authentication, id) {
return $http.delete('/api/blogs/' + id, {headers : { Authorization: 'Bearer ' + authentication.getToken()}})
.then(function(response) {
return response.data;
})
.catch(function(error) {
throw error;
});
}
function createGame($http, gameStarter) {
return $http.post('/api/games', { gameStarter: gameStarter })
.then(function(response){
return response.data;
})
.catch(function(error){
throw error;
});
}
function getGame($http) {
return $http.get('/api/games')
.then(function(response){
return response.data;
})
.catch(function(error){
throw error;
});
}
function makeMove($http, row, col) {
return $http.put('/api/games', {row: row, col: col})
.then(function(response){
return response.data;
})
.catch(function(error){
throw error;
});
}
function deleteGame($http) {
return $http.delete('/api/games')
.then(function(response) {
return response.data;
})
.catch(function(error) {
throw error;
});
}
function deleteGames($http) {
return $http.delete('/api/games')
.then(function(response) {
return response.data;
})
.catch(function(error) {
throw error;
});
}
/** PAGE CONTROLLERS **/
app.controller('HomeController', ['$scope', function($scope) {
var vm = this;
vm.pageHeader = {
title: "Blogger"
};
}]);
app.controller('AddBlogController', ['$scope', '$http', '$location', 'authentication', function($scope, $http, $location, authentication) {
var ab = this;
ab.pageHeader = {
title: 'Blog Add'
};
ab.blogTitle = '';
ab.blogEntry = '';
ab.blogAuthor = authentication.currentUser().name;
ab.authorEmail = authentication.currentUser().email;
ab.submit = function() {
var data = {
blogTitle: ab.blogTitle,
blogEntry: ab.blogEntry,
blogAuthor: ab.blogAuthor,
authorEmail: ab.authorEmail
};
postBlog($http, authentication, data)
.then(function(data) {
ab.blog = data;
console.log('Blog Posted!');
$location.path('bloglist');
})
.catch(function(error) {
console.error('Could not post blog');
});
};
}]);
app.controller('BlogListController', ['$scope','$http', 'authentication', function($scope, $http, authentication) {
var bl = this;
bl.pageHeader = {
title: 'Blog List'
};
bl.isLoggedIn = function() {
return authentication.isLoggedIn();
}
getAllBlogs($http)
.then(function(data) {
bl.blogs = data;
bl.isAuthor = function(authorEmail) {
return authentication.currentUser().email === authorEmail
};
console.log('Blogs Found!');
})
.catch(function(error) {
console.error('Could not get list of blogs!');
});
}]);
app.controller('BlogEditController', ['$scope', '$http', '$routeParams', '$location', 'authentication', function($scope, $http, $routeParams, $location, authentication) {
var eb = this;
eb.blog = {};
eb.id = $routeParams.id;
eb.pageHeader = {
title: 'Edit Blog'
};
getABlog($http, eb.id)
.then(function(data) {
eb.blog = data;
console.log('Blog Found!');
})
.catch(function(error){
throw error;
});
eb.submit = function() {
var data = eb.blog;
data.blogTitle = userForm.blogTitle.value;
data.blogEntry = userForm.blogEntry.value;
updateBlog($http, authentication, eb.id, data)
.then(function(data){
eb.blog = data;
console.log('Blog was successfully updated!');
$location.path('bloglist');
})
.catch(function(error) {
throw error;
});
}
}]);
app.controller('BlogDeletionController', ['$scope', '$http', '$routeParams', '$location', 'authentication', function($scope, $http, $routeParams, $location, authentication) {
var bd = this;
bd.id = $routeParams.id;
bd.pageHeader = {
title: 'Blog Deletion'
};
getABlog($http, bd.id)
.then(function(data) {
bd.blog = data;
console.log('Blog Found!');
})
.catch(function(error){
throw error;
});
bd.submit = function() {
deleteBlog($http, authentication, bd.id)
.then(function(data) {
console.log('Blog was successfully deleted!');
$location.path('bloglist');
})
.catch(function(error){
throw error;
});
}
}]);
app.controller('GamesController', ['$scope', '$http', '$interval','authentication', function($scope, $http, $interval, authentication) {
var pg = this;
pg.pageHeader = {
title: "Games"
};
pg.grid = null;
pg.currentPlayer = null;
pg.winner = null;
pg.activeGame = false;
pg.playerLeft = false;
pg.gameStarter = authentication.currentUser().email;
function getGameState() {
$http.get('/api/games')
.then(function (response) {
pg.grid = response.data.grid;
pg.currentPlayer = response.data.currentPlayer;
pg.winner = response.data.winner;
pg.activeGame = response.data.activeGame;
pg.playerLeft = response.data.playerLeft;
pg.gameStarter = response.data.gameStarter;
console.log(pg.gameStarter);
})
.catch(function (error) {
pg.playerLeft = true;
console.error('Error fetching game state:', error);
});
}
pg.createGame = function() {
createGame($http, { gameStarter: pg.gameStarter})
.then(function (response) {
pg.grid = response.grid;
pg.currentPlayer = 'X';
pg.winner = response.winner;
pg.activeGame = true;
})
.catch(function (error) {
});
};
pg.makeMove = function(row, col) {
if ((pg.currentPlayer === 'X' && pg.gameStarter.gameStarter !== authentication.currentUser().email) ||
(pg.currentPlayer === 'O' && pg.gameStarter.gameStarter === authentication.currentUser().email)) {
return;
}
makeMove($http, row, col)
.then(function (response) {
var index = row * 3 + col;
pg.grid[index] = response;
})
.catch(function (error) {
});
};
pg.delete = function() {
deleteGame($http)
.then(function(response) {
})
.catch(function(error) {
console.error('Error deleting game:', error);
});
};
var intervalPromise = $interval(getGameState, 200);
$scope.$on('$destroy', function(){
if (angular.isDefined(intervalPromise)) {
$interval.cancel(intervalPromise);
intervalPromise = undefined;
}
if (pg.activeGame) {
deleteGame($http)
.then(function(response) {
})
.catch(function(error) {
console.error('Error deleting game:', error);
});
}
});
}]);
|
import {ChangeEvent, useEffect, useState} from "react";
import {useDispatch, useSelector} from "react-redux";
import {setQuantity} from "@/redux/donationSlice";
import {RootState} from "@/redux/store";
import {DonationFormProps} from "@/utility/types";
import {DonationNavButtons} from "@/components/reusable/DonationNavButtons";
export function FormStepTwo({step, setStep}: DonationFormProps) {
const [isValidated, setIsValidated] = useState<boolean>(true);
const quantity = useSelector((state: RootState) => state.donation.quantity);
const dispatch = useDispatch();
useEffect(() => {
if (parseInt(quantity) <= 0) {
setIsValidated(false);
}
}, [quantity])
function handleQuantity(event: ChangeEvent<HTMLInputElement>) {
const input = parseInt(event.target.value);
const newQuantity = input < 0 ? '0' : event.target.value;
dispatch(setQuantity(newQuantity));
if(newQuantity !== '0') {
setIsValidated(true);
}
}
return (
<section className="flex flex-col mx-32 pt-8 package-sending-section">
<p className="mb-24">Krok {step}/4</p>
<h4 className="text-4xl">Podaj liczbę 60l worków, w które spakowałeś/aś rzeczy:</h4>
<div className="flex gap-2 mt-16 mb-16">
<span>Liczba 60l worków:</span>
<input
value={quantity}
onChange={handleQuantity}
type="number"
className="bag-number"
/>
</div>
{!isValidated ? <p className="text-red-800 donation-instruction-warning">* Możesz wysłać minumum 1 paczkę</p> : null}
<DonationNavButtons
isFirst={false}
isValidated={isValidated}
step={step}
setStep={setStep}
/>
</section>
);
}
|
import { GraphQLString, GraphQLNonNull } from 'graphql';
import { mutationWithClientMutationId } from 'graphql-relay';
import { successField } from '@entria/graphql-mongo-helpers';
import { generateJwtToken } from '../../../auth';
import { errorField } from '../../error-field/ErrorField';
import { fieldError } from '../../../utils/fieldError';
import { UserModel } from '../UserModel';
import { UserType } from '../UserType';
export const userRegister = mutationWithClientMutationId({
name: 'UserRegister',
inputFields: {
username: { type: new GraphQLNonNull(GraphQLString) },
email: { type: new GraphQLNonNull(GraphQLString) },
password: { type: new GraphQLNonNull(GraphQLString) },
},
mutateAndGetPayload: async ({ email, username, password }) => {
const existingUser = await UserModel.findOne({ email });
if (existingUser) {
return fieldError('email', 'This email is already used');
}
const usernameTaken = await UserModel.findOne({ username });
if (usernameTaken) {
return fieldError('password', 'This username is already used');
}
const user = await new UserModel({
email,
username,
password,
}).save();
const token = generateJwtToken(user);
return {
token,
id: user._id,
success: 'User registered with success',
};
},
outputFields: {
token: {
type: GraphQLString,
resolve: ({ token }) => token,
},
me: {
type: UserType,
resolve: async ({ id }) => await UserModel.findById(id),
},
...successField,
...errorField,
},
});
|
import React, { useState } from 'react'
import Head from 'next/head'
import { Row, Col, Breadcrumb, Affix } from 'antd'
import { CalendarOutlined, FolderOpenOutlined, FireOutlined } from '@ant-design/icons'
import Header from '../components/Header'
import Author from '../components/Author'
import Footer from '../components/Footer'
import '../static/style/pages/detailed.css'
import axios from 'axios'
import servicePath from '../config/apiUrl'
import marked from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'
import Tocify from '../components/tocify.tsx'
import dynamic from 'next/dynamic'
import { StickyContainer, Sticky } from 'react-sticky';
const ParticlesBg = dynamic(
import('particles-bg'),
{
ssr: false //这个要加上,禁止使用 SSR
}
)
const Detailed = (props) => {
const renderer = new marked.Renderer();
const tocify = new Tocify()
renderer.heading = function (text, level, raw) {
const anchor = tocify.add(text, level);
return `<a id="${anchor}" href="#${anchor}" class="anchor-fix"><h${level}>${text}</h${level}></a>\n`;
};
marked.setOptions({
renderer: renderer, //这个是必须填写的,你可以通过自定义的Renderer渲染出自定义的格式
gfm: true, //启动类似Github样式的Markdown,填写true或者false
pedantic: false,//只解析符合Markdown定义的,不修正Markdown的错误。填写true或者false
sanitize: false,//原始输出,忽略HTML标签,这个作为一个开发人员,一定要写flase
tables: true,//支持Github形式的表格,必须打开gfm选项
breaks: true,// 支持Github换行符,必须打开gfm选项,填写true或者false
smartLists: true,//优化列表输出,这个填写ture之后,你的样式会好看很多,所以建议设置成ture
highlight: function (code) {
return hljs.highlightAuto(code).value
}
})
let html = marked(props.article_content)
return (
<>
<Head>
<title>{props.title}</title>
</Head>
<StickyContainer>
<Sticky>{({ style }) => <div style={{ ...style, zIndex: 1000 }}><Header /></div>}</Sticky>
<div>
<Row className="comm-main" type="flex" justify="center">
<Col className="comm-left" xs={24} sm={24} md={16} lg={16} xl={11} >
<div>
<div className="bread-div">
<Breadcrumb>
<Breadcrumb.Item><a href="/">首页</a></Breadcrumb.Item>
<Breadcrumb.Item><a href={"/list?id=" + props.typeId}>{props.typeName}</a></Breadcrumb.Item>
<Breadcrumb.Item>{props.title}</Breadcrumb.Item>
</Breadcrumb>
</div>
<div>
<div className="detailed-title">
{props.title}
</div>
<div className="list-icon center">
<span><CalendarOutlined />{props.addTime.substring(0, 10)}</span>
<span><FolderOpenOutlined />{props.typeName}</span>
<span><FireOutlined />{props.view_count}人</span>
</div>
<div className="detailed-content"
dangerouslySetInnerHTML={{ __html: html }}
>
</div>
</div>
</div>
</Col>
<Col className="comm-right" xs={0} sm={0} md={7} lg={5} xl={4}>
<Author />
<Affix offsetTop={10}>
<div className="detailed-nav comm-box">
<div className="nav-title">文章目录</div>
{tocify && tocify.render()}
</div>
</Affix>
</Col>
</Row>
<Footer />
<ParticlesBg type="square" bg={true} />
</div>
</StickyContainer>
</>
)
}
Detailed.getInitialProps = async (context) => {
console.log(context.query.id)
let id = context.query.id
const promise = new Promise((resolve) => {
axios(servicePath.getArticleById + id).then(
(res) => {
console.log(res)
resolve(res.data.data[0])
}
)
})
return await promise
}
export default Detailed
|
<script>
import {
reactive,
computed,
onMounted,
onUnmounted,
ref,
toRefs,
watch
} from 'vue'
import ModelButton from './components/ModelButton.vue'
import Emits from './components/Emits.vue'
import Emits1 from './components/Emits.vue'
import VmodelTest from './components/VmodelTest.vue'
import TransitionTest from './components/TransitionTest.vue'
export default {
components: {
ModelButton,
Emits,
Emits1,
VmodelTest,
TransitionTest
},
props: {
msg: String
},
methods: {
onClick() {
console.log('click me')
}
},
setup() {
const { counter, doubleCounter } = useCounter()
// 使用元素引用
const desc = ref(null)
// 侦听器
watch(counter, (val, oldValue) => {
const p = desc.value
p.textContent = `counter change from ${oldValue} to ${val}`
})
const msg2 = ref('some message')
return { counter, doubleCounter, msg2, desc }
}
}
function useCounter() {
const data = reactive({
counter: 1,
doubleCounter: computed(() => data.counter * 2)
})
let timer
onMounted(() => {
setInterval(() => {
data.counter++
}, 1000)
})
onUnmounted(() => {
clearInterval(timer)
})
return toRefs(data)
}
</script>
<template>
<header></header>
<main>
<!-- 第一课 -->
<p ref="desc"></p>
<p>{{ doubleCounter }}</p>
<p>{{ counter }}</p>
<!-- <p>{{ msg2 }}</p> -->
<!-- composition -->
<!-- <Composition></Composition> -->
<!-- Teleport: ModalButton -->
<ModelButton></ModelButton>
<!-- Emits -->
<Emits @my-click="onClick"></Emits>
<!-- 实例方法定义组件 -->
<comp></comp>
<!-- v-model 的使用 -->
<VmodelTest></VmodelTest>\
<!-- Transition 使用 -->
<TransitionTest></TransitionTest>
<!-- is属性的使用 -->
<component is="comp"></component>
<table>
<tr v-is="'blog-post-row'"></tr>
</table>
</main>
</template>
<style>
@import './assets/base.css';
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
font-weight: normal;
}
header {
line-height: 1.5;
}
</style>
|
Тестовое задание
* Создайте абстрактный класс BankCard, который будет описывать сущность «Банковская карта». Этот класс должен предоставлять свойство «Баланс», а также функции:
«Пополнить» — пополняет карту на переданную сумму;
«Оплатить» — списывает с карты переданную сумму и возвращает результат типа Boolean;
«Получить информацию о балансе»;
«Получить информацию о доступных средствах» — возвращает информацию о балансе, кредитном лимите и любых других средствах.
* Создайте два производных от BankCard класса DebitCard и CreditCard.
* В классе DebitCard реализуйте функции «Пополнить» и «Получить информацию о балансе».
* Класс CreditCard должен иметь дополнительное свойство «Кредитный лимит». Основные средства кредитной карты состоят из двух частей: кредитная часть и собственные средства.
При пополнении кредитной карты необходимо сначала погасить кредитную часть, и только затем увеличивать собственные средства.
При оплате сначала списываются собственные средства, затем кредитные.
Реализуйте функции «Пополнить», «Оплатить» и «Получить информацию о балансе». Должны учитываться как собственные, так и кредитные средства.
* Создайте несколько производных классов от DebitCard и CreditCard. Добавьте для конкретных дебетовых и кредитных карт различные бонусные программы в виде отдельных переменных.
Примеры:
Бонусные баллы в размере 1% от покупок.
Потенциальный кэшбэк 5% от покупок при условии трат больше 5 000 тыс.
Накопление в размере 0.005% от суммы пополнений.
Для конкретных дебетовых и кредитных карт скорректируйте функции «Пополнить» и «Оплатить» так, чтобы они учитывали конкретные бонусные программы.
Для конкретных дебетовых и кредитных карт реализуйте функцию «Получение информации обо всех доступных средствах». Функция должна учитывать собственные и кредитные средства, а также соответствующие бонусы.
Проанализируйте получившиеся классы. При необходимости перенесите реализацию функций на уровень выше.
Убедитесь, что все функции ваших классов работают корректно. Для этого создайте экземпляры классов и проверьте работу каждой из описанных функций.
|
import { useDispatch, useSelector } from "react-redux";
import { cartActions } from "../../store/cart";
import classes from "./CartButton.module.css";
const CartButton = props => {
const dispatch = useDispatch();
const itemsNumber = useSelector(state => state.cart.items.length);
const toggle = () => {
dispatch(cartActions.toggle());
};
return (
<button className={classes.button} onClick={toggle}>
<span>My Cart</span>
<span className={classes.badge}>{itemsNumber}</span>
</button>
);
};
export default CartButton;
|
'use strict';
const Web3 = require('web3');
const sinon = require('sinon');
const { assert } = require('chai');
const Spy = require('../../../utils/Spy');
const PricerRule = require('../../../lib/ContractInteract/PricerRule');
const AssertAsync = require('../../../utils/AssertAsync');
const Contracts = require('../../../lib/Contracts');
describe('PricerRule.constructor()', () => {
let web3;
let address;
beforeEach(() => {
web3 = new Web3();
address = '0x0000000000000000000000000000000000000002';
});
it('should construct with correct parameter', async () => {
const fakeInstance = sinon.fake();
const spyContract = sinon.replace(Contracts, 'getPricerRule', sinon.fake.returns(fakeInstance));
const instance = new PricerRule(web3, address);
assert.strictEqual(address, instance.address, 'Address must match');
assert.strictEqual(web3, instance.auxiliaryWeb3, 'Web3 instance must match');
Spy.assert(spyContract, 1, [[web3, address]]);
sinon.restore();
});
it('should throw an error when getPricerRule returns undefined object', async () => {
const spyContract = sinon.replace(Contracts, 'getPricerRule', sinon.fake.returns(undefined));
const errorMessage = `Could not load PricerRule contract for: ${address}`;
await AssertAsync.reject(new PricerRule(web3, address), errorMessage);
Spy.assert(spyContract, 1, [[web3, address]]);
sinon.restore();
});
it('should throw an error when web3 object is undefined', async () => {
await AssertAsync.reject(
new PricerRule(undefined, address),
`Mandatory Parameter 'auxiliaryWeb3' is missing or invalid.`
);
});
it('should throw an error when PricerRule contract address is undefined', async () => {
await AssertAsync.reject(
new PricerRule(web3, undefined),
`Mandatory Parameter 'address' is missing or invalid: undefined.`
);
});
});
|
package org.sparta.programmers.lv3;
import java.util.Arrays;
public class StrSort {
public static void main(String[] args) {
class Solution {
public String[] solution(String[] strings, int n) {
String[] answer = new String[strings.length];
Word[] word = new Word[strings.length];
for (int i = 0; i < strings.length; i++) {
word[i] = new Word(strings[i], strings[i].charAt(n));
}
Arrays.sort(word);
for (int i=0;i< word.length; i++){
answer[i]=word[i].word;
}
return answer;
}
static class Word implements Comparable<Word> {
String word;
char c;
public Word(String word, char c) {
this.word = word;
this.c = c;
}
@Override
public int compareTo(Word o) {
if(this.c<o.c) return -1;
else if(this.c>o.c) return 1;
else return this.word.compareTo(o.word);
}
}
}
}
}
|
# Chroma and SQLite3 workaround
__import__("pysqlite3")
import sys
sys.modules["sqlite3"] = sys.modules.pop("pysqlite3")
import streamlit as st
from vectordb import query
from create_wordcloud import show_wordcloud
# Define a function to generate the word cloud
@st.cache_data
def generate_wordcloud(file_names, selected_file, list_pos):
return show_wordcloud(file_names, selected_file, list_pos)
# Define a function to generate the query
@st.cache_data
def generate_query(text, selected_file):
return query(text, selected_file)
# Define a function to highlight the word in the text
def highlight(text, word):
return text.replace(word, f'<span style="color:orange">{word}</span>')
# Configure the Streamlit page layout
st.set_page_config(layout="wide")
st.set_option("deprecation.showPyplotGlobalUse", False)
# Add a sidebar for selecting a candidate file
file_names = {
"Juan Daniel Oviedo": "oviedo.txt",
"Carlos Fernando Galán": "galan.txt",
"Diego Molano": "molano.txt",
"Gustavo Bolivar": "bolivar.txt",
}
selected_file = st.sidebar.selectbox("Escoja un candidato", file_names.keys())
# Display the app title and selected candidate
st.title("Elecciones Bogotá 2023 :city_sunset:")
st.subheader(
"En este dashboard, podrás explorar los temas más importantes de los candidatos a la alcaldía de Bogotá."
)
# Add a divider and a subheader for the next steps
st.divider()
st.header(f"¿Qué dice {selected_file} sobre...?")
text = st.text_input("Escribe un texto para buscar en las entrevistas y debates:")
distance = 0.8
if text:
results, distances, ids = generate_query(text, selected_file)
_, col2, _, col4, _, col6, _ = st.columns([1, 5, 1, 5, 1, 5, 1])
with col2:
if distances[0] < distance:
response = f"'{results[0]['transcribe']}'"
st.video(results[0]["webpage_url"], start_time=results[0]["start_time"])
st.markdown(highlight(response, text), unsafe_allow_html=True)
st.markdown(f"Distancia usando similaridad de coseno: {distances[0]:.3f}")
else:
st.error("No se encontró ninguna coincidencia relevante")
with col4:
if distances[1] < distance:
response = f"'{results[1]['transcribe']}'"
st.video(results[1]["webpage_url"], start_time=results[1]["start_time"])
st.markdown(highlight(response, text), unsafe_allow_html=True)
st.markdown(f"Distancia usando similaridad de coseno: {distances[1]:.3f}")
else:
st.error("No se encontró ninguna coincidencia relevante")
with col6:
if distances[2] < distance:
response = f"'{results[2]['transcribe']}'"
st.video(results[2]["webpage_url"], start_time=results[2]["start_time"])
st.markdown(highlight(response, text), unsafe_allow_html=True)
st.markdown(f"Distancia usando similaridad de coseno: {distances[2]:.3f}")
else:
st.error("No se encontró ninguna coincidencia relevante")
st.divider()
st.header(f"¿De qué habla {selected_file}?")
st.markdown(
f"A continuación te mostramos las palabras más comunes usadas por el candidato {selected_file} tanto en entrevistas como en debates:"
)
# Generate and display a word cloud from the preprocessed text data
dict_pos = {
"noun_on": "NOUN",
"verb_on": "VERB",
"adj_on": "ADJ",
"propn_on": "PROPN",
} # Dictionary of parts of speech
col1, col2 = st.columns([7, 2])
with col2:
st.markdown("Seleccione las partes de discurso a incluir en el wordcloud:")
selected = []
noun_on = st.toggle("Sustantivos", True)
if noun_on:
selected.append("noun_on")
propn_on = st.toggle("Nombres propios", True)
if propn_on:
selected.append("propn_on")
verb_on = st.toggle("Verbos", True)
if verb_on:
selected.append("verb_on")
adj_on = st.toggle("Adjetivos", True)
if adj_on:
selected.append("adj_on")
# Get the corresponding values for the selected keys
list_pos = [dict_pos[key] for key in selected]
with col1:
if list_pos == []:
st.error("No se ha seleccionado ninguna parte de discurso")
else:
wordcloud = generate_wordcloud(file_names, selected_file, list_pos)
st.image(wordcloud)
|
import React, { useContext, useEffect, useState } from "react"
import { LocationContext } from "./LocationProvider"
import "./Location.css"
import { useParams, useHistory } from "react-router-dom"
export const LocationDetail = () => {
const { getLocationById } = useContext(LocationContext)
const [location, setLocation] = useState({})
const { locationId } = useParams();
const history = useHistory();
// debugger
useEffect(() => {
getLocationById(locationId)
.then((response) => {
setLocation(response)
})
}, [])
return (
<section className="location">
<h3 className="location__name">{location.name}</h3>
<div className="location__address">{location.address}</div>
<h4>Employees</h4>
<ul>
{location.employees?.map(employee => <li key={employee.id}>{employee.name}</li>)}
</ul>
<h4>Current Residents</h4>
<ul>
{location.animals?.map(animal => <li key={animal.id}>{animal.name}</li>)}
</ul>
<button onClick={() => { history.push(`/locations/edit/${location.id}`) }}>Edit</button>
</section>
)
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCarsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('make_id');
$table->unsignedBigInteger('model_id');
$table->unsignedInteger('year');
$table->unsignedDecimal('mileage');
$table->string('color', 64);
$table->unsignedDecimal('price');
$table->timestamps();
$table->foreign('make_id')->references('id')->on('car_makes')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('model_id')->references('id')->on('car_models')->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('cars');
}
}
|
<script lang="ts">
import {
Alert,
Button,
Card,
Heading,
Hr,
Input,
Label,
Mark,
Modal,
P,
Search,
Spinner,
Toggle
} from 'flowbite-svelte';
import Icon from 'svelte-icons-pack/Icon.svelte';
import Plus from 'svelte-icons-pack/cg/CgMathPlus.js';
import { enhance } from '$app/forms';
import Spacer from '$lib/components/Spacer.svelte';
import type { DashboardSavedSearches, DashboardUser } from '$lib/types/frontend';
// State
let loading = false;
let newSearchModalOpen = false;
// Data from server
export let data: DashboardUser & { SavedSearch: DashboardSavedSearches[] };
export let user: DashboardUser;
$: user = data;
export let savedSearches: DashboardSavedSearches[];
$: savedSearches = data.SavedSearch;
export let form: {
message?: string;
};
</script>
<div>
<Heading>
Hey {user.username}
</Heading>
<Spacer spacing="15" />
<P size="xl">
How strong is your <Mark>rare</Mark> game?
</P>
</div>
<Spacer spacing="30" />
<div class="flex gap-2">
<Search size="md" />
<Button on:click={() => (newSearchModalOpen = true)}
><Icon src={Plus} /> <Spacer direction="horizontal" spacing="10" /> New</Button
>
<Modal title="Add a new query" bind:open={newSearchModalOpen}>
<form id="new-query" method="post" action="/app?/newQuery" use:enhance>
<Label>
<P>Search terms</P>
<Input placeholder="Junko Ohashi DEF, かとうはつえ, etc." name="query" />
<Spacer spacing="15" />
<Toggle checked={true} name="vinylOnly">Vinyl Only</Toggle>
<Spacer spacing="15" />
<P>
This interface is a WIP, please bear with me as more options will be added for
things like Platform, exclude terms, etc. :)
</P>
</Label>
</form>
<svelte:fragment slot="footer">
<Button form="new-query" type="submit" bind:disabled={loading}>
{#if loading}
<Spinner size={4} />
{:else}
Submit
{/if}
</Button>
<Button color="alternative" on:click={() => (newSearchModalOpen = false)}>Cancel</Button
>
</svelte:fragment>
</Modal>
</div>
<Spacer spacing="30" />
<!-- main content, the saved search cards -->
<div>
{#if form?.message}
<Alert>
{form.message}
<div slot="icon">
<Icon src={Plus} />
</div>
</Alert>
<Spacer spacing="15" />
{/if}
{#if !savedSearches.length}
<P align="center" size="xl">You have no saved searches! :(</P>
{:else}
<div class="saved-searches">
{#each savedSearches as search}
<Card href={`/app/${search.id}`}>
<Heading tag="h4">
{search.query}
</Heading>
<Spacer spacing="15" />
<Hr />
<Spacer spacing="15" />
<P>
<b>Format:</b> <i>{search.vinylOnly ? 'Vinyl only' : 'All formats'}</i>
</P>
</Card>
{/each}
</div>
{/if}
</div>
<style>
.saved-searches {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 10px;
}
</style>
|
declare namespace _default {
namespace promises {
/**
* By calling `promises.add`, a new [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* is made available for other code or plugins to depend on via the
* {@link _converse.api.waitUntil} method.
*
* Generally, it's the responsibility of the plugin which adds the promise to
* also resolve it.
*
* This is done by calling {@link _converse.api.trigger}, which not only resolves the
* promise, but also emits an event with the same name (which can be listened to
* via {@link _converse.api.listen}).
*
* @method _converse.api.promises.add
* @param {string|array} [promises] The name or an array of names for the promise(s) to be added
* @param {boolean} [replace=true] Whether this promise should be replaced with a new one when the user logs out.
* @example _converse.api.promises.add('foo-completed');
*/
function add(promises?: string | any[], replace?: boolean): void;
}
/**
* Wait until a promise is resolved or until the passed in function returns
* a truthy value.
* @method _converse.api.waitUntil
* @param {string|function} condition - The name of the promise to wait for,
* or a function which should eventually return a truthy value.
* @returns {Promise}
*/
function waitUntil(condition: string | Function): Promise<any>;
}
export default _default;
//# sourceMappingURL=promise.d.ts.map
|
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Helpers\YouTube;
use App\Models\Video;
use App\Models\Comment;
use App\Models\Message;
use App\Models\Rating;
class WatchController extends Controller
{
public function ratingServlet(Request $request)
{
switch(true)
{
case !Auth::check():
return "Please log-in.";
case $request->has("action_add_rating"):
// Validate POST values
$request->validate([
"video_id" => ["required", "string", "exists:videos,video_id"],
"rating" => ["required", "numeric", "min:1", "max:5"],
]);
// Update/create the rating
$rating = Rating::updateOrCreate(
["video_id" => $request->video_id, "user_id" => $request->user()->username],
["rating" => $request->rating]
);
// Initialize the video
$video = Video::where("video_id", $request->video_id);
// Update the video's rating count
if($rating->wasRecentlyCreated && !$rating->wasChanged())
{
// Increment rating count
$video ->increment("num_ratings", 1);
}
// Calculate the video's average rating
$avg_rating = Rating::where("video_id", $request->video_id)
->avg("rating");
// Update the video with the average rating
$video->update([
"avg_rating" => $avg_rating,
]);
// Return the user back with a success message
return "Thanks for the rating!";
default:
return "An error occurred.";
}
}
public function commentServlet(Request $request)
{
switch(true)
{
case !Auth::check():
return "LOGIN " . $request->form_id;
case $request->has("add_comment"):
// Validate POST values
$request->validate([
"video_id" => ["required", "string", "min:11", "max:11"],
"comment" => ["required", "string", "max:500"],
]);
// Get the video
$video = Video::where("video_id", $request->video_id)->firstOrFail();
// Get uploader and commenter
$commenter = $request->user();
$uploader = $video->uploader();
// Generate a new comment ID
$id_loop = true;
while($id_loop == true)
{
// Generate a new 11 char YouTube ID
$c_id = YouTube::generateId();
// If the video exists
if(!Comment::where('comment_id', $c_id)->exists())
$id_loop = false; // Cancel the loop
}
// Check if the reference video exists
// TO-DO: Move this to its own rule
$reference_video = Video::where("video_id", $request->field_reference_video);
if(!$reference_video->exists() || $request->field_reference_video == $request->video_id)
$request->field_reference_video = null;
// Check if reply_parent_id exists
// TO-DO: Also move this to its own rule somehow
$comment = Comment::where("comment_id", $request->reply_parent_id)->first();
$request->reply_parent_id = match (true) {
// Does the comment exist?
!$comment => null,
// If the reply parent ID of the comment being responded to is filled
// Set it to that same reply parent ID
$comment->reply_parent_id !== null => $comment->reply_parent_id,
// We already checked if the comment exists, let's just let it go thru
default => $request->reply_parent_id,
};
// Create the comment
Comment::create([
"comment_id" => $c_id,
"body" => $request->comment,
"commenter" => $commenter->username,
"video_id" => $request->video_id,
"reference_video" => $request->field_reference_video,
"reply_parent_id" => $request->reply_parent_id,
]);
// Update the video's comment count
$video->increment("num_comments", 1);
// Get the original comment from the reply_parent_id
$og_comment = Comment::where("comment_id", $request->reply_parent_id)->first();
// This will dictate whether we are sending it to the commenter or the replier
$send_to = ($og_comment)
? $og_comment->commenter()
: $uploader;
// Send a message to the commenter or uploader
if($send_to->id !== $commenter->id)
{
Message::create([
"message_id" => YouTube::generateId(),
"sent_by" => $commenter->id,
"sent_to" => $send_to->id,
"subject" => $commenter->username . " has left a ".(($request->reply_parent_id) ? "reply to your comment on \"".$video->title."\"" : "comment on your video \"".$video->title."\""),
"message" => $commenter->username . " commented: \n\"" . $request->comment . "\"" . (($og_comment) ? "\n\nOriginal comment: \n\"".$og_comment->body."\"" : "")
]);
}
// Return the user back with a success message
return "OK " . $request->form_id;
default:
return "ERROR " . $request->form_id;
}
}
}
|
import { BaseTelegramClient, tl } from '@mtcute/core'
import { ArrayPaginated, ChatInviteLink, ChatInviteLinkMember, InputPeerLike, PeersIndex } from '../../types/index.js'
import { makeArrayPaginated, normalizeDate, toInputUser } from '../../utils/index.js'
import { resolvePeer } from '../users/resolve-peer.js'
/**
* Iterate over users who have joined
* the chat with the given invite link.
*
* @param chatId Chat ID
* @param params Additional params
*/
export async function getInviteLinkMembers(
client: BaseTelegramClient,
chatId: InputPeerLike,
params?: {
/**
* Invite link for which to get members
*/
link?: string | ChatInviteLink
/**
* Maximum number of users to return
*
* @default 100
*/
limit?: number
/**
* Offset request/join date used as an anchor for pagination.
*/
offsetDate?: Date | number
/**
* Offset user used as an anchor for pagination
*/
offsetUser?: tl.TypeInputUser
/**
* Whether to get users who have requested to join
* the chat but weren't accepted yet
*/
requested?: boolean
/**
* Search for a user in the pending join requests list
* (if passed, {@link requested} is assumed to be true)
*
* Doesn't work when {@link link} is set (Telegram limitation)
*/
requestedSearch?: string
},
): Promise<ArrayPaginated<ChatInviteLinkMember, { date: number; user: tl.TypeInputUser }>> {
const peer = await resolvePeer(client, chatId)
if (!params) params = {}
const { limit = 100, link, requestedSearch, requested = Boolean(requestedSearch) } = params
const { offsetUser = { _: 'inputUserEmpty' } } = params
const offsetDate = normalizeDate(params.offsetDate) ?? 0
const res = await client.call({
_: 'messages.getChatInviteImporters',
limit,
peer,
link: typeof link === 'string' ? link : link?.link,
requested,
q: requestedSearch,
offsetDate,
offsetUser,
})
const peers = PeersIndex.from(res)
const members = res.importers.map((it) => new ChatInviteLinkMember(it, peers))
const last = members[members.length - 1]
const nextOffset = last ?
{
date: last.raw.date,
user: toInputUser(last.user.inputPeer),
} :
undefined
return makeArrayPaginated(members, res.count, nextOffset)
}
|
import { useState } from "react";
const PostForm = (props) => {
const [post, setPost] = useState({
title: props?.data.title || "",
body: props?.data.body || ""
});
const onChangeHandler = (e) => {
setPost({
...post,
[e.target.name]: e.target.value
});
}
const renderField = (label) => {
return (
<div>
<label>{label}</label>
<input type="text" name={label.toLowerCase()} onChange={onChangeHandler} value={post[label.toLowerCase()]}/>
</div>
);
}
const onSubmitHandler = (e) => {
e.preventDefault();
props.onSubmit(post);
setPost({
title: '',
body: ''
});
}
return (
<form onSubmit={onSubmitHandler}>
{renderField("Title")}
{renderField("Body")}
<button>Submit</button>
</form>
)
}
export default PostForm;
|
import 'package:flutter/rendering.dart';
import 'composition.dart';
import 'frame_rate.dart';
import 'lottie_delegates.dart';
import 'lottie_drawable.dart';
import 'render_cache.dart';
/// A Lottie animation in the render tree.
///
/// The RenderLottie attempts to find a size for itself that fits in the given
/// constraints and preserves the composition's intrinsic aspect ratio.
class RenderLottie extends RenderBox {
RenderLottie({
required LottieComposition? composition,
LottieDelegates? delegates,
bool? enableMergePaths,
bool? enableApplyingOpacityToLayers,
double progress = 0.0,
FrameRate? frameRate,
double? width,
double? height,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
FilterQuality? filterQuality,
bool enableRenderCache = false,
required double devicePixelRatio,
}) : assert(progress >= 0.0 && progress <= 1.0),
assert(
!enableRenderCache || frameRate != FrameRate.max,
'FrameRate.max cannot be used with enableRenderCache. '
'You should use a specific frame rate. e.g. FrameRate(60)'),
_drawable = composition != null
? (LottieDrawable(composition, frameRate: frameRate)
..setProgress(progress)
..delegates = delegates
..enableMergePaths = enableMergePaths ?? false
..isApplyingOpacityToLayersEnabled =
enableApplyingOpacityToLayers ?? false
..filterQuality = filterQuality)
: null,
_width = width,
_height = height,
_fit = fit,
_alignment = alignment,
_enableRenderCache = enableRenderCache,
_devicePixelRatio = devicePixelRatio;
/// The lottie composition to display.
LottieComposition? get composition => _drawable?.composition;
LottieDrawable? _drawable;
void setComposition(LottieComposition? composition,
{required double progress,
required FrameRate? frameRate,
required LottieDelegates? delegates,
bool? enableMergePaths,
bool? enableApplyingOpacityToLayers,
FilterQuality? filterQuality}) {
var drawable = _drawable;
enableMergePaths ??= false;
enableApplyingOpacityToLayers ??= false;
var needsLayout = false;
var needsPaint = false;
if (composition == null) {
if (drawable != null) {
drawable = _drawable = null;
needsPaint = true;
needsLayout = true;
}
} else {
if (drawable == null ||
drawable.composition != composition ||
drawable.frameRate != frameRate) {
drawable =
_drawable = LottieDrawable(composition, frameRate: frameRate);
needsLayout = true;
needsPaint = true;
}
needsPaint |= drawable.setProgress(progress);
if (drawable.delegates != delegates) {
drawable.delegates = delegates;
needsPaint = true;
}
if (enableMergePaths != drawable.enableMergePaths) {
drawable.enableMergePaths = enableMergePaths;
needsPaint = true;
}
if (enableApplyingOpacityToLayers !=
drawable.isApplyingOpacityToLayersEnabled) {
drawable.isApplyingOpacityToLayersEnabled =
enableApplyingOpacityToLayers;
needsPaint = true;
}
if (filterQuality != drawable.filterQuality) {
drawable.filterQuality = filterQuality;
needsPaint = true;
}
}
if (needsPaint) {
markNeedsPaint();
}
if (needsLayout && (_width == null || _height == null)) {
markNeedsLayout();
}
}
/// If non-null, requires the composition to have this width.
///
/// If null, the composition will pick a size that best preserves its intrinsic
/// aspect ratio.
double? get width => _width;
double? _width;
set width(double? value) {
if (value == _width) {
return;
}
_width = value;
markNeedsLayout();
}
/// If non-null, require the composition to have this height.
///
/// If null, the composition will pick a size that best preserves its intrinsic
/// aspect ratio.
double? get height => _height;
double? _height;
set height(double? value) {
if (value == _height) {
return;
}
_height = value;
markNeedsLayout();
}
/// How to inscribe the composition into the space allocated during layout.
BoxFit? get fit => _fit;
BoxFit? _fit;
set fit(BoxFit? value) {
if (value == _fit) {
return;
}
_fit = value;
markNeedsPaint();
}
/// How to align the composition within its bounds.
AlignmentGeometry get alignment => _alignment;
AlignmentGeometry _alignment;
set alignment(AlignmentGeometry value) {
if (value == _alignment) {
return;
}
_alignment = value;
markNeedsPaint();
}
bool get enableRenderCache => _enableRenderCache;
bool _enableRenderCache;
set enableRenderCache(bool value) {
if (value == _enableRenderCache) {
return;
}
_enableRenderCache = value;
markNeedsPaint();
}
double get devicePixelRatio => _devicePixelRatio;
double _devicePixelRatio;
set devicePixelRatio(double value) {
if (value == _devicePixelRatio) {
return;
}
_devicePixelRatio = value;
markNeedsPaint();
}
/// Find a size for the render composition within the given constraints.
///
/// - The dimensions of the RenderLottie must fit within the constraints.
/// - The aspect ratio of the RenderLottie matches the intrinsic aspect
/// ratio of the Lottie animation.
/// - The RenderLottie's dimension are maximal subject to being smaller than
/// the intrinsic size of the composition.
Size _sizeForConstraints(BoxConstraints constraints) {
// Folds the given |width| and |height| into |constraints| so they can all
// be treated uniformly.
constraints = BoxConstraints.tightFor(
width: _width,
height: _height,
).enforce(constraints);
if (_drawable == null) {
return constraints.smallest;
}
return constraints
.constrainSizeAndAttemptToPreserveAspectRatio(_drawable!.size);
}
@override
double computeMinIntrinsicWidth(double height) {
assert(height >= 0.0);
if (_width == null && _height == null) {
return 0.0;
}
return _sizeForConstraints(BoxConstraints.tightForFinite(height: height))
.width;
}
@override
double computeMaxIntrinsicWidth(double height) {
assert(height >= 0.0);
return _sizeForConstraints(BoxConstraints.tightForFinite(height: height))
.width;
}
@override
double computeMinIntrinsicHeight(double width) {
assert(width >= 0.0);
if (_width == null && _height == null) {
return 0.0;
}
return _sizeForConstraints(BoxConstraints.tightForFinite(width: width))
.height;
}
@override
double computeMaxIntrinsicHeight(double width) {
assert(width >= 0.0);
return _sizeForConstraints(BoxConstraints.tightForFinite(width: width))
.height;
}
@override
bool hitTestSelf(Offset position) => true;
@override
Size computeDryLayout(BoxConstraints constraints) {
return _sizeForConstraints(constraints);
}
@override
void performLayout() {
size = _sizeForConstraints(constraints);
}
@override
void paint(PaintingContext context, Offset offset) {
if (_drawable == null) return;
RenderCacheContext? cacheContext;
if (enableRenderCache) {
cacheContext = RenderCacheContext(
handle: globalRenderCache.acquire(this),
devicePixelRatio: _devicePixelRatio,
localToGlobal: localToGlobal,
);
} else {
globalRenderCache.release(this);
}
_drawable!.draw(
context.canvas,
offset & size,
fit: _fit,
alignment: _alignment.resolve(TextDirection.ltr),
renderCache: cacheContext,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(
DiagnosticsProperty<LottieComposition>('composition', composition));
properties.add(DoubleProperty('width', width, defaultValue: null));
properties.add(DoubleProperty('height', height, defaultValue: null));
properties.add(EnumProperty<BoxFit>('fit', fit, defaultValue: null));
properties.add(DiagnosticsProperty<AlignmentGeometry>(
'alignment', alignment,
defaultValue: null));
}
@override
void dispose() {
globalRenderCache.release(this);
super.dispose();
}
}
|
/* для любознательных: Написать программу премножения любых целых чисел.
Данная программа использует методы. Число вводится как строка. Число раскладывается в ряд по степеням числа 10 - каждый символ строки-числа (массива
символов по сути) умножается на 10 в степени, равной его порядковому номер. После перемножения получается матрица вычисленного числа без сдвига.
Далее двиг по арифметическим правилам и приведение числа-произведения к нормальному изображению. В завершении произведение из-за размеров приводится
к строчному типу.
Где :
--- naimed1 и naimed2 - вводимые числа ( при вводе-выводе используются их более удобные названия 'a' и 'b');
--- indexA и indexB - разрядность вводимых чисел;
--- indexArrayResult - рязрядность числа-произведения вводимых чисел;
--- arrayAfterMultipcation - число-произведение вводимых чисел (свертка без смещения);
--- arrayFinal - число-произведение вводимых чисел (свертка со смещением);
--- с - число-произведение в строком типе ( метод Message - Информация для пользователя).
*/
string InputRequest(string name1)//Ввод числа.
{
Console.Write("\tВведите очень большое число " + name1 + ": ");
string name = Console.ReadLine()!;
Console.WriteLine("\tВведено : " + name);
return name!;
}
int[] CreateArray(int size)//Создание массива
{
return new int[size];
}
int ArrayLenght(string name)//Определение разрядности вводимого числа
{
int indexArray = name!.Length;
Console.WriteLine("\tРазрядность числа : " + name + " равна " + indexArray);
return indexArray;
}
void PolynomialArray(string name, int indexArray,string nameNumber)//Разложение введенного числа в ряд по степеням числа 10-для наглядности
{
int i = 0;
Console.WriteLine("\tРазложение введенного чисела "+nameNumber+ " в ряд по степеням числа 10 :");
while (i < indexArray)
{
Console.Write(name[i] + "x10X" + (indexArray - i - 1) + "+");
i++;
}
Console.WriteLine();
}
int SizeArray(int index1Array, int index2Array, char array1Number0, char array2Number0)//Определение рязрядности числа-произведения
{
int indexSumm = index1Array + index2Array - 1;
char temp1a = Convert.ToChar(array1Number0);
char temp1b = Convert.ToChar(array2Number0);
int temp1 = (temp1a - '0') * (temp1b - '0');
if (temp1 / 10 != 0) indexSumm++;
Console.WriteLine("\tРазрядность числа-произведения двух введенных чисел : " + indexSumm);
return indexSumm;
}
int[] ArrayMultiplication(int index1Array, int index2Array, int indexSumm, string name1, string name2, int[] arrayResult)//Умножение чисел
{
int k = 0;
int j = index2Array - 1;
while (j >= 0)
{
int i = index1Array - 1;
k = indexSumm - 1 - index2Array + j + 1;
while (i >= 0)
{
char tempora = Convert.ToChar(name1[i]);
char temporb = Convert.ToChar(name2[j]);
int tempopar = (tempora - '0') * (temporb - '0');
arrayResult[k] = tempopar + arrayResult[k];
i--;
k--;
}
j--;
}
return arrayResult;
}
int[] ArrayFinal(int[] arrayIn, int[] arrayOut, int indexSumm)//Приведение результата произведения к стандартному виду
{
int temp3 = 0;
int nn = indexSumm - 1;
while (nn >= 0)
{
int rrr = arrayIn[nn] + temp3;
arrayOut[nn] = rrr % 10;
temp3 = rrr / 10;
nn--;
}
return arrayOut;
}
void PrintArray(int[] array, int size)//Вывод на экран результата произведения
{
Console.WriteLine();
int indexend2 = 0;
while (indexend2 < size)
{
Console.Write(" " + array[indexend2]);
indexend2++;
}
}
void Message(string a,string b, int[] array, int index )//Вывод для пользователя и приведения результата к строковому виду.
{
//Console.WriteLine();
Console.WriteLine("\n\n\tИнформация для пользователя");
Console.WriteLine(" \n" + " Введено число a : " + a + " \n\t и число b : " + b);
int indexend3 = 1;
string c = Convert.ToString(array[0]);
while (indexend3 < index)
{
c = c + Convert.ToString(array[indexend3]);
indexend3++;
}
Console.WriteLine("\n\t Их произведение равно : " + c);
}
string naimed1 = InputRequest("a");
string naimed2 = InputRequest("b");
int indexA = ArrayLenght(naimed1);
int indexB = ArrayLenght(naimed2);
PolynomialArray(naimed1, indexA,naimed1);
PolynomialArray(naimed2, indexB,naimed2);
int indexArrayResult = SizeArray(indexA, indexB, naimed1[0], naimed2[0]);
int[] arrayAfterMultipcation = CreateArray(indexArrayResult);
arrayAfterMultipcation = ArrayMultiplication(indexA, indexB, indexArrayResult, naimed1, naimed2, arrayAfterMultipcation);
PrintArray(arrayAfterMultipcation, indexArrayResult);
int[] arrayFinal = CreateArray(indexArrayResult);
arrayFinal = ArrayFinal(arrayAfterMultipcation, arrayFinal, indexArrayResult);
PrintArray(arrayFinal, indexArrayResult);
Message(naimed1,naimed2,arrayFinal,indexArrayResult);
|
<?php
namespace App\Nova;
use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\Currency;
use Laravel\Nova\Fields\BelongsTo;
use Wm\MapMultiPolygon\MapMultiPolygon;
use Laravel\Nova\Http\Requests\NovaRequest;
class CatalogArea extends Resource
{
/**
* The model the resource corresponds to.
*
* @var class-string<\App\Models\CatalogArea>
*/
public static $model = \App\Models\CatalogArea::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* @var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* @var array
*/
public static $search = [
'id',
];
/**
* Get the fields displayed by the resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return array
*/
public function fields(NovaRequest $request)
{
return [
ID::make()->sortable(),
BelongsTo::make('Catalog')->readonly(),
BelongsTo::make('Catalog Type')->readonly(),
$this->estimated_value > 0 ? Text::make('Valore Stimato', 'estimated_value')->displayUsing(function ($value) {
return '<p style="color:green; text-align:left;">' . number_format($value, 2, ',', '.') . '€' . '</p>';
})->sortable()->asHtml()
:
Text::make('Valore Stimato', 'estimated_value', function ($value) {
return '<p style="color:red">Nessuna stima disponibile</p>';
})->sortable()->asHtml(),
Text::make('Link')
->resolveUsing(function ($value, $resource, $attribute) {
return '<a class="link-default" target="_blank" href="' . route(
'catalog-area',
['id' => $resource->id]
) . '">View Area</a>';
})
->asHtml()
->exceptOnForms(),
MapMultiPolygon::make('Geometry')->withMeta([
'center' => ['42.795977075', '10.326813853'],
'attribution' => '<a href="https://webmapp.it/">Webmapp</a> contributors',
])->hideFromIndex(),
Text::make('Area', function () {
$area
= DB::table('catalog_areas')
->select(DB::raw('ST_Area(geometry) as area'))
->where('id', $this->id)
->value('area');
return number_format($area, 2, ',', '.') . ' MQ';
})->hideFromIndex()
->sortable(),
Text::make(
'Interventi Forestali',
function () {
//if $this->catalog_estimate is an empty array display ND
if (empty($this->catalog_estimate)) {
return '<p style="color:red">ND</p>';
}
$items = $this->catalog_estimate['interventions']['items'];
$info = $this->catalog_estimate['interventions']['info'];
$o = '<style> table, th, td { border: 1px solid black; padding: 5px;}</style>';
$o .= '<table border="1">';
$o .= "<tr>";
$o .= "<th>Codice Intervento</th>";
$o .= "<th>Area</th>";
$o .= "<th>€/Ettaro</th>";
$o .= "<th>Totale (€)</th>";
$o .= "</tr>";
//create headings for interventions info table: Area(ettari) e Totale(€). Insert only intervention_area value in the column Area
$i = '<style> table, th, td { border: 1px solid black; padding: 5px;}</style>';
$i .= '<table border="1">';
$i .= "<tr>";
$i .= "<th colspan='3'>Info</th>";
$i .= "<th colspan='1'>Area</th>";
$i .= "<th>€</th>";
$i .= "</tr>";
//if $items is empty display a row with ND
if (empty($items)) {
$o .= "<tr>";
$o .= "<td>ND</td>";
$o .= "<td>ND</td>";
$o .= "<td>ND</td>";
$o .= "<td>ND</td>";
$o .= "</tr>";
}
//if $info is empty display a row with ND
if (empty($info)) {
$i .= "<tr>";
$i .= "<td colspan='4'>ND</td>";
$i .= "</tr>";
}
foreach ($items as $item) {
$o .= "<tr>";
$o .= $item['code'] ? "<td>{$item['code']}</td>" : "<td>ND</td>";
$o .= $item['area'] ? "<td>{$item['area']}</td>" : "<td>ND</td>";
$o .= $item['unit_price'] ? "<td>{$item['unit_price']}</td>" : "<td>ND</td>";
$o .= $item['price'] ? "<td>{$item['price']}</td>" : "<td>ND</td>";
$o .= "</tr>";
}
foreach ($info as $key => $value) {
$i .= "<tr>";
$i .= "<td colspan='3'>{$key}</td>";
//only if $key == intervention_area insert the value in the column Area and not in the column €
if ($key == 'intervention_area') {
$i .= "<td>{$value}</td>";
$i .= "<td>ND</td>";
} else {
$i .= "<td>ND</td>";
$i .= "<td>{$value}</td>";
}
$i .= "</tr>";
}
$o .= "</table>";
$i .= "</table>";
return [$o, $i];
}
)->asHtml()->onlyOnDetail(),
Text::make('Mantenimento', function () {
if (empty($this->catalog_estimate)) {
return '<p style="color:red">ND</p>';
}
$maintenanceItems = $this->catalog_estimate['maintenance']['items'];
$maintenanceSummary = $this->catalog_estimate['maintenance']['summary'];
$maintenanceCertifications = $this->catalog_estimate['maintenance']['certifications'];
//create headings for maintenance items table
$o = '<style> table, th, td { border: 1px solid black; padding: 5px;}</style>';
$o .= '<table border="1">';
$o .= "<tr>";
$o .= "<th>Codice Intervento</th>";
$o .= "<th>Area</th>";
$o .= "<th>€/Ettaro</th>";
$o .= "<th>Totale(€)</th>";
$o .= "</tr>";
//create headings for maintenance summary table
$i = '<style> table, th, td { border: 1px solid black; padding: 5px;}</style>';
$i .= '<table border="1">';
$i .= "<tr>";
$i .= "<th colspan='3'>Summary</th>";
$i .= "<th colspan='3'>€</th>";
$i .= "</tr>";
//create headings for maintenance certifications table
$u = '<style> table, th, td { border: 1px solid black; padding: 5px;}</style>';
$u .= '<table border="1">';
$u .= "<tr>";
$u .= "<th>Certifications</th>";
$u .= "<th>€</th>";
$u .= "</tr>";
foreach ($maintenanceItems as $item) {
$o .= "<tr>";
$o .= $item['code'] ? "<td>{$item['code']}</td>" : "<td>ND</td>";
$o .= $item['area'] ? "<td>{$item['area']}</td>" : "<td>ND</td>";
$o .= $item['unit_price'] ? "<td>{$item['unit_price']}</td>" : "<td>ND</td>";
$o .= $item['price'] ? "<td>{$item['price']}</td>" : "<td>ND</td>";
$o .= "</tr>";
}
foreach ($maintenanceCertifications as $certification) {
$u .= "<tr>";
$u .= $certification['code'] ? "<td>{$certification['code']}</td>" : "<td>ND</td>";
$u .= $certification['price'] ? "<td>{$certification['price']}</td>" : "<td>ND</td>";
$u .= "</tr>";
}
foreach ($maintenanceSummary as $key => $value) {
$i .= "<tr>";
$i .= "<td colspan='3'>{$key}</td>";
$i .= "<td>{$value}</td>";
$i .= "</tr>";
}
$o .= "</table>";
$i .= "</table>";
$u .= "</table>";
return [$o, $u, $i];
})->asHtml()->onlyOnDetail(),
Text::make('Costi Generali', function () {
if (empty($this->catalog_estimate)) {
return '<p style="color:red">ND</p>';
}
$generals = $this->catalog_estimate['general'];
$o = '<style> table, th, td { border: 1px solid black; padding: 5px;}</style>';
$o .= '<table border="1">';
$o .= "<tr>";
$o .= "<th>Costi Generali</th>";
$o .= "<th>€</th>";
$o .= "</tr>";
foreach ($generals as $key => $value) {
$o .= "<tr>";
$o .= "<td>{$key}</td>";
$o .= "<td>{$value}</td>";
$o .= "</tr>";
}
$o .= "</table>";
return $o;
})->asHtml()->onlyOnDetail(),
];
}
/**
* Get the cards available for the request.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return array
*/
public function cards(NovaRequest $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return array
*/
public function filters(NovaRequest $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return array
*/
public function lenses(NovaRequest $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return array
*/
public function actions(NovaRequest $request)
{
return [];
}
}
|
using System.Collections;
using UnityEngine;
namespace AI
{
public class RushEnemyAI : DefaultEnemyAI
{
/*Notes:
*FNAF Source decompiled: https://imgur.com/a/xe01I#aaR227u
* Each animatronic gets updated after a certain amount of time.
* Bonnie gets one every 4 and 97/100 seconds, Chica every 4 and 98/100 seconds, Freddy every 3 and 2/100 seconds, and Foxy every 5 and 1/100 seconds.
* They are then chosen to move if a random number between 1 and 20 is less than or equal to the animatronic's current activity level.
* This makes them move more often the higher the activity level is and randomizes when they move.
* Bonnie and Chica can move at the same time. The 1/100 sec offset makes Chica's check run one tick after Bonnie's check.
* Foxy has a countdown time that's supposed to prevent him from moving until about 1-17.5 seconds after the monitor is put down.
* I'm not sure if it's intended or not, but since the countdown time is set when any camera is looked at and it's impossible for Foxy to move from Pirate Cove while the countdown time is greater than 0, viewing any camera keeps Foxy from attacking.
*/
[SerializeField] private float attackDuration = 3f;
private bool isAttacking = false;
private int attackFailCount;
public override void AttackState()
{
state = AIState.Attacking;
//hide model
//somehow show on camera that he is approaching
if(!isAttacking )
{
isAttacking = true;
StartCoroutine(RunTowardsPlayer(attackDuration));
}
}
public override void CheckIfBeingWatched()
{
base.CheckIfBeingWatched();
isBeingWatched = Player.Instance.isInCamera;
}
IEnumerator RunTowardsPlayer(float duration)
{
yield return new WaitForSeconds(duration);
AttackPlayer();
isAttacking = false;
}
public override void AttackFail()
{
base.AttackFail();
int powerDrain = 10 + (attackFailCount * 50);
Player.Instance.powerManager.powerReserve -= powerDrain;
attackFailCount++;
print($"{name} has drained {powerDrain} from the players Power Reserve!");
}
}
}
|
import { css, cx } from "@emotion/css"
import styled from "@emotion/styled"
import Link from "next/link"
import { useTranslation } from "react-i18next"
const StyledBreadcrumb = styled.div`
font-size: 1rem;
margin: 0;
.breadcrumb {
font-size: 16px;
.list {
margin: 0.5rem 0;
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
}
.group {
display: inline-flex;
align-items: center;
}
.arrow {
margin-left: 0.75rem;
color: #333;
}
}
`
const wrapper = css`
padding: 1rem 2rem;
color: #fff;
border-radius: 2px;
&:nth-of-type(n + 2) {
margin-top: 2.5rem;
}
`
const link = css`
color: #696e77;
text-decoration: none !important;
&:hover {
color: #1a2333;
}
`
const breadCrumbText = css`
color: #1a2333;
font-size: 16px;
`
export interface BreakcrumbProps {
pieces: BreadcrumbPiece[]
}
export interface BreadcrumbPiece {
text: string
url: string
externalLink?: boolean
}
const MARKER = "›"
const Breadcrumbs: React.FC<React.PropsWithChildren<React.PropsWithChildren<BreakcrumbProps>>> = ({
pieces,
}) => {
const { t } = useTranslation()
return (
<StyledBreadcrumb>
<div className={cx(wrapper)}>
<nav className="breadcrumb" aria-label={t("breadcrumb")}>
<ol className="list">
{pieces.map((piece, index) => {
const isLast = index === pieces.length - 1
return isLast ? (
<li key={piece.url} className="group">
<span className={cx(breadCrumbText)} aria-current="page">
{piece.text}
</span>
</li>
) : (
<li key={piece.url} className="group">
{piece.externalLink ? (
<a href={piece.url} className={cx(breadCrumbText, link)}>
{piece.text}
</a>
) : (
<Link href={piece.url} className={cx(breadCrumbText, link)}>
{piece.text}
</Link>
)}
<span className="arrow" aria-hidden="true">
{MARKER}
</span>
</li>
)
})}
</ol>
</nav>
</div>
</StyledBreadcrumb>
)
}
export default Breadcrumbs
|
#ifndef CREATURE_HPP
#define CREATURE_HPP
#include <iostream>
#include <string>
#include "point.hpp"
using namespace std;
class Creature{
private:
string name{};
Point location{};
string direction{"right"};
public:
Creature();
Creature(const string& name, const Point& location);
Creature(const string& name, const Point& location, const string& direction);
string get_name() const;
string get_direction() const;
const Point& get_position() const;
void move_to(int new_x, int new_y);
//void set_direction(Direction dir);
void forward(int steps=1);
friend ostream& operator<<(ostream& out, const Creature& p);
};
ostream& operator<<(ostream& out, const Creature& p);
#endif
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id')->references('id')->on('users');
$table->unsignedBigInteger('vehicle_id')->references('id')->on('vehicles');
$table->string('phone_1');
$table->string('phone_2');
$table->string('address_id');
$table->string('address_mlg');
$table->time('pickup_time');
$table->date('pickup_date');
$table->string('pickup_address');
$table->time('dropoff_time');
$table->date('dropoff_date');
$table->string('dropoff_address');
$table->string('id_card');
$table->string('id_card_2');
$table->string('driver_license');
$table->float('total_price', 10, 2);
$table->string('note')->nullable();
$table->enum('order_status', ['PENDING', 'REJECTED', 'WAITING_FOR_PAYMENT', 'PAYMENT_DONE', 'CANCELED', 'COMPLETED']);
$table->string('payment_method')->nullable();
$table->string('transaction_id')->nullable();
$table->string('virtual_account')->nullable();
$table->string('qr_link')->nullable();
$table->string('deep_link')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('orders');
}
};
|
package com.example.roomapp.roomdb
import androidx.room.TypeConverter
import com.example.roomapp.model.Beers
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class BeersTypeConverter {
var gson = Gson()
@TypeConverter
fun beersToString(beers: Beers): String = gson.toJson(beers)
@TypeConverter
fun stringToBeers(data: String): Beers {
val listType = object : TypeToken<Beers>() {}.type
return gson.fromJson(data, listType)
}
}
|
<script setup>
import {CheckIcon, XIcon, QuestionMarkCircleIcon, ClipboardListIcon} from "@heroicons/vue/outline";
import Tooltip from "@/Components/Tooltip.vue";
import Button from "@/Components/Button.vue";
import {ref, watch} from "vue";
import {transactionFormat} from "@/Composables/index.js";
import Modal from "@/Components/Modal.vue";
import InputError from "@/Components/InputError.vue";
import {useForm} from "@inertiajs/vue3";
import Input from "@/Components/Input.vue";
import Label from "@/Components/Label.vue";
import {RadioGroup, RadioGroupLabel, RadioGroupOption} from "@headlessui/vue";
import BaseListbox from "@/Components/BaseListbox.vue";
import CountryLists from "../../../../../public/data/countries.json";
import VueTailwindDatepicker from "vue-tailwind-datepicker";
const props = defineProps({
member: Object,
countries: Array,
nationalities: Array,
})
const formatter = ref({
date: 'YYYY-MM-DD',
month: 'MMM'
})
const kycApprovalModal = ref(false);
const modalComponent = ref('');
const approvalType = ref('');
const selectedCountry = ref(props.member.country.id);
const selectedNationality = ref(props.member.nationality);
const { formatDateTime } = transactionFormat();
const openKycApprovalModal = (ibId, componentType) => {
kycApprovalModal.value = true;
if (componentType === 'approve') {
approvalType.value = 'approve'
modalComponent.value = 'Approve KYC';
} else if (componentType === 'reject') {
approvalType.value = 'reject'
modalComponent.value = 'Reject KYC';
} else if (componentType === 'view') {
modalComponent.value = 'KYC Details';
}
}
const form = useForm({
id: props.member.id,
type: '',
remark: '',
});
const genders = [
{
name: 'male',
value: 'male',
},
{
name: 'female',
value: 'female',
},
]
const getUserGender = (user_gender) => {
return genders.find(gender => gender.value === user_gender);
}
const selected = ref(getUserGender(props.member.gender));
watch(selectedCountry, (newCountry) => {
const foundNationality = props.nationalities.find(nationality => nationality.id === newCountry);
if (foundNationality) {
selectedNationality.value = foundNationality.value;
} else {
selectedNationality.value = null; // Reset if not found
}
})
const closeModal = () => {
kycApprovalModal.value = false
modalComponent.value = null;
}
const submitForm = () => {
form.type = approvalType.value;
form.post(route('member.verify_member'), {
onSuccess: () => {
closeModal();
form.reset();
},
});
}
const userForm = useForm({
user_id: props.member.id,
name: props.member.name,
username: props.member.username,
email: props.member.email,
dob: props.member.dob,
dial_code: props.member.dial_code,
phone: props.member.phone,
gender: props.member.gender,
address: props.member.address_1,
country: '',
nationality: '',
identification_number: props.member.identification_number,
});
const handleButton = (type) => {
userForm.gender = selected.value ? selected.value.value : null;
userForm.country = selectedCountry.value;
userForm.nationality = selectedNationality.value;
userForm.post(route('member.validateKyc'), {
onSuccess: () => {
// If form submission is successful
if (type === 'reject') {
approvalType.value = 'reject';
modalComponent.value = 'Reject KYC';
} else if (type === 'approve') {
approvalType.value = 'approve';
modalComponent.value = 'Approve KYC';
}
},
});
};
</script>
<template>
<div class="inline-flex justify-center items-center gap-2">
<Tooltip content="Approve" placement="bottom">
<Button
type="button"
pill
class="justify-center px-4 pt-2 mx-1 w-8 h-8 focus:outline-none"
variant="success"
@click="openKycApprovalModal(member.id, 'approve')"
>
<CheckIcon aria-hidden="true" class="w-6 h-6 absolute" />
<span class="sr-only">View</span>
</Button>
</Tooltip>
<Tooltip content="Reject" placement="bottom">
<Button
type="button"
pill
class="justify-center px-4 pt-2 mx-1 w-8 h-8 focus:outline-none"
variant="danger"
@click="openKycApprovalModal(member.id, 'reject')"
>
<XIcon aria-hidden="true" class="w-6 h-6 absolute" />
<span class="sr-only">Transfer Upline</span>
</Button>
</Tooltip>
<Tooltip content="View" placement="bottom">
<Button
type="button"
pill
class="justify-center px-4 pt-2 mx-1 w-8 h-8 focus:outline-none"
variant="gray"
@click="openKycApprovalModal(member.id, 'view')"
>
<ClipboardListIcon aria-hidden="true" class="w-6 h-6 absolute" />
<span class="sr-only">Reset</span>
</Button>
</Tooltip>
</div>
<Modal :show="kycApprovalModal" :title="modalComponent" @close="closeModal" :max-width="modalComponent === 'KYC Details' ? '4xl' : 'lg'">
<div v-if="modalComponent === 'Approve KYC'">
<div class="px-2 space-y-2">
<div class="flex justify-center">
<div class="flex items-center justify-center rounded-full w-14 h-14 grow-0 shrink-0 bg-warning-300">
<QuestionMarkCircleIcon class="w-14 text-white" />
</div>
</div>
<h2 class="text-xl font-semibold dark:text-white pt-5">Approve KYC</h2>
<div class="text-sm font-normal dark:text-gray-400">
Do you want to approve KYC and verify this member?
</div>
</div>
<div class="pt-5 px-2 grid grid-cols-2 gap-4">
<Button type="button" variant="secondary" class="px-6 justify-center" @click="closeModal">
Cancel
</Button>
<Button class="px-6 justify-center" @click.prevent="submitForm">Confirm</Button>
</div>
</div>
<!-- Reject -->
<div v-if="modalComponent === 'Reject KYC'">
<div class="flex gap-2 mt-3 mb-8">
<Label class="text-sm dark:text-white w-1/4 pt-0.5" for="remark" value="Remark" />
<div class="flex flex-col w-full">
<Input
id="remark"
type="text"
placeholder="Enter remark (visible to member)"
class="block w-full"
:class="form.errors.remark ? 'border border-error-500 dark:border-error-500' : 'border border-gray-400 dark:border-gray-600'"
v-model="form.remark"
/>
<InputError :message="form.errors.remark" class="mt-2" />
</div>
</div>
<div class="pt-5 px-2 grid grid-cols-2 gap-4 border-t dark:border-gray-700">
<Button type="button" variant="secondary" class="px-6 justify-center" @click="closeModal">
Cancel
</Button>
<Button class="px-6 justify-center" @click.prevent="submitForm">Confirm</Button>
</div>
</div>
<!-- View -->
<div v-if="modalComponent === 'KYC Details'">
<div class="flex justify-center">
<img :src="member.profile_photo_url ? member.profile_photo_url : 'https://img.freepik.com/free-icon/user_318-159711.jpg'" class="w-20 h-20 rounded-full" alt="">
</div>
<div class="py-8">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-1.5">
<Label for="name" :value="$t('public.name')" />
<Input
id="name"
type="text"
class="block w-full"
v-model="userForm.name"
autofocus
autocomplete="name"
/>
<InputError class="mt-2" :message="userForm.errors.name" />
</div>
<div class="space-y-1.5">
<Label for="username" :value="$t('public.username')" />
<Input
id="username"
type="text"
class="block w-full"
v-model="userForm.username"
autofocus
autocomplete="username"
/>
<InputError class="mt-2" :message="userForm.errors.username" />
</div>
<div class="space-y-1.5">
<Label for="email" :value="$t('public.email')" />
<Input
id="email"
type="email"
class="block w-full"
v-model="userForm.email"
autocomplete="email"
/>
<InputError class="mt-2" :message="userForm.errors.email" />
</div>
<div class="space-y-1.5">
<Label
for="phone"
:value="$t('public.mobile_phone')"
/>
<div class="flex gap-3">
<BaseListbox
class="w-[240px]"
:options="CountryLists"
v-model="userForm.dial_code"
with-img
is-phone-code
:error="!!userForm.errors.phone"
/>
<Input
id="phone"
type="text"
class="block w-full"
:placeholder="$t('public.phone_placeholder')"
v-model="userForm.phone"
:invalid="userForm.errors.phone"
/>
</div>
<InputError :message="userForm.errors.phone"/>
</div>
<div class="space-y-1.5">
<Label class="text-sm dark:text-white" for="dob" value="Date of Birth" />
<div class="md:col-span-3">
<vue-tailwind-datepicker
input-classes="py-2.5 w-full rounded-lg dark:placeholder:text-gray-500 focus:ring-primary-400 hover:border-primary-400 focus:border-primary-400 dark:focus:ring-primary-500 dark:hover:border-primary-500 dark:focus:border-primary-500 bg-white dark:bg-gray-800 dark:text-white border border-gray-300 dark:border-gray-800" v-model="userForm.dob"
as-single
:formatter="formatter"
/>
</div>
</div>
<div class="space-y-1.5">
<Label
for="gender"
:value="$t('public.gender')"
/>
<RadioGroup v-model="selected">
<RadioGroupLabel class="sr-only">{{ $t('public.signal_status') }}</RadioGroupLabel>
<div class="flex gap-3 items-center self-stretch w-full">
<RadioGroupOption
as="template"
v-for="(gender, index) in genders"
:key="index"
:value="gender"
v-slot="{ active, checked }"
>
<div
:class="[
active
? 'ring-0 ring-white ring-offset-0'
: '',
checked ? 'border-gray-400 dark:border-white bg-gray-500 dark:bg-gray-600 text-white' : 'border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 dark:text-white',
]"
class="relative flex cursor-pointer rounded-xl border p-3 focus:outline-none w-full"
>
<div class="flex items-center w-full">
<div class="text-sm flex flex-col gap-3 w-full">
<RadioGroupLabel
as="div"
class="font-medium"
>
<div class="flex justify-center items-center gap-3">
{{ $t('public.' + gender.name) }}
</div>
</RadioGroupLabel>
</div>
</div>
</div>
</RadioGroupOption>
</div>
<InputError :message="userForm.errors.gender" class="mt-2" />
</RadioGroup>
</div>
<div class="space-y-1.5">
<Label
for="country"
:value="$t('public.country')"
/>
<BaseListbox
v-model="selectedCountry"
:options="countries"
:placeholder="$t('public.country')"
class="w-full"
:error="!!userForm.errors.country"
/>
<InputError class="mt-2" :message="userForm.errors.country" />
</div>
<div class="space-y-1.5">
<Label
for="nationality"
:value="$t('public.nationality')"
/>
<BaseListbox
v-model="selectedNationality"
:options="nationalities"
:placeholder="$t('public.nationality')"
class="w-full"
:error="!!userForm.errors.nationality"
/>
<InputError class="mt-2" :message="userForm.errors.nationality" />
</div>
<div class="space-y-1.5">
<Label for="address" :value="$t('public.address')" />
<Input
id="address"
type="text"
class="block w-full"
v-model="userForm.address"
autocomplete="address"
:invalid="userForm.errors.address"
/>
<InputError class="mt-2" :message="userForm.errors.address" />
</div>
<div class="space-y-1.5">
<Label for="identification_number" :value="$t('public.identification_no')" />
<Input
id="identification_number"
type="text"
class="block w-full"
v-model="userForm.identification_number"
:invalid="userForm.errors.identification_number"
/>
<InputError class="mt-2" :message="userForm.errors.identification_number" />
</div>
<div class="flex flex-col gap-2">
<div class="text-sm text-left w-full dark:text-white">
Proof of Identity (FRONT)
</div>
<div class="p-2 dark:bg-white rounded-lg w-full flex justify-center border dark:border-white">
<img :src="member.front_identity" class="max-h-64 rounded-lg" alt="">
</div>
</div>
<div class="flex flex-col gap-2">
<div class="text-sm text-left w-full dark:text-white">
Proof of Identity (BACK)
</div>
<div class="p-2 dark:bg-white rounded-lg w-full flex justify-center border dark:border-white">
<img :src="member.back_identity" class="max-h-64 rounded-lg" alt="">
</div>
</div>
</div>
</div>
<div class="pt-8 border-t dark:border-gray-700">
<div class="flex justify-end gap-3">
<Button
type="button"
variant="danger"
class="flex justify-center px-6"
@click="handleButton('reject')"
>
Reject
</Button>
<Button
type="button"
variant="success"
class="flex justify-center px-6"
@click="handleButton('approve')"
>
Approve KYC
</Button>
</div>
</div>
</div>
</Modal>
</template>
|
function toggleThemeMenu() {
let themeMenu = document.querySelector('.bd-mode-toggle');
if (!themeMenu) return;
// Check local storage for the selected theme and apply it
const selectedTheme = localStorage.getItem('selectedTheme');
if (selectedTheme) {
const container = document.querySelector('.wrapcontent');
container.setAttribute('data-bs-theme', selectedTheme);
const themeIcons = {
light: 'sun-fill',
dark: 'moon-stars-fill',
auto: 'circle-half'
};
const themeToggle = document.querySelector('.theme-icon-active use');
themeToggle.setAttribute('href', `#${themeIcons[selectedTheme]}`);
// Remove the active class from all theme buttons
document.querySelectorAll('[data-bs-theme-value]').forEach(value => {
value.classList.remove('active');
});
// Add the active class to the selected theme button
const activeThemeButton = document.querySelector(`[data-bs-theme-value="${selectedTheme}"]`);
if (activeThemeButton) {
activeThemeButton.classList.add('active');
}
}
document.querySelectorAll('[data-bs-theme-value]').forEach(value => {
value.addEventListener('click', () => {
const theme = value.getAttribute('data-bs-theme-value');
const container = document.querySelector('.wrapcontent');
container.setAttribute('data-bs-theme', theme);
// Update the theme icon in the dropdown
const themeToggle = document.querySelector('.theme-icon-active use');
const themeIcons = {
light: 'sun-fill',
dark: 'moon-stars-fill',
auto: 'circle-half'
};
themeToggle.setAttribute('href', `#${themeIcons[theme]}`);
// Remove the active class from all theme buttons
document.querySelectorAll('[data-bs-theme-value]').forEach(button => {
button.classList.remove('active');
});
// Add the active class to the clicked theme button
value.classList.add('active');
localStorage.setItem('selectedTheme', theme);
});
});
}
toggleThemeMenu();
var weight, height, measure, bmi, error ;
function calculate() {
weight = document.getElementById("weight").value;
height = document.getElementById("height").value;
error = "Please enter some values";
height /= 100;
height *= height;
bmi = weight/height;
bmi = bmi.toFixed(1);
if (bmi <= 18.4) {
measure = "Your BMI is " + bmi + " which means " + "you are Underweight";
} else if (bmi >= 18.5 && bmi <= 24.9) {
measure = "Your BMI is " + bmi + " which means " + "You are Normal";
} else if (bmi >= 25 && bmi <= 29.9) {
measure = "Your BMI is " + bmi + " which means " + "You are Overweight";
} else if (bmi >= 30) {
measure = "Your BMI is " + bmi + " which means " + "You are Obese";
}
if (weight === 0 ) {
document.getElementById("results").innerHTML = error;
} else if (height === 0){
document.getElementById("results").innerHTML = error;
}
else {
document.getElementById("results").innerHTML = measure;
}
if (weight < 0) {
document.getElementById("results").innerHTML = "Negative Values not Allowed";
}
}
var numP = 100; // Increase the number of particles
for (var i = 1; i < numP; i++) {
var _p = document.getElementById('p0').cloneNode(false);
_p.id = "p" + i;
document.getElementById('particles').appendChild(_p);
gsap.set(_p, { scale: 0.1 + 1.0 * Math.random(), alpha: 0.25 + Math.random(), x: window.innerWidth * Math.random(), y: window.innerHeight * Math.random() });
}
var mouseX = 0;
var mouseY = 0;
var isMouseMoving = false; // Add a flag to track mouse movement
function handleMouseMove(e) {
mouseX = e.clientX || e.touches[0].clientX; // Use touch coordinates for mobile
mouseY = e.clientY || e.touches[0].clientY;
isMouseMoving = true; // Set the flag to true when there's movement
}
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('touchmove', handleMouseMove);
function animateParticles() {
if (!isMouseMoving) {
return; // Don't animate if the mouse is not moving
}
for (var ii = 1; ii < numP; ii++) {
gsap.to('#p' + ii, 0.5, {
delay: 0.005 * ii,
x: mouseX + 25 - 50 * Math.random(),
y: mouseY + 25 - 50 * Math.random(),
ease: Back.easeOut.config(3)
});
gsap.to('#p' + ii, 0.005 * ii, { scale: 1 }); // Adjust the scale for smaller particles
gsap.to('#p' + ii, 0.5, { delay: 0.005 * ii, scale: 0 });
}
isMouseMoving = false; // Reset the flag after the animations are applied
}
gsap.ticker.add(animateParticles);
|
<template>
<div class="page no-tabbar" data-name="chat">
<div class="navbar">
<div class="navbar-bg"></div>
<div class="navbar-inner">
<div class="left">
<a href="#" class="link back">
<i class="icon icon-back"></i>
<span class="if-not-md">Back</span>
</a>
</div>
<div class="title">
<div>${faker.name.firstName() + ' ' + faker.name.lastName()}</div>
<div class="subtitle">Online</div>
</div>
<div class="right">
<img class="avatar shape-circle" src="${faker.internet.avatar()}" height="40" width="40" alt="" />
</div>
</div>
</div>
<div class="toolbar messagebar">
<div class="toolbar-inner">
<a href="#" class="link ripple-color-gray" @click="${openAttachmentActions}">
<i class="icon f7-icons if-not-md">paperclip</i>
<i class="icon material-icons if-md">attach_file</i>
</a>
<div class="messagebar-area">
<textarea placeholder="Message"></textarea>
</div>
<a href="#" class="link ripple-color-gray" @click="${sendMessage}">
<i class="icon f7-icons if-not-md">paperplane</i>
<i class="icon material-icons if-md">send</i>
</a>
</div>
</div>
<div class="page-content messages-content">
<div class="messages">
<div class="messages-title">
<span class="badge badge-fade badge-round no-margin">January 01, 2023</span>
</div>
<div class="message message-sent">
<div class="message-content">
<div class="message-bubble">
<div class="message-text">Hi, Jane</div>
<div class="message-text-footer">1:00 PM</div>
</div>
</div>
</div>
<div class="message message-sent">
<div class="message-content">
<div class="message-bubble">
<div class="message-text">How are you?</div>
<div class="message-text-footer">1:01 PM</div>
</div>
</div>
</div>
<div class="message message-received">
<div class="message-avatar">
<img class="shape-circle" src="https://source.unsplash.com/jzY0KRJopEI/128x128" alt="" />
</div>
<div class="message-content">
<div class="message-name">Jane</div>
<div class="message-bubble">
<div class="message-text">Hi, I am fine.</div>
<div class="message-text-footer">3:14 PM</div>
</div>
</div>
</div>
<div class="message message-received">
<div class="message-avatar">
<img class="shape-circle" src="https://source.unsplash.com/jzY0KRJopEI/128x128" alt="" />
</div>
<div class="message-content">
<div class="message-name">Jane</div>
<div class="message-bubble">
<div class="message-text">How are you?</div>
<div class="message-text-footer">3:15 PM</div>
</div>
</div>
</div>
<div class="message message-sent">
<div class="message-content">
<div class="message-bubble">
<div class="message-text">I am fine too.</div>
<div class="message-text-footer">5:47 PM</div>
</div>
</div>
</div>
<div class="messages-title">
<span class="badge badge-fade badge-round no-margin">Yesterday</span>
</div>
<div class="message message-sent">
<div class="message-content">
<div class="message-bubble">
<div class="message-image">
<img src="https://source.unsplash.com/Hs4dGxnCRxU" alt="" />
</div>
<div class="message-text">Look at this cutest puppy ever!</div>
<div class="message-text-footer">7:15 AM</div>
</div>
</div>
</div>
<div class="messages-title">
<span class="badge badge-fade badge-round no-margin">Today</span>
</div>
<div class="message message-received">
<div class="message-avatar">
<img class="shape-circle" src="https://source.unsplash.com/jzY0KRJopEI/128x128" alt="" />
</div>
<div class="message-content">
<div class="message-name">Jane</div>
<div class="message-bubble">
<div class="message-text">That's beautiful</div>
<div class="message-text-footer">6:05 AM</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default function(props, {$, $el, $f7, $f7route, $f7router, $h, $on, $store, $theme, $update}) {
let messagebar = null;
let messages = null;
let initializeMessagebar = function() {
messagebar = $f7.messagebar.create({
el: $el.value.find('.messagebar'),
textareaEl: $el.value.find('.messagebar textarea')
});
}
let initializeMessages = function() {
messages = $f7.messages.create({
el: $el.value.find('.messages'),
scrollMessages: true,
scrollMessagesOnEdge: false,
firstMessageRule: function(message, previousMessage, nextMessage) {
if (message.isTitle) {
return false;
}
if (!previousMessage || previousMessage.type !== message.type || previousMessage.name !== message.name) {
return true;
}
return false;
},
lastMessageRule: function(message, previousMessage, nextMessage) {
if (message.isTitle) {
return false;
}
if (!nextMessage || nextMessage.type !== message.type || nextMessage.name !== message.name) {
return true;
}
return false;
},
tailMessageRule: function(message, previousMessage, nextMessage) {
if (message.isTitle) {
return false;
}
if (!nextMessage || nextMessage.type !== message.type || nextMessage.name !== message.name) {
return true;
}
return false;
}
});
}
let sendMessage = function() {
let text = messagebar.getValue().replace(/\n/g, '<br/>').trim();
if (text.length) {
messages.addMessage({
text: text,
textFooter: moment().format('h:m A'),
type: 'sent'
});
messagebar.clear();
messagebar.focus();
receiveMessage();
}
}
let receiveMessage = function() {
let replies = ['Amazing', 'Are you sure?', 'I am not sure.', 'I need to think about it.', 'Of course', 'What?'];
let reply = replies.random();
setTimeout(function() {
messages.showTyping({
name: 'Jane',
avatar: 'https://source.unsplash.com/jzY0KRJopEI/128x128'
});
setTimeout(function() {
messages.addMessage({
name: 'Jane',
avatar: 'https://source.unsplash.com/jzY0KRJopEI/128x128',
text: reply,
textFooter: moment().format('h:m A'),
type: 'received'
});
messages.hideTyping();
}, 3000);
}, 2000);
}
let openAttachmentActions = function() {
let actions = $f7.actions.create({
grid: true,
buttons: [
[
{
icon: '<span class="shape-container shape-circle size-48 bg-color-pink"><i class="icon fa-solid fa-camera color-white"></i></span>',
text: 'Photo'
},
{
icon: '<span class="shape-container shape-circle size-48 bg-color-green"><i class="icon fa-solid fa-video color-white"></i></span>',
text: 'Video'
},
{
icon: '<span class="shape-container shape-circle size-48 bg-color-blue"><i class="icon fa-solid fa-microphone color-white"></i></span>',
text: 'Audio'
},
{
icon: '<span class="shape-container shape-circle size-48 bg-color-teal"><i class="icon fa-solid fa-map-marker-alt color-white"></i></span>',
text: 'Location'
},
{
icon: '<span class="shape-container shape-circle size-48 bg-color-purple"><i class="icon fa-solid fa-address-card color-white"></i></span>',
text: 'Contact'
},
{
icon: '<span class="shape-container shape-circle size-48 bg-color-amber"><i class="icon fa-solid fa-file-alt color-white"></i></span>',
text: 'Document'
}
]
]
});
actions.open();
}
$on('pageBeforeIn', function() {
initializeMessagebar();
initializeMessages();
});
return $render;
}
</script>
|
import React, { useState } from 'react';
import {
Box,
Typography,
TextField,
Button,
Divider,
FormControl,
InputAdornment,
IconButton,
Paper,
Avatar,
Grid,
Fade
} from '@mui/material';
import { useTranslation } from "react-i18next";
import { useFormik } from 'formik';
import { get, words, map, join, upperCase, slice } from "lodash";
import { Visibility, VisibilityOff } from '@mui/icons-material';
import LockOpenIcon from '@mui/icons-material/LockOpen';
import LockIcon from '@mui/icons-material/Lock';
import { useDispatch, useSelector } from "react-redux";
import { LoadingButton } from '@mui/lab';
import CloseSession from "../../../assets/icons/CloseSession"
import Layout from "../../../components/layout/Layout";
import validator from "./validator";
import Notification from "../../../components/form/Notification";
import BtnLanguage from "../../../components/form/BtnLanguage";
import Alert from "../../../components/form/Alert";
import { logout } from "../../../store/auth/thunk/logout";
import { putProfileRequest } from "../../../store/auth/actions/putProfile";
const Profile = () => {
const dispatch = useDispatch();
const [__, i18n] = useTranslation("auth");
const [showPass, setShowPass] = useState(false);
const [isEdit, setIsEdit] = useState(false);
const [loadingEdit, setLoadingEdit] = useState(false);
const [showNoti, setShowNoti] = useState({ open: false, msg: "", variant: "" });
const [alert, setAlert] = useState({ open: false, title: "", subtitle: "", type: "" })
const dataUser = useSelector(state => state.auth.login.dataUser);
const getState = useSelector(state => state);
const module = "profile"
const inputs = __(`${module}.input`, { returnObjects: true })
const sections = __(`${module}.section`, { returnObjects: true })
const handleClickShowPassword = () => {
setShowPass(state => !state)
}
const onHeadBtn = (lang) => {
let selectLanguage = lang;
i18n.changeLanguage(selectLanguage);
localStorage.setItem("lang", selectLanguage)
}
const closeAlert = () => {
setAlert({ open: false, title: "", subtitle: "", type: "", btn: "" })
}
const setError = (err) => {
if (!!get(err, "response.data") && (get(err, "response.status") !== 500)) {
setAlert({
open: true,
title: get(err, "response.data.Message", ""),
subtitle: (<ul>{map(get(err, "response.data.ValidationError", []), (item) => <li>{`• ${item}`}</li>)}</ul>),
type: "error",
btn: __(`${module}.actions.close`),
func: closeAlert
})
} else {
setShowNoti({ open: true, msg: get(err, "message"), variant: "error" })
}
}
const formik = useFormik({
initialValues: {
name: get(dataUser, "username"),
// phone: get(dataUser, "phone"),
email: get(dataUser, "email"),
company: get(dataUser, "companyname"),
password: "",
confirmation: "",
},
validationSchema: validator(inputs),
onSubmit: (values) => {
const body = {
companyid: Number(get(dataUser, "companyId")),
// phone: get(values, "phone"),
username: get(values, "name"),
language: i18n.resolvedLanguage,
userid: get(dataUser, "userId"),
...(!!get(values, "password") && { pass: get(values, "password") }),
}
if (isEdit) {
setLoadingEdit(true)
putProfileRequest(body, () => getState)
.then(({ data }) => {
setShowNoti({ open: true, msg: __(`${module}.msg.update`), variant: "success" })
setLoadingEdit(false)
})
.catch((err) => { setError(err); setLoadingEdit(false) })
}
}
});
const onEdit = () => {
if (!isEdit) {
setIsEdit(true)
}
}
const onLogout = () => {
const body = {
companyid: Number(get(dataUser, "companyId")),
userid: get(dataUser, "userId"),
language: localStorage.getItem("lang"),
}
dispatch(logout(body))
}
const short = (text) => {
return (upperCase(join(slice(map(words(text), (w) => get(w, "[0]")), 0, 2), "")))
}
return (
<Layout propsToolbar={{ customBtn: <BtnLanguage active={i18n.resolvedLanguage} onClickEn={onHeadBtn} onClickEs={onHeadBtn} /> }} >
<Box>
<Paper className='flex justify-between items-center py-6 px-8 w-full mb-6' elevation={3} >
<Box className='flex'>
<Avatar alt={short(get(dataUser, "username"))} src={"/"} sx={{ height: 80, width: 80 }} >{short(get(dataUser, "username"))}</Avatar>
<Box className='pl-8'>
<Typography variant="buttonXtra">{get(dataUser, "username", "- -")}</Typography>
<Box className='flex'>
<Typography variant="bodyLarge">{get(dataUser, "email", "- -")}</Typography>
<Typography className='px-2' variant="bodyLarge" color="text.slite">|</Typography>
<Typography variant="bodyLarge">{get(dataUser, "companyname", "- -")}</Typography>
</Box>
</Box>
</Box>
<Button color="primary" startIcon={<CloseSession />} onClick={onLogout}>
<Typography variant="buttonMedium" >{__(`${module}.button.logout`)}</Typography>
</Button>
</Paper>
<Paper className='w-full mb-8' elevation={3} >
<Box component="form" onSubmit={get(formik, "handleSubmit")}>
<Box className='py-6 px-8 w-full'>
<Typography className='pb-4' component={Box} variant="buttonXtra">{__(`${module}.title`)}</Typography>
<Typography className='py-3' component={Box} variant="bodySmall">{get(sections, "[0]")}</Typography>
<Divider />
<Grid className='pt-4' container spacing={3}>
<Grid item xs={6} md={6}>
<Box className='mb-8'>
<FormControl fullWidth >
<Typography className='pb-2' component="label" htmlFor="email" >
{get(inputs, "[2].name")}
</Typography>
<TextField
fullWidth
id="email"
name="email"
placeholder={get(inputs, "[2].placeholder")}
value={get(formik, "values.email")}
onChange={get(formik, "handleChange")}
error={get(formik, "touched.email") && Boolean(get(formik, "errors.email"))}
helperText={get(formik, "touched.email") && get(formik, "errors.email")}
// disabled={!isEdit}
disabled={true}
/>
</FormControl>
</Box>
</Grid>
<Grid item xs={6} md={6}>
<Box className='mb-8'>
<FormControl fullWidth >
<Typography className='pb-2' component="label" htmlFor="name" >
{get(inputs, "[0].name")}
</Typography>
<TextField
fullWidth
id="name"
name="name"
placeholder={get(inputs, "[0].placeholder")}
value={get(formik, "values.name")}
onChange={get(formik, "handleChange")}
error={get(formik, "touched.name") && Boolean(get(formik, "errors.name"))}
helperText={get(formik, "touched.name") && get(formik, "errors.name")}
disabled={!isEdit}
/>
</FormControl>
</Box>
</Grid>
{/* <Grid item xs={6} md={4}>
<Box className='mb-8'>
<FormControl fullWidth >
<Typography className='pb-2' component="label" htmlFor="phone" >
{get(inputs, "[5].name")}
</Typography>
<TextField
fullWidth
id="phone"
name="phone"
placeholder={get(inputs, "[5].placeholder")}
value={get(formik, "values.phone")}
onChange={get(formik, "handleChange")}
error={get(formik, "touched.phone") && Boolean(get(formik, "errors.phone"))}
helperText={get(formik, "touched.phone") && get(formik, "errors.phone")}
disabled={!isEdit}
/>
</FormControl>
</Box>
</Grid> */}
</Grid>
<Typography className='py-3' component={Box} variant="bodySmall">{get(sections, "[1]")}</Typography>
<Divider />
<Grid className='pt-4' container spacing={3}>
<Grid item xs={6} md={4}>
<Box className='mb-8'>
<FormControl fullWidth >
<Typography className='pb-2' component="label" htmlFor="company" >
{get(inputs, "[1].name")}
</Typography>
<TextField
fullWidth
id="company"
name="company"
placeholder={get(inputs, "[1].placeholder")}
value={get(formik, "values.company")}
onChange={get(formik, "handleChange")}
error={get(formik, "touched.company") && Boolean(get(formik, "errors.company"))}
helperText={get(formik, "touched.company") && get(formik, "errors.company")}
// disabled={!isEdit}
disabled={true}
/>
</FormControl>
</Box>
</Grid>
</Grid>
<Typography className='py-3' component={Box} variant="bodySmall">{get(sections, "[2]")}</Typography>
<Divider />
<Grid className='pt-4' container spacing={3}>
<Grid item xs={6} md={4}>
<Box className='mb-8'>
<FormControl fullWidth >
<Typography className='pb-2' component="label" htmlFor="password" >
{get(inputs, "[3].name")}
</Typography>
<TextField
id="password"
name="password"
placeholder={get(inputs, "[3].placeholder")}
type={showPass ? 'text' : 'password'}
value={get(formik, "values.password")}
onChange={get(formik, "handleChange")}
error={get(formik, "touched.password") && Boolean(get(formik, "errors.password"))}
helperText={get(formik, "touched.password") && get(formik, "errors.password")}
disabled={!isEdit}
InputProps={{
autoComplete: 'new-password',
endAdornment:
<InputAdornment position="end" className='mr-2'>
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
edge="end"
disabled={!isEdit}
>
{showPass ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}}
/>
</FormControl>
</Box>
</Grid>
<Grid item xs={6} md={4}>
<Fade in={isEdit}>
<Box className='mb-8'>
<FormControl fullWidth >
<Typography className='pb-2' component="label" htmlFor="password" >
{get(inputs, "[4].name")}
</Typography>
<TextField
id="confirmation"
name="confirmation"
placeholder={get(inputs, "[4].placeholder")}
type={showPass ? 'text' : 'password'}
value={get(formik, "values.confirmation")}
onChange={get(formik, "handleChange")}
error={get(formik, "touched.confirmation") && Boolean(get(formik, "errors.confirmation"))}
helperText={get(formik, "touched.confirmation") && get(formik, "errors.confirmation")}
InputProps={{
autoComplete: 'new-password',
endAdornment:
<InputAdornment position="end" className='mr-2'>
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
onMouseDown={handleClickShowPassword}
edge="end"
disabled={!isEdit}
>
{showPass ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}}
/>
</FormControl>
</Box>
</Fade>
</Grid>
</Grid>
</Box>
<Divider />
<Box className='p-10 w-full flex justify-end'>
<Fade in={isEdit}>
<Box className='mr-6'>
<Button
variant="text"
type="button"
size='large'
onClick={() => setIsEdit(false)}
sx={{ color: "text.main" }}
>
{__(`${module}.button.cancel`)}
</Button>
</Box>
</Fade>
{isEdit
? (
<LoadingButton
color={"success"}
variant="contained"
type="submit"
size='large'
startIcon={<LockOpenIcon />}
loading={loadingEdit}
>
{__(`${module}.button.is-edit`)}
</LoadingButton>
) : (
<Button
color={"primary"}
variant="contained"
type="button"
onClick={onEdit}
size='large'
startIcon={<LockIcon />}
>
{__(`${module}.button.name`)}
</Button>
)}
</Box>
</Box>
</Paper>
<Notification showNoti={showNoti} setShowNoti={setShowNoti} />
<Alert
title={get(alert, "title")}
subtitle={get(alert, "subtitle")}
btn1={{ label: get(alert, "btn"), func: get(alert, "func") }}
btn2={{ label: get(alert, "btn2", ""), func: get(alert, "func2", () => { }) }}
type={get(alert, "type")}
openAlert={get(alert, "open")}
closeAlert={closeAlert}
/>
</Box >
</Layout >
)
}
export default Profile
|
<div class="main-container" [class.main-is-mobile]="mobileQuery.matches">
<mat-toolbar color="primary" class="main-toolbar">
<button mat-icon-button (click)="snav.toggle()" [disabled]="!authService.IsAuthenticated()">
<mat-icon svgIcon="menu"></mat-icon>
</button>
<span class="fill-space"></span>
<div>
<span *ngIf="authService.IsAuthenticated()">Welcome {{authService.CurrentUser()}}</span>
<!-- <span *ngIf="!authService.IsAuthenticated()">
<a mat-list-item routerLink="">Login</a>
</span> -->
<button mat-icon-button [matMenuTriggerFor]="menu" [disabled]="!authService.IsAuthenticated()">
<mat-icon svgIcon="user"></mat-icon>
</button>
<mat-menu #menu="matMenu">
<button mat-menu-item *ngIf="authService.IsAuthenticated()" routerLink="/manage-user">
<mat-icon svgIcon="profile"></mat-icon>
<span>User Management</span>
</button>
<button mat-menu-item *ngIf="authService.IsAuthenticated()" routerLink="/manage-role">
<mat-icon svgIcon="settings"></mat-icon>
<span>Role Management</span>
</button>
<button mat-menu-item disabled>
<mat-icon svgIcon="notification-active"></mat-icon>
<span>Notification</span>
</button>
<button mat-menu-item *ngIf="authService.IsAuthenticated()" (click)="LogOut()">
<mat-icon svgIcon="logout"></mat-icon>
<span>Logout</span>
</button>
</mat-menu>
</div>
</mat-toolbar>
<mat-sidenav-container class="main-sidenav-container" [style.marginTop.px]="mobileQuery.matches ? 56 : 0">
<!-- <mat-sidenav #snav [mode]="mobileQuery.matches ? 'over' : 'side'" -->
<mat-sidenav #snav mode="over" [fixedInViewport]="mobileQuery.matches" fixedTopGap="56">
<mat-nav-list>
<mat-list-item *ngFor="let routes of permittedRoutes">
<a [routerLink]="routes.entitypath">{{routes.displayname}}</a>
</mat-list-item>
</mat-nav-list>
<!-- <mat-nav-list>
<mat-list-item *ngFor="let link of links">
<a matLine href="...">{{ link }}</a>
<button mat-icon-button (click)="showInfo(link)">
<mat-icon>info</mat-icon>
</button>
</mat-list-item>
</mat-nav-list> -->
</mat-sidenav>
<mat-sidenav-content>
<router-outlet></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
</div>
|
import random
class Player:
def __init__(self, name, dealer):
self.name=name
self.dealer=dealer
self.win=0
self.loss=0
self.tie=0
self.hand=[]
def decide_hit(self):
# DO NOT MODIFY
return random.choice([True, True, False])
def deal_to(self,card_value):
"""
>>> player = Player(None, None)
>>> player.deal_to(11)
>>> player.hand
[11]
>>> player.deal_to(10)
>>> player.hand
[11, 10]
"""
self.hand.append(card_value)
@property
def card_sum(self):
"""
>>> player = Player(None, None)
>>> player.deal_to(2)
>>> player.card_sum
2
>>> player.deal_to(10)
>>> player.card_sum
12
"""
sum1=0
for i in self.hand:
sum1+=i
return sum1
def play_round(self):
"""
>>> from dealer import Dealer
>>> import random; random.seed(1)
>>> dealer = Dealer()
>>> dealer.shuffle_deck()
>>> player = Player(None, dealer)
We see that after the first call the play_round, we have only hit once as dictated by decide_hit
>>> player.play_round()
>>> player.hand
[10]
After calling play_round again, decide_hit has decided to stand
>>> player.play_round()
>>> player.hand
[10]
After a third call to play_round, we've decided to hit, but busted!
>>> player.play_round()
>>> player.hand
[10, 8, 10]
After a final call to play_round, our hand shouldn't change since we've already busted
>>> player.play_round()
>>> player.hand
[10, 8, 10]
"""
count=self.decide_hit()
while count!=False and self.card_sum<21:
self.dealer.signal_hit(self)#ask the professor
count=self.decide_hit()
def discard_hand(self):
"""
>>> player = Player(None, None)
>>> player.deal_to(11)
>>> player.deal_to(5)
>>> player.discard_hand()
>>> player.hand
[]
"""
self.hand.clear()
@property
def wins(self):
return self.win
@property
def ties(self):
return self.tie
@property
def losses(self):
return self.loss
def record_win(self):
"""
>>> player = Player(None, None)
>>> player.record_win()
>>> player.wins
1
"""
self.win+=1
def record_loss(self):
"""
>>> player = Player(None, None)
>>> player.record_loss()
>>> player.losses
1
"""
self.loss+=1
def record_tie(self):
"""
>>> player = Player(None, None)
>>> player.record_tie()
>>> player.ties
1
"""
self.tie+=1
def reset_stats(self):
"""
>>> player = Player(None, None)
>>> player.record_tie()
>>> player.record_loss()
>>> player.record_win()
>>> player.reset_stats()
>>> player.ties
0
>>> player.wins
0
>>> player.losses
0
"""
self.tie=0
self.win=0
self.loss=0
def __repr__(self):
"""
Output should include the player name, their current hand, and their wins/ties/losses in that order
>>> player = Player("Eric", None)
>>> player.record_loss()
>>> player.record_win()
>>> player.record_win()
>>> player
Eric: [] 2/0/1
"""
return "{}: {} {}/{}/{}".format(self.name,self.hand,self.wins,self.ties,self.losses)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
import React from "react";
import "./Testimonial.css";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import { Pagination } from "swiper";
import "swiper/css/pagination";
import profilePic1 from "../../img/profile1.jpg";
import profilePic2 from "../../img/profile2.jpg";
import profilePic3 from "../../img/profile3.jpg";
import profilePic4 from "../../img/profile4.jpg";
const Testimonial = () => {
const clients = [
{
img: profilePic1,
review:
"Your attention to detail, expertise, and professionalism were evident throughout the entire project. Not only did you meet my expectations, but you exceeded them in every way. The quality of your work and your commitment to delivering on time were truly outstanding. I also appreciate your excellent communication skills. You were always responsive to my questions and open to feedback, which made the collaboration seamless and enjoyable.",
},
{
img: profilePic2,
review:
"I recently hired a full stack web developer on Fiverr, and I am extremely impressed with the results. The developer demonstrated a deep understanding of both front-end and back-end technologies, delivering a website that not only looks visually stunning but also performs flawlessly. Their attention to detail and ability to implement complex functionalities were remarkable..",
},
{
img: profilePic3,
review:
"Amazing service excellent work and great delivery. would recommend to others. He is very collaborative and will call or ask for any more further assistance. I would recommend this person to many different buyers for what ever work they may need.",
},
{
img: profilePic4,
review:
"Zain was excellent to work with. He took all my revisions and made my very first website exactly how I wanted it. I would recommend Zain to anyone looking to build their custom website.",
},
];
return (
<div className="t-wrapper" id="testimonial">
<div className="t-heading">
<span>Clients always get </span>
<span>Exceptional Work </span>
<span>from me...</span>
<div className="blur t-blur1" style={{ background: "var(--purple)" }}></div>
<div className="blur t-blur2" style={{ background: "skyblue" }}></div>
</div>
<Swiper
// install Swiper modules
modules={[Pagination]}
slidesPerView={1}
pagination={{ clickable: true }}
>
{clients.map((client, index) => {
return (
<SwiperSlide key={index}>
<div className="testimonial">
<img src={client.img} alt="" />
<span>{client.review}</span>
</div>
</SwiperSlide>
);
})}
</Swiper>
</div>
);
};
export default Testimonial;
|
/* 9.27 TCP, in SYN-RCVD state, MUST send a reset and go to CLOSED, on recv a seg with SYN in window. */
/* Procedure
1. Client connect to the Server.
2. Change the ACK packet sent from the Client to the Server to a SYN packet.
3. Judge whether the Client received a RST packet.
4. Judge the Server state. */
#include "tx_api.h"
#include "nx_api.h"
#include "nx_tcp.h"
#include "nx_ip.h"
#include "nx_ram_network_driver_test_1500.h"
extern void test_control_return(UINT status);
#if !defined(NX_DISABLE_IPV4)
#define DEMO_STACK_SIZE 2048
#define TEST_INTERFACE 0
/* Define the ThreadX and NetX object control blocks... */
static TX_THREAD ntest_0;
static TX_THREAD ntest_1;
static NX_PACKET_POOL pool_0;
static NX_IP ip_0;
static NX_IP ip_1;
static NX_TCP_SOCKET client_socket;
static NX_TCP_SOCKET server_socket;
/* Define the counters used in the test application... */
static ULONG error_counter;
static ULONG syn_counter;
static ULONG rst_counter;
static UINT syn_flag;
/* Define thread prototypes. */
static void ntest_0_entry(ULONG thread_input);
static void ntest_1_entry(ULONG thread_input);
static void ntest_0_connect_received(NX_TCP_SOCKET *server_socket, UINT port);
static void ntest_0_disconnect_received(NX_TCP_SOCKET *server_socket);
extern void _nx_ram_network_driver_1500(struct NX_IP_DRIVER_STRUCT *driver_req);
extern void _nx_ram_network_driver(struct NX_IP_DRIVER_STRUCT *driver_req);
extern UINT (*advanced_packet_process_callback)(NX_IP *ip_ptr, NX_PACKET *packet_ptr, UINT *operation_ptr, UINT *delay_ptr);
extern USHORT _nx_ip_checksum_compute(NX_PACKET *, ULONG, UINT, ULONG *, ULONG *);
static UINT my_packet_process_9_27(NX_IP *ip_ptr, NX_PACKET *packet_ptr, UINT *operation_ptr, UINT *delay_ptr);
static void my_tcp_packet_receive_9_27_01(NX_IP *ip_ptr, NX_PACKET *packet_ptr);
static void my_tcp_packet_receive_9_27_02(NX_IP *ip_ptr, NX_PACKET *packet_ptr);
/* Define what the initial system looks like. */
#ifdef CTEST
VOID test_application_define(void *first_unused_memory)
#else
void netx_9_27_application_define(void *first_unused_memory)
#endif
{
CHAR *pointer;
UINT status;
/* Setup the working pointer. */
pointer = (CHAR *) first_unused_memory;
error_counter = 0;
syn_counter = 0;
rst_counter = 0;
syn_flag = 0;
/* Create the main thread. */
tx_thread_create(&ntest_0, "thread 0", ntest_0_entry, 0,
pointer, DEMO_STACK_SIZE,
3, 3, TX_NO_TIME_SLICE, TX_AUTO_START);
pointer = pointer + DEMO_STACK_SIZE;
/* Create the main thread. */
tx_thread_create(&ntest_1, "thread 1", ntest_1_entry, 0,
pointer, DEMO_STACK_SIZE,
4, 4, TX_NO_TIME_SLICE, TX_AUTO_START);
pointer = pointer + DEMO_STACK_SIZE;
/* Initialize the NetX system. */
nx_system_initialize();
/* Create a packet pool. */
status = nx_packet_pool_create(&pool_0, "NetX Main Packet Pool", 256, pointer, 8192);
pointer = pointer + 8192;
if(status)
error_counter++;
/* Create an IP instance. */
status = nx_ip_create(&ip_0, "NetX IP Instance 0", IP_ADDRESS(1, 2, 3, 5), 0xFFFFFF00UL, &pool_0, _nx_ram_network_driver,
pointer, 2048, 1);
pointer = pointer + 2048;
/* Create another IP instance. */
status += nx_ip_create(&ip_1, "NetX IP Instance 1", IP_ADDRESS(1, 2, 3, 4), 0xFFFFFF00UL, &pool_0, _nx_ram_network_driver_1500,
pointer, 2048, 2);
pointer = pointer + 2048;
if(status)
error_counter++;
/* Enable ARP and supply ARP cache memory for IP Instance 0. */
status = nx_arp_enable(&ip_0, (void *) pointer, 1024);
pointer = pointer + 1024;
if(status)
error_counter++;
/* Enable ARP and supply ARP cache memory for IP Instance 1. */
status = nx_arp_enable(&ip_1, (void *) pointer, 1024);
pointer = pointer + 1024;
if(status)
error_counter++;
/* Enable TCP processing for both IP instances. */
status = nx_tcp_enable(&ip_0);
status += nx_tcp_enable(&ip_1);
/* Check TCP enable status. */
if(status)
error_counter++;
}
/* Define the test threads. */
static void ntest_0_entry(ULONG thread_input)
{
UINT status;
ULONG actual_status;
/* Print out test information banner. */
printf("NetX Test: TCP Spec 9.27 Test........................................");
/* Check for earlier error. */
if(error_counter)
{
printf("ERROR!\n");
test_control_return(1);
}
/* Ensure the IP instance has been initialized. */
status = nx_ip_status_check(&ip_1, NX_IP_INITIALIZE_DONE, &actual_status, NX_IP_PERIODIC_RATE);
/* Check status... */
if(status != NX_SUCCESS)
{
error_counter++;
return;
}
/* Create a socket. */
status = nx_tcp_socket_create(&ip_0, &server_socket, "Server Socket",
NX_IP_NORMAL, NX_FRAGMENT_OKAY, NX_IP_TIME_TO_LIVE, 200,
NX_NULL, ntest_0_disconnect_received);
/* Check for error. */
if(status)
error_counter++;
/* Setup this thread to listen. */
status = nx_tcp_server_socket_listen(&ip_0, 12, &server_socket, 5, ntest_0_connect_received);
/* Check for error. */
if(status)
error_counter++;
ip_0.nx_ip_tcp_packet_receive = my_tcp_packet_receive_9_27_01;
/* Accept a client socket connection. */
status = nx_tcp_server_socket_accept(&server_socket, NX_NO_WAIT);
tx_thread_sleep(NX_IP_PERIODIC_RATE);
if(server_socket.nx_tcp_socket_state != NX_TCP_CLOSED)
error_counter++;
/* Unaccept the server socket. */
status = nx_tcp_server_socket_unaccept(&server_socket);
/* Check for error. */
if(status)
error_counter++;
/* Unlisten on the server port. */
status = nx_tcp_server_socket_unlisten(&ip_0, 12);
/* Check for error. */
if(status)
error_counter++;
/* Delete the socket. */
status = nx_tcp_socket_delete(&server_socket);
/* Check for error. */
if(status)
error_counter++;
}
static void ntest_1_entry(ULONG thread_input)
{
UINT status;
/* Create a socket. */
status = nx_tcp_socket_create(&ip_1, &client_socket, "Client Socket",
NX_IP_NORMAL, NX_FRAGMENT_OKAY, NX_IP_TIME_TO_LIVE, 200,
NX_NULL, NX_NULL);
/* Check for error. */
if(status)
error_counter++;
/* Bind the socket. */
status = nx_tcp_client_socket_bind(&client_socket, 12, NX_IP_PERIODIC_RATE);
/* Check for error. */
if(status)
error_counter++;
/* Deal rst with my routing. */
ip_1.nx_ip_tcp_packet_receive = my_tcp_packet_receive_9_27_02;
advanced_packet_process_callback = my_packet_process_9_27;
/* Attempt to connect the socket. */
status = nx_tcp_client_socket_connect(&client_socket, IP_ADDRESS(1, 2, 3, 5), 12, NX_IP_PERIODIC_RATE);
/* Disconnect the socket. */
status = nx_tcp_socket_disconnect(&client_socket, NX_IP_PERIODIC_RATE);
/* Unbind the socket. */
status = nx_tcp_client_socket_unbind(&client_socket);
/* Check for error. */
if(status)
error_counter++;
/* Delete the socket. */
status = nx_tcp_socket_delete(&client_socket);
/* Check for error. */
if(status)
error_counter++;
/* Return error. */
if(error_counter || (syn_counter != 1) || (rst_counter != 1))
{
printf("ERROR!\n");
test_control_return(1);
}
/* Return success. */
else
{
printf("SUCCESS!\n");
test_control_return(0);
}
}
static UINT my_packet_process_9_27(NX_IP *ip_ptr, NX_PACKET *packet_ptr, UINT *operation_ptr, UINT *delay_ptr)
{
NX_TCP_HEADER *tcp_header_ptr;
ULONG checksum;
#if defined(__PRODUCT_NETXDUO__)
ULONG *source_ip, *dest_ip;
#else
ULONG source_ip, dest_ip;
#endif
if (packet_ptr -> nx_packet_length < 40)
return NX_TRUE;
tcp_header_ptr = (NX_TCP_HEADER*)((packet_ptr -> nx_packet_prepend_ptr) + 20);
NX_CHANGE_ULONG_ENDIAN(tcp_header_ptr -> nx_tcp_header_word_3);
if ((tcp_header_ptr -> nx_tcp_header_word_3 & NX_TCP_ACK_BIT))
{
syn_flag = 1;
/* Clean the ACK bit. */
tcp_header_ptr -> nx_tcp_header_word_3 = tcp_header_ptr -> nx_tcp_header_word_3 & 0xFFEFFFFF;
/* Set the SYN bit. */
tcp_header_ptr -> nx_tcp_header_word_3 = tcp_header_ptr -> nx_tcp_header_word_3 | NX_TCP_SYN_BIT;
/*SYN occupy a squence number*/
client_socket.nx_tcp_socket_tx_sequence ++;
NX_CHANGE_ULONG_ENDIAN(tcp_header_ptr -> nx_tcp_header_word_3);
#if defined(__PRODUCT_NETXDUO__)
packet_ptr -> nx_packet_prepend_ptr += sizeof(NX_IPV4_HEADER);
packet_ptr -> nx_packet_length -= sizeof(NX_IPV4_HEADER);
#else
packet_ptr -> nx_packet_prepend_ptr += sizeof(NX_IP_HEADER);
packet_ptr -> nx_packet_length -= sizeof(NX_IP_HEADER);
#endif
/* Calculate the TCP checksum. */
tcp_header_ptr -> nx_tcp_header_word_4 = 0;
#if defined(__PRODUCT_NETXDUO__)
dest_ip = &client_socket.nx_tcp_socket_connect_ip.nxd_ip_address.v4;
source_ip = &ip_1.nx_ip_interface[TEST_INTERFACE].nx_interface_ip_address;
checksum = _nx_ip_checksum_compute(packet_ptr, NX_PROTOCOL_TCP,
packet_ptr -> nx_packet_length,
source_ip, dest_ip);
checksum = ~checksum & NX_LOWER_16_MASK;
#else
dest_ip = client_socket.nx_tcp_socket_connect_ip;
source_ip = ip_1.nx_ip_address;
checksum = _nx_tcp_checksum(packet_ptr, source_ip, dest_ip);
#endif
/* Move the checksum into header. */
NX_CHANGE_ULONG_ENDIAN(tcp_header_ptr -> nx_tcp_header_word_4);
tcp_header_ptr -> nx_tcp_header_word_4 = (checksum << NX_SHIFT_BY_16);
NX_CHANGE_ULONG_ENDIAN(tcp_header_ptr -> nx_tcp_header_word_4);
#if defined(__PRODUCT_NETXDUO__)
packet_ptr -> nx_packet_prepend_ptr -= sizeof(NX_IPV4_HEADER);
packet_ptr -> nx_packet_length += sizeof(NX_IPV4_HEADER);
#else
packet_ptr -> nx_packet_prepend_ptr -= sizeof(NX_IP_HEADER);
packet_ptr -> nx_packet_length += sizeof(NX_IP_HEADER);
#endif
advanced_packet_process_callback = NX_NULL;
}
else
NX_CHANGE_ULONG_ENDIAN(tcp_header_ptr -> nx_tcp_header_word_3);
return NX_TRUE;
}
static void my_tcp_packet_receive_9_27_01(NX_IP *ip_ptr, NX_PACKET *packet_ptr)
{
NX_TCP_HEADER *tcp_header_ptr;
if((server_socket.nx_tcp_socket_state == NX_TCP_SYN_RECEIVED) && (syn_flag == 1))
{
tcp_header_ptr = (NX_TCP_HEADER *)packet_ptr -> nx_packet_prepend_ptr;
NX_CHANGE_ULONG_ENDIAN(tcp_header_ptr -> nx_tcp_header_word_3);
/* Check the packet is a SYN one. */
if (tcp_header_ptr -> nx_tcp_header_word_3 & NX_TCP_SYN_BIT)
{
syn_counter++;
/* Deal packets with default routing. */
ip_0.nx_ip_tcp_packet_receive = _nx_tcp_packet_receive;
}
NX_CHANGE_ULONG_ENDIAN(tcp_header_ptr -> nx_tcp_header_word_3);
}
/* Let server receives the packet. */
_nx_tcp_packet_receive(ip_ptr, packet_ptr);
}
static void my_tcp_packet_receive_9_27_02(NX_IP *ip_ptr, NX_PACKET *packet_ptr)
{
NX_TCP_HEADER *tcp_header_ptr;
tcp_header_ptr = (NX_TCP_HEADER *)packet_ptr -> nx_packet_prepend_ptr;
NX_CHANGE_ULONG_ENDIAN(tcp_header_ptr -> nx_tcp_header_word_3);
if(tcp_header_ptr -> nx_tcp_header_word_3 & NX_TCP_RST_BIT)
{
rst_counter++;
/* Deal packets with default routing. */
ip_1.nx_ip_tcp_packet_receive = _nx_tcp_packet_receive;
}
NX_CHANGE_ULONG_ENDIAN(tcp_header_ptr -> nx_tcp_header_word_3);
/* Let server receives the packet. */
_nx_tcp_packet_receive(ip_ptr, packet_ptr);
}
static void ntest_0_connect_received(NX_TCP_SOCKET *socket_ptr, UINT port)
{
/* Check for the proper socket and port. */
if((socket_ptr != &server_socket) || (port != 12))
error_counter++;
}
static void ntest_0_disconnect_received(NX_TCP_SOCKET *socket)
{
/* Check for proper disconnected socket. */
if(socket != &server_socket)
error_counter++;
}
#else
#ifdef CTEST
VOID test_application_define(void *first_unused_memory)
#else
void netx_9_27_application_define(void *first_unused_memory)
#endif
{
/* Print out test information banner. */
printf("NetX Test: TCP Spec 9.27 Test........................................N/A\n");
test_control_return(3);
}
#endif
|
import React, { createContext, useReducer } from "react";
type TagsContextType = {
tags: string[];
dispatch: React.Dispatch<{ type: string; payload?: string }>;
};
export const TagsContext = createContext<TagsContextType>(
{} as TagsContextType
);
const actionTypes = {
ADD_TAG: "ADD_TAG",
REMOVE_TAG: "REMOVE_TAG",
CLEAR_TAG: "CLEAR_TAG",
};
export const addTagAction = (tag: string) => ({
type: actionTypes.ADD_TAG,
payload: tag,
});
export const removeTagAction = (tag: string) => ({
type: actionTypes.REMOVE_TAG,
payload: tag,
});
export const clearTagsAction = () => ({
type: actionTypes.CLEAR_TAG,
});
const reducer = (
state: string[] = [],
{ type, payload }: { type: string; payload?: string }
): any => {
switch (type) {
case actionTypes.ADD_TAG:
if (payload && state.includes(payload)) return;
return [...state, payload];
case actionTypes.REMOVE_TAG:
return state.filter((tag) => tag !== payload);
case actionTypes.CLEAR_TAG:
return [];
default:
return state;
}
};
const initialState: string[] = [];
const TagsProvider = ({ children }: { children: React.ReactNode }) => {
const [tags, dispatch] = useReducer(reducer, initialState);
return (
<TagsContext.Provider value={{ tags, dispatch }}>
{children}
</TagsContext.Provider>
);
};
export default TagsProvider;
|
package com.chhatrola.SpringHibernateJpaDemo.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by niv214 on 26/4/20.
*/
@Entity
public class Student {
public Student() {
}
public Student(String name) {
this.name = name;
}
@Id
@GeneratedValue
private Long id;
private String name;
@OneToOne(fetch = FetchType.LAZY)
private Passport passport;
@ManyToMany(mappedBy = "students")
private List<Course> courses = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Passport getPassport() {
return passport;
}
public void setPassport(Passport passport) {
this.passport = passport;
}
public List<Course> getCourses() {
return courses;
}
public void addCourses(Course course) {
this.courses.add(course);
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}' +
'\n';
}
}
|
--042-Các loại trigger DML và DDL
/*
DML (Data Manipulation Language) Triggers: DML triggers được kích hoạt bởi
các hành động DML (INSERT, UPDATE, DELETE) trên một bảng cụ thể hoặc một view.
Chúng có thể được định nghĩa để kích hoạt trước hoặc sau khi hành động DML được thực hiện.
DDL(Data Definition Language) Triggers: DDL triggers được kích hoạt bởi các hành động DDL (CREATE, ALTER, DROP)
trên một đối tượng cơ sở dữ liệu như bảng, view, sequence, index, synonym, hoặc schema.
Chúng chỉ có thể được định nghĩa để kích hoạt sau khi hành động DDL được thực hiện.
Database Triggers: Database triggers được kích hoạt bởi các sự kiện liên quan đến cơ sở dữ liệu
như login, logout, startup, shutdown, hoặc các hành động DDL hoặc DML ở mức độ cơ sở dữ liệu.
Chúng có thể được định nghĩa để kích hoạt trước hoặc sau khi sự kiện diễn ra.
Schema Triggers: Schema triggers được kích hoạt bởi các hành động DDL hoặc DML ở mức độ schema.
Chúng chỉ có thể được định nghĩa để kích hoạt sau khi sự kiện diễn ra.
*/
--Một DML Trigger sẽ kích hoạt khi một lệnh DML (INSERT, UPDATE, DELETE) được thực thi
CREATE OR REPLACE TRIGGER trg_before_insert_user
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
--DBMS_OUTPUT.PUT_LINE('INSERT operation is being performed on USERS table');
INSERT INTO TEMP(text) VALUES('INSERT operation is being performed on USERS table');
END;
/
CREATE TABLE temp(
text VARCHAR2(200)
);
INSERT INTO users(
username,
hashed_password,
password_algorithm,
email,
facebook_id,
google_id,
premium,
date_created)
VALUES('jennyhuong', STANDARD_HASH('abc123456', 'SHA256'),'SHA256', 'jennyhuong@gmail.com', '', '', 1, SYSDATE);
SELECT * FROM users;
DELETE FROM users WHERE USERNAME='jennyhuong';
--DDL(Data Definition Language) Trigger sẽ kích hoạt khi một lệnh DDL (CREATE, ALTER, DROP) được thực thi
CREATE OR REPLACE TRIGGER trg_before_ddl
BEFORE DDL ON SCHEMA
DECLARE
ddl_type VARCHAR2(50);
BEGIN
--Làm thế nào để biết loại DDL (Data Definition Language) nào đang được thực hiện ?
--ora_dict_obj_type sẽ trả về loại đối tượng được thao tác
--ora_sysevent sẽ trả về sự kiện DDL đang được thực hiện (CREATE, ALTER, DROP, etc.)
ddl_type := ora_sysevent;
INSERT INTO TEMP(text) VALUES('A ' || ddl_type ||
' operation is being performed on a ' ||
ora_dict_obj_type || ' in the schema');
END;
/
CREATE TABLE xxx(
x NUMBER
);
ALTER TABLE xxx ADD (y NUMBER);
DROP TABLE xxx;
--Database Trigger sẽ kích hoạt khi một sự kiện ở cấp độ cơ sở dữ liệu xảy ra,
--như thay đổi trạng thái của cơ sở dữ liệu
CREATE OR REPLACE TRIGGER trg_before_logon
BEFORE LOGON ON DATABASE
BEGIN
INSERT INTO TEMP(text) VALUES('A user is trying to log on to the database');
END;
/
SELECT * FROM TEMP;
DELETE FROM TEMP WHERE 1=1; COMMIT;
|
using System;
using Microsoft.EntityFrameworkCore.Diagnostics;
using KdbndpTypes;
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore;
/// <summary>
/// Provides extension methods for <see cref="KdbndpRange{T}"/> supporting KingbaseES translation.
/// </summary>
public static class KdbndpRangeDbFunctionsExtensions
{
/// <summary>
/// Determines whether a range contains a specified value.
/// </summary>
/// <param name="range">The range in which to locate the value.</param>
/// <param name="value">The value to locate in the range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="range"/>.</typeparam>
/// <returns>
/// <value>true</value> if the range contains the specified value; otherwise, <value>false</value>.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static bool Contains<T>(this KdbndpRange<T> range, T value)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(Contains)));
/// <summary>
/// Determines whether a range contains a specified range.
/// </summary>
/// <param name="a">The range in which to locate the specified range.</param>
/// <param name="b">The specified range to locate in the range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// <value>true</value> if the range contains the specified range; otherwise, <value>false</value>.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static bool Contains<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(Contains)));
/// <summary>
/// Determines whether a range is contained by a specified range.
/// </summary>
/// <param name="a">The specified range to locate in the range.</param>
/// <param name="b">The range in which to locate the specified range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// <value>true</value> if the range contains the specified range; otherwise, <value>false</value>.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static bool ContainedBy<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(ContainedBy)));
/// <summary>
/// Determines whether a range overlaps another range.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// <value>true</value> if the ranges overlap (share points in common); otherwise, <value>false</value>.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static bool Overlaps<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(Overlaps)));
/// <summary>
/// Determines whether a range is strictly to the left of another range.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// <value>true</value> if the first range is strictly to the left of the second; otherwise, <value>false</value>.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static bool IsStrictlyLeftOf<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(IsStrictlyLeftOf)));
/// <summary>
/// Determines whether a range is strictly to the right of another range.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// <value>true</value> if the first range is strictly to the right of the second; otherwise, <value>false</value>.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static bool IsStrictlyRightOf<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(IsStrictlyRightOf)));
/// <summary>
/// Determines whether a range does not extend to the left of another range.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// <value>true</value> if the first range does not extend to the left of the second; otherwise, <value>false</value>.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static bool DoesNotExtendLeftOf<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(DoesNotExtendLeftOf)));
/// <summary>
/// Determines whether a range does not extend to the right of another range.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// <value>true</value> if the first range does not extend to the right of the second; otherwise, <value>false</value>.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static bool DoesNotExtendRightOf<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(DoesNotExtendRightOf)));
/// <summary>
/// Determines whether a range is adjacent to another range.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// <value>true</value> if the ranges are adjacent; otherwise, <value>false</value>.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static bool IsAdjacentTo<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(IsAdjacentTo)));
/// <summary>
/// Returns the set union, which means unique elements that appear in either of two ranges.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// A range containing the unique elements that appear in either range.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static KdbndpRange<T> Union<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(Union)));
/// <summary>
/// Returns the set intersection, which means elements that appear in each of two ranges.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// A range containing the elements that appear in both ranges.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static KdbndpRange<T> Intersect<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(Intersect)));
/// <summary>
/// Returns the set difference, which means the elements of one range that do not appear in a second range.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// The elements that appear in the first range, but not the second range.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static KdbndpRange<T> Except<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(Except)));
/// <summary>
/// Returns the smallest range which includes both of the given ranges.
/// </summary>
/// <param name="a">The first range.</param>
/// <param name="b">The second range.</param>
/// <typeparam name="T">The type of the elements of <paramref name="a"/>.</typeparam>
/// <returns>
/// The smallest range which includes both of the given ranges.
/// </returns>
/// <exception cref="NotSupportedException">{method} is only intended for use via SQL translation as part of an EF Core LINQ query.</exception>
public static KdbndpRange<T> Merge<T>(this KdbndpRange<T> a, KdbndpRange<T> b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(Merge)));
}
|
/* tslint:disable */
/* eslint-disable */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { ApplicationVersion } from '../../models/application-version';
export interface GetApplicationVersionResource$Params {
/**
* Unique identifier of the application.
*/
id: string;
/**
* The header is required to access this endpoint.
*/
Accept: 'application/vnd.com.nsn.cumulocity.applicationVersion+json' | 'application/vnd.com.nsn.cumulocity.applicationVersionCollection+json';
/**
* The version field of the application version.
*/
version?: string;
/**
* The tag of the application version.
*/
tag?: string;
}
export function getApplicationVersionResource(http: HttpClient, rootUrl: string, params: GetApplicationVersionResource$Params, context?: HttpContext): Observable<StrictHttpResponse<ApplicationVersion>> {
const rb = new RequestBuilder(rootUrl, getApplicationVersionResource.PATH, 'get');
if (params) {
rb.path('id', params.id, {});
rb.header('Accept', params.Accept, {});
rb.query('version', params.version, {});
rb.query('tag', params.tag, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/vnd.com.nsn.cumulocity.applicationVersion+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<ApplicationVersion>;
})
);
}
getApplicationVersionResource.PATH = '/application/applications/{id}/versions?version=1.0';
|
//
// MoviesListViewTests.swift
// MoviesTests
//
// Created by Rodrigo Camara on 27/10/2022.
//
import XCTest
@testable import Movies
final class MoviesListViewTests: XCTestCase {
var view: MoviesListViewController?
var presenterMock: MoviesListPresenterMock!
override func setUp() {
super.setUp()
presenterMock = .init()
view = MoviesListViewController(dependencyResolver: MoviesListDependencyResolverMock(presenter: presenterMock))
}
override func tearDown() {
view = nil
presenterMock = nil
super.tearDown()
}
func test_setUpView() {
// Given
let viewModel = MoviesListViewModel(page: 1,
results: [MoviesResultViewModel(
title: "Movie",
year: "1994",
overview: "It's a movie...",
backdropPath: "/aaaaaa.jpg",
posterPath: "/bbbbb.jpg",
genre: "Drama",
id: 190)],
totalPages: 1,
totalResults: 1)
// When
let viewCount = view?.view.subviews.count ?? 0
view?.setUpView(viewModel: viewModel)
let setupViewExp = expectation(description: "setUpView")
DispatchQueue.main.async {
setupViewExp.fulfill()
}
wait(for: [setupViewExp], timeout: 1)
//Then
let newViewCount = view?.view.subviews.count
XCTAssertEqual(newViewCount, viewCount + 1, "View must have 1 new view inside subviews")
}
}
|
// ** React Imports
import { useState, useEffect, forwardRef } from "react";
import withReactContent from "sweetalert2-react-content";
// ** Store & Actions
import { useDispatch, useSelector } from "react-redux";
import { getAllData, getData } from "@src/views/apps/user/store";
import CoreHttpHandler from "../../../../http/services/CoreHttpHandler";
// ** Third Party Components
import { Search, Trash } from "react-feather";
import { X } from "react-feather";
// ** Reactstrap Imports
import {
Card,
Input,
Row,
Col,
Button,
Badge,
Table,
CardBody,
Label,
InputGroup,
InputGroupText,
} from "reactstrap";
import {
Loader,
Pagination,
DatePicker,
ToastAlertError,
ToastAlertSuccess,
} from "../../reuseable";
// ** Styles
import "@styles/react/libs/tables/react-dataTable-component.scss";
// ** React Imports
import { Link } from "react-router-dom";
// ** Custom Components
import Swal from "sweetalert2";
// ** Reactstrap Imports
import moment from "moment/moment";
import { MdAddCircle } from "react-icons/md";
const MySwal = withReactContent(Swal);
const ProductsTable = () => {
// ** States
const [currentPage, setCurrentPage] = useState(0);
const [loading, setLoading] = useState(true);
const [data, setData] = useState([]);
const [totalPages, setTotalPages] = useState(0);
const [currentParams, setCurrentParams] = useState({
limit: 10,
page: 0,
});
const [searchVal, setSearchVal] = useState("");
const [showCreate, setShowCreate] = useState(false);
useEffect(() => {
if (searchVal == "") {
getUsersData();
} else {
onClickSearch();
}
}, [currentParams]);
const getUsersData = () => {
setLoading(true);
CoreHttpHandler.request(
"products",
"fetch",
{
...currentParams,
},
(response) => {
setLoading(false);
setTotalPages(response.data.data.data.totalPages);
setData(response.data.data.data.product);
},
(failure) => {}
);
};
const Remove = (item) => {
MySwal.fire({
title: "Are you sure?",
icon: "warning",
padding: "50px",
showCancelButton: true,
customClass: {
confirmButton: "btn btn-primary",
cancelButton: "btn btn-outline-danger ms-1",
},
background: "#020202",
buttonsStyling: false,
confirmButtonText: "Yes",
}).then(
(result) => {
if (result.value) {
CoreHttpHandler.request(
"products",
"delete",
{
product_id: item.id,
},
(response) => {
ToastAlertSuccess("Product has been Deleted");
getUsersData();
},
(err) => {
ToastAlertError(
err?.response?.data?.message
? err?.response.data.message
: "something went wrong"
);
}
);
}
},
(error) => {}
);
};
const onClickSearch = (page) => {
if (page == 0) {
setCurrentPage({
limit: 10,
page: 0,
});
}
setLoading(true);
CoreHttpHandler.request(
"products",
"search",
{
page: page == 0 ? 0 : currentParams.page,
limit: currentParams.limit,
name: searchVal,
},
(response) => {
setLoading(false);
const res = response.data.data.data.data;
setTotalPages(response.data.data.data.totalPages);
setData(res);
},
(failure) => {}
);
};
return (
<>
<h3 className='mt-50'>Products</h3>
<Row className='mt-1 justify-content-end'>
<Col sm='3'>
<InputGroup className='input-group-merge'>
<Input
className='search-product'
placeholder='Search Product'
value={searchVal}
onChange={(e) => setSearchVal(e.target.value)}
/>
<InputGroupText>
{searchVal.length > 0 && (
<X
style={{ cursor: "pointer" }}
onClick={() => {
getUsersData();
setSearchVal("");
}}
className='text-muted'
size={14}
/>
)}
</InputGroupText>
</InputGroup>
</Col>
<Col sm='1'>
<Button
className='text-primary cursor-pointer'
onClick={() => onClickSearch(0)}
size='sm'
color='primary'
style={{ height: "35px" }}>
<Search size={15} />
</Button>
</Col>
</Row>
<br />
{!loading && data ? (
<Table
striped
responsive
className='border-none'>
<thead>
<tr style={{ fontSize: "11px" }}>
<th>SN</th>
<th>Name</th>
<th>Category</th>
<th>Date</th>
<th>Status</th>
<th>Details</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{data?.map((p, index) => {
return (
<tr key={p.id}>
<td>{index + 1}</td>
<td>{p.name}</td>
<td>{p.product_category}</td>
<td>{moment(p.dt).format("YYYY-MM-DD")}</td>
<td>
{p.enabled ? (
<Badge
pill
color='light-primary'
className='mr-1'>
Active
</Badge>
) : (
<Badge
pill
color='light-danger'
className='mr-1'>
Pending
</Badge>
)}
</td>
<td>
{" "}
<Link
to={{
pathname: `/apps/product/edit/${p.id}`,
state:
p["attachment"][0]?.url != null
? { ...p, type: "Edit" }
: { ...p, type: "Edit", attachment: [] },
}}>
<Button
color='primary'
size='sm'>
Edit
</Button>
</Link>
</td>
<td onClick={() => Remove(p)}>
<Trash
size={18}
style={{ marginLeft: "20px", cursor: "pointer" }}
/>
</td>
</tr>
);
})}
</tbody>
</Table>
) : null}
{!loading && !data?.length && (
<div className='text-ceter'>No Data Found</div>
)}
<Loader loading={loading} />
<Pagination
total={totalPages}
handlePagination={(e) =>
setCurrentParams({ limit: 10, page: e.selected })
}
/>
<Link
to={{
pathname: `/apps/product/add`,
state: { type: "Add", attachment: [] },
}}>
<MdAddCircle
color='#f3ac3b'
size='35'
style={{
cursor: "pointer",
float: "right",
marginRight: "20px",
}}
onClick={() => setShowCreate(true)}
/>
</Link>
</>
);
};
export default ProductsTable;
|
import { BadRequestException, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { plainToClass } from 'class-transformer';
import { validateSync } from 'class-validator';
import { LoginDto } from './dto/login.dto';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
/**
* local 전략 커스텀 인증 로직
* - 요청 body를 loginDto에 매핑 => 유효성 검사 실행
* - => 성공 => 다음 로직 실행
* - => 실패 => 400 응답 처리
* @param context
* @returns
*/
async canActivate(context: ExecutionContext): Promise<any> {
const request = context.switchToHttp().getRequest();
// dto = body 매핑
const validateConfig = plainToClass(
LoginDto, //
request.body,
{ enableImplicitConversion: true },
);
// 유효성 검사 실행
const errors = validateSync(
validateConfig, //
{ skipMissingProperties: false },
);
if (errors.length > 0) {
// 메세지만 추출
const messages = errors.map((error) => {
const constraints = error.constraints;
return Object.keys(constraints) //
.map((key) => constraints[key])
.reduce((perv, cur) => perv.concat(cur));
});
// AuthGuard의 handleRequest를 사용하여 에러를 헨들링 한다.
super.handleRequest(new BadRequestException(messages), null, null, null);
}
// 위의 커스텀 인증 로직이 모두 통과하면 AuthGuard의 canActivate를 호출한다.
return super.canActivate(context);
}
}
|
import React from 'react';
import { connect } from 'react-redux';
import { element, oneOfType, arrayOf, object } from 'prop-types';
import NavigationHeaderBar from '../../components/NavigationHeaderBar'
import MainFeaturedStory from '../../components/container/MainFeaturedStory'
import FeaturedPosts from "../../components/container/FeaturedPosts"
import {callAddBlog} from "../../../api/redux/async-actions";
const Main = (props) => {
const { children, blogs} = props
return (
<React.Fragment>
{/*<NavigationHeaderBar />*/}
<div className="container">
<MainFeaturedStory />
<section>
<FeaturedPosts {...props}/>
{children}
</section>
</div>
</React.Fragment>
)
}
Main.propTypes = {
children: oneOfType([arrayOf(element), object]).isRequired,
};
const mapStateToProps = state => {
return ({ posts: state.blogs })
}
const mapDispatchToProps = dispatch => ({
dispatchCallAddBlog: data => dispatch(callAddBlog(data)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Main);
|
<template>
<div class="dashboard-container">
<SidebarMenu />
<div class="content-area">
<UserHeader />
<div class="table-container">
<h1>Lista de Capelas</h1>
<table>
<thead>
<tr>
<th>NOME</th>
<th>PARÓQUIA</th>
<th>RUA</th>
<th>NÚMERO</th>
<th>CEP</th>
<th>COMPLEMENTO</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<tr v-for="(capela, index) in capelas" :key="index">
<td>{{ capela.nome }}</td>
<td>{{ getParoquiaName(capela.paroqId) }}</td>
<td>{{ capela.rua }}</td>
<td>{{ capela.numero }}</td>
<td>{{ capela.cep }}</td>
<td>{{ capela.complemento }}</td>
<td class="actions">
<button @click="viewCapela(capela.id)"><i class="fas fa-eye"></i></button>
<router-link :to="{ name: 'EditChapel', params: { id: capela.id } }">
<button><i class="fas fa-edit"></i></button>
</router-link>
<button @click="deleteCapela(capela.id)"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
<button class="download-report" @click="downloadReport">Baixar Relatório</button>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import SidebarMenu from '../components/SidebarMenu.vue';
import UserHeader from '../components/Header.vue';
import { jsPDF } from 'jspdf';
interface Capela {
id: number;
nome: string;
paroqId: number;
rua: string;
numero: string;
cep: string;
complemento: string;
}
interface Paroquia {
id: number;
nome: string;
}
export default defineComponent({
name: 'ListagemCapelas',
components: {
SidebarMenu,
UserHeader
},
setup() {
const capelas = ref<Capela[]>([]);
const paroquias = ref<Paroquia[]>([]);
const router = useRouter();
const fetchCapelas = async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('Você precisa estar logado para visualizar as capelas.');
return;
}
try {
const response = await axios.get(`${process.env.VUE_APP_API_URL}/api/capela/listar`, {
headers: {
'x-access-token': token
}
});
capelas.value = response.data;
} catch (error) {
console.error('Erro ao buscar capelas:', error);
alert('Erro ao buscar capelas.');
}
};
const fetchParoquias = async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('Você precisa estar logado para visualizar as paróquias.');
return;
}
try {
const response = await axios.get(`${process.env.VUE_APP_API_URL}/api/paroquia/listar`, {
headers: {
'x-access-token': token
}
});
paroquias.value = response.data;
} catch (error) {
console.error('Erro ao buscar paróquias:', error);
alert('Erro ao buscar paróquias.');
}
};
const getParoquiaName = (id: number) => {
const paroquia = paroquias.value.find(paroquia => paroquia.id === id);
return paroquia ? paroquia.nome : 'Desconhecida';
};
const viewCapela = (id: number) => {
router.push({ name: 'SeeChapel', params: { id } });
};
const deleteCapela = async (id: number) => {
const token = localStorage.getItem('token');
if (!token) {
alert('Você precisa estar logado para deletar uma capela.');
return;
}
try {
await axios.delete(`${process.env.VUE_APP_API_URL}/api/capela/deletar/${id}`, {
headers: {
'x-access-token': token
}
});
capelas.value = capelas.value.filter(capela => capela.id !== id);
alert('Capela deletada com sucesso!');
} catch (error) {
console.error('Erro ao deletar capela:', error);
alert('Erro ao deletar capela.');
}
};
const downloadReport = () => {
const pdf = new jsPDF();
pdf.text("Relatório de Capelas", 10, 10);
capelas.value.forEach((capela, index) => {
pdf.text(`${capela.nome} - ${getParoquiaName(capela.paroqId)} - ${capela.rua} - ${capela.numero} - ${capela.cep} - ${capela.complemento}`, 10, 20 + (index * 10));
});
pdf.save('Relatório_Capelas.pdf');
};
onMounted(() => {
fetchCapelas();
fetchParoquias();
});
return {
capelas,
paroquias,
getParoquiaName,
viewCapela,
deleteCapela,
downloadReport
};
}
});
</script>
<style scoped>
.dashboard-container {
display: flex;
width: 100%;
min-height: 100vh;
}
.content-area {
flex-grow: 1;
display: flex;
flex-direction: column;
background-color: rgb(239, 239, 239);
}
.table-container {
background-color: #ffffff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin-right: 20px;
margin-left: 20px;
}
h1 {
margin-bottom: 20px;
text-align: center;
}
table {
width: 100%;
border-collapse: separate;
text-align: center;
}
thead {
background-color: #dcdcdc;
}
th, td {
border: 0.1px solid #dcdcdc;
padding: 8px;
border-radius: 20px;
}
th {
background-color: #f9f9f9;
}
.actions {
display: flex;
justify-content: space-around;
}
.actions button {
background: none;
border: none;
cursor: pointer;
color: #333;
}
.actions button:hover {
color: #000;
}
.download-report {
cursor: pointer;
margin: 20px auto;
display: block;
padding: 10px 20px;
background-color: #820000;
color: white;
border: none;
border-radius: 5px;
text-align: center;
}
</style>
|
import { useLocation } from "react-router";
import {
IonPage,
IonContent,
IonButton,
useIonPopover,
isPlatform,
} from "@ionic/react";
import PageHeader from "@components/page/PageHeader";
import FullCalendar, {
EventApi,
DateSelectArg,
EventClickArg,
EventContentArg,
formatDate,
} from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin, { Draggable } from "@fullcalendar/interaction";
import "./SchedulePage.css";
import { useEffect, useRef, useState } from "react";
import { useEvents } from "@backend/Database";
import EventData from "@models/EventData";
import Scheduler from "@components/schedule/Scheduler";
import { StatusBar, Style } from "@capacitor/status-bar";
export default function SchedulePage() {
const location = useLocation();
const page = location.pathname.split("/")[1];
const pageCapitalize = page.charAt(0).toUpperCase() + page.slice(1);
const events = useEvents();
const containerEl = document.getElementById("external-events");
const [draggable, setDraggable] = useState(false);
useEffect(() => {
if (isPlatform("ios") && isPlatform("capacitor")) {
StatusBar.setStyle({
style: Style.Dark,
});
}
});
useEffect(() => {
resizeFix(); // Ionic mobile content resize fix
}, [location]);
const resizeFix = async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
window.dispatchEvent(new Event("resize"));
};
useEffect(() => {
if (containerEl && !draggable) {
new Draggable(containerEl, {
itemSelector: ".fc-event",
eventData: function (eventEl) {
return {
title: eventEl.innerText,
duration: "00:15:00",
};
},
});
setDraggable(true);
}
}, [containerEl, draggable]);
return (
<>
<PageHeader name={pageCapitalize} />
<IonContent forceOverscroll={false}>
<div
className="container"
style={{
height: "100%",
display: "flex",
flexFlow: "column nowrap",
// alignItems: "stretch"
}}
>
<div
style={{
flex: 2,
overflow: "auto",
}}
>
<FullCalendar
height={"100%"}
plugins={[timeGridPlugin, interactionPlugin]}
initialView="timeGridDay"
slotDuration="00:15:00"
slotLabelInterval={"00:15:00"}
slotLabelFormat={{
hour: "numeric",
minute: "2-digit",
omitZeroMinute: false,
meridiem: "short",
}}
nowIndicator={true}
allDaySlot={false}
// headerToolbar={false}
scrollTime={new Date(
Date.now() - 15 * 60 * 1000
).toLocaleTimeString("en-US", {
hour12: false,
hour: "numeric",
minute: "numeric",
})}
dayHeaders={false}
// dateClick={async (date) => {
// console.log(date)
// const eventData = new EventData();
// eventData.title = "Test";
// eventData.start = date.dateStr;
// date.date.setMinutes(50);
// eventData.end = date.dateStr;
// const result = await events.create(eventData);
// console.log(result);
// }}
eventReceive={(event) => {
console.log(event.view.title);
}}
longPressDelay={0}
businessHours={{
daysOfWeek: [0, 1, 2, 3, 4, 5, 6],
startTime: "08:00",
endTime: "23:00",
}}
defaultTimedEventDuration={"00:15:00"}
events={events.values}
droppable={true}
/>
</div>
<div
style={{
flex: 1,
overflow: "auto",
}}
>
<Scheduler />
</div>
</div>
</IonContent>
</>
);
}
|
#include <iostream>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iomanip>
#include <stdio.h>
using namespace std;
#define BUFF_LEN 1024
int main(int argc, char *argv[]){
//boot up message
cout<<"The client is up and running"<<endl;
//create tcp client socket,code from beej
int client_socket;
client_socket = socket(AF_INET, SOCK_STREAM, 0);
//specify IP address and dynamic port for the client socket,code from beej
struct sockaddr_in client_address;
client_address.sin_family = AF_INET;
client_address.sin_addr.s_addr = inet_addr("127.0.0.1");
socklen_t len=sizeof(client_address);
getsockname(client_socket,(struct sockaddr *) &client_address,&len);
//specify IP address and dynamic port for the server socket,code from beej
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(33112);
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
//connect to mainserver,code from beej
socklen_t len1=sizeof(server_address);
int connection_status = connect(client_socket,(struct sockaddr *) &server_address, len1);
//check for error within connection_status
if(connection_status==-1){
perror("connect");
exit(0);
}
while(1){
//input country name and user id
char bufSend[BUFF_LEN] ={0};
char bufRecv[BUFF_LEN] ={0};
string CName;
string UID;
string request;
cout<<"Enter country name: ";
cin >> CName;
cout<<"Enter user ID: ";
cin >> UID;
//send inputs to AWS
request = CName+" "+UID;
strcpy(bufSend,request.c_str());//change string to char[]
//code from beej
send(client_socket, bufSend, sizeof(bufSend),0);
cout<<"client has sent "<<UID<<" and "<<CName<<" to main server using TCP"<<endl;
recv(client_socket, &bufRecv, sizeof(bufRecv), 0);
string msg1=bufRecv;
cout<<msg1<<endl;
memset(bufSend,0,BUFF_LEN);
memset(bufRecv,0,BUFF_LEN);
}
close(client_socket);
return 0;
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2022 TOYOTA MOTOR CORPORATION
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Toyota Motor Corporation nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import (
Command,
FindExecutable,
LaunchConfiguration,
PathJoinSubstitution,
)
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
def declare_arguments():
declared_arguments = []
declared_arguments.append(
DeclareLaunchArgument('description_package',
default_value='hsrb_description',
description='Description package with robot URDF/xacro files.'))
declared_arguments.append(
DeclareLaunchArgument('description_file',
default_value='hsrb4s.urdf.xacro',
description='URDF/XACRO description file with the robot.'))
return declared_arguments
def generate_launch_description():
description_package = LaunchConfiguration('description_package')
description_file = LaunchConfiguration('description_file')
robot_description_content = Command(
[PathJoinSubstitution([FindExecutable(name='xacro')]), ' ',
PathJoinSubstitution([FindPackageShare(description_package), 'robots', description_file])])
robot_description = {'robot_description': robot_description_content}
rviz_config_file = PathJoinSubstitution([FindPackageShare('hsrb_description'), 'launch', 'display.rviz'])
joint_state_publisher_node = Node(package='joint_state_publisher_gui',
executable='joint_state_publisher_gui')
robot_state_publisher_node = Node(package='robot_state_publisher',
executable='robot_state_publisher',
parameters=[robot_description])
rviz_node = Node(package='rviz2',
executable='rviz2',
arguments=['-d', rviz_config_file])
nodes = [joint_state_publisher_node, robot_state_publisher_node, rviz_node]
return LaunchDescription(declare_arguments() + nodes)
|
# MorseCodeTool
## Licence: MIT
## Application objective:
I wanted to try out how to create an infinite audio stream in .net core
and generate some audio signal into it.
Morse code seemed to me to be an ideal and simple enough choice.
## How the application works:
The input text is translated into Morse code.
Morse code is translated into a field of spaces and the character X, where X is an audio signal.
Space plays no sound and X plays sound.
At the same time, the rules of pauses between letters and words are respected.
For example, the text SOS is translates:
to morse code: `... --- ... `
to instrumental sequence: `x x x xxx xxx xxx x x x `
Spaces between letters and between words need to be stretched to respect the rules of morse code.
I wanted the spaces to still be spaces when output to the console, but the application needs to
distinguish between spaces between letters and between words,
so I decided to use ASCII 32 and for word spacing use ASCII 160.
I declare that one instrument lasts a tenth of a second.
Subsequently, the number of samples per instrument is calculated.
Instruments array is traversed and sound samples are generated according to them.
When the end of the instrument list is reached, it starts again from the beginning.
To generate the audio signal, I used an audio stream, which is implemented using the IWaveProvider interface.
The provider tells itself about the filling of the buffer for playing the sound and starts playing it.
As soon as it approaches the end of the buffer during playback, it will ask for another buffer filling.
So the audio data is generated piece by piece in advance.
The application is therefore a state machine that remembers where the generation of audio data ended and as soon as
the application provider requests additional data, the application continues generating from the last position
where the previous generation ended.
|
export type UserBio = {
title: string;
description: string;
};
export type Skill = {
name: string;
ratingOutOf10: number;
};
export type Achievement = {
title: string;
description: string;
};
export type experienceCompany = {
name: string;
jobTitle: string;
startAt: string;
endAt: string;
location: string;
summary: string;
workInfo?: {
title: string;
description: string
};
achievements?: {
achievementsTitle: string;
list: Achievement[];
};
};
export type Education = {
instituteName: string;
courseName: string;
fieldOfStudy: string;
startAt: string;
endAt?: string;
grade: string;
university?:string;
location?:string;
};
export type resumeData = {
name: string;
designation: string;
mobileNo: string;
email: string;
website: {
url:string,
name:string,
},
address: string;
userBio: UserBio;
skilSet: Skill[];
experience: experienceCompany[];
educations: Education[];
awards: string[]; // You can update this type based on the actual structure of awards if needed
};
|
import { sendRequest, ResponseHandler } from "./sendRequest";
import { AnonSettings, ChatPreview, Message } from "./types";
type ActionReq = {
chatId: string,
}
type SendMessageReq = {
chatId : string,
text : string,
};
type LoadChatsReq = {
count : number,
offset : number,
};
type LoadMessagesReq = {
chatId : string,
count : number,
offset : number,
};
type CreatePersChatReq = {
profileId: string,
};
type RateAnonChatReq = {
chatId : string,
rate : "up" | "down",
};
type ErrRes = {
error: string,
}
type SuccessRes = {
success: true,
}
type SendMessageRes = {
messageId: string,
}
type LoadChatsRes = {
count: number,
chats: ChatPreview[]
}
type LoadMessagesRes = {
count : number,
messages : Message[]
}
type CreateChatRes = {
chatId: string,
};
export async function sendMessage(req: SendMessageReq, handler: ResponseHandler<SendMessageRes, ErrRes>) {
await sendRequest("post", "/api/chat/send-message", req, handler);
}
export async function loadChats(req: LoadChatsReq, handler: ResponseHandler<LoadChatsRes, ErrRes>) {
await sendRequest("post", "/api/chat/load-chats", req, handler);
}
export async function loadMessages(req: LoadMessagesReq, handler: ResponseHandler<LoadMessagesRes, ErrRes>) {
await sendRequest("post", "/api/chat/load-messages", req, handler);
}
export async function createChat(req: CreatePersChatReq, handler: ResponseHandler<CreateChatRes, ErrRes>) {
await sendRequest("post", "/api/chat/personal", req, handler);
}
export async function deleteChat(req: ActionReq, handler: ResponseHandler<SuccessRes, ErrRes>) {
await sendRequest("delete", `/api/chat/personal/${req.chatId}`, {}, handler);
}
export async function enterAnonQueue(req: AnonSettings, handler: ResponseHandler<SuccessRes, ErrRes>) {
await sendRequest("post", "/api/chat/anonymous/enter-queue", req, handler);
}
export async function leaveAnonQueue(handler: ResponseHandler<SuccessRes, ErrRes>) {
await sendRequest("post", "/api/chat/anonymous/leave-queue", {}, handler);
}
export async function leaveAnonChat(req: ActionReq, handler: ResponseHandler<SuccessRes, ErrRes>) {
await sendRequest("post", "/api/chat/anonymous/leave-chat", req, handler);
}
export async function rateAnonChat(req: RateAnonChatReq, handler: ResponseHandler<SuccessRes, ErrRes>) {
await sendRequest("post", "/api/chat/anonymous/rate-user", req, handler);
}
export async function blockAnonChat(req: ActionReq, handler: ResponseHandler<SuccessRes, ErrRes>) {
await sendRequest("post", "/api/chat/anonymous/block-user", req, handler);
}
|
当数据表中存在数据类型为varchar、blob、text的列,则对该表的更新、删除等操作会造成数据表所占据的磁盘空间产生碎片(因为更新、删除后,以前
分配的磁盘空间不会自动回收),即磁盘空间地浪费和查询的费时,优化数据表就能整理磁盘碎片,让数据在磁盘中更紧凑。
优化数据表的语法(执行该语句期间,相应的表会被加上只读锁):
OPTIMIZE TABLE tab1,tab2,...; //对InnoDB和MyISAM两种类型的表都有效。但只会优化表中varchar、blob、text类型的列。
补充:
检查表,检查表是否存在错误(执行该语句期间,相应的表会被加上只读锁):
CHECK TABLE tab1,tab2,...; //详见《MySQL从入门到精通》P306页
分析表,分析表的状态情况(执行该语句期间,相应的表会被加上只读锁):
ANALYSE TABLE tab1,tab2,...; //详见《MySQL从入门到精通》P306页
(完)
|
import { Construct } from "constructs";
import { App, TerraformOutput, TerraformStack, Fn } from "cdktf";
import { AwsProvider } from "@cdktf/provider-aws/lib/provider";
import { DataAwsAmi } from "@cdktf/provider-aws/lib/data-aws-ami";
import { Instance } from "@cdktf/provider-aws/lib/instance";
import { KeyPair } from "@cdktf/provider-aws/lib/key-pair";
import { SecurityGroup } from "@cdktf/provider-aws/lib/security-group";
import { readFileSync } from "fs";
import { Vpc } from "./.gen/modules/vpc";
import { UbuntuEc2Instance } from "./UbuntuEc2Instance";
interface AwsSettings {
accessKey: string;
secretKey: string;
region: string;
}
interface AwsMeetupConfig {
awsSettings: AwsSettings;
sshPublicKey?: { keyName: string; publicKey: string };
}
export class AwsMeetupStack extends TerraformStack {
constructor(scope: Construct, id: string, config: AwsMeetupConfig) {
super(scope, id);
const { awsSettings, sshPublicKey } = config;
new AwsProvider(this, "aws", { ...awsSettings });
const keyPair = sshPublicKey
? new KeyPair(this, "KeyPair", { ...sshPublicKey })
: undefined;
const securityGroup = new SecurityGroup(this, "ssh-security-group", {
name: "ssh-access",
description: "Security group for SSH access",
ingress: [
{
description: "SSH",
fromPort: 22,
toPort: 22,
protocol: "tcp",
cidrBlocks: ["0.0.0.0/0"], // allows any IP to connect, consider restricting this
},
],
});
const ubuntuAmi = new DataAwsAmi(this, "ubuntu-ami", {
mostRecent: true,
filter: [
{
name: "name",
values: ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"],
},
{
name: "virtualization-type",
values: ["hvm"],
},
],
owners: ["099720109477"],
});
const cidr = "10.0.0.0/16";
const azs = ["eu-west-1a", "eu-west-1b", "eu-west-1c"];
const privateSubnets = azs.map((_, i) => Fn.cidrsubnet(cidr, 4, i + 1));
const vpc = new Vpc(this, "vpc", {
name: "vpc-test",
azs,
cidr,
privateSubnets,
});
const ec2 = new Instance(this, "web", {
ami: ubuntuAmi.id,
instanceType: "t3.micro",
keyName: keyPair?.keyName,
securityGroups: [securityGroup.name],
tags: {
Name: "web",
},
});
const ec2Web = new UbuntuEc2Instance(this, "web2", {
name: "MyName",
securityGroup,
keyPair,
instanceType: "t2.micro",
});
new TerraformOutput(this, "web-ip", {
description: "ip of the ec2 web instance",
value: ec2.publicIp,
});
new TerraformOutput(this, "web-2-ip", {
description: "ip of the ec2 web instance",
value: ec2Web.publicIp,
});
}
}
const AWS_SETTINGS_PATH = process.env.AWS_SETTINGS_PATH
? process.env.AWS_SETTINGS_PATH
: "./awscreds.json";
function loadAwsSettings(): AwsSettings {
const content = readFileSync(AWS_SETTINGS_PATH, { encoding: "utf-8" });
const json = JSON.parse(content);
return json;
}
const SSH_PUBLIC_KEY_NAME = process.env.SSH_PUBLIC_KEY_NAME;
const SSH_PUBLIC_KEY_VALUE = process.env.SSH_PUBLIC_KEY_VALUE;
const sshPublicKey =
SSH_PUBLIC_KEY_NAME && SSH_PUBLIC_KEY_VALUE
? {
keyName: SSH_PUBLIC_KEY_NAME,
publicKey: SSH_PUBLIC_KEY_VALUE,
}
: undefined;
const app = new App();
new AwsMeetupStack(app, "aws-meetup-dev", {
awsSettings: loadAwsSettings(),
sshPublicKey,
});
app.synth();
|
#include "yesoulbike.h"
#ifdef Q_OS_ANDROID
#include "keepawakehelper.h"
#endif
#include "virtualbike.h"
#include <QBluetoothLocalDevice>
#include <QDateTime>
#include <QFile>
#include <QMetaEnum>
#include <QSettings>
#include <chrono>
#include <math.h>
using namespace std::chrono_literals;
yesoulbike::yesoulbike(bool noWriteResistance, bool noHeartService, uint8_t bikeResistanceOffset,
double bikeResistanceGain) {
m_watt.setType(metric::METRIC_WATT);
Speed.setType(metric::METRIC_SPEED);
refresh = new QTimer(this);
this->noWriteResistance = noWriteResistance;
this->noHeartService = noHeartService;
this->bikeResistanceGain = bikeResistanceGain;
this->bikeResistanceOffset = bikeResistanceOffset;
initDone = false;
connect(refresh, &QTimer::timeout, this, &yesoulbike::update);
refresh->start(200ms);
}
void yesoulbike::writeCharacteristic(uint8_t *data, uint8_t data_len, const QString &info, bool disable_log,
bool wait_for_response) {
QEventLoop loop;
QTimer timeout;
if (wait_for_response) {
connect(gattCommunicationChannelService, &QLowEnergyService::characteristicChanged, &loop, &QEventLoop::quit);
timeout.singleShot(300ms, &loop, &QEventLoop::quit);
} else {
connect(gattCommunicationChannelService, &QLowEnergyService::characteristicWritten, &loop, &QEventLoop::quit);
timeout.singleShot(300ms, &loop, &QEventLoop::quit);
}
if (writeBuffer) {
delete writeBuffer;
}
writeBuffer = new QByteArray((const char *)data, data_len);
gattCommunicationChannelService->writeCharacteristic(gattWriteCharacteristic, *writeBuffer);
if (!disable_log) {
emit debug(QStringLiteral(" >> ") + writeBuffer->toHex(' ') + QStringLiteral(" // ") + info);
}
loop.exec();
}
void yesoulbike::update() {
qDebug() << m_control->state() << bluetoothDevice.isValid() << gattCommunicationChannelService
<< gattWriteCharacteristic.isValid() << gattNotify1Characteristic.isValid() << initDone;
if (m_control->state() == QLowEnergyController::UnconnectedState) {
emit disconnected();
return;
}
if (initRequest) {
initRequest = false;
btinit();
} else if (bluetoothDevice.isValid() && m_control->state() == QLowEnergyController::DiscoveredState &&
gattCommunicationChannelService && gattWriteCharacteristic.isValid() &&
gattNotify1Characteristic.isValid() && initDone) {
update_metrics(true, watts());
// updating the treadmill console every second
if (sec1Update++ == (500 / refresh->interval())) {
sec1Update = 0;
// updateDisplay(elapsed);
}
if (requestResistance != -1) {
if (requestResistance > 15)
requestResistance = 15;
else if (requestResistance == 0)
requestResistance = 1;
if (requestResistance != currentResistance().value()) {
emit debug(QStringLiteral("writing resistance ") + QString::number(requestResistance));
// forceResistance(requestResistance);
}
requestResistance = -1;
}
if (requestStart != -1) {
emit debug(QStringLiteral("starting..."));
// btinit();
requestStart = -1;
emit bikeStarted();
}
if (requestStop != -1) {
emit debug(QStringLiteral("stopping..."));
// writeCharacteristic(initDataF0C800B8, sizeof(initDataF0C800B8), "stop tape");
requestStop = -1;
}
}
}
void yesoulbike::serviceDiscovered(const QBluetoothUuid &gatt) {
emit debug(QStringLiteral("serviceDiscovered ") + gatt.toString());
}
void yesoulbike::characteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) {
// qDebug() << "characteristicChanged" << characteristic.uuid() << newValue << newValue.length();
Q_UNUSED(characteristic);
QSettings settings;
QString heartRateBeltName =
settings.value(QZSettings::heart_rate_belt_name, QZSettings::default_heart_rate_belt_name).toString();
emit debug(QStringLiteral(" << ") + newValue.toHex(' '));
lastPacket = newValue;
if (newValue.length() != 12) {
return;
}
double distance = GetDistanceFromPacket(newValue);
Resistance = newValue.at(4);
emit resistanceRead(Resistance.value());
if (settings.value(QZSettings::cadence_sensor_name, QZSettings::default_cadence_sensor_name)
.toString()
.startsWith(QStringLiteral("Disabled"))) {
Cadence = ((uint8_t)newValue.at(6));
}
m_watts = (((uint16_t)((uint8_t)newValue.at(7)) << 8) + (uint16_t)((uint8_t)newValue.at(8)));
if (!settings.value(QZSettings::speed_power_based, QZSettings::default_speed_power_based).toBool()) {
Speed = 0.37497622 * ((double)Cadence.value());
} else {
Speed = metric::calculateSpeedFromPower(
watts(), Inclination.value(), Speed.value(),
fabs(QDateTime::currentDateTime().msecsTo(Speed.lastChanged()) / 1000.0), this->speedLimit());
}
if (watts())
KCal +=
((((0.048 * ((double)watts()) + 1.19) *
settings.value(QZSettings::weight, QZSettings::default_weight).toFloat() * 3.5) /
200.0) /
(60000.0 / ((double)lastRefreshCharacteristicChanged.msecsTo(
QDateTime::currentDateTime())))); //(( (0.048* Output in watts +1.19) * body weight in kg
//* 3.5) / 200 ) / 60
Distance += ((Speed.value() / 3600000.0) *
((double)lastRefreshCharacteristicChanged.msecsTo(QDateTime::currentDateTime())));
if (!settings.value(QZSettings::yesoul_peloton_formula, QZSettings::default_yesoul_peloton_formula).toBool()) {
m_pelotonResistance = ((Resistance.value() * 0.88) *
settings.value(QZSettings::peloton_gain, QZSettings::default_peloton_gain).toDouble()) +
settings.value(QZSettings::peloton_offset, QZSettings::default_peloton_offset)
.toDouble(); // 15% lower than yesoul bike
} else {
m_pelotonResistance = (((Resistance.value() * 1.1099) - 20.769) *
settings.value(QZSettings::peloton_gain, QZSettings::default_peloton_gain).toDouble()) +
settings.value(QZSettings::peloton_offset, QZSettings::default_peloton_offset).toDouble();
}
if (Cadence.value() > 0) {
CrankRevs++;
LastCrankEventTime += (uint16_t)(1024.0 / (((double)(Cadence.value())) / 60.0));
}
lastRefreshCharacteristicChanged = QDateTime::currentDateTime();
#ifdef Q_OS_ANDROID
if (settings.value(QZSettings::ant_heart, QZSettings::default_ant_heart).toBool())
Heart = (uint8_t)KeepAwakeHelper::heart();
else
#endif
{
if (heartRateBeltName.startsWith(QStringLiteral("Disabled"))) {
update_hr_from_external();
}
}
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
bool cadence = settings.value(QZSettings::bike_cadence_sensor, QZSettings::default_bike_cadence_sensor).toBool();
bool ios_peloton_workaround =
settings.value(QZSettings::ios_peloton_workaround, QZSettings::default_ios_peloton_workaround).toBool();
if (ios_peloton_workaround && cadence && h && firstStateChanged) {
h->virtualbike_setCadence(currentCrankRevolutions(), lastCrankEventTime());
h->virtualbike_setHeartRate((uint8_t)metrics_override_heartrate());
}
#endif
#endif
emit debug(QStringLiteral("Current Resistance: ") + QString::number(Resistance.value()));
emit debug(QStringLiteral("Current Speed: ") + QString::number(Speed.value()));
emit debug(QStringLiteral("Current Calculate Distance: ") + QString::number(Distance.value()));
emit debug(QStringLiteral("Current Cadence: ") + QString::number(Cadence.value()));
emit debug(QStringLiteral("Current Distance: ") + QString::number(distance));
emit debug(QStringLiteral("Current CrankRevs: ") + QString::number(CrankRevs));
emit debug(QStringLiteral("Last CrankEventTime: ") + QString::number(LastCrankEventTime));
emit debug(QStringLiteral("Current Watt: ") + QString::number(watts()));
if (m_control->error() != QLowEnergyController::NoError) {
qDebug() << QStringLiteral("QLowEnergyController ERROR!!") << m_control->errorString();
}
}
double yesoulbike::GetDistanceFromPacket(const QByteArray &packet) {
uint16_t convertedData = (packet.at(2) << 8) | packet.at(3);
double data = ((double)convertedData) / 100.0f;
return data;
}
void yesoulbike::btinit() {
uint8_t initData1[] = {0xf5, 0x20, 0x20, 0x40, 0xf6};
writeCharacteristic(initData1, sizeof(initData1), QStringLiteral("init"), false, true);
QByteArray descriptor;
descriptor.append((char)0x01);
descriptor.append((char)0x00);
gattCommunicationChannelService->writeDescriptor(
gattNotify1Characteristic.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration), descriptor);
initDone = true;
}
void yesoulbike::stateChanged(QLowEnergyService::ServiceState state) {
QBluetoothUuid _gattWriteCharacteristicId((quint16)0xFFF1);
QBluetoothUuid _gattNotify1CharacteristicId((quint16)0xFFF4);
QMetaEnum metaEnum = QMetaEnum::fromType<QLowEnergyService::ServiceState>();
emit debug(QStringLiteral("BTLE stateChanged ") + QString::fromLocal8Bit(metaEnum.valueToKey(state)));
if (state == QLowEnergyService::ServiceDiscovered) {
// qDebug() << gattCommunicationChannelService->characteristics();
gattWriteCharacteristic = gattCommunicationChannelService->characteristic(_gattWriteCharacteristicId);
gattNotify1Characteristic = gattCommunicationChannelService->characteristic(_gattNotify1CharacteristicId);
Q_ASSERT(gattWriteCharacteristic.isValid());
Q_ASSERT(gattNotify1Characteristic.isValid());
// establish hook into notifications
connect(gattCommunicationChannelService, &QLowEnergyService::characteristicChanged, this,
&yesoulbike::characteristicChanged);
connect(gattCommunicationChannelService, &QLowEnergyService::characteristicWritten, this,
&yesoulbike::characteristicWritten);
connect(gattCommunicationChannelService,
static_cast<void (QLowEnergyService::*)(QLowEnergyService::ServiceError)>(&QLowEnergyService::error),
this, &yesoulbike::errorService);
connect(gattCommunicationChannelService, &QLowEnergyService::descriptorWritten, this,
&yesoulbike::descriptorWritten);
// ******************************************* virtual bike init *************************************
if (!firstStateChanged && !this->hasVirtualDevice()
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
&& !h
#endif
#endif
) {
QSettings settings;
bool virtual_device_enabled =
settings.value(QZSettings::virtual_device_enabled, QZSettings::default_virtual_device_enabled).toBool();
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
bool cadence =
settings.value(QZSettings::bike_cadence_sensor, QZSettings::default_bike_cadence_sensor).toBool();
bool ios_peloton_workaround =
settings.value(QZSettings::ios_peloton_workaround, QZSettings::default_ios_peloton_workaround).toBool();
if (ios_peloton_workaround && cadence) {
qDebug() << "ios_peloton_workaround activated!";
h = new lockscreen();
h->virtualbike_ios();
} else
#endif
#endif
if (virtual_device_enabled) {
emit debug(QStringLiteral("creating virtual bike interface..."));
auto virtualBike = new virtualbike(this, noWriteResistance, noHeartService);
// connect(virtualBike,&virtualbike::debug ,this,&yesoulbike::debug);
connect(virtualBike, &virtualbike::changeInclination, this, &yesoulbike::changeInclination);
this->setVirtualDevice(virtualBike, VIRTUAL_DEVICE_MODE::PRIMARY);
}
}
firstStateChanged = 1;
// ********************************************************************************************************
// this devices requires first to be initialized and then you can subscribe to its notification
initRequest = true;
emit connectedAndDiscovered();
}
}
void yesoulbike::descriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue) {
emit debug(QStringLiteral("descriptorWritten ") + descriptor.name() + " " + newValue.toHex(' '));
}
void yesoulbike::characteristicWritten(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) {
Q_UNUSED(characteristic);
emit debug(QStringLiteral("characteristicWritten ") + newValue.toHex(' '));
}
void yesoulbike::serviceScanDone(void) {
emit debug(QStringLiteral("serviceScanDone"));
QBluetoothUuid _gattCommunicationChannelServiceId((quint16)0xFFF0);
gattCommunicationChannelService = m_control->createServiceObject(_gattCommunicationChannelServiceId);
connect(gattCommunicationChannelService, &QLowEnergyService::stateChanged, this, &yesoulbike::stateChanged);
gattCommunicationChannelService->discoverDetails();
}
void yesoulbike::errorService(QLowEnergyService::ServiceError err) {
QMetaEnum metaEnum = QMetaEnum::fromType<QLowEnergyService::ServiceError>();
emit debug(QStringLiteral("yesoulbike::errorService") + QString::fromLocal8Bit(metaEnum.valueToKey(err)) +
m_control->errorString());
}
void yesoulbike::error(QLowEnergyController::Error err) {
QMetaEnum metaEnum = QMetaEnum::fromType<QLowEnergyController::Error>();
emit debug(QStringLiteral("yesoulbike::error") + QString::fromLocal8Bit(metaEnum.valueToKey(err)) +
m_control->errorString());
}
void yesoulbike::deviceDiscovered(const QBluetoothDeviceInfo &device) {
emit debug(QStringLiteral("Found new device: ") + device.name() + QStringLiteral(" (") +
device.address().toString() + ')');
// if (device.name().startsWith(QStringLiteral("YESOUL")))
{
bluetoothDevice = device;
m_control = QLowEnergyController::createCentral(bluetoothDevice, this);
connect(m_control, &QLowEnergyController::serviceDiscovered, this, &yesoulbike::serviceDiscovered);
connect(m_control, &QLowEnergyController::discoveryFinished, this, &yesoulbike::serviceScanDone);
connect(m_control,
static_cast<void (QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error),
this, &yesoulbike::error);
connect(m_control, &QLowEnergyController::stateChanged, this, &yesoulbike::controllerStateChanged);
connect(m_control,
static_cast<void (QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error),
this, [this](QLowEnergyController::Error error) {
Q_UNUSED(error);
Q_UNUSED(this);
emit debug(QStringLiteral("Cannot connect to remote device."));
emit disconnected();
});
connect(m_control, &QLowEnergyController::connected, this, [this]() {
Q_UNUSED(this);
emit debug(QStringLiteral("Controller connected. Search services..."));
m_control->discoverServices();
});
connect(m_control, &QLowEnergyController::disconnected, this, [this]() {
Q_UNUSED(this);
emit debug(QStringLiteral("LowEnergy controller disconnected"));
emit disconnected();
});
// Connect
m_control->connectToDevice();
return;
}
}
bool yesoulbike::connected() {
if (!m_control) {
return false;
}
return m_control->state() == QLowEnergyController::DiscoveredState;
}
uint16_t yesoulbike::watts() {
if (currentCadence().value() == 0) {
return 0;
}
return m_watts;
}
void yesoulbike::controllerStateChanged(QLowEnergyController::ControllerState state) {
qDebug() << QStringLiteral("controllerStateChanged") << state;
if (state == QLowEnergyController::UnconnectedState && m_control) {
qDebug() << QStringLiteral("trying to connect back again...");
initDone = false;
m_control->connectToDevice();
}
}
|
import React, { useState } from "react";
import { NavLink } from "react-router-dom";
import styled from "styled-components";
const Button = styled.button`
margin: 2px;
background-color: white;
color: black;
padding: 5px 15px;
border-radius: 15px;
outline: 0;
text-transform: uppercase;
cursor: pointer;
box-shadow: 0px 2px 2px lightgray;
transition: ease background-color 1s;
&:hover {
color: #fafafa;
background-color: #616161;
transform: scale(1.03);
}
`;
const ButtonToggle = styled(Button)`
opacity: 0.6;
${({ active }) =>
active &&
`
opacity: 1;
color: #fafafa;
background-color: #424242;
`}
`;
const types = ["home", "projects", "skills", "experience", "studies", "others"];
function BtnGroup() {
const [active, setActive] = useState(types[0]);
return (
<div>
{types?.map((type) => (
<NavLink key={type} to={type}>
<ButtonToggle
active={active === type}
onClick={() => {
setActive(type);
// console.log(type);
}}
>
{type}
</ButtonToggle>
</NavLink>
))}
</div>
);
}
export default function Header() {
return (
<header className="inner">
<BtnGroup />
</header>
);
}
|
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
class RoleAndUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
switch ($this->method()) {
case 'POST':
return [
'role_id' => 'required|max:255',
'user_id' => 'nullable|max:255',
];
case 'PUT':
// $worker_uuid = $this->route()->uuid;
return [
'role_id' => 'required|max:255|',
'user_id' => 'nullable|max:255',
];
default:
break;
}
}
public function messages()
{
switch ($this->method()) {
case 'POST':
return [
'role_id.required' => 'Role harus diisi!',
'role_id.max' => 'Maksimal karakter Role adalah :max karakter!',
'user_id.max' => 'Maksimal karakter User adalah :max karakter!'
];
case 'PUT':
return [
'role_id.required' => 'Role harus diisi!',
'role_id.max' => 'Maksimal karakter Role adalah :max karakter!',
'user_id.max' => 'Maksimal karakter User adalah :max karakter!'
];
default:
break;
}
}
// protected function failedValidation(Validator $validator)
// {
// throw new ValidationException(
// $validator,
// dd($this->route()->uuid)
// );
// }
}
|
/**
* GroundCashRecapAction.java
*
*/
package com.fedex.lacitd.cashcontrol.prestier.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fedex.lacitd.cashcontrol.datatier.controller.*;
import com.fedex.lacitd.cashcontrol.datatier.valueobject.*;
import com.fedex.lacitd.cashcontrol.biztier.bizdelegates.*;
import com.fedex.lacitd.cashcontrol.biztier.common.*;
import com.fedex.lacitd.cashcontrol.prestier.struts.form.*;
import com.fedex.lacitd.cashcontrol.common.*;
import org.apache.struts.action.*;
import java.util.*;
import org.apache.commons.beanutils.ConvertUtils;
/**
* This class manages the requests for the Prepaid
* Detail Screen
* @author ccardenas
*/
public class GroundCashRecapAction extends Action implements java.io.Serializable{
/**
* This method is executed by Struts framework when a request to the
* related URI is done.
*
* @param mapping object
* @param form object
* @param request object
* @param response object
* @return Struts action forward
* @exception Exception
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if(request.getSession().getAttribute("userProfile") == null) return mapping.findForward("logout");
if("ChangePaymentCurr".equals(request.getParameter("action"))) {
return changePaymentCurr(mapping,form,request,response);
}
else if("UpdateInformation".equals(request.getParameter("action"))) {
return updateInformation(mapping,form,request,response);
}
else if("CloseEmployee".equals(request.getParameter("action"))) {
return closeEmployee(mapping,form,request,response);
}
else if("toROD".equals(request.getParameter("action"))) {
updateInformation(mapping,form,request,response);
return mapping.findForward("toROD");
}
else if("toCOD".equals(request.getParameter("action"))) {
updateInformation(mapping,form,request,response);
return mapping.findForward("toCOD");
}
else if("toFTC".equals(request.getParameter("action"))) {
updateInformation(mapping,form,request,response);
return mapping.findForward("toFTC");
}
else if("toPOA".equals(request.getParameter("action"))) {
updateInformation(mapping,form,request,response);
return mapping.findForward("toPOA");
}
else if("toPrepaid".equals(request.getParameter("action"))) {
updateInformation(mapping,form,request,response);
return mapping.findForward("toPrepaid");
}
else if("showPage".equals(request.getParameter("action"))) {
updateInformation(mapping,form,request,response);
return show(mapping,form,request,response);
}
else if("sortTable".equals(request.getParameter("action"))) {
return show(mapping,form,request,response);
}
else if("changeCourier".equals(request.getParameter("action"))) {
updateInformation(mapping,form,request,response);
return show(mapping,form,request,response);
}
else if ("SplitCurrency".equals(request.getParameter("action"))) {
return splitCurrency(mapping, form, request, response);
}
else if ("ReassignPayments".equals(request.getParameter("action"))){
return reassignPayments(mapping,form,request,response);
}
else{
return show(mapping,form,request,response);
}
}
/**
* Method to Split Currency
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
private ActionForward splitCurrency(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
PrepPoaBizDelegate prepBiz=new PrepPoaBizDelegate();
GroundCashRecapForm ccrForm = (GroundCashRecapForm) form;
double exchangeRate = new Double(request.getParameter("exchangeRate")).doubleValue();
String amountToChangeString = request.getParameter("amountToChange");
double amountToChange = 0;
if(amountToChangeString != null && amountToChangeString.trim().length()>0)
amountToChange=new Double(request.getParameter("amountToChange")).doubleValue();
Collection groundsSelected = new ArrayList();
GroundDetailsTableVO groundCashRecap = null;
Iterator itRec = ccrForm.getTrackNbrs().iterator();
while(itRec.hasNext())
{ groundCashRecap = (GroundDetailsTableVO)itRec.next();
if(groundCashRecap.isSelected()) {
groundsSelected.add(groundCashRecap);
}
}
ArrayList currencies = (ArrayList)ccrForm.getSupportedCurrencies();
SupportedCurrencyVO scVO=null;
for(int i=0;i<currencies.size();i++)
{ scVO= (SupportedCurrencyVO)currencies.get(i);
if(!(ccrForm.getCurrentCurrency().equals(scVO.getCurrencyCode())))
{ break;}
}
prepBiz.splitGroundCurrency(groundsSelected,scVO.getCurrencyCode(),exchangeRate,amountToChange);
return show(mapping,form,request,response);
}
/**
* This method prepares the information to be showed
* by the Prepaid Details page.
*
* @param mapping object
* @param form object
* @param request object
* @param response object
* @return Struts action forward
* @exception Exception
*/
private ActionForward show(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
try{
GroundCashRecapForm ccrForm=(GroundCashRecapForm) form;
// Initialization of parameters
Integer pageNumber = new Integer(1);
String sortColumn = "awb_nbr";
String sortDirection = "asc";
int rowsByPage = 20; //Hard coded !!
if(ccrForm.getPageNumber() != null)
pageNumber = ccrForm.getPageNumber();
if(ccrForm.getSortColumn() !=null)
sortColumn = ccrForm.getSortColumn();
if(ccrForm.getSortDirection() !=null)
sortDirection = ccrForm.getSortDirection();
ccrForm.setPageNumber(pageNumber);
ccrForm.setSortColumn(sortColumn);
ccrForm.setSortDirection(sortDirection);
if("ALL".equals(ccrForm.getCourier())) {
ccrForm.setCourier(null);
rowsByPage = 40; //Hard coded !!
}
// Getting employee profile
EmployeeProfile ep=(EmployeeProfile)request.getSession().getAttribute("userProfile");
// Get the supported currencies
ccrForm.setSupportedCurrencies(ep.getSupportedCurrencies());
ccrForm.setCountryBanks((Collection)request.getSession().getAttribute("countryBanks"));
PrepPoaBizDelegate biz=new PrepPoaBizDelegate();
//get the currently used currencies
Collection colUsedCurr=biz.getGroundUsedCurrencies(ep.getLocationCd(),ccrForm.getCourier());
Iterator iterSuppCurr=ccrForm.getSupportedCurrencies().iterator();
ccrForm.setCurrentlyUsedCurrencies(new ArrayList());
while(iterSuppCurr.hasNext()) {
SupportedCurrencyVO scVO=(SupportedCurrencyVO)iterSuppCurr.next();
if(colUsedCurr.contains(scVO.getCurrencyCode())) {
ccrForm.getCurrentlyUsedCurrencies().add(scVO);
}
}
if(request.getAttribute("updated")==null && //if still it was not updated
ccrForm.getPreviousCurrencyCode()!=null &&
!"".equals(ccrForm.getPreviousCurrencyCode()) &&
ccrForm.getCurrentCurrency()!=null &&
!"".equals(ccrForm.getCurrentCurrency()) &&
!ccrForm.getCurrentCurrency().equals(ccrForm.getPreviousCurrencyCode())
) {
updateInformation(mapping,form,request,response);
}
// Setting the current currency
if("split".equals(ccrForm.getCurrentCurrency())) {
// Get list of receivables for the location and the courier
Hashtable result = biz.getSplitGroundTable(ep.getLocationCd(),ccrForm.getCourier(),pageNumber,new Integer(rowsByPage),sortColumn,sortDirection);
ccrForm.setTrackNbrs((List) result.get("RESULTSET"));
ccrForm.setNumberOfPages((Integer) result.get("NUMBEROFPAGES"));
ccrForm.setDualCurrency(true);
}
else {
if(ccrForm.getCurrentlyUsedCurrencies().size()==1){
ccrForm.setCurrentCurrency(((SupportedCurrencyVO)ccrForm.getCurrentlyUsedCurrencies().toArray()[0]).getCurrencyCode());
}
else {
if(ccrForm.getCurrentCurrency()==null) {
ccrForm.setCurrentCurrency(ep.getDefaultCurrency());
}
else {
boolean validCurr=false;
Iterator iterCurr=ep.getSupportedCurrencies().iterator();
while(iterCurr.hasNext()){
SupportedCurrencyVO scVO=(SupportedCurrencyVO)iterCurr.next();
if(ccrForm.getCurrentCurrency().equalsIgnoreCase(scVO.getCurrencyCode())){
validCurr=true;
break;
}
}
if (!validCurr){
ccrForm.setCurrentCurrency(ep.getDefaultCurrency());
}
}
}
// Getting the grounds
Hashtable result = biz.getGroundDetailsTable(ep.getLocationCd(),ccrForm.getCourier(),ccrForm.getCurrentCurrency(),pageNumber,new Integer(rowsByPage),sortColumn,sortDirection);
ccrForm.setTrackNbrs((List) result.get("RESULTSET"));
ccrForm.setNumberOfPages((Integer) result.get("NUMBEROFPAGES"));
}
// Getting the employees with payments
ccrForm.setEmployeesWithPayments(new CommonOpsBizDelegate().getEmployeesWithPayments(ep.getLocationCd()));
// Get valid prepaid status
/* Fill status of Ground */
Collection statusGrn = new ArrayList();
PreStatusVO statAux = new PreStatusVO();
statAux.setStatusIdNbr(new Integer(0));
statAux.setStatusDesc("No clear");
statusGrn.add(statAux);
PreStatusVO statAux2 = new PreStatusVO();
statAux2.setStatusIdNbr(new Integer(1));
statAux2.setStatusDesc("Clear");
statusGrn.add(statAux2);
PreStatusVO statAux3 = new PreStatusVO();
statAux3.setStatusIdNbr(new Integer(3)); // number ??
statAux3.setStatusDesc("Bill Account");
statusGrn.add(statAux3);
ccrForm.setGrnStatus(statusGrn);//biz.getAllPreStatus());
// Setting the attributes for paging
setPagingAttributes(request,rowsByPage);
// Setting the used payment types
Collection paymentTypes=new PaymentTypeController().getPaymentTypeByGndLocation(ep.getLocationCd());
ccrForm.setPaymentTypes(paymentTypes);
// Calculate the total amounts
calcTotals(ccrForm,ep.getLocationCd(),ccrForm.getCourier(),ccrForm.getCurrentCurrency(),pageNumber,new Integer(rowsByPage));
// Check if there are split record for GROUND.
int splittes = new CommonOpsBizDelegate().getSplitCountTable(ep.getLocationCd(), ccrForm.getCourier(),"GROUND");
if(splittes > 0)
ccrForm.setDualCurrency(true); //If splitted records exist then dualCurrency flag is true
else //If no splitted records then dualCurrency flag is false
ccrForm.setDualCurrency(false);
request.setAttribute("rowsByPage",new Integer(rowsByPage));
request.setAttribute("GroundCashRecapForm",ccrForm);
}
catch(Exception e) {
Constants.logger.debug(Utils.stackTraceToString(e));
ActionErrors ae=new ActionErrors();
ae.add(ActionErrors.GLOBAL_ERROR,new ActionError("errors.messages.CouldNotGetDataFromDB"));
saveErrors(request,ae);
}
return mapping.findForward("Success");
}
/**
* This method changes the currency of the selected
* prepaid.
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
private ActionForward changePaymentCurr(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
GroundController pc=new GroundController();
GroundVO pVO=pc.getGround(new Integer(request.getParameter("groundId")));
pVO.setPaymentCurrency(request.getParameter("newCurr"));
pc.updateGround(pVO);
return show(mapping,form,request,response);
}
/**
* This method apply the changes made for the
* checkin agent in the Prepaid Page.
*
* @param Struts action mapping object
* @param Struts action form object
* @param http request object
* @param http response object
* @return Struts action forward
* @exception Exception
*/
private ActionForward updateInformation(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
GroundCashRecapForm ccrForm=(GroundCashRecapForm)form;
Iterator iterRec=ccrForm.getTrackNbrs().iterator();
while(iterRec.hasNext()){
GroundDetailsTableVO rec=(GroundDetailsTableVO)iterRec.next();
if(!rec.isModified()){
iterRec.remove();
}else{
EmployeeProfile ep=(EmployeeProfile)request.getSession().getAttribute("userProfile");
rec.setChngStatusDate(Utils.changeDateToTZ(new java.util.Date(),ep.getLocationTimeZone()));
rec.setChngStatusEmployeeId(ep.getEmployeeId());
if(rec.getCustNm()==null){
if (rec.getCustNmPrev()!=null) rec.setRcptChngEmpId(ep.getEmployeeId());
}else{
if (!rec.getCustNm().equals(rec.getCustNmPrev())) rec.setRcptChngEmpId(ep.getEmployeeId());
else rec.setRcptChngEmpId(null);
}
if(rec.getRcptNbr()==null){
if (rec.getRcptNbrPrev()!=null) rec.setRcptChngEmpId(ep.getEmployeeId());
}else{
if (!rec.getRcptNbr().equals(rec.getRcptNbrPrev())) rec.setRcptChngEmpId(ep.getEmployeeId());
else rec.setRcptChngEmpId(null);
}
if(rec.getOtherPaymentType()==3 && rec.getOtherDocNumber().length()>4)
rec.setOtherDocNumber(rec.getOtherDocNumber().substring(rec.getOtherDocNumber().length()-4));
}
}
if(!ccrForm.getTrackNbrs().isEmpty()){
PrepPoaBizDelegate biz=new PrepPoaBizDelegate();
biz.applyGroundChanges(ccrForm.getTrackNbrs());
}
if("YES".equals(request.getParameter("reload"))){
request.setAttribute("updated","updated");//it was updated
return show(mapping,form,request,response);
}else{
return mapping.findForward("Summary");
}
}
/**
* This method is used to reassign payments to another location and courier
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
private ActionForward reassignPayments(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
GroundCashRecapForm ccrForm=(GroundCashRecapForm)form;
Iterator iterRec=ccrForm.getTrackNbrs().iterator();
EmployeeProfile ep=(EmployeeProfile)request.getSession().getAttribute("userProfile");
if(new EmployeeController().getEmployee(ccrForm.getNewEmployeeId())==null){
ActionErrors ae=new ActionErrors();
ae.add(ActionErrors.GLOBAL_ERROR,new ActionError("app.messages.CourierDoesNotExist"));
saveErrors(request,ae);
return show(mapping,form,request,response);
}
GroundController gc=new GroundController();
while(iterRec.hasNext()){
GroundDetailsTableVO gnd=(GroundDetailsTableVO)iterRec.next();
if(gnd.isSelected()){
GroundVO gVO=gc.getGround(new Integer(gnd.getGroundId()));
gVO.setOrigEmpNbr(gVO.getCourEmpIdNbr());
gVO.setRsgnEmpNbr(ep.getEmployeeId());
gVO.setCourEmpIdNbr(ccrForm.getNewEmployeeId());
gVO.setLocationCd(ccrForm.getNewReassLocationCd());
//Validate Currency for the country
String curResult = Utils.validateCountryCurencyInProcess(gVO.getLocationCd(),gVO.getPaymentCurrency());
if(curResult!=null){
gVO.setPaymentCurrency(curResult);
}
gc.updateGround(gVO);
}
}
return updateInformation(mapping,form,request,response);
}
/**
* This method close the current employee.
*
* @param Struts action mapping object
* @param Struts action form object
* @param http request object
* @param http response object
* @return Struts action forward
* @exception Exception
*/
private ActionForward closeEmployee(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
updateInformation(mapping,form,request,response);
GroundCashRecapForm ccrForm=(GroundCashRecapForm)form;
Collection colCourier=new ArrayList();
colCourier.add(ccrForm.getCourier());
EmployeeProfile ep=(EmployeeProfile)request.getSession().getAttribute("userProfile");
CommonOpsBizDelegate biz=new CommonOpsBizDelegate();
if(biz.closeCouriers(ep.getEmployeeId(),ep.getLocationCd(),colCourier)){
return mapping.findForward("Summary");
}else{
ActionErrors ae=new ActionErrors();
ae.add(ActionErrors.GLOBAL_ERROR,new ActionError("errors.messages.AllInvoicesStateToClose"));
saveErrors(request,ae);
return show(mapping,form,request,response);
}
}
/**
* This method put the correct paging attributes values in the request.
*
* @param rowsByPage
* @return Struts action forward
* @exception Exception
*/
private void setPagingAttributes(HttpServletRequest request, int rowsByPage) throws Exception{
Integer length=null,currentPage=null,offset=null;
if(request.getParameter("currentPage")!=null) {
currentPage=((Integer)ConvertUtils.convert((String)request.getParameter("currentPage"),Class.forName("java.lang.Integer")));
if(currentPage.intValue()==0) currentPage=new Integer(1);
}
else
currentPage=new Integer(1);
if(request.getParameter("length")!=null){
length=((Integer)ConvertUtils.convert((String)request.getParameter("length"),Class.forName("java.lang.Integer")));
if(length.intValue()==0) length=new Integer(rowsByPage);
}
else
length=new Integer(rowsByPage);
offset = new Integer(length.intValue()*(currentPage.intValue()-1));
request.setAttribute("currentPage",currentPage);
request.setAttribute("length",length);
request.setAttribute("offset",offset);
}
/**
* This method set the attributes to show
* a particular page from the list of prepaids.
*
* @param Struts action mapping object
* @param Struts action form object
* @param http request object
* @param http response object
* @return Struts action forward
* @exception Exception
*/
/*
private ActionForward showPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
GroundCashRecapForm ccrForm=null;
if(form==null){
ccrForm=new GroundCashRecapForm();
}else{
ccrForm=(GroundCashRecapForm)form;
}
int rowsByPage = 20;
if("ALL".equals(ccrForm.getCourier()) || ccrForm.getCourier() == null) {
ccrForm.setCourier(null);
rowsByPage = 40;
}
setPagingAttributes(request, rowsByPage);
calcTotals(ccrForm,((Integer)request.getAttribute("offset")).intValue(),((Integer)request.getAttribute("length")).intValue());
request.setAttribute("GroundCashRecapForm",ccrForm);
return mapping.findForward("Success");
}
*/
/**
* This method re-calculates the totals for the payments.
*
* @param Struts action mapping object
* @param Struts action form object
* @param http request object
* @param http response object
* @return Struts action forward
* @exception Exception
*/
private void calcTotals(GroundCashRecapForm ccrForm,
String locationCd,
String employeeId,
String currentCurrencyCd,
Integer pageNumber,
Integer rowsByPage) throws Exception {
if(ccrForm.isDualCurrency() && "split".equals(currentCurrencyCd)) {
calcTotalsSplit(ccrForm,locationCd,employeeId,pageNumber,rowsByPage);
}
else {
PrepPoaBizDelegate delegate = new PrepPoaBizDelegate();
TotalSummaryVO totalSummaryVO = delegate.getGroundDetailsTotal(locationCd,employeeId,currentCurrencyCd,pageNumber,rowsByPage);
ccrForm.setCashTotal(totalSummaryVO.getCashTotal().doubleValue());
ccrForm.setCouponTotal(totalSummaryVO.getCouponTotal().doubleValue());
ccrForm.setDepositTotal(totalSummaryVO.getDepositTotal().doubleValue());
ccrForm.setCreditCardTotal(totalSummaryVO.getCreditCardTotal().doubleValue());
ccrForm.setCheckTotal(totalSummaryVO.getCheckTotal().doubleValue());
ccrForm.setCashSubTotal(totalSummaryVO.getCashSubTotal().doubleValue());
ccrForm.setCouponSubTotal(totalSummaryVO.getCouponSubTotal().doubleValue());
ccrForm.setDepositSubTotal(totalSummaryVO.getDepositSubTotal().doubleValue());
ccrForm.setCreditCardSubTotal(totalSummaryVO.getCreditCardSubTotal().doubleValue());
ccrForm.setCheckSubTotal(totalSummaryVO.getCheckSubTotal().doubleValue());
ccrForm.setCanClose(true);
if(totalSummaryVO.getStatusCd() != null && totalSummaryVO.getStatusCd().intValue() < 1)
ccrForm.setCanClose(false);
ccrForm.setTotalPayments(ccrForm.getCashTotal()+ccrForm.getCheckTotal()+ccrForm.getCouponTotal()+ccrForm.getCreditCardTotal()+ccrForm.getDepositTotal());
}
}
private void calcTotalsSplit(GroundCashRecapForm ccrForm,
String locationCd,
String employeeId,
Integer pageNumber,
Integer rowsByPage) throws Exception {
PrepPoaBizDelegate delegate = new PrepPoaBizDelegate();
TotalSummaryVO totalSummaryVO = delegate.getGroundDetailsSplitTotal(locationCd,employeeId,pageNumber,rowsByPage);
ccrForm.setCashTotal(totalSummaryVO.getCashTotal().doubleValue());
ccrForm.setCouponTotal(totalSummaryVO.getCouponTotal().doubleValue());
ccrForm.setDepositTotal(totalSummaryVO.getDepositTotal().doubleValue());
ccrForm.setCreditCardTotal(totalSummaryVO.getCreditCardTotal().doubleValue());
ccrForm.setCheckTotal(totalSummaryVO.getCheckTotal().doubleValue());
ccrForm.setCashSubTotal(totalSummaryVO.getCashSubTotal().doubleValue());
ccrForm.setCouponSubTotal(totalSummaryVO.getCouponSubTotal().doubleValue());
ccrForm.setDepositSubTotal(totalSummaryVO.getDepositSubTotal().doubleValue());
ccrForm.setCreditCardSubTotal(totalSummaryVO.getCreditCardSubTotal().doubleValue());
ccrForm.setCheckSubTotal(totalSummaryVO.getCheckSubTotal().doubleValue());
ccrForm.setUsdCashTotal(totalSummaryVO.getUsdCashTotal().doubleValue());
ccrForm.setUsdCouponTotal(totalSummaryVO.getUsdCouponTotal().doubleValue());
ccrForm.setUsdDepositTotal(totalSummaryVO.getUsdDepositTotal().doubleValue());
ccrForm.setUsdCreditCardTotal(totalSummaryVO.getUsdCreditCardTotal().doubleValue());
ccrForm.setUsdCheckTotal(totalSummaryVO.getUsdCheckTotal().doubleValue());
ccrForm.setUsdCashSubTotal(totalSummaryVO.getUsdCashSubTotal().doubleValue());
ccrForm.setUsdCouponSubTotal(totalSummaryVO.getUsdCouponSubTotal().doubleValue());
ccrForm.setUsdDepositSubTotal(totalSummaryVO.getUsdDepositSubTotal().doubleValue());
ccrForm.setUsdCreditCardSubTotal(totalSummaryVO.getUsdCreditCardSubTotal().doubleValue());
ccrForm.setUsdCheckSubTotal(totalSummaryVO.getUsdCheckSubTotal().doubleValue());
ccrForm.setCanClose(true);
if(totalSummaryVO.getStatusCd() != null && totalSummaryVO.getStatusCd().intValue() < 1)
ccrForm.setCanClose(false);
ccrForm.setTotalPayments(ccrForm.getCashTotal()+ccrForm.getCheckTotal()+ccrForm.getCouponTotal()+ccrForm.getCreditCardTotal()+ccrForm.getDepositTotal());
ccrForm.setUsdTotalPayments(ccrForm.getUsdCashTotal()+ccrForm.getUsdCheckTotal()+ccrForm.getUsdCouponTotal()+ccrForm.getUsdCreditCardTotal()+ccrForm.getUsdDepositTotal());
}
}
|
---
title: 'iomando Dashboard 1.0'
date: '2014-08-04'
path: '/blog/2014/iomando-dashboard-10/'
tags: ['iomando', 'changelog']
featured: false
excerpt: 'Our control panel is transitioning from beta to the newly named iomando Dashboard, and is now ready for release.'
---

When we [introduced iomando v2.0](/blog/2013/iomando-20) in April 2013, alongside a [hardware update](/blog/2013/iomando-20-hardware), we also launched a beta version of our management console. Initially, it was intended as a supplementary tool to the existing management features within the mobile app, which we have been [enhancing](/blog/2013/iomando-11) since its [launch](/blog/2013/iomando-10). Over time, however, it has evolved into a standalone product.
We [previously announced](/blog/2014/iomando-door-status/) ambitious plans for the control panel nearly a year ago. However, the introduction of [new product lines](/blog/2014/iomando-api) slightly delayed its deployment. Despite this, we are thrilled to announce that our control panel has now shed its beta status, rebuild as the iomando Dashboard, and is ready for release.
## Web Based
The most significant update for the iomando Dashboard is its transition to a web-based platform, moving away from being a native mobile app. I've elaborated on this decision in an [additional post](/blog/2014/mobile-to-web), but the primary reasons for this shift are:
- Our customers expressed a need for more professional tools, and we wanted to leverage a larger screen to maximize the potential of the iomando Dashboard.
- The tasks related to access and management began to diverge significantly. To optimize each experience independently, we separated the management capabilities from the mobile app.
- Our [transition](/blog/2014/hard-choices) from a vertically integrated company to a [horizontal service provider](/blog/2014/iomando-api) necessitated additional tools for integration with third-party services and for offering more customization options than a one-size-fits-all solution for end-users.

As a side note, starting December 1st, we will discontinue support for the mobile management tool, integrating all its features into the new iomando Dashboard.
## Inside the iomando Dashboard
Upon logging in, the first thing you'll notice in the iomando Dashboard is a comprehensive list of all your spaces. Selecting a space directs you to its Home section.

We've improved the navigation and enlarged the controls for better compatibility with touch interfaces and tablets like the iPad. The interface is intuitive, divided into four distinct sections:
- Home
- Access Control
- User Management
- Settings
### Home
In the Home section, you'll find a prominent map showing the location of your space, along with important data like active user count. We have significant plans for the Home section and are currently developing additional features and analytics, such as access frequency, open rates, and more.

### Access Control
In the next tab, you have Access Control. This feature lists all the events that have occurred at each door, including a detailed log of user accesses, Door Status, and a 'Back in Time' capability, which allows the administrator to view the state of a door at any given moment.

Real-time, remote features such as User Management and Access Control set us apart in the industry, and have become a testament to the foresight of our [past design choices](/blog/2013/betting-on-cellular/).
### User Management
The third tab is dedicated to User Management, the core area for management activities. In this section, we want to highlight two new features: Groups and New User.

### Groups
Groups have become the fundamental unit for grouping users with the same access level. You can see all Groups listed in the left column. A Group is an entity within the space that shares specific parameters, meaning every user included in a Group automatically inherits its permissions.
Every Group shares these features:
- Name.
- Accesses: The administrator can set the Group's available accesses.
- Geofence: The administrator can also set the maximum distance from which group members are allowed to open doors.

For instance, an administrator might create a "Managers" Group with unlimited access throughout the building and no geofence restrictions. Conversely, for employees on the second floor, another Group could be created with access limited to second-floor doors and a geofence restriction of 100 meters.
### New User
After creating a Group, the next step is to add users and set their time permissions. Adding users with the iomando Dashboard is more streamlined than ever. Simply navigate to the desired Group and tap 'New User'. You can choose between basic and advanced modes.
- Basic mode is incredibly straightforward. Just enter the user’s phone number to grant them 24/7 unlimited access. Given that over 54% of total activations on our platform are 24/7, a basic mode seemed essential.
- Advanced mode, accessible with just a tap, unleashes the full capabilities of the iomando Dashboard. It enables the administrator to set restricted time frames, specific days, and even expiration dates for permissions.

So, to continue with the example above, you might use Basic mode for the Manager, granting unlimited 24/7 access. However, consider a new freelance employee on the 2nd floor who is only permitted to be present on Wednesday and Friday from 09:00 to 17:00. To set this up, simply activate the advanced mode, follow the steps, and you're all set.
### Settings
Finally, in Settings, we're keeping things familiar for those who have used the Beta version. Here, you'll find standard options like email, password, billing information, and other similar settings.
## Final Word
The launch of the iomando Dashboard is a significant milestone for us. We always find joy in delivering new products to our customers, but this release has broader implications for our product team.
By separating the management tool and creating the iomando Dashboard, we can now independently address both aspects of the access experience — opening and managing. This separation enables us to innovate and refine each use case more effectively, free from the limitations we previously faced.
We are excited about what lies ahead for iomando. In the coming months, expect to see a lot more from us, as we dedicate our efforts to creating the best possible access experience for the mobile era.
|
################################################################################
##
## [ PROJ ] Postratify Helios survey responses
## [ FILE ] fit_stan.R
## [ AUTH ] Justin Ortagus, Benjamin Skinner, Melvin Tanner
## [ INIT ] 14 November 2019
##
################################################################################
## libraries
libs <- c("cmdstanr", "tidyverse", "rstan")
invisible(suppressMessages(sapply(libs, require, character.only = TRUE)))
## directories
args <- commandArgs(trailingOnly = TRUE)
root <- ifelse(length(args) == 0, file.path("..", ".."), args)
dat_dir <- file.path(root, "data", "clean")
est_dir <- file.path(root, "data", "estimates")
ext_dir <- file.path(root, "data", "external")
sta_dir <- file.path(root, "scripts", "stan")
scr_dir <- file.path(root, "scripts", "r")
## macros
source(file.path(scr_dir, "macros.R"))
## functions
source(file.path(scr_dir, "functions.R"))
## -------------------------------------
## Stan-specific settings
## -------------------------------------
## stan file
stan_file <- file.path(sta_dir, "mrp.stan")
## stan sampler settings
stan_seed <- 19806
stan_adapt_delta <- .99
stan_max_depth <- 15L
stan_num_cores <- parallel::detectCores()
stan_num_chains <- 4
stan_num_threads <- 1
stan_num_warmup <- 1000L
stan_num_samples <- 1000L
## -----------------------------------------------------------------------------
## READ DATA FOR MODELS
## -----------------------------------------------------------------------------
## we want to run MRP for each outcome; since each outcome has its
## own data set, we just read in a list of the stan_dat_q*.Rdump files;
## for each data file, we read it into memory, center the 1st and
## 2nd-level covariates, and add the file name to the list name (to
## make sure that everything aligns later)
data_list <- get_rstan_data_list(path = dat_dir,
pattern = "stan_dat_q*")
## -----------------------------------------------------------------------------
## COMPILE STAN MODEL
## -----------------------------------------------------------------------------
## compile Stan model from mrp.stan script; it's small so it's not a
## big deal to recompile each run, but we don't have to do so
mod <- cmdstan_model(stan_file,
compile = TRUE,
cpp_options = list(stan_threads = TRUE))
## -----------------------------------------------------------------------------
## COMPUTE POSTERIOR FOR EACH OUTCOME IN LIST
## -----------------------------------------------------------------------------
## mod$sample() is the main command; since we have so many models, we
## just run through each one at a time, storing the resulting fit
## object in a list (NB: it should have the name of the data list
## object we set above, so that makes life easier)
## OPTIONS:
## seed := value doesn't matter, but for replication, we choose one
## adapt_delta (default: .80) := sets stepsize for HMC
## num_cores := use maximum cores to speed computation
## num_chains := want a few to check convergence
fit_list <- map(data_list,
~ mod$sample(.x,
seed = stan_seed,
adapt_delta = stan_adapt_delta,
max_treedepth = stan_max_depth,
iter_warmup = stan_num_warmup,
iter_sampling = stan_num_samples,
parallel_chains = stan_num_cores,
chains = stan_num_chains,
threads_per_chain = stan_num_threads))
## -----------------------------------------------------------------------------
## EXTRACT INFORMATION
## -----------------------------------------------------------------------------
## we "read" the output from each model output object and extract
## everything; we should end up with a list of lists, with the
## parameters being in vectors or matrices
full_fit_list <- map(fit_list,
~ read_stan_csv(.x$output_files()))
## -----------------------------------------------------------------------------
## SAVE POSTERIORS LIST
## -----------------------------------------------------------------------------
saveRDS(full_fit_list, file.path(est_dir, "full_fit_list.rds"))
## -----------------------------------------------------------------------------
## DIAGNOSTICS
## -----------------------------------------------------------------------------
## -------------------------------------
## calculate divergences
## -------------------------------------
diverg <- map(full_fit_list,
~ get_num_divergent(.x)) %>%
bind_rows %>%
pivot_longer(cols = everything(),
names_to = "question",
values_to = "num_divergent") %>%
mutate(pct_divergent = num_divergent /
(stan_num_samples * stan_num_chains) * 100)
## -------------------------------------
## combine all values into on data frame
## -------------------------------------
diag <- diverg
## -------------------------------------
## save
## -------------------------------------
write_csv(diag, file.path(est_dir, "stan_diagnostics.csv"))
################################################################################
## END SCRIPT
################################################################################
|
import { Injectable } from '@angular/core';
import * as moment from 'moment';
import { Post } from '../interfaces/post.interface';
@Injectable({
providedIn: 'root'
})
export class PostsService {
arrPosts: Post[];
constructor() {
this.arrPosts = [
{
titulo: 'Batman 3 Jokers, de Geoff Johns y Jason Fabok',
texto: 'Si hay algún personaje dentro del mundo del cómic y más concretamente de los superhéroes más icónico que Batman es precisamente su principal enemigo, Joker el aclamado príncipe payaso del crimen. Y es que no es precisamente corta la trayectoria del personaje que nació en los años 40, y tampoco son pocas la cantidad de obras que ha protagonizado nuestro villano favorito de Gotham, llegando incluso a eclipsar por completo a la figura de Batman y a protagonizar una película en solitario.Pero para hablar de esta nueva serie titulada Los 3 Jokers tenemos que remontarnos unos años atrás, concretamente al año 2015 y al número 42 de la serie regular de La liga de la Justicia, durante el evento de Darkseid war, donde Batman se sentaba en la silla de Metron, un artefacto de poder y conocimiento del universo de DC, y formulaba la siguiente pregunta ¿Cuál es el nombre del joker?, cuya respuesta supimos más tarde y era que existían 3 de ellos.Así durante 5 años hemos estado pendiente de que iba todo este asunto, y del que nos han ido soltando pequeñas pistas, como cuáles eran estos 3 jokers gracias a un pequeño vistazo que nos brindaron Geoff Jones junto a Jason Fabok durante la Comic Con de 2018.',
autor: 'Joel Iglesias',
imagen: 'https://i1.wp.com/www.tomosygrapas.com/wp-content/uploads/2021/01/batman-three-jokers-banner.jpg?w=978&ssl=1',
fecha: new Date(),
categoria: 'reseñas'
},
{
titulo: 'Novedades Panini Marzo 2022',
texto: 'Ya tenemos con nosotros el comunicado de novedades definitivo en PDF con todos los cómics que publicará Panini a lo largo de marzo de 2022. Un mes en que como es habitual tendremos muchos cómics de Marvel, cómic indepiente y manga. Os dejamos a continuación el PDF para que podáis ver por vosotros mismos las novedades de este mes. Novedades Panini Marzo 2022 by TomosyGrapas on Scribd',
autor: 'Alfredo Matarranz',
imagen: 'https://i2.wp.com/www.tomosygrapas.com/wp-content/uploads/2022/03/shmma464_0.png?w=788&ssl=1',
fecha: new Date(),
categoria: 'noticias'
},
{
titulo: 'EL DON | Presentación y firma virtual de lo nuevo de ISAAC SÁNCHEZ Loulogio',
texto: 'Isaac Sánchez, Loulogio, vuelve sin darnos respiro de su Taxus para romper con lo establecido y seguir progresando como autor con El Don. Una historia que llama al cómic book americano pero que nos sitúa en Alcorcón para ofrecernos una historia de superhéroes muy distintos a los que estamos acostumbrados. Obsesión por mejorar y exprimir los recursos del cómic es lo que nos encontraremos en esta nueva obra de un autor que no ha hecho más que despegar y que ya nos impresiona con su gran nivel. No se lo pierdan.',
autor: 'El hombre Máquina',
imagen: 'https://i2.wp.com/www.tomosygrapas.com/wp-content/uploads/2020/01/ISAAK-SANCHEZ.jpg?resize=1024%2C576&ssl=1',
fecha: new Date(),
categoria: 'entrevistas'
}
];
/**
* grabar en LocalStorage el array inicial al arrancar la app si el array no está ya en el localstorage
*/
if (JSON.parse(localStorage.getItem("blog")) == null) {
this.grabarLocalStorage(this.arrPosts);
}
}
grabarLocalStorage(arrayPost: Post[]) {
localStorage.setItem("blog", JSON.stringify(arrayPost));
}
obtenerLocalStorage(): Post[] {
let blog: Post[] = JSON.parse(localStorage.getItem("blog"));
return blog;
}
getAll(): Post[] {
return this.obtenerLocalStorage();
}
/**
* Recupera el array de LocalStorage e inserta el post nuevo pasado por parámetro
* @param pPost post generado en el formulario
*/
create(pPost: Post) {
const oldArrPost = JSON.parse(localStorage.getItem("blog"));
oldArrPost.push(pPost);
this.grabarLocalStorage(oldArrPost);
}
/**
*
* @returns Devuelve todas las categorias del array para rellenar el 'selector' de ListaPosts
*/
getCategory(): string[] {
const arrayPost = this.getAll();
return [...new Set(arrayPost.map(post => post.categoria))];
}
}
|
import { Montserrat } from 'next/font/google';
import { createTheme } from '@mui/material/styles';
export const montserrat = Montserrat({
weight: ['300', '400', '500', '700'],
subsets: ['latin'],
display: 'swap',
fallback: ['Helvetica', 'Arial', 'sans-serif'],
});
// Create a theme instance.
const theme = createTheme({
palette: {
primary: {
main: '#00F0A9',
},
background: {
default: "#000",
},
text: {
primary: '#fff',
},
},
components: {
MuiCard: {
styleOverrides: {
root: {
background: '#000',
},
},
},
MuiCardHeader: {
styleOverrides: {
subheader: {
color: 'white', // Set the default color of MuiCardHeader subheader to white
},
},
},
},
typography: {
fontFamily: montserrat.style.fontFamily,
body1: {
color: '#fff',
},
},
});
export default theme;
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { createPortal } from 'react-dom';
import css from './Modal.module.css'
const modalRoot = document.querySelector('#modal-root');
export class Modal extends Component {
componentDidMount() {
window.addEventListener('keydown', this.hendleEscClose)
}
componentWillUnmount() {
window.removeEventListener('keydown', this.hendleEscClose )
}
hendleEscClose = event => {
if (event.code === 'Escape') {
this.props.modalClose()
}
}
hendleBackdropClose = event => {
if (event.target === event.currentTarget) {
this.props.modalClose()
}
}
render() {
const { largeImageURL, tags } = this.props.modalOpen;
return createPortal (
<div className={css.modalBackdrop} onClick={this.hendleBackdropClose}>
<div className={css.modalContent}>
<img src={largeImageURL} alt={tags} loading="lazy" />
</div>
</div>,
modalRoot
);
}
}
Modal.propTypes = {
modalOpen: PropTypes.shape({
largeImageURL: PropTypes.string.isRequired,
tags: PropTypes.string.isRequired,
}),
modalClose: PropTypes.func.isRequired,
}
|
import React, { useEffect, useState } from "react";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
IconButton,
DialogContentText,
TextField, // Import TextField
} from "@mui/material";
import { makeStyles } from "@mui/styles";
import {
AddCircleOutline as AddCircleOutlineIcon,
Edit as EditIcon,
Delete as DeleteIcon,
Visibility as VisibilityIcon,
ChevronLeft as ChevronLeftIcon,
ChevronRight as ChevronRightIcon,
Clear as ClearIcon,
} from "@mui/icons-material";
import SliderReview from "../sliderReview";
interface ContainerProps {
onImageUpload: (image: string) => void;
}
const useStyles = makeStyles({
container: {
border: "1px dashed #ccc",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
padding: "20px",
cursor: "pointer",
width: "450px", // Set the fixed width
minHeight: "600px", // Remove the fixed height
position: "relative", // Add position for relative positioning of the text field
},
imageWrapper: {
display: "flex",
alignItems: "center",
justifyContent: "center",
width: "100%",
flexDirection: "column",
textAlign: "center",
position: "relative",
},
uploadedImage: {
maxWidth: "80%",
maxHeight: "100%",
},
previousImages: {
display: "flex",
justifyContent: "center",
flexWrap: "wrap",
marginTop: "10px",
},
smallImage: {
width: "100px",
height: "100px",
margin: "5px",
},
buttomicons: {
display: "flex",
alignItems: "center",
justifyContent: "center",
paddingLeft: "18px",
},
iconButtons: {
position: "absolute",
top: 10,
right: 10,
zIndex: 1,
},
EditButtons: {
position: "absolute",
top: 10,
right: 10,
zIndex: 1,
backgroundColor: "lightgray",
},
addImageButton: {
zIndex: 2,
position: "relative",
},
textFieldModal: {
position: "absolute",
zIndex: 2,
backgroundColor: "white",
border: "1px solid #ccc",
padding: "10px",
cursor: "grab",
},
});
const Container: React.FC<ContainerProps> = ({ onImageUpload }) => {
const classes = useStyles();
const [isDialogOpen, setDialogOpen] = useState(false);
const [selectedImage, setSelectedImage] = useState<string | null>(null);
const [previousImages, setPreviousImages] = useState<string[]>([]);
const [deleteConfirmationOpen, setDeleteConfirmationOpen] = useState(false);
const [reviewImageIndex, setReviewImageIndex] = useState<number | null>(null);
const [review, setReview] = useState(false);
const [isTextEditModalOpen, setTextEditModalOpen] = useState(false);
const [textFieldPosition, setTextFieldPosition] = useState({
top: 0,
left: 0,
});
const handleDeleteConfirmation = () => {
if (reviewImageIndex && reviewImageIndex !== null) {
const updatedImages = [...previousImages];
updatedImages.splice(reviewImageIndex, 1); // Remove the current image
setPreviousImages(updatedImages);
setReviewImageIndex(null);
setSelectedImage(
updatedImages[reviewImageIndex - 1] || updatedImages[0] || null
); // Select the previous image or the first one
setDeleteConfirmationOpen(false);
}
};
const handleClearAll = () => {
// Clear all images and reset the state
setPreviousImages([]);
setReviewImageIndex(null);
setSelectedImage(null);
setDeleteConfirmationOpen(false);
};
useEffect(() => {
const storedImages = localStorage.getItem("uploadedImages");
if (storedImages) {
setPreviousImages(JSON.parse(storedImages));
}
}, []);
useEffect(() => {
localStorage.setItem("uploadedImages", JSON.stringify(previousImages));
}, [previousImages]);
const handleOpenDialog = () => {
setDialogOpen(true);
};
const handleCloseDialog = () => {
setDialogOpen(false);
setSelectedImage(previousImages[previousImages.length - 1] || null);
};
const handleImageInputChange = (
event: React.ChangeEvent<HTMLInputElement>
) => {
const file = event.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const image = e.target?.result as string;
setSelectedImage(image);
};
reader.readAsDataURL(file);
}
};
const handleImageUpload = () => {
if (selectedImage) {
setPreviousImages((prevImages) => [...prevImages, selectedImage]);
onImageUpload(selectedImage);
handleCloseDialog();
}
};
const handleReviewImageClick = (index: number) => {
setSelectedImage(previousImages[index]);
setReviewImageIndex(index);
};
const handleReviewButtonClick = () => {
if (previousImages.length > 0) {
setReviewImageIndex(0);
setDialogOpen(false);
setReviewImageIndex(0);
}
};
const handleTextEditModalOpen = () => {
setTextEditModalOpen(true);
};
const handleTextEditModalClose = () => {
setTextEditModalOpen(false);
};
const handleTextFieldDragStart = (e: React.DragEvent<HTMLDivElement>) => {
e.dataTransfer.setData("text", "");
};
const handleSliderDrop = (e: React.DragEvent<HTMLDivElement>) => {
const textFieldLeft = e.clientX;
const textFieldTop = e.clientY;
setTextFieldPosition({ left: textFieldLeft, top: textFieldTop });
};
return (
<div className={classes.container}>
{reviewImageIndex !== null ? (
<SliderReview
images={previousImages}
onClose={() => setReviewImageIndex(null)}
/>
) : null}
<div className={classes.imageWrapper}>
{selectedImage && (
<div>
<IconButton
className={classes.EditButtons}
color="primary"
size="large"
aria-label="Edit Slider"
onClick={handleTextEditModalOpen}
>
<EditIcon fontSize="inherit" />
</IconButton>
<IconButton
className={classes.iconButtons}
color="warning"
aria-label="Delete"
onClick={(e) => {
e.stopPropagation();
setDeleteConfirmationOpen(true);
}}
>
<DeleteIcon />
</IconButton>
<img
src={selectedImage}
alt="Selected"
className={classes.uploadedImage}
onDragStart={handleTextFieldDragStart}
draggable={true}
onDragEnd={handleSliderDrop}
/>
</div>
)}
{selectedImage ? (
<IconButton
color="primary"
size="large"
aria-label="Upload Image"
className={classes.addImageButton}
onClick={handleOpenDialog}
>
<AddCircleOutlineIcon fontSize="inherit" />
</IconButton>
) : (
<IconButton
color="primary"
size="large"
aria-label="Upload Image"
style={{ marginBottom: "10px" }}
onClick={handleOpenDialog}
>
<AddCircleOutlineIcon fontSize="inherit" />
</IconButton>
)}
<div className={classes.previousImages}>
{previousImages.map((image, index) => (
<img
src={image}
alt={`Previous ${index + 1}`}
key={index}
className={classes.smallImage}
onClick={() => handleReviewImageClick(index)}
/>
))}
</div>
</div>
<div
className={classes.buttomicons}
onDrop={handleSliderDrop}
onDragOver={(e) => e.preventDefault()}
>
{previousImages.length > 0 && (
<IconButton
className={classes.iconButtons}
color="primary"
aria-label="Review"
onClick={handleReviewButtonClick}
>
<VisibilityIcon fontSize="inherit" />
</IconButton>
)}
{previousImages.length > 0 && (
<IconButton
className={classes.iconButtons}
color="error"
aria-label="Clear All"
onClick={handleClearAll}
>
<ClearIcon fontSize="inherit" />
</IconButton>
)}
</div>
<Dialog open={isDialogOpen} onClose={handleCloseDialog}>
<DialogTitle>Upload Image</DialogTitle>
<DialogContent>
<input
accept="image/*"
style={{ display: "none" }}
id="image-input"
type="file"
onChange={handleImageInputChange}
/>
<label htmlFor="image-input">
<Button
variant="outlined"
component="span"
color="primary"
fullWidth
>
Choose Image
</Button>
</label>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseDialog} color="primary">
Cancel
</Button>
<Button onClick={handleImageUpload} color="primary">
Upload
</Button>
</DialogActions>
</Dialog>
<Dialog
open={deleteConfirmationOpen}
onClose={() => setDeleteConfirmationOpen(false)}
>
{/* ... (Delete confirmation dialog code) */}
</Dialog>
<Dialog
open={deleteConfirmationOpen}
onClose={() => setDeleteConfirmationOpen(false)}
>
<DialogTitle color="primary">Delete Image</DialogTitle>
<DialogContent>
<DialogContentText>
Are you sure you want to delete this image?
</DialogContentText>
</DialogContent>
<DialogActions>
<Button
onClick={() => setDeleteConfirmationOpen(false)}
color="primary"
>
Cancel
</Button>
<Button onClick={handleDeleteConfirmation} color="warning">
Delete
</Button>
</DialogActions>
</Dialog>
<Dialog
open={isTextEditModalOpen}
onClose={handleTextEditModalClose}
maxWidth="xs"
>
<DialogTitle>Edit Text</DialogTitle>
<DialogContent>
<TextField
label="Text"
variant="outlined"
multiline
fullWidth
// You can add value and onChange for handling the text field's value
/>
</DialogContent>
<DialogActions>
<Button onClick={handleTextEditModalClose} color="primary">
Cancel
</Button>
<Button onClick={handleTextEditModalClose} color="primary">
Save
</Button>
</DialogActions>
</Dialog>
{/* Draggable text field */}
{isTextEditModalOpen && (
<div
className={classes.textFieldModal}
style={{ top: textFieldPosition.top, left: textFieldPosition.left }}
draggable={true}
onDragStart={handleTextFieldDragStart}
>
<TextField label="Drag me" variant="outlined" multiline fullWidth />
</div>
)}
</div>
);
};
export default Container;
|
package com.example.demo;
import com.example.demo.model.User;
import com.example.demo.repositories.UserRepository;
import com.example.demo.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
public class UserServiceIntegrationTest {
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService; // объект тестируемого класса
@Test
void saveUserHappyFlowIntegrationTest() {
// создаем тестового юзера и заполняем его поля: id, firsName, lastName
User user = new User();
user.setId(1);
user.setFirstName("Sergey");
user.setLastName("LD");
// добавляем в репозиторий нового юзера с двумя полями: firsName, lastName (id должен присвоиться автоматически)
userRepository.save(new User("Sergey", "LD"));
// проверяем, совпадают ли созданный нами user и user, полученный из репозитория
assertEquals(user, userService.getUser(1)); //
}
}
|
<h1>[Linux] 파일 아카이브(Archive)</h1>
<h3>📌INDEX</h3>
- [아카이브(archive)란?](#아카이브archive란)
- [tar](#tar)
- [아카이브 실습(문제)](#아카이브-실습문제)
<br>
<br>
<h2>아카이브(Archive)란?</h2>
- 리눅스에서 **여러 파일을 한 파일로 묶는 것**을 아카이브(archive)라 한다.
- ''보따리''라고 생각하기
- 다른 시스템과 파일 주고 받기, 기존 아카이브에서 파일의 추출, 백업 등을 위해 사용
- 파일의 메타 데이터가 포함되기 때문에, 파일의 용량이 없더라도 아카이브에는 용량 존재
- **.tar 확장자** 사용
- 일반 아카이브는 묶어만 주기 때문에, 압축률은 0이다.
<br>
<br>
<h2>tar</h2>
- 파일 **아카이브 및 압축에 사용하는 명령어**
- 특정: 아카이브 생성 시 **피드백 없이** 덮어쓴다.
- 이전 파일로 돌아갈 수 있으므로 주의해야한다.
- 묶인 파일이 풀릴 때에도 이전으로 돌아가면서 덮어씌워지기 때문에 주의
- 파일의 소유권 및 권한을 저장
- 여러 파일을 묶어서 한 번에 압축 가능
- 추출 시 현재 작업 디렉토리로 추출된다.
- 옵션
- c : create, 새로운 묶음 생성
- x : extract, 묶인 파일 풀기
- t : list, 묶음을 풀기 전에 목록 출력
- f : file, 묶음 파일명 지정
- v : visual, 파일이 묶이거나 풀리는 과정 출력
- z : tar + gzip
- j : tar + bzip2
- J : Tar + xz
- -C : 압축을 해제할 때, 해제할 디렉토리 지정
- 많이 사용하는 조합 : cvf(생성), tvf(확인), xvf(해제)
- 아카이브 **생성 : tar cvf [생성될 아카이블 파일명] [아카이브할 파일·디렉토리]**
- 아카이브 **추출(해체) : tar -xvf [대상tar]**
- 압축
- **gzip : tar -zcvf [이름] [대상파일]**
- **bzip2 : tar -jcvf [이름] [대상파일]**
- **xz : tar -Jcvf [이름] [대상파일]**
사용 예
+ 아카이브 생성 : tar cvf
```shell
[root@localhost ~]# tar cvf xinetd.tar /etc/xinetd.d/
```
- 아카이브 생성 + gzip 압축 : tar zcvf
```shell
[root@localhost ~]# tar cvzf xinetd.tar.gz /etc/xinetd.d/
```
- 아카이브 생성 + bzip2 압축 : tar jcvf
```shell
[root@localhost ~]# tar cvjf xinetd.tar.bz2 /etc/xinetd.d/
```
- 아카이브 생성 + xz 압축 : tar Jcvf
```shell
[root@localhost ~]# tar cvJf xinetd.tar.xz /etc/xinetd.d/
```
- 확인 : tar tvf
```shell
[root@localhost ~]# tar tvf xinetd.tar
```
- 풀기 : tar xvf
```shell
[root@localhost ~]# tar xvf xinetd.tar
```
- gzip 압축 해제 + tar 풀기 : tar xvzf
```shell
[root@localhost ~]# tar xvzf xinetd.tar.gz
```
<br>
<br>
<h2>아카이브 실습(문제)</h2>
1. /usr/bin 디렉토리를 아카이브 및 압축 (gzip, bzip2, xz) 해보자
```shell
[root@localhost ~]# tar -cvf bin.tar /usr/bin
[root@localhost ~]# tar -zcvf bin.tar.gz /usr/bin
[root@localhost ~]# tar -jcvf bin.tar.bz2 /usr/bin
[root@localhost ~]# tar -Jcvf bin.tar.xz /usr/bin
```
2. 1번에서 압축한 파일 중 xz 파일을 /tmp 에 압축해제해보자
```shell
[root@localhost ~]# tar -Jxvf bin.tar.xz -C /tmp
```
3. centos 홈 디렉토리의 모든 파일을 아카이브해서 gzip 방식으로 압축해보자.
```shell
[root@localhost ~]# tar -zcvf centos.tar.gzip ~centos/
```
4. 3번에서 압축한 파일을 /tmp/dir01 디렉토리에 해제해보자
```shell
[root@localhost ~]# tar -zxvf centos.tar.gzip -C /tmp/dir01
```
5. 아카이브 된 파일의 내용을 보고 싶을 때 사용하는 명령어와 옵션을 작성해보자
```shell
[root@localhost ~]# tar -tvf [아카이브된 파일명]
```
|
\documentclass{article}
\usepackage{amsmath}
\usepackage[spanish]{babel}
\begin{document}
Hola a todos, amiguitos.
\[
\underbrace{
\begin{matrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{matrix}
}_{\textrm{Ejemplo de \texttt{matrix}}}
\]
\[
\underbrace{
\begin{pmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{pmatrix}
}_{\textrm{Ejemplo de \texttt{pmatrix}}}
\]
\[
\underbrace{
\begin{bmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{bmatrix}
}_{\textrm{Ejemplo de \texttt{bmatrix}}}
\]
\[
\underbrace{
\begin{Bmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{Bmatrix}
}_{\textrm{Ejemplo de \texttt{Bmatrix}}}
\]
\[
\underbrace{
\begin{vmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{vmatrix}
}_{\textrm{Ejemplo de \texttt{vmatrix}}}
\]
\[
\underbrace{
\begin{Vmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{Vmatrix}
}_{\textrm{Ejemplo de \texttt{Vmatrix}}}
\]
\[
\overbrace{\boxed{1+1}}^{\textrm{Ejemplo de boxed}}
\]
Integrales más atractivas con límites encima y debajo en vez de a la derecha
\[
\int\limits_{0}^{-10}{x \: dx}
\]
\[
\iint\limits_{0}^{-10}{x \: dx}
\]
\[
\iiint\limits_{0}^{-10}{x \: dx}
\]
\end{document}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Twitter</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header id="main-header">
<div class="content">
<nav>
<ul>
<li><img src="/images/home.svg" alt="Home"> Nome</li>
<li><img src="/images/notification.svg" alt="Home"> Notifications</li>
<li><img src="/images/message.svg" alt="Home"> Messages</li>
</ul>
</nav>
<img src="/images/logo.svg" alt="Logo Twitter">
<div class="side">
<input type="text" placeholder="Search on Twitter">
<img src="/images/avatar.png" alt="Avatar">
<button>Tweet</button>
</div>
</div>
</header>
<div class="banner">
<h1>Just a Twitter design</h1>
</div>
<div class="bar">
<div class="content">
<ul>
<li class="active">
<span>Tweets</span>
<strong>1234</strong>
</li>
<li>
<span>Followings</span>
<strong>1234</strong>
</li>
<li>
<span>Followers</span>
<strong>1234</strong>
</li>
<li>
<span>Favorites</span>
<strong>1234</strong>
</li>
</ul>
<div class="actions">
<button>Follow</button>
<img src="/images/more.svg" alt="More">
</div>
</div>
</div>
<div class="wrapper-content content">
<aside class="profile">
<img class="avatar" src="/images/avatar.png" alt="Tiago Marinho">
<h1>Tiago Marinho</h1>
<span>@Exibit</span>
<p>Web, Design, Lorem Ipsum</p>
<ul class="list">
<li><img src="/images/place.svg" alt="Place">Namur, Belgium</li>
<li><img src="/images/url.svg" alt="URL">exibit.be</li>
<li><img src="/images/joined.svg" alt="Joined">Joined June 2007</li>
<li><img src="/images/born.svg" alt="Born">Born the 7th of January 1997</li>
</ul>
<div class="widget followers">
<strong><img src="/images/followers.svg" alt="Followers">73 followers that you know</strong>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="widget images">
<strong><img src="/images/images.svg" alt="Images">266 Photos and videos</strong>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</aside>
<section class="timeline">
<nav>
<a href="" class="active">Tweets</a>
<a href="">Tweets and replies</a>
<a href="">Medias</a>
</nav>
<ul class="tweets">
<li>
<img src="/images/avatar.png" alt="Avatar">
<div class="info">
<strong>Tiago Marinho <span>@tiagomariinhoo</span></strong>
<p>Conteudo do tweet Conteudo do tweet Conteudo do tweet Conteudo do tweet Conteudo do tweet</p>
<div class="actions">
<a href=""><img src="/images/comments.svg" alt="Comments">4</a>
<a href=""><img src="/images/retweet.svg" alt="Retweet">5</a>
<a href=""><img src="/images/like.svg" alt="Like">6</a>
</div>
</div>
</li>
<li>
<img src="/images/avatar.png" alt="Avatar">
<div class="info">
<strong>Tiago Marinho <span>@tiagomariinhoo</span></strong>
<p>Conteudo do tweet Conteudo do tweet Conteudo do tweet Conteudo do tweet Conteudo do tweet</p>
<div class="actions">
<a href=""><img src="/images/comments.svg" alt="Comments">4</a>
<a href=""><img src="/images/retweet.svg" alt="Retweet">5</a>
<a href=""><img src="/images/like.svg" alt="Like">6</a>
</div>
</div>
</li>
</ul>
</section>
<aside class="widgets">
<div class="widget follow">
<div class="title">
<strong>Who to follow</strong>
<a href="" class="">Refresh</a>
<a href="" class="">View All</a>
</div>
<ul>
<li>
<div class="profile">
<img src="/images/avatar.png" alt="Avatar">
<div class="info">
<strong>Spade <span>@spade_be</span></strong>
<button>Follow</button>
</div>
</div>
<a href="" class="">x</a>
</li>
<li>
<div class="profile">
<img src="/images/avatar.png" alt="Avatar">
<div class="info">
<strong>Spade <span>@spade_be</span></strong>
<button>Follow</button>
</div>
</div>
<a href="" class="">x</a>
</li>
<li>
<div class="profile">
<img src="/images/avatar.png" alt="Avatar">
<div class="info">
<strong>Spade <span>@spade_be</span></strong>
<button>Follow</button>
</div>
</div>
<a href="" class="">x</a>
</li>
</ul>
</div>
<div class="widget trends"></div>
</aside>
</div>
</body>
</html>
|
import {Injectable} from '@angular/core';
import {Observable} from "rxjs";
import {environment} from "../../environments/environment.prod";
import {HttpClient} from "@angular/common/http";
import {Comment} from "../model/Comment";
const COMMENT_API = environment.apiServerUrl + '/api/comment/';
@Injectable({
providedIn: 'root'
})
export class CommentService {
constructor(private http: HttpClient) {
}
getAllComments(articleId: string): Observable<Comment[]> {
return this.http.get<Comment[]>(COMMENT_API + articleId + '/all');
}
save(comment: Comment, articleId: string): Observable<Comment> {
return this.http.post<Comment>(COMMENT_API + articleId + '/add', comment);
}
deleteCommentById(id: string) {
return this.http.delete(COMMENT_API + 'delete/' + id);
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>Gráfico de Radiación con D3.js</title>
<!-- Agrega las referencias a Bootstrap y jQuery -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- Agrega la referencia a D3.js -->
<style>
.loader {
/* Estilos anteriores... */
display: flex;
flex-direction: column;
}
.loader img {
display: block;
margin: 0 auto; /* Centra la imagen */
}
.loader p {
margin-top: 10px; /* Ajusta el margen superior del párrafo */
text-align: center; /* Centra el texto horizontalmente */
font-weight: bold; /* Opcional: Añade negrita al texto */
}
/* Oculta el contenido principal al principio */
#mainContent {
display: none;
}
.resize-image {
/* Ajusta el tamaño de la imagen */
width: 50%; /* Puedes cambiar este valor según tu preferencia */
height: auto; /* Para mantener la proporción de la imagen */
}
.title {
font-size: 2em;
text-align: center;
}
.resize-image-small {
width: 200px; /* Define el ancho deseado */
height: auto; /* Mantén la proporción */
}
.blue-text {
color: #06a0e3;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="loader" class="loader">
<img src="http://localhost:8080/sol.gif" alt="Cargando...">
<p>Cargando datos...</p>
</div>
<div id="mainContent" style="display: none;">
<button class="btn btn-primary mt-3" onclick="goBack()">Regresar</button>
<h1 class="title blue-text">MEDICIONES MENSUALES <img src="http://localhost:8080/solazul.png" alt="Foto" class="resize-image-small"></h1>
<div class="container mt-4">
<div class="container mt-4">
<div class="row">
<div class="col">
<label for="mes" class="blue-text">SELECTOR DEL MES:</label>
<input type="month" class="form-control" id="mes" value="2023-07">
<button class="btn btn-primary mt-3" onclick="capturarMes()">Capturar Mes</button>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="card mt-3">
<div class="card-body">
<h5 class="card-title blue-text">IRRADIANCIA MAXIMA MENSUAL :</h5>
<p class="card-text blue-text" id="irradiacionmensual">...</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card mt-3">
<div class="card-body">
<h5 class="card-title blue-text">PROMEDIO IRRADIANCIA MENSUAL:</h5>
<p class="card-text blue-text" id="resultadopromedio">...</p>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function goBack() {
window.history.back();
}
function capturarMes() {
var mesSeleccionado = document.getElementById('mes').value;
console.log(mesSeleccionado)
document.getElementById('loader').style.display = 'block';
document.getElementById('loader').querySelector('p').innerText = 'Consultando a la base de datos...';
document.getElementById('mainContent').style.display = 'none';
const baseURL = 'http://localhost:8080';
const partes = mesSeleccionado.split("-");
const endpoint = '/radiacionmaximapormes';
const url = new URL(endpoint, baseURL);
url.searchParams.append('anio', parseInt(partes[0], 10));
url.searchParams.append('mes', parseInt(partes[1], 10));
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('La solicitud no fue exitosa');
}
return response.json(); // Procesa la respuesta como JSON
})
.then(data => {
const irradiacionmensual = document.getElementById('irradiacionmensual');
irradiacionmensual.innerHTML = `<strong>${data}</strong> Watts por metro2`;
console.log('Datos recibidos:', data);
})
.catch(error => {
// Manejo de errores
console.error('Error al realizar la solicitud:', error);
});
//segunda cosnulta
const endpoint1 = '/irradiacionPromedio';
const url1 = new URL(endpoint1, baseURL);
url1.searchParams.append('anio', parseInt(partes[0], 10));
url1.searchParams.append('mes', parseInt(partes[1], 10));
fetch(url1)
.then(response => {
if (!response.ok) {
throw new Error('La solicitud no fue exitosa');
}
return response.json(); // Procesa la respuesta como JSON
})
.then(data => {
const irradiacionmensual = document.getElementById('resultadopromedio');
irradiacionmensual.innerHTML = `<strong>${data}</strong> Watts por metro2`;
console.log('Datos recibidos:', data);
document.getElementById('loader').style.display = 'none';
// Muestra el contenido principal
document.getElementById('mainContent').style.display = 'block';
console.log("Termino de cargar datos ");
})
.catch(error => {
// Manejo de errores
console.error('Error al realizar la solicitud:', error);
});
}
document.getElementById('loader').style.display = 'none';
// Muestra el contenido principal
document.getElementById('mainContent').style.display = 'block';
console.log("Termino de cargar datos ");
</script>
</body>
</html>
|
#include <Arduino.h>
#include <RcLedConf.h>
#include <EasyBuzzer.h>
#include <LedManager.h>
#include <EffectManager.h>
#include <Radio.h>
LedManager* ledManager = nullptr;
EffectManager* effectManager = nullptr;
bool backwardNotif = false;
void backward()
{
if(!backwardNotif)
{
ledManager->setBackwardLedsState(true);
if(!effectManager->specialEffectHasSound())
{ // Use squence number = 0 for infinite sequence
// Pause duration must not be 0 (infinite beep) so we set off duration at 0 and pause duration at 500 ms
EasyBuzzer.beep(880,500,0,1,500,0);
}
backwardNotif = true;
}
}
void stopBackward()
{
if(backwardNotif)
{
ledManager->setBackwardLedsState(false);
if(!effectManager->specialEffectHasSound()) EasyBuzzer.stop();
backwardNotif = false;
}
}
bool stopNotif = false;
void braking()
{
if(!stopNotif)
{
ledManager->setStopLedsState(true);
stopNotif = true;
}
}
void stopBraking()
{
if(stopNotif)
{
ledManager->setStopLedsState(false);
stopNotif = false;
}
}
#define BLINK_TIME 500 // 500 ms
unsigned long lastBlinkTime;
bool lastBlinkState = false;
bool blinkingLeft = false;
bool blinkingRight = false;
void blinkLeft(bool on)
{
if(on)
{
blinkingLeft = true;
unsigned long now = millis();
if(now-lastBlinkTime > BLINK_TIME)
{
lastBlinkTime = now;
lastBlinkState = !lastBlinkState;
ledManager->setLeftLedsState(lastBlinkState);
if(!backwardNotif && !effectManager->specialEffectHasSound()) lastBlinkState ? EasyBuzzer.singleBeep(880,50) : EasyBuzzer.singleBeep(440,50);
}
}
else if(blinkingLeft)
{
ledManager->setLeftLedsState(false);
blinkingLeft = false;
lastBlinkState = false;
lastBlinkTime = 0;
}
}
void blinkRight(bool on)
{
if(on)
{
blinkingRight = true;
unsigned long now = millis();
if(now-lastBlinkTime > BLINK_TIME)
{
lastBlinkTime = now;
lastBlinkState = !lastBlinkState;
ledManager->setRightLedsState(lastBlinkState);
if(!backwardNotif && !effectManager->specialEffectHasSound()) lastBlinkState ? EasyBuzzer.singleBeep(880,50) : EasyBuzzer.singleBeep(440,50);
}
}
else if(blinkingRight)
{
ledManager->setRightLedsState(false);
blinkingRight = false;
lastBlinkState = false;
lastBlinkTime = 0;
}
}
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
EasyBuzzer.setPin(BUZZER_PIN);
ledManager = LedManager::getLedManager();
ledManager->init();
EasyBuzzer.singleBeep(440,500);
ledManager->colorWipe(LedManager::Strip::STRIP_2,LedManager::BLACK,0); // Turn off back leds
effectManager = EffectManager::getEffectManager();
effectManager->init(ledManager);
radioInit(effectManager);
#ifdef SERIAL_OUT
Serial.begin(115200);
Serial.println("Démarrage RC LED !");
#endif
}
// Button detection
boolean oldButtonState = HIGH;
void loop() {
// Gestion du buzzer
EasyBuzzer.update();
// Animation des yeux et effets speciaux
effectManager->updateEffects();
// Traitement du signal radio
radioProcessSignal();
switch(radioGetChannel1State())
{
case LEFT :
blinkRight(false);
blinkLeft(true);
break;
case RIGHT :
blinkLeft(false);
blinkRight(true);
break;
case CENTER :
default :
blinkLeft(false);
blinkRight(false);
break;
}
MotionState motionState = radioGetMotionState();
if(motionState == BRAKE)
{
braking();
}
else
{
stopBraking();
}
if(motionState == BACK)
{
backward();
}
else
{
stopBackward();
}
// Get current button state.
boolean newButtonState = digitalRead(BUTTON_PIN);
// Check if state changed from high to low (button press).
if((newButtonState == LOW) && (oldButtonState == HIGH)) {
// Short delay to debounce button.
delay(20);
// Check if button is still low after debounce.
newButtonState = digitalRead(BUTTON_PIN);
if(newButtonState == LOW) { // Yes, still low
//Serial.println("Change special effect !");
effectManager->changeSpecialEffect(true);
}
}
// Set the last-read button state to the old state.
oldButtonState = newButtonState;
}
|
<template>
<div class="registerhome" >
<el-card class="registercard">
<div slot="header">
<span style="font-weight: bold;font-size: larger">注册</span>
<el-button type="primary" size="medium" @click="tologin" style="float: right">登入</el-button>
</div>
<el-form ref="Registerform"
:model="RegisterformData"
label-width="90px"
:rules="registerVaild"
status-icon
:hide-required-asterisk="false"
label-position="left">
<el-form-item label="用户名" class="registeritem" prop="username">
<el-input v-model="RegisterformData.username" class="registerinput"></el-input>
</el-form-item>
<el-form-item label="密码" class="registeritem" prop="password">
<el-input type="password" v-model="RegisterformData.password" class="registerinput"></el-input>
</el-form-item>
<el-form-item label="确认密码" class="registeritem" prop="password2">
<el-input type="password" v-model="RegisterformData.password2" class="registerinput"></el-input>
</el-form-item>
<el-form-item label="sip工位号" class="registeritem" prop="station">
<el-input v-model="RegisterformData.station" class="registerinput"></el-input>
</el-form-item>
<el-form-item label="邮箱" class="registeritem" >
<el-input v-model="RegisterformData.email" class="registerinput"></el-input>
</el-form-item>
<el-form-item label="电话" class="registeritem" >
<el-input v-model="RegisterformData.mobile" class="registerinput"></el-input>
</el-form-item>
<el-form-item>
<el-button type="success" size="medium" @click="registeruser">注册</el-button>
</el-form-item>
</el-form>
</el-card>
</div>
</template>
<script>
export default {
name: "Register",
data() {
let vailidUsername=async (rule, value, callback)=>{
var req= await this.axios.get("/isusername",{params:{username:this.RegisterformData.username}})
this.isRegisterusername=req.data
console.log("返回对象"+ this.isRegisterusername)
if (value==='')
{
callback(new Error("不能为空"))
}
else if (this.isRegisterusername)
{
callback(new Error("用户名已注册"))
}
else {
callback()
}
}
let validPassword2 = (rule, value, callback) => {
if (value === '') {
callback(new Error('请再次输入密码'));
} else if (value !== this.RegisterformData.password) {
callback(new Error('两次输入密码不一致!'));
} else {
callback();
}
}
let validEmail= (rule,value,callback)=>{
let emailformat=/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
/* if (value==='')
{
callback(new Error("不能为空"))
}*/
if (!emailformat.test(value))
{
callback(new Error("输入邮箱格式不正确"))
}
else
{
callback()
}
}
return {
isRegisterusername:true,
RegisterformData :{
username: "",
password: "",
password2: "",
station:"",
email: "",
mobile: ""
},
registerVaild: {
username: [{validator:vailidUsername,trigger:'blur'}],
password: [{ min: 6, max: 12, message: '长度在 6到 12 个字符', trigger: 'blur' },
{required: true, message: '不能为空', trigger: 'blur'}],
password2: [{validator: validPassword2, trigger: 'blur' }],
station:[{required: true, message: '不能为空', trigger: 'blur'}],
email: [{validator: validEmail, trigger: 'blur' }],
}
}
},
methods: {
registeruser(){
if (!this.isRegisterusername) {
this.axios.post("/registerUser", this.RegisterformData)
.then(req => {
if (req.data === "success") {
this.$message.success("注册成功")
this.$router.push("/")
}
})
}
},
tologin()
{
this.$router.push("/")
}
},
}
</script>
<style scoped>
.registercard{
width: 25%;
float: left;
margin: 13% auto auto 35%;
}
.registerinput{
width: 70%;
float: left;
}
.registeritem{
margin: auto auto 15px 20%;
}
.registerhome{
height: 100%;
width: 100%;
margin: 0 0;
background-image: url("../assets/register.jpg");
background-size: cover;
}
</style>
|
# DUOSoftHardwareTokens
[](https://opensource.org/licenses/Apache-2.0)
## Overview
DUOSoftHardwareTokens is a script that creates soft hardware tokens (TOTP) for DUO security and imports them to Duo via the Duo Admin API.
From the script output, you can import the soft hardware tokens (TOTP) into apps such as Google Authenticator and Microsoft Authenticator or into a password database like Keeper.
## Prerequisites
- Duo Admin API details with `Grant write resource` permission.
- Setup instructions for the Duo Admin API can be [found here](https://duo.com/docs/adminapi).
## Installation / Download
### Download from Github
``` powershell
Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/dylanmccrimmon/DUOSoftHardwareTokens/main/DUOSoftHardwareTokens.ps1' -OutFile 'DUOSoftHardwareTokens.ps1'
```
## Examples
### Default
``` powershell
DUOSoftHardwareTokens.ps1 -DUOAPIHostName 'api-XXXXX.duosecurity.com' -DUOAPIIntegrationKey 'XXXXXXXX' -DUOAPISecretKey 'XXXXXXXXXXXXXX'
QR Code Link: https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=otpauth://totp/DUOHardwareToken(999-36507284)?secret=EGXNGO5GGUT542UTAIITH646MDXSKD6H&issuer=DUOSoftHardwareTokens&algorithm=SHA1&digits=6&period=30
Please enter the TOTP code displayed in your auth app? [OTP or Q to quit]: 458850
TOTP is correct. Authenticator application seems to be working correctly
Token data successfully sent to Duo. You can now manage the token in the Duo admin dashboard.
```
### Skip TOTP user verification
``` powershell
DUOSoftHardwareTokens.ps1 -DUOAPIHostName 'api-XXXXX.duosecurity.com' -DUOAPIIntegrationKey 'XXXXXXXX' -DUOAPISecretKey 'XXXXXXXXXXXXXX' -SkipTOTPUserVerification
QR Code Link: https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=otpauth://totp/DUOHardwareToken(999-21870497)?secret=MDF2V6FGYMVAID2DTDMI3PKR3NNXGVLJ&issuer=DUOSoftHardwareTokens&algorithm=SHA1&digits=6&period=30
Token data successfully sent to Duo. You can now manage the token in the Duo admin dashboard.
```
### Output TOTP data
``` powershell
DUOSoftHardwareTokens.ps1 -DUOAPIHostName 'api-XXXXX.duosecurity.com' -DUOAPIIntegrationKey 'XXXXXXXX' -DUOAPISecretKey 'XXXXXXXXXXXXXX' -OutputTOTPData
QR Code Link: https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=otpauth://totp/DUOHardwareToken(999-52107829)?secret=KRCGNX3MLGMTGLRW5KJIFIS4HSGM4IQP&issuer=DUOSoftHardwareTokens&algorithm=SHA1&digits=6&period=30
Issuer : DUOHardwareTokens
Account : DUOHardwareToken(999-52107829)
Secret : KRCGNX3MLGMTGLRW5KJIFIS4HSGM4IQP
Algorithm : HMAC-SHA-1
Digits : 6
Period : 30
Please enter the TOTP code displayed in your auth app? [OTP or Q to quit]: 984395
TOTP is correct. Authenticator application seems to be working correctly
Token data successfully sent to Duo. You can now manage the token in the Duo admin dashboard.
```
## Syntax
``` powershell
DUOSoftHardwareTokens.ps1
[[-DUOAPIHostName] <String>]
[[-DUOAPIIntegrationKey] <String>]
[[-DUOAPISecretKey] <String>]
[[-TOTPPeriod] <Int16>]
[[-TOTPDigits] <Int16>]
[-SkipTOTPUserVerification]
[-SkipTOTPQRCodeLink]
[-OutputTOTPData]
[<CommonParameters>]
```
## Parameters
### -DUOAPIHostName
Specifies the DUO API host name to use.
```yaml
Type: String
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DUOAPIIntegrationKey
Specifies the DUO API intergration key.
```yaml
Type: String
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DUOAPISecretKey
Specifies the DUO API secret key.
```yaml
Type: String
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -TOTPPeriod
Specifies the TOTP period.
```yaml
Type: Int16
Accepted values: 30, 60
Required: False
Position: Named
Default value: 30
Accept pipeline input: False
Accept wildcard characters: False
```
### -TOTPDigits
Specifies the TOTP digits.
```yaml
Type: Int16
Accepted values: 6, 8
Required: False
Position: Named
Default value: 6
Accept pipeline input: False
Accept wildcard characters: False
```
### -SkipTOTPUserVerification
Specifies if the script should skip the user verification of the TOTP code.
```yaml
Type: Switch
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -SkipTOTPQRCodeLink
Specifies if the script should skip displaying the QR Code link.
```yaml
Type: Switch
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -OutputTOTPData
Specifies if the script should output PSCustomObject of the TOTP data.
```yaml
Type: Switch
Required: False
Position: Named
Default value: True
Accept pipeline input: False
Accept wildcard characters: False
```
## License
[Apache-2.0](https://choosealicense.com/licenses/apache-2.0/)
|
import React from "react";
import { Navigate } from "react-router";
import { FormattedMessage, useIntl } from "react-intl";
import { useSelector } from "react-redux";
import { sendPasswordRecoveryRequest } from "../../../services/api/sendPasswordRecoveryRequest";
import { StepsList } from "../StepsList";
import { SmsForm } from "../../../components/SmsForm";
import { PassportNumberForm } from "../PassportNumberForm";
import "./PasswordRecoveryPageBodyStyles.css";
import {
selectCode,
selectPassportNum,
} from "../../../redux/selectors/userSelectors";
import { PasswordForm } from "../../../components/PasswordForm";
type RecoveryFormProps = {
activeStep: number;
incrementStep: () => void;
};
export const RecoveryForm: React.FC<RecoveryFormProps> = ({
activeStep,
incrementStep,
}) => {
const intl = useIntl();
const passportNumber = useSelector(selectPassportNum);
const verificationCode = useSelector(selectCode);
const onSuccessSubmit = (newPassword: string) => {
const passwordRecoveryInformation = {
newPassword,
confirmPassword: newPassword,
passportNumber,
verificationCode,
};
sendPasswordRecoveryRequest(passwordRecoveryInformation).then(
incrementStep
);
};
return (
<div className="recovery-form-body-wrapper">
{activeStep !== 3 && (
<div className="recovery-form-header-wrapper">
<h1>
<FormattedMessage id="passRecovery" />
</h1>
<div className="recovery-form-body_progress_bar">
<ul className="recovery-form-body_list">
<StepsList
steps={[
intl.formatMessage({ id: "enterPassportNumber" }),
intl.formatMessage({ id: "enterSmsCode" }),
intl.formatMessage({ id: "enterPassword" }),
]}
activeStep={activeStep}
/>
</ul>
</div>
</div>
)}
<div className="recovery-form-content-container">
<div className="recovery-form-content-wrapper">
<div className="content-input">
{activeStep < 0 ? (
<Navigate to="/" />
) : activeStep === 0 ? (
<PassportNumberForm onSuccessSubmit={incrementStep} />
) : activeStep === 1 ? (
<SmsForm onSuccessSubmit={incrementStep} />
) : activeStep === 2 ? (
<PasswordForm onSuccessSubmit={onSuccessSubmit} />
) : null}
</div>
</div>
</div>
</div>
);
};
|
@extends('admin.layouts.app')
@section('title', $title)
@section('breadcrumb')
<script type="text/javascript">
mn_selected = 'mn_courses';
</script>
<ol class="breadcrumb">
<li><a href="{{ route('admin-home') }}"><i class="fa fa-home"></i> {{ __('common.home') }}</a></li>
<li>{{ __('courses.list') }}</li>
</ol>
@stop
@section('content')
<div class="card">
<div class="card-header container-fluid d-flex justify-content-between">
<h3 class="box-title">{{ $title }}</h3>
<div class="box-action pull-right">
<ul class="d-flex mb-0">
<li class="mr-2"><a href="{{ route(\App\Models\Course::CREATE) }}" class="btn btn-primary mr-1"><i
class="fa fa-plus-square"></i> {{ __('common.create') }}</a></li>
<li><a href="{{ route(\App\Models\Course::LIST) }}" class="btn btn-default"><i
class="fa fa-refresh"></i> {{ __('common.reload') }}</a></li>
</ul>
</div>
</div>
<div class="card-body container-fluid pt-4 px-4">
<div class="row g-4">
<div class="box-search-table pull-right d-flex justify-content-between mt-2">
<div class="box-delete_multi pull-left">
{{-- <a href="javascript:;" id="btn-delete-all" data-routes="/admin/roles/destroy" class="btn btn-danger"><i class="fa fa-trash-o"></i> {{__('common.delete_all')}}</a> --}}
</div>
<div class="row">
<div class="col-6">
<div class="select_course">
<select name="category_course" id="category_course" class="form-control search-selecte-category bg-white">
<option value="">{{ __('common.choose') }}</option>
@foreach ($category_course as $category)
<option
{{ isset($_GET['category_course']) && $_GET['category_course'] == $category->id ? 'selected' : '' }}
value="{{ $category->id }}">{{ $category->title }}</option>
@endforeach
</select>
</div>
</div>
<div class="col-6">
<div>
{!! Form::open([
'url' => route(\App\Models\Course::LIST),
'id' => 'form-search',
'method' => 'GET',
'class' => 'd-flex',
]) !!}
{!! Form::text('search', Request::get('search'), [
'class' => 'form-control form-inline',
'maxlength' => 50,
'id' => 'input_source',
'placeholder' => __('common.keyword'),
'autocomplete' => 'off',
]) !!}
<button class="btn btn-primary ml-2" type="submit"><i class="fa fa-search"></i></button>
{!! Form::hidden('numpaging', Request::get('numpaging')) !!}
{!! Form::hidden('paging', Request::get('paging')) !!}
{!! Form::hidden('category_course', Request::get('category_course')) !!}
{!! Form::close() !!}
</div>
</div>
</div>
</div>
<table class="table table-striped mt-2" id="table-main">
<thead>
<tr>
<th class="w_30">{{ __('common.stt') }}</th>
<th class="w_100 text-center">{!! __('courses.image') !!}</th>
<th>{!! sort_title('title', __('courses.title')) !!}</th>
<th class="w_200">{!! sort_title('category', __('courses.category')) !!}</th>
<th class="w_200">{!! sort_title('time', __('courses.time')) !!}</th>
<th class="w_100">{!! sort_title('is_visible', __('common.status')) !!}</th>
<th class="w_130">{{ __('common.action') }}</th>
</tr>
</thead>
<tbody>
@if (!$courses->isEmpty())
@php
$no = ($courses->currentPage() - 1) * $courses->perPage() + 1;
@endphp
@foreach ($courses as $key => $value)
<tr>
<td class="text-center align-middle">{{ $no++ }}</td>
<td class="w_100 text-center"><img src="{{ $value->image_url }}" width="100%"
height="60px"></td>
<td class="align-middle">{{ \Illuminate\Support\Str::limit($value->title) }}</td>
<td class="align-middle">{{ $value->course_categories->title }}</td>
<td class="align-middle">{{ $value->time }}</td>
<td class="text-center w_100 align-middle">
@if ($value->status)
<div class="form-check form-switch">
<input class="form-check-input is_visible" type="checkbox" role="switch"
id="is_visible_{{ $value->id }}" data-id="{{ $value->id }}"
data-visible="{{ $value->is_visible }}" checked>
</div>
@else
<div class="form-check form-switch">
<input class="form-check-input is_visible" type="checkbox" role="switch"
id="is_visible_{{ $value->id }}" data-id="{{ $value->id }}"
data-visible="{{ $value->is_visible }}">
</div>
@endif
</td>
<td class="action align-middle text-center">
<a href="{{ route(\App\Models\Course::UPDATE, $value->id) }}"
class="btn btn-primary" title="{{ trans('common.edit') }}"><i
class="fa fa-edit"></i></a>
<a href="javascript:;"
onclick="deleteModal('{{ $value->id }}', '/admin/courses/destroy')"
title="{{ trans('common.delete') }}" class="btn btn-danger"><i
class="fa fa-trash-o"></i></a>
</td>
</tr>
@endforeach
@else
<tr>
<td colspan="7">{{ __('common.no_data') }}</td>
</tr>
@endif
</tbody>
</table>
<div class="footer-table row">
<div class="col-sm-6 d-flex">
<div class="box-numpaging">
{!! Form::select('numpaging', App\Libs\Constants::$list_numpaging, Request::get('numpaging'), [
'class' => 'form-control select',
'id' => 'selectNumpaging',
]) !!}
</div>
<span class="total-record ml-2">{!! __('common.total_data', ['total' => $courses->total()]) !!}</span>
</div>
<div class="col-sm-6">
<div class="pull-right">
{{ $courses->links('vendor/pagination/bootstrap-4') }}
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
@section('script')
@include('partials.numpaging')
<script type="text/javascript">
$(document).ready(function() {
$("#category_course").change(function(e) {
var search_keyWord = '{{Request::get('search')}}' ?? '';
location.href = '?search=' +search_keyWord+ '&category_course=' + $(this).val();
});
});
$(document).ready(function() {
$('.search-selecte-category').select2({
placeholder: "{{ __('common.choose') }}",
});
});
$(document).ready(function() {
$(".is_visible").click(function(e) {
let is_visible = $(this).data('visible');
let id = $(this).data('id');
var _url = "{{ route('courses.active') }}";
$.ajax({
url: _url,
type: 'POST',
data: {
id: id,
is_visible: is_visible
},
success: function(data, success) {
showNotificationActive(data.message);
}
});
})
});
</script>
@endsection
|
import express from 'express';
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import authRoute from './routes/auth.js';
import hotelsRoute from './routes/hotels.js';
import roomsRoute from './routes/rooms.js';
import usersRoute from './routes/users.js';
import cookieParser from 'cookie-parser';
const app = express();
dotenv.config();
const connect= async()=>{
try {
await mongoose.connect(process.env.MONGO);
console.log("Connected to MongoDB!");
} catch(error){
throw error;
}
};
mongoose.connection.on("disconnected", ()=>{
console.log("Disconnected from MongoDB!");
})
// app.get('/', (req,res)=>{
// res.send("Hello World!");
// })
//missleexpres
app.use(cookieParser())
app.use(express.json());
app.use("/api/auth", authRoute);
app.use("/api/users", usersRoute);
app.use("/api/hotels", hotelsRoute);
app.use("/api/rooms", roomsRoute);
app.use((err, req, res, next)=>{
const errorStatus = err.status || 500;
const errorMessage = err.message || "Something went wrong!";
return res.status(errorStatus).json({success: false,status:errorStatus, message: errorMessage,stack: err.stack});
});
app.listen(8800, ()=>{
connect()
console.log("Connected to backend!");
});
|
import { Injectable } from "@angular/core";
import { Page } from "../models/page.model.client";
// injecting service into module
@Injectable()
export class PageService {
pages: Page[] = [
{ _id: "321", name: "Post 1", websiteId: "456", title: "Lorem" },
{ _id: "432", name: "Post 2", websiteId: "456", title: "Lorem" },
{ _id: "543", name: "Post 3", websiteId: "456", title: "Lorem" }
];
createPage(page: Page) {
page._id = Math.random().toString();
this.pages.push(page);
return page;
}
findPagesByWebsiteId(websiteId: string) {
let result = [];
for (let i = 0; i < this.pages.length; i++) {
if (this.pages[i].websiteId === websiteId) {
result.push(this.pages[i]);
}
}
return result;
}
findPageById(pageId: string) {
for (let i = 0; i < this.pages.length; i++) {
if (pageId === this.pages[i]._id) {
return this.pages[i];
}
}
}
updatePage(page: Page) {
const oldPage = this.findPageById(page._id);
const index = this.pages.indexOf(oldPage);
this.pages[index] = page;
}
deletePage(pageId: string) {
const oldPage = this.findPageById(pageId);
const index = this.pages.indexOf(oldPage);
this.pages.splice(index, 1);
}
}
|
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ChartsModule } from 'ng2-charts';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { AuthModule } from '@auth0/auth0-angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './partials/header/header.component';
import { FooterComponent } from './partials/footer/footer.component';
import { NavbarIndexComponent } from './partials/navbar-index/navbar-index.component';
import { IndexComponent } from './views/index/index.component';
import { DashboardModule } from './module/dashboard/dashboard.module';
import { PageNotFoundComponent } from './views/page-not-found/page-not-found.component';
import { IndexCarouselComponent } from './partials/index-carousel/index-carousel.component';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NavbarIndexComponent,
IndexComponent,
PageNotFoundComponent,
IndexCarouselComponent,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
FormsModule,
DashboardModule,
ChartsModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
}),
AuthModule.forRoot({
domain: 'tunegocio.us.auth0.com',
clientId: '6Nk6ueM27Am4htjttAMteQDeoSex93jl'
}),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
<h1 align="center">
Poghota App
</h1>
<p align="center">
<img src="https://github.com/solidados/poghota-city-life/assets/81189948/e785ab2d-c45b-4182-9bdb-e98505ace8ab" alt="logo" width="180" />
</p>
<p align="center"><i>city-life</i></p>
<h3 align="center">
Tumo labs project for city life
</h3>
## Overview
To start the project:
- clone, copy ZIP or fork this repo
- goto `root` folder and install all dependencies:
> `$ cd <project folder>`
`$ pip install requirements.txt`
`$ python3 app.py`
> This must show that the server runs on localhost:5000
- goto `frontend` folder and install all dependencies:
> `$ cd <project folder>/frontend`
`$ npm install`
`$ npm start`
`localhost:3000` will be opened in new web browser's tab
## Technology Stack
> The 'Poghota' project is an application built using the following technology stack:
### Frontend:
**[React](https://react.dev/reference/react)**: Application is based on this JS library
**[Prettier](https://www.npmjs.com/package/prettier)**: An opinionated code formatter that ensures consistent code
style across the project.
**[ESLint](https://www.npmjs.com/package/eslint)**: A JavaScript linter that identifies and enforces coding patterns
and best practices.
**[Husky](https://www.npmjs.com/package/husky)**: A Git hook manager used to trigger scripts on pre-commit and
pre-push actions.
**[lint-staged](https://www.npmjs.com/package/lint-staged)**: A tool that runs linters on staged
files to enforce code quality before committing.
**[date-fns](https://www.npmjs.com/package/date-fns)**: Plugin that provides the most comprehensive, yet simple and
consistent toolset for manipulating `JavaScript` dates in a browser & `Node.js`
### Backend:
**[Flask](https://flask.palletsprojects.com/en/3.0.x/)**: Web framework written in Python for building the application.
**[MongoDB](https://www.mongodb.com/docs/)**: Application Stores Information in the following database
**[Flask_CORS](https://flask-cors.readthedocs.io/en/latest/)**: Cross-Origin Resource Sharing extension for handling cross-origin requests.
**[Flask_PyMongo](https://flask-pymongo.readthedocs.io/en/latest/)**: Flask extension for interacting with MongoDB.
**[jwt](https://jwt.io/introduction)**: JSON Web Token library for creating and verifying tokens.
**[werkzeug.security](https://werkzeug.palletsprojects.com/en/3.0.x/)**: Provides password hashing and checking utilities.
**[dotenv](https://pypi.org/project/python-dotenv/)**: Loads environment variables from a `.env` file
## Setting up and Running the Project Locally
### Prerequisites
Before you begin, ensure that you have the following software installed on your machine:
1. Node.js (v14.x or higher)
2. npm (Node Package Manager) or yarn
3. Python 3.11
### Clone the Repository
1. Open your terminal or command prompt.
2. Change the current working directory to the location where you want to clone the project.
3. Run the following command to clone the repository:
> `git clone https://github.com/<your-username>/poghota-city-life.git`
Replace `<your-username>` with your actual GitHub username.
4. Change into the project directory:
> `cd poghota-city-life`
### Install Dependencies
1. After navigating to the project directory, install the required dependencies using npm or yarn:\
Using npm:`npm install`\
Using yarn:`yarn install`
2. Install the necessary requirements from the `requirements.txt` file
Using pip: `pip install requirements.txt`
### Build the Project
1. To build the project, run the following command:\
Using npm:`npm run build`\
Using yarn:`yarn build`
### Start the Development Server
1. To view the application in your browser, use the following command:\
Using npm:`npm start`\
Using yarn:`yarn start`
2. To start the development server, use the following command:
`python3 app.py`
This will start the development server at `http://localhost:5000/`, and the application will be accessible at `http://localhost:3000/`.
|
import java.util.ArrayList;
public class Bank {
private String name;
private ArrayList<Branch> branches;
public Bank(String name) {
this.name = name;
this.branches = new ArrayList<Branch>();
}
public boolean addBranch(String branchName){
if (findBranch(branchName) == null) {
this.branches.add(new Branch(branchName));
return true;
}
return false;
}
public boolean addCustomer(String branchName, String customerName, double initialAmount) {
Branch branch = findBranch(branchName);
if (branch != null) {
return branch.newCustomer(customerName,initialAmount);
}
return false;
}
public boolean addCustomerTransaction(String branchName, String customerName, double amount){
Branch branch = findBranch(branchName);
if (branch != null) {
return branch.addCustomerTransaction(customerName, amount);
}
return false;
}
private Branch findBranch(String branchName){
for (int i=0; i<this.branches.size(); i++){
Branch checkedBranch = this.branches.get(i);
if (checkedBranch.getName().equals(branchName)){
return checkedBranch;
}
}
return null;
}
public boolean listCustomers(String branchName, boolean showTransactions){
Branch branch = findBranch(branchName);
if (branch != null){
System.out.println("Customer details for branch " + branch.getName());
ArrayList<Customer> branchCustomers = branch.getCustomers();
for (int i=0; i<branchCustomers.size(); i++){
Customer branchCustomer = branchCustomers.get(i);
System.out.println("Customer: " + branchCustomer.getName() + "" +
"[" + (i+1) + "]");
if (showTransactions){
System.out.println("Transactions");
ArrayList<Double> transactions = branchCustomer.getTransactions();
for (int j=0; j< transactions.size(); j++){
System.out.println("[" + (j+1) + "] Amount " +transactions.get(j));
}
}
}
return true;
} else {
return false;
}
}
}
|
import React, {EffectCallback, FunctionComponent, Key, useEffect, useState} from "react";
import useUsers from "../custom_hooks/useUsers";
import { GridWrapper } from "./UserResultsStyles";
import { Spinner } from "../../assets/Spinner";
import { UserItem } from "../user_item/UserItem";
import { SetState } from "../../types/state/stateTypes";
interface Props {
searchResults: string
};
export const UserResults: FunctionComponent<Props> = (props:Props): JSX.Element => {
const [users, setUsers]: [object[], SetState<[]>] = useUsers(props.searchResults);
const [isLoading, setIsLoading]: [boolean, SetState<boolean>] = useState(true);
const initState: EffectCallback = () =>
setIsLoading(false);
// useEffect(initState,[]);
useEffect(() => {
initState();
},[users]);
const userList: JSX.Element[] =
users.map((user: any, index: Key) => <UserItem key={user["id"]} user={user}/>);
// if(users.length === 0){
// return <div style={{color:"blue"}}>user not found</div>
// }
//////////
return isLoading || users.length === 0 ?
<Spinner/>
:
<GridWrapper isLoading = {isLoading}>
{userList}
</GridWrapper>
};
|
package com.lin.basic.oop;
/**
* @program: Java
* @description: 递归循环测试
* @author: linsz
* @create: 2022-06-04 00:10
**/
public class RecursionDemo {
public static void main(String[] args) {
System.out.println(getSumWithFor()); //5050
System.out.println(getSumWithRecursion(100)); //5050
}
//1.计算1~100的和 for循环
public static int getSumWithFor() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
return sum;
}
//2. 递归实现
public static int getSumWithRecursion(int n) {
if (n == 1) {
return 1;
} else {
return n + getSumWithRecursion(n - 1);
}
}
}
|
package environment
import (
"net/http"
"bunnyshell.com/cli/pkg/api"
"bunnyshell.com/cli/pkg/api/common"
"bunnyshell.com/cli/pkg/lib"
"bunnyshell.com/sdk"
"github.com/spf13/pflag"
)
type StartOptions struct {
common.PartialActionOptions
WithDependencies bool
}
func NewStartOptions(id string) *StartOptions {
return &StartOptions{
PartialActionOptions: *common.NewPartialActionOptions(id),
}
}
func (options *StartOptions) UpdateFlagSet(flags *pflag.FlagSet) {
options.PartialActionOptions.UpdateFlagSet(flags)
flags.BoolVar(&options.WithDependencies, "with-dependencies", options.WithDependencies, "Start the component dependencies too.")
}
func Start(options *StartOptions) (*sdk.EventItem, error) {
model, resp, err := StartRaw(options)
if err != nil {
return nil, api.ParseError(resp, err)
}
return model, nil
}
func StartRaw(options *StartOptions) (*sdk.EventItem, *http.Response, error) {
profile := options.GetProfile()
ctx, cancel := lib.GetContextFromProfile(profile)
defer cancel()
isPartialAction := options.IsPartial()
request := lib.GetAPIFromProfile(profile).EnvironmentAPI.EnvironmentStart(ctx, options.ID).
EnvironmentPartialStartAction(sdk.EnvironmentPartialStartAction{
IsPartial: &isPartialAction,
Components: options.GetActionComponents(),
WithDependencies: &options.WithDependencies,
})
return request.Execute()
}
|
import fastify from "fastify";
import queryDb from "./queryDb.js";
import spawn from "child_process";
const fastifyClient = fastify({
logger: true
});
fastifyClient.post('/suggestions', {
schema: {
body: {
type: 'object',
additionalProperties: true
},
response: {
200: {
type: 'object',
properties: {
success: { type: 'boolean' },
data: {
type: 'array',
additionalProperties: true
}
}
}
}
}
}, async (request, reply) => {
const data = request.body;
let questions = parseQuestions(data.questions);
const questionsString = JSON.stringify(questions);
console.log(questions);
const py = spawn.spawnSync('python3', ['pythonTest.py'], {
input: questionsString,
encoding: 'utf-8'
});
const dataString = py.stdout;
let pythonResult = JSON.parse(dataString);
console.log(pythonResult);
let symbolsToFetch = []
for (let match of pythonResult) {
symbolsToFetch.push([match[0], match[1]]);
}
symbolsToFetch = symbolsToFetch.sort((a, b) => a[1] - b[1]);
symbolsToFetch = symbolsToFetch.slice(0, 3);
const result = queryDb(symbolsToFetch);
console.log(result);
return returnCorrectResponse(result);
});
const answerMap = {
0: "A",
1: "B",
2: "C",
3: "D"
}
function parseQuestions(questionList) {
let result = [];
for (let i = 0; i < questionList.length; i++) {
let question = questionList[i].question;
let selectedChoice = question.choices
.map((choice, index) => {
return {
index: index,
isSelected: choice.selected
}
})
.filter((choice) => choice.isSelected)[0]
result.push({
"question_tag": question.tag,
"answer": answerMap[selectedChoice.index]
})
}
return result;
}
function drawChartPoints() {
let randomScalingFactor = function () {
return Math.round;
}
}
function returnCorrectResponse(data) {
return {
success: true,
data: data
}
}
const start = async () => {
try {
await fastifyClient.listen({ port: 9001, host: '0.0.0.0' }); // Corrected this line
fastifyClient.log.info(`Server running at ${fastifyClient.server.address().port}`);
} catch (err) {
fastifyClient.log.error(err);
process.exit(1);
}
};
start();
|
/**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
'use strict';
( function() {
CKEDITOR.plugins.add( 'uploadimage', {
requires: 'uploadwidget,autogrow',
onLoad: function() {
CKEDITOR.addCss(
'.cke_upload_uploading img{' +
'opacity: 0.3' +
'}'
);
},
init: function( editor ) {
if(!editor.ui || !editor.ui.space("top")) {
// Workaround for bug: https://dev.ckeditor.com/ticket/14610
editor.on( 'uiSpace', function( event ) {
if ( event.data.space != "top" )
return;
event.data.html += "<div />";
});
}
var config = editor.config
require(["SHARED/uiSelectImage", "SHARED/jquery"], function(UISelectImage, $){
if(editor.editable()) {
$(editor.editable().$).parent().on('dragover', function(e) {
if(e && e.originalEvent && e.originalEvent.dataTransfer
&& e.originalEvent.dataTransfer.types
&& e.originalEvent.dataTransfer.types.length
&& e.originalEvent.dataTransfer.types[0] == 'Files') {
$(this).addClass('dragEntered');
}
});
$(editor.editable().$).parent().on('dragleave', function(e) {
$(this).removeClass('dragEntered');
});
$(editor.editable().$).parent().on('drop', function(e) {
$(this).removeClass('dragEntered');
});
}
var uploadId = UISelectImage.generateUploadId();
config.uploadUrl = UISelectImage.getUploadURL(uploadId);
editor.on( 'fileUploadRequest', function(evt) {
// Prevent the default request handler.
evt.stop();
var fileLoader = evt.data.fileLoader,
formData = new FormData(),
xhr = fileLoader.xhr;
fileLoader.uploadId = uploadId;
fileLoader.thumbnailURL = UISelectImage.getThumbnailURL(uploadId);
fileLoader.uploadUrl = config.uploadUrl;
xhr.open( 'POST', fileLoader.uploadUrl, true );
formData.append( 'upload', fileLoader.file, fileLoader.fileName );
fileLoader.xhr.send( formData );
// Renew uploadId
uploadId = UISelectImage.generateUploadId();
config.uploadUrl = UISelectImage.getUploadURL(uploadId);
}, null, null, 4 );
editor.on( 'fileUploadResponse', function( evt ) {
// Prevent the default response handler.
evt.stop();
// Get XHR and response.
var data = evt.data,
xhr = data.fileLoader.xhr,
status = xhr.status;
if (status == 200) {
data.url = data.fileLoader.thumbnailURL;
} else {
// An error occurred during upload.
data.message = UISelectImage.getUploadingImageErrorMessage();
UISelectImage.abortUpload(data.fileLoader.uploadId);
evt.cancel();
}
if (editor.resizeEditor) {
editor.resizeEditor(editor);
}
});
})
// Do not execute this paste listener if it will not be possible to upload file.
if ( !CKEDITOR.plugins.clipboard.isFileApiSupported ) {
return;
}
var fileTools = CKEDITOR.fileTools,
uploadUrl = fileTools.getUploadUrl( editor.config, 'selectImage' );
if ( !uploadUrl ) {
CKEDITOR.error( 'uploadimage-config' );
return;
}
// Handle images which are available in the dataTransfer.
fileTools.addUploadWidget( editor, 'uploadimage', {
supportedTypes: /image\/(jpeg|png|gif|jpg)/,
uploadUrl: uploadUrl,
fileToElement: function() {
var root = (editor.editable ? editor.editable() : (editor.mode == 'wysiwyg' ? editor.document && editor.document.getBody() : editor.textarea ) );
// Remove placeholder class
if ( root.hasClass( 'placeholder' ) ) {
root.removeClass( 'placeholder' );
root.setHtml("");
}
var img = new CKEDITOR.dom.element( 'img' );
img.setAttribute( 'src', loadingImage );
return img;
},
parts: {
img: 'img'
},
onUploading: function( upload ) {
// Show the image during the upload.
this.parts.img.setAttribute( 'src', upload.data );
// Update CKEditor height
setTimeout(function() {
editor.execCommand( 'autogrow' );
}, 500);
},
onUploaded: function( upload ) {
this.replaceWith( '<img src="' + upload.url + '" />' );
if(editor.resizeEditor) {
editor.resizeEditor();
} else if(editor.resize) {
editor.resize();
}
setTimeout(function() {
editor.execCommand( 'autogrow' );
}, 500);
}
} );
// This means that we need to read them from the <img src="data:..."> elements.
editor.on( 'paste', function( evt ) {
// For performance reason do not parse data if it does not contain img tag and data attribute.
if ( !evt.data.dataValue.match( /<img[\s\S]+data:/i ) ) {
return;
}
var data = evt.data,
// Prevent XSS attacks.
tempDoc = document.implementation.createHTMLDocument( '' ),
temp = new CKEDITOR.dom.element( tempDoc.body ),
imgs, img, i;
// Without this isReadOnly will not works properly.
temp.data( 'cke-editable', 1 );
temp.appendHtml( data.dataValue );
imgs = temp.find( 'img' );
for ( i = 0; i < imgs.count(); i++ ) {
img = imgs.getItem( i );
// Image have to contain src=data:...
var isDataInSrc = img.getAttribute( 'src' ) && img.getAttribute( 'src' ).substring( 0, 5 ) == 'data:',
isRealObject = img.data( 'cke-realelement' ) === null;
// We are not uploading images in non-editable blocs and fake objects (http://dev.ckeditor.com/ticket/13003).
if ( isDataInSrc && isRealObject && !img.data( 'cke-upload-id' ) && !img.isReadOnly( 1 ) ) {
var loader = editor.uploadRepository.create( img.getAttribute( 'src' ) );
loader.upload( uploadUrl );
fileTools.markElement( img, 'uploadimage', loader.id );
fileTools.bindNotifications( editor, loader );
}
}
data.dataValue = temp.getHtml();
} );
}
} );
// jscs:disable maximumLineLength
// Black rectangle which is shown before image is loaded.
var loadingImage = 'data:image/gif;base64,R0lGODlhDgAOAIAAAAAAAP///yH5BAAAAAAALAAAAAAOAA4AAAIMhI+py+0Po5y02qsKADs=';
// jscs:enable maximumLineLength
/**
* The URL where images should be uploaded.
*
* @since 4.5
* @cfg {String} [imageUploadUrl='' (empty string = disabled)]
* @member CKEDITOR.config
*/
} )();
|
<div class="container">
<div class="mb-5 row">
<div class="col">
<mat-card class="mb-3">
<mat-card-content>
<div class="d-flex my-3">
<div class="w-50" i18n>User Count</div>
<div class="w-50">{{ userCount }}</div>
</div>
<div class="d-flex my-3">
<div class="w-50" i18n>Transaction Count</div>
<div class="w-50">
<ng-container *ngIf="transactionCount">
{{ transactionCount }} ({{ transactionCount / userCount | number
: '1.2-2' }} <span i18n>per User</span>)
</ng-container>
</div>
</div>
<div class="d-flex my-3">
<div class="w-50" i18n>Data Gathering</div>
<div class="w-50">
<div class="overflow-hidden">
<div class="mb-2">
<button
color="accent"
mat-flat-button
(click)="onGather7Days()"
>
<ion-icon
class="mr-1"
name="cloud-download-outline"
></ion-icon>
<span i18n>Gather Recent Data</span>
</button>
</div>
<div class="mb-2">
<button
color="accent"
mat-flat-button
(click)="onGatherMax()"
>
<ion-icon
class="mr-1"
name="cloud-download-outline"
></ion-icon>
<span i18n>Gather All Data</span>
</button>
</div>
<div>
<button
class="mb-2 mr-2"
color="accent"
mat-flat-button
(click)="onGatherProfileData()"
>
<ion-icon
class="mr-1"
name="cloud-download-outline"
></ion-icon>
<span i18n>Gather Profile Data</span>
</button>
</div>
</div>
</div>
</div>
<div class="align-items-start d-flex my-3">
<div class="w-50" i18n>Exchange Rates</div>
<div class="w-50">
<table>
<tr *ngFor="let exchangeRate of exchangeRates">
<td class="d-flex">
<bc-value
[locale]="user?.settings?.locale"
[value]="1"
></bc-value>
</td>
<td class="pl-1">{{ exchangeRate.label1 }}</td>
<td class="px-1">=</td>
<td class="d-flex justify-content-end">
<bc-value
[locale]="user?.settings?.locale"
[precision]="4"
[value]="exchangeRate.value"
></bc-value>
</td>
<td class="pl-1">{{ exchangeRate.label2 }}</td>
<td>
<button
*ngIf="customCurrencies.includes(exchangeRate.label2)"
class="mini-icon mx-1 no-min-width px-2"
mat-button
(click)="onDeleteCurrency(exchangeRate.label2)"
>
<ion-icon name="trash-outline"></ion-icon>
</button>
</td>
</tr>
</table>
<div class="mt-2">
<button
color="primary"
mat-flat-button
(click)="onAddCurrency()"
>
<ion-icon class="mr-1" name="add-outline"></ion-icon>
<span i18n>Add Currency</span>
</button>
</div>
</div>
</div>
<div *ngIf="hasPermissionForSystemMessage" class="d-flex my-3">
<div class="w-50" i18n>System Message</div>
<div class="w-50">
<div *ngIf="info.systemMessage">
<span>{{ info.systemMessage }}</span>
<button
class="mini-icon mx-1 no-min-width px-2"
mat-button
(click)="onDeleteSystemMessage()"
>
<ion-icon name="trash-outline"></ion-icon>
</button>
</div>
<button
*ngIf="!info.systemMessage"
color="accent"
mat-flat-button
(click)="onSetSystemMessage()"
>
<ion-icon
class="mr-1"
name="information-circle-outline"
></ion-icon>
<span i18n>Set Message</span>
</button>
</div>
</div>
<div *ngIf="hasPermissionToToggleReadOnlyMode" class="d-flex my-3">
<div class="w-50" i18n>Read-only Mode</div>
<div class="w-50">
<mat-slide-toggle
color="primary"
[checked]="info?.isReadOnlyMode"
(change)="onReadOnlyModeChange($event)"
></mat-slide-toggle>
</div>
</div>
<div
*ngIf="hasPermissionForSubscription"
class="d-flex my-3 subscription"
>
<div class="w-50" i18n>Coupons</div>
<div class="w-50">
<div *ngFor="let coupon of coupons">
<span>{{ coupon.code }} ({{ coupon.duration }})</span>
<button
class="mini-icon mx-1 no-min-width px-2"
mat-button
(click)="onDeleteCoupon(coupon.code)"
>
<ion-icon name="trash-outline"></ion-icon>
</button>
</div>
<div class="mt-2">
<form #couponForm="ngForm">
<mat-form-field appearance="outline" class="mr-2">
<mat-select
name="duration"
[value]="couponDuration"
(selectionChange)="onChangeCouponDuration($event.value)"
>
<mat-option value="7 days">7 Days</mat-option>
<mat-option value="14 days">14 Days</mat-option>
<mat-option value="30 days">30 Days</mat-option>
<mat-option value="1 year">1 Year</mat-option>
</mat-select>
</mat-form-field>
<button
color="primary"
mat-flat-button
(click)="onAddCoupon()"
>
<span i18n>Add</span>
</button>
</form>
</div>
</div>
</div>
<div class="d-flex my-3">
<div class="w-50" i18n>Housekeeping</div>
<div class="w-50">
<button color="warn" mat-flat-button (click)="onFlushCache()">
<ion-icon class="mr-1" name="close-circle-outline"></ion-icon>
<span i18n>Flush Cache</span>
</button>
</div>
</div>
</mat-card-content>
</mat-card>
</div>
</div>
</div>
|
import { useEffect, useState } from 'react';
import { ICourse } from '../../models/Models';
import { Button } from "@mui/material";
import { addDoc, collection, onSnapshot, doc, getDoc, updateDoc, deleteDoc, QuerySnapshot } from 'firebase/firestore';
import { db } from '../../Firebase';
interface Props {
idcurrent: string
}
const CourseForm: React.FC<Props> = ({ idcurrent }) => {
const [currentstateId, setCurrentstateId] = useState("");
const valuesinitial: ICourse = {
id: "",
name: ''
}
const [values, setValues] = useState<ICourse>(valuesinitial);
const handle = (e: React.ChangeEvent<HTMLInputElement>, max: number) => {
const { name, value } = e.target;
if (e.target.value.length <= max) {
setValues({ ...values, [name]: value });
}
}
const WriteCourse = async () => {
if (currentstateId === "") {
await addDoc(collection(db, "courses"), {
name: values.name
});
setValues(valuesinitial);
} else {
const docRef = doc(db, "courses", idcurrent)
await updateDoc(docRef, {
name: values.name
});
setValues(valuesinitial);
setCurrentstateId("");
}
}
const getCourseById = async (id: string) => {
const itemRef = doc(db, 'courses', id);
const itemDoc = await getDoc(itemRef);
const item = {
id: itemDoc.id,
...itemDoc.data(),
} as ICourse;
setValues(item);
}
useEffect(() => {
if (idcurrent === "") {
setValues({ ...valuesinitial });
} else {
setCurrentstateId(idcurrent);
getCourseById(idcurrent);
}
}, [idcurrent]);
return (
<form onSubmit={(e) => e.preventDefault()}>
<h3>Courses Form</h3>
<label>Name</label>
<input type="text" name='name' className='form-control' onChange={e => handle(e, 25)} value={values.name} />
<Button onClick={() => WriteCourse()}>{currentstateId === "" ? "CREATE" : "UPDATE"}</Button>
</form>
)
}
export const CourseCrud = () => {
const clientstate: ICourse = {
id: '',
name: ''
};
const [currentId, setCurrentId] = useState("");
const propertyNames = Object.getOwnPropertyNames(clientstate);
const [collect, setCollect] = useState<Array<ICourse> | null>(null)
useEffect(() => {
const unsubscribe = onSnapshot(collection(db, 'courses'), (snapshot: QuerySnapshot) => {
const data = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})) as ICourse[];
setCollect(data);
});
return () => unsubscribe();
}, [db]);
const remove = async (id: string) => {
await deleteDoc(doc(db, "courses", id));
}
return (
<div>
<CourseForm idcurrent={currentId} />
<table className="table">
<thead>
<tr>
{
propertyNames.map((propertyName) => (
<th key={propertyName} scope="col">{propertyName.toUpperCase()}</th>
))
}
<th scope="col">ACTIONS</th>
</tr>
</thead>
<tbody>
{
collect?.map((course: ICourse) => (
<CourseRow course={course} key={course.id}>
<button className="btn btn-primary" onClick={() => setCurrentId(course.id)}>Update</button>
<button className="btn btn-danger" onClick={() => remove(course.id)}>Remove</button>
</CourseRow>
))
}
</tbody>
</table>
</div>
)
}
type PropsCourse = {
course: ICourse;
children: JSX.Element[];
}
export const CourseRow: React.FC<PropsCourse> = ({ course, children }) => {
return (
<tr>
<th scope="row">{course.id}</th>
<td>{course.name}</td>
<th>
{
children
}
</th>
</tr>
)
}
|
<div class="card">
<div class="card-body h-vh100">
<h4 class="card-title text-uppercase card-border-title">{{ 'DATA.CLUB_MEMBER.ACCOUNT_CHANGE_LOG' | translate }}
</h4>
<div class="row">
<div class="col-12">
<div class="row mb-3 mt-2">
<div class="col-xl-2 col-lg-3 col-md-3 col-sm-6 col-12">
<div class="input-group form-search mb-2">
<input class="form-control form-search-input" [placeholder]="'HEADER.SEARCH' | translate"
[(ngModel)]="searchValue" (keyup.enter)="onSearch()" />
<div>
<div class="btn-search-primary" (click)="onSearch()"><i class="fas fa-search"></i></div>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-3 col-md-3 col-sm-6 col-12">
<ng-select class="mb-2" [(ngModel)]="selectUpdateType" (ngModelChange)="onChangeUpdateType($event)"
[placeholder]="'SELECTBOX.UPDATE_TYPE' | translate">
<ng-option *ngFor="let itm of listTypeUpdate" [value]="itm">
{{ itm }}
</ng-option>
</ng-select>
</div>
<div class="col-xl-3 col-lg-3 col-md-3 col-sm-6 col-12 date-range-picker ">
<input type="text" ngxDaterangepickerMd [timePicker]="true" [timePickerSeconds]="true"
placeholder="DD/MM/YYYY-00:00:00 - DD/MM/YYYY-23:59:59" [timePicker24Hour]="true"
[(ngModel)]="selectedDateTime" class="form-control text-center"
[locale]="{ applyLabel: 'OK', format: 'DD/MM/YYYY HH:mm:ss' }" [showClearButton]=true
(rangeClicked)="onFilterDateChange($event)" (datesUpdated)="onFilterDateChange($event)"
(choosedDate)="onFilterDateChange($event)" />
</div>
</div>
</div>
<!-- Table -->
<div class="col-12 h-vh100">
<div class="table-responsive">
<table
class="table table-striped table table-bordered table-nowrap dt-responsive nowrap no-footer dtr-inline">
<thead>
<tr class="text-center text-overflow text-uppercase font-size-15">
<th scope="col">{{ 'TABLE.ACCOUNT_ID' | translate }}</th>
<th scope="col">{{ 'TABLE.FULL_NAME' | translate }}</th>
<th scope="col">{{ 'TABLE.EMAIL' | translate }}</th>
<th scope="col">{{ 'TABLE.PHONE' | translate }}</th>
<th scope="col">{{ 'TABLE.PIN' | translate }}</th>
<th scope="col">{{ 'TABLE.UPDATE_TYPE' | translate }}</th>
<th scope="col">{{ 'TABLE.CREATED_AT' | translate }}</th>
<ng-template [ngxPermissionsOnly]="'G_BODYCHANGES'">
<th scope="col">{{ 'TABLE.MANAGE' | translate }}</th>
</ng-template>
</tr>
</thead>
<tbody>
<tr class="align-middle h6 h-80 font-size-14" *ngFor="let item of listAccountChange">
<td class="text-center">{{ item.accountId}}</td>
<td class="text-center">{{ item.fullName}}</td>
<td class="text-center">{{ item.email}}</td>
<td class="text-center">{{ item.phoneNumber}}</td>
<td class="text-center">{{ item.pin}}</td>
<td class="text-center">
{{item.updateType}}
</td>
<td class="text-center text-capitalize">
<p class="m-0">{{ (item.createdAt | date: dateFormat)||'-' }}</p>
<p class="m-0 pt-2">{{ item.createdAt | date: timeFormat }}</p>
</td>
<ng-template [ngxPermissionsOnly]="'G_BODYCHANGES'">
<td class="text-center">
<button type="button" class="btn btn-primary btn-sm btn-only-shadow"
[ngbTooltip]="'BUTTON.VIEW' | translate" (click)="viewDetail(item.updateBody)">
<i class="fas fa-eye"></i></button>
</td>
</ng-template>
</tr>
</tbody>
</table>
</div>
<div class=" text-center pagination-footer flex-wrap pagination-rounded">
<div class="paging-limit mt-3">
<ng-select [clearable]="false" [(ngModel)]="pageSize" (change)="onChangeLimit()">
<ng-option [value]="10">10</ng-option>
<ng-option [value]="20">20</ng-option>
<ng-option [value]="50">50</ng-option>
</ng-select>
</div>
<div class="paging-nav h6">
<ngb-pagination class="mb-0 font-size-12" [maxSize]="4" [rotate]="true" [ellipses]="false"
[boundaryLinks]="true" [(page)]="page" [pageSize]="pageSize" [collectionSize]="total"
(pageChange)="loadNext($event)">
<ng-template ngbPaginationPrevious>{{ 'BUTTON.PREV' | translate }}</ng-template>
<ng-template ngbPaginationNext>{{ 'BUTTON.NEXT' | translate }}</ng-template>
</ngb-pagination>
</div>
<div class="paging-total mt-3">
<span class="h6 fw-bold">{{ total || 0 }}</span> {{ 'PAGING.ITEM_IN' | translate }} <span
class="h6 fw-bold">{{
pages || 0 }}</span> {{ 'PAGING.PAGES' | translate }}
</div>
</div>
</div>
</div>
</div>
</div>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.