text
stringlengths 184
4.48M
|
|---|
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
import React from 'react';
import PropTypes from 'prop-types';
import * as clipboard from 'clipboard-polyfill';
import '../../scss/shared/copiedNotification.scss';
class CopyButtonWrapper extends React.Component {
state = {
showNotification: false
};
componentWillUnmount() {
const { showNotification } = this.state;
if (showNotification && this.timeoutId) clearTimeout(this.timeoutId);
}
onCopy = () => {
const {
content,
message,
autoHideTime,
showCopiedNotification: showCopiedNotificationAction,
callback
} = this.props;
clipboard.writeText(content);
showCopiedNotificationAction(message, autoHideTime);
callback();
};
timeoutId;
render() {
const { children, className } = this.props;
return (
<span className={`u-cursor-pointer${className ? ` ${className}` : ''}`} onClick={this.onCopy}>
{children}
</span>
);
}
}
CopyButtonWrapper.propTypes = {
autoHideTime: PropTypes.number,
content: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
children: PropTypes.element.isRequired,
message: PropTypes.string,
className: PropTypes.string,
callback: PropTypes.func
};
CopyButtonWrapper.defaultProps = {
autoHideTime: 3000,
message: 'Successfully Copied!',
className: '',
callback: () => {}
};
export default CopyButtonWrapper;
|
/*
Tener en cuenta que el index puede variar en el transcurso de la función
*/
package main
import (
"fmt"
"sync"
)
var (
buffer [5]int = [5]int{-1, -1, -1, -1, -1,}
index int
wg sync.WaitGroup
mu sync.Mutex
contador = make(chan int, 4)
prev int
)
func productor() {
for n:= 0; n < 20; {
item := n
mu.Lock()
select{
case contador<-n%5:
index = n%5
buffer[index] = item
fmt.Printf("productor %d %d %v\n", index, item, buffer)
n++
default:
}
mu.Unlock()
}
wg.Done()
}
func consumidor(){
var item int
for n:=0; n < 20;{
mu.Lock()
select{
case <-contador:
index = n%5
item = buffer[index]
buffer[index] = -1
fmt.Printf("consumidor %d %d %v\n", index, item, buffer)
n++
default:
}
mu.Unlock()
}
wg.Done()
}
func main() {
wg.Add(2)
go consumidor()
go productor()
wg.Wait()
}
|
<script setup lang="ts">
import { ref } from 'vue';
import { MenuItem } from '@/utils/interfaces'
const menuActive = (index: number): void => {
menuItems.value.map(item => item.active = false);
menuItems.value[index].active = true;
}
const menuItems = ref<MenuItem[]>([
{
id: 1,
path: '/',
name: 'Home',
active: true,
},
{
id: 2,
path: '/inventory',
name: 'Inventory',
active: false,
},
{
id: 3,
path: '/skins',
name: 'Skins',
active: false,
}
]);
</script>
<template>
<div class="menu absolute left-0 right-0 pt-4">
<div class="container mx-auto px-2">
<div class="menu-content flex items-center justify-between">
<div class="menu-logo w-10 h-10">
<img class="rounded-xl" src="/images/logo.jpg">
</div>
<div class="menu-nav">
<ul class="menu flex items-center gap-x-6 text-[#F1FAEE] text-2xl font-poetsenone">
<li class="transition-all duration-300"
:class="menuItem.active ? 'text-[#A8DADC]' : 'hover:text-white' "
v-for="(menuItem, menuIndex) in menuItems" :key="menuItem.id"
@click="menuActive(menuIndex)"
>
<RouterLink :to="menuItem.path">{{ menuItem.name }}</RouterLink>
</li>
</ul>
</div>
</div>
</div>
</div>
</template>
|
@model Models.ProductGroup
@{
ViewBag.Title = "افزودن " + Server.HtmlDecode(Html.DisplayNameFor(model => model).ToString());
}
<h2>افزودن @Html.DisplayNameFor(model => model)</h2>
@using (Html.BeginForm("Create", "ProductGroups",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true)
<div class="form-group">
<div class="form-group">
@Html.LabelFor(model => model.Title, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Code, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Code)
@Html.ValidationMessageFor(model => model.Code)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.InventoryAmount, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.InventoryAmount)
@Html.ValidationMessageFor(model => model.InventoryAmount)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ProductGroupUnitId, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ProductGroupUnitId", String.Empty)
@Html.ValidationMessageFor(model => model.ProductGroupUnitId)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Density, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Density)
@Html.ValidationMessageFor(model => model.Density)
</div>
</div>
<div class="form-group">
<div class="col-md-2">
</div>
<div class="col-md-10">
@Html.EditorFor(model => model.IsActive)
@Html.LabelFor(model => model.IsActive)
@Html.ValidationMessageFor(model => model.IsActive)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
</div>
<div class="form-group" id="buttons">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="ایجاد" class="btn btn-primary" />
@Html.ActionLink("بازگشت به فهرست", "Index")
</div>
</div>
</div>
</div>
}
|
package com.example.android.architecture.blueprints.todoapp.ui.fragments
import androidx.navigation.NavController
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.MediumTest
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.data.MainRepository
import com.example.android.architecture.blueprints.todoapp.data.source.local.entity.Task
import com.example.android.architecture.blueprints.todoapp.testutil.launchFragmentInHiltContainer
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import io.mockk.mockk
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.*
import org.hamcrest.CoreMatchers.not
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import javax.inject.Inject
@ExperimentalCoroutinesApi
@HiltAndroidTest
@MediumTest
class TaskDetailFragmentTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@Inject
lateinit var repository: MainRepository
lateinit var navController: NavController
@Before
fun setup() {
hiltRule.inject()
navController = mockk(relaxed = true)
}
@Test
fun completedTasksDetails_DisplayedInUi() = runTest {
// given - Add completed task to DB
val task = Task("BBC", "Ukrain", true)
repository.saveTask(task)
// when - Launching fragment details our tasks
val bundle = TaskDetailFragmentArgs(task.id).toBundle()
launchFragmentInHiltContainer<TaskDetailFragment>(bundle)
//then - assert that tittle and description are both correct
onView(withId(R.id.task_detail_title_text)).check(matches(isDisplayed()))
onView(withId(R.id.task_detail_title_text)).check(matches(withText("BBC")))
onView(withId(R.id.task_detail_description_text)).check(matches(isDisplayed()))
onView(withId(R.id.task_detail_description_text)).check(matches(withText("Ukrain")))
// and make sure the "active" checkbox is shown unchecked
onView(withId(R.id.task_detail_complete_checkbox)).check(matches(isDisplayed()))
onView(withId(R.id.task_detail_complete_checkbox)).check(matches(isChecked()))
}
@Test
fun activeTaskDetails_DisplayedInUi() = runTest {
// GIVEN - Add active (incomplete) task to the DB
val activeTask = Task("Active Task", "AndroidX Rocks", false)
repository.saveTask(activeTask)
// WHEN - Details fragment launched to display task
val bundle = TaskDetailFragmentArgs(activeTask.id).toBundle()
launchFragmentInHiltContainer<TaskDetailFragment>(bundle)
// THEN - Task details are displayed on the screen
// make sure that the title/description are both shown and correct
onView(withId(R.id.task_detail_title_text)).check(matches(isDisplayed()))
onView(withId(R.id.task_detail_title_text)).check(matches(withText("Active Task")))
onView(withId(R.id.task_detail_description_text)).check(matches(isDisplayed()))
onView(withId(R.id.task_detail_description_text)).check(matches(withText("AndroidX Rocks")))
// and make sure the "active" checkbox is shown unchecked
onView(withId(R.id.task_detail_complete_checkbox)).check(matches(isDisplayed()))
onView(withId(R.id.task_detail_complete_checkbox)).check(matches(not(isChecked())))
}
}
|
import Shop from "../../models/shopModel.js";
import request from "supertest";
import app from "../../app.js";
import mongoose from "mongoose";
import dotenv from "dotenv";
import cloudinary from "cloudinary";
import connectDatabase from "../../config/database.js";
import testLogo from "../../__mocks__/test-logo.js";
// Setting up config file
dotenv.config({ path: "config/config.env" });
// Setting up cloudinary configuration
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
// Variable to store user token for admin account
let adminToken;
// Variable to store shop id
let shopId;
// Connects to a MongoDB database
beforeAll(async () => {
connectDatabase();
// Authorize as Admin
const res = await request(app).post("/api/login").send({
email: process.env.ADMIN_TEST_EMAIL,
password: "sickPassword!",
});
adminToken = res.body.token;
// Upload logo image to Cloudinary
const result = await cloudinary.uploader.upload(testLogo, {
folder: "IGZlogos",
width: 150,
crop: "scale",
});
// Insert shop for delete test and store id
const insertShopRes = await Shop.create({
shopName: "Test Shop6",
shopEmail: "testShop6@gmail.com",
password: "123456789",
confirmPassword: "123456789",
phoneNumber: "123456789",
address: "123 Avenija 67",
zipCode: "3456",
logo: {
public_id: result.public_id,
url: result.secure_url,
},
});
shopId = insertShopRes._id;
});
// Disconnects from MongoDB database
afterAll(async () => {
await mongoose.connection.close();
});
describe("GET /api/admin/shops", () => {
it("should get all shops from database", (done) => {
request(app)
.get("/api/admin/shops")
.set("Accept", "application/json")
.set("Cookie", [`user_token=${adminToken}`])
.expect("Content-Type", /json/)
.expect(200)
.end((err, res) => {
if (err) return done(err);
// Assert that the response contains shops
expect(res.body).toHaveProperty("shops");
done();
});
});
});
describe("DELETE /api/admin/shop/:id", () => {
it("should delete shop from database", (done) => {
request(app)
.delete(`/api/admin/shop/${shopId}`)
.set("Accept", "application/json")
.set("Cookie", [`user_token=${adminToken}`])
.expect("Content-Type", /json/)
.expect(200)
.end((err, res) => {
if (err) return done(err);
// Assert that the response contains success
expect(res.body).toHaveProperty("success", true);
done();
});
});
it("should return error if there is no shop with this id", (done) => {
request(app)
.delete(`/api/admin/shop/64b510cc5c620d7bef933d5f`)
.set("Accept", "application/json")
.set("Cookie", [`user_token=${adminToken}`])
.expect("Content-Type", /json/)
.expect(404)
.end((err, res) => {
if (err) return done(err);
// Assert that the response contains the error message
expect(res.body).toHaveProperty("success", false);
expect(res.body).toHaveProperty("error", { statusCode: 404 });
expect(res.body).toHaveProperty(
"message",
"Shop not found with id: 64b510cc5c620d7bef933d5f"
);
done();
});
});
});
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { ModalZoomCartaInicialComponent } from './modal-zoom-carta-inicial.component';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
describe('ModalZoomCartaInicialComponent', () => {
let component: ModalZoomCartaInicialComponent;
let fixture: ComponentFixture<ModalZoomCartaInicialComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ModalZoomCartaInicialComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
imports: [ MatDialogModule],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef, useValue: {} },
]
})
.compileComponents();
fixture = TestBed.createComponent(ModalZoomCartaInicialComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('deve fechar o "modal" quando clicar no botão de fechar', () => {
spyOn(component, 'fecharZoom').and.stub();
const botao: HTMLElement = fixture.nativeElement.querySelector('#fechar');
fixture.detectChanges();
botao.click();
expect(component.fecharZoom).toHaveBeenCalled();
})
});
|
# Import necessary libraries
from flask import Flask, request, jsonify
from flask_cors import CORS # Import CORS
import numpy as np
import pandas as pd
import tensorflow as tf
import keras
from keras.applications import DenseNet121
from keras.preprocessing import image
from keras.applications.densenet import preprocess_input
from sklearn.metrics.pairwise import linear_kernel
import pathlib
app = Flask(__name__)
CORS(app)
model = keras.models.load_model('keras_model.h5')
df_embeddings = pd.read_csv('embeddings_data.csv')
df = pd.read_csv('fashion-dataset/styles.csv', nrows=6000)
# Compute cosine similarity between embeddings
cosine_sim = linear_kernel(df_embeddings, df_embeddings)
# Function to recommend products based on an image
def recommend_products(image_path):
# Preprocess the input image to match the model's requirements
img = image.load_img(image_path, target_size=(200, 200))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
img = preprocess_input(img)
# Get the image embedding from your pre-trained model
image_embedding = model.predict(img).reshape(-1)
# Compute similarity scores between the input image and all products
sim_scores = cosine_sim.dot(image_embedding)
# Sort products by similarity scores and get the top 5 most similar
top_indices = np.argsort(sim_scores)[::-1][:5]
# Return the recommended products
recommendations = df.iloc[top_indices].to_dict(orient='records')
return recommendations
# API endpoint to receive an image and get product recommendations
@app.route('/recommend', methods=['POST'])
def get_recommendations():
try:
# Get the image file from the request
image_file = request.files['image']
# Save the image temporarily
image_path = 'temp_image.jpg'
image_file.save(image_path)
# Call the recommendation function
recommendations = recommend_products(image_path)
return jsonify({'recommendations': recommendations})
except Exception as e:
return jsonify({'error': str(e)})
if __name__ == '__main__':
app.run(debug=True)
|
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AgGridModule } from 'ag-grid-angular';
import { HttpClientModule } from '@angular/common/http';
import { MatSliderModule } from '@angular/material/slider';
import { AppRoutingModule } from './app-routing.module';
import {MatButtonModule, MatSidenav, MatSidenavModule} from '@angular/material';
import { AppComponent } from './app.component';
import { HomeComponent } from './Dashboard/Home/home.component';
import { NgTemplateComponent } from './Dashboard/ng-template/ng-template.component';
import { GridComponent } from './Dashboard/grid/grid.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HomelayoutComponent } from './Layout/HomeLayout/homelayout.component';
import { AdminlayoutComponent } from './Layout/AdminLayout/adminlayout.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { LightBoxComponent } from './Dashboard/light-box/light-box.component';
import { ProductComponent } from './Dashboard/product/product.component';
import { CategoryComponent } from './Dashboard/category/category.component';
import {MatCheckboxModule} from '@angular/material/checkbox';
import { NgxNumberSpinnerModule } from 'ngx-number-spinner';
import {NgxPaginationModule} from 'ngx-pagination';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import { AboutComponent } from './Dashboard/about/about.component';
import { LoginComponent } from './Dashboard/login/login.component';
import { SidebarModule } from 'ng-sidebar';
import {MatInputModule} from '@angular/material/input';
import {MatCardModule} from '@angular/material/card';
import {MatTableModule,MatPaginatorModule, MatAutocomplete, MatAutocompleteModule} from '@angular/material'
import {MatSnackBarModule} from '@angular/material/snack-bar';
import {SocialLoginModule,AuthServiceConfig,GoogleLoginProvider,FacebookLoginProvider,LinkedinLoginProvider} from 'ng4-social-login';
import { NewCustomerComponent } from './Dashboard/new-customer/new-customer.component';
import { ProductDetailComponent } from './Dashboard/product-detail/product-detail.component';
import { CartComponent } from './Dashboard/cart/cart.component';
import { LoggedComponent } from './Dashboard/logged/logged.component';
import { AdminProductComponent } from './Dashboard/admin-product/product-list-add/admin-product.component';
import { ProductUpdateComponent } from './Dashboard/admin-product/product-update/product-update.component';
import { CustomerListAddComponent } from './Dashboard/admin-customer/customer-list-add/customer-list-add.component';
import { CustomerUpdateComponent } from './Dashboard/admin-customer/customer-update/customer-update.component';
import { AdminPanelLoginComponent } from './Dashboard/admin-panel-login/admin-panel-login.component';
import { UserProfileComponent } from './Dashboard/user-profile/user-profile.component';
import { PaymentComponent } from './Dashboard/payment/payment.component';
import { DialogElementsComponent } from './Dashboard/dialog-elements/dialog-elements.component';
import {MatDialogModule} from '@angular/material/dialog';
import { SaledProductComponent } from './Dashboard/saled-product/saled-product.component';
import { AdminCategoryComponent } from './Dashboard/admin-category/admin-category.component';
import { AdminCategoryUpdateComponent } from './Dashboard/admin-category-update/admin-category-update.component';
const config = new AuthServiceConfig([
{
id:FacebookLoginProvider.PROVIDER_ID,
provider:new FacebookLoginProvider('196279738306517')
}],false);
export function provideConfig(){
return config;
}
@NgModule({
declarations: [
AppComponent,
HomeComponent,
NgTemplateComponent,
GridComponent,
HomelayoutComponent,
AdminlayoutComponent,
LightBoxComponent,
ProductComponent,
LoggedComponent,
CategoryComponent,
LoginComponent,
AboutComponent,
LoginComponent,
NewCustomerComponent,
ProductDetailComponent,
CartComponent,
LoggedComponent,
AdminProductComponent,
ProductUpdateComponent,
CustomerListAddComponent,
CustomerUpdateComponent,
AdminPanelLoginComponent,
UserProfileComponent,
PaymentComponent,
DialogElementsComponent,
SaledProductComponent,
AdminCategoryComponent,
AdminCategoryUpdateComponent,
],
imports: [
MatSnackBarModule,
FormsModule,
ReactiveFormsModule,
MatAutocompleteModule,
SocialLoginModule,
MatCardModule,
MatSidenavModule,
MatInputModule,
SidebarModule,
BrowserModule,
MatDialogModule,
AppRoutingModule,
HttpClientModule,
MatButtonModule,
MatCheckboxModule,
MatSliderModule,
NgxNumberSpinnerModule,
AgGridModule.withComponents([]),
BrowserAnimationsModule,
NgxPaginationModule,
MatProgressSpinnerModule
],
entryComponents: [
DialogElementsComponent,
],
providers: [{provide:AuthServiceConfig,useFactory:provideConfig}],
bootstrap: [AppComponent]
})
export class AppModule { }
|
import {ThunkAction} from "redux-thunk";
import {AppStateType} from "./redux-store";
import {getAuthUserData} from "./auth-reducer";
import {getUserProfile} from "./profile-reduser";
import {setIsFetching, SetIsFetchingType} from "./users-reducer";
import {AxiosError} from "axios";
import {handleNetworkError} from "../utils/HandleNetworkError/handleNetworkError";
export type AppStateInitialType = {
initialized: boolean
error: null | string,
}
export type SetErrorType = ReturnType<typeof setError>
type InitializedSuccessAppType = ReturnType<typeof initializedSuccessApp> | SetErrorType | SetIsFetchingType
type AppReducerActionType = InitializedSuccessAppType
let initialState: AppStateInitialType = {
initialized: false,
error: null
}
export const appReducer = (state = initialState, action: AppReducerActionType): AppStateInitialType => {
switch (action.type) {
case "APP/SET-INITIALIZED":
return {
...state,
initialized: true
}
case "APP/SET-ERROR":
return {...state, ...action.error}
default:
return state;
}
}
export const initializedSuccessApp = () => ({type: "APP/SET-INITIALIZED"}) as const
export const setError = (error: { error: string | null }) => ({type: "APP/SET-ERROR", error}) as const
//Thunk creator for login user
type AppReducerThunkType = ThunkAction<void, AppStateType, unknown, AppReducerActionType>
export const initializeApp = (): AppReducerThunkType => async (dispatch
, getState: () => AppStateType) => {
dispatch(setIsFetching(true))
try {
await dispatch(getAuthUserData())
if (getState().auth.isAuth) await dispatch(getUserProfile(getState().auth.id!))
dispatch(initializedSuccessApp())
dispatch(setIsFetching(false))
} catch (e) {
const error = e as AxiosError
handleNetworkError(dispatch, error)
}
}
|
import 'package:flutter/material.dart';
import 'story_brain.dart';
// Step 15 - Run the app and see if you can see the screen update with the first story. Delete this if it looks as you expected.
void main() => runApp(const Destini());
class Destini extends StatelessWidget {
const Destini({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
home: const StoryPage(),
);
}
}
// Step 9 - Create a new storyBrain object from the StoryBrain class.
StoryBrain storyBrain = StoryBrain();
class StoryPage extends StatefulWidget {
const StoryPage({Key? key}) : super(key: key);
@override
State<StoryPage> createState() => _StoryPageState();
}
class _StoryPageState extends State<StoryPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("images/title-1.jpg"),
fit: BoxFit.cover,
)
),
padding: const EdgeInsets.symmetric(vertical: 50.0, horizontal: 15.0),
constraints: const BoxConstraints.expand(),
child: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
flex: 6,
child: Center(
child: Text(
// Step 10 - use the storyBrain to get the first story title and display it in this Text Widget.
// 'Story Text will go here.',
storyBrain.getStory(),
style: const TextStyle(
fontSize: 25.0,
color: Colors.yellow,
),
),
),
),
Expanded(
child: Container(
color: Colors.redAccent,
child: TextButton(
onPressed: () {
// Choice 1 made by user.
// Step 18 - Call the nextStory() method from storyBrain and pass the number 1 as the choice made by the user.
setState(() {
storyBrain.nextStory(1);
});
},
child: Text(
// Step 13 - Use the storyBrain to get the text for choice 1.
// 'Choice 1',
storyBrain.getChoice1(),
style: const TextStyle(
color: Colors.purple,
fontSize: 20.0,
),
),
),
),
),
const SizedBox(
height: 20,
),
Expanded(
// Step 26 - Use a Flutter Visibility Widget to wrap this FlatButton.
// Step 28 - Set the "visible" property of the Visibility Widget to equal the output from the buttonShouldBeVisible() method in the storyBrain.
child: Visibility(
visible: storyBrain.buttonShouldBeVisible(),
child: Container(
color: Colors.blue,
child: TextButton(
onPressed: () {
//Choice 2 made by user.
// Step 19 - Call the nextStory() method from storyBrain and pass the number 2 as the choice made by the user.
setState(() {
storyBrain.nextStory(2);
});
},
child: Text(
// Step 14 - Use the storyBrain to get the text for choice 2.
// 'choice 2',
storyBrain.getChoice2(),
style: const TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
),
),
),
)
],
)),
),
);
}
}
//TODO: Step 24 - Run the app and try to figure out what code you need to add to this file to make the story change when you press on the choice buttons.
//TODO: Step 29 - Run the app and test it against the Story Outline to make sure you've completed all the steps. The code for the completed app can be found here: https://github.com/londonappbrewery/destini-challenge-completed/
|
@ LED_Template.s
@ December 2021
@ Adam Watkins / Richard Verhoeven
@ Write to GPIO PIN 22 via memory mapped I/O
@ Wire the Gertboard as follows:
@ connect GP22 of header J2 to B4 of header J3
@ put a jumper on B5 out (output side of U4)
@ Adapted by:
@ <Student Name 1> <Student Number 1>
@ <Student Name 2> <Student Number 2>
.global main
.equ SYS_EXIT, 0x1
.equ GPIO_ADDR, 0x3F200000 @ GPIO_Base for RPi 3
.equ GPSET0, 0x1C @ Value to set a GPIO pin to ON
.equ GPCLR0, 0x28 @ Value to set a GPIO pin to OFF
.equ GERT22, 22 @ RPi GPIO to gertboard mappings
.text
.include "Hardware.s" @ open, map, unmap and close functions
main:
BL open_mem @ Open /dev/mem
LDR R0, =GPIO_ADDR @ Load hardware address to map
BL map @ call mmap2
LDR R1, =gpiobase @ Store address of mapping
STR R0, [R1]
MOV R0, #22 @ Pin number
MOV R1, #1 @ Code for output
BL set_pin_function @ Set pin to output
CMP R0, #0 @ If return value ...
BLT exit @ <0 (error) then exit
MOV R0, #22 @ Pin number
MOV R1, =GPSET0 @ Set (turn on LED)
BL set_pin_value @ Turn on LED
MOV R0, #25 @ Pin number
MOV R1, #1 @ Code for output
BL set_pin_function @ Set pin to output
CMP R0, #0 @ If return value ...
BLT exit @ <0 (error) then exit
MOV R0, #25 @ Pin number
MOV R1, =GPCLR0 @ Set (turn on LED)
BL set_pin_value @ Turn on LED
exit:
LDR R0, =gpiobase @ Load start unmap the memory
LDR R0, [R0]
BL unmap @ Unmap
LDR R1, =file_desc @ Load file decriptor address
LDR R0, [R1] @ Load file descriptor value
BL close_mem @ Close /dev/mem
MOV R7, #SYS_EXIT @ Return
SWI 0
@ Functions
@@@@@ set_pin_function : function to set pin n to output in GPSELm
@ Parameters:
@ R0: pin number
@ R1: code of function (see chapter 6 BCM2837 manual for codes)
@ Returns:
@ R0: -1 on error
set_pin_function:
@ successively subtract 10 from R1 until <10
@ store offset of of GPSELm in R5
STMFD SP!, {R2-R7, LR} @ save registers
BL check_pin @ check if pin number OK
CMP R0, #0 @ if returned value is
BLT exit_set_func @ <0 then exit function (error)
@ find GPSELm from pin number
CMP R0, #9 @ GPSEL0?
MOV R5, #0
BHI gpsel1
BAL clr_GPSELm @ offset of GPSEL0 (= GPIO base address) in R5 = 0
gpsel1:
SUB R0, #10
CMP R0, #9 @ GPSEL1?
BHI gpsel2
MOV R5, #4
BAL clr_GPSELm @ offset of GPSEL1 in R5
gpsel2:
SUB R0, #10
MOV R5, #8 @ offset of GPSEL2 in R5
clr_GPSELm:
MOV R3, R0 @ save R0
MOV R6, #0b111 @ load R6 with bit pattern for BIC to clear 3 bits
MOV R2, #3
MUL R7, R3, R2
MOV R6, R6, LSL R7 @ shift R6 R3*3 times left
clear:
LDR R3, =gpiobase
LDR R2, [R3] @ load base memory address of gpio
LDR R4, [R2, R5] @ load current contents of GPSELm
BIC R4, R4, R6 @ clear the 3 bits corresponding to the pin
MOV R1, R1, LSL R7 @ shift R1 (function) R7 times left
ORR R4, R1 @ set the function bits in R4 ( R4 is a copy of the
@ current GPSELm register with the 3 bits corresponding
@ to pin R1 set o 0)
LDR R3, =gpiobase
LDR R3, [R3] @ load memory base address of gpio
STR R4, [R3, R5] @ copy R4 to GPSELm
exit_set_func:
LDMFD SP!, {R2-R7, LR} @ restore R2-R7 and LR
MOV PC, LR @ R0 still holds GPIO base address if no error occurred..
@@@@ set_pin_value: function to set the pin
@ Parameters:
@ R0: pin number
@ R1: offset of GPSET0/GPCLR0
@ Returns:
@ R0: returns: -1 if error
set_pin_value:
STMFD SP!, {R2-R3, LR}
MOV R3, R0 @ save R0
BL check_pin @ check if pin number is correct
CMP R0, #0 @ if value returned from check_pin
BLT ret_set @ <1 then return (error)
MOV R3, #1 @ will be shifted until pin position R1
MOV R3, R3, LSL R0 @ shift by R0 bits left
LDR R2, =gpiobase @ gpio base address in memory
LDR R2, [R2]
STR R3, [R2, R1] @ set or clear pin; R0+R2 address of GPSET/CLR0
@ notice that register is Write only
ret_set:
LDMFD SP!, {R2-R3, LR}
MOV PC, LR @ return - R0 still holds base address if no error occurred
@@@@ check_pin : check if pin number is legal
@ Parameters:
@ R0: pin number
@ Return
@ R0: -1 if illegal
check_pin:
CMP R0, #1 @ GPIO 0 and 1 not available
BLS error @ GPIO2 is connected to GP0, GPIO3 to GP1
CMP R0, #5 @ GPIO5 not available
BEQ error
CMP R0, #6 @ GPIO6 not available
BEQ error
CMP R0, #16 @ GPIO 12, 13, 16 not available - R1 >16?
BHI next_check @ GPIO 14 and 15 set for UART so leave alone
CMP R0, #11 @ GPIO# <12?
BLS next_check
BAL error
next_check:
CMP R0, #21 @ GPIO19, 20 and 21 not available
BHI check_next
CMP R0, #18
BLS check_next
BAL error
check_next:
CMP R0, #27 @ GPIO27 is connected to GP21
BEQ ret
CMP R0, #25 @ no pins over 25
BHI error
MOV PC, LR
error:
MOV R0, #-1 @ signal error to caller
ret:
MOV PC, LR
.data
@@@@ Constants
dev_mem: .asciz "/dev/mem"
@@@@ Variables
.align 4
file_desc: .word 0x0 @ file descriptor
gpiobase:
.word 0x0 @ address to which gpio is mapped
|
<?php
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\NewsController;
use App\Http\Controllers\ArticleController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\HeaderController;
use App\Http\Controllers\GalleryController;
use App\Http\Controllers\SummaryController;
use App\Http\Controllers\BlogController;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\TeamController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/storage-link', function () {
$targetFolder = storage_path('app/public');
$linkFolder = $_SERVER['DOCUMENT_ROOT'] . '/storage';
symlink($targetFolder, $linkFolder);
});
Route::get('/sign_in', [AuthController::class, 'index'])->middleware('guest');
Route::get('/sign_up', [AuthController::class, 'sign_up']);
Route::post('/registration', [AuthController::class, 'registration'])->middleware('guest');
Route::post('/', [AuthController::class, 'authenticate']);
Route::get('/logout', [AuthController::class, 'logout']);
Route::get('/', [HomeController::class, 'index'])->name('home.layout.main');
Route::prefix('header')->group(function () {
Route::get('/index', [HeaderController::class, 'index'])->middleware('auth');
Route::get('/create', [HeaderController::class, 'create'])->middleware('auth');
Route::post('/store', [HeaderController::class, 'store']);
Route::get('/edit/{id}', [HeaderController::class, 'edit'])->middleware('auth');
Route::post('/update/{id}', [HeaderController::class, 'update']);
Route::post('/destroy/{id}', [HeaderController::class, 'destroy']);
});
Route::prefix('summary')->group(function () {
Route::get('/index', [SummaryController::class, 'index'])->middleware('auth');
Route::get('/create', [SummaryController::class, 'create'])->middleware('auth');
Route::post('/store', [SummaryController::class, 'store']);
Route::get('/edit/{id}', [SummaryController::class, 'edit'])->middleware('auth');
Route::post('/update/{id}', [SummaryController::class, 'update']);
});
Route::prefix('gallery')->group(function () {
Route::get('/index', [GalleryController::class, 'index'])->middleware('auth');
Route::get('/create', [GalleryController::class, 'create'])->middleware('auth');
Route::post('/store', [GalleryController::class, 'store']);
Route::get('/edit/{id}', [GalleryController::class, 'edit'])->middleware('auth');
Route::post('/update/{id}', [GalleryController::class, 'update']);
Route::post('/destroy/{id}', [GalleryController::class, 'destroy']);
});
Route::prefix('article')->group(function () {
Route::get('/index/{id}', [ArticleController::class, 'index']);
Route::get('/aindex', [ArticleController::class, 'aindex'])->middleware('auth');
Route::get('/create', [ArticleController::class, 'create'])->middleware('auth');
Route::post('/store', [ArticleController::class, 'store']);
Route::get('/edit/{id}', [ArticleController::class, 'edit'])->middleware('auth');
Route::post('/update/{id}', [ArticleController::class, 'update']);
Route::post('/destroy/{id}', [ArticleController::class, 'destroy']);
});
Route::prefix('news')->group(function () {
Route::get('/index/{id}', [NewsController::class, 'index']);
Route::get('/aindex', [NewsController::class, 'aindex'])->middleware('auth');
Route::get('/create', [NewsController::class, 'create'])->middleware('auth');
Route::post('/store', [NewsController::class, 'store']);
Route::get('/edit/{id}', [NewsController::class, 'edit'])->middleware('auth');
Route::post('/update/{id}', [NewsController::class, 'update']);
Route::post('/destroy/{id}', [NewsController::class, 'destroy']);
});
Route::prefix('team')->group(function () {
Route::get('/index', [TeamController::class, 'index']);
});
Route::prefix('customers')->group(function () {
Route::get('/index', [CustomerController::class, 'index']);
});
Route::prefix('blog')->group(function () {
Route::get('/index', [BlogController::class, 'index']);
});
Route::prefix('dashboard')->group(function () {
Route::get('/index', [AdminController::class, 'index'])->middleware('auth');
});
|
Imports System.Data.SqlClient
''' <summary>
''' Classe para acesso ao banco de dados, neste caso SQL Server
''' </summary>
''' <remarks></remarks>
Public Class ClasseBancoDados
Private ConexaoBD As SqlConnection
Private Comandos As SqlCommand
Private DataAdapter As SqlDataAdapter
Private strComandoSQL, strOperacao, strChavePesquisa As String
'construtor
Public Sub New(ByVal strConexao As String)
ConexaoBD = New SqlConnection(strConexao)
strOperacao = ""
End Sub
''' <summary>
''' Abertura do banco de dados
''' </summary>
''' <remarks></remarks>
Public Sub Abrir()
Try
ConexaoBD.Open()
Catch excecao As SqlException
'formErroNaRede.ShowDialog()
'formErroNaRede.Dispose()
MsgBox("NÃO FOI POSSÍVEL CONECTAR AO BANCO DE DADOS." & vbCrLf & vbCrLf & _
"Verifique se há algum problema com rede." & vbCrLf & vbCrLf & _
"Uma exceção foi gerada: " + excecao.Message & vbCrLf & vbCrLf & "Será encerrado.", _
MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, _
"Aviso")
End
Catch ex As Exception
MsgBox("NÃO FOI POSSÍVEL CONECTAR AO BANCO DE DADOS." & vbCrLf & vbCrLf & _
"Verifique se há algum problema com rede." & vbCrLf & vbCrLf & _
"Uma exceção foi gerada: " + ex.Message & vbCrLf & vbCrLf & "Será encerrado.", _
MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, _
"Aviso")
End
End Try
End Sub
''' <summary>
''' Fechamento do banco de dados
''' </summary>
''' <remarks></remarks>
Public Sub Fechar()
ConexaoBD.Close()
End Sub
''' <summary>
''' Ajusta membro da operacao
''' </summary>
''' <value>Tipo de operação no cadastro</value>
''' <returns>Retorna o tipo de operação</returns>
''' <remarks></remarks>
Public Property Operacao As String
Get
Return strOperacao
End Get
Set(value As String)
strOperacao = value
End Set
End Property
''' <summary>
''' Executa um script sql e retorna uma DataTable
''' </summary>
''' <param name="parConexao">Conexao ativa</param>
''' <param name="parScriptSelect">Script SQL, select</param>
''' <param name="parTabelaNome">Nome da tabela</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function RetornaDataTable(ByRef parConexao As SqlConnection, _
ByVal parScriptSelect As String, _
ByVal parTabelaNome As String) As DataTable
Dim comando As New SqlCommand
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim dataTableTemp As New DataTable
Try
comando.Connection = parConexao
comando.CommandType = CommandType.Text
comando.CommandText = parScriptSelect
da.SelectCommand = comando
da.Fill(ds, parTabelaNome)
dataTableTemp = ds.Tables(parTabelaNome)
Catch ex As Exception
Throw New Exception("Falha ao carregar o DataTable")
End Try
Return dataTableTemp
End Function
'ajusta o membro "strComandoSQL"
Public Property ComandoSQL As String
Get
Return strComandoSQL
End Get
Set(value As String)
strComandoSQL = value
End Set
End Property
'cria o objeto cmdComandoSQL
Public Sub CriaComandoSQL()
Comandos = New SqlCommand(strComandoSQL, ConexaoBD)
End Sub
'apaga todos os parametros que existem no objeto comandos
Public Sub LimparParametros()
Comandos.Parameters.Clear()
End Sub
'adiciona o parametro ao objeto comandos
Public Sub AdicionarParametro(ByVal strNomeParametro As String, ByVal strValor As String)
Try
Comandos.Parameters.AddWithValue(strNomeParametro, strValor)
Catch excecao As SqlException
MsgBox("Erro em tempo de execucao: " + excecao.Message)
End Try
End Sub
'adiciona o parametro ao objeto comandos
Public Sub AdicionarParametroNumero(ByVal strNomeParametro As String, ByVal dblValor As Double)
Try
Comandos.Parameters.AddWithValue(strNomeParametro, dblValor)
Catch excecao As SqlException
MsgBox("Erro em tempo de execucao: " + excecao.Message)
End Try
End Sub
'adiciona o parametro ao objeto comandos
Public Sub AdicionarParametroNumeroInteiro(ByVal strNomeParametro As String, ByVal intValor As Integer)
Try
Comandos.Parameters.AddWithValue(strNomeParametro, intValor)
Catch excecao As SqlException
MsgBox("Erro em tempo de execucao: " + excecao.Message)
End Try
End Sub
'adiciona o parametro ao objeto comandos
Public Sub AdicionarParametroString(ByVal strNomeParametro As String, ByVal strValor As String)
Try
Comandos.Parameters.AddWithValue(strNomeParametro, strValor)
Catch excecao As SqlException
MsgBox("Erro em tempo de execucao: " + excecao.Message)
End Try
End Sub
'adiciona o parametro ao objeto comandos
Public Sub AdicionarParametroDataHora(ByVal strNomeParametro As String, ByVal datValor As DateTime)
Try
Comandos.Parameters.AddWithValue(strNomeParametro, datValor)
Catch excecao As SqlException
MsgBox("Erro em tempo de execucao: " + excecao.Message)
End Try
End Sub
'executa o comando de dados
Public Sub ExecutaSQL()
Try
Comandos.ExecuteNonQuery()
Catch excecao As SqlException
MsgBox("Erro em tempo de execução: " + excecao.Message)
End Try
Comandos.Dispose()
End Sub
'executa o comando de dados
Public Function ExecutaSQL_ComRetorno() As Double
Dim dblRetorno As Double = 0
Try
dblRetorno = Comandos.ExecuteScalar()
Catch excecao As SqlException
MsgBox("Erro em tempo de execução: " + excecao.Message)
End Try
Comandos.Dispose()
ExecutaSQL_ComRetorno = dblRetorno
End Function
'retorna a conexao criada com o banco de dados
Public Function ConexaoAtiva()
Return ConexaoBD
End Function
'cria objeto DataAdapter
Public Sub CriaDataAdapter()
DataAdapter = New SqlDataAdapter
End Sub
'atribui a propriedade SelectCommand de DataTable e conteudo de Comandos
Public Sub DataAdapterComando()
DataAdapter.SelectCommand = Comandos
End Sub
'preencha uma tabela com dados retornados
Public Sub PreencherDataSet(ByVal MeuDataSet As System.Data.DataTable)
DataAdapter.Fill(MeuDataSet)
End Sub
End Class
|
'CORRELATED QUERIES'
'uses values of the outer query to generate a result'
'depends on the main query to execute'
'are evaluated in loops, for each row. This means correlated queries increase runtime'
SELECT
-- Select country ID, date, home, and away goals from match
main.country_id,
main.date,
main.home_goal,
main.away_goal
FROM match AS main
WHERE
-- Filter the main query by the subquery
(home_goal + away_goal) >
(SELECT AVG((sub.home_goal + sub.away_goal) * 3)
FROM match AS sub
-- Join the main query to the subquery in WHERE
WHERE main.country_id = sub.country_id);
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'NESTED SUBQUERIES'
'subquery inside another subquery'
'correlated subquery requires both the outer and inner subquery to run and produce results'
SELECT
-- Select the season and max goals scored in a match
season,
MAX(home_goal + away_goal) AS max_goals,
-- Select the overall max goals scored in a match
(SELECT MAX(home_goal + away_goal) FROM match) AS overall_max_goals,
-- Select the max number of goals scored in any match in July
(SELECT MAX(home_goal + away_goal)
FROM match
WHERE id IN (
SELECT id FROM match WHERE EXTRACT(MONTH FROM date) = 07)) AS july_max_goals
FROM match
GROUP BY season;
SELECT
c.name AS country,
-- Calculate the average matches per season
AVG(outer_s.matches) AS avg_seasonal_high_scores
FROM country AS c
-- Left join outer_s to country
LEFT JOIN (
SELECT country_id, season,
COUNT(id) AS matches
FROM (
SELECT country_id, season, id
FROM match
WHERE home_goal >= 5 OR away_goal >= 5) AS inner_s
-- Close parentheses and alias the subquery
GROUP BY country_id, season) AS outer_s
ON c.id = outer_s.country_id
GROUP BY country;
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'COMMON TABLE EXPRESSIONS (CTE)'
'table declared before the main query'
'for easier readablity'
WITH cte AS (
SELECT col1, col2
FROM table)
SELECT
AVG(col1) AS avg_col
FROM cte
'Why use CTE?'
'executed ones: CTE is then stored in memory. Improves query performance'
'improve organization of queries'
'referencing other ctes'
'referencing itself (SELF JOIN)'
-- Set up your CTE
WITH match_list AS (
SELECT
country_id,
id
FROM match
WHERE (home_goal + away_goal) >= 10)
-- Select league and count of matches from the CTE
SELECT
l.name AS league,
COUNT(match_list.id) AS matches
FROM league AS l
-- Join the CTE to the league table
LEFT JOIN match_list ON l.id = match_list.country_id
GROUP BY l.name;
|
#!/usr/bin/env python
import rospy
from nav_msgs.msg import OccupancyGrid
from sensor_msgs.msg import LaserScan
from tf.transformations import euler_from_quaternion
from filterpy.kalman import KalmanFilter
import numpy as np
class ObstacleTracker:
def __init__(self):
self.map = None
self.laser = None
self.velocities = {}
self.prev_positions = {}
self.current_positions = {}
self.kf_list = []
self.dt = 0.1
self.max_distance = 10.0 # maximum distance between current and previous position to be considered the same obstacle
# Initialize Kalman filters for each obstacle
self.num_obstacles = 10 # number of obstacles to track
for i in range(self.num_obstacles):
kf = KalmanFilter(dim_x=4, dim_z=2)
kf.x = np.array([0, 0, 0, 0]) # initial state: x, y, vx, vy
kf.P = np.eye(4) * 100 # initial covariance matrix
kf.F = np.array([[1, 0, self.dt, 0], [0, 1, 0, self.dt], [0, 0, 1, 0], [0, 0, 0, 1]]) # state transition matrix
kf.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) # observation matrix
kf.R = np.array([[0.01, 0], [0, 0.01]]) # measurement noise covariance matrix
self.kf_list.append(kf)
# Subscribe to map and laser scan topics
rospy.Subscriber("/map", OccupancyGrid, self.map_callback)
rospy.Subscriber("/scan", LaserScan, self.laser_callback)
def map_callback(self, msg):
self.map = msg
def laser_callback(self, msg):
self.laser = msg
def run(self):
rate = rospy.Rate(10) # 10 Hz
while not rospy.is_shutdown():
if self.map is not None and self.laser is not None:
# Transform robot's position to map's frame of reference
(trans, rot) = self.tf_listener.lookupTransform(self.map.header.frame_id, self.laser.header.frame_id, rospy.Time(0))
robot_x, robot_y, robot_yaw = self.get_robot_pose(trans, rot)
# Iterate over all cells in the map and detect obstacles
for i in range(self.map.info.width):
for j in range(self.map.info.height):
index = j * self.map.info.width + i
if self.map.data[index] > 50: # obstacle detected
# Convert cell coordinates to world coordinates
x = i * self.map.info.resolution + self.map.info.origin.position.x
y = j * self.map.info.resolution + self.map.info.origin.position.y
# Find the closest obstacle in the previous map update
min_distance = float("inf")
min_kf_index = None
for k in range(self.num_obstacles):
if k in self.prev_positions:
distance = np.sqrt((x - self.prev_positions[k][0])**2 + (y - self.prev_positions[k][1])**2)
if distance < min_distance:
min_distance = distance
min_kf_index = k
# import rospy
# from nav_msgs.msg import OccupancyGrid
# from filterpy.kalman import KalmanFilter
# import numpy as np
# class ObstacleTracker:
# def __init__(self):
# self.map = None
# self.velocities = {}
# self.prev_positions = {}
# self.current_positions = {}
# self.kf_list = []
# self.dt = 0.1
# self.max_distance = 10.0 # maximum distance between current and previous position to be considered the same obstacle
# # Initialize Kalman filters for each obstacle
# self.num_obstacles = 10 # number of obstacles to track
# for i in range(self.num_obstacles):
# kf = KalmanFilter(dim_x=4, dim_z=2)
# kf.x = np.array([0, 0, 0, 0]) # initial state: x, y, vx, vy
# kf.P = np.eye(4) * 100 # initial covariance matrix
# kf.F = np.array([[1, 0, self.dt, 0], [0, 1, 0, self.dt], [0, 0, 1, 0], [0, 0, 0, 1]]) # state transition matrix
# kf.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) # observation matrix
# kf.R = np.array([[0.01, 0], [0, 0.01]]) # measurement noise covariance matrix
# self.kf_list.append(kf)
# # Subscribe to map topic
# rospy.Subscriber("/map", OccupancyGrid, self.map_callback)
# def map_callback(self, msg):
# self.map = msg
# def run(self):
# rate = rospy.Rate(10) # 10 Hz
# while not rospy.is_shutdown():
# if self.map is not None:
# # Iterate over all cells in the map and detect obstacles
# for i in range(self.map.info.width):
# for j in range(self.map.info.height):
# index = j * self.map.info.width + i
# if self.map.data[index] > 50: # obstacle detected
# # Convert cell coordinates to world coordinates
# x = i * self.map.info.resolution + self.map.info.origin.position.x
# y = j * self.map.info.resolution + self.map.info.origin.position.y
# # Find the closest obstacle in the previous map update
# min_distance = float("inf")
# min_kf_index = None
# for k in range(self.num_obstacles):
# if k in self.prev_positions:
# distance = np.sqrt((x - self.prev_positions[k][0])**2 + (y - self.prev_positions[k][1])**2)
# if distance < min_distance:
# min_distance = distance
# min_kf_index = k
# if min_kf_index is not None and min_distance < self.max_distance:
# # Update Kalman filter with new observation
# kf = self.kf_list[min_kf_index]
# measurement = np.array([[x], [y]])
# kf.update(measurement)
# # Store current and previous positions of obstacle
# self.current_positions[min_kf_index] = (x, y)
# self.prev_positions.pop(min_kf_index, None)
# else:
# # Create a new Kalman filter for the obstacle
# kf_index = None
# for k in range(self.num_obstacles):
# if
#!/usr/bin/env python
# import rospy
# from nav_msgs.msg import OccupancyGrid
# from geometry_msgs.msg import TwistWithCovarianceStamped
# from filterpy.kalman import KalmanFilter
# from numpy import dot, eye, array
# class ObstacleVelocityEstimator:
# def __init__(self):
# # Initialize ROS node
# rospy.init_node('obstacle_velocity_estimator', anonymous=True)
# # Initialize subscribers and publishers
# self.map_sub = rospy.Subscriber('/map', OccupancyGrid, self.map_callback)
# self.velocity_pub = rospy.Publisher('/obstacle_velocity', TwistWithCovarianceStamped, queue_size=10)
# # Initialize class variables
# self.grid_map = None
# self.grid_resolution = None
# self.kf = None
# def map_callback(self, map):
# # Save map data and resolution
# self.grid_map = array(map.data).reshape(map.info.height, map.info.width)
# self.grid_resolution = map.info.resolution
# # Initialize Kalman filter if not already initialized
# if self.kf is None:
# self.kf = KalmanFilter(dim_x=4, dim_z=2)
# self.kf.x = array([0.0, 0.0, 0.0, 0.0]).T
# self.kf.P = eye(4) * 1000
# self.kf.R = eye(2) * 10
# self.kf.Q = eye(4) * 0.01
# # Predict and update Kalman filter using map data
# if self.kf is not None:
# dt = 1.0 / rospy.get_param('~rate')
# self.kf.F = array([[1, 0, dt, 0],
# [0, 1, 0, dt],
# [0, 0, 1, 0],
# [0, 0, 0, 1]])
# self.kf.predict()
# for i in range(self.grid_map.shape[0]):
# for j in range(self.grid_map.shape[1]):
# if self.grid_map[i, j] > 0:
# x = j * self.grid_resolution
# y = i * self.grid_resolution
# z = array([x, y])
# H = array([[1, 0, 0, 0],
# [0, 1, 0, 0]])
# self.kf.update(z, H)
# # Publish estimated velocity as TwistWithCovarianceStamped message
# velocity_msg = TwistWithCovarianceStamped()
# velocity_msg.header.stamp = rospy.Time.now()
# velocity_msg.twist.twist.linear.x = self.kf.x[2]
# velocity_msg.twist.twist.linear.y = self.kf.x[3]
# velocity_msg.twist.covariance = self.kf.P.flatten().tolist()
# self.velocity_pub.publish(velocity_msg)
# if __name__ == '__main__':
# try:
# estimator = ObstacleVelocityEstimator()
# rospy.spin()
# except rospy.ROSInterruptException:
# pass
#!/usr/bin/env python
import rospy
import numpy as np
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import OccupancyGrid
from geometry_msgs.msg import PoseArray, PoseStamped, Twist
from filterpy.kalman import KalmanFilter
NUM_OBS = 3 # number of obstacles
class KalmanVelEstimator:
def __init__(self):
self.obstacle_poses = np.zeros((NUM_OBS,3)) # obstacle poses [x,y,theta]
self.obstacle_vels = np.zeros((NUM_OBS,2)) # obstacle velocities [vx,vy]
self.filter_list = [] # list of Kalman filters for each obstacle
# Initialize Kalman filters
for i in range(NUM_OBS):
kf = KalmanFilter(dim_x=4, dim_z=2)
kf.F = np.array([[1.0, 0.0, 0.1, 0.0],
[0.0, 1.0, 0.0, 0.1],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0]])
kf.H = np.array([[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0]])
kf.R = np.array([[0.01, 0.0],
[0.0, 0.01]])
kf.P = np.diag([1.0, 1.0, 1.0, 1.0])
self.filter_list.append(kf)
# Subscribe to laser data and occupancy grid map
self.laser_sub = rospy.Subscriber('/scan', LaserScan, self.laser_callback)
self.grid_sub = rospy.Subscriber('/map', OccupancyGrid, self.grid_callback)
# Publish estimated obstacle poses and Turtlebot3 velocity
self.obstacle_poses_pub = rospy.Publisher('/obstacle_poses', PoseArray, queue_size=1)
self.cmd_vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
def laser_callback(self, scan_msg):
# Extract laser data and estimate obstacle velocities using Kalman filters
ranges = np.array(scan_msg.ranges)
angles = np.linspace(scan_msg.angle_min, scan_msg.angle_max, len(ranges))
for i in range(NUM_OBS):
# TODO: implement obstacle detection and pose estimation from laser data
# For now, assume that obstacle poses are known
vel_x = 0.0
vel_y = 0.0
if i == 0:
vel_x = 0.1
vel_y = 0.0
elif i == 1:
vel_x = 0.0
vel_y = 0.1
elif i == 2:
vel_x = -0.1
vel_y = -0.1
# Update Kalman filter
kf = self.filter_list[i]
kf.predict()
kf.update(np.array([vel_x, vel_y]))
self.obstacle_vels[i,:] = kf.x
def grid_callback(self, grid_msg):
# Extract occupancy grid map and update obstacle poses using estimated velocities
# For now, assume that obstacle poses are updated with constant velocity model
resolution = grid_msg.info.resolution
origin_x = grid_msg.info.origin.position.x
origin_y = grid_msg.info.origin.position.y
data = np.array(grid_msg.data).reshape(grid_msg.info.height, grid_msg.info.width)
for i in range(NUM_OBS):
pose = self.obstacle_poses[i,:]
vel = self.obstacle_vels[i,:]
pose[0] += vel[0] * np.cos(pose[2]) * resolution
pose[1] += vel[1] * np.sin(pose[2]) * resolution
pose[2] = np.arctan2(vel[1], vel[0])
pose[0] = np.clip(pose[0], 0.0, data.shape[1] * resolution)
pose[1] = np.clip(pose[1], 0.0, data.shape[0] * resolution)
self.obstacle_poses[i,:] = pose
# Publish estimated obstacle poses
poses_msg = PoseArray()
poses_msg.header.stamp = rospy.Time.now()
poses_msg.header.frame_id = 'map'
for i in range(NUM_OBS):
pose = self.obstacle_poses[i,:]
p = PoseStamped()
p.header.stamp = rospy.Time.now()
p.header.frame_id = 'map'
p.pose.position.x = pose[0] + origin_x
p.pose.position.y = pose[1] + origin_y
p.pose.position.z = 0.0
p.pose.orientation.z = np.sin(pose[2]/2)
p.pose.orientation.w = np.cos(pose[2]/2)
poses_msg.poses.append(p)
self.obstacle_poses_pub.publish(poses_msg)
# Publish Turtlebot3 velocity
cmd_vel_msg = Twist()
# TODO: implement control law to follow detected obstacles
cmd_vel_msg.linear.x = 0.1
self.cmd_vel_pub.publish(cmd_vel_msg)
if __name__ == '__main__':
rospy.init_node('kalman_vel_estimator', anonymous=True)
estimator = KalmanVelEstimator()
rospy.spin()
|
import 'dart:convert';
import 'dart:io';
import 'package:asws_mobile/utils/textfeildutils.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../constant/apiendpoint.dart';
import '../../utils/loader.dart';
import '../../utils/textutils.dart';
import '../../utils/toast.dart';
class AddStudentScreen extends StatefulWidget {
List<String> droplist;
List<String> parentstatus;
AddStudentScreen(this.droplist, this.parentstatus);
@override
State<AddStudentScreen> createState() => _AddStudentScreenState();
}
class _AddStudentScreenState extends State<AddStudentScreen> {
TextEditingController _firstnamecontroller = TextEditingController();
TextEditingController _lastnamecontroller = TextEditingController();
// TextEditingController _zonecontroller = TextEditingController();
// TextEditingController _centercontroller = TextEditingController();
TextEditingController _statecontroller = TextEditingController();
TextEditingController _citycontroller = TextEditingController();
TextEditingController _pincodecontroller = TextEditingController();
TextEditingController _siblingfullnamecontroller = TextEditingController();
TextEditingController _siblingagecontroller = TextEditingController();
TextEditingController _siblingstandardcontroller = TextEditingController();
TextEditingController _siblingschoolnamecontroller = TextEditingController();
// TextEditingController _gardianstatuscontroller = TextEditingController();
TextEditingController _gardianfirstnameontroller = TextEditingController();
TextEditingController _gardianlastnameontroller = TextEditingController();
TextEditingController _gardianphonecontroller = TextEditingController();
TextEditingController _gardianemailcontroller = TextEditingController();
TextEditingController _gardianeducationcontroller = TextEditingController();
TextEditingController _gardianaddresscontroller = TextEditingController();
TextEditingController _gardianocccupationcontroller = TextEditingController();
//TextEditingController _gendercontroller = TextEditingController();
TextEditingController _dobcontroller = TextEditingController();
TextEditingController _emailcontroller = TextEditingController();
TextEditingController _addresscontroller = TextEditingController();
TextEditingController _schoolcontroller = TextEditingController();
// TextEditingController _startdatecontroller = TextEditingController();
TextEditingController _adhaarcontroller = TextEditingController();
TextEditingController _phonecontroller = TextEditingController();
List<DropdownMenuItem<String>> droplist = [];
int _index = 0;
File? userimage;
String? gender = "Male";
String? issibling = "Yes";
String? broorsis = "Brother";
String _currentSelectedcenter = "";
String _currentSelectedzone = "";
String _parentstatus = "";
@override
void initState() {
// TODO: implement initState
super.initState();
_currentSelectedcenter = widget.droplist.first;
_currentSelectedzone = widget.droplist.first;
_parentstatus = widget.parentstatus.first;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
title: const Text("Add Student"),
),
body: Stepper(
currentStep: _index,
onStepCancel: () {
if (_index > 0) {
setState(() {
_index -= 1;
});
}
},
onStepContinue: () {
if (_index <= 1) {
setState(() {
_index += 1;
});
} else {
if (userimage != null) {
if (_firstnamecontroller.text != "") {
if (_schoolcontroller.text != "") {
if (_dobcontroller.text != "") {
if (_adhaarcontroller.text != "") {
if (_phonecontroller.text != "") {
if (_emailcontroller.text != "") {
if (_statecontroller.text != "") {
if (_citycontroller.text != "") {
if (_pincodecontroller.text != "") {
if (_adhaarcontroller.text != "") {
if (_gardianfirstnameontroller.text != "") {
if (_gardianphonecontroller.text != "") {
if (_gardianemailcontroller.text != "") {
if (_addresscontroller.text != "") {
addnewStudent(userimage, context);
} else {
showToast("Please Enter Address");
}
} else {
showToast("Please Enter Parent Email");
}
} else {
showToast(
"Please Enter Parent Mobile No");
}
} else {
showToast("Please Enter Parent Name");
}
} else {
showToast("Please Enter Aadhaar No");
}
} else {
showToast("Please Enter PinCode");
}
} else {
showToast("Please Enter City");
}
} else {
showToast("Please Enter State");
}
} else {
showToast("Please Enter Email");
}
} else {
showToast("Please Enter Mobile No");
}
} else {
showToast("Please Enter Aadhaar No");
}
} else {
showToast("Please Enter Date of Birth");
}
} else {
showToast("Please Enter School Name");
}
} else {
showToast("Please Enter Student Name");
}
} else {
showToast("Please upload photo");
}
}
},
onStepTapped: (int index) {
setState(() {
_index = index;
});
},
steps: <Step>[
Step(
isActive: _index == 0,
title: Text(
'Student Details',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: _index == 0
? Theme.of(context).primaryColor
: Colors.black),
),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Stack(
children: [
userimage == null
? const CircleAvatar(
radius: 50,
)
: CircleAvatar(
radius: 50,
backgroundImage: FileImage(userimage!),
),
GestureDetector(
onTap: () {
openphotooption(context);
},
child: CircleAvatar(
backgroundColor: Colors.grey.shade300,
radius: 15,
child: const Icon(
Icons.add_a_photo,
color: Colors.black,
size: 20,
),
),
)
],
),
),
const SizedBox(
height: 20,
),
normalgreytext("Select Zone"),
const SizedBox(
height: 5,
),
DropdownButton<String>(
isExpanded: true,
value: _currentSelectedzone,
icon: const Icon(Icons.arrow_downward),
elevation: 16,
// style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 1,
color: Colors.grey,
),
onChanged: (String? value) {
// This is called when the user selects an item.
setState(() {
_currentSelectedzone = value!;
});
},
items: widget.droplist
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
const SizedBox(
height: 20,
),
normalgreytext("Select Center"),
const SizedBox(
height: 5,
),
DropdownButton<String>(
isExpanded: true,
value: _currentSelectedcenter,
icon: const Icon(Icons.arrow_downward),
elevation: 16,
// style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 1,
color: Colors.grey,
),
onChanged: (String? value) {
// This is called when the user selects an item.
setState(() {
_currentSelectedcenter = value!;
});
},
items: widget.droplist
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _firstnamecontroller,
hinttext: "First name",
title: "First Name",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _lastnamecontroller,
hinttext: "Last name",
title: "Last Name",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _schoolcontroller,
hinttext: "School name",
title: "School Name",
isnum: 1,
),
const SizedBox(
height: 20,
),
normalgreytext("Gender"),
const SizedBox(
height: 5,
),
Row(
children: [
Row(
children: [
Radio<String>(
value: "Male",
groupValue: gender,
onChanged: (value) {
setState(() {
gender = value;
});
},
),
Text("Male")
],
),
SizedBox(
width: 10,
),
Row(
children: [
Radio<String>(
value: "Female",
groupValue: gender,
onChanged: (value) {
setState(() {
gender = value;
});
},
),
Text("Female")
],
),
],
),
const SizedBox(
height: 20,
),
GestureDetector(
onTap: () {
_pickDateDialog();
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
normalgreytext("Date of Birth"),
const SizedBox(
height: 5,
),
TextFormField(
controller: _dobcontroller,
decoration: const InputDecoration(
enabled: false,
hintText: "Birth date",
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
],
),
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _adhaarcontroller,
hinttext: "xxxxxxxxxxxxx",
title: "Aadhaar No.",
isnum: 0,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _phonecontroller,
hinttext: "987665543211",
title: "Mobile No.",
isnum: 0,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _emailcontroller,
hinttext: "Email",
title: "Email",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _addresscontroller,
hinttext: "address",
title: "Address",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _statecontroller,
hinttext: "State",
title: "State",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _citycontroller,
hinttext: "City",
title: "City",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _pincodecontroller,
hinttext: "",
title: "Pincode",
isnum: 0,
),
],
)),
Step(
isActive: _index == 1,
title: Text(
'Sibling Details',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: _index == 1
? Theme.of(context).primaryColor
: Colors.black),
),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
normalgreytext("Sibling"),
const SizedBox(
height: 5,
),
Row(
children: [
Row(
children: [
Radio<String>(
value: "Yes",
groupValue: issibling,
onChanged: (value) {
setState(() {
issibling = value;
});
},
),
Text("Yes")
],
),
SizedBox(
width: 10,
),
Row(
children: [
Radio<String>(
value: "No",
groupValue: issibling,
onChanged: (value) {
setState(() {
issibling = value;
_index += 1;
});
},
),
Text("No")
],
),
],
),
const SizedBox(
height: 20,
),
Row(
children: [
Row(
children: [
Radio<String>(
value: "Brother",
groupValue: broorsis,
onChanged: (value) {
setState(() {
broorsis = value;
});
},
),
Text("Brother")
],
),
SizedBox(
width: 10,
),
Row(
children: [
Radio<String>(
value: "Sister",
groupValue: broorsis,
onChanged: (value) {
setState(() {
broorsis = value;
_index += 1;
});
},
),
Text("Sister")
],
),
],
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _siblingfullnamecontroller,
hinttext: "Name",
title: "Full Name",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _siblingagecontroller,
hinttext: "",
title: "Age",
isnum: 0,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _siblingstandardcontroller,
hinttext: "",
title: "Standard",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _siblingschoolnamecontroller,
hinttext: "",
title: "School Name",
isnum: 1,
),
],
)),
Step(
isActive: _index == 2,
title: Text(
'Family Details',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: _index == 2
? Theme.of(context).primaryColor
: Colors.black),
),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 20,
),
normalgreytext("Parental Status"),
const SizedBox(
height: 5,
),
DropdownButton<String>(
isExpanded: true,
value: _parentstatus,
icon: const Icon(Icons.arrow_downward),
elevation: 16,
// style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 1,
color: Colors.grey,
),
onChanged: (String? value) {
// This is called when the user selects an item.
setState(() {
_parentstatus = value!;
});
},
items: widget.parentstatus
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _gardianfirstnameontroller,
hinttext: "",
title: "First Name",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _gardianlastnameontroller,
hinttext: "",
title: "Last Name",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _gardianphonecontroller,
hinttext: "",
title: "Phone No.",
isnum: 0,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _gardianemailcontroller,
hinttext: "",
title: "Email",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _gardianaddresscontroller,
hinttext: "address",
title: "Address",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _gardianeducationcontroller,
hinttext: "",
title: "Educational Qualification",
isnum: 1,
),
const SizedBox(
height: 20,
),
Feilds2(
controller: _gardianocccupationcontroller,
hinttext: "",
title: "Occupation",
isnum: 1,
),
],
)),
],
),
);
}
void openphotooption(context) {
showModalBottomSheet(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
isScrollControlled: true,
context: context,
builder: (context) {
return Container(
padding: const EdgeInsets.all(30),
height: 180,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
GestureDetector(
onTap: () {
pickimage(ImageSource.camera);
Navigator.pop(context);
},
child: Column(
children: const [
CircleAvatar(
radius: 30,
child: Icon(
Icons.camera,
color: Colors.white,
),
),
SizedBox(
height: 20,
),
Text("Camara")
],
),
),
GestureDetector(
onTap: () {
pickimage(ImageSource.gallery);
Navigator.pop(context);
},
child: Column(
children: const [
CircleAvatar(
radius: 30,
child: Icon(
Icons.image,
color: Colors.white,
),
),
SizedBox(
height: 20,
),
Text("Gallery")
],
),
)
],
),
);
});
}
void pickimage(source) async {
final image =
await ImagePicker().pickImage(source: source, imageQuality: 20);
if (image == null) return;
final temimage = File(image.path);
setState(() {
userimage = temimage;
});
}
void _pickDateDialog() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
//which date will display when user open the picker
firstDate: DateTime(1950),
//what will be the previous supported year in picker
lastDate: DateTime
.now()) //what will be the up to supported date in picker
.then((pickedDate) {
//then usually do the future job
if (pickedDate == null) {
//if user tap cancel then this function will stop
return;
}
setState(() {
//for rebuilding the ui
_dobcontroller.text = DateFormat('yyyy/MM/dd').format(pickedDate);
});
});
}
void addnewStudent(File? imageFileList, context) async {
bool sib = issibling == "Yes";
int sibage = int.parse(
_siblingagecontroller.text.isEmpty ? "0" : _siblingagecontroller.text);
debugPrint(sib.toString());
print(sibage);
SharedPreferences userdata = await SharedPreferences.getInstance();
final token = userdata.getString("token");
print(token);
final url = Uri.parse(ApiEndPoints.baseurl + ApiEndPoints.addnewstudent);
GlobalMethods().showLoader(context, true);
var request = http.MultipartRequest("Post", url);
request.files
.add(await http.MultipartFile.fromPath("file", imageFileList!.path));
request.headers.addAll({
"Content-type":
"multipart/form-data; boundary=<calculated when request is sent>",
"Authorization": "Bearer $token"
});
request.fields.addAll({
'student':
'{\n"addmissionNumber":68787,\n"addmissionDate":"${DateFormat('yyyy/MM/dd').format(DateTime.now())}",\n "firstName":"${_firstnamecontroller.text} ",\n"lastName":"${_lastnamecontroller.text}",\n"dateOfBirth":"${_dobcontroller.text}",\n"placeOfBirth":"ueruige3r",\n"priviousSchool":"${_schoolcontroller.text}",\n"email":"${_emailcontroller.text}",\n "phone":${int.parse(_phonecontroller.text)},\n "address":"${_addresscontroller.text}",\n "state":"${_statecontroller.text}",\n "zipCode":${int.parse(_pincodecontroller.text)},\n "city":"${_citycontroller.text}",\n "nearByCentre":"$_currentSelectedcenter",\n "siblings":$sib,\n "brOrSis":"$broorsis",\n "siblingFullName":"${_siblingfullnamecontroller.text}",\n "sibAge":$sibage,\n "sibStandard":"${_siblingstandardcontroller.text}",\n "sibSidNumber":6890,\n "parentalStatus":"$_parentstatus",\n"parentFirstName":"${_gardianfirstnameontroller.text}",\n "parentLastName":"${_gardianlastnameontroller.text}",\n "parentEmail":"${_gardianemailcontroller.text}",\n "parentPhone":45432453,\n "parentDateOfBirth":"2002/3/12",\n"parentPlaceOfBirth":"fueuifh",\n "mediumOfinstruction":"efiefib",\n "parentAddress":"${_gardianaddresscontroller.text}",\n"parentState":"euiiue",\n "parentZipCode":7979,\n"parentCity":"neifgeigfi",\n "educationQualification":"${_gardianeducationcontroller.text}",\n "occupation":"${_gardianocccupationcontroller.text}"\n}'
});
var streamResponse = await request.send();
var response = await http.Response.fromStream(streamResponse);
GlobalMethods().showLoader(context, false);
debugPrint(response.statusCode.toString());
if (response.statusCode == 200) {
_firstnamecontroller.text = "";
_lastnamecontroller.text = "";
_statecontroller.text = "";
_citycontroller.text = "";
_pincodecontroller.text = "";
_siblingfullnamecontroller.text = "";
_siblingagecontroller.text = "";
_siblingstandardcontroller.text = "";
_siblingschoolnamecontroller.text = "";
_gardianfirstnameontroller.text = "";
_gardianlastnameontroller.text = "";
_gardianphonecontroller.text = "";
_gardianemailcontroller.text = "";
_gardianeducationcontroller.text = "";
_gardianaddresscontroller.text = "";
_gardianocccupationcontroller.text = "";
_dobcontroller.text = "";
_emailcontroller.text = "";
_addresscontroller.text = "";
_schoolcontroller.text = "";
_adhaarcontroller.text = "";
_phonecontroller.text = '';
showToast("Post Uploaded Sucessfully");
} else {
showToast("Something Went Wrong");
}
}
}
|
---
title: jQuery - 흐르는 롤링 배너 (+ 반응형 타입 추가)
description: >
흐르는 형태로 무한 롤링되는 배너 코드 예제입니다.
slug: 2023-07-23-flow-banner
date: 2023-07-23 00:00:00+0000
image: https://media.githubusercontent.com/media/ctrlcccv/ctrlcccv.github.io/master/assets/img/post/flow-banner.webp
categories:
- jQuery
tags:
- 흐르는 롤링 배너
---
흐르는 형태로 무한 롤링되는 배너를 만들었다.
## HTML 구조
```html
<div class="flow_banner">
<ul class="list">
<li>TEXT1</li>
<li>TEXT2</li>
<li>TEXT3</li>
<li>TEXT4</li>
<li>TEXT5</li>
</ul>
</div>
```
무한 롤링 효과를 위해 list 클래스의 요소들이 flow_banner 배너의 2배 크기만큼 복제될 예정이다.
## CSS 스타일
```css
ul, li {list-style: none;}
.flow_banner {overflow: hidden;display: flex;max-width: 1180px;margin: 30px auto;background: #000;}
.flow_banner .list {display: flex;}
.flow_banner .list > li {white-space: nowrap;font-size: 18px;color: #fff;padding: 20px;}
@keyframes flowRolling {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-100%);
}
}
/* 반응형 스타일 */
@media (max-width: 1280px) {
.flow_banner .list > li {font-size: 16px;padding: 10px;}
}
@media (max-width: 767px) {
.flow_banner .list > li {font-size: 14px;padding: 5px;}
}
```
list 클래스에 flowRolling 애니메이션을 추가할 예정이다.
transform:translateX() 속성을 사용하여 list 클래스의 가로 크기만큼 왼쪽으로 이동하는 애니메이션이다.
배너 함수를 실행하면서 복제된 요소들의 애니메이션 타이밍이 어긋나서 함수가 실행된 후 애니메이션 속성을 추가했다.
## jQuery 코드 (크기 고정형)
```js
$(window).on('load', function() {
setFlowBanner();
})
function setFlowBanner() {
const $wrap = $('.flow_banner');
const $list = $('.flow_banner .list');
let wrapWidth = $wrap.width();
let listWidth = $list.width();
const speed = 92; //1초에 몇픽셀 이동하는지 설정
//리스트 복제
let $clone = $list.clone();
$wrap.append($clone);
flowBannerAct()
//배너 실행 함수
function flowBannerAct() {
//무한 반복을 위해 리스트를 복제 후 배너에 추가
if (listWidth < wrapWidth) {
const listCount = Math.ceil(wrapWidth * 2 / listWidth);
for (let i = 2; i < listCount; i++) {
$clone = $clone.clone();
$wrap.append($clone);
}
}
$wrap.find('.list').css({
'animation': `${listWidth / speed}s linear infinite flowRolling`
});
}
// 마우스가 요소 위로 진입했을 때 일시정지
$wrap.on('mouseenter', function () {
$wrap.find('.list').css('animation-play-state', 'paused');
});
// 마우스가 요소에서 빠져나갈 때 재생
$wrap.on('mouseleave', function () {
$wrap.find('.list').css('animation-play-state', 'running');
});
}
```
레이아웃 변화가 없는 배너를 위한 스크립트다. 리사이즈 이벤트와 배너 초기화를 삭제했다.
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8535540836842352" crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-8535540836842352"
data-ad-slot="2974559225"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
## jQuery 코드 (반응형)
```js
$(window).on('load', function() {
setFlowBanner();
})
function setFlowBanner() {
const $wrap = $('.flow_banner');
const $list = $('.flow_banner .list');
let wrapWidth = ''; //$wrap의 가로 크기
let listWidth = ''; //$list의 가로 크기
const speed = 92; //1초에 몇픽셀 이동하는지 설정
//리스트 복제
let $clone = $list.clone();
$wrap.append($clone);
flowBannerAct()
//반응형 :: 디바이스가 변경 될 때마다 배너 롤링 초기화
let oldWChk = window.innerWidth > 1279 ? 'pc' : window.innerWidth > 767 ? 'ta' : 'mo';
$(window).on('resize', function() {
let newWChk = window.innerWidth > 1279 ? 'pc' : window.innerWidth > 767 ? 'ta' : 'mo';
if (newWChk != oldWChk) {
oldWChk = newWChk;
flowBannerAct();
}
});
//배너 실행 함수
function flowBannerAct() {
//배너 롤링 초기화
if (wrapWidth != '') {
$wrap.find('.list').css({
'animation': 'none'
});
$wrap.find('.list').slice(2).remove();
}
wrapWidth = $wrap.width();
listWidth = $list.width();
//무한 반복을 위해 리스트를 복제 후 배너에 추가
if (listWidth < wrapWidth) {
const listCount = Math.ceil(wrapWidth * 2 / listWidth);
for (let i = 2; i < listCount; i++) {
$clone = $clone.clone();
$wrap.append($clone);
}
}
$wrap.find('.list').css({
'animation': `${listWidth / speed}s linear infinite flowRolling`
});
}
// 마우스가 요소 위로 진입했을 때 일시정지
$wrap.on('mouseenter', function () {
$wrap.find('.list').css('animation-play-state', 'paused');
});
// 마우스가 요소에서 빠져나갈 때 재생
$wrap.on('mouseleave', function () {
$wrap.find('.list').css('animation-play-state', 'running');
});
}
```
반응형 레이아웃은 창 크기가 변경되면 배너의 크기도 변경되어, 복제된 list 클래스의 수가 맞지 않아 애니메이션 오류가 생길 수 있다. 이를 방지하기 위해 리사이즈 이벤트를 추가했다.
리사이즈할 때마다 배너 함수(flowBannerAct)를 실행하게 되면 브라우저에 과부하를 줄 수 있어, 화면 크기에 따라 디바이스 정보를 변수에 담고 디바이스가 변경되면 함수를 실행했다.
<br>
flowBannerAct 함수가 실행되면 기존 배너 가로 크기를 담은 wrapWidth 변수값이 있을 시, 애니메이션과 복제되었던 list 클래스 요소들을 2개만 남기고 제거하여 초기화했다.
나열된 list 클래스의 가로 크기가 flow_banner 클래스의 가로 크기의 두 배 이상이 되어야 애니메이션이 끝나고 처음으로 돌아갈 때 list 클래스의 뒷부분이 잘리지 않고 무한으로 반복된다.
list 클래스의 가로 크기를 flow_banner 클래스의 가로 크기에 나누어 필요한 요소의 수를 구한 후 반복문을 사용하였다.
<br>
마지막으로 list 클래스의 가로 크기에 speed 변수값을 나누어, list 클래스의 li 개수가 몇 개가 되던 동일한 속도로 이동되도록 애니메이션 속성을 추가했다. 다만 speed 변수값을 픽셀 단위로 선언하여 상대적으로 크기가 작은 모바일에서는 PC화면보다 빠르게 이동되는 것처럼 보일 수 있는데, 이건 레이아웃마다 느낌이 다를 것 같아서 필요하면 따로 예외처리 해주면 될 것 같다.
<br>
<div class="btn_wrap">
<a target="_blank" href="https://ctrlcccv.github.io/ctrlcccv-demo/2023-07-23-flow-banner/">예제결과 미리보기</a>
<a href="https://ctrlcccv.github.io/code/2024-01-05-vertical-banner/">[관련글] jQuery - 아래에서 위로 흐르는 롤링 배너 (반응형)</a>
</div>
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:yechanclock/data/date.dart';
import 'package:yechanclock/data/word_data.dart';
import 'package:yechanclock/ui/lock_page.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String? videoId = YoutubePlayer.convertUrlToId("https://www.youtube.com/watch?v=BBAyRBTfsOU");
var dateData = DateData();
var wordData = WordData();
YoutubePlayerController _controller = YoutubePlayerController(
initialVideoId: '2pPjM_NraCQ',
flags: YoutubePlayerFlags(
autoPlay: true,
),
);
@override
Widget build(BuildContext context) {
final Stream _timeStreamImprove =
Stream.periodic(Duration(seconds: 1), (var i) {
dateData.getNowDateData();
});
int randomValue = Random().nextInt(30);
return StreamBuilder(
stream: _timeStreamImprove,
builder: (context, snapshot) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: (dateData.nowHour >= 10 && dateData.nowDay == 0) ? Text("고생 많았다") : Text(widget.title),
),
body: Center(
child: dateData.nowDay != 0
? Column(
children: <Widget>[
SizedBox(
height: 20,
),
Container(
width: MediaQuery.sizeOf(context).width * 0.8,
height: MediaQuery.sizeOf(context).height * 0.3,
child: Text(
wordData.wordData[randomValue],
style: TextStyle(fontSize: 24),
),
),
SizedBox(
height: 30,
),
Text(
"2024 대학수학능력시험 (D-${dateData.nowDay})",
),
Text(
"${dateData.nowDay - 1}일 ${dateData.nowHour - 1}시간 ${dateData.nowMinute - 1}분 ${dateData.nowSecond}초",
style: Theme.of(context).textTheme.headlineMedium,
)
],
)
: dateData.nowHour >= 10
? Center(
child: Column(
children: [
Text("오메데토"),
Text("축하해"),
YoutubePlayer(
controller: _controller,
),
Container(
height: 500,
width: 300,
child: ListView.builder(
itemCount: wordData.wordData.length,
itemBuilder: (context, idx){
return Column(
children: [
SizedBox(height: 10,),
Container(
child: Text(wordData.wordData[idx]),
),
Container(width: MediaQuery.sizeOf(context).width,height: 0.5,color: Colors.black,)
],
);
}
),
)
],
),
)
: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
width: MediaQuery.sizeOf(context).width * 0.8,
child: Text(
"예찬아 오늘은 너가 그동안의 노력을 성과로 만드는 날이다 운좋게 찍으라는 말은 그동안 너의 노력을 개무시하는 말이라 생각한다 내가 할수있는건 그저 그동안 너가 고생했던 노력들이 합당한 성과를 만들어내기를 바란다. -장현용-",
style: Theme.of(context)
.textTheme
.headlineMedium,
)),
Container(
width: MediaQuery.sizeOf(context).width * 0.8,
child: Text(
"예찬아 잘보고와라 밥이나 한끼해야지. -김대우-",
style: Theme.of(context)
.textTheme
.headlineMedium,
)),
],
),
),
), // T
floatingActionButton: (dateData.nowHour >= 10 && dateData.nowDay == 0) ? Container() : FloatingActionButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (_) => LockPage()));
},
child: Icon(Icons.safety_check),
), // his trailing comma makes auto-formatting nicer for build methods.
);
},
);
}
}
|
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.db import models
class User(AbstractUser):
""""
Login User
各ユーザーPointを取得する
"""
username_validator = UnicodeUsernameValidator()
username = models.CharField(
max_length=150,
unique=False,
validators = [username_validator],
help_text=('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'
),
)
email = models.EmailField(blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
point = models.ForeignKey(
'Point',
related_name='used_point_log',
null=True,
on_delete=models.SET_NULL,
)
class Meta:
default_permissions = ()
|
import { cn } from '@/lib/utils';
import { Alert, AlertDescription, AlertTitle } from './ui';
interface CustomAlertProps {
icon: React.ReactNode;
title: string;
description: string;
className?: string;
variant?: 'default' | 'destructive';
}
export const CustomAlert = ({
icon,
title,
description,
className,
variant = 'default',
}: CustomAlertProps) => {
return (
<Alert variant={variant} className={cn('flex items-center gap-5 z-50', className)}>
<div>{icon}</div>
<div>
<AlertTitle className='text-lg'>{title}</AlertTitle>
<AlertDescription>{description}</AlertDescription>
</div>
</Alert>
);
};
|
import { useState } from "react";
import Modal from "./Modal";
import toast from "react-hot-toast";
import axios from "axios";
import { SERVER_URL } from "../main";
const TodoItem = ({
title,
description,
dueDate,
isCompleted,
toggleHandler,
deleteHandler,
setRefresh,
id,
}) => {
const [updatedTitle, setUpdatedTitle] = useState(title);
const [updatedDescription, setUpdatedDescription] = useState(description);
const [open, setOpen] = useState(false);
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
const updateHandler = async (e) => {
e.preventDefault();
handleClose();
try {
const { data } = await axios.put(
`${SERVER_URL}/task/${id}`,
{
title: updatedTitle,
description: updatedDescription,
},
{
withCredentials: true,
}
);
toast.success(data.message);
setUpdatedTitle("");
setUpdatedDescription("");
setRefresh((prev) => !prev);
} catch (error) {
toast.error(error?.response?.data.message);
}
};
return (
<>
<div className={`todo ${isCompleted && "completed"}`}>
<div>
<h4>{title}</h4>
<p>{description}</p>
<p className="dueDate">Due: {dueDate}</p>
</div>
<div>
<input
onChange={() => toggleHandler(id)}
type="checkbox"
checked={isCompleted}
/>
<div className="todoBtn">
<button onClick={handleOpen} className="deleteBtn">
✏️
</button>
<button onClick={() => deleteHandler(id)} className="deleteBtn">
❌
</button>
</div>
</div>
<Modal
isOpen={open}
onClose={handleClose}
title={updatedTitle}
description={updatedDescription}
setUpdatedTitle={setUpdatedTitle}
setUpdatedDescription={setUpdatedDescription}
updateHandler={updateHandler}
></Modal>
</div>
</>
);
};
export default TodoItem;
|
import { Component, ViewChild } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { Planificacoes } from '../../providers/planificacoes';
import { Chart } from 'chart.js';
import * as moment from 'moment';
import 'moment/locale/pt';
@Component({
selector: 'page-estatisticas',
templateUrl: 'estatisticas.html'
})
export class EstatisticasPage {
@ViewChild('barCanvas') barCanvas;
barChart: any;
mes: any;
locale = moment.locale("pt");
id: number;
constructor(private navCtrl: NavController,private alertCtrl: AlertController, private planService: Planificacoes, private local: Storage) {
}
ionViewDidEnter(){
this.mes = moment().format("MMMM");
this.getAnalytics();
}
getAnalytics(){
this.local.get("id").then(
result => {
this.id = result;
console.log ("res recebeu -> " + result);
let dados = {
mes: moment(this.mes,"MMMM").format("MM"),
id: this.id
}
this.planService.analyticsPlan(dados).then((dados)=>{
let resposta = dados["data"];
this.barChart = new Chart(this.barCanvas.nativeElement, {
type: 'bar',
data: {
labels: ["AFPS", "ACM", "EP", "EM", "ED", "EM","LO/EE","Mat","NT","FC"],
datasets: [{
label: '# de vezes trabalhado',
data: [resposta.area_formacao_pessoal_social, resposta.area_conhecimento_mundo, resposta.expressao_plastica, resposta.expressao_motora, resposta.expressao_dramatica, resposta.expressao_musical, resposta.linguagem_oral_expressao_escrita, resposta.matematica, resposta.novas_tecnologias, resposta.formacao_crista],
backgroundColor: [
'rgba(159, 64, 255, 1)',
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 64, 65, 1)',
'rgba(75, 192, 192, 1)',
'rgba(64, 65, 255, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(25, 63, 100, 1)',
]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
legend: {
display: false
}
}
});
},(err)=>{
console.log("ESTATISTICAS, erro -> " + err);
let alert = this.alertCtrl.create({
title: 'Erro!',
subTitle: 'Erro interno no servidor. Tente mais tarde.',
buttons: [
{
text: 'Ok'
}
]
});
alert.present();
});
}
);
}
mes_anterior(){
this.mes = moment(this.mes, "MMMM").subtract(1, "months").format("MMMM");
this.getAnalytics();
}
mes_seguinte(){
this.mes = moment(this.mes, "MMMM").add(1, "months").format("MMMM");
this.getAnalytics();
}
}
|
import {
ArrayContains,
ArrayMaxSize,
ArrayMinSize,
IsArray,
IsInt,
IsNotEmpty,
Max,
MaxLength,
Min,
MinLength,
ValidateNested,
} from "class-validator";
import { Type } from "class-transformer";
export class CalculatePriceDtoLineItem {
@IsNotEmpty()
@MinLength(1)
@MaxLength(255)
name: string;
@IsNotEmpty()
@Min(0.01)
@Max(99999.99)
price: number;
@IsNotEmpty()
@Min(1)
@Max(1000)
@IsInt()
qty: number;
@IsNotEmpty()
standardVAT: boolean;
}
export class CalculatePriceDto {
@IsNotEmpty()
@ArrayMinSize(1)
@ArrayMaxSize(100)
@IsArray()
@ValidateNested({ each: true })
@Type(() => CalculatePriceDtoLineItem)
items: CalculatePriceDtoLineItem[];
}
|
package java9.bean;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java9.tostring.Node2StringSeparado;
import java9.tostring.Node2StringSeparado2ResumirText;
public class NodoXML2 extends AbstractNodo
{
protected String tagname;
protected String id;
protected List<INodoXMl> hijos = new ArrayList<>();
protected String text;
protected Map<String, String> atributos = new LinkedHashMap<>();
protected Node2StringSeparado node2String = new Node2StringSeparado2ResumirText();
public NodoXML2(String tagname)
{
this();
this.tagname = tagname;
}
public NodoXML2(String tagname, String id)
{
this();
this.tagname = tagname;
this.id = id;
}
public static INodoXMl creaNodoComentario(String comentario)
{
INodoXMl com = new NodoXML2();
com.setComentario(comentario);
return com;
}
@Override
public void addAtributo(String nombreAtrib, String valorAtrib)
{
if (nombreAtrib != null)
this.atributos.put(nombreAtrib, valorAtrib);
}
@Override
public void addHijo(INodoXMl hijo)
{
if (hijo != null) {
hijo.setPadre(this);
this.hijos.add(hijo);
}
}
@Override
public INodoXMl addHijo(String tagNameHijo)
{
NodoXML2 hijo = new NodoXML2(tagNameHijo);
addHijo(hijo);
return hijo;
}
@Override
public String toString()
{
return node2String.node2String(this);
}
@Override
public Stream<INodoXMl> getElementsByTagNameStream(String tagname)
{
return this.hijos.stream().filter(h -> tagname.equals(h.getTagname()));
}
@Override
public List<INodoXMl> getElementsByTagName(String tagname)
{
/**
* List<NodoXML2> l = new ArrayList<>();
getElementsByTagNameStream(tagname).forEach(h -> l.add(h));
return l;
*
*
*/
return getElementsByTagNameStream(tagname).collect(Collectors.toList());
}
@Override
public int numHijos()
{
return this.hijos.size();
}
@Override
public boolean tieneHijos()
{
return (numHijos() > 0);
}
@Override
public int numAtribs()
{
return this.atributos.size();
}
@Override
public boolean tieneAtribs()
{
return (numAtribs() > 0);
}
@Override
public INodoXMl getFirstChild()
{
if (this.hijos.isEmpty())
return null;
return this.hijos.get(0);
}
@Override
public INodoXMl getLastChild()
{
if (this.hijos.isEmpty())
return null;
return this.hijos.get(this.hijos.size());
}
@Override
public INodoXMl getHijo(int i)
{
if (i >= 0 && i < this.hijos.size())
return this.hijos.get(i);
return null;
}
@Override
public String getAtributo(String nombreAtrib)
{
return this.atributos.get(nombreAtrib);
}
@Override
public boolean hasAtributo(String nombreAtrib)
{
return this.atributos.containsKey(nombreAtrib);
}
@Override
public boolean hasAttributes()
{
return !this.atributos.isEmpty();
}
@Override
public boolean hasChilds()
{
return (numHijos() > 0);
}
@Override
public boolean hasAtribs()
{
return (numAtribs() == 0);
}
@Override
public String getTagname()
{
return this.tagname;
}
@Override
public void setTagname(String tagname)
{
this.tagname = tagname;
}
@Override
public String getId()
{
return this.id;
}
@Override
public void setId(String id)
{
this.id = id;
}
@Override
public List<INodoXMl> getHijos()
{
return this.hijos;
}
@Override
public void setHijos(List<INodoXMl> hijos)
{
this.hijos = hijos;
}
@Override
public String getText()
{
return this.text;
}
@Override
public void setText(String text)
{
this.text = text;
}
@Override
public Map<String, String> getAtributos()
{
return this.atributos;
}
@Override
public void setAtributos(Map<String, String> atributos)
{
this.atributos = atributos;
}
@Override
public Node2StringSeparado getNode2String()
{
return node2String;
}
@Override
public void setNode2String(Node2StringSeparado node2String)
{
this.node2String = node2String;
}
@Override
public String getComentario()
{
return null;
}
@Override
public void setComentario(String comentario)
{
}
public NodoXML2()
{
}
}
|
package com.example.mvcsecurityjpa.userDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.example.mvcsecurityjpa.entity.User;
import com.example.mvcsecurityjpa.repository.UserRepository;
import com.example.mvcsecurityjpa.userDetails.UserDetailsImpl;
/**
* UserDetailsService
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private UserRepository userRepository;
UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
if(user == null) {
throw new UsernameNotFoundException("Not Found");
}
return new UserDetailsImpl(user);
}
}
|
Technology can be a valuable tool for enhancing interview preparation and increasing your chances of success. In this chapter, we will discuss strategies for utilizing technology to enhance interview preparation.
Researching the Company
-----------------------
Researching the company is an important part of interview preparation, and technology can make it easier to access information about the company's products, services, and culture. Some tips for utilizing technology to research the company include:
* Visiting the company's website to gain insight into its mission, values, and products/services
* Reading reviews on websites such as Glassdoor to gain insight into the company culture and interview process
* Connecting with current or former employees on LinkedIn to gain additional insights and ask questions
* Using social media platforms such as Twitter or Facebook to follow the company and gain additional insights
Remember that the more you know about the company, the better prepared you will be to answer questions and showcase your skills and experience effectively.
Practicing Interview Questions
------------------------------
Practicing interview questions is an important part of interview preparation, and technology can make it easier to access sample questions and practice answering them. Some tips for utilizing technology to practice interview questions include:
* Using online resources such as InterviewBit, LeetCode, or HackerRank to practice technical interview questions
* Recording yourself answering common interview questions using a webcam or smartphone to review and improve your performance
* Using video conferencing tools such as Zoom or Skype to practice mock interviews with friends or family members
* Participating in online forums or discussion groups to gain additional insights and feedback
Remember that the more you practice answering interview questions, the more confident and prepared you will be during the actual interview.
Accessing Additional Resources
------------------------------
Accessing additional resources can help you gain additional insights and prepare more effectively for the interview. Some tips for utilizing technology to access additional resources include:
* Watching videos or tutorials on how to improve your interview skills and techniques
* Reading articles or blog posts about the latest interview trends and strategies
* Using online tools such as Grammarly or Hemingway to improve your written communication skills
* Participating in online courses or workshops to gain additional skills and experience
Remember that the more resources you have at your disposal, the better prepared you will be to showcase your skills and experience effectively during the interview.
Conclusion
----------
Utilizing technology to enhance interview preparation can be a valuable tool for increasing your chances of success. By researching the company using online resources, practicing interview questions using video conferencing tools, and accessing additional resources such as videos and tutorials, you can gain additional insights and prepare more effectively for the interview. Remember to approach interview preparation with a positive and open mindset, and use technology as a tool for enhancing your skills and experience. With these strategies and tips, you can successfully leverage technology to enhance interview preparation and increase your chances of landing your dream job.
|
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
<base href="/mount/ultralaser_home/Projects/c2_wiki_recovery/out/">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="page">
<h1>
<img src="wiki.gif" />
Extended Set Theory
</h1>
<p>
Unfortunately, the following doesn't quite capture the performance modeling potential that extended set processing (XSP) may provide. While the papers at <a href="http://xsp.xegesis.org">http://xsp.xegesis.org</a> might imply that XSP may only be particularly suited to database and data processing applications, XSP is not limited to these -- any more than the <a href="RelationalModel.html">RelationalModel</a> is limited to just DBMSes. XSP can provide a unifying mathematical structure over all known data structures and data representations, such as files, records, queues, stacks, XML files, SQL tables, B-trees, and so on. Since all of these can be represented as extended sets, they can all be manipulated and transformed with extended set operations -- just as relations can be manipulated and transformed with <a href="RelationalAlgebra.html">RelationalAlgebra</a>.
</p>
<p>
In short: In the same way that relational algebra provides operations on relations, XSP can define operations on <em>anything</em> that can be represented as an extended set -- which is no less than <strong>any</strong> and <strong>all</strong> data representations, whether low-level (physical), high-level (conceptual), or the mappings between these.
</p>
<p>
-- <a href="DaveVoorhis.html">DaveVoorhis</a> (<em>with input from D L Childs</em>)
</p>
<hr/>
<p>
A proposed extension to classical <a href="SetTheory.html">SetTheory</a> proposed by <a href="DaveChilds.html">DaveChilds</a>, in which sets can be augmented by what are known as <em>scopes</em> (a term which has little to do with scoping in <a href="ProgrammingLanguage.html">ProgrammingLanguage</a> theory). Scopes allow the imposition of ordering and/or the attachment of labels to sets; what the <a href="RelationalModel.html">RelationalModel</a> achieves by the convention of limiting its classical sets (relations) to contain only "tuples" (unordered sets of name/value pairs, essentially).
</p>
<p>
Unfortunately, online references are scarce - however it looks interesting.
</p>
<p>
One online reference is at <a href="http://xsp.xegesis.org/Xsp-uxr.pdf">http://xsp.xegesis.org/Xsp-uxr.pdf</a> ; unfortunately the paper does reek a bit of marketing-speak. (If you ignore that, you will find some technical rigor...)
</p>
<p>
<em>Quoting from this paper:</em>
</p>
<p>
Consider the following two tables T1 and T2.
</p>
<code>
A | B | C<br/>
T1 = ----+----+----<br/>
a | b | c<br/>
x | y | z<br/>
</code>
<code>
C | B | A<br/>
T2 = ----+----+----<br/>
z | y | x<br/>
c | b | a<br/>
</code>
<p>
While they are obviously <strong>different</strong> to an observer, they have exactly the same domain names and row values, and are therefore considered, under the conventions of the RDM, to represent the same "relation". The intelligent human can easily understand the extra-mathematical convention (which, to my knowledge, cannot be defined in the mathematics underlying the RDM) that the ordering of the rows and columns is insignificant. Capturing the same notions at a formal level is considerably more challenging.
</p>
<p>
<em>Your knowledge of RDM is faulty: no </em>extra-mathematical convention<em> is required. Difference in ordering of values in rows/columns are an artifact of particular tabular representations you have chosen. There is not ordering of rows/columns in RDM. Access to a specific tuple (row) is by key(s) and then to a specific attribute value (row-column intersection) is by attribute name. SQL-based DBMSes are not a counterexample, they are known to deviate from RDM significantly.</em>
</p>
<p>
-- MaD70 2008/05/02
</p>
<p>
<em>Specificaly C. J. Date, in </em>'Database in Depth<em>' - </em>O'Reilly<em>, gives this definition of tuple:</em>
</p>
<p>
"<strong>Definition:</strong> Let T1, T2, . . . ,Tn (n >= 0) be type names, not necessarily all distinct. Associate with each Ti a distinct attribute name, Ai; each of the n attribute-name:type-name combinations that results is an attribute. Associate with each attribute a value vi of type Ti; each of the n attribute:value combinations that results is a component. The set of all n components thus defined, t say, is a tuple value (or just a tuple for short) over the attributes A1, A2,..., An. The value n is the degree of t; a tuple of degree one is unary, a tuple of degree two is binary, a tuple of degree three is ternary,..., and more generally a tuple of degree n is n-ary. The set of all n attributes is the heading of t."
</p>
<p>
-- MaD70 2008/06/23
</p>
<p>
<em>Huh? Formalizing this is trivial. The simplest way is to model a row as a function from field names to field values, and a table as a set or multiset of rows; then equivalent tables have identical models. (Purists might want to specify this axiomatically rather than by assuming a specific model, but there is no difficulty in doing that either.)</em>
</p>
<p>
<em>Added later after reading "</em>Feasibility of a set-theoretic data structure: a general structure based on a reconstituted definition of relation<em>": this is in fact how Childs does model it in that paper. So I don't see what is "considerably more challenging". Oh well.</em>
</p>
<p>
[...]
Classical set theory deals with a membership concept in which something is either "there" or "not there". Extended set theory adds an additional condition to the membership concept in which something is either "there under the specific condition" or "not there under the specific condition".
[...]
As we will see shortly, it is this additional membership dimension that allows XST to model structures and operations that actually exist in a computer, but that cannot be modeled [in] CST.
</p>
<p>
<em>"Cannot be modelled in classical set theory"?!</em>
</p>
<p>
[Yeah, yeah, yeah, if you work at it, you can build up all of math from set theory; that's not the point, and the paper you're criticizing isn't a pure math paper.]
</p>
<p>
<em>It didn't say, "cannot easily be modelled...". Besides, this was just the final straw in a paper that is full of hype.</em>
</p>
<p>
[I took the point to be that it takes meta-notation that is traditionally outside the realm of set theory, and extends set theory to include a certain kind of label as part of the extended theory.]
</p>
<p>
[One could doubtless do the same thing modelled in plain old set theory, but sometimes it is simpler to make an addition to the underlying theory.]
</p>
<p>
<em>A fair point, but as far as I can tell, the theory seems to be a kind of modal logic. Why does the paper not say so, rather than implying it is something new and magical?</em>
</p>
<p>
[Anyway, whatever flaws this particular paper has do not apply to the original theory, as far as I know (which isn't saying much). The question is whether this approach is helpful; I'd just ignore the overarching claims.]
</p>
<p>
<em>OK, the theory probably deserves a second chance. Are there any other on-line papers describing it?</em>
</p>
<p>
<em>Answering my own question: the reference and abstract for the main paper "Extended Set Theory" is at </em><a href="http://www.informatik.uni-trier.de/~ley/db/conf/vldb/Childs77.html.">http://www.informatik.uni-trier.de/~ley/db/conf/vldb/Childs77.html.</a> Other papers by Childs are referenced at <a href="http://xsp.xegesis.org/Papers.htm.''">http://xsp.xegesis.org/Papers.htm.''</a>
</p>
<p>
<em></em><a href="http://www.hti.umich.edu/cgi/t/text/pageviewer-idx?c=umr;cc=umr;sid=e2f01a05d983efad565cb19b5468870c;rgn=full%20text;idno=BAC0294.0001.001;view=pdf;seq=00000001">http://www.hti.umich.edu/cgi/t/text/pageviewer-idx?c=umr;cc=umr;sid=e2f01a05d983efad565cb19b5468870c;rgn=full%20text;idno=BAC0294.0001.001;view=pdf;seq=00000001</a> also seems to be relevant (full text of "<em>Feasibility of a set-theoretic data structure: a general structure based on a reconstituted definition of relation</em>").<em></em>
</p>
<p>
URL above gives an error (2008/05/02). That paper is available at: <a href="http://hdl.handle.net/2027.42/4164">http://hdl.handle.net/2027.42/4164</a>
Moreover there is <em>Description of a set-theoretic data structure</em>, also by David L. Childs, at: <a href="http://hdl.handle.net/2027.42/4163">http://hdl.handle.net/2027.42/4163</a>
</p>
<p>
-- MaD70 2008/05/02
</p>
<hr/>
<p>
<strong>From </strong><a href="TheThirdManifesto.html">TheThirdManifesto</a><strong></strong>
</p>
<p>
<strong>I worked for many years on extended set-theoretic databases, which go beyond Codd and Date in providing an even more complete and mathematical set of database principles.</strong>
</p>
<p>
<em>I wonder what is an extended set? Sounds like snake oil for me. A different kind of set most probably is something else. For example, SQL tables aren't sets, but bags, because they have duplicates.</em>
</p>
<p>
Relational math has an inherent difficulty, according to Dave Childs, whereby all the operations one might do on relations do not always return relations.
</p>
<p>
<em>That's OK, because the operations one might do on multirelations always return multirelations. (A multirelation is just a multiset, a.k.a. bag, of tuples. See </em><a href="http://erw.dsi.unimi.it/ERW/x407.html">http://erw.dsi.unimi.it/ERW/x407.html</a> and <a href="http://vigna.dsi.unimi.it/ftp/papers/Multirelations.pdf)">http://vigna.dsi.unimi.it/ftp/papers/Multirelations.pdf)</a> Furthermore these generalized operations coincide with <a href="DrCodd.html">DrCodd</a>'s original definitions when they are applied to sets.<em></em>
</p>
<p>
Queries have to be "conformable". Dave thought it would be nice if database was based on a kind of mathematics that had closure. He observed that when one considers what one "would" get back from a relational query that isn't conformable, the thing appears still to be a set, even though it isn't a relation.
</p>
<p>
Similarly, relational theory, at that time at least, outlawed things like nested relations. Again, Dave thought that set theory would be better, because it allows nested sets.
</p>
<p>
<em>Yes, outlawing nested multirelations is an unnecessary restriction.</em>
</p>
<p>
But there is a problem using classical set theory in this way: N-tuples are defined in set theory, typically via something like <a, b> == { a, {a, b} }. The practical result of this would be that if you got the latter set as a result, poof it would be an n-tuple.
</p>
<p>
<em>I'm not sure why this should be considered a serious problem. Most mathematicians view constructions like { a, {a, b} } simply as an example of how tuples </em>could<em> be defined in terms of sets, and treat tuples as distinct entities in practice. If you want more formality than that, then there are easier approaches than having to reconstruct set theory; for example, reserve a distinct symbol <pair> that is not otherwise used, and define <a, b> == { <pair>, a, {a, b} }.</em>
</p>
<ul>
<li>
<em>Or, to model arbitrary records you could define <field1:a, field2:b> == { <record>, {<field1>, a}, {<field2>, b} }, where <record> and the field names are distinct from any other values. Constructing any arbitrary container out of sets (or indeed, any other reasonable container) is not a problem.</em>
</li>
</ul>
<ul>
<li>
<em>Another alternative is to use the definition of a relation from </em><a href="CategoryTheory.html">CategoryTheory</a>, as described in <a href="http://vigna.dsi.unimi.it/ftp/papers/Multirelations.pdf.''">http://vigna.dsi.unimi.it/ftp/papers/Multirelations.pdf.''</a>
</li>
</ul>
<p>
So Dave devised a new theoretical definition of set theory that keeps n-tuples separate from nested sets. It has been looked at by better math heads than mine, including W V O Quine, and found to be solid.
</p>
<p>
The practical aspect of it all is that it offers an alternative way of implementing databases, with interesting potential advantages:
</p>
<ul>
<li>
Operations would be closed. Every operation on two (or more) sets would return a set as its result.
</li>
</ul>
<ul>
<li>
More computer data structures could be directly defined. More on that in the response to the question below.
</li>
</ul>
<p>
<strong>Relational math can describe the logic of the data it provides to you, but it isn't strong enough to describe the storage space upon which it is implemented. XST can model the user data, but it can also model the storage, all the way down to the bits.</strong>
</p>
<p>
<em>I wonder why one would want to do this. You use the relational model to model the logic level. Than you use whatever you want - hierarchies, networks, files, any kind of graph or list - to map that to implementation. A RDBMS should have all this implementation functionality, but very separate from the logical model; and users should never deal with the physical layer or its mapping to the logical schema, only DBAs and the such should care about this.</em>
</p>
<ul>
<li>
You want to do this because there are richer information structures available to you this way. Consider a string of bits vs. an int of bits. Their semantics are defined by specific logical permutations of their bits. Different logical permutations. How many such permutational semantics do we have access to? Well, seven or eight fundamental types, most of which amount to one of [string, integer, float, pointer]. And there are a few weird ones - <a href="GeneralizedBalancedTernary.html">GeneralizedBalancedTernary</a> and so on. But what else is possible? Who knows? No one has explored this - or at least no one who has published anything about it. -- Pete
<ul>
<li>
This has been considered, which is why various types are in use. Also, machine instruction formats employ a variety of bit patterns.
</li>
<li>
<em>More information please. If the few fundamental types we use are, after consideration, the only fundamental types in the universe that possess utility, then please point out someone who has demonstrated this. If, on the other hand, you know of someone who has adequately described the entire universe of such permuatonal arithmetics, please point them out instead. As for the alphabet of one or another machine instruction set, unless there are permutational arithmetics backing those alphabets I fail to grasp your point.</em>
</li>
<li>
[You're mistaking his point. He is contradicting your statement that "No one has explored this - or at least no one who has published anything about it", both of which are false, and you pretty much already contradicted yourself when you said "there are a few weird ones". Yes, and in fact, there are a <strong>lot</strong> of "weird" ones. Guess how many different kinds of ternary codes have been explored? Guess how many kinds of GreyCode? The entire set of what is possible for a binary operator on two N bit inputs yielding an N bit output is obvious: the set of all such possible mappings (which is <strong>rather</strong> large for N=32). Are any of those mappings provably useless in all possible applications? Of course not. One can always work backwards to contrive a use for something.]
</li>
<li>
[But how many of the possible operations are <strong>definitely</strong> useful? Well, the ones where people have published showing that they are useful, obviously. Which of those uses are common enough to put into an instruction set? Look at all of the instruction sets ever developed and you will see various opinions on the topic, with some consensus and some idiosyncracies. Multiply-and-accumulate is considered critical for DSP processors, but is rare in general purpose CPUs, so it is a question of optimization for intended use.]
</li>
<li>
[What does this have to do with relational databases? It's getting pretty far afield, but I would claim that it would be obviously useful to be able to introduce new operators and types rather than being stuck with just the builtins that e.g. SQL offers. And that of course is quite an old opinion in some quarters by now, not something unique to the topic of this page.]
</li>
</ul>
</li>
</ul>
<p>
Yes, you do that. And that's the bug. A relational system cannot be implemented in relational terms: the logic making up relational database systems has to be implemented in ordinary software, and is therefore not logically complete in the way that the relational operations seem to be.
</p>
<p>
<em>Why is it a bug? Specifically, why would we want to </em>restrict<em> the modelling of database representation issues to have to use same theory that is used to model the abstract database structure? Especially when there is an existing theory of abstraction functions and representation invariants that is perfectly adequate?</em> <strong>See </strong><a href="ExtendedSetTheoryStorageModel.html">ExtendedSetTheoryStorageModel</a>.<strong></strong>
</p>
<p>
It would be better, one argues, if your theory could work all the way down to the bits, so that instead of writing more or less ad hoc code to implement your database, you could implement mathematical expressions of more and more detail until <em>voila!</em> you were done. In relational, this is really not possible, because relational just won't describe itself all the way down. In <a href="ExtendedSetTheory.html">ExtendedSetTheory</a> (XST), it turns out, you can do this. So, in this sense, it's "better".
</p>
<p>
Along the way, XST also models things that relational cannot. For example, I might readily build an object Person that contained a collection Children, each of whom was another Person. Relational would have us implement this with a relation of Person, and some kind of key field, maybe Parent, so that we could join an individual Person back into the database to find her Children. Relational thinkers start to think that this is "natural" but in fact it is not. Hierarchic or object thinkers might well prefer the hierarchic nested structure, taking all the Persons back to some primordial set of First Persons.
</p>
<p>
Neither is "right". What is the case is that XST can model the Person relation if you want to, but it can model the hierarchic one as well. And it can do more: XST can directly model the storage underlying either of these models.
</p>
<p>
<em>Why would you want to do that?</em> you ask. Well, let's think about that on a separate page <a href="ExtendedSetTheoryStorageModel.html">ExtendedSetTheoryStorageModel</a>.
</p>
<p>
<strong>I suspect that there really is a conceptual barrier between object thinking and database thinking.</strong>
</p>
<p>
<em>Obviously, because there is no underlying theory behind object-orientation. This is one of the strongest points of Date, Darwen and Pascal. There are no precise definitions, and when there are they are unnecessary. For example, what's an object, a variable or a value? And a class, what's it besides a type?</em>
</p>
<p>
[[The <a href="ActorsModel.html">ActorsModel</a>, which is equivalent to concurrent object-oriented computation, has considerable theory underlying it. In this model, an object reference is an actor name, the state of an object is an actor and its set of acquaintances, and a class is an actor that constructs new actors. Alternatively, objects can be modelled as closures in the <a href="LambdaCalculus.html">LambdaCalculus</a>; in
that case a message send is a closure application, an object reference is a closure value, the state of an object is an environment, and classes are higher order functions.]]
</p>
<p>
Well, I don't know the theoretical answer to that but I have been in my day expert in both relational and in OO, and they are both powerful ways of organizing my thoughts. Yet O-R Mapping is weak, and leads us to wonderful solutions with inherent problems built in.
</p>
<p>
For example, I'm here right now because there's a discussion going on the Refactoring group about refactoring SQL. It comes down to this: you can't refactor SQL because everything you do of that kind wrecks all those cool optimized queries.
</p>
<p>
It would be better, one argues, if there were a more smooth transition between one's [object] program and one's database, instead of a barrier. XST offered that possibility. There have been a few implementations of XST and they all turned out to be quite marvelous. None of them made it in the marketplace. That might be a condemnation of the notion, but I don't think so. I've seen too many marvelous things not make it in the marketplace to believe that failure or success in the market implies much about technical or theoretical quality.
</p>
<p>
-- <a href="RonJeffries.html">RonJeffries</a>
</p>
<hr/>
<p>
The relevant point seems really to be about avoiding <em>semantic noise</em>. For example, representing a set as a list introduces 'semantic noise' because the interpreter/compiler doesn't know that the list is to be interpreted as a set. Use of an <a href="AbstractDataType.html">AbstractDataType</a> can help, but an ADT doesn't work so well in 'open' systems (i.e. communication with an external database) and even in a closed system we'd be depending far too heavily on the mythical <a href="SufficientlySmartCompiler.html">SufficientlySmartCompiler</a>. My impression is that extended sets hit a <em>sweet spot</em> between classical sets recursive record-based data structures. That is, extended sets unify structural properties from both of these domains without considerable semantic noise. This is useful if you wish to avoid complexity from supporting two classes of operators (i.e. some operators for functional data, other operators for sets). I'm considering extended sets on this basis: my earlier design used recursive record-based data structures, which was suitable for <a href="MessagePassing.html">MessagePassing</a>, but I've changed basis to <a href="ReactiveDemandProgramming.html">ReactiveDemandProgramming</a> which pervasively uses sets, and I'm finding quite awkward the need for separate operators for sets vs. other data structures.
</p>
<p>
That said, XSP seems to represent a particular technology rather than a well-defined closed calculus for operating upon extended sets. I would really like to see an effective representation for processing extended sets - preferably something defined reflexively (i.e. such that queries and processing on extended sets are themselves extended sets). I would like to see reasoning about termination, determinism, and optimizations. I'm not seeing this sort of information on the XSP site, or if it exists it is buried beneath a ton of marketing and buzzwords.
</p>
<p>
<em>Being able to abstract </em>'all<strong> (or at least many) computational objects as extended sets indeed provides a degree of semantic simplification. This is analogous to the manner that, e.g., the </strong><a href="RelationalModel.html">RelationalModel</a> simplifies storage by representing all storage mechanisms as <a href="RelVar.html">RelVar</a>s. However, I think extended set theory's main strength is that it provides an opportunity to use a common, relatively simple optimisation scheme from the lowest, most concrete levels of a system to the highest, most abstract levels. I don't know to what degree either of these ideas have been implemented; it's something I intend to ask D L Childs.<em></em>
</p>
<p>
<em>XSP is not intended to be a particular technology. I can't comment on the writing style used on the XSP web site -- other than to note that Childs is a mathematician, not an English writer, and the site appears to be mainly intended to promote the idea to potential implementers. And by "potential implementers", I mean investors with the money and inclination to fund speculative commercial software development; the site is largely not aimed at computer scientists or programmers. I too would like to see an effective representation for extended sets, plus reasoning about termination, determinism and optimisations. I suspect that's left as an exercise for the reader, but I will ask Childs if he's written anything on these.</em>
</p>
<p>
<em>It seems our areas of interest have some overlap. Given I'm working on a </em>PhD in this area, I'm not sure whether to feel threatened or organise a conference. :-) I suppose the appropriate "academic" thing is to do the latter.<em></em>
</p>
<p>
-- <a href="DaveVoorhis.html">DaveVoorhis</a>
</p>
<hr/>
<p>
<a href="SetTheory.html">SetTheory</a>, <a href="CategoryMath.html">CategoryMath</a>, <a href="CategoryTheory.html">CategoryTheory</a> (heh, heh...), <a href="AlgebraixData.html">AlgebraixData</a> (does this implementation mean this is no longer just a theory?) <em>No, there are a number of implementations; of classical set "theory", too.</em>
</p>
</div>
</body>
</html>
|
import React, {Component} from "react";
import {connect} from "react-redux";
import {createEvent} from "../actions/events";
import image3 from "../Images/outdoor2.jpeg"
class AddEvents extends Component {
constructor(props) {
super(props);
this.onChangeType = this.onChangeType.bind(this);
this.onChangeName = this.onChangeName.bind(this);
this.onChangeDate = this.onChangeDate.bind(this);
this.onChangeDescription = this.onChangeDescription.bind(this);
this.onChangeLocation = this.onChangeLocation.bind(this);
this.saveEvents = this.saveEvents.bind(this);
this.newEvents = this.newEvents.bind(this);
this.state = {
id: null,
type: "",
name: "",
date: "",
description: "",
location: "",
submitted:false,
};
}
onChangeType(e){
this.setState({
type: e.target.value,
});
}
onChangeName(e){
this.setState({
name: e.target.value,
});
}
onChangeDate(e){
this.setState({
date: e.target.value,
});
}
onChangeDescription(e){
this.setState({
description: e.target.value,
});
}
onChangeLocation(e){
this.setState({
location: e.target.value,
});
}
saveEvents(){
const {type,name,date,description,location} = this.state;
this.props
.createEvent(type,name,date,description,location)
.then((data)=> {
this.setState({
id:data.id,
type: data.type,
name: data.name,
date: data.date,
description: data.description,
location: data.location,
submitted:true,
});
console.log(data);
})
.catch((e) =>{
console.log(e);
});
}
newEvents(){
this.setState({
id: null,
type: "",
name: "",
date: "",
description: "",
location: "",
submitted:false,
});
}
render() {
return (
<div className="bg-secondary">
<img src={image3} alt="Image 1" className="center"/>
<div className="submit-form" >
{this.state.submitted ? (
<div>
<h4>You have submitted successfully the Event!</h4>
<button className="btn btn-success" onClick={this.newEvents}>
Add another event
</button>
</div>
) : (
<div>
<div className="form-group">
<label htmlFor="type">Type of Event</label>
<input
type="text"
className="form-control"
id="type"
required
value={this.state.type}
onChange={this.onChangeType}
name="type"
/>
</div>
<div className="form-group">
<label htmlFor="name">Name of event</label>
<input
type="text"
className="form-control"
id="name"
required
value={this.state.name}
onChange={this.onChangeName}
name="name"
/>
</div>
<div className="form-group">
<label htmlFor="date">Date of the event</label>
<input
type="text"
className="form-control"
id="date"
required
value={this.state.date}
onChange={this.onChangeDate}
name="date"
/>
</div>
<div className="form-group">
<label htmlFor="description">Description of the event</label>
<input
type="text"
className="form-control"
id="description"
required
value={this.state.description}
onChange={this.onChangeDescription}
name="description"
/>
</div>
<div className="form-group">
<label htmlFor="location">Location of the event</label>
<input
type="text"
className="form-control"
id="location"
required
value={this.state.location}
onChange={this.onChangeLocation}
name="location"
/>
</div>
<button onClick={this.saveEvents} className="btn btn-success">
Submit
</button>
</div>
)}
</div>
</div>
);
}
}
export default connect(null,{createEvent})(AddEvents);
|
//sort 0's 1's and 2's
//Ex: arr[]={0,1,1,0,2,0,2,1} => {0,0,0,1,1,1,2,2}
#include<iostream>
using namespace std;
void printArray(int arr[], int size){
for(int i=0; i<size; i++){
cout<<arr[i]<<" ";
}
}
void Sort(int arr[], int size)
{
int start=0, end=size-1, mid = 0;
while(mid <= end){
if(arr[mid] == 0){
swap(arr[start],arr[mid]);
start++;
mid++;
}
else if(arr[mid] == 1){
mid++;
}
else if(arr[mid] == 2){
swap(arr[mid], arr[end]);
end--;
}
}
}
int main(){
int arr[8] = {0,1,1,0,2,0,2,1};
Sort(arr, 8);
printArray(arr, 8);
}
|
<!DOCTYPE html>
<html lang="pt-BR>
<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>Document</title>
<style>
.Img-twitter {
height: 200px;
width: 200px;
display: block;
margin-top: 5px;
border: 1px solid red;
}
</style>
</head>
<body>
<h1 style="background-color: blueviolet;"> Cabeçalho </h1> <!--Internal Style sheet-->
<p> <b> ipsum dolor</b> sit amet, <strong> adipiscing elit </strong>.
Integer ullamcorper nibh mattis pharetra ultricies.
Cras pretium congue mi eu sollicitudin.
Aenean interdum risus sed sapien vehicula, vel ultricies dui sollicitudin.
Curabitur suscipit lorem bibendum venenatis tempus.
Sed a velit sit amet nisl tincidunt dignissim.
Vivamus ac tellus ac erat mollis facilisis quis sed odio.
Vestibulum sollicitudin odio elit, eu ornare sem interdum ut. </p>
<!--"B" (Bold) e "Strong" deixam em negrito o texto. Porém a linguagem interpreta diferentes essas duas tags -->
<!--"I" e "em" deixam em itálico o texto. Porém a linguagem interpreta diferentes essas duas tags -->
<!--"Del" e "s" colocam um risco nos caracteres de um texto-->
<!--"Ins" e "u" colocam um underline na palavra-->
<!--Small diminui o tamanho do texto-->
<!--Sup eleva um elemento (expoente, por exemplo)-->
<!--Sub rebaixa um elemento-->
<!--Br realiza a quebra de linha-->
<!--Blockquote promove a inserção de um bloco de citação-->
<!--Hr coloca uma linha em um lugar da página-->
<!--Code formata os caracteres em formato de código-->
<!--Pre insere um texto com espaçamento pessoal, ou seja, não segue a regra do HTML-->
<!--Span - formata um conteiner genérico inline-->
<!--Div - formata um conteiner genérico block-->
<a href="https://www.w3schools.com/css/css_background.asp" target="_blank">Clique Aqui</a>
<a href="https://twitter.com/i/flow/login?redirect_after_login=%2Flogin%3Flang%3Dpt" target="_blank">
<img class="Img-twitter"
src="https://media.cnn.com/api/v1/images/stellar/prod/230723020951-elon-musk-twitter-revamp-intl-hnk.jpg?c=original">
</a>
<blockquote cite="https://twitter.com/i/flow/login?redirect_after_login=%2Flogin%3Flang%3Dpt">
Estou fazendo um bloco de citação
</blockquote> <!--Não posso colocar o blockquote dentro de um parágrafo. -->
<p>Nunc <code>quis nisl faucibus</code>, sagittis nunc eu,
condimentum tellus.
Maecenas ante ex, rhoncus sed consequat molestie, ornare id mi.
Proin sit amet gravida orci.</p>
<pre> <code>
// Create a Set
const letters = new Set(["a","b","c"]);
// List all Elements
let text = "";
letters.forEach (function(value) {
text += value;
})</code>
</pre>
</body>
</html>
|
from solutions.base import BaseSolution
class Solution(BaseSolution):
DICT_TRIE = {
"o": {"n": {"e": "1"}},
"t": {"w": {"o": "2"}, "h": {"r": {"e": {"e": "3"}}}},
"f": {"o": {"u": {"r": "4"}}, "i": {"v": {"e": "5"}}},
"s": {"i": {"x": "6"}, "e": {"v": {"e": {"n": "7"}}}},
"e": {"i": {"g": {"h": {"t": "8"}}}},
"n": {"i": {"n": {"e": "9"}}},
}
@classmethod
def extract_digit(cls, line: str, reverse: bool = False) -> str:
"""Extract the first (or last) digit from a string
:param line: The string to extract the digit from
:param reverse: Whether to extract the last digit instead of the first
:return: The first (or last) digit in the string
"""
range_ = range(len(line) - 1, -1, -1) if reverse else range(len(line))
for i in range_:
if line[i].isdigit():
return line[i]
msg = "No digit found"
raise ValueError(msg)
@classmethod
def extract_digit_with_words(cls, line: str, reverse: bool = False) -> str:
"""Extract the first (or last) digit from a string,
including digits as words (e.g. "one" -> "1")
:param line: The string to extract the digit from
:param reverse: Whether to extract the last digit instead of the first
:return: The first (or last) digit in the string
"""
range_ = range(len(line) - 1, -1, -1) if reverse else range(len(line))
for i in range_:
if line[i].isdigit():
return line[i]
n = 0
node = cls.DICT_TRIE
while True:
try:
node = node[line[i + n]] # type: ignore[assignment]
except (KeyError, IndexError):
break
else:
if isinstance(node, str):
return node
n += 1
msg = "No digit found"
raise ValueError(msg)
@classmethod
def calculate_calibration_value(cls, line: str, include_words: bool) -> int:
"""Calculate the calibration value of a string
:param line: The string to calculate the calibration value of
:param include_words: Whether to allow digits as words (e.g. "one" -> "1")
:return: The calibration value of the string
"""
func = cls.extract_digit_with_words if include_words else cls.extract_digit
first = func(line)
last = func(line, reverse=True)
return int(first + last)
def setup(self) -> None:
self.lines = self.raw_input.splitlines()
def part_1(self) -> int:
return sum(
self.calculate_calibration_value(line, include_words=False)
for line in self.lines
)
def part_2(self) -> int:
return sum(
self.calculate_calibration_value(line, include_words=True)
for line in self.lines
)
|
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import DiagnoseStep from 'initial-diagnose/components/DiagnoseStep';
const DiagnoseRightSideWrapper = styled.div.attrs({ className: 'diagnose-right-side-wrapper' })`
background: #2e4663;
`;
const DiagnoseStepsWrapper = styled.div.attrs({ className: 'diagnose-steps-wrapper' })`
position: absolute;
top: 52%;
left: 81.5%;
height: 70vh;
width: 13vw;
transform: translate(-50%, -50%);
`;
const DiagnoseRightSide = ({ steps, currentStepNumber }) => (
<DiagnoseRightSideWrapper>
<DiagnoseStepsWrapper>
{steps.map(step => (
<DiagnoseStep
key={step.name}
name={step.name}
number={step.number}
description={step.description}
isCurrent={currentStepNumber === step.number}
isCompleted={currentStepNumber > step.number}
/>
))}
</DiagnoseStepsWrapper>
</DiagnoseRightSideWrapper>
);
DiagnoseRightSide.propTypes = {
steps: PropTypes.instanceOf(Array).isRequired,
currentStepNumber: PropTypes.number.isRequired,
};
export default DiagnoseRightSide;
|
import {catchError, map, switchMap, tap} from "rxjs/operators";
import {Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {Effect, ofType} from "@ngrx/effects";
import {CourseModel} from "../model/course.model";
import {EntityReducer} from "../ngrx/entity.reducer";
import {EntityEffects} from "../ngrx/entity.effects";
import {LecturerModel} from "../model/lecturer.model";
import {createAction, props} from "@ngrx/store";
import {HttpClient} from "@angular/common/http";
@Injectable()
export class CourseEffects {
@Effect()
fetchCourses = this.entityEffects.fetchEntities(this.coursesReducer);
@Effect()
addCourse = this.entityEffects.addEntity(this.coursesReducer);
@Effect()
editCourse = this.entityEffects.editEntity(this.coursesReducer);
@Effect()
deleteCourse = this.entityEffects.deleteEntity(this.coursesReducer);
@Effect()
fetchLecturers = this.entityEffects.fetchSecondaryEntities<LecturerModel>(this.coursesReducer, 'Lecturer');
@Effect({dispatch: false})
deleteCourseSuccess = this.entityEffects.actions$.pipe(
ofType(this.coursesReducer.entityActions.deleteEntitySuccess),
tap(() => this.router.navigate(['courses']))
);
@Effect()
removeRegistrationsFromCourse = this.entityEffects.actions$.pipe(
ofType(this.coursesReducer.removeRegistrationFromCourse),
switchMap(payload => this.http.put('http://localhost:8080/course/deleteFromCourse/'+ payload.course.id, payload.regIds)
.pipe(map(() => this.coursesReducer.entityActions.updateEntitySuccess({entity: payload.course})),
catchError(err => this.entityEffects.handleError(err, this.coursesReducer))))
);
constructor(private entityEffects: EntityEffects<CourseModel>, private coursesReducer: CoursesReducer,
private router: Router, private http: HttpClient) {}
}
@Injectable({
providedIn: 'root'
})
export class CoursesReducer extends EntityReducer<CourseModel> {
REMOVE_REGISTRATIONS_FROM_COURSE = '[Course] Remove Registrations From Course';
removeRegistrationFromCourse = createAction(this.REMOVE_REGISTRATIONS_FROM_COURSE, props<{regIds: number[], course: CourseModel}>());
constructor() {
super('Course')
}
}
|
//
// UIImage+CCUI.m
// CCUI
//
// Created by Fancy
//
#import "UIImage+CCUI.h"
#import "CCUIDefines.h"
@implementation UIImage (CCUI)
+ (UIImage *)cc_imageWithColor:(UIColor *)color {
return [UIImage cc_imageWithColor:color size:CGSizeMake(4, 4) cornerRadius:0];
}
+ (UIImage *)cc_imageWithColor:(UIColor *)color
size:(CGSize)size
cornerRadius:(CGFloat)cornerRadius {
size = CGSizeFlatted(size);
if (size.width <= 0 ||
size.height <= 0 ||
isinf(size.width) ||
isinf(size.height) ||
isnan(size.width) ||
isnan(size.height)) {
return nil;
}
color = color ? color : UIColor.clearColor;
BOOL opaque = (cornerRadius == 0.0);
UIImage *result = [UIImage cc_imageWithSize:size opaque:opaque scale:0 actions:^(CGContextRef contextRef) {
CGContextSetFillColorWithColor(contextRef, color.CGColor);
if (cornerRadius > 0) {
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) cornerRadius:cornerRadius];
[path addClip];
[path fill];
} else {
CGContextFillRect(contextRef, CGRectMake(0, 0, size.width, size.height));
}
}];
return result;
}
+ (UIImage *)cc_imageWithSize:(CGSize)size
opaque:(BOOL)opaque
scale:(CGFloat)scale
actions:(void (^)(CGContextRef contextRef))actionBlock {
if (!actionBlock || size.width <= 0 || size.height <= 0) {
return nil;
}
UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];
format.scale = scale;
format.opaque = opaque;
UIGraphicsImageRenderer *render = [[UIGraphicsImageRenderer alloc] initWithSize:size format:format];
UIImage *imageOut = [render imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
CGContextRef context = rendererContext.CGContext;
actionBlock(context);
}];
return imageOut;
}
+ (UIImage *)cc_imageWithView:(UIView *)view {
CGSize size = view.bounds.size;
if (size.width <= 0 ||
size.height <= 0 ||
isinf(size.width) ||
isinf(size.height) ||
isnan(size.width) ||
isnan(size.height)) {
return nil;
}
return [UIImage cc_imageWithSize:view.bounds.size opaque:NO scale:0 actions:^(CGContextRef contextRef) {
[view.layer renderInContext:contextRef];
}];
}
+ (UIImage *)cc_imageWithView:(UIView *)view afterScreenUpdates:(BOOL)afterUpdates {
CGSize size = view.bounds.size;
if (size.width <= 0 ||
size.height <= 0 ||
isinf(size.width) ||
isinf(size.height) ||
isnan(size.width) ||
isnan(size.height)) {
return nil;
}
return [UIImage cc_imageWithSize:view.bounds.size opaque:NO scale:0 actions:^(CGContextRef contextRef) {
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:afterUpdates];
}];
}
+ (UIImage *)cc_imageWithLight:(UIImage *)light dark:(UIImage *)dark {
if (@available(iOS 13.0, *)) {
if (light && dark) {
UITraitCollection *const scaleTraitCollection = [UITraitCollection currentTraitCollection];
UITraitCollection *const darkUnscaledTraitCollection = [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark];
UITraitCollection *const darkScaledTraitCollection = [UITraitCollection traitCollectionWithTraitsFromCollections:@[scaleTraitCollection, darkUnscaledTraitCollection]];
UIImage *image = [light imageWithConfiguration:[light.configuration configurationWithTraitCollection:[UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight]]];
dark = [dark imageWithConfiguration:[dark.configuration configurationWithTraitCollection:[UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark]]];
[image.imageAsset registerImage:dark withTraitCollection:darkScaledTraitCollection];
return image;
} else if (light) {
return light;
} else if (dark) {
return dark;
} else {
return nil;
}
} else {
return light;
}
}
@end
|
using System.Security.Claims;
using Mac.CarHub.Application.Common.Interfaces;
using Mac.CarHub.Application.Common.Models;
using Mac.CarHub.Application.Common.Models.Identity;
using Mac.CarHub.Application.Lookups.Roles.Queries.GetRoles;
using Mac.CarHub.Application.Models;
using Mac.CarHub.Domain.Constants;
using Mac.CarHub.Domain.Entities;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using LoginRequest = Mac.CarHub.Application.Common.Models.Identity.LoginRequest;
namespace Mac.CarHub.Infrastructure.Identity;
public class IdentityService(
UserManager<ApplicationUser> userManager,
IUserClaimsPrincipalFactory<ApplicationUser> userClaimsPrincipalFactory,
IAuthorizationService authorizationService,
SignInManager<ApplicationUser> signInManager,
IHostEnvironment hostEnvironment,
IFileService fileService,
RoleManager<ApplicationRole> roleManager
// ,
// TimeProvider timeProvider,
// IOptionsMonitor<BearerTokenOptions> bearerTokenOptions,
// IEmailSender<ApplicationUser> emailSender,
// LinkGenerator linkGenerator
) : IIdentityService
{
// private string? confirmEmailEndpointName = null;
public async Task<string?> GetUserNameAsync(string userId)
{
var user = await userManager.Users.FirstAsync(u => Equals(u.Id, userId));
return user.UserName;
}
public async Task<(Result Result, UserDetailsResponse? user)> CreateUserAsync(CreateUserCommand cmd,
CancellationToken cancellationToken)
{
var user = new ApplicationUser
{
UserName = cmd.UserName,
Email = cmd.Email,
FirstName = cmd.FirstName,
LastName = cmd.LastName,
PhoneNumber = cmd.PhoneNumber,
NationalId = cmd.NationalId ?? string.Empty,
};
if (cmd.PersonalPhoto is not null)
{
user.ProfilePicture = await fileService.SaveToDiskAsync(cmd.PersonalPhoto, cancellationToken);
}
else if (cmd.DefaultAvatar is not null)
{
user.ProfilePicture = cmd.DefaultAvatar;
}
var result = await userManager.CreateAsync(user, cmd.Password);
if (!result.Succeeded)
{
return (result.ToApplicationResult(), null);
}
var role = await userManager.AddToRoleAsync(user, cmd.RoleId);
(_, UserDetailsResponse? userDetails) = await this.GetUserDetailsAsyncHandler(user.Id);
return (role.ToApplicationResult(), userDetails);
}
public async Task<(Result Result, UserDetailsResponse? user)> UpdateUserAsync(EditUserCommand cmd,
CancellationToken cancellationToken)
{
var user = await userManager.Users.SingleOrDefaultAsync(u => u.Id == cmd.Id, cancellationToken);
if (user is null)
{
return (Result.Failure(new[] { "User not found" }), null);
}
if (cmd.Username != null) user.UserName = cmd.Username;
if (!string.IsNullOrWhiteSpace(cmd.FistName))
user.FirstName = cmd.FistName;
if (!string.IsNullOrWhiteSpace(cmd.LastName))
user.LastName = cmd.LastName;
user.LastName = string.IsNullOrWhiteSpace(cmd.LastName) ? null : cmd.LastName;
if (cmd.Email != null) user.Email = cmd.Email;
if (cmd.NationalId != null) user.NationalId = cmd.NationalId;
if (cmd.PhoneNumber != null) user.PhoneNumber = cmd.PhoneNumber;
if (cmd.ProfilePicture is not null)
{
if (user.ProfilePicture is not null)
{
await fileService.DeleteFileAsync(user.ProfilePicture, cancellationToken);
}
user.ProfilePicture = await fileService.SaveToDiskAsync(cmd.ProfilePicture, cancellationToken);
}
var result = await userManager.UpdateAsync(user);
(_, UserDetailsResponse? userDetails) = await this.GetUserDetailsAsyncHandler(user.Id);
return (result.ToApplicationResult(), userDetails);
}
public async Task<bool> IsUsernameUniqueAsync(string username)
{
var user = await userManager.FindByNameAsync(username);
return user is null;
}
public async Task<bool> IsUsernameUniqueExceptAsync(string username, Guid userId,
CancellationToken cancellationToken)
{
var user = await userManager.FindByNameAsync(username);
return user is null || user.Id == userId;
}
public async Task<bool> IsEmailUniqueAsync(string email)
{
var user = await userManager.FindByEmailAsync(email);
return user is null;
}
public async Task<UserDetailsResponse?> GetUserDetailsAsync(Guid userId)
{
(_, UserDetailsResponse? user) = await GetUserDetailsAsyncHandler(userId);
return user;
}
public async Task<bool> IsInRoleAsync(string userId, string role)
{
var user = userManager.Users.SingleOrDefault(u => u.Id.ToString() == userId);
return user != null && await userManager.IsInRoleAsync(user, role);
}
public async Task<bool> AuthorizeAsync(string userId, string policyName)
{
var user = userManager.Users.SingleOrDefault(u => u.Id.ToString() == userId);
if (user == null)
{
return false;
}
var principal = await userClaimsPrincipalFactory.CreateAsync(user);
var result = await authorizationService.AuthorizeAsync(principal, policyName);
return result.Succeeded;
}
public async Task<Result> DeleteUserAsync(string userId)
{
var user = userManager.Users.SingleOrDefault(u => u.Id.ToString() == userId);
return user != null ? await DeleteUserAsync(user) : Result.Success();
}
public async Task<Result> AuthenticateAsync(LoginRequest request, bool useCookieScheme, bool isPersistent)
{
signInManager.AuthenticationScheme =
useCookieScheme ? IdentityConstants.ApplicationScheme : IdentityConstants.BearerScheme;
var user = await userManager.FindByNameAsync(request.UserName);
if (user is null)
{
// for development purposes, we don't want to expose the fact that the user does not exist
// return TypedResults.Problem("User not found", statusCode: StatusCodes.Status404NotFound);
// must return at production unauthorized
// return TypedResults.Problem(result.ToString(), statusCode: StatusCodes.Status401Unauthorized);
return Result.Failure(new[] { "User not found" });
}
var roles = await userManager.GetRolesAsync(user);
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName!),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Email, user.Email!),
};
if (hostEnvironment.IsDevelopment())
{
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
}
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10)
};
await signInManager.SignInWithClaimsAsync(user, isPersistent, claims);
var result = await signInManager.PasswordSignInAsync(request.UserName, request.Password, isPersistent, false);
if (result.RequiresTwoFactor)
{
if (!string.IsNullOrEmpty(request.TwoFactorCode))
{
result = await signInManager.TwoFactorAuthenticatorSignInAsync(request.TwoFactorCode, isPersistent,
rememberClient: isPersistent);
}
else if (!string.IsNullOrEmpty(request.TwoFactorRecoveryCode))
{
result = await signInManager.TwoFactorRecoveryCodeSignInAsync(request.TwoFactorRecoveryCode);
}
}
if (!result.Succeeded)
{
// return TypedResults.Problem(result.ToString(), statusCode: StatusCodes.Status401Unauthorized);
return Result.Failure(new[] { "Invalid password" });
}
return Result.Success();
}
public async Task<Result> DeleteUserAsync(ApplicationUser user)
{
var result = await userManager.DeleteAsync(user);
return result.ToApplicationResult();
}
// public async Task<Result> AuthenticateAsync(Models.LoginRequest request, bool useCookieScheme, bool isPersistent)
// {
// var user = await userManager.FindByNameAsync(request.UserName);
//
// if (user == null)
// {
// return Result.Failure(new[] {"User not found"});
// }
//
// var result = await userManager.CheckPasswordAsync(user, request.Password);
//
// return result ? Result.Success() : Result.Failure(new[] {"Invalid password"});
// }
private async Task<(IList<string> roles, UserDetailsResponse? user)> GetUserDetailsAsyncHandler(Guid userId)
{
ArgumentNullException.ThrowIfNull(userId);
var user = await userManager.Users
.Include(u => u.ProfilePicture)
.SingleOrDefaultAsync(u => u.Id == userId);
ArgumentNullException.ThrowIfNull(user);
var userResponse = new UserDetailsResponse
{
Id = user.Id,
UserName = user.UserName ?? "",
Email = user.Email,
PhoneNumber = user.PhoneNumber,
FirstName = user.FirstName,
LastName = user.LastName,
NationalId = user.NationalId,
};
if (user.ProfilePicture is not null)
{
userResponse.ProfilePicture = user.ProfilePicture.FilePath;
}
var roles = await userManager.GetRolesAsync(user);
return (roles, userResponse);
}
public async Task<RoleVm> GetRolesAsync(CancellationToken cancellationToken)
{
var roles = await roleManager
.Roles
.Select(r => new RoleDto { Id = r.Id.ToString(), Name = r.Name! })
.ToListAsync(cancellationToken);
return new RoleVm { Roles = roles };
}
}
|
'use client'
import styles from '@/app/components/styles/input.module.css'
import { useState, useEffect } from 'react'
import placeholderFirstNames from '@/app/services/placeholderFirstNames'
import placeholderLastNames from '@/app/services/placeholderLastNames'
import getRandomInt from '../services/randomNumber'
const Input = () => {
const [placeholderName, setPlaceholderName] = useState('')
const [username, setUsername] = useState('')
const [pronouns, setPronouns] = useState('')
useEffect(()=>{
const num1 = getRandomInt(0,9)
const num2 = getRandomInt(0,9)
const nome = "Ex: " + placeholderFirstNames[num1] + " " + placeholderLastNames[num2];
setPlaceholderName(nome)
}, [])
return (
<main>
<div className={styles.userInfo}>
<h2 className={styles.h2}>Insert your information</h2>
{/* Username Input */}
<div className={styles.usernameInput}>
<label
className={styles.label}
htmlFor='username'
>Insert your name:</label>
<input
className={styles.input}
name='username'
placeholder={placeholderName}
value={username}
onChange={(e)=>setUsername(e.target.value)}
/>
</div>
{/* Pronouns Input */}
<div className={styles.pronounsInput}>
<label
className={styles.label}
htmlFor='pronouns'
>Insert your pronouns:</label>
<select
className={styles.select}
name='pronouns'
defaultValue={"Your Pronouns"}
onChange={(e)=>{setPronouns(e.target.value)}}
>
<option disabled>Your Pronouns</option>
<option>He/him</option>
<option>She/Her</option>
<option>They/Them</option>
<option>Don't call me</option>
</select>
</div>
{/* Botão gerar sua história */}
<button className={styles.button}>Generate your story</button>
</div>
</main>
)
}
export default Input
|
const { Engine, Render, Runner, World, Bodies, Body, Events } = Matter;
const cellsHorizontal = 15;
const cellsVertical = 15;
const width = window.innerWidth;
const height = window.innerHeight;
const unitLengthX = width / cellsHorizontal;
const unitLengthY = height / cellsVertical;
const engine = Engine.create();
engine.world.gravity.y = 0;
const { world } = engine;
const render = Render.create({
element: document.body,
engine: engine,
options: {
wireframes: false,
width,
height
}
});
Render.run(render);
Runner.run(Runner.create(), engine);
// Walls
const walls = [
// Top
Bodies.rectangle(width * 0.5, 0, width, 4, { label: 'wall', isStatic: true }),
// Left
Bodies.rectangle(0, height * 0.5, 4, height, { label: 'wall', isStatic: true }),
// Right
Bodies.rectangle(width, height * 0.5, 4, height, { label: 'wall', isStatic: true }),
// Down
Bodies.rectangle(width * 0.5, height, width, 4, { label: 'wall', isStatic: true })
];
World.add(world, walls);
// Maze
const shuffle = (arr) => {
let counter = arr.length;
while(counter > 0) {
const index = Math.floor(Math.random() * counter);
counter--;
const temp = arr[counter];
arr[counter] = arr[index];
arr[index] = temp;
}
return arr;
}
const grid = Array(cellsVertical).fill(null).map(() => Array(cellsHorizontal).fill(false));
const verticals = Array(cellsVertical).fill(null).map(() => Array(cellsHorizontal - 1).fill(false));
const horizontals = Array(cellsVertical - 1).fill(null).map(() => Array(cellsHorizontal).fill(false));
const startRow = Math.floor(Math.random() * cellsVertical);
const startColumn = Math.floor(Math.random() * cellsHorizontal);
const wallBreaker = (row, column) => {
if(grid[row][column]) {
return;
}
grid[row][column] = true;
const neighbors = shuffle([
[row - 1, column, 'Up'],
[row, column + 1, 'Right'],
[row + 1, column, 'Down'],
[row, column - 1, 'Left']
]);
for(let neighbor of neighbors) {
const [nextRow, nextColumn, direction] = neighbor;
if(nextRow < 0 || nextRow >= cellsVertical || nextColumn < 0 || nextColumn >= cellsHorizontal) {
continue;
};
if(grid[nextRow][nextColumn]) {
continue;
};
if(direction === 'Left') {
verticals[row][column - 1] = true;
} else if (direction === 'Right') {
verticals[row][column] = true;
} else if(direction === 'Up') {
horizontals[row - 1][column] = true;
} else if (direction === 'Down') {
horizontals[row][column] = true;
};
wallBreaker(nextRow, nextColumn);
}
}
wallBreaker(startRow, startColumn);
console.log(horizontals, verticals);
horizontals.forEach((row, rowIndex) => {
row.forEach((open, columnIndex) => {
if(open) {
return;
};
const wall = Bodies.rectangle(
columnIndex * unitLengthX + unitLengthX / 2,
rowIndex * unitLengthY + unitLengthY,
unitLengthX,
10,
{
label: 'wall',
isStatic: true,
render: {
fillStyle: 'red'
}
}
);
World.add(world, wall);
});
});
verticals.forEach((row, rowIndex) => {
row.forEach((open, columnIndex) => {
if(open) {
return true;
}
const wall = Bodies.rectangle(
columnIndex * unitLengthX + unitLengthX,
rowIndex * unitLengthY + unitLengthY / 2,
10,
unitLengthY,
{
label: 'wall',
isStatic: true,
render: {
fillStyle: 'red'
}
}
);
World.add(world, wall);
});
});
// Goal
const goal = Bodies.rectangle(
width - unitLengthX / 2,
height - unitLengthY / 2,
unitLengthX * 0.5,
unitLengthY * 0.7,
{
label: 'goal',
isStatic: true,
render: {
fillStyle: 'green'
}
}
);
World.add(world, goal);
// Ball
const ballRadius = Math.min(unitLengthX, unitLengthY) / 4;
const ball = Bodies.circle(
unitLengthX / 2,
unitLengthY / 2,
ballRadius,
{
label: 'ball'
}
);
World.add(world, ball);
document.addEventListener('keydown', event => {
const { x, y } = ball.velocity;
if(event.code === 'ArrowLeft') {
Body.setVelocity(ball, { x: x - 3, y });
};
if(event.code === 'ArrowUp') {
Body.setVelocity(ball, { x, y: y - 3 });
};
if(event.code === 'ArrowRight') {
Body.setVelocity(ball, { x: x + 3, y: y });
};
if(event.code === 'ArrowDown') {
Body.setVelocity(ball, { x: x, y: y + 3 });
};
});
// Win Condition
Events.on(engine, 'collisionStart', event => {
event.pairs.forEach(collision => {
const labels = ['ball', 'goal'];
if(
labels.includes(collision.bodyA.label) &&
labels.includes(collision.bodyB.label)
) {
document.querySelector('.winner').classList.remove('hidden');
world.gravity.y = 1;
world.bodies.forEach(body => {
if(body.label === 'wall' || body.label === 'goal') {
Body. setStatic(body, false);
}
})
}
});
});
|
<?php
namespace App\Repository;
use App\Entity\News;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use DateTime;
/**
* @extends ServiceEntityRepository<News>
*
* @method News|null find($id, $lockMode = null, $lockVersion = null)
* @method News|null findOneBy(array $criteria, array $orderBy = null)
* @method News[] findAll()
* @method News[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class NewsRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, News::class);
}
/*
* 1) Find out the length of all news
* 2) Pick the largest by descending order
* 3) Return only the new that's on top aka has the largest numbers of chars
*/
public function getLongestNewAndShortestComm(): array|null
{
return $this->createQueryBuilder('n')
->select('n.newsDescription as longest_new')
->addSelect('c.commentContent as news_comment')
->leftJoin('n.newsComments', 'c')
->orderBy('LENGTH(n.newsDescription)', 'DESC')
->addOrderBy('LENGTH(c.commentContent)')
->setMaxResults('1')
->getQuery()
->getOneOrNullResult();
}
public function getNewsForGivenPeriod(DateTime $timeFrom): array {
return $this->createQueryBuilder('n')
->select('n.newsDescription')
->andWhere('n.createdAtDateAndTime >= :time_from')
->setParameter('time_from', $timeFrom)
->getQuery()
->getSingleColumnResult();
}
// /**
// * @return News[] Returns an array of News objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('n')
// ->andWhere('n.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('n.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?News
// {
// return $this->createQueryBuilder('n')
// ->andWhere('n.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
|
package com.example.pokemonpazarama.data.di
import com.example.pokemonpazarama.data.repository.PokemonRepositoryImpl
import com.example.pokemonpazarama.data.service.PokemonApi
import com.example.pokemonpazarama.domain.repository.PokemonRepository
import com.example.pokemonpazarama.util.Constants.BASE_URL
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.build()
}
@Provides
@Singleton
fun providePokemonApi(
okHttpClient: OkHttpClient
): PokemonApi {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(PokemonApi::class.java)
}
@Provides
@Singleton
fun providePokemonRepository(
pokemonApi: PokemonApi
): PokemonRepository {
return PokemonRepositoryImpl(pokemonApi)
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Boommath</title>
<link rel="icon" type="image/png" href="gambar/logotab.png">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap" rel="stylesheet">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
overflow-x: hidden;
background: linear-gradient(to top, #f4f1de 0%, #5dceff 100%);
min-height: 100vh;
}
header {
position: fixed;
top: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding: 1rem 0rem;
width: calc(100% - 2rem);
max-width: 1150px;
margin-inline: auto;
z-index: 1000;
}
.back-btn {
display: grid;
place-items: center;
transition: 0.2s ease;
}
.back-btn:hover {
transform: scale(1.1);
}
.back-btn img {
height: 3rem;
filter: drop-shadow(2px 0px 4px rgba(0, 0, 0, 0.25));
}
.logo-img {
height: 75px;
}
.logo {
cursor: default;
}
.parallax {
position: relative;
display: flex;
justify-content: center;
height: 100vh;
}
.parallax img {
position: absolute;
height: 100%;
object-fit: cover;
pointer-events: none;
}
.parallax #sun {
top: 0;
left: 0;
}
.parallax #aw1 {
top: 0;
right: 0;
}
.parallax #aw11 {
top: 0;
left: 0;
}
.parallax #aw2 {
bottom: 0;
width: 100%;
height: calc(100% - 100px);
}
.parallax #shad {
width: 100%;
}
#text {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 2.5rem;
text-align: center;
color: #7363bd;
}
.sec {
position: relative;
padding: 100px 1rem;
background: linear-gradient(to top, #5dceff 0%, #ffffff 100%);
width: 100%;
}
.sec h3 {
font-size: 3rem;
color: black;
margin-bottom: 10px;
}
.sec p {
font-size: 1rem;
color: black;
font-weight: 300;
}
.penting {
border: 2px solid #7363bd;
background-color: #f4f1de;
color: #f4f1de;
padding: 10px;
}
.penting p {
color: #7363bd;
}
.ss-img {
display: grid;
place-items: center;
}
.ss-img img {
max-width: 100%;
max-height: 350px;
}
.tabel p {
color: black;
text-align: center;
}
.video-frame {
position: relative;
max-width: 560px;
}
.video-frame iframe {
position: absolute;
top: 5.3%;
left: 17.7%;
width: 64.5%;
height: 41.5%;
border-radius: 4px;
}
.video-frame img {
width: 100%;
height: auto;
}
@media screen and (min-width: 1024px) {
.sec {
padding: 100px 100px;
}
}
</style>
</head>
<body>
<header>
<a href="subm.php" class="back-btn">
<img src="gambar/balik.png" alt="">
</a>
<a href="" class="logo">
<img src="gambar/logo.png" alt="logo" class="logo-img">
</a>
</header>
<section class="parallax">
<h3 id="text">Model dan Sistem Persamaan Linear Dua Variabel</h3>
<img src="gambar/sunpl.png" id="sun">
<img src="gambar/awanpl1.png" id="aw1">
<img src="gambar/awanpl11.png" id="aw11">
<img src="gambar/awanpl2.png" id="aw2">
<img src="gambar/shadowpl.png" id="shad">
</section>
<section class="sec">
<h2>Bentuk Umum Sistem Persamaan Linear Dua Variabel</h2>
<br>
<p>Di Kelas VII, kalian telah mempelajari materi tentang persamaan linear satu variabel. Masih
ingatkah kamu apa yang dimaksud dengan persamaan linear satu variabel? Selain persamaan linear
dua variabel, kalian tentunya masih ingat persamaan garis lurus pada Bab 4 di Semester 1. Persamaan
garis lurus masih erat kaitannya dengan persamaan linear dua variabel.
</p>
<p>
Sebelum kalian menggali informasi, sebaiknya kalian perhatikan uraian berikut:
<br>Contoh bentuk persamaan linear dua variabel
<br>a. y = x + 5
<br>b. a + 2b = 4
<br>c. 3m + 6n = 9
<br>Variabel pada persamaan y = x + 5 adalah x dan y, sedangkan variabel pada persamaan a + 2b = 4
adalah a dan b. Adapun variabel pada persamaan 3m + 6n = 9 adalah m dan n.
</p>
<div class="penting">
<p>Persamaan linear dua variabel dapat dinyatakan dalam bentuk
ax + by = c dengan a, b, c ∈ R, a, b ≠ 0, dan x, y suatu variabel.</p>
</div>
<br>
<div class="tabel">
<p>Tabel. Bentuk Umum Persamaan Linear Dua Variabel</p>
</div>
<div class="ss-img">
<img src="gambar/model.png" alt="model">
</div>
<br><br>
<h2>Video Bentuk Umum Sistem Persamaan Linear Dua Variabel</h2>
<div class="video-frame" data-video-id="VIDEO_ID">
<iframe width="560" height="315" src="https://www.youtube.com/embed/bUxrbDCWZ5E"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen></iframe>
<img src="gambar/laptop.png" alt="Laptop Frame">
</div>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.0/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.0/ScrollTrigger.min.js"></script>
<script>
gsap.from("#sun", {
scrollTrigger: {
scrub: true
},
x: 0,
y: 200,
})
gsap.from("#aw1", {
scrollTrigger: {
scrub: true
},
x: 200,
y: 30,
})
gsap.from("#aw11", {
scrollTrigger: {
scrub: true
},
x: -200,
y: 80,
})
gsap.from("#aw2", {
scrollTrigger: {
scrub: true,
end: '+=400'
},
y: 200,
})
gsap.from("#shad", {
scrollTrigger: {
scrub: true
},
y: 0,
})
gsap.from("#text", {
scrollTrigger: {
scrub: true
},
y: 50,
})
</script>
<script>
function playVideo() {
var frame = document.querySelector('.video-frame');
var videoId = frame.dataset.videoId;
var embedUrl = 'https://www.youtube.com/embed/' + videoId + '?autoplay=1';
frame.innerHTML = '<iframe width="100%" height="100%" src="' + embedUrl +
'" frameborder="0" allowfullscreen></iframe>';
}
document.querySelector('.play-button').addEventListener('click', playVideo);
</script>
</body>
</html>
|
use std::collections::HashMap;
pub struct Solution {}
impl Solution {
pub fn min_subarray(nums: Vec<i32>, p: i32) -> i32 {
let remains = nums.iter().fold(0, |acc, num| (acc + num) % p);
if remains == 0 {
return 0;
}
let mut min_len = nums.len() as i32;
let mut map = HashMap::new();
map.insert(0, -1);
let mut tmp_remains = 0;
for i in 0..nums.len() {
tmp_remains = (tmp_remains + nums[i]) % p;
let target = (p + tmp_remains - remains) % p;
if let Some(j) = map.get(&target) {
min_len = min_len.min(i as i32 - j);
}
map.insert(tmp_remains, i as i32);
}
if min_len == nums.len() as i32 {
-1
} else {
min_len
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_1590() {
assert_eq!(
Solution::min_subarray(vec![1000000000, 1000000000, 1000000000], 3),
0
);
assert_eq!(Solution::min_subarray(vec![3, 1, 4, 2], 6), 1);
assert_eq!(Solution::min_subarray(vec![6, 3, 5, 2], 9), 2);
assert_eq!(Solution::min_subarray(vec![1, 2, 3], 3), 0);
assert_eq!(Solution::min_subarray(vec![3], 2), -1);
}
}
|
// Adam Rilatt
// 14 September 2023
// Distributed Project 1 -- Abstract Storage Device
#ifndef STORAGE_DEVICE_H
#define STORAGE_DEVICE_H
#include <string>
class StorageDevice {
public:
/**
Attempts to create a new location.
@param location The location to create. Locations should be unique.
@throws std::runtime_error if the location was not successfully created (for
example, if the location already exists).
*/
virtual void create_location(const std::string& location) = 0;
/**
Accesses the given location in the database and attempts to find the given
key, then returns its corresponding value.
@param location The location in which to find the given key.
@param key The key corresponding to the desired value.
@throws std::runtime_error if the value is not found.
*/
virtual std::string read(const std::string& location, const std::string& key) = 0;
/**
Accesses the given location and attempts to store the given key-value pair.
@param location The location in which to place the given key-value pair.
@param key The key to save.
@param value The value to save.
@throws std::runtime_error if the write operation was not successful.
*/
virtual void write(const std::string& location, const std::string& key, const std::string& value) = 0;
/**
Accesses the given location and deletes the given key-value pair, if it exists.
If it doesn't exist, or if the operation otherwise fails, returns false.
@param location The location in which to find the key-value pair to delete.
@param key The key belonging to the key-value pair to delete.
@throws std::runtime_error if the delete operation was not successful.
*/
virtual void remove(const std::string& location, const std::string& key) = 0;
};
#endif
|
import 'package:flutter/material.dart';
import 'package:grab_meals/constants/colors.dart';
import 'package:grab_meals/utils/helper.dart';
import 'package:grab_meals/widgets/custom_nav_bar.dart';
import 'package:grab_meals/widgets/search_bar.dart';
class DessertScreen extends StatelessWidget {
static const routeName = '/dessertScreen';
const DessertScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
GestureDetector(
onTap: () {
Navigator.of(context).pop();
},
child: const Icon(
Icons.arrow_back_ios_rounded,
color: AppColors.primary,
),
),
const SizedBox(
width: 5,
),
Expanded(
child: Row(
children: [
Text(
"Desserts",
style: Helper.getTheme(context).headline5,
),
],
),
),
const Icon(Icons.shopping_cart),
],
),
),
const SizedBox(
height: 20,
),
const SearchBar(
title: "Search Food",
),
const SizedBox(
height: 15,
),
DessertCard(
image: Image.asset(
Helper.getImageAssetName("apple_pie.jpg"),
fit: BoxFit.cover,
),
name: "French Apple Pie",
shop: "Minute by tuk tuk",
rating: "4.9",
),
const SizedBox(
height: 5,
),
DessertCard(
image: Image.asset(
Helper.getImageAssetName("dessert2.jpg"),
fit: BoxFit.cover,
),
name: "Dark Chocolate Cake",
shop: "Cakes by Tella",
rating: "4.7",
),
const SizedBox(
height: 5,
),
DessertCard(
image: Image.asset(
Helper.getImageAssetName("dessert4.jpg"),
fit: BoxFit.cover,
),
name: "Street Shake",
shop: "Cafe Racer",
rating: "4.9",
),
const SizedBox(
height: 5,
),
DessertCard(
image: Image.asset(
Helper.getImageAssetName("dessert5.jpg"),
fit: BoxFit.cover,
),
name: "Fudgy Chewy Brownies",
shop: "Minute by tuk tuk",
rating: "4.9",
),
const SizedBox(
height: 100,
),
],
),
),
),
const Positioned(
bottom: 0,
left: 0,
child: CustomNavBar(
menu: true,
),
),
],
),
);
}
}
class DessertCard extends StatelessWidget {
const DessertCard({
Key? key,
required String name,
required String rating,
required String shop,
required Image image,
}) : _name = name,
_rating = rating,
_shop = shop,
_image = image,
super(key: key);
final String _name;
final String _rating;
final String _shop;
final Image _image;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 250,
width: double.infinity,
child: Stack(
children: [
SizedBox(
height: 250,
width: double.infinity,
child: _image,
),
Container(
height: 250,
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
Colors.black.withOpacity(0.7),
Colors.black.withOpacity(0.2),
],
),
),
),
Align(
alignment: Alignment.bottomLeft,
child: Container(
height: 70,
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_name,
style: Helper.getTheme(context).headline4!.copyWith(color: Colors.white,),
),
Row(
children: [
const Icon(Icons.star, color: Colors.yellowAccent,),
const SizedBox(
width: 5,
),
Text(
_rating,
style: const TextStyle(color: AppColors.mainColor),
),
const SizedBox(
width: 5,
),
Text(
_shop,
style: const TextStyle(color: Colors.white),
),
const SizedBox(
width: 5,
),
const Padding(
padding: EdgeInsets.only(bottom: 8.0),
child: Text(
".",
style: TextStyle(color: AppColors.mainColor),
),
),
const SizedBox(
width: 5,
),
const Text(
"Desserts",
style: TextStyle(color: Colors.white),
),
],
)
],
),
),
)
],
),
);
}
}
|
import { instanceDomain } from '@moodlenet/core'
import { getWebappUrl } from '@moodlenet/react-app/server'
import { getProfileHomePageRoutePath } from '@moodlenet/web-user/common'
import {
getCurrentProfileIds,
getProfileOwnKnownEntities,
getProfileRecord,
} from '@moodlenet/web-user/server'
import assert from 'assert'
import JiraApi from 'jira-client'
import { env } from './init/env.mjs'
import { kvStore } from './init/kvStore.mjs'
import { approvalJiraIssueObject, jiraResponse2JiraIssueEntityMeta } from './lib.mjs'
import type { JiraIssueMetaEntity, ServiceConfigs, UserApprovalRequest } from './types.mjs'
const jira = new JiraApi(env.jiraApiOptions)
await jira.getCurrentUser().catch(err => {
throw new Error(`jira authentication failed`, { cause: err })
})
// type UserRequestStateResp = {
// userApprovalRequest: UserApprovalRequest
// canPrompt: boolean
// jiraIssueMetaEntity: JiraIssueMetaEntity
// }
export async function getUserRequestState_currentUser() {
const profileIds = await getCurrentProfileIds()
if (!profileIds) return null
return getUserRequestState({ profileKey: profileIds._key })
}
export type UserRequestState =
| {
type: 'in-charge'
canPrompt: boolean
userApprovalRequest: UserApprovalRequest
jiraIssueMetaEntity: JiraIssueMetaEntity
}
| {
type: 'no-request'
isEligible: boolean
}
export async function getUserRequestState({
profileKey,
}: {
profileKey: string
}): Promise<UserRequestState> {
const userApprovalRequest = (await kvStore.get('user-approval-request', profileKey)).value
const serviceConfigs = await getServiceConfigs()
if (!userApprovalRequest) {
const ownResources = await getProfileOwnKnownEntities({ profileKey, knownEntity: 'resource' })
return {
type: 'no-request',
isEligible: isEligible(ownResources.length, serviceConfigs),
}
}
const jiraIssueMetaEntity = await fetchJiraIssueMetaEntity({
jiraIssueId: userApprovalRequest.jiraIssueId,
})
if (!jiraIssueMetaEntity) {
kvStore.unset('user-approval-request', profileKey)
const ownResources = await getProfileOwnKnownEntities({ profileKey, knownEntity: 'resource' })
return {
type: 'no-request',
isEligible: isEligible(ownResources.length, serviceConfigs),
}
}
const canPrompt =
new Date(userApprovalRequest.lastRequest).valueOf() +
1000 * 60 * 60 * 24 * serviceConfigs.publishingApproval.daysIntervalBeforeRequests <
Date.now()
return {
type: 'in-charge',
userApprovalRequest,
canPrompt,
jiraIssueMetaEntity,
} as const
}
function isEligible(ownResouorceAmount: number, serviceConfigs: ServiceConfigs): boolean {
return ownResouorceAmount >= serviceConfigs.publishingApproval.resourceAmount
}
export async function promptReopenOrCreateJiraIssue_currentUser() {
const profileIds = await getCurrentProfileIds()
assert(profileIds, 'no current user : cannot reopen/create jira issue')
return promptReopenOrCreateJiraIssue({ profileKey: profileIds._key })
}
export async function promptReopenOrCreateJiraIssue({ profileKey }: { profileKey: string }) {
const userRequestState = await getUserRequestState({ profileKey })
const lastRequest = new Date().toISOString()
if (userRequestState.type === 'no-request' && userRequestState.isEligible) {
const jiraCreated = await createJiraIssue({ profileKey })
const userApprovalRequest: UserApprovalRequest = {
jiraIssueId: jiraCreated.id,
lastRequest,
profileKey,
}
await kvStore.set('user-approval-request', profileKey, userApprovalRequest)
}
if (userRequestState.type === 'in-charge' && userRequestState.canPrompt) {
await reopenJiraIssue({
jiraIssueId: userRequestState.jiraIssueMetaEntity.id,
})
await jira.addComment(userRequestState.jiraIssueMetaEntity.id, `User prompted approval request`)
const userApprovalRequest: UserApprovalRequest = {
...userRequestState.userApprovalRequest,
lastRequest,
}
await kvStore.set('user-approval-request', profileKey, userApprovalRequest)
}
return getUserRequestState({ profileKey })
}
export async function reopenJiraIssue({ jiraIssueId }: { jiraIssueId: string }) {
const { reopenTransitionId } = env.userApprovalJiraConfigs
await jira.transitionIssue(jiraIssueId, {
transition: { id: reopenTransitionId },
})
}
export async function createJiraIssue_currentUser() {
const profileIds = await getCurrentProfileIds()
assert(profileIds, 'no current user : cannot create jira issue')
return createJiraIssue({ profileKey: profileIds._key })
}
export async function createJiraIssue({ profileKey }: { profileKey: string }) {
const profile = await getProfileRecord(profileKey)
assert(profile, `couldn't find profile ${profileKey}`)
const profileHomepage = getWebappUrl(
getProfileHomePageRoutePath({
_key: profile.entity._key,
displayName: profile.entity.displayName,
}),
)
const moderationJiraConfigs = env.userApprovalJiraConfigs
const serviceConfigs = await getServiceConfigs()
const newIssueObject = approvalJiraIssueObject({
profileMeta: {
profileHomePage: profileHomepage,
profileKey: profile.entity._key,
profileName: profile.entity.displayName,
instanceDomain,
},
moderationJiraConfigs,
jiraAssignee: serviceConfigs.publishingApproval.jira.createAssignee,
})
const issueResponse = await jira.addNewIssue(newIssueObject)
const jiraIssueMetaEntity = jiraResponse2JiraIssueEntityMeta(issueResponse)
return jiraIssueMetaEntity
}
export async function fetchJiraIssueMetaEntity({ jiraIssueId }: { jiraIssueId: string }) {
const issueResponse = await jira.getIssue(jiraIssueId, ['id']).catch(err => {
try {
const msgObj = JSON.parse(err.message)
if (msgObj.errorMessages.includes('The issue no longer exists.')) {
return null
}
throw err
} catch {
throw err
}
})
if (!issueResponse) {
return null
}
// console.log('issueResponse', issueResponse)
const jiraIssueMetaEntity = jiraResponse2JiraIssueEntityMeta(issueResponse)
return jiraIssueMetaEntity
}
export async function getServiceConfigs() {
const config = (await kvStore.get('service-configs', '')).value
assert(config)
return config
}
|
import { t } from "@lingui/macro"
import blake from "blakejs"
import isEqual from "lodash.isequal"
import { BaseAddress } from "src/lib/addressClasses/BaseAddress"
import { getLeadingBits } from "src/lib/bits/getLeadingBits"
import { getTrailingBits } from "src/lib/bits/getTrailingBits"
import { byteToBits } from "src/lib/bytes/byteToBits"
import { getFirstByte } from "src/lib/bytes/getFirstByte"
/**
* Ergo address types.
*
* @see {@link https://docs.ergoplatform.com/dev/wallet/address/}
*/
type TErgoAddressType = {
type: number
bits: Array<number>
name: string
}
const ergoAddressTypes = [
{
type: 1,
bits: [1, 0, 0, 0],
name: "Pay-to-PublicKey (P2PK)",
},
{
type: 2,
bits: [0, 1, 0, 0],
name: "Pay-to-Script-Hash (P2SH)",
},
{
type: 3,
bits: [1, 1, 0, 0],
name: "Pay-to-Script (P2S)",
},
]
/**
* Extended class that parses Bech32 address during initialization.
*/
export class Base58Address extends BaseAddress {
constructor(address: string, decoded: Uint8Array) {
super(address) // sets address property in the base class (lowercased there)
this.class = this.constructor.name
this.encoding = "Base58"
this.decoded = {
bytes: Array.from(decoded),
hex: Buffer.from(decoded).toString("hex"),
}
// generate header
const headerByteArray = getFirstByte(decoded)
const headerByte = parseInt(Buffer.from(headerByteArray).toString("hex"), 16)
const headerBits = byteToBits(headerByte, 8)
// generate checksum property
const checksumBytes = getErgoChecksum(decoded)
this.payload.checksum = {
bytes: Array.from(Buffer.from(checksumBytes)),
hex: Buffer.from(checksumBytes).toString("hex"),
}
// generate content
const contentBytes = getErgoContent(decoded)
this.payload.content = {
bytes: Array.from(Buffer.from(contentBytes)),
hex: Buffer.from(contentBytes).toString("hex"),
}
if (isErgoAddress(decoded)) {
this.isSupported = true
this.blockchain.name = "Ergo"
this.blockchain.explorerUrl = `https://explorer.ergoplatform.com/en/addresses/`
this.currency = {
decimals: 9,
ticker: "ERG",
tickerSymbol: "Σ",
nano: "nanoERG",
}
this.payload.prefix = {
byte: headerByte,
hex: Buffer.from(headerByteArray).toString("hex"),
bits: headerBits,
leading: {
bits: getLeadingBits(headerBits),
type: t`Address Type`,
},
trailing: {
bits: getTrailingBits(headerBits),
type: t`Network Type`,
},
}
if (this.payload.prefix.trailing !== undefined) {
this.blockchain.network = getErgoNetwork(this.payload.prefix.trailing.bits)
// invalidate if not mainnet
if (this.blockchain.network !== "Mainnet") {
this.isSupported = false
}
}
if (this.payload.prefix.leading !== undefined) {
const typeObject = getErgoType(this.payload.prefix.leading.bits)
Object.assign(this, { type: typeObject })
// invalidate if not mainnet
if (typeObject.type !== 1) {
this.isSupported = false
}
}
}
}
}
/**
* Returns the content bytes last four bytes of the Ergo address (which is the checksum payload).
*
* @param decoded - Uint8Array with the full decoded address
*/
function getErgoContent(decoded: Uint8Array): Uint8Array {
const size = decoded.length
const result = decoded.slice(0, size - 4) // remove last four (checksum) bytes
return result.slice(1) // remove first (header) byte
}
/**
* Returns the last four bytes of the Ergo address (which is the checksum payload).
*
* @param decoded - Uint8Array with the full decoded address
*/
function getErgoChecksum(decoded: Uint8Array): Uint8Array {
const size = decoded.length
return decoded.slice(size - 4, size)
}
/**
* Returns true if this is an Ergo address.
*
* @param decoded - Array with 8 bits
*/
function isErgoAddress(decoded: Uint8Array): boolean {
const size = decoded.length
const script = decoded.slice(0, size - 4)
const checksum = decoded.slice(size - 4, size)
const calculatedChecksum = Buffer.from(blake.blake2b(script, undefined, 32)).slice(0, 4)
return calculatedChecksum.toString("hex") === Buffer.from(checksum).toString("hex")
}
/**
* Returns the blockchain network by calculating the sum of network header bits.
*
* @param networkBits - Array with 4 network bits
*/
function getErgoNetwork(networkBits: Array<number>) {
const sum = networkBits.reduce((a, b) => a + b)
if (sum === 0) {
return "Mainnet"
}
if (sum === 1) {
return "Testnet"
}
throw `Unable to determine Ergo network using network header bits ${networkBits.join()}`
}
/**
* Returns the Ergo address 'type' object matching the type header bits.
*
* @param typeBits - Array with 4 type bits
*/
function getErgoType(typeBits: Array<number>): TErgoAddressType {
const type = ergoAddressTypes.find(({ bits }) => isEqual(bits, typeBits))
if (type === undefined) {
throw `Unable to determine Ergo address type using header bits ${typeBits.join()}`
}
return type
}
|
/**
memcpy.s
@ Subroutine memcpy: Provided a source address in x0, a destination address in x1, and a size in x2,
@ memcpy will copy x2 bytes from the source address to the destination address.
@ x0: Must contain the source address
@ x1: Must contain the destination address
@ x2: Must contain the number of bytes to copy
@ All registers are preserved, except x0, x1, x2, and x30
*/
.text
.global memcpy
memcpy:
// Save registers x19 to x29, and the link register lr on the stack
stp x29, x30, [sp, -16]!
stp x19, x20, [sp, -16]!
stp x21, x22, [sp, -16]!
stp x23, x24, [sp, -16]!
stp x25, x26, [sp, -16]!
stp x27, x28, [sp, -16]!
stp x29, lr, [sp, -16]!
// Set up the stack frame for this function
mov x29, sp
// Loop through and copy each byte from source to destination
loop:
// Check if we've copied all bytes
cmp x2, #0
b.eq exit
// Load a byte from the source address into x19
ldrb w19, [x0], #1
// Store the byte in the destination address
strb w19, [x1], #1
// Decrement the byte count
sub x2, x2, #1
// Repeat until all bytes are copied
b loop
// Clean up the stack frame
exit:
// Restore the saved registers x19 to x29, and the link register lr from the stack
ldp x29, lr, [sp], 16
ldp x27, x28, [sp], 16
ldp x25, x26, [sp], 16
ldp x23, x24, [sp], 16
ldp x21, x22, [sp], 16
ldp x19, x20, [sp], 16
ldp x29, x30, [sp], 16
ret
|
<!-- 시즌2 : 함수
- 자바스크립트? 함수형 언어, 객체 지향을 독특한 관점에서 구현하고 있음
- 함수? 모듈화의 근간, 정보 은닉, 객체 행위 지정 등등
* 유의사항 *
- 전역변수는 사용하지 않는 것이 좋다. 여러가지 이유로 그 값이 변경될 수 있기 때문이다.
- 함수 안에서 전역변수를 사용하고 있는데, 누군가에 의해서 전역변수의 값이 달라졌다면 어떻게 될까? 함수의 동작도 달라지게 된다. 이것은 버그의 원인이 된다.
- 또한 함수를 다른 에플리케이션에 이식하는데도 어려움을 초래한다.
- 함수의 핵심은 로직의 재활용이라는 점을 상기하자.
- 변수를 선언할 때는 꼭 var을 붙이는 것을 습관화해야 한다. 전역변수를 사용해야 하는 경우라면 그것을 사용하는 이유를 명확히 알고 있을 때 사용하도록 하자.
* 유효범위(scope) : 변수의 수명을 의미
- (e.g) 함수 밖에서 변수를 선언하면, 그 변수는 전역변수(global variable)이 된다.
다시 말해서, 어떤 함수 안에서도 그 변수에 접근할 수 있다.
let vscope = 'global';
funciton fscope() {
alert(vscope);
}
fscope();
let vscope = 'global';
function fscope(){
return vscope;
}
console.log(fscope()); // global
-->
<!--
- (e.g) 지역변수의 유효범위는 함수 안이다.
전역변수의 유효범위는 애플리케이션 전역인데, 같은 이름의 지역변수와 전역변수가 동시에 정의되어 있다면, 지역변수가 우선한다
let vscope = 'global';
function fscope(){
let vscope = 'local'; // 차이!
return vscope
}
console.log(fscope()); // local
console.log(vscope); // global
- (e.g) 함수밖에서도 vscope의 값이 local인 이유는 무엇일까?
그것은 함수 fscope의 지역변수를 선언할 때 let을 사용하지 않았기 때문이다.
let을 사용하지 않은 지역변수는 전역변수가 된다.
let vscope = 'global';
function fscope(){
vscope = 'local'; // 차이! // let이 없으면 전역변수가 되버려!
return vscope
}
console.log(fscope()); // local
console.log(vscope); // local
let vscope = 'global';
function fscope(){
let vscope = 'local';
vscope = 'local'
return vscope
}
console.log(fscope()); // local
console.log(vscope); // global
-->
<!-- 유효범위의 필요성과 지역변수 사용의 필요성
: 변수 i를 지역변수로 사요했을 대와 전역변수로 사용했을 때의 차이점
: 전역변수는 각기 다른 로직에서 사용하는 같은 이름의 변수값을 변경시켜서 의도하지 않은 문제를 발생시킨다.
- (e.g)
function a () {
let i = 0;
}
for (let i = 0; i<5; i++) {
a(); // call the function
console.log(i);
}
// 0
// 1
// 2
// 3
// 4
- (e.g) 결과 무한 반복! 무한루프에 빠지는 코드 !
function a () {
i = 0; // 차이 // let이 없으면 i는 전역변수가 됨
}
for (let i = 0; i<5; i++) { // 여기 'i'는 전역변수
a(); // call the function // i는 계속 0이 되어 5보다 커지지 않으므로 무한루프에 빠지게 됨
console.log(i);
}
-->
<!-- 전역변수를 불가피하게 사용해야하는 경우
: 하나의 객체를 (전역변수로) 만들고, 객체의 속성으로 (전역)변수를 관리하는 방법을 사용한다.
- (e.g) MYAPP이라는 변수 하나에, 필요한 전역 변수들을 넣음
let MYAPP = {} // 전역변수, 객체임
MYAPP.calculator = { // 객체에 calculator라는 속성(=객체 안에 들어있는 변수)을 (다시 객체로) 줌
'left' : null, // null = 아직 값을 지정하지 않았다는 의미
'right' : null
}
MYAPP.coordinate = {
'left' : null, // left와 right는 위와 스펠링이 같지만, 속성이
'right' : null
}
MYAPP.calculator.left = 10;
MYAPP.calculator.right = 20;
function sum() {
return MYAPP.calculator.left + MYAPP.calculator.right;
}
console.log(sum()); // 30
* 만약 전역변수를 사용하고 싶지 않다면?
: 익명함수를 호출함으로서 이러한 목적을 달성할 수 있음!
: MYAPP은 전역변수가 아니라, 함수(function) 안에 지역변수가 된 것임
: 익명함수는 모듈화 기법으로 제이쿼리나 자바스크립트 라이브러리에서 자주 활용된대
: 익명함수란? 이름이 없는 함수로, 즉시 실행이 필요할 경우 사용합니다.
(function () {
//logic
})();
- (e.g)
(function(){
var MYAPP = {}
MYAPP.calculator = {
'left' : null,
'right' : null
}
MYAPP.coordinate = {
'left' : null,
'right' : null
}
MYAPP.calculator.left = 10;
MYAPP.calculator.right = 20;
function sum(){
return MYAPP.calculator.left + MYAPP.calculator.right;
}
console.log(sum());
}())
-->
<!-- 유효범위의 대상 (함수)
: 자바스크립트는 함수에 대한 유효범위만을 제공한다.
: 많은 언어들이 블록 (대체로 {,})에 대한 유효범위를 제공하는 것돠 다른 점이다!
- (e.g) 함수 중가로 안에서 선언된 변수만이 그 함수 안에서의 지역변수가 되는 것이고,
for문, if문 중가로 안에서 선언된 변수는, 지역변수로서의 의미를 갖지 않는다.
- * var가 function-scoped로 hoisting이 되었다면
* let, const는 block-scoped단위로 hoisting이 일어남
- (e.g) name은 지역변수로 for 문 안에서 선언 되었는데 이를 for문 밖에서 호출하고 있기 때문에 에러 발생! (=자바에서도 같은 에러 발생)
for (let i = 0 ; i < 1; i++) {
let name = "Suji";
}
console.log(name);
- (e.g) var로 선언하면 에러가 발생하지 않지만, 사용 비추e.g
for(var i = 0; i < 5; i++){
var name = 'Suji';
}
console.log(name); // Suji
-->
<!-- 정적 유효범위
: 자바스크립트는 함수가 선언된 시점에서의 유효범위를 갖는다.
: 이러한 유효범위의 방식을 정적 유효범위 (static scoping) 혹은 (lexical scoping)이라고 한다.
- (e.g) 사용될 때가 아니고, 정의될 때의 전역변수가 사용되게 된다 = 정적 유효범위, 어휘적 유효범위
let i = 5; // 전역변수(global variable)
function a() {
let i = 10;
b(); // b가 정의되는 시점에서 변수를 바라보게 된다면, 정적 유효범위!
}
function b() {
console.log(i);
}
a(); // 5
-->
|
import Button from "@components/Buttons/Button";
import Modal from "@components/Modal";
import fullName from "@util/fullName";
import React, { useState } from "react";
import { useAlert } from "react-alert";
import strapi from "@api/strapi";
import { useAuth } from "@contexts/auth";
import NProgress from "nprogress";
import styles from "@components/Modal.module.css";
export default function MessageModal({ show, recipient, onClose }) {
const [message, setMessage] = useState("");
const alert = useAlert();
const { updateUser } = useAuth();
const onSend = async () => {
if (!message) return alert.error("Please enter a message");
NProgress.start();
try {
const { data: chatroom } = await strapi.post("chatrooms", {
participant: recipient.id,
});
await strapi.post("messages", {
chatroom: chatroom.id,
content: message,
});
updateUser();
alert.success("Message sent!");
} catch {
alert.error("Error occurred in attempting to send message.");
}
NProgress.done();
onClose();
};
if (!show) return <></>;
return (
<Modal
className="shortModal"
show={show}
title="Start a conversation"
onClose={onClose}
>
<div className=""></div>
<p>Send your first message to {fullName(recipient)}</p>
<br />
<textarea
className={styles.messageTextArea}
value={message}
placeholder="Type here..."
onChange={(e) => {
setMessage(e.target.value);
}}
></textarea>
<Button color="greenBg" onClick={onSend}>
Send
</Button>
</Modal>
);
}
|
import { Component, Input, OnInit } from '@angular/core';
import { TimeFormatService } from '../../../shared/services/time-format.service';
import { ChartOptions } from '../battery-statistics/battery-statistics.component';
import * as moment from 'moment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { environment } from '../../../../environments/environment';
import { TokenStorageServiceService } from '../../../auth/login/token-storage-service.service';
@Component({
selector: 'app-resident-statistics',
templateUrl: './resident-statistics.component.html',
styleUrls: []
})
export class ResidentStatisticsComponent implements OnInit {
public chartOptions: Partial<ChartOptions>;
header:any;
selectedInterval: string = 'Last 7 days';
@Input() titleShow = false;
@Input() type: string;
@Input() forType: string = "";
role = '';
constructor(private tokenStorage: TokenStorageServiceService,private timeFormat: TimeFormatService,private http: HttpClient,private routeActivate: ActivatedRoute ) {
let user: any = localStorage.getItem('loggedInUser');
if(user){
user = JSON.parse(user);
this.role = user.user_type;
}
this.chartOptions = {
series: [
{
name: 'Resident profile viewed',
data: [10, 30, 50, 60, 70, 30, 70],
},
{
name: 'Unique profile viewed',
data: [2, 15, 20, 5, 21, 9, 18],
},
],
chart: {
type: 'line',
height: 320,
animations: {
enabled: false,
},
zoom: {
enabled: false,
type: 'x',
},
toolbar: {
show: false
}
},
// title: {
// text: "Screen time usage (Hours)",
// align: 'center',
// margin: 0,
// offsetX: 0,
// offsetY: 0,
// style: {
// fontSize: '18px',
// fontWeight: 600,
// fontFamily: 'Whitney A,Whitney B,Helvetica,Arial,sans-serif',
// color: '#434342'
// },
// },
dataLabels: {
enabled: false,
},
legend: {
show: true,
position: "bottom",
fontSize: '14px',
fontFamily: 'Whitney A,Whitney B,Helvetica,Arial,sans-serif',
fontWeight: 500,
offsetY: 8,
itemMargin: {
horizontal: 5,
vertical: 10
},
markers: {
width: 15,
height: 15,
radius: 0,
offsetX: 0,
offsetY: 0
},
},
xaxis: {
type: 'datetime',
title: {
text: 'Date',
offsetX: 0,
offsetY: 12,
style: {
color: '#434342',
fontSize: '14px',
fontFamily: 'Whitney A,Whitney B,Helvetica,Arial,sans-serif',
fontWeight: 500,
cssClass: 'apexcharts-xaxis-title',
},
},
categories: [
'7 Dec 2020',
'8 Dec 2020',
'9 Dec 2020',
'10 Dec 2020',
'11 Dec 2020',
'12 Dec 2020',
'13 Dec 2020',
],
labels: {
style: {
colors: '#aaa093',
fontSize: '12px',
fontFamily: 'Whitney A,Whitney B,Helvetica,Arial,sans-serif',
fontWeight: 500,
cssClass: 'apexcharts-xaxis-label',
},
},
},
markers: {
size: 5
},
yaxis: {
title: {
text: 'Number of profiles viewed',
offsetX: -6,
offsetY: 0,
style: {
color: '#434342',
fontSize: '14px',
fontFamily: 'Whitney A,Whitney B,Helvetica,Arial,sans-serif',
fontWeight: 500,
cssClass: 'apexcharts-xaxis-title',
},
},
min: 0,
tickAmount: 4,
labels: {
style: {
colors: '#aaa093',
fontSize: '12px',
fontFamily: 'Whitney A,Whitney B,Helvetica,Arial,sans-serif',
fontWeight: 500,
cssClass: 'apexcharts-xaxis-label',
},
},
},
tooltip: {
x: {
format: 'dd/MM/yyyy',
},
y: {
formatter: function (val: any) {
return val;
},
},
fixed: {
enabled: false,
position: 'topRight',
offsetX: 0,
offsetY: 0,
},
},
colors: ['#025174', '#bfb4ae', '#87657d', '#8cab88'],
// stroke: {
// show: true,
// curve: 'straight',
// lineCap: 'butt',
// colors: undefined,
// width: 5,
// dashArray: [0, 0, 0, 10],
// },
fill: {
colors: ['#025174'],
opacity: 1,
type: 'solid',
gradient: {
shade: 'light',
type: 'vertical',
shadeIntensity: 1,
gradientToColors: undefined,
inverseColors: false,
opacityFrom: 1,
opacityTo: 1,
stops: [1],
},
},
};
}
momentToday = moment();
customProgressDates: any = {};
getFilterFormat(){
return this.timeFormat.getFilterFormat();
}
getHeaders(){
this.header = new HttpHeaders().set(
"Authorization",
this.tokenStorage.getToken()
);
}
noData = false;
changeDate(e: any){
this.customProgressDates = {
startDate: new Date(e.startDate),
endDate: new Date(e.endDate)
}
const diff = moment(e.endDate).diff(moment(e.startDate), 'days');
const dates = [];
for(let i = 0; i < diff + 1; i++){
dates.push(moment(e.startDate).add(i,'days').format('YYYY-MM-DD'))
}
this.isLoading = true;
this.getHeaders();
this.http.get(`${environment.apiUrlNew}/kpi/get/`,{headers:this.header}).subscribe((data: any) => {
let KPIData = [];
if(this.type === 'ward' && this.role === 'SSA'){
data.body.filter(value => value.details.ward_id === this.wardId).forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}else if(this.type === 'facility' && this.role === 'SSA'){
data.body.filter(value => value.details.facility_id === this.facilityId).forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}else if(this.type === 'customer' && this.role === 'SSA'){
data.body.filter(value => value.details.customer_id === this.customerId).forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}else if(this.type === 'dashboard' && this.role === 'SSA'){
data.body.forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}else if(this.type === 'ward' && this.role === 'CA'){
data.body.filter(value => value.details.ward_id === this.wardId).forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}else if(this.type === 'facility' && this.role === 'CA'){
data.body.filter(value => value.details.facility_id === this.facilityId).forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}else if(this.type === 'customer' && this.role === 'CA'){
const user = JSON.parse(localStorage.getItem('loggedInUser'));
this.customerId = user.customers.customer_id;
data.body.filter(value => value.details.customer_id === this.customerId).forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}else if(this.type === 'ward' && this.role === 'FA'){
data.body.filter(value => value.details.ward_id === this.wardId).forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}else if(this.type === 'facility' && this.role === 'FA'){
data.body.filter(value => value.details.facility_id === this.facilityId).forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}else if(this.type === 'ward' && this.role === 'WA'){
data.body.filter(value => value.details.ward_id === this.wardId).forEach(value =>{
const exists = dates.includes(value.meta.Rdate);
if(exists){
KPIData.push(value)
}
})
const intermediate = [];
KPIData.forEach(val => {
const exists = intermediate.find(value => value.meta.Rdate === val.meta.Rdate);
if(!exists){
val.KPI.ResidentProfilesViewed = parseFloat(val.KPI.ResidentProfilesViewed);
val.KPI.UniqueProfilesViewed = parseFloat(val.KPI.UniqueProfilesViewed)
Object.assign(val, {count : 1})
intermediate.push(val);
}else{
exists.KPI.ResidentProfilesViewed = exists.KPI.ResidentProfilesViewed + parseFloat(val.KPI.ResidentProfilesViewed);
exists.KPI.UniqueProfilesViewed = exists.KPI.UniqueProfilesViewed + parseFloat(val.KPI.UniqueProfilesViewed);
exists.count = exists.count + 1;
}
})
KPIData = intermediate;
}
KPIData.sort((a,b) => {
return parseInt(a.meta.timestamp) > parseInt(b.meta.timestamp) ? 1 : -1;
});
const categories = KPIData.map((value: any) => {
return value.meta.Rdate;
})
const resident = KPIData.map((value: any, i: number )=> {
return value.KPI.ResidentProfilesViewed
})
let max = 0;
if(KPIData.length > 0){
this.isDataAvailable = true;
}
KPIData.forEach(val => {
if(parseInt(val.KPI.ResidentProfilesViewed) > max){
max = parseInt(val.KPI.ResidentProfilesViewed);
}
if(parseInt(val.KPI.UniqueProfilesViewed) > max){
max = parseInt(val.KPI.UniqueProfilesViewed)
}
})
const unique = KPIData.map((value: any, i: number ) => {
return value.KPI.UniqueProfilesViewed;
})
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.customProgressDates = {
startDate: categories[0],
endDate: categories[categories.length - 1]
}
this.chartOptions.yaxis.max = this.rounded(max);
this.isLoading = false
})
}
wardId = '';
ngOnInit(): void {
this.getLast7days();
}
getLast7days(){
this.selectedInterval = 'Last 7 days';
if(this.type === 'ward' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('week');
});
}else if(this.type === 'facility' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.facilityId = data.get('facilityId');
this.getKPIFacilityData('week');
});
}else if(this.type === 'customer' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.customerId = data.get('customer_id');
this.getKPICustomerData('week');
});
}else if(this.type === 'dashboard' && this.role === 'SSA'){
this.getKPIDashboardData('week');
}else if(this.type === 'ward' && this.role === 'CA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('week');
});
}else if(this.type === 'facility' && this.role === 'CA'){
this.routeActivate.paramMap.subscribe(data => {
this.facilityId = data.get('facilityId');
this.getKPIFacilityData('week');
});
}else if(this.type === 'customer' && this.role === 'CA'){
const user = JSON.parse(localStorage.getItem('loggedInUser'));
this.customerId = user.customers.customer_id;
this.getKPICustomerData('week');
}else if(this.type === 'ward' && this.role === 'FA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('week');
});
}else if(this.type === 'facility' && this.role === 'FA'){
const user = JSON.parse(localStorage.getItem('loggedInUser'));
this.facilityId = user.facilities.facility_id;
this.getKPIFacilityData('week');
}else if(this.type === 'ward' && this.role === 'WA'){
let user: any = localStorage.getItem('loggedInUser');
if(user){
user = JSON.parse(user);
this.wardId = user.wards[0].ward_id;
this.getKPIWardData('week');
}
}
}
isLoading = false;
isDataAvailable = false;
getKPIWardData(interval: string){
this.isLoading = true;
this.getHeaders();
if(interval === 'week'){
this.http.get(`${environment.apiUrlNew}/kpi/getSevenDaysWSummary/?ward_id=${this.wardId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.ward_id === this.wardId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
if(KPIData.length > 0){
this.isDataAvailable = true;
}
const categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
const resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
const unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}else if(interval === 'month'){
this.http.get(`${environment.apiUrlNew}/kpi/getOneMonthWSummary/?ward_id=${this.wardId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.ward_id === this.wardId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
if(KPIData.length > 0){
this.isDataAvailable = true;
}
const categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
const resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
const unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}else if(interval === 'threeMonth'){
this.http.get(`${environment.apiUrlNew}/kpi/getThreeMonthsWSummary/?ward_id=${this.wardId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.ward_id === this.wardId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
if(KPIData.length > 0){
this.isDataAvailable = true;
}
let categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
// unique = unique.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// resident = resident.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// categories = categories.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1)
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}else if(interval === 'sixMonth'){
this.http.get(`${environment.apiUrlNew}/kpi/getSixMonthsWSummary/?ward_id=${this.wardId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.ward_id === this.wardId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
if(KPIData.length > 0){
this.isDataAvailable = true;
}
let categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
// unique = unique.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// resident = resident.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// categories = categories.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1)
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}
}
rounded(numb: number){
const round = Math.round(numb);
return Math.ceil(round / 5) * 5;
}
facilityId = '';
getKPIFacilityData(interval: string){
this.isLoading = true;
this.getHeaders();
if(interval === 'week'){
this.http.get(`${environment.apiUrlNew}/kpi/getSevenDaysFSummary/?facility_id=${this.facilityId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.facility_id === this.facilityId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
if(KPIData.length > 0){
this.isDataAvailable = true;
}
const categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
const resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
const unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
//console.log("maxtime"+ this.rounded(max));
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}else if(interval === 'month'){
this.http.get(`${environment.apiUrlNew}/kpi/getOneMonthFSummary/?facility_id=${this.facilityId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.facility_id === this.facilityId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
if(KPIData.length > 0){
this.isDataAvailable = true;
}
const categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
const resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
const unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}else if(interval === 'threeMonth'){
this.http.get(`${environment.apiUrlNew}/kpi/getThreeMonthsFSummary/?facility_id=${this.facilityId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.facility_id === this.facilityId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
if(KPIData.length > 0){
this.isDataAvailable = true;
}
let categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
// unique = unique.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// resident = resident.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// categories = categories.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
}
this.isLoading = false;
})
}else if(interval === 'sixMonth'){
this.http.get(`${environment.apiUrlNew}/kpi/getSixMonthsFSummary/?facility_id=${this.facilityId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.facility_id === this.facilityId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
if(KPIData.length > 0){
this.isDataAvailable = true;
}
let categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
// unique = unique.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// resident = resident.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// categories = categories.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1)
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}
}
customerId = '';
getKPICustomerData(interval: string){
this.isLoading = true;
this.getHeaders();
if(interval === 'week'){
this.http.get(`${environment.apiUrlNew}/kpi/getSevenDaysCSummary/?customer_id=${this.customerId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.customer_id === this.customerId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
const categories = KPIData.map((value: any) => {
console.log(value.details.Rdate);
return value.details.Rdate;
})
const resident = KPIData.map((value: any, i: number )=> {
//console.log(value.Graph.UniqueProfilesViewed);
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
const unique = KPIData.map((value: any, i: number ) => {
console.log(value.Graph.UniqueProfilesViewed);
return value.Graph.UniqueProfilesViewed;
})
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
this.chartOptions.yaxis.max = this.rounded(max);
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else
//if(unique.length > 0 || resident.length > 0)
{
this.isDataAvailable = true;
//this.isDataAvailable = false;
}
}
this.isLoading = false;
})
}else if(interval === 'month'){
this.http.get(`${environment.apiUrlNew}/kpi/getOneMonthCSummary/?customer_id=${this.customerId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.customer_id === this.customerId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
let categories = KPIData.map((value: any) => {
console.log(value.Graph.UniqueProfilesViewed);
return value.details.Rdate;
})
let resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let unique = KPIData.map((value: any, i: number ) => {
//console.log(value.Graph.UniqueProfilesViewed);
return value.Graph.UniqueProfilesViewed;
})
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
console.log(categories);
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
this.chartOptions.yaxis.max = this.rounded(max);
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
// if(unique.length > 0 || resident.length > 0){
// this.isDataAvailable = true;
// //this.isDataAvailable = false;
// }
}
this.isLoading = false;
})
}else if(interval === 'threeMonth'){
this.http.get(`${environment.apiUrlNew}/kpi/getThreeMonthsCSummary/?customer_id=${this.customerId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.customer_id === this.customerId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
let categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
// unique = unique.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// resident = resident.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// categories = categories.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1)
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
this.chartOptions.yaxis.max = this.rounded(max);
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
// if(unique.length > 0 || resident.length > 0){
// this.isDataAvailable = true;
// }else {
// this.isDataAvailable = false;
// }
}
this.isLoading = false;
})
}else if(interval === 'sixMonth'){
this.http.get(`${environment.apiUrlNew}/kpi/getSixMonthsCSummary/?customer_id=${this.customerId}`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body.filter(value => value.details.customer_id === this.customerId)
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
;
let categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let resident = KPIData.map((value: any, i: number )=> {
return value.Graph.ResidentProfilesViewed
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let unique = KPIData.map((value: any, i: number ) => {
return value.Graph.UniqueProfilesViewed;
})
// unique = unique.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// resident = resident.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// categories = categories.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1)
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
this.chartOptions.yaxis.max = this.rounded(max);
if(this.rounded(max)==0 ){
this.isDataAvailable = false;
}else {
this.isDataAvailable = true;
}
// if(unique.length > 0 || resident.length > 0){
// this.isDataAvailable = true;
// }
}
this.isLoading = false;
})
}
}
getLast1Month(){
this.selectedInterval = 'Last 1 month';
if(this.type === 'ward' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('month');
});
}else if(this.type === 'facility' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.facilityId = data.get('facilityId');
this.getKPIFacilityData('month');
});
}else if(this.type === 'customer' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.customerId = data.get('customer_id');
this.getKPICustomerData('month');
});
}else if(this.type === 'dashboard' && this.role === 'SSA'){
this.getKPIDashboardData('month');
}else if(this.type === 'ward' && this.role === 'CA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('month');
});
}else if(this.type === 'facility' && this.role === 'CA'){
this.routeActivate.paramMap.subscribe(data => {
this.facilityId = data.get('facilityId');
this.getKPIFacilityData('month');
});
}else if(this.type === 'customer' && this.role === 'CA'){
const user = JSON.parse(localStorage.getItem('loggedInUser'));
this.customerId = user.customers.customer_id;
this.getKPICustomerData('month');
}else if(this.type === 'ward' && this.role === 'FA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('month');
});
}else if(this.type === 'facility' && this.role === 'FA'){
const user = JSON.parse(localStorage.getItem('loggedInUser'));
this.facilityId = user.facilities.facility_id;
this.getKPIFacilityData('month');
}else if(this.type === 'ward' && this.role === 'WA'){
let user: any = localStorage.getItem('loggedInUser');
if(user){
user = JSON.parse(user);
this.wardId = user.wards[0].ward_id;
this.getKPIWardData('month');
}
}
}
getLast3Month(){
this.selectedInterval = 'Last 3 months';
if(this.type === 'ward' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('threeMonth');
});
}else if(this.type === 'facility' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.facilityId = data.get('facilityId');
this.getKPIFacilityData('threeMonth');
});
}else if(this.type === 'customer' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.customerId = data.get('customer_id');
this.getKPICustomerData('threeMonth');
});
}else if(this.type === 'dashboard' && this.role === 'SSA'){
this.getKPIDashboardData('threeMonth');
}else if(this.type === 'ward' && this.role === 'CA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('threeMonth');
});
}else if(this.type === 'facility' && this.role === 'CA'){
this.routeActivate.paramMap.subscribe(data => {
this.facilityId = data.get('facilityId');
this.getKPIFacilityData('threeMonth');
});
}else if(this.type === 'customer' && this.role === 'CA'){
const user = JSON.parse(localStorage.getItem('loggedInUser'));
this.customerId = user.customers.customer_id;
this.getKPICustomerData('threeMonth');
}else if(this.type === 'ward' && this.role === 'FA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('threeMonth');
});
}else if(this.type === 'facility' && this.role === 'FA'){
const user = JSON.parse(localStorage.getItem('loggedInUser'));
this.facilityId = user.facilities.facility_id;
this.getKPIFacilityData('threeMonth');
}else if(this.type === 'ward' && this.role === 'WA'){
let user: any = localStorage.getItem('loggedInUser');
if(user){
user = JSON.parse(user);
this.wardId = user.wards[0].ward_id;
this.getKPIWardData('threeMonth');
}
}
}
getLast6Month(){
this.selectedInterval = 'Last 6 months';
if(this.type === 'ward' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('sixMonth');
});
}else if(this.type === 'facility' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.facilityId = data.get('facilityId');
this.getKPIFacilityData('sixMonth');
});
}else if(this.type === 'customer' && this.role === 'SSA'){
this.routeActivate.paramMap.subscribe(data => {
this.customerId = data.get('customer_id');
this.getKPICustomerData('sixMonth');
});
}else if(this.type === 'dashboard' && this.role === 'SSA'){
this.getKPIDashboardData('sixMonth');
}else if(this.type === 'ward' && this.role === 'CA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('sixMonth');
});
}else if(this.type === 'facility' && this.role === 'CA'){
this.routeActivate.paramMap.subscribe(data => {
this.facilityId = data.get('facilityId');
this.getKPIFacilityData('sixMonth');
});
}else if(this.type === 'customer' && this.role === 'CA'){
const user = JSON.parse(localStorage.getItem('loggedInUser'));
this.customerId = user.customers.customer_id;
this.getKPICustomerData('sixMonth');
}else if(this.type === 'ward' && this.role === 'FA'){
this.routeActivate.paramMap.subscribe(data => {
this.wardId = data.get('wardId');
this.getKPIWardData('sixMonth');
});
}else if(this.type === 'facility' && this.role === 'FA'){
const user = JSON.parse(localStorage.getItem('loggedInUser'));
this.facilityId = user.facilities.facility_id;
this.getKPIFacilityData('sixMonth');
}else if(this.type === 'ward' && this.role === 'WA'){
let user: any = localStorage.getItem('loggedInUser');
if(user){
user = JSON.parse(user);
this.wardId = user.wards[0].ward_id;
this.getKPIWardData('sixMonth');
}
}
}
getKPIDashboardData(interval: string){
this.isLoading = true;
this.getHeaders();
if(interval === 'week'){
this.http.get(`${environment.apiUrlNew}/kpi/getSevenDaysSummary/`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
const intermediate = [];
KPIData.forEach(value => {
const exists = intermediate.find(val => val.details.Rdate === value.details.Rdate);
if(!exists){
value.Graph.ResidentProfilesViewed = parseFloat(value.Graph.ResidentProfilesViewed);
value.Graph.UniqueProfilesViewed = parseFloat(value.Graph.UniqueProfilesViewed)
intermediate.push(value);
}
})
KPIData = intermediate;
let categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let resident = KPIData.map((value: any, i: number )=> {
return (value.Graph.ResidentProfilesViewed)
})
let unique = KPIData.map((value: any, i: number ) => {
return (value.Graph.UniqueProfilesViewed);
})
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
if(unique.length > 0 || resident.length > 0){
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}
else if(interval === 'month'){
this.http.get(`${environment.apiUrlNew}/kpi/getOneMonthSummary/`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
const intermediate = [];
KPIData.forEach(value => {
const exists = intermediate.find(val => val.details.Rdate === value.details.Rdate);
if(!exists){
value.Graph.ResidentProfilesViewed = parseFloat(value.Graph.ResidentProfilesViewed);
value.Graph.UniqueProfilesViewed = parseFloat(value.Graph.UniqueProfilesViewed)
intermediate.push(value);
}else{
exists.Graph.ResidentProfilesViewed = exists.Graph.ResidentProfilesViewed + parseFloat(value.Graph.ResidentProfilesViewed);
exists.Graph.UniqueProfilesViewed = exists.Graph.UniqueProfilesViewed + parseFloat(value.Graph.UniqueProfilesViewed)
}
})
KPIData = intermediate;
const categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
const resident = KPIData.map((value: any, i: number )=> {
return (value.Graph.ResidentProfilesViewed)
})
const unique = KPIData.map((value: any, i: number ) => {
return (value.Graph.UniqueProfilesViewed);
})
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
if(unique.length > 0 || resident.length > 0){
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}
else if(interval === 'threeMonth'){
this.http.get(`${environment.apiUrlNew}/kpi/getThreeMonthsSummary/`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
const intermediate = [];
KPIData.forEach(value => {
const exists = intermediate.find(val => val.details.Rdate === value.details.Rdate);
if(!exists){
value.Graph.ResidentProfilesViewed = parseFloat(value.Graph.ResidentProfilesViewed);
value.Graph.UniqueProfilesViewed = parseFloat(value.Graph.UniqueProfilesViewed)
intermediate.push(value);
}
})
KPIData = intermediate;
let categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let resident = KPIData.map((value: any, i: number )=> {
return (value.Graph.ResidentProfilesViewed)
})
let unique = KPIData.map((value: any, i: number ) => {
return (value.Graph.UniqueProfilesViewed);
})
// unique = unique.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// resident = resident.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// categories = categories.filter((val: any, i: number) => ((i - 1)%3 === 0 && i > 1) || i === 0 || i === KPIData.length - 1)
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
if(unique.length > 0 || resident.length > 0){
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}
else if(interval === 'sixMonth'){
this.http.get(`${environment.apiUrlNew}/kpi/getSixMonthsSummary/`,{headers:this.header}).subscribe((data: any) => {
if(data.itemCount > 0){
let KPIData = data.body
.sort((a,b) => {
return new Date(a.details.Rdate).getTime() > new Date(b.details.Rdate).getTime() ? 1 : -1;
});
const intermediate = [];
KPIData.forEach(value => {
const exists = intermediate.find(val => val.details.Rdate === value.details.Rdate);
if(!exists){
value.Graph.ResidentProfilesViewed = parseFloat(value.Graph.ResidentProfilesViewed);
value.Graph.UniqueProfilesViewed = parseFloat(value.Graph.UniqueProfilesViewed)
intermediate.push(value);
}
})
KPIData = intermediate;
let categories = KPIData.map((value: any) => {
return value.details.Rdate;
})
let max = 0;
KPIData.forEach(val => {
if(parseInt(val.Graph.ResidentProfilesViewed) > max){
max = parseInt(val.Graph.ResidentProfilesViewed);
}
if(parseInt(val.Graph.UniqueProfilesViewed) > max){
max = parseInt(val.Graph.UniqueProfilesViewed)
}
})
let resident = KPIData.map((value: any, i: number )=> {
return (value.Graph.ResidentProfilesViewed)
})
let unique = KPIData.map((value: any, i: number ) => {
return (value.Graph.UniqueProfilesViewed);
})
// unique = unique.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// resident = resident.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1);
// categories = categories.filter((val: any, i: number) => ((i - 1)%6 === 0 && i > 1) || i === 0 || i === KPIData.length - 1)
this.customProgressDates = {
startDate: categories[categories.length - 1],
endDate: categories[0]
}
this.chartOptions.series[0].data = resident;
this.chartOptions.series[1].data = unique;
this.chartOptions.xaxis.categories = categories;
this.chartOptions.yaxis.max = this.rounded(max);
if(unique.length > 0 || resident.length > 0){
this.isDataAvailable = true;
}
}
this.isLoading = false;
})
}
}
}
|
import SwiftUI
struct THSubscriptionPage: View {
var body: some View {
AsyncContentView {
return try await THRequests.loadSubscriptions()
} content: { subscriptions in
SubscriptionContent(subscriptions)
}
}
}
fileprivate struct SubscriptionContent: View {
@ObservedObject private var appModel = THModel.shared
@State private var subscriptions: [THHole]
@State private var showAlert = false
@State private var deleteError = ""
init(_ subscriptions: [THHole]) {
self._subscriptions = State(initialValue: subscriptions)
}
private func unsubscribe(_ hole: THHole) {
Task { @MainActor in
do {
try await appModel.deleteSubscription(hole.id)
if let idx = subscriptions.firstIndex(of: hole) {
subscriptions.remove(at: idx)
}
} catch {
deleteError = error.localizedDescription
showAlert = true
}
}
}
var body: some View {
Group {
if subscriptions.isEmpty {
Text("Empty Subscription List")
.foregroundColor(.secondary)
} else {
THBackgroundList {
ForEach(subscriptions) { hole in
THHoleView(hole: hole)
.swipeActions {
Button(role: .destructive) {
unsubscribe(hole)
} label: {
Image(systemName: "trash")
}
}
}
.alert("Remove Subscription Error", isPresented: $showAlert) {
} message: {
Text(deleteError)
}
}
}
}
.navigationTitle("Subscription List")
}
}
|
type ProductsListProps = { products: Products }
export function ProductsList({products}: ProductsListProps) {
let results = <ProductsListEmpty></ProductsListEmpty>;
const stylesColumnText = "p-2 text-left";
const stylesColumnNumber = "p-2 text-right";
if (products?.length) {
results = <div className="rounded-xl border-gray-200 border bg-white p-4">
<table className="w-full">
<thead>
<tr className="border-b-2 border-black uppercase text-sm">
<th className={stylesColumnText}>Product</th>
<th className={stylesColumnText}>Dimension A</th>
<th className={stylesColumnText}>Dimension B</th>
<th className={stylesColumnText}>Dimension C</th>
<th className={stylesColumnNumber}>Cost</th>
<th className={stylesColumnNumber}>MSRP</th>
<th className={stylesColumnNumber}>Margin</th>
</tr>
</thead>
<tbody>
{products.map((product) => (
<tr key={product.name}>
<td className={stylesColumnText}>{product.name}</td>
<td className={stylesColumnText}>{product.dimensionA}</td>
<td className={stylesColumnText}>{product.dimensionB}</td>
<td className={stylesColumnText}>{product.dimensionC}</td>
<td className={stylesColumnNumber}>${product.cost}</td>
<td className={stylesColumnNumber}>${product.msrp}</td>
<td className={stylesColumnNumber}>{Math.round(product.margin*100)}%</td>
</tr>
))}
<tr></tr>
</tbody>
</table>
</div>
}
return results;
}
export function ProductsListEmpty() {
return (
<div className="min-h-full rounded-xl border-gray-200 border bg-white p-4 flex flex-col justify-center items-center">
<a href="/products" className="[&>p]:hover:underline text-gray-200">
<h2 className="text-center font-bold text-2xl text-gray-200">No Products Found</h2>
<p className="text-center text-gray-200 mb-8">Try searching again or clear the search</p>
</a>
</div>
);
}
|
import jwt from "jsonwebtoken";
import { secret } from "../constants";
/**
* Encrypts a given string using a simple encryption algorithm.
*
* @param str - The string to be encrypted.
*
* @returns {string} - The encrypted string.
*/
export function encrypt(str: string): string {
let encryptedStr = "";
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
encryptedStr += String.fromCharCode(charCode + 1);
}
return encryptedStr;
}
/**
* Decrypts a given encrypted string using a simple decryption algorithm.
*
* @param encryptedStr - The encrypted string to be decrypted.
*
* @returns {string} - The decrypted string.
*/
export function decrypt(encryptedStr: string): string {
let decryptedStr = "";
for (let i = 0; i < encryptedStr.length; i++) {
let charCode = encryptedStr.charCodeAt(i);
decryptedStr += String.fromCharCode(charCode - 1);
}
return decryptedStr;
}
/**
* validateToken: A function to validate a JWT token.
*
* @param token - The JWT token to be validated.
*
* @returns {boolean} - Returns true if the token is valid, false otherwise.
*/
export function validateToken(token?: string): boolean {
try {
const key = decrypt(secret);
if (!token) {
return false;
}
const valid = jwt.verify(token, key);
return true;
} catch (error) {
console.log(error);
return false;
}
}
/**
* Generates a JWT token
*
* @returns token - JWT token
*/
export function generateToken(): string {
return jwt.sign({ user: "123", name: "Kapil Patil" }, decrypt(secret), {
expiresIn: "1h",
});
}
|
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\CategoryResource\Pages;
use App\Filament\Resources\CategoryResource\RelationManagers;
use App\Models\Category;
use Filament\Forms;
use Filament\Forms\Components\Card;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Form;
use Filament\Resources\Resource;
use Filament\Resources\Table;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
class CategoryResource extends Resource
{
protected static ?string $model = Category::class;
protected static ?string $navigationIcon = 'heroicon-o-view-grid';
protected static ?string $modelLabel = 'Question Categories';
protected static ?int $navigationSort = 2;
public static function form(Form $form): Form
{
return $form
->schema([
Card::make()
->schema([
TextInput::make('category_name')->unique(),
])
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('category_name')->sortable()->searchable(),
TextColumn::make('created_at'),
])
->filters([
//
])
->actions([
Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\DeleteBulkAction::make(),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListCategories::route('/'),
'create' => Pages\CreateCategory::route('/create'),
'view' => Pages\ViewCategory::route('/{record}'),
'edit' => Pages\EditCategory::route('/{record}/edit'),
];
}
}
|
import React from "react";
import { memo } from "react";
import { Link } from "react-router-dom";
const Item = ({ image, title, price, id, stock }) => {
const urlDetails = `./item/${id}`;
return (
<div className="card-container">
<header className="image-header">
<img className="image-main" src={image} />
<h1>{title}</h1>
<h2 className="tittle-card">{id}</h2>
<p className="eth">${price}</p>
<div>stock: {stock} </div>
<Link to={urlDetails}>
<button className="boton btn btn-warning">Ver Detalle</button>
</Link>
</header>
</div>
);
};
export default memo(Item);
|
/*
* Licensed to The OpenNMS Group, Inc (TOG) under one or more
* contributor license agreements. See the LICENSE.md file
* distributed with this work for additional information
* regarding copyright ownership.
*
* TOG licenses this file to You under the GNU Affero General
* Public License Version 3 (the "License") or (at your option)
* any later version. You may not use this file except in
* compliance with the License. You may obtain a copy of the
* License at:
*
* https://www.gnu.org/licenses/agpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
/**
* @author Alejandro Galue <agalue@opennms.org>
* @copyright 2014 The OpenNMS Group, Inc.
*/
'use strict';
const angular = require('angular-js');
require('angular-mocks');
require('../../../../../src/main/assets/js/apps/onms-requisitions/requisitions');
const OnmsDateFormatter = require('../../../../../src/main/assets/js/apps/onms-date-formatter');
var scope, $q, controllerFactory, dateFormatterService, mockModalInstance, mockRequisitionsService = {}, asset = { key: 'admin', value: 'agalue' };
function createController() {
return controllerFactory('AssetController', {
$scope: scope,
$uibModalInstance: mockModalInstance,
DateFormatterService: dateFormatterService,
RequisitionsService: mockRequisitionsService,
asset: asset,
assetsBlackList: []
});
}
beforeEach(function() {
window._onmsDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ssxxx";
window._onmsZoneId = 'America/New_York';
window._onmsFormatter = new OnmsDateFormatter();
});
beforeEach(angular.mock.module('onms-requisitions', function($provide) {
$provide.value('$log', console);
}));
beforeEach(angular.mock.inject(function($rootScope, $controller, $interval, _$q_, DateFormatterService) {
scope = $rootScope.$new();
controllerFactory = $controller;
$q = _$q_;
dateFormatterService = DateFormatterService;
$interval.flush(200);
}));
beforeEach(function() {
mockRequisitionsService.getAvailableAssets = jasmine.createSpy('getAvailableAssets');
var assets = $q.defer();
assets.resolve(['address1','city','state','zip']);
mockRequisitionsService.getAvailableAssets.and.returnValue(assets.promise);
mockModalInstance = {
close: function(obj) { console.info(obj); },
dismiss: function(msg) { console.info(msg); }
};
});
test('Controller: AssetController: test controller', function() {
createController();
scope.$digest();
expect(scope.asset.value).toBe(asset.value);
expect(scope.assetFields.length).toBe(4);
expect(scope.assetFields[0]).toBe('address1');
expect(scope.getAvailableAssetFields()).toEqual(['address1','city','state','zip']);
scope.assetsBlackList.push('address1');
expect(scope.getAvailableAssetFields()).toEqual(['city','state','zip']);
});
|
import MyTask from './MyTasks';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import axios from 'axios';
import { fakeTask1, fakeTask2 } from '@utils/testDummy';
import useBindStore from '@store/zustand';
const mockNavigate = jest.fn();
jest.mock('react-router', () => ({
...jest.requireActual('react-router'),
Navigate: (props: any) => {
mockNavigate(props.to);
return null;
},
useNavigate: () => mockNavigate
}));
describe('<MyTask />', () => {
let AD: JSX.Element;
function createMockLocalStorage (storage: any): void {
const localStorageMock = (function () {
let store: any = storage;
return {
getItem: function (key: string) {
return store[key] ?? null;
},
setItem: function (key: string, value: string) {
store[key] = value.toString();
},
clear: function () {
store = {};
}
};
})();
Object.defineProperty(window, 'localStorage', {
value: localStorageMock
});
}
beforeAll(() => {
AD = <MyTask />;
global.matchMedia = global.matchMedia ?? function () {
return {
addListener: jest.fn(),
removeListener: jest.fn()
};
};
});
it('should render my task', async () => {
createMockLocalStorage({ userId: 1 });
axios.get = jest.fn().mockResolvedValue({ data: [fakeTask1, fakeTask2] });
render(AD);
await waitFor(() => { expect(useBindStore.getState().userTasks).toEqual([fakeTask1, fakeTask2]); });
});
it('should handle task click', async () => {
createMockLocalStorage({ userId: 1 });
axios.get = jest.fn().mockResolvedValue({ data: [fakeTask1, fakeTask2] });
render(AD);
await waitFor(() => { expect(useBindStore.getState().userTasks).toEqual([fakeTask1, fakeTask2]); });
const tab = screen.getAllByRole('tab')[1];
fireEvent.click(tab);
const task = screen.getByRole('listitem');
fireEvent.click(task);
});
it('should handle userId null', async () => {
localStorage.clear();
render(AD);
});
});
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Event do
describe 'Default factory' do
it 'is valid' do
expect(build(:event)).to be_valid
end
end
describe 'associations' do
subject(:event) { build(:event) }
it { is_expected.to belong_to(:project) }
it { is_expected.to have_many(:attendances).dependent(:destroy) }
it { is_expected.to have_many(:attendees).through(:attendances) }
it { is_expected.to have_many(:event_files).dependent(:destroy) }
it { is_expected.to have_many(:text_images).dependent(:destroy) }
end
describe 'description sanitizer' do
it 'sanitizes script tags in the description' do
event = create(:event, description_multiloc: {
'en' => '<p>Test</p><script>This should be removed!</script>'
})
expect(event.description_multiloc).to eq({ 'en' => '<p>Test</p>This should be removed!' })
end
it 'retains paragraphs and line breaks in the description' do
event = create(:event, description_multiloc: {
'en' => '<p>Test<br><br>One<br>Two</p><p>Three</p>'
})
expect(event.description_multiloc).to eq({ 'en' => '<p>Test<br><br>One<br>Two</p><p>Three</p>' })
end
end
describe 'timing validation' do
it 'succeeds when start_at and end_at are equal' do
event = build(:event)
event.end_at = event.start_at
expect(event).to be_valid
end
it 'fails when end_at is before start_at' do
event = build(:event)
event.end_at = event.start_at - 1.minute
expect(event).to be_invalid
end
end
describe 'online_link' do
it 'succeeds when online link is a valid url' do
event = build(:event)
event.online_link = 'https://www.example.com'
expect(event).to be_valid
end
it 'fails when online link is not a valid url' do
event = build(:event)
event.online_link = 'not valid url'
expect(event).to be_invalid
end
end
describe 'attendees_count' do
let(:event) { create(:event) }
it 'is incremented when an attendance is created' do
expect { create(:event_attendance, event: event) }
.to change { event.reload.attendees_count }.by(1)
end
it 'is decremented when an attendance is destroyed' do
attendance = create(:event_attendance, event: event)
expect { attendance.destroy }
.to change { event.reload.attendees_count }.by(-1)
end
end
end
|
package pl.jawegiel.rickandmortyapp.presenter
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import pl.jawegiel.rickandmortyapp.interfaces.ListItemMVPContract
import pl.jawegiel.rickandmortyapp.model.AdditionalData
import pl.jawegiel.rickandmortyapp.model.RickAndMortyData
// @formatter:off
class PresenterListItem(private val view: ListItemMVPContract.View, private val restModel: ListItemMVPContract.Model) : ListItemMVPContract.Presenter {
override fun makeACall(id: Int) {
restModel.fetchResponse(this, id)
}
override fun loadItems(id: Int, isOnline: Boolean) {
if (isOnline) {
makeACall(id)
}
}
override fun processData(isArgsExist: Boolean, isOnline: Boolean) {
if (isArgsExist) {
view.setBasicValuesToViews()
loadItems(view.getItemPosition(), isOnline)
}
}
override fun passErrorResponseMessageToView(errorResponse: String) {
view.showErrorResponseToast(errorResponse)
}
override fun passResponseToView(rickAndMortyData: RickAndMortyData?) {
view.assignResponse(rickAndMortyData)
}
override fun processRawJson(rawJson: String): RickAndMortyData {
val rootObj = JsonParser().parse(rawJson).asJsonObject
val rootKeys = rootObj.keySet()
var id = 0
var image = ""
var name = ""
var status = ""
var species = ""
var jsonObj: JsonObject
var originName = ""
var originUrl = ""
var locationName = ""
var locationUrl = ""
var created = ""
for (key in rootKeys) {
when (key) {
"id" -> id = rootObj.get(key).asInt
"image" -> image = rootObj.get(key).asString
"name" -> name = rootObj.get(key).asString
"status" -> status = rootObj.get(key).asString
"species" -> species = rootObj.get(key).asString
"origin" -> {
jsonObj = rootObj.get(key).asJsonObject
originName = jsonObj.get("name").asString
originUrl = jsonObj.get("url").asString
}
"location" -> {
jsonObj = rootObj.get(key).asJsonObject
locationName = jsonObj.get("name").asString
locationUrl = jsonObj.get("url").asString
}
"created" -> created = rootObj.get(key).asString
}
}
return RickAndMortyData(id, image, name, status, AdditionalData(species, originName, originUrl, locationName, locationUrl, created))
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="header">
<a href="#" class="logo">Portfolio.</a>
<nav class="navbar">
<a href="#home" class="active">Home</a>
<a href="#about">About</a>
<a href="#services">Sevices</a>
<a href="#portfolio">Portfolio</a>
<a href="#contact">Contact</a>
</nav>
<div class='bx bx-moon' id="darkMode-icon"></i> </div>
<div class="bx bx-menu" id="menu-icon"></div>
</header>
<section class="home" id="home">
<div class="home-content">
<h3>Hello, I am</h3>
<h1> Zeyad Wael</h1>
<p> Junior Computer Science at Nile University. I am intrested in Web development and Problem solving </p>
<div class="social-media">
<a href="https://www.facebook.com/"> <i class='bx bxl-facebook'> </i> </a>
<a href="https://twitter.com/home"> <i class='bx bxl-twitter'> </i> </a>
<a href="https://www.instagram.com/"> <i class='bx bxl-instagram-alt'> </i> </a>
<a href="https://www.linkedin.com/in/zeyad-elghadban-964a98203/"> <i class='bx bxl-linkedin'></i> </a>
</div>
<a href="https://drive.google.com/file/d/1GcfjJKjhlKEDcue_9DAB9-qILvsK_Gg2/view?usp=drive_link"
class="btn">Download CV</a>
</div>
<div class="profession-container">
<div class="profession-box">
<div class="profession" style="--i:0;">
<i class='bx bx-code-alt'></i>
<h3> Web Developer </h3>
</div>
<div class="profession" style="--i:1;">
<i class='bx bx-code-curly'></i>
<h3> Problem Solver </h3>
</div>
<div class="profession" style="--i:2;">
<i class='bx bx-video'></i>
<h3> video editor </h3>
</div>
<div class="profession" style="--i:3;">
<i class='bx bxs-camera'></i>
<h3> Photographer </h3>
</div>
<div class="circle"></div>
</div>
<div class="overlay"></div>
</div>
<div class="home-img">
<img src="me4.png" alt="">
</div>
</section>
<section class="about" id="about">
<div class="about-img">
<img src="me4pt2.png" alt="">
</div>
<div class="about-content">
<h2 class="heading">About <span>Me</span></h2>
<h3>Hi, I'm here to tell you about myself</h3>
<p> I am a Junior Student studying Bachelor of Computer Science at Nile University, I am passionate about
using Modern Technology to solve complex Coding problems, create Creative designs, and make a positive
impact on the world.
I have worked with (CSS-HTML-JS) during the Meta course. I gained from it a good set of skills about how
to Design, Create, and Style simple websites. Also, gained skills in how to connect a live server and
how to update it using Version Control to edit my website which gave me an overall skill in front-end
development.
I'm aiming to improve my skills in problem-solving as I have been in touch with several Coding
languages. I took a C++ Internship at ( orange Labs ) and Became part of an ECPC problem-solving group
which gained from them how to solve modern coding problems in a much easier, faster, and simpler way.
I understand how important and effective working with a team and during college gained leadership skills
and Improved both communication and presentation skills by being the team lead of Projects at Nile University
</p>
<a href="#" class="btn">Read More</a>
</div>
</section>
<section class="services" id="services">
<h2 class="heading">My <span>Skills</span></h2>
<div class="services-container">
<div class="services-box">
<i class='bx bx-code-alt'></i>
<h3>Web Development</h3>
<p>I can easily design a webage after gaining a solid set of skills after taking the meta (front end
course) and ready to improve my skills even further</p>
<a href="#" class="btn">Read More</a>
</div>
<div class="services-box">
<i class='bx bx-code-curly'></i>
<h3>Problem Solving</h3>
<p>Got a good skill in programming and problem solving as I made several projects using c++ and particatped in the ECPC
Egyptian coding contest and now I am learning more about java</p>
<a href="#" class="btn">Read More</a>
</div>
<div class="services-box">
<i class='bx bx-video'></i>
<h3>Video Editing</h3>
<p>It is a new skill that I recently developed in the past 2 years and made a few projects about editing a few movies and series and willing to improve it in the future </p>
<a href="#" class="btn">Read More</a>
</div>
</div>
</section>
<section class="portfolio" id="portfolio">
<h2 class="heading">Latest <span>Project</span></h2>
<div class="portfolio-container">
<div class="portfolio-box">
<img src="portfolio1.jpg" alt="">
<div class="portfolio-layer">
<h4>Web Design</h4>
<p> A cinema booking website which is done by me and my team using HTML-CSS-JAVASCRIPT</p>
<a href="#"><i class="bx bx-link-external"></i></a>
</div>
</div>
<div class="portfolio-box">
<img src="portfolio2.jpg" alt="">
<div class="portfolio-layer">
<h4>Programming</h4>
<p>We made a car reservation system uisng (c++) as a language </p>
<a href="#"><i class="bx bx-link-external"></i></a>
</div>
</div>
<div class="portfolio-box">
<img src="portfolio3.jpg" alt="">
<div class="portfolio-layer">
<h4>Photography</h4>
<p>Fascinating pictures from my gallery that was taken by me from 6years ago until now</p>
<a href="#"><i class="bx bx-link-external"></i></a>
</div>
</div>
<div class="portfolio-box">
<img src="portfolio4.jpg" alt="">
<div class="portfolio-layer">
<h4>Flutter</h4>
<p>Made a fully functional Hotel reservation system with my team using flutter as a language</p>
<a href="#"><i class="bx bx-link-external"></i></a>
</div>
</div>
<div class="portfolio-box">
<img src="portfolio5.jpg" alt="">
<div class="portfolio-layer">
<h4>Logic Design project</h4>
<p>Made a automatic door using proteus and Tinkercad so it open freely if key matches the password</p>
<a href="#"><i class="bx bx-link-external"></i></a>
</div>
</div>
<div class="portfolio-box">
<img src="portfolio6.jpg" alt="">
<div class="portfolio-layer">
<h4>Data Analysis</h4>
<p>Movie Recommender made by me and my team to recommend movies acrroding certain category</p>
<a href="#"><i class="bx bx-link-external"></i></a>
</div>
</div>
</div>
</section>
<section class="contact" id="contact">
<h2 class="heading">Contact <span>Me</span></h2>
<form action="#">
<div class="input-box">
<input type="text" placeholder="Full Name">
<input type="email" placeholder="Email Address">
</div>
<div class="input-box">
<input type="number" placeholder="Mobile Number">
<input type="text" placeholder="Email Subject">
</div>
<textarea name="" id="" cols="30" rows="10" placeholder="Your Messages"></textarea>
<input type="submit" value="Send Message" class="btn">
</form>
</section>
<footer class="footer">
<div class="footer-text">
<p> Copyrights © 2024 TiGeR | All Rights Reserved </p>
</div>
<div class="footer-iconTop">
<a href="#home"> <i class='bx bx-arrow-to-top'> </i> </a>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.js"></script>
<script src="https://unpkg.com/scrollreveal"></script>
<script src="JavaD.js"> </script>
</body>
</html>
|
use std::time::Duration;
use lmntalc::util::Pos;
use reqwest::ClientBuilder;
use semver::Version;
use tower_lsp::lsp_types::Position;
pub fn to_position(pos: Pos) -> Position {
Position {
line: pos.line,
character: pos.column,
}
}
pub fn span_to_range(span: lmntalc::util::Span) -> tower_lsp::lsp_types::Range {
tower_lsp::lsp_types::Range {
start: to_position(span.low()),
end: to_position(span.high()),
}
}
pub async fn check_update() -> Option<Version> {
let client = ClientBuilder::new()
.user_agent(concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION")
))
.timeout(Duration::from_secs(2))
.build();
if let Ok(client) = client {
let response = client
.get("https://crates.io/api/v1/crates/lmntal-language-server")
.send()
.await;
if let Ok(response) = response {
return response
.json::<serde_json::Value>()
.await
.map_or(None, |json| {
let version = json["crate"]["max_version"].as_str()?;
let version = Version::parse(version).ok()?;
let current = Version::parse(env!("CARGO_PKG_VERSION")).ok()?;
if version > current {
Some(version)
} else {
None
}
});
}
}
None
}
|
import type { Meta, StoryObj } from '@storybook/react';
import { userEvent, within } from '@storybook/test';
import { EditableTextField } from '@exsui/ui';
const meta: Meta<typeof EditableTextField> = {
component: EditableTextField,
tags: ['autodocs'],
argTypes: {
initialValue: {
control: 'text',
description: 'The value of the text field',
},
onSave: {
action: 'changed',
description: 'Function to call when the text field changes',
},
},
decorators: [
(Story) => (
<div className="p-4">
<Story />
</div>
),
],
parameters: {
controls: { expanded: true },
},
title: 'Input/EditableTextField',
};
export default meta;
type Story = StoryObj<typeof EditableTextField>;
export const Primary: Story = {
play: async ({ canvasElement }) => {
const textField = within(canvasElement).getByRole('textbox');
userEvent.type(textField, 'New text');
},
render: (props) => <EditableTextField {...props} />,
args: {
initialValue: 'Initial value',
onSave: (newValue) => console.log('New value:', newValue),
},
};
|
@extends('admin.layouts.app')
@section('title', 'Create Category')
@section('content')
<div class="card">
<h1>Tạo danh mục</h1>
<div>
<form action="{{route('categories.store')}}" method="post">
@csrf
<div class="input-group input-group-static mb-4">
<label for="">Tên</label>
<input type="text" value="{{ old('name') }}" name="name" class="form-control">
@error('name')
<span class="text-danger">{{$message}}</span>
@enderror
</div>
<div class="input-group input-group-static mb4">
<label name="group" class="ms-0">Danh mục cha</label>
<select name="parent_id" class="form-control">
<option value="">Chọn danh mục cha</option>
@foreach ($parentCategories as $item)
<option value="{{ $item->id }}" {{ old('parent_id') == $item->id ? 'selected' : ''}}>
{{ $item->name }}</option>
@endforeach
</select>
@error('parent_ids')
<span class="text-danger">{{$message}}</span>
@enderror
</div>
<button type="submit" class="btn btn-submit btn-primary">Lưu lại</button>
</form>
</div>
</div>
@endsection
|
/******************************************************************************
* Copyright (C) 2016-2017 IMMS GmbH, Thomas Elste <thomas.elste@imms.de>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
******************************************************************************/
#define _GNU_SOURCE
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <inttypes.h>
#include <sched.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/mman.h>
#include <cyclicping.h>
#include <tcp.h>
#include <udp.h>
#include <uart.h>
#include <stsn.h>
#include <ftrace.h>
#ifdef HAVE_NETMAP
#include <netmap.h>
#endif
int run=1;
int abort_fd=0, latency_target_fd;
static struct cyclicping_module modules[] = {
{ "udp", udp_init, udp_client, udp_server, udp_deinit,
udp_usage },
{ "tcp", tcp_init, tcp_client, tcp_server, tcp_deinit,
tcp_usage },
{ "uart", uart_init, uart_client, uart_server, uart_deinit,
uart_usage },
{ "stsn", stsn_init, stsn_client, stsn_server, stsn_deinit,
stsn_usage },
#ifdef HAVE_NETMAP
{ "netmap", netmap_init, netmap_client, netmap_server, netmap_deinit,
netmap_usage },
#endif
{ NULL },
};
/* borrowed from cyclictest */
void set_latency_target(void)
{
struct stat s;
int err;
uint32_t latency_target_value=0;
err = stat("/dev/cpu_dma_latency", &s);
if (err == -1) {
return;
}
latency_target_fd = open("/dev/cpu_dma_latency", O_RDWR);
if (latency_target_fd == -1) {
perror("WARN: open /dev/cpu_dma_latency");
return;
}
err = write(latency_target_fd, &latency_target_value,
sizeof(latency_target_value));
if (err < 1) {
perror("# error setting cpu_dma_latency");
close(latency_target_fd);
return;
}
}
/**
* Waits until next packet is due. Called by interface module in client mode.
*
* \param cfg Cyclicping config data.
* \param tfrom Last packet time stamp.
* \return 0 on success.
*/
int client_wait(struct cyclicping_cfg *cfg, struct timespec tfrom)
{
/* count down loops */
if(cfg->opts.number) {
cfg->opts.number--;
if(!cfg->opts.number) {
run=0;
return 0;
}
}
/* wait till start of next interval */
tfrom.tv_nsec+=cfg->opts.interval*1000;
while(tfrom.tv_nsec>=NSEC_PER_SEC) {
tfrom.tv_nsec-=NSEC_PER_SEC;
tfrom.tv_sec++;
}
clock_nanosleep(cfg->opts.clock, TIMER_ABSTIME, &tfrom, NULL);
return 0;
}
/**
* Runs the cyclicping main loop by either calling the server or client
* run functions of the interface module.
*
* \param cfg Cyclicping config data.
* \return 0 on success.
*/
int run_cyclicping(struct cyclicping_cfg *cfg)
{
int i, ret=0;
char *modargv[MAX_MOD_ARG];
char *saveptr=NULL;
/* get args for interface module */
modargv[0]=strtok_r(cfg->opts.opt_mod, ":", &saveptr);
for(i=1; i<MAX_MOD_ARG; i++) {
modargv[i]=strtok_r(NULL, ":", &saveptr);
if(modargv[i]==NULL)
break;
}
if(cfg->current_mod->init(cfg, modargv, i))
return 1;
gettimeofday(&cfg->test_start, NULL);
if(cfg->opts.ftrace)
start_ftrace();
while(run) {
if(cfg->opts.server)
ret=cfg->current_mod->run_server(cfg);
else
ret=cfg->current_mod->run_client(cfg);
if(ret)
break;
}
if(cfg->opts.ftrace)
stop_ftrace();
gettimeofday(&cfg->test_end, NULL);
if(abort_fd)
close(abort_fd);
if(cfg->current_mod->deinit)
cfg->current_mod->deinit(cfg);
return ret;
}
/**
* Get histogram-, packet- and payload buffers.
*
* \param cfg Cyclicping config data.
*/
void allocate_buffers(struct cyclicping_cfg *cfg)
{
int i;
/* histogram buffers for send, recv, and roundtrip */
if(cfg->opts.histogram) {
for(i=0; i<=STAT_ALL; i++) {
cfg->stat[i].histogram_data=(uint32_t*)malloc(
cfg->opts.histogram*sizeof(uint32_t));
if(cfg->stat[i].histogram_data==NULL) {
perror("failed to allocate histogram memory\n");
exit(1);
}
memset(cfg->stat[i].histogram_data, 0,
cfg->opts.histogram*sizeof(uint32_t));
}
}
for(i=0; i<=STAT_ALL; i++) {
cfg->stat[i].min=UINT32_MAX;
}
cfg->recv_packet=(char*)malloc(cfg->opts.length);
if(cfg->recv_packet==NULL) {
perror("failed to allocate receive memory\n");
exit(1);
}
cfg->send_packet=(char*)malloc(cfg->opts.length);
if(cfg->send_packet==NULL) {
perror("failed to allocate send memory\n");
exit(1);
}
/* data for each packet if packet dump was requested */
if(cfg->opts.dumpfile) {
cfg->dump=(struct pdump*)malloc(
cfg->opts.number*sizeof(struct pdump));
if(cfg->dump==NULL) {
perror("failed to allocate dump memory\n");
exit(1);
}
}
}
/**
* Set CPU affinity.
*
* \param cfg Cyclicping config data.
*/
void set_affinity(struct cyclicping_cfg *cfg)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cfg->opts.affinity, &set);
if(sched_setaffinity(getpid(), sizeof(set), &set) == -1) {
perror("failed to set affinity");
exit(1);
}
}
/**
* Free all buffers we allocated.
*
* \param cfg Cyclicping config data.
*/
void cleanup_cfg(struct cyclicping_cfg *cfg)
{
int i;
if(cfg->send_packet)
free(cfg->send_packet);
if(cfg->recv_packet)
free(cfg->recv_packet);
if(cfg->opts.dumpfile)
free(cfg->opts.dumpfile);
for(i=0; i<=STAT_ALL; i++) {
if(cfg->stat[i].histogram_data) {
free(cfg->stat[i].histogram_data);
}
}
if(cfg->dump) {
free(cfg->dump);
}
}
/**
* Handler for SIGINT and SIGTERM.
*
* \param signum Signal number.
*/
void term_handler(int signum)
{
run=0;
/* An interface module might wait on a file descriptor. Close it to
* make the module return. */
if(abort_fd) {
close(abort_fd);
abort_fd=0;
}
}
int main(int argc, char *argv[])
{
struct sigaction new_action;
struct cyclicping_cfg cfg;
struct sched_param param;
int ret;
new_action.sa_handler = term_handler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction (SIGINT, &new_action, NULL);
sigaction (SIGTERM, &new_action, NULL);
memset(&cfg, 0, sizeof(struct cyclicping_cfg));
cfg.modules=modules;
parse_cfg(argc, argv, &cfg);
if(cfg.opts.mlock) {
if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
perror("mlockall failed");
return -1;
}
}
if(cfg.opts.priority) {
param.sched_priority=cfg.opts.priority;
if(sched_setscheduler(0, SCHED_FIFO, ¶m) == -1) {
perror("sched_setscheduler failed");
return -1;
}
}
set_latency_target();
if(cfg.opts.opt_affinity)
set_affinity(&cfg);
if(cfg.opts.ftrace) {
if(setup_ftrace()) {
return -1;
}
}
allocate_buffers(&cfg);
ret=run_cyclicping(&cfg);
if(!cfg.opts.quiet)
printf("\n\n\n");
if(!ret) {
if(cfg.opts.histogram) {
if(cfg.opts.gnuplot)
print_gnuplot_histogram(&cfg, argc, argv);
else
print_histogram(&cfg, argc, argv);
}
}
if(cfg.dump)
write_dump(&cfg);
if(cfg.opts.ftrace)
printf("trace available at: /sys/kernel/debug/tracing/trace\n");
cleanup_cfg(&cfg);
return ret;
}
|
import Loader from "components/attedance_system/common/Loader";
import React from "react";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";
import { useAuth } from "util/auth";
import { createAttendance, useAllAttendance } from "util/db";
import Link from 'next/link';
const AttendanceForm = ({ students, class_id }) => {
const { register, handleSubmit, errors, reset } = useForm();
const auth = useAuth();
const onSubmit = async (data) => {
const attendanceData = Object.keys(data).map((studentId) => {
const selectedStudent = students.find(
(student) => student.id === studentId
);
return {
student_id: studentId,
class_id: class_id,
teacher_id: auth.user.uid,
attendance: data[studentId],
college_rollno: selectedStudent.college_rollno,
};
});
console.log(attendanceData)
const successResults = [];
const errorResults = [];
for (const data of attendanceData) {
try {
const result = await createAttendance({
...data,
owner: auth.user.uid
});
successResults.push(result);
} catch (error) {
errorResults.push({ data, error });
}
}
if (successResults.length > 0) {
toast.success("Successfully Marked");
}
if (errorResults.length > 0) {
toast.error(
`Error marking attendance`
);
}
reset();
};
function formatDate(inputDate) {
let dateObj;
if (typeof inputDate === "string") {
dateObj = new Date(inputDate);
} else if (inputDate instanceof Date) {
dateObj = inputDate;
} else {
throw new Error("Invalid input date format");
}
const year = dateObj.getFullYear();
const month = String(dateObj.getMonth() + 1).padStart(2, "0");
const day = String(dateObj.getDate()).padStart(2, "0");
const formattedDate = `${year}-${month}-${day}`;
return formattedDate;
}
const { data: attendanceData } = useAllAttendance();
const CheckAttendance = attendanceData?.filter((i) => {
return (
i.class_id === class_id &&
formatDate(i.createdAt) === formatDate(new Date())
);
});
return (
<div className="h-screen">
{!students && <Loader />}
{students && (
<>
{CheckAttendance?.length > 0 &&
<div>
<h3 className="text-center text-red-800 my-4 animate-bounce">
*Today's attendance has already been taken*
</h3>
</div>
}
<div className="flex justify-center mt-3">
<Link href={`/attendance/${class_id}`}>
<button className='red-button text-xs'>Show attendance</button>
</Link>
</div>
<section className="m-3 w-[95%] lg:w-[80%] mx-auto">
<form className="" onSubmit={handleSubmit(onSubmit)}>
<div className="md:overflow-x-hidden overflow-x-scroll">
<table className=" w-[95%] lg:w-full mx-auto">
<thead>
<tr>
<th className="p-3 md:text-lg text-sm border-r-[1px] border-gray-200 bg-red-800 text-white">
No.
</th>
<th className="p-3 md:text-lg text-sm border-r-[1px] border-gray-200 bg-red-800 text-white">
Roll no.
</th>
<th className="p-3 md:text-lg text-sm border-r-[1px] border-gray-200 bg-red-800 text-white">
Uni Roll no.
</th>
<th className="p-3 md:text-lg text-sm border-r-[1px] border-gray-200 bg-red-800 text-white text-left">
Name
</th>
<th className="p-3 md:text-lg text-sm border-r-[1px] border-gray-200 bg-red-800 text-white text-center">
Attendance
</th>
<th className="p-3 md:text-lg text-sm bg-red-800 text-white">
Phone no.
</th>
</tr>
</thead>
<tbody>
{students
?.sort((a, b) => a.college_rollno - b.college_rollno)
?.map((student, index) => (
<tr
key={student.id}
className="border-t-[1px] border-red-300"
>
<td>
<div className="md:text-lg text-center text-sm font-semibold px-3 py-4">
{index + 1}.
</div>
</td>
<td>
<div className="md:text-lg text-center text-sm font-semibold px-3 py-4">
{student.college_rollno}
</div>
</td>
<td>
<div className="md:text-lg text-center text-sm font-semibold px-3 py-4">
{student.university_rollno}
</div>
</td>
<td>
<h2 className="md:text-lg text-sm text-red-700 font-semibold px-3 py-4">
{student.name}
</h2>
</td>
<td className="flex mt-1 justify-center py-4">
{errors.student?.id && (
<p className="mt-1 text-sm text-left text-red-600">
{errors.student?.id.message}
</p>
)}
<fieldset>
<div className="flex flex-col space-x-3">
<div className=" flex space-x-3">
<div className="flex items-center">
<label
className="mr-2 block text-sm font-medium leading-6 text-gray-900"
>
P
</label>
<input
ref={register({
required: "Required",
})}
defaultChecked={true}
value="Present"
name={student.id}
type="radio"
disabled={CheckAttendance?.length > 0 ? true : false}
className="h-4 w-4 border-gray-200 text-indigo-600 focus:ring-indigo-600"
/>
</div>
<div className="flex items-center">
<label
className="mr-2 block text-sm font-medium leading-6 text-gray-900"
>
A
</label>
<input
ref={register({
required: "Required",
})}
value="Absent"
name={student.id}
type="radio"
disabled={CheckAttendance?.length > 0 ? true : false}
className="h-4 w-4 border-gray-200 text-indigo-600 focus:ring-indigo-600"
/>
</div>
<div className="flex items-center">
<label
className="mr-2 block text-sm font-medium leading-6 text-gray-900"
>
L
</label>
<input
ref={register({
required: "Required",
})}
value="Leave"
name={student.id}
type="radio"
disabled={CheckAttendance?.length > 0 ? true : false}
className="h-4 w-4 border-gray-200 text-indigo-600 focus:ring-indigo-600"
/>
</div>
</div>
{errors.student?.id && (
<p className="mt-1 text-sm text-left text-red-600">
{errors.student?.id.message}
</p>
)}
</div>
</fieldset>
</td>
<td>
<h2 className="md:text-lg text-center text-sm text-red-700 font-semibold px-3 py-4">
{student.phone_number}
</h2>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="flex justify-end mt-6">
{CheckAttendance?.length > 0 ? (
<button className="red-button" disabled>
Already taken
</button>
) : (
<button className="red-button" type="submit">
Submit Attendance
</button>
)}
</div>
</form>
</section>
</>
)}
</div>
);
};
export default AttendanceForm;
|
import 'theme.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'models/my_theme_provider.dart';
import 'screens/home_screen.dart';
void main() {
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => MyThemeModel(),
child: Consumer<MyThemeModel>(
builder: (context, theme, child) => MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Analog Clock',
theme: themeData(context),
darkTheme: darkThemeData(context),
themeMode: theme.isLightTheme ? ThemeMode.light : ThemeMode.dark,
home: const HomeScreen(),
),
));
}
}
|
<div class="flex flex-col pt-12">
<div class="sm:mx-auto sm:w-full sm:max-w-md">
<h2 class="mt-6 text-center text-3xl leading-9 font-extrabold text-gray-900">
Log in to your account
</h2>
<p class="mt-2 text-center text-sm leading-5 text-gray-500 max-w">
Or
<a routerLink="/auth/register"
class="font-medium text-blue-600 hover:text-blue-500 focus:outline-none
focus:underline transition ease-in-out duration-150">
make a new account
</a>
</p>
</div>
<div class="sm:mx-auto sm:w-full sm:max-w-md">
<div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
<form [formGroup]="loginForm" (ngSubmit)="onLogin()">
<div>
<label for="username" class="block text-sm font-medium leading-5 text-gray-700">Username</label>
<div class="mt-1 flex-col rounded-md">
<input name="username" type="text" formControlName="username"
class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md
placeholder-gray-400 focus:outline-none focus:shadow-outline-blue focus:border-blue-300
transition duration-150 ease-in-out sm:text-sm sm:leading-5">
<span *ngIf="!username.valid && username.touched" class="text-red-600"> Username required </span>
</div>
</div>
<div class="mt-6">
<label for="password" class="block text-sm font-medium leading-5 text-gray-700">
Password
</label>
<div class="mt-1 rounded-md">
<input id="password" name="password" type="password" formControlName="password"
class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md
placeholder-gray-400 focus:outline-none focus:shadow-outline-blue
focus:border-blue-300 transition duration-150 ease-in-out sm:text-sm sm:leading-5">
<span *ngIf="!password.valid && password.touched" class="text-red-600"> Password required </span>
</div>
</div>
<span *ngIf="loginForm.hasError('notFound')" class="text-red-600"> Wrong username or password. </span>
<div class="mt-6">
<span class="block w-full rounded-md">
<button type="submit" (click)="submit = true"
class="w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium
rounded-md text-white bg-blue-600 hover:bg-blue-500 focus:outline-none
focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition
duration-150 ease-in-out">
Login
</button>
</span>
</div>
</form>
</div>
</div>
</div>
|
# Realtime Chat Application with SpringBoot and Angular
This is a real-time chat application with a client in the browser developed using Angular for the frontend and Spring Boot for the backend. The backend uses WebSocket (via Spring's WebSocket support) for real-time communication between users. It also integrates with MySQL to store user data and chat history. Users can register with their email, first name, and last name, and then initiate chats with other registered users. The application also supports viewing and deleting old chats and allows users to sign out.
### [LIVE PREVIEW](https://hassanmahfuj.github.io/chatapp-live)
## Screenshots




## Features
- User Registration:
- New users can register with their email address, first name, and last name.
- Login:
- Users can log in using their registered email address.
- Real-time Chat:
- Users can start real-time chats with other registered users. Chats are always one-on-one.
- Chat History:
- Users can view a list of old chats (conversations) and delete them. Single message can also be deleted.
- Sign Out:
- Users can sign out from the application.
## Installation Guide
### Clone the Project
1. Open a terminal window.
2. Navigate to the directory where you want to store the project.
3. Clone the project repository using the following command:
```
https://github.com/hassanmahfuj/Realtime-Chat-Application-with-SpringBoot-and-Angular.git
```
### Setting up MySQL Database (Database)
1. Install MySQL if not already installed.
2. Create a new database for the chat application:
```sql
CREATE DATABASE chat_app;
```
### Setting up Spring Boot (Backend)
1. Open the `chatapp-backend` project in IntelliJ IDEA.
2. Update the database configuration in the Spring Boot backend `src/main/resources/application.properties`:
```
spring.datasource.url=jdbc:mysql://localhost:3306/chat_app
spring.datasource.username=yourusername
spring.datasource.password=yourpassword
```
### Setting up Angular (Frontend)
1. Make sure you have Node.js and npm installed on your system. If not, install them.
2. Navigate to the frontend directory:
```
cd chatapp-frontend
```
3. Install the required packages:
```
npm install
```
## Running the Application
1. Open IntelliJ IDEA and run the Spring Boot application by pressing `Shift` + `F10` or the `Run` button.
2. Start the Angular frontend by running the following command in the chatapp-frontend directory:
```
ng serve
```
3. Access the application in your web browser at http://localhost:4200.
4. You can now register, log in, and start chatting in real-time!
## Contact
If you have any questions or encounter issues, feel free to contact at humahfuj@example.com.
### Enjoy chatting!
|
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:responsive_adaptive/core/utils/app_styles.dart';
import 'package:responsive_adaptive/models/drawer_item_model.dart';
class DrawerItem extends StatelessWidget {
const DrawerItem({
super.key,
required this.drawerItemInfo,
this.isActive = false,
});
final DrawerIteModel drawerItemInfo;
final bool isActive;
@override
Widget build(BuildContext context) {
return ListTile(
leading: SvgPicture.asset(drawerItemInfo.image),
title: FittedBox(
// Used FittedBox to avoid constrains on the Text widget
// Used BoxFit.scaleDown to make Text widget scale down to fit the constraints
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(
drawerItemInfo.title,
style: isActive
? AppStyles.styleBold16(context)
: AppStyles.styleMedium16(context),
),
),
trailing: isActive
? Container(
width: 3.27,
color: const Color(0xff4eb7f2),
)
: null,
);
}
}
|
let imageDetails, imagePixels, imageBase64;
const circleRadius = 256; // threshold chosen as the half of 512 px.
function testImage(){
const userInput = document.getElementById('imageInput');
// console.log(userInput);
// If the user upload files, the first one is stored in file variable.
if (userInput.files && userInput.files[0]) {
imageDetails = userInput.files[0];
displayImage(imageDetails);
}
}
function displayImage(imageDetails){
// Create a FileReader object
const reader = new FileReader();
reader.readAsDataURL(imageDetails);
// Once the file is read, file data are given as a source to the displayedImage balise
// to display the image in the UI.
reader.onload = function (e) {
imageBase64 = e.target.result;
document.getElementById('displayedImage').src = imageBase64;
checkImageDimensions(imageDetails);
};
}
function checkImageDimensions (imageDetails){
// Create an image object with the URL correponding to the file as a source.
const img = new Image();
img.src = URL.createObjectURL(imageDetails);
// Once the image is created, we fetch the width and the weight to create an alert
// in case they are different from 512*512.
img.onload = function() {
var width = img.width;
var height = img.height;
if (width != 512 || height != 512){
alert('Image dimensions should be 512*512');
}
checkNtpCircle(img);
};
}
function checkNtpCircle(img){
// Create a canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Draw the image on the canvas
ctx.drawImage(img, 0, 0, img.width, img.height);
// Get the image data (pixels information)
const canvasImgDetails = ctx.getImageData(0, 0, img.width, img.height);
imagePixels = canvasImgDetails.data;
const centerX = img.width / 2;
const centerY = img.height / 2;
let countNtpOut = 0;
const circleRadiusSquared = circleRadius * circleRadius;
// For each pixel :
// Check if it is transparent
// Compute its distance to center
for (let i = 0; i<imagePixels.length; i+=4){
if (imagePixels[i+3] !== 0) {
const x = (i/4) % img.width;
const y = Math.floor((i/4)/img.width);
const distanceToCenterSquared = Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2);
if (distanceToCenterSquared > circleRadiusSquared) {
alert("You have at least 1 non transparent pixel out of the limited circle for the badge.");
break;
}
}
}
detectColorMood();
}
/*
const nonTrasparentpixel = imagePixels[i+3] !== 0;
const x = (i/4) % img.width;
const y = Math.floor((i/4)/img.width);
const distanceToCenterSquared = Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2);
// If it is transparent and its distance to center > circle radius = 256 :
// update the count of nontransparent pixel.
if (nonTrasparentpixel && distanceToCenterSquared > circleRadiusSquared){
countNtpOut += 1;
}
}
*/
// Compute the % and display it in the alert
/*
const ntpOutPercent = ((countNtpOut / (imagePixels.length / 4)) * 100).toFixed(2);
if (countNtpOut > 0){
alert("You have " + ntpOutPercent + "% of non transparent pixel out of the limited circle for the badge.");
}
*/
// detectColorMood();
// }
function detectColorMood(){
let totalBrightness = 0;
let totalIntensity = 0;
let countNtPix = 0;
// Compute the lightness and intensity of the image taking into account only the non transparent pixel
for (let i=0; i < imagePixels.length; i+=4){
const transparency = imagePixels[i+3];
if(transparency !== 0){
// Each pixel has 4 values in data : red, green, blue and trasparency.
const red = imagePixels[i];
const green = imagePixels[i+1];
const blue = imagePixels[i+2];
const max = Math.max(red, green, blue);
const min = Math.min(red, green, blue);
const lightness = max / 255;
const intensity = (red + green + blue) / 3;
totalBrightness += lightness;
totalIntensity += intensity;
countNtPix += 1;
}
}
const averageBrightness = totalBrightness / countNtPix;
const averageIntensity = totalIntensity / countNtPix;
// If the image has an average intensity < 100 or an average brightness < 0.5 :
// it is considered as a "sad" image.
if (averageIntensity < 100 || averageBrightness < 0.5) {
alert("Your image is too sad for a badge ... Try something brighter !");
}
displayAvatar();
}
function displayAvatar(){
const img = new Image();
img.src = imageBase64;
// Creation of canvas with the dimension of the desired circle
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = circleRadius * 2;
canvas.height = circleRadius * 2;
// Create the circle on the canvas that will limit the drawing of the image.
ctx.beginPath();
ctx.arc(circleRadius, circleRadius,circleRadius,0, 2*Math.PI);
ctx.closePath();
ctx.clip();
// Draw the image on the circle canvas
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, circleRadius * 2, circleRadius * 2);
// Make the border brown and thick
ctx.strokeStyle = 'rgb(86,61,45)';
ctx.lineWidth = 20;
ctx.stroke();
// Display it on the UI
document.getElementById("displayedAvatar").src = canvas.toDataURL();
}
|
#include<iostream>
using namespace std;
int count = 0;
void lcs_bu(string x, string y, int **c, char **b)
{
int m, n;
m = x.length() + 1;
n = y.length() + 1;
for(int i=0;i<n;i++)
{
c[0][i] = 0;
}
for(int i=0;i<m;i++)
{
c[i][0] = 0;
}
for(int i=1;i<m;i++) // x string row
{
for(int j=1;j<n;j++) // y string column
{
count++;
if(x[i-1] == y[j-1])
{
c[i][j] = c[i-1][j-1] + 1;
b[i][j] = '!';
}
else if(c[i-1][j] >= c[i][j-1])
{
c[i][j] = c[i-1][j];
b[i][j] = '^';
}
else
{
c[i][j] = c[i][j-1];
b[i][j] = '<';
}
}
}
}
void print_lcs(string x, char **b, int i, int j)
{
if((i==0) || (j==0))
{
return;
}
else if(b[i][j] == '!')
{
print_lcs(x, b, i-1, j-1);
cout<<x[i-1];
}
else if(b[i][j] == '^')
{
print_lcs(x, b, i-1, j);
}
else
{
print_lcs(x, b, i, j-1);
}
}
int main()
{
string x, y;
cout<<"enter string 1: ";
cin>>x;
cout<<"enter string 2: ";
cin>>y;
int **c = new int*[x.length() + 1];
char **b = new char*[x.length() + 1];
for(int i=0;i<=x.length();i++)
{
c[i] = new int[y.length() + 1];
b[i] = new char[y.length() + 1];
}
lcs_bu(x, y, c, b);
cout<<"the longest common subsequence is: "<<endl;
print_lcs(x, b, x.length(), y.length());
cout<<"\nthe count is: "<<count<<endl;
}
|
import React, { useState, useEffect } from "react";
import Layout from "../Layout/Layout";
import ProductItem from "../Components/ProductItem/ProductItem";
import { useDispatch, useSelector } from "react-redux";
import { fetchOneProduct } from "../Redux/slices/products";
import { saveScrollPosition } from "../Redux/slices/position";
import Loader from "../Components/Loader/Loader";
const ProductPage = () => {
const [scrollPosition, setScrollPosition] = useState(0);
useEffect(() => {
const handleScroll = () => {
setScrollPosition(window.scrollY);
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
useEffect(() => {
window.scrollTo(0, scrollPosition);
}, [scrollPosition]);
const dispatch = useDispatch();
const product = useSelector((state) => state.products.product);
useEffect(() => {
const currentURL = window.location.href;
const id = currentURL.split("/").pop();
dispatch(fetchOneProduct(id));
}, [dispatch]);
useEffect(() => {
return () => {
dispatch(
saveScrollPosition({ scrollX: window.scrollX, scrollY: window.scrollY })
);
};
}, [dispatch]);
const status = product.status;
return (
<Layout>
{status === "loading" && <Loader />}
{status === "loaded" && <ProductItem product={product} />}
</Layout>
);
};
export default ProductPage;
|
package com.robosoft.weatherapp.ui
import android.app.AlertDialog
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.robosoft.weatherapp.R
import com.robosoft.weatherapp.adapter.FavouritesScreenAdapter
import com.robosoft.weatherapp.database.WeatherDB
import com.robosoft.weatherapp.databinding.ActivityRecentSearchBinding
import com.robosoft.weatherapp.dataclass.RecyclerViewItems
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class RecentSearchActivity : AppCompatActivity() {
private lateinit var recentSearchBinding: ActivityRecentSearchBinding
private lateinit var recyclerView: RecyclerView
private lateinit var weatherDB: WeatherDB
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
recentSearchBinding = ActivityRecentSearchBinding.inflate(layoutInflater)
setContentView(recentSearchBinding.root)
val backImg = recentSearchBinding.backImg
backImg.setOnClickListener {
onBackPressed()
}
recentSearchBinding.searchIv.setOnClickListener {
val intent = Intent(this, SearchScreenActivity::class.java)
startActivityForResult(intent, 100)
}
recyclerView = recentSearchBinding.recyclerview
recyclerView.layoutManager = LinearLayoutManager(this)
val totalList = arrayListOf<RecyclerViewItems>()
weatherDB = WeatherDB.getDatabase((applicationContext ?: this))
GlobalScope.launch {
val a = weatherDB.weatherDetailsDao().getAllData()
for (i in a) {
totalList.add(
RecyclerViewItems(
i.city,
i.fav,
i.temperature,
i.climateText
)
)
}
if (totalList.isEmpty()) {
recentSearchBinding.noFavouritesLayout.visibility = View.VISIBLE
recentSearchBinding.favouritesLayout.visibility = View.GONE
} else recyclerView.adapter = FavouritesScreenAdapter(totalList)
}
recentSearchBinding.clearAllTv.setOnClickListener {
showAlertDialog(totalList)
}
}
private fun showAlertDialog(totalList: ArrayList<RecyclerViewItems>) {
val builder = AlertDialog.Builder(this)
//set message for alert dialog
builder.setMessage("Are you sure want to remove all the recent searches?")
builder.setIcon(android.R.drawable.ic_dialog_alert)
//performing positive action
builder.setPositiveButton("Yes") { _, _ ->
recentSearchBinding.noFavouritesLayout.visibility = View.VISIBLE
recentSearchBinding.favouritesLayout.visibility = View.GONE
totalList.clear()
}
//performing negative action
builder.setNegativeButton("No") { _, _ ->
}
// Create the AlertDialog
val alertDialog: AlertDialog = builder.create()
// Set other dialog properties
alertDialog.setCancelable(false)
alertDialog.show()
}
}
|
class It:
def __iter__(self):
self.val = 0
return self
def __next__(self):
if self.val <= 100:
temp = self.val
self.val = self.val+1
return temp
else:
raise StopIteration
inr = It()
ite_obj = iter(inr)
for i in ite_obj:
print(i)
"""
Generator
"""
def gen(n):
for i in range(0, n+1):
yield i
"""
Comparison between iterators and generators
In iterators, we need to make use of the interator protocol methods (iter() and next()) but generators are simpler as we only need to use a function.
Generators use yield, iterators don't.
Implementing our own iterators requires us writing a class as shown earlier, generators don't need classes in python.
Generators are faster than iterators but iterators are more memory-effecient.
"""
|
import java.util.HashMap;
import java.util.Map;
public class RomanToInteger {
public static int romanToInt(String s) {
Map<Character, Integer> romanValues = new HashMap<>();
romanValues.put('I', 1);
romanValues.put('V', 5);
romanValues.put('X', 10);
romanValues.put('L', 50);
romanValues.put('C', 100);
romanValues.put('D', 500);
romanValues.put('M', 1000);
int result = 0;
int prevValue = 0;
for (int i = s.length() - 1; i >= 0; i--) {
int curValue = romanValues.get(s.charAt(i));
if (curValue >= prevValue) {
result += curValue;
} else {
result -= curValue;
}
prevValue = curValue;
}
return result;
}
public static void main(String[] args) {
String romanNumeral = "IX"; // Example: Input your Roman numeral here
int integerEquivalent = romanToInt(romanNumeral);
System.out.println("Integer equivalent: " + integerEquivalent);
}
}
|
import { Flex, FlexProps, ImageProps, Text } from "@chakra-ui/react";
import { observer } from "mobx-react-lite";
import { FC } from "react";
import { Check } from "react-feather";
import { NFT } from "../../store/nfts";
import { NFTImage } from "./NFTImage";
interface NFTItemProps extends Omit<FlexProps, "onSelect"> {
nft: NFT;
selected?: boolean;
onSelect?: (nft: NFT) => void;
imageProps?: ImageProps;
}
export const NFTItem: FC<NFTItemProps> = observer(
({ nft, onSelect, selected, imageProps, ...props }) => {
return (
<Flex
position="relative"
direction="column"
gap={2}
p={2}
overflow="hidden"
alignItems="center"
cursor="pointer"
rounded={["30px"]}
bg="gray.800"
transition="all 0.2s"
// borderWidth={selected ? "2px" : "1px"}
borderWidth="2px"
borderColor={selected ? "primary.200" : "gray.700"}
boxShadow="0px 0px 10px rgba(0, 0, 0, 0.4)"
_hover={{
borderColor: selected ? "" : "gray.600",
boxShadow: "0px 0px 20px rgba(0, 0, 0, 0.8)",
}}
onClick={() => {
onSelect?.(nft);
}}
{...props}
>
<NFTImage
nft={nft}
boxSize=""
w="full"
h="120px"
objectFit="cover"
// bg="gray.900"
rounded={["25px"]}
{...imageProps}
/>
{selected && (
<Flex
position="absolute"
w="full"
h="full"
top="0"
left="0"
alignItems="center"
justifyContent="center"
backdropBlur="md"
bg="rgba(0,0,0,0.7)"
>
<Flex
rounded="full"
alignItems="center"
justifyContent="center"
boxShadow="dark-lg"
bg="rgba(0,0,0,0.7)"
p={4}
>
<Check
size="45px"
strokeWidth={4}
// color="var(--chakra-colors-primary-200)"
color="white"
/>
</Flex>
</Flex>
)}
<Flex
direction="column"
alignItems="flex-start"
maxW="full"
overflowX="hidden"
w="full"
p={2}
px={4}
whiteSpace="nowrap"
>
<Text
fontSize="md"
maxW="full"
textOverflow="ellipsis"
overflow="hidden"
fontWeight={500}
>
{nft.symbol}
</Text>
<Flex w="full" maxW="full" gap={1}>
<Text
textOverflow="ellipsis"
overflow="hidden"
fontSize="xs"
flex="1"
color="gray.500"
>
{nft.name}
</Text>
<Text
textOverflow="ellipsis"
overflow="hidden"
fontSize="xs"
color="gray.500"
>
#{nft.id}
</Text>
</Flex>
</Flex>
</Flex>
);
}
);
|
//
// Model.swift
// Downloader
//
// Created by Chris Eidhof on 15.11.21.
//
import Foundation
@MainActor
final class DownloadModel: NSObject, ObservableObject, Sendable {
let url: URL
init(_ url: URL) {
self.url = url
}
enum State {
case notStarted
case started
case inProgress(bytesWritten: Int64, bytesExpected: Int64)
case paused(resumeData: Data?)
case done(URL)
}
@Published var state = State.notStarted
private var downloadTask: URLSessionDownloadTask?
func start() async throws {
state = .started
let task = URLSession.shared.downloadTask(with: url)
task.delegate = self
task.resume()
downloadTask = task
}
func cancel() async {
let data = await downloadTask?.cancel()
state = .paused(resumeData: data)
}
}
extension URLSessionDownloadTask {
func cancel() async -> Data? {
await withCheckedContinuation { cont in
self.cancel(byProducingResumeData: { data in
cont.resume(returning: data)
})
}
}
}
extension DownloadModel: URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
Task {
state = .done(location)
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
Task {
state = .inProgress(bytesWritten: totalBytesWritten, bytesExpected: totalBytesExpectedToWrite)
}
}
}
|
import { CreatePerguntaDto } from 'src/perguntas/dto/create-pergunta.dto';
import { ApiProperty } from '@nestjs/swagger';
import {validate,
validateOrReject,
Contains,
IsInt,
Length,
IsEmail,
IsFQDN,
IsDate,
Min,
Max,
IsString,
IsNumber,
MinLength,
MaxLength,
Validate,
IsDefined,
IsArray,} from 'class-validator';
import { TesteUpdateRespostaDto } from 'src/respostas/dto/teste-update-resposta.dto';
export class ArrayUpdateResposta {
@ApiProperty({
description: 'Array de respostas',
example: [
{
id:1,
name:"Resposta 1"
},
{
id:2,
name:"Resposta 2"
},
{
id:3,
name:"Resposta 3"
}
]
})
@IsArray()
@IsDefined()
respostas: TesteUpdateRespostaDto[];
}
|
# Systemd Timer Units
โดยส่วนใหญ่แล้ว user มักจะใช้ cron ในการทำ task schedular แต่เราก็สามารถใช้ ```systemd``` เพื่อกำหนดเวลาให้งานทำงานโดยอัตโนมัติเหมือนกัน
## timer
การตั้งเวลา เราจะต้องสร้างหน่วยจับเวลาและหน่วยบริการที่เกี่ยวข้องก่อน เริ่มต้นที่ timer
timer คือ ไฟล์ที่ลงท้ายด้วย **.timer** ซึ่งอยู่ในประเภทของ **systemd unit files**
.timer จะเก็บข้อมูลการกำหนดค่าเกี่ยวกับงานที่จะถูก execute ด้วย systemd Timer
file timer จะอยู่ใน ```/etc/systemd/system/```
ภายใน file ก็จะแบ่งเป็น 3 section
- [Unit] : ข้อมูลทั่วไปเกี่ยวไฟล์ systemd unit files
- [Timer] : ประกอบด้วย เวลาที่จะเริ่ม และ task ที่จะ execute
- [Install] : ข้อมูลเกี่ยวกับการติดตั้ง ระบุว่าตัวจับเวลาควรเริ่มต้นเมื่อถึงจุดไหน
และ timer ยังแบ่งได้เป็น 2 ประเภท
> <ins>Monotonic </ins>
> - timer อนุญาตให้ execute หลัง event ที่เกิดขึ้นแล้ว
> - ใช้เป็น **OnBootSec** (system boots) หรือ **OnActiveSec** (systemd unit ที่ active)
```
[Timer]OnBootSec=10sec Unit=greeting.service
```
><ins>Realtime</ins>
> - ทำงานเหมือน cron หรือก็คือทำงานตามที่กำหนด
> - ควรใช้ **OnCalendar**
```
DayofWeek Year-Month-Day Hour:Minute:Second
```
เช่น
```
OnCalendar=*-*-* 02:30:00 -> ทุก 02.30 ของทุกวัน
OnCalendar=Mon *-*-* 02:30:00 -> ทุก 02.30 ของทุกวันจันทร์
OnCalendar=hourly -> ทุกชั่วโมง
OnCalendar=*:0/6 -> ทุก 6 ชั่วโมง
OnCalendar=10:00,18:00 -> ทุกเวลา 10 โมง และ 6 โมงเย็นของทุกวัน
```
## service
ทุก timer ต้องมีตัวกระตุ้น ก็คือ ไฟล์ .service
```
Unit=myscript.service
```
> ทั้ง .timer และ .service ควรมีชื่อ file เหมือนกัน!
และ .service ให้ระบุคำสั่งหรือสคริปต์ที่ควรเรียกใช้เมื่อตัวจับเวลาทริกเกอร์โดยเพิ่มตัวเลือก **"ExecStart"**
```
ExecStart=/usr/local/bin/myscript.sh
```
.timer ที่ได้ก็คือ
```
[Unit]
Description=Run myscript every day at 2:30am
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
Unit=myscript.service
[Install]
WantedBy=timers.target
```
และ .service ที่ได้ก็คือ
```
[Unit]
Description=My script
[Service]
Type=simple
User=myuser
ExecStart=/usr/local/bin/myscript.sh
Restart=on-failure
[Install]
WantedBy=default.target
```
## systemctl Command
systemctl เป็น<ins> interface ที่ใช้ควบคุม systemd units</ins>
เปิดใช้งานคำสั่งได้โดย
```
$ systemctl COMMAND UNIT_NAME [OPTION]
```
หรือ
```
$ systemctl LIST_UNIT
```
เช่น
```
$ sudo systemctl disble myscript.timer
$ sudo systemctl enable myscript.timer
$ sudo systemctl start myscript.timer
```
สามารถตรวจสอบสถานะได้โดยการ เช็ค status ว่าทำงานอยู่มั้ย
```
$ sudo systemctl status name.timer
$ sudo systemctl status name.service
```
หากคุณแก้ไข .timer หรือ.service ในภายหลัง ต้องดูให้แน่ใจก่อนว่าได้โหลด `systemd` ใหม่หลังจากนั้นแล้ว ด้วยการใช้คำสั่ง
```
$ sudo systemd daemon-reload
```
|
// default parameter
function addTwo(a,b){
if(typeof b === "undefined"){
b = 0;
}
return a + b;
}
const ans = addTwo(4); //since only 4 passed so, 4 + undefined will result in nan so, to avoid this we can add if condition that if b will be undefined then value of b will be zero so it will return 4 + 0 = 4;
|
import { ButtonRow, ContainedButton, Headline3 } from 'gobble-lib-react';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { useCameras } from '../hooks/use-camers';
import { CameraCard } from './camera-card';
const CameraListWrapper = styled.div`
display: flex;
gap: 8px;
margin: 4px 16px;
`;
const TopBar = styled.div`
display: grid;
grid-template-columns: 1fr auto;
justify-items: center;
align-items: center;
margin-bottom: 16px;
`;
export const CameraList = () => {
const nav = useNavigate();
const cameras = useCameras();
return (
<div>
<TopBar>
<Headline3>Cameras</Headline3>
<ContainedButton onClick={() => nav('/cameras/0')}>
<i className='fa-solid fa-plus' />
</ContainedButton>
</TopBar>
<CameraListWrapper>
{
cameras.map(cam => <CameraCard key={cam.id} cam={cam} />)
}
</CameraListWrapper>
</div>
);
};
|
<template>
<v-chart :options="barLine"/>
</template>
<script>
import ECharts from 'vue-echarts'
import 'echarts/lib/chart/bar'
import 'echarts/lib/chart/line'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/title'
import 'echarts/lib/component/tooltip'
// import 'echarts/lib/chart'
export default {
name: 'PreviewBar',
props: {
method: String
},
components: {
'v-chart': ECharts
},
data () {
var colors = ['#5793f3', '#d14a61', '#675bba']
let dataSet = this.$store.state.response.previewBarData
return {
barLine: {
title: {
text: '算法执行开销与代价函数计算值',
show: true,
textStyle: {
color: '#ccc',
fontSize: 10
},
bottom: 0,
left: 'center'
},
color: colors,
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
}
},
grid: {
left: '12%',
right: '12%'
},
toolbox: {
feature: {
dataView: {show: true, readOnly: false},
restore: {show: true},
saveAsImage: {show: true}
}
},
legend: {
data: ['时间开销', '代价函数', '综合'],
textStyle: {
color: '#ccc'
},
orient: 'horizontal',
itemWidth: 12,
itemHeight: 8,
top: 0
},
xAxis: [
{
type: 'category',
axisTick: {
alignWithLabel: true
},
data: ['LPMS', 'QTMS', 'TOPO', 'APHiD', 'TREE', 'MPIPP'],
axisLabel: {
color: '#ccc',
rotate: 45,
fontSize: 10,
margin: 6
}
}
],
yAxis: [
{
type: 'value',
name: '时间开销',
min: 0,
max: 50,
position: 'right',
axisLine: {
lineStyle: {
color: colors[0]
}
},
axisLabel: {
show: false
}
},
{
type: 'value',
name: '代价函数',
min: 0,
max: 50,
position: 'left',
axisLine: {
lineStyle: {
color: colors[1]
}
},
axisLabel: {
show: false
}
},
{
type: 'value',
name: '综合',
min: 0,
max: 100,
position: 'right',
offset: 80,
axisLine: {
lineStyle: {
color: colors[2]
}
}
}
],
series: [
{
name: '时间开销',
type: 'bar',
data: dataSet.algorithm
},
{
name: '代价函数',
type: 'bar',
yAxisIndex: 1,
data: dataSet.communication
},
{
name: '综合',
type: 'line',
yAxisIndex: 2,
data: dataSet.overall
}
]
}
}
}
}
</script>
<style lang="stylus" scoped>
@import '~styles/variables'
</style>
|
def modifiedPascalF(n:Int) = {
def pascalHelper(xs: List[Int], k: Int): List[Int] = {
(xs, k) match
case (h1 :: Nil, _) => Nil
case (h1 :: h2 :: t, k) if k % 2 == 0 => h1 + h2 :: pascalHelper(h2::t, k)
case (h1 :: h2 :: t, k) if k % 2 == 1 => h1 - h2 :: pascalHelper(h2::t, k)
case (_,_) => throw new Exception("Internal error")
}
def pascalHelper2(xs: List[Int], row: Int): List[Int] = {
if row < n then pascalHelper2(1 :: pascalHelper(xs, row)::: List(1), row + 1)
else 1 :: pascalHelper(xs, row)::: List(1)
}
if n<0 then
List()
else if n==0 then
List(1)
else if n==1 then
List(1,1)
else pascalHelper2(List(1,1),2)
}
def modifiedPascalI(n:Int) = {
var t1 = new Array[Int](0)
if (n<0) {}
else if(n==0) then
t1 = Array.fill(1)(1)
else if(n == 1) then
t1 = Array.fill(2)(1)
else
var row = 2
t1 = Array.fill(2)(1)
while(row <= n) do {
var i = 1
var array = new Array[Int](row + 1)
while (i < array.length - 1) do {
if (row % 2 == 0) then
array(i) = t1(i-1) + t1(i)
else
array(i) = t1(i-1) - t1(i)
i += 1
}
array(0) = 1
array(array.length - 1) = 1
t1 = array
row += 1
}
t1
}
modifiedPascalF(1)
modifiedPascalF(5)
modifiedPascalF(-1)
modifiedPascalI(1).toList
modifiedPascalI(5).toList
modifiedPascalI(-1).toList
|
# Data Analyst Associate Practical Exam Submission
## Requirements
- Postgresql 15
- pgAdmin 4
- PowerBI
## Databases
ER Model

## Task 1
1. For every column in the data:
- State whether the values match the description given in the table above.
- State the number of missing values in the column.
- Describe what you did to make values match the description if they did not match.
**Product_id:** There were 1500 unique product identifier values. No values are missing.
**Category:** There were 6 unique category values. There were 25 null values '-'. Changes were made to the column; null values were replaced with 'Unknown'.
```
UPDATE pets_supplies
SET category = CASE
WHEN category IS NULL OR category = '-' THEN 'Unknown'
ELSE category
END;
```
**Animal:** There were 4 unique values matching the four values provided in the data dictionary. No values are missing, so no changes were made to the column.
```
SELECT COUNT(animal)
FROM pets_supplies
WHERE animal IS NULL OR category = 'NA' OR animal = '-';
```
```
SELECT COUNT(DISTINCT animal)
FROM pets_supplies;
```
**Size:** There were 3 unique values matching the three values provided in the data dictionary. No data is missing. The format of the column values was standardized, with the first letter in uppercase and the rest in lowercase.
```
SELECT COUNT(size)
FROM pets_supplies
WHERE size IS NULL or size = 'NA' OR size = '-';
```
```
UPDATE pets_supplies
SET size = CASE
WHEN size IS NULL THEN 'Unknown'
ELSE INITCAP(LOWER(size))
END;
```
**Price:** This column contained positive values, consistent with the description. 150 'Unlisted' data are missing. All missing values were replaced with the global mean. All column values were rounded to 2 decimal places.
```
SELECT COUNT(*)
FROM pets_supplies
WHERE price IS NULL OR price = 'unlisted';
```
```
UPDATE pets_supplies
SET price = (
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY CASE WHEN price = 'unlisted' THEN NULL ELSE price::numeric END)
FROM pets_supplies
WHERE price <> 'unlisted'
)
WHERE price = 'unlisted';
```
```
UPDATE pets_supplies
SET price = ROUND(price::numeric, 2)
WHERE price <> 'unlisted' AND price <> '';
```
**Sales:** This column contains positive values, consistent with the description. No values are missing. All column values were rounded to 2 decimal places.
```
SELECT COUNT(sales)
FROM pets_supplies
WHERE sales < 0 OR sales IS NULL;
```
```
UPDATE pets_supplies
SET sales = ROUND(sales::numeric, 2);
```
**Rating:** The values in this column ranged from 1 to 10, consistent with the description. 150 'NA' data are missing. All missing values were replaced with 0.
```
SELECT COUNT(rating)
FROM pets_supplies
WHERE rating IS NULL OR rating = 'NA';
```
```
UPDATE pets_supplies
SET rating =
CASE
WHEN rating IS NULL OR rating = 'NA' THEN 0
ELSE rating::numeric
END;
```
**Repeat_purchase:** The values in this column were either zero or one. No values are missing, but there were 142 negative values -0 and -1. All negative values were standardized to positive format.
```
SELECT COUNT(repeat_purchase)
FROM pets_supplies
WHERE repeat_purchase IS NULL OR repeat_purchase = '-0' OR repeat_purchase = '-1';
```
```
UPDATE pets_supplies
SET repeat_purchase = CASE
WHEN repeat_purchase = '-0' THEN '0'
WHEN repeat_purchase = '-1' THEN '1'
ELSE repeat_purchase
END;
```
## Task 2
2. Create a visualization that shows how many products are repeat purchases. Use the visualization to:
- State which category of the variable repeat purchases has the most observations.
- Explain whether the observations are balanced across categories of the variable repeat purchases.

A bar chart is an appropriate choice in this case because it effectively illustrates the imbalance in the data between repeat purchase (category 1) and non-repeat purchase (category 0). The graph clearly shows that category 1 has a count of 906 observations of customers who repeatedly buy the product and represents about 60.40% of the total observations, while there is a count of 594 observations of customers who do not repeatedly buy the product (category 0).
The observations are not balanced across the categories of the "repeat_purchase" variable, underscoring the need for attention to customer loyalty programs to encourage repeat purchases.
## Task 3
3. Describe the distribution of all of the sales. Your answer must include a visualization that shows the distribution.

A bar chart is ideal for visualizing this information because it visually compares the sales figures of the different categories indicating that no category exceeds 35 million in sales, with "Equipment" being the highest selling category and "Unknown" the lowest selling category. It allows a quick assessment of relative sales performance and highlights that "Equipment" contributes significantly to total sales reaching a total of 34.8 million with 23.3%. It also underlines the need to investigate the "Unknown" category, which represents only 1.8% of sales, providing valuable information for possible product improvements.
The "Toys" category followed closely behind "Equipment", with total sales of 31.9 million. The "Food" category also performed well, with total sales of 28.7 million euros.
Sales in the "Medical", "Housing" and "Accessories" categories were 21.4 million, 17.5 million and 12.1 million, respectively.
## Task 4
4. Describe the relationship between repeat purchases and sales. Your answer must include a visualization to demonstrate the relationship.

A scatter plot is the preferred option in this case because it effectively visualizes the positive correlation between repeat purchases and sales, given that both variables are continuous.
In the "Accessories" category, which recorded a high number of 126 repeat purchases, significant sales were also recorded, amounting to 12.1 million in monetary sales. This indicates a positive correlation, as a higher number of repeat purchases is associated with higher sales.
Similarly, in the "Equipment" category, which recorded the highest number of 370 repeat purchases, significant sales were observed, amounting to 34.8 million in monetary sales. This reinforces the positive correlation between repeat purchases and sales.
The "Toys" category also shows this trend, with a high number of 255 repeat purchases and sales amounting to 31.9 million in monetary sales.
Other categories such as "Food", "Housing", "Medicines" and "Unknown" also show a positive correlation between repeat purchases and sales, as categories with a higher number of repeat purchases tend to have higher sales.
Given the positive correlation observed, it is recommended that the team should
Implement or improve customer loyalty programs to encourage more repeat purchases.
Engage with customers after purchase through feedback surveys, personalized recommendations and targeted marketing campaigns. This can help you understand their preferences and ensure they buy again.
## Technology Stack
- Postgresql 15
- PowerBI
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>v-model 与自定义组件</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 自定义组件 v-model -->
<custom-screen v-model="text"></custom-screen>
<br />
<!-- 原生元素 v-model -->
输入框:<input type="text" v-model="text" />
</div>
<script type="text/javascript">
/*
在自定义组件中, value 属性和 input 事件尤为重要,它们分别负责不同方向的数据传递。
value属性用于接收外部传入的值以更新组件内部的状态;
input事件由开发者决定在什么时候调用,并负责将组件内部的状态同步到外部。
*/
// 自定义组件
Vue.component('custom-screen', {
// 使用value属性接受外部传入的值
props: ['value'],
methods: {
handleReset() {
console.log('重置为\'\'')
// 使用 $emit 发送input事件,并将目标值作为参数传出
this.$emit('input','')
}
},
template:`
<div>
<h2>输入值为:{{value}}</h2>
<button @click="handleReset">重置为空</button>
</div>
`
})
new Vue({
el:'#app',
data() {
return {
text: ''
}
},
})
</script>
</body>
</html>
|
import os
import numpy as np
# pip install opencv-python
import cv2
from random import shuffle
# Libraries for Image Classification
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
TRAIN_DIR = 'train'
IMG_SIZE = 128
IMAGE_CHANNELS = 3
FIRST_NUM_CHANNEL = 32
FILTER_SIZE = 3
LR = 0.0001
PERCENT_TRAINING_DATA = 80
NUM_EPOCHS = 50
MODEL_NAME = 'emotion_cnn'
TEST_IMG = 'bibi2.jpg'
def define_classes():
all_classes = []
for folder in os.listdir(TRAIN_DIR):
all_classes.append(folder)
return all_classes, len(all_classes)
def define_labels(all_classes):
all_labels = []
for x in range(len(all_classes)):
all_labels.append(np.array([0. for i in range(len(all_classes))]))
all_labels[x][x] = 1
return all_labels
all_classes, NUM_OUTPUT = define_classes()
all_labels = define_labels(all_classes)
# Make the model
convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, IMAGE_CHANNELS], name='input')
convnet = conv_2d(convnet, FIRST_NUM_CHANNEL, FILTER_SIZE, activation='relu')
convnet = max_pool_2d(convnet, FILTER_SIZE)
convnet = conv_2d(convnet, FIRST_NUM_CHANNEL*2, FILTER_SIZE, activation='relu')
convnet = max_pool_2d(convnet, FILTER_SIZE)
convnet = conv_2d(convnet, FIRST_NUM_CHANNEL*4, FILTER_SIZE, activation='relu')
convnet = max_pool_2d(convnet, FILTER_SIZE)
convnet = conv_2d(convnet, FIRST_NUM_CHANNEL*8, FILTER_SIZE, activation='relu')
convnet = max_pool_2d(convnet, FILTER_SIZE)
convnet = fully_connected(convnet, FIRST_NUM_CHANNEL*16, activation='relu')
convnet = dropout(convnet, 0.8)
convnet = fully_connected(convnet, NUM_OUTPUT, activation='softmax')
convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')
model = tflearn.DNN(convnet, tensorboard_dir='log')
print('LOADING MODEL ' + '{}.meta'.format(MODEL_NAME))
if os.path.exists('{}.meta'.format(MODEL_NAME)):
# Load the Model
model.load(MODEL_NAME)
test_img = cv2.imread(TEST_IMG)
test_img = cv2.resize(test_img, (IMG_SIZE, IMG_SIZE))
# Classify the image
data = test_img.reshape(IMG_SIZE, IMG_SIZE, IMAGE_CHANNELS)
data_res_float = model.predict([data])[0]
for x in range(len(all_labels)):
print(all_classes[x] + ' ' + str(data_res_float[x]*100))
|
<?php
namespace App\Http\Controllers;
use App\Helpers\FetchConvertTasks;
use Illuminate\Http\Request;
use Session;
class TaskController extends Controller
{
public function index()
{
$tasks = FetchConvertTasks::fetchTasks();
return view('welcome',compact('tasks'));
}
public function addTask(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|string|max:255',
]);
$tasks = FetchConvertTasks::fetchTasks();
$existingTask = collect($tasks)->first(function ($task) use ($validatedData) {
return $task['title'] === $validatedData['title'];
});
if ($existingTask) {
return response()->json([
'success' => false,
'message' => 'The task ' . $validatedData['title'] . ' is already in the list.',
]);
}
$newTask = [
'id' => count($tasks) + 1,
'title' => $validatedData['title'],
'completed' => false,
];
$tasks[] = $newTask;
Session::put('tasks', $tasks);
return response()->json([
'success' => true,
'message' => 'Task created successfully',
'tasks' => $tasks,
]);
}
public function update($taskId)
{
$tasks = FetchConvertTasks::fetchTasks();
foreach ($tasks as &$task) {
if ($task['id'] == $taskId) {
$task['completed'] = true;
break;
}
}
Session::put('tasks', $tasks);
return response()->json(['message' => 'Task status updated successfully','tasks' => $tasks], 200);
}
public function delete($taskId)
{
$tasks = FetchConvertTasks::fetchTasks();
$index = array_search($taskId, array_column($tasks, 'id'));
if ($index !== false) {
unset($tasks[$index]);
$tasks = array_values($tasks);
Session::put('tasks', $tasks);
return response()->json(['message' => 'Task deleted successfully', 'tasks' => $tasks], 200);
} else {
return response()->json(['message' => 'Task not found'], 404);
}
}
}
|
import os
import openai
import playsound as ps
from gtts import gTTS
from pydub import AudioSegment
from pydub.playback import play
import speech_recognition as sr
from time import sleep
# Set up your openai API
openai.api_key = 'your openai api key'
messages = [{"role": "user", "content": "Hello GPT!"}]
def delete_file(file_path):
try:
os.remove(file_path)
print(f"File '{file_path}' has been deleted successfully.")
except OSError as e:
print(f"Error occurred while deleting the file: {e}")
def generate_response(messages1):
# Call the openai API
response1 = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=messages1
)
return response1.choices[0].message.content
def text_to_speech(text1):
tts = gTTS(text=text1, lang="en")
filename1 = "gpt.mp3"
tts.save(filename1)
file = open(filename1)
file.close()
song = AudioSegment.from_mp3("./gpt.mp3")
print('playing sound...')
play(song)
delete_file(filename1)
def speach_to_text():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Say something...")
audio = recognizer.listen(source)
text = ""
catch = False
while not catch:
try:
text = recognizer.recognize_google(audio)
print("You said: " + text)
catch = True
except sr.UnknownValueError:
print("Sorry, I could not understand what you said.")
except sr.RequestError as e:
print(f"Sorry, an error occurred: {e}")
return text
# Main loop
print("Welcome to the Chatbot! Say 'exit' to end the conversation.")
while True:
user_input = speach_to_text()
messages.append({"role": "user", "content": user_input})
sleep(2)
if user_input.lower().strip() == 'exit':
break
# Generate a response
response = generate_response(messages)
messages.append({"role": "assistant", "content": response})
print("Chatbot:", response)
text_to_speech(response)
sleep(2)
# in case you wanted to save the file and play it later
# if os.path.isfile("gpt.mp3"):
# print("file exists")
# else:
# print("doesn't exist")
#
# ps.playsound("./gpt.mp3")
# print('playing sound using pydub')
|
package algo_question.stack;
/*
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
*/
import java.util.HashMap;
import java.util.Map;
public class StackUseDeque{
public static void main(String[] args) {
System.out.println(climbStairs(2));
}
//Approach 1: Recursion
public static int climbStairs(int n) {
if (n == 0 || n == 1) {
return 1;
}
return climbStairs(n-1) + climbStairs(n-2);
}
//Approach 2: Memoization
public static int climbStairs1(int n) {
Map<Integer, Integer> memo = new HashMap<>();
return climbStairs1(n, memo);
}
private static int climbStairs1(int n, Map<Integer, Integer> memo) {
if (n == 0 || n == 1) {
return 1;
}
if (!memo.containsKey(n)) {
memo.put(n, climbStairs1(n-1, memo) + climbStairs1(n-2, memo));
}
return memo.get(n);
}
}
|
<!-- 登录页面 -->
<template>
<el-container class="custom-bg">
<div class="custom-box">
<div class="custom-header">
<!-- 企业logo -->
<div class="logo">LOGO</div>
</div>
<div class="tab-box">
<el-tabs v-model="activeName" style="border-bottom: none;">
<el-tab-pane label="账密登录" name="acc_pwd">
<!-- ****** 所有在el-tab-pane下的字元素必须同时使用 custom-tab-pane 类选择器 ****** -->
<el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="60px"
class="demo-ruleForm custom-style custom-tab-pane">
<el-form-item label="账号" prop="username" class="custom-form-item">
<el-input ref="acc_inp" v-model="ruleForm.username" class="custom-login-inp" @keyup.enter.native="inpFocus('pwd_inp')"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password" class="custom-form-item">
<el-input ref="pwd_inp" type="password" v-model="ruleForm.password" class="custom-login-inp" @keyup.enter.native="(submitForm('ruleForm'))"></el-input>
</el-form-item>
<el-form-item>
<!-- 添加loading组件防止重复点击 -->
<el-button class="custom-login-button" :loading="login_btn_loading" type="primary"
@click="submitForm('ruleForm')">登录
</el-button>
</el-form-item>
</el-form>
</el-tab-pane>
<el-tab-pane label="手机号登录" name="">
<div class="custom-tab-pane"></div>
</el-tab-pane>
<el-tab-pane label="扫码登录" name="">
<div class="custom-tab-pane"></div>
</el-tab-pane>
</el-tabs>
</div>
<!-- <div class="custom-footer">-->
<!-- 保留 -->
<!-- </div>-->
</div>
<!-- </el-col>-->
<!-- </el-row>-->
</el-container>
</template>
<script>
import axios from "axios";
import MessageUtil from "../utils/MessageUtil.js"
import router from "@/router";
export default {
data() {
return {
login_btn_loading: false,
activeName: 'acc_pwd',
ruleForm: {
username: '',
password: '',
},
rules: {
username: [
{required: true, message: '请输入账号', trigger: 'blur'},
{min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur'}
],
password: [
{required: true, message: '请输入密码', trigger: 'blur'},
{min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'}
],
}
}
},
methods: {
/**
* 登录
* @param formName
*/
submitForm(formName) {
this.login_btn_loading = true;
this.$refs[formName].validate((valid) => {
if (valid) {
console.log("ok")
let URL = "http://localhost:8081/V0/login";
axios.post(
URL, this.ruleForm, false
).then(res => {
console.log(res.data.code)
switch (res.data.code) {
case "00": {
MessageUtil.success("登录成功");
window.sessionStorage.setItem("userInfo", JSON.stringify(res.data.data.user));
window.sessionStorage.setItem("userPower", JSON.stringify(res.data.data.userPower));
this.$router.push("index");
break;
}
case "06": {
MessageUtil.error("账号或密码错误");
break;
}
case "10": {
MessageUtil.error("用户无访问权限");
break;
}
};
this.login_btn_loading = false;
})
} else {
MessageUtil.error('账号或密码格式错误');
this.login_btn_loading = false;
this.inpFocus("acc_inp");
}
})
},
inpBlur(refName) {
this.$refs[refName].blur();
},
inpFocus(refName) {
this.$refs[refName].focus();
}
}
}
</script>
<!-- 覆盖原有element-ui样式-->
<style scoped>
::v-deep .custom-login-inp input {
border: none;
outline: none;
}
::v-deep .el-tabs__item {
width: 110px;
text-align: center;
}
::v-deep .el-tabs__nav-wrap::after {
display: none;
}
::v-deep div.el-tabs__active-bar.is-top {
max-width: 20px;
left: 33px;
}
::v-deep .el-form-item:last-of-type {
width: 100%;
height: 40px;
position: relative;
}
</style>
<style scoped>
body {
margin: 0;
padding: 0;
overflow: hidden;
}
.custom-bg {
height: 100vh;
width: 100vw;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
background: url("../assets/login-bg.webp") no-repeat;
background-size: 100% 100%;
overflow: hidden;
}
.custom-box {
width: 400px;
/*height: 450px;*/
height: fit-content;
background-color: rgba(256, 256, 256, 1);
border-radius: 10px;
overflow: hidden;
}
.custom-header {
height: 60px;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
border-bottom: 1px solid #000;
}
.logo {
width: fit-content;
height: fit-content;
}
.tab-box {
height: 300px;
display: flex;
justify-content: center;
padding-top: 30px;
}
.custom-tab-pane {
width: 300px;
min-height: 200px;
height: fit-content;
margin: 0 auto;
}
.custom-form-item {
border-bottom: 2px solid #99CCFF;
}
.custom-login-button {
position: absolute;
width: 150px;
left: 20px;
}
</style>
|
import math
import random
from datetime import datetime, timedelta
from random import shuffle
from statistics import mean, median
import pandas as pd
from ams.services.equities import equity_fundy_service
from ams.services.ticker_service import get_ticker_eod_data
EQUITIES = ['GOOG', 'COST', 'FB', 'MSFT', 'NKE', 'NVDA', 'AAPL']
TOP_2014 = ['NFX', 'GMCR', 'LUV', 'EA', 'NBR', 'AA', 'WMB', 'UA', 'AVGO', 'MNK']
TOP_2015 = ['NFX', 'AMZN', 'ATVI', 'NVDA', 'ALTUS', 'HRL', 'VRSN', 'RAI', 'SBUX', 'FSLR']
TOP_2016 = ['NVDA', 'FCX', 'NEM', 'SEP', 'AMAT', 'PWR', 'CMA', 'MLM', 'HAL', 'OKE']
TOP_EQ = TOP_2016
EXAMINE_YEAR = 2018
YEAR_SPAN = 1
FROM_YEAR = f'{EXAMINE_YEAR}-01-01'
TO_YEAR = f'{EXAMINE_YEAR + YEAR_SPAN}-01-01'
EXAMINE_AFTER = f'{EXAMINE_YEAR + 1}-01-01'
HOLD_DAYS = 1
def test_get_roi_for_any_day_of_week():
# Arrange
all_ticks = []
for e in EQUITIES:
df = get_ticker_eod_data(e)
# df = df[df['date'].str[:4] == str(EXAMINE_YEAR)]
if df is None:
continue
# Drop rows with date null
df = df.dropna(subset=['date'])
df['date'] = pd.to_datetime(df['date'], format="%Y-%m-%d")
df['close-prev'] = df['close'].shift(HOLD_DAYS)
df['roi'] = (df['close'] - df['close-prev']) / df['close-prev']
df['prev-1-days'] = df['close'].shift(1)
df['prev-2-days'] = df['close'].shift(2)
df['roi-prev'] = (df['prev-2-days'] - df['prev-1-days']) / df['prev-1-days']
df['did_fall'] = df['roi-prev'] < 0
# df = df[df['did_fall'] == True]
df['date_of_week'] = df['date'].dt.day_name()
df_g = df.groupby(['date_of_week', 'ticker']).agg({'roi': 'mean'})
df = df_g.reset_index()
all_ticks.append(df)
df = pd.concat(all_ticks)
print(f'Total rows: {df.shape[0]}')
df_g = df.groupby(['date_of_week']).agg({'roi': 'mean'})
print(df_g.head())
def test_get_roi_for_day_of_week():
# Arrange
all_ticks = []
for e in TOP_EQ:
df = get_ticker_eod_data(e)
if FROM_YEAR:
df = df[df['date'] >= FROM_YEAR]
if TO_YEAR:
df = df[df['date'] < TO_YEAR]
if df is None:
continue
df = df.dropna(subset=['date', 'close'])
df['prev'] = df['open'].shift(HOLD_DAYS)
df = df.dropna(subset=['close', 'prev'])
df['roi'] = (df['close'] - df['prev']) / df['prev']
df['date_of_week'] = pd.to_datetime(df['date']).dt.day_name()
df = df[df['date_of_week'] == 'Monday']
all_ticks.append(df)
df = pd.concat(all_ticks)
print(f'Total rows: {df.shape[0]}')
num_years = 10
roi = shuffle_and_calc_roi(df)
print(f'ROI: {roi * 100:.3f}%')
def shuffle_and_calc_roi(df: pd.DataFrame):
df = df.sample(frac=1).reset_index(drop=True)
init_invest = 100
current_amt = init_invest
for ndx, row in df.iterrows():
roi = row['roi']
current_amt = current_amt * (1 + roi)
if current_amt <= 0:
break
# print(f'Current amount: {current_amt}')
roi = (current_amt - init_invest) / init_invest
print(f'ROI: {roi}')
return roi
def test_ef():
df_equity_funds = equity_fundy_service.get_equity_fundies()
print(df_equity_funds.head())
def test_tuesday():
# Arrange
equities = ['AU', 'GFI', 'GRD', 'FNV'] # , 'JWN', 'COST', 'DELL', 'DDOG', 'F', 'FANG', 'FSLY', 'GME', 'HPE', 'IBM', 'INTC', 'JPM', 'KO', 'LMT', 'MCD', 'MSFT', 'NKE', 'NVDA', 'PFE', 'PG', 'PLTR', 'PYPL', 'QCOM', 'SBUX', 'TSLA', 'TWTR', 'V', 'WMT', 'XOM']
equities = ['AG', 'SVM', 'EXK', 'MUX']
equities = ['TGB', 'ERO', 'SCCO', 'HBM']
equities = ['CLF', 'BHP', 'MSB', 'VALE']
# equities = ['AGRO', 'BG', 'SEB', 'TAGS']
# equities = ['CENX', 'RIO', 'VEDL', 'AA']
# Gold stocks in 2014
# equities = ['ABX', 'AU', 'AUY', 'GG', 'NEM', 'RGLD'] # 11%
# silver stock symbols 2014
equities = ['SILV', 'ASM', 'AG', 'HL', 'SVM', 'PAAS', 'CDE', 'FSM', 'EXK'] # 14.63
for y in range(2014, 2021):
calc(year_start=y, equities=equities)
def calc(year_start: int, equities: list):
all_ticks = []
for e in equities:
df = get_ticker_eod_data(e)
if df is None:
continue
# filter df between 2 dates
df = df[df['date'] >= f'{year_start}-01-01'].copy()
df = df[df['date'] <= f'{year_start + 2}-01-01'].copy()
df['close-prev'] = df['close'].shift(2)
df['roi'] = (df['close'] - df['close-prev']) / df['close-prev']
df.dropna(subset=['roi', 'date'], inplace=True)
if df is None:
continue
df['date_of_week'] = pd.to_datetime(df['date']).dt.day_name()
df = df[df['date_of_week'] == 'Wednesday']
all_ticks.append(df)
df = pd.concat(all_ticks)
print(f'Total rows: {df.shape[0]}')
init_amount = 100
curr_amt = init_amount
df = df.sample(frac=1)
total_rows = df.shape[0]
for _, r in df.iterrows():
roi = r['roi']
curr_amt = curr_amt * (1 + roi)
if curr_amt <= 0:
raise Exception('You\'re now broke!')
total_ret = curr_amt - init_amount
years = total_rows / 52
if curr_amt > init_amount:
ann_ror = ((1 + total_ret) ** (1 / years)) - 1
print(f'Num years: {years}: Annualized ROR: {(ann_ror * 100)}%')
print(f'Year start: {year_start}: Total return: {total_ret:.2f}')
def test_chart():
import matplotlib.pyplot as plt
equities = ['FSLR']
# , 'JWN', 'COST', 'DELL', 'DDOG', 'F', 'FANG', 'FSLY', 'GME', 'HPE', 'IBM',
# 'INTC', 'JPM', 'KO', 'LMT', 'MCD', 'MSFT', 'NKE', 'NVDA', 'PFE', 'PG', 'PLTR', 'PYPL',
# 'QCOM', 'SBUX', 'TSLA', 'TWTR', 'V', 'WMT', 'XOM']
# return
shuffle(equities)
start_date = 2017
num_months = 15
moving_average_span = 19
num_samples = 10000
inv_total = 100
all_roi_vals = []
for ndx in range(1):
eq = equities[random.choice(range(len(equities)))]
df = get_ticker_eod_data(eq)
df.sort_values('date', inplace=True)
if df.shape[0] == 0:
continue
first_date = df['date'].iloc[:1].values.tolist()[0]
first_dt = datetime.strptime(first_date, '%Y-%m-%d')
start_dt = first_dt + timedelta(days=random.choice(range(365 * 6)))
start_val_dt = start_dt + timedelta(days=(num_months * 30) - int((num_months / 3) * 30))
end_val_dt = start_dt + timedelta(days=(num_months * 30))
df = df[(df['date'] >= start_dt.strftime('%Y-%m-%d')) & (df['date'] <= start_val_dt.strftime('%Y-%m-%d'))]
df['date'] = pd.to_datetime(df['date'])
# Create a line chart
label = 'Close - Diff 20DMA'
plt.plot(df['date'], df['close'], label='ClosePrice')
# plt.plot(df['date'], df[diff_col], label=label)
#
# Add labels and title
plt.xlabel('Date')
plt.ylabel(label)
plt.title(f'{eq} {label}')
# Add legend
plt.legend()
# Display the chart
plt.show()
def test_show_nice_chart():
from mplchart.chart import Chart
from mplchart.helper import get_prices
from mplchart.primitives import Candlesticks, Volume
from mplchart.indicators import ROC, SMA, EMA, RSI, MACD
ticker = 'AAPL'
freq = 'daily'
df = get_ticker_eod_data(ticker)
df.sort_values('date', inplace=True)
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
# prices = get_prices(ticker, freq=freq)
prices = df[['open', 'high', 'low', 'close', 'volume']]
max_bars = 250
indicators = [
Candlesticks(), SMA(50), SMA(200), Volume(),
RSI(),
MACD(),
]
chart = Chart(title=ticker, max_bars=max_bars)
chart.plot(prices, indicators)
chart.show()
|
const refreshToken = require('../database/models/refreshToken');
const AuthService = require('../services/authService');
module.exports = {
async signup(req, res) {
try {
const userData = req.body;
console.log(req.body);
const { user, token, refreshToken } = await AuthService.signup(userData);
res.status(201).send({
auth: true,
message: 'User registered successfully!',
data: {
id: user.id,
accessToken: token,
refreshToken: refreshToken
}
});
} catch (error) {
res.status(500).send({
auth: false,
message: 'Error creating user',
errors: [error.message],
});
}
},
async signin(req, res) {
try {
const credentials = req.body;
const { user, token, refreshToken } = await AuthService.signin(credentials);
res.status(200).send({
auth: true,
message: 'Successfully Logged In',
data: {
id: user.id,
accessToken: token,
refreshToken: refreshToken,
}
});
} catch (error) {
res.status(500).send({
auth: false,
message: 'Error While Logging In',
errors: [error.message],
});
}
},
async signout(req, res) {
try {
const { token } = req.body;
await AuthService.signout(token);
res.status(200).send({
auth: false,
message: 'Successfully Logged Out',
});
} catch (error) {
res.status(500).send({
auth: false,
message: 'Error While Logging Out',
errors: [error.message],
});
}
},
async refreshToken(req, res) {
try {
const token = req.body.token;
const AccessToken = await AuthService.refreshToken(token);
res.status(200).send({
auth: true,
message: 'Successfully Refreshed Token',
data: {
accessToken: AccessToken
}
});
} catch (error) {
res.status(403).send({
auth: false,
message: 'Error While Refreshing Token',
errors: [error.message],
})
}
}
};
|
import React, { useEffect, useState } from "react";
import ImagePreset from "./assets/image-preset.png";
export default function ListItem({ launch = {}, index, hasLoaded }) {
const [isLoading, setIsLoading] = useState(true);
const { flight_number = "", links = {}, name, details } = launch;
useEffect(() => {
if (hasLoaded) {
setTimeout(() => {
setIsLoading(false);
}, 250);
}
}, [hasLoaded]);
return (
<li
data-index={index}
className="list-group-item d-flex align-items-center"
>
{isLoading ? (
<span className="fa fa-2x fa-spinner fa-spin mx-auto" />
) : (
<>
<img
src={links?.patch?.small || ImagePreset}
className="mx-3"
width={50}
height={50}
/>
<div>
<h6 className="my-2">
{flight_number}:
<span className={`${flight_number && "ms-1"}`}>{name}</span>
</h6>
<p>{details}</p>
</div>
</>
)}
</li>
);
}
|
// typescript import
import { NextPage } from 'next';
// import
import React, { useEffect } from 'react';
import { useApolloClient } from '@apollo/client';
import { useCrossContextEvents } from '@admin/hooks';
import OrderQa from '@admin/order-qa';
import './styles/index.less';
// graphql typescript
import {
getOrderReplied as getOrderRepliedType,
getOrderRepliedVariables as getOrderRepliedVariablesType,
} from '@meepshop/types/gqls/admin';
// grphaql import
import { getOrderReplied } from './gqls/index';
// typescript definition
interface PropsType {
namespacesRequired: string[];
orderId: string;
noWrapper: true;
}
// definition
const RefactorOrderQa: NextPage<PropsType> = React.memo(({ orderId }) => {
const [{ messageReplied }, setProps] = useCrossContextEvents<{
closePanel?: boolean;
messageReplied?: boolean | null;
}>(`order-qa/${orderId}`, {});
const client = useApolloClient();
useEffect(() => {
const queryOrderReplied = client
.watchQuery<getOrderRepliedType, getOrderRepliedVariablesType>({
query: getOrderReplied,
variables: {
orderId,
},
})
.subscribe(({ data }) => {
const messageRepliedData = data.viewer?.order?.messageReplied || null;
if (
messageReplied !== undefined &&
messageRepliedData !== null &&
messageReplied !== messageRepliedData
)
setProps({ messageReplied: true });
});
return () => {
queryOrderReplied.unsubscribe();
};
}, [client, messageReplied, orderId, setProps]);
return (
<OrderQa
orderId={orderId}
onClose={() => {
setProps({ closePanel: true });
}}
/>
);
});
RefactorOrderQa.getInitialProps = async ({ query }) => ({
namespacesRequired: ['@meepshop/locales/namespacesRequired'],
orderId: query.orderId as string,
noWrapper: true,
});
export default RefactorOrderQa;
|
within IDEAS.Buildings.Components.Shading.Interfaces;
partial model PartialShading "Window shading partial"
parameter Boolean controlled=true
"if true, shading has a control input"
annotation(Evaluate=true);
parameter Modelica.SIunits.Angle azi
"Window azimuth angle"
annotation(Dialog(group="Window properties"));
Modelica.Blocks.Interfaces.RealInput HDirTil
"Direct solar illuminance on surface" annotation (Placement(
transformation(extent={{-80,30},{-40,70}}), iconTransformation(extent={
{-60,50},{-40,70}})));
Modelica.Blocks.Interfaces.RealInput HSkyDifTil
"Diffuse sky solar illuminance on tilted surface" annotation (Placement(
transformation(extent={{-80,10},{-40,50}}), iconTransformation(extent={{-60,30},
{-40,50}})));
Modelica.Blocks.Interfaces.RealInput HGroDifTil
"Diffuse ground solar illuminance on tilted surface" annotation (Placement(
transformation(extent={{-80,-10},{-40,30}}), iconTransformation(extent={{-60,10},
{-40,30}})));
Modelica.Blocks.Interfaces.RealInput angZen
"Angle of incidence" annotation (
Placement(transformation(extent={{-80,-90},{-40,-50}}),
iconTransformation(extent={{-60,-70},{-40,-50}})));
Modelica.Blocks.Interfaces.RealOutput HShaDirTil
"Shaded direct solar illuminance on surface" annotation (Placement(
transformation(extent={{20,30},{60,70}}), iconTransformation(extent={{
40,50},{60,70}})));
Modelica.Blocks.Interfaces.RealOutput HShaSkyDifTil
"Shaded diffuse sky solar illuminance on tilted surface" annotation (Placement(
transformation(extent={{20,10},{60,50}}), iconTransformation(extent={{40,30},
{60,50}})));
Modelica.Blocks.Interfaces.RealOutput HShaGroDifTil
"Shaded diffuse ground solar illuminance on tilted surface" annotation (Placement(
transformation(extent={{20,-10},{60,30}}), iconTransformation(extent={{40,10},
{60,30}})));
Modelica.Blocks.Interfaces.RealOutput iAngInc
"Angle of incidence after transmittance through (possible) shading"
annotation (Placement(transformation(extent={{20,-70},{60,-30}}),
iconTransformation(extent={{40,-50},{60,-30}})));
Modelica.Blocks.Interfaces.RealInput angInc "Inclination angle" annotation (
Placement(transformation(extent={{-80,-70},{-40,-30}}),
iconTransformation(extent={{-60,-50},{-40,-30}})));
Modelica.Blocks.Interfaces.RealInput angAzi "Azimuth angle" annotation (
Placement(transformation(extent={{-80,-110},{-40,-70}}),
iconTransformation(extent={{-60,-90},{-40,-70}})));
Modelica.Blocks.Interfaces.RealInput Ctrl(min=0, max=1) if controlled
"Control signal between 0 and 1, i.e. 1 is fully closed" annotation (
Placement(transformation(
extent={{20,-20},{-20,20}},
rotation=-90,
origin={-10,-110}), iconTransformation(
extent={{10,-10},{-10,10}},
rotation=-90,
origin={0,-100})));
annotation (Diagram(coordinateSystem(preserveAspectRatio=false,extent={{-100,
-100},{100,100}})), Icon(coordinateSystem(
preserveAspectRatio=true, extent={{-50,-100},{50,100}}), graphics={
Polygon(
points={{-50,80},{0,60},{4,60},{4,-20},{-50,0},{-50,80}},
smooth=Smooth.None,
pattern=LinePattern.None,
fillColor={255,255,170},
fillPattern=FillPattern.Solid,
lineColor={0,0,0}),
Polygon(
points={{4,40},{50,20},{50,-32},{20,-20},{4,-20},{4,40}},
smooth=Smooth.None,
pattern=LinePattern.None,
fillColor={179,179,179},
fillPattern=FillPattern.Solid,
lineColor={0,0,0}),
Line(
points={{0,60},{20,60},{20,80},{50,80}},
color={95,95,95},
smooth=Smooth.None),
Line(
points={{0,-20},{20,-20},{20,-70},{20,-70},{50,-70}},
color={95,95,95},
smooth=Smooth.None),
Line(
points={{0,60},{0,66},{0,100},{50,100}},
color={95,95,95},
smooth=Smooth.None),
Line(
points={{0,-20},{0,-90},{50,-90}},
color={95,95,95},
smooth=Smooth.None),
Line(
points={{4,60},{4,-20}},
color={0,0,0},
thickness=0.5,
smooth=Smooth.None)}),
Documentation(revisions="<html>
<ul>
<li>
July 18, 2016 by Filip Jorissen:<br/>
Cleaned up implementation and documentation.
</li>
</ul>
</html>", info="<html>
<p>Partial model for shading computations.</p>
</html>"));
end PartialShading;
|
import { UseFormReturn } from "react-hook-form"
import { z } from "zod"
import { InputControl } from "../components/input-control"
import { TextareaControl } from "../components/textarea-control"
export const ContactMessageSchema = z.object({
full_name: z.string().trim().min(1, "Please enter your name."),
email: z.string().trim().min(1, "A valid email address is required.").email(),
message_text: z.string().trim().min(1, "Enter the text of your message."),
})
export type ContactMessageData = z.infer<typeof ContactMessageSchema>
interface ContactFormProps {
form: UseFormReturn<ContactMessageData>
onSubmit: (args: ContactMessageData) => void
}
export function ContactForm({ form, onSubmit }: ContactFormProps) {
const { register, reset, handleSubmit, formState } = form
const { errors: formErrors, isSubmitting } = formState
const submit = (data: ContactMessageData) => {
// formState.isValid is always false
if (formErrors.full_name || formErrors.email || formErrors.message_text) {
return
}
onSubmit(data)
reset()
}
return (
<form onSubmit={handleSubmit(submit)}>
<div className="flex flex-wrap mx-[-16px]">
<div className="w-full md:w-1/2 px-4">
<InputControl
name="full_name"
type="text"
label="Full Name"
register={register("full_name")}
error={formErrors.full_name}
/>
</div>
<div className="w-full md:w-1/2 px-4">
<InputControl
name="email"
type="email"
label="Email"
register={register("email")}
error={formErrors.email}
/>
</div>
<div className="w-full px-4">
<TextareaControl
name="message_text"
label="Message"
register={register("message_text")}
rows={5}
error={formErrors.message_text}
/>
</div>
<div className="w-full px-4">
<button
type="submit"
className="text-base font-medium text-white bg-primary py-4 px-9 hover:bg-opacity-80 hover:shadow-signUp rounded-md transition duration-300 ease-in-out"
disabled={isSubmitting}
>
Submit
</button>
</div>
</div>
</form>
)
}
|
package kopo.poly.controller;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.transaction.Transactional;
import kopo.poly.dto.MsgDTO;
import kopo.poly.dto.UserFollowDTO;
import kopo.poly.dto.UserInfoDTO;
import kopo.poly.service.INoticeService;
import kopo.poly.service.IUserInfoService;
import kopo.poly.util.CmmUtil;
import kopo.poly.util.EncryptUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.*;
@Slf4j
@RequestMapping(value = "/user")
@RequiredArgsConstructor
@Controller
public class UserInfoController {
// @RequiredArgsConstructor 를 통해 메모리에 올라간 서비스 객체를 Controller에서 사용할 수 있게 주입함
private final IUserInfoService userInfoService;
private final INoticeService noticeService;
private final AmazonS3 s3Client;
private final String bucketName;
/**
* 회원가입 화면으로 이동
*/
@GetMapping(value = "userRegForm")
public String userRegForm() {
log.info(this.getClass().getName() + ".user/userRegForm Start!");
log.info(this.getClass().getName() + ".user/userRegForm End!");
return "user/userRegForm";
}
/**
* 회원가입 전 아이디 중복체크하기(Ajax를 통해 입력한 아이디 정보 받음)
*/
@ResponseBody
@PostMapping(value = "getUserIdExists")
public UserInfoDTO getUserExists(HttpServletRequest request) throws Exception {
log.info(this.getClass().getName() + ".getUserIdExists Start!");
String userId = CmmUtil.nvl(request.getParameter("userId"));
log.info("userId : " + userId);
// Builder 통한 값 저장
UserInfoDTO pDTO = UserInfoDTO.builder().userId(userId).build();
// 회원아이디를 통해 중복된 아이디인지 조회
UserInfoDTO rDTO = Optional.ofNullable(userInfoService.getUserIdExists(pDTO))
.orElseGet(() -> UserInfoDTO.builder().build());
log.info(this.getClass().getName() + ".getUserIdExists End!");
return rDTO;
}
/**
* 회원가입 로직 처리
*/
@ResponseBody
@PostMapping(value = "insertUserInfo")
public MsgDTO insertUserInfo(MultipartHttpServletRequest request) throws Exception {
log.info(this.getClass().getName() + ".insertUserInfo Start!");
String msg; // 회원가입 결과에 대한 메시지를 전달할 변수
String userId = CmmUtil.nvl(request.getParameter("userId"));
String userName = CmmUtil.nvl(request.getParameter("userName"));
String password = CmmUtil.nvl(request.getParameter("password"));
String email = CmmUtil.nvl(request.getParameter("email"));
log.info("userId : " + userId);
log.info("userName : " + userName);
log.info("password : " + password);
log.info("email : " + email);
MultipartFile file = request.getFile("profileImage");
String imageUrl = "/assets/img/thumbnail.png";
if (file != null && !file.isEmpty()) {
try {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String fileName = "profiles/" + userId + "_" + UUID.randomUUID().toString() + "." + extension;
s3Client.putObject(new PutObjectRequest(bucketName, fileName, file.getInputStream(), null)
.withCannedAcl(CannedAccessControlList.PublicRead));
imageUrl = s3Client.getUrl(bucketName, fileName).toString();
} catch (Exception e) {
log.error("파일 업로드 실패: " + e.getMessage());
return MsgDTO.builder().result(0).msg("파일 업로드 실패").build();
}
}
// 웹 (회원정보 입력화면)에서 받는 정보를 저장할 변수를 메모리에 올리기
UserInfoDTO pDTO = UserInfoDTO.builder()
.userId(userId)
.userName(userName)
.password(EncryptUtil.encHashSHA256(password))
.email(EncryptUtil.encAES128CBC(email))
.regId(userId)
.chgId(userId)
.profilePath(imageUrl)
.build();
// 회원가입 서비스 호출하여 결과 받기
int res = userInfoService.insertUserInfo(pDTO);
log.info("회원가입 결과(res) : " + res);
if (res == 1) {
msg = "회원가입되었습니다.";
} else if (res == 2) {
msg = "이미 가입된 아이디입니다.";
} else if (res == 3) {
msg = "이미 가입된 이메일입니다.";
} else {
msg = "오류로 인해 회원가입이 실패하였습니다.";
}
// 결과 메시지 전달하기
MsgDTO dto = MsgDTO.builder().result(res).msg(msg).build();
log.info(this.getClass().getName() + ".insertUserInfo End!");
return dto;
}
/**
* 로그인을 위한 입력 화면으로 이동
*/
@GetMapping(value = "login")
public String login() {
log.info(this.getClass().getName() + ".user/login Start!");
log.info(this.getClass().getName() + ".user/login End!");
return "user/login";
}
/**
* 로그인 처리 및 결과 알려주는 화면으로 이동
*/
@ResponseBody
@PostMapping(value = "loginProc")
public MsgDTO loginProc(HttpServletRequest request, HttpSession session) throws Exception {
log.info(this.getClass().getName() + ".loginProc Start!");
String msg; // 로그인 결과에 대한 메시지를 전달할 변수
String userId = CmmUtil.nvl(request.getParameter("userId"));
String password = CmmUtil.nvl(request.getParameter("password"));
log.info("userId : " + userId);
log.info("password : " + password);
// 웹(회원정보 입력화면)에서 받는 정보를 저장할 변수를 메모리에 올리기
UserInfoDTO pDTO = UserInfoDTO.builder()
.userId(userId)
.password(EncryptUtil.encHashSHA256(password)).build();
// 로그인을 위해 아이디와 비밀번호가 일치하는지 확인하기 위한 usreInfoService 호춣하기
int res = userInfoService.getUserLogin(pDTO);
UserInfoDTO rDTO = Optional.ofNullable(userInfoService.getUserIdExists(pDTO))
.orElseGet(() -> UserInfoDTO.builder().build());
log.info("res : " + res);
/*
* 스프링에서 세션을 사용하기 위해서는 함수명의 파라미터에 HttpSession session 존재해야 한다.
* 세션은 톰켓의 메모리에 저장되기 때문에 url마다 전달하는게 필요하지 않고,
* 그냥 메모리에서 부르면 되기 때문에 jsp, controller에서 쉽게 불러서 쓸 수 있다.
*/
if (res == 1) { // 로그인 성공
/*
* 세션에 회원아이디 저장하기, 추후 로그인여부를 체크하기 위해 세션에 값이 존재하는지 체크한다.
* 일반적으로 세션에 저장되는 키는 대문자로 입력하며, 앞에 SS를 붙인다.
*
* Session 단어에서 SS를 가져온 것이다.
*/
msg = "로그인이 성공했습니다.";
session.setAttribute("SS_USER_ID", userId);
session.setAttribute("SS_USER_NAME", rDTO.userName());
log.info("SS_USER_ID : " + rDTO.userId());
log.info("SS_USER_NAME : " + rDTO.userName());
} else {
msg = "아이디와 비밀번호가 올바르지 않습니다.";
}
// 결과 메시지 전달하기
MsgDTO dto = MsgDTO.builder().result(res).msg(msg).build();
log.info(this.getClass().getName() + "loginProc End!");
return dto;
}
/**
* 로그인 성공 페이지 이동
*/
@GetMapping(value = "loginSuccess")
public String loginSuccess() {
log.info(this.getClass().getName() + ".user/loginSuccess Start!");
log.info(this.getClass().getName() + ".user/loginSuccess End!");
return "user/loginSuccess";
}
/**
* 회원탈퇴 페이지
*/
@GetMapping(value = "deleteUser")
public String deleteUser() {
log.info(this.getClass().getName() + ".user/deleteUser Start!");
log.info(this.getClass().getName() + ".user/deleteUser End!");
return "user/deleteUser";
}
/**
* 회원탈퇴 과정
*/
@ResponseBody
@GetMapping(value = "deleteUserProc")
public ResponseEntity<?> deleteUserProc(HttpSession session) throws Exception {
log.info(this.getClass().getName() + ".user/deleteUserProc Start!");
String userId = (String) session.getAttribute("SS_USER_ID");
log.info("userId : " + userId);
UserInfoDTO userInfo = userInfoService.getUserInfo(userId);
if (userInfo != null && userInfo.profilePath() != null && !userInfo.profilePath().isEmpty()) {
try {
// 프로필 이미지 경로에서 파일 이름 추출
String fileName = userInfo.profilePath().substring(userInfo.profilePath().lastIndexOf("/") + 1);
// S3에서 파일 삭제
s3Client.deleteObject(bucketName, "profiles/" + fileName);
log.info("S3 버킷에서 파일 삭제 성공: " + fileName);
} catch (Exception e) {
log.error("S3 버킷에서 파일 삭제 실패: " + e.getMessage());
}
}
UserInfoDTO pDTO = UserInfoDTO.builder().userId(userId).build();
// 회원가입 서비스 호출하여 결과 받기
userInfoService.deleteUserProc(pDTO);
log.info(this.getClass().getName() + ".user/deleteUserProc End!");
return ResponseEntity.ok().body("회원탈퇴 성공!");
}
/**
* 유저 프로필
*/
@GetMapping(value = "userProfile/{userId}") // URL 경로 변경
public String userProfile(@PathVariable("userId") String userId, HttpSession session, ModelMap model) throws Exception {
log.info(this.getClass().getName() + ".user/userProfile Start!");
// 세션에서 로그인한 사용자의 ID를 가져옵니다.
String ssUserId = (String) session.getAttribute("SS_USER_ID");
// URL에서 받은 userId를 사용하여 사용자 정보를 가져옵니다.
UserInfoDTO dto = userInfoService.getUserInfo(userId);
// 팔로우 상태를 확인하기 위한 DTO 생성
UserFollowDTO pDTO = UserFollowDTO.builder().followingId(userId).followerId(ssUserId).build();
long countByFollowerId = userInfoService.countByFollowerId(userId);
long countByFollowingId = userInfoService.countByFollowingId(userId);
long countByUserId = noticeService.countByUserId(userId);
// 팔로우 상태 확인
boolean followStatus = userInfoService.getFollowInfo(pDTO);
String existsYn = followStatus ? "Y" : "N";
log.info("countByFollowerId : " + countByFollowerId);
log.info("countByFollowingId : " + countByFollowingId);
log.info("countByUserId : " + countByUserId);
// 모델에 사용자 정보와 팔로우 상태를 추가
model.addAttribute("dto", dto);
model.addAttribute("existsYn", existsYn);
model.addAttribute("countByFollowerId", countByFollowerId);
model.addAttribute("countByFollowingId", countByFollowingId);
model.addAttribute("countByUserId", countByUserId);
log.info(this.getClass().getName() + ".user/userProfile End!");
return "user/userProfile";
}
/**
* 유저 프로필 설정
*/
@GetMapping(value = "userProfileEdit")
public String userProfileEdit(HttpSession session, ModelMap model) throws Exception {
log.info(this.getClass().getName() + ".user/userProfileEdit Start!");
String userId = (String) session.getAttribute("SS_USER_ID");
UserInfoDTO pDTO = userInfoService.getUserInfo(userId);
String profilePath = pDTO.profilePath() != null && !pDTO.profilePath().isEmpty() ? pDTO.profilePath() : "/assets/img/profile.png";
log.info("profilePath : " + profilePath);
log.info("userName : " + pDTO.userName());
model.addAttribute("profilePath", profilePath);
model.addAttribute("pDTO", pDTO);
log.info(this.getClass().getName() + ".user/userProfileEdit End!");
return "user/userProfileEdit";
}
/**
* 팔로우 추가
*/
@ResponseBody
@PostMapping(value = "addFollow")
public MsgDTO addFollow(HttpServletRequest request, HttpSession session, ModelMap model) throws Exception {
log.info(this.getClass().getName() + ".user/addFollow Start!");
MsgDTO dto = null;
String msg = "";
try {
String followUserId = CmmUtil.nvl(request.getParameter("followUserId"));
String userId = (String) session.getAttribute("SS_USER_ID");
log.info("followUserId : " + followUserId);
log.info("userId : " + userId);
UserFollowDTO pDTO = UserFollowDTO.builder().followingId(followUserId).followerId(userId).build();
userInfoService.addFollower(pDTO);
msg = "팔로우 추가 완료!";
} catch (Exception e) {
msg = "실패하였습니다. : " + e.getMessage();
log.info(e.toString());
e.printStackTrace();
} finally {
dto = MsgDTO.builder().msg(msg).build();
log.info(this.getClass().getName() + ".user/addFollow End!");
}
return dto;
}
/**
* 팔로우 제거
*/
@ResponseBody
@PostMapping(value = "removeFollow")
public MsgDTO removeFollow(HttpServletRequest request, HttpSession session) {
log.info(this.getClass().getName() + ".removeFollow Start!");
String msg = ""; // 메시지 내용
MsgDTO dto = null; // 결과 메시지 구조
try {
String followUserId = CmmUtil.nvl(request.getParameter("followUserId"));
String userId = (String) session.getAttribute("SS_USER_ID");
log.info("followUserId : " + followUserId);
log.info("userId : " + userId);
UserFollowDTO pDTO = UserFollowDTO.builder().followingId(followUserId).followerId(userId).build();
userInfoService.removeFollower(pDTO);
msg = "삭제되었습니다.";
} catch (Exception e) {
msg = "실패하였습니다. : " + e.getMessage();
log.info(e.toString());
e.printStackTrace();
} finally {
// 결과 메시지 전달하기
dto = MsgDTO.builder().msg(msg).build();
log.info(this.getClass().getName() + ".removeFollow End!");
}
return dto;
}
/**
* 아이디 찾기 페이지
*/
@GetMapping(value = "searchUserId")
public String searchUserId() {
log.info(this.getClass().getName() + ".user/searchUserId Start!");
log.info(this.getClass().getName() + ".user/searchUserId End!");
return "user/searchUserId";
}
/**
* 아이디 찾기
*/
@ResponseBody
@PostMapping(value = "searchUserIdProc")
public MsgDTO searchUserIdProc(HttpServletRequest request, ModelMap model) throws Exception {
log.info(this.getClass().getName() + ".user/searchUserIdProc Start!");
String msg;
String userName = CmmUtil.nvl(request.getParameter("userName"));
String email = CmmUtil.nvl(request.getParameter("email"));
log.info("userName : " + userName);
log.info("email : " + email);
UserInfoDTO pDTO = UserInfoDTO.builder()
.userName(userName)
.email(EncryptUtil.encAES128CBC(email))
.build();
String res = userInfoService.searchUserIdProc(pDTO);
if (!Objects.equals(res, "")) {
msg = userName + " 회원님의 아이디는 " + res + "입니다.";
} else {
msg = "회원정보가 일치하지 않습니다.";
}
MsgDTO dto = MsgDTO.builder().msg(msg).build();
// model.addAttribute("rDTO", rDTO);
log.info(this.getClass().getName() + ".user/searchUserIdProc End!");
return dto;
}
/**
* 이메일 중복찾기
*/
@ResponseBody
@PostMapping(value = "getEmailExists")
public UserInfoDTO getEmailExists(HttpServletRequest request) throws Exception {
log.info(this.getClass().getName() + ".getEmailExists Start!");
String email = CmmUtil.nvl(request.getParameter("email"));
log.info("email : " + email);
UserInfoDTO pDTO = UserInfoDTO.builder()
.email(EncryptUtil.encAES128CBC(email))
.build();
UserInfoDTO rDTO = Optional.ofNullable(userInfoService.getEmailExists(pDTO))
.orElseGet(() -> UserInfoDTO.builder().build());
log.info(this.getClass().getName() + ".getEmailExists End!");
return rDTO;
}
/**
* 비밀번호 찾기 페이지
*/
@GetMapping(value = "searchPassword")
public String searchPassword(HttpSession session) {
log.info(this.getClass().getName() + ".user/searchPassword Start!");
session.setAttribute("USER_ID", "");
session.removeAttribute("USER_ID");
log.info(this.getClass().getName() + ".user/searchPassword End!");
return "user/searchPassword";
}
/**
* 비밀번호 찾기
*/
@PostMapping(value = "searchPasswordProc")
public String searchPasswordProc(HttpServletRequest request, ModelMap model, HttpSession session) throws Exception {
log.info(this.getClass().getName() + ".user/searchPasswordProc start!");
String userId = CmmUtil.nvl(request.getParameter("userId"));
String userName = CmmUtil.nvl(request.getParameter("userName"));
String email = CmmUtil.nvl(request.getParameter("email"));
log.info("userId : " + userId);
log.info("userName : " + userName);
log.info("email : " + email);
UserInfoDTO pDTO = UserInfoDTO.builder()
.userId(userId)
.userName(userName)
.email(EncryptUtil.encAES128CBC(email))
.build();
UserInfoDTO rDTO = Optional.ofNullable(userInfoService.searchPasswordProc(pDTO))
.orElseGet(() -> UserInfoDTO.builder().build());
model.addAttribute("rDTO", rDTO);
session.setAttribute("USER_ID", userId);
log.info(this.getClass().getName() + ".user/searchPasswordProc end!");
return "user/newPassword";
}
/**
* 닉네임 변경 페이지
*/
@GetMapping(value = "changeUserName")
public String changeUserName() throws Exception {
log.info(this.getClass().getName() + ".changeUserName Start!");
return "user/changeUserName";
}
/**
* 닉네임 변경하기
*/
@ResponseBody
@PostMapping(value = "newUserNameProc")
public MsgDTO newUserNameProc(HttpServletRequest request, HttpSession session) throws Exception {
log.info(this.getClass().getName() + ".newUserNameProc Start!");
MsgDTO dto = null;
String msg = "";
try {
String userId = (String) session.getAttribute("SS_USER_ID");
String userName = request.getParameter("userName");
log.info("userId : " + userId);
log.info("userName : " + userName);
UserInfoDTO pDTO = UserInfoDTO.builder()
.userId(userId)
.userName(userName)
.build();
userInfoService.newUserNameProc(pDTO);
session.setAttribute("SS_USER_NAME", userName);
msg = "닉네임이 재설정되었습니다.";
} catch (Exception e) {
msg = "시스템 문제로 닉네임 변경이 실패하였습니다." + e.getMessage();
log.info(e.toString());
e.printStackTrace();
} finally {
// 결과 메시지 전달하기
dto = MsgDTO.builder().msg(msg).build();
}
log.info(this.getClass().getName() + ".newUserNameProc End!");
return dto;
}
/**
* 비밀번호 변경
*/
@ResponseBody
@PostMapping(value = "newPasswordProc")
public MsgDTO newPasswordProc(HttpServletRequest request, HttpSession session) throws Exception {
log.info(this.getClass().getName() + ".user/newPasswordProc Start!");
String msg = "";
MsgDTO dto = null;
String userId = CmmUtil.nvl((String) session.getAttribute("USER_ID"));
if (userId.length() > 0) {
try {
String password = CmmUtil.nvl(request.getParameter("password"));
log.info("password : " + password);
UserInfoDTO pDTO = UserInfoDTO.builder()
.userId(userId)
.password(EncryptUtil.encHashSHA256(password))
.build();
userInfoService.newPasswordProc(pDTO);
session.setAttribute("USER_ID", "");
session.removeAttribute("USER_ID");
msg = "비밀번호가 재설정되었습니다.";
} catch (Exception e) {
msg = "실패하였습니다. : " + e.getMessage();
log.info(e.toString());
e.printStackTrace();
} finally {
// 결과 메시지 전달하기
dto = MsgDTO.builder().msg(msg).build();
log.info(this.getClass().getName() + ".newPasswordProc End!");
}
}
return dto;
}
/**
* 특정 유저의 팔로우 리스트
*/
@Transactional
@GetMapping(value = "followList/{userId}")
public String followList(@PathVariable("userId") String userId, ModelMap model)
throws Exception {
log.info(this.getClass().getName() + ".followList Start!");
UserInfoDTO rDTO = userInfoService.getUserInfo(userId);
List<UserFollowDTO> rList = Optional.ofNullable(userInfoService.getFollowList(userId))
.orElseGet(ArrayList::new);
log.info("rList : " + rList);
model.addAttribute("profileUserName", rDTO.userName());
model.addAttribute("rList", rList);
log.info(this.getClass().getName() + ".followList End!");
return "user/followList";
}
/**
* 특정 유저의 팔로잉 리스트
*/
@Transactional
@GetMapping(value = "followingList/{userId}")
public String followingList(@PathVariable("userId") String userId, ModelMap model)
throws Exception {
log.info(this.getClass().getName() + ".followingList Start!");
UserInfoDTO rDTO = userInfoService.getUserInfo(userId);
List<UserFollowDTO> rList = Optional.ofNullable(userInfoService.getFollowingList(userId))
.orElseGet(ArrayList::new);
log.info("rList : " + rList);
model.addAttribute("profileUserName", rDTO.userName());
model.addAttribute("rList", rList);
log.info(this.getClass().getName() + ".followingList End!");
return "user/followingList";
}
}
|
import { PlaceOrder } from "../../../src/application/use-cases/place-order/place-order";
import { ItemsRepositoryInMemory } from "../../../src/infra/repository/in-memory/items-repository-in-memory";
import { CouponsRepositoryInMemory } from "../../../src/infra/repository/in-memory/coupons-repository-in-memory";
import { OrdersRepositoryInMemory } from "../../../src/infra/repository/in-memory/orders-repository-in-memory";
import { PlaceOrderInput } from "../../../src/application/use-cases/place-order/place-order-input";
import { PgPromiseConnectionAdapter } from "../../../src/infra/database/pg-promise-connection-adapter";
import { ItemsRepositoryDatabase } from "../../../src/infra/repository/database/items-repository-database";
import { ItemsRepositoryPrisma } from "../../../src/infra/repository/database/items-repository-prisma";
import { CouponsRepositoryPrisma } from "../../../src/infra/repository/database/coupons-repository-prisma";
import { OrdersRepositoryPrisma } from "../../../src/infra/repository/database/orders-repository-prisma";
import { PrismaConnectionAdapter } from "../../../src/infra/database/prisma-connection-adapter";
import { PrismaRepositoryFactory } from "../../../src/infra/factory/prisma-repository-factory";
import { InMemoryRepositoryFactory } from "../../../src/infra/factory/in-memory-repository-factory";
import { GetOrder } from "../../../src/application/query/get-order";
import { OrderDAODatabase } from "../../../src/infra/dao/order-dao-database";
import { Broker } from "../../../src/infra/broker/broker";
let placeOrder: PlaceOrder;
let getOrder: GetOrder;
beforeEach(() => {
const connection = new PrismaConnectionAdapter();
const repositoryFactory = new PrismaRepositoryFactory();
const orderDAO = new OrderDAODatabase(connection);
const broker = new Broker();
placeOrder = new PlaceOrder(repositoryFactory, broker);
getOrder = new GetOrder(orderDAO);
});
test("Deve obter um pedido pelo código", async () => {
// Request/Input/DTO (Dados de entrada) - Dados de entrada
const input = {
cpf: "839.435.452-10",
orderItems: [
{ idItem: 1, quantity: 1 },
{ idItem: 2, quantity: 1 },
{ idItem: 3, quantity: 3 },
],
date: new Date("2022-06-05"),
coupon: "VALE5",
};
// Response/Output (Dados de saída)
const placeOrderOutput = await placeOrder.execute(input);
const getOrderOutput = await getOrder.execute({
code: placeOrderOutput.code,
});
expect(getOrderOutput.code).toBe("202200000001");
expect(getOrderOutput.total).toBe(75.65);
});
afterEach(async () => {
const prisma = new PrismaConnectionAdapter();
await prisma.connection.$executeRawUnsafe("DELETE FROM order_items");
await prisma.connection.$executeRawUnsafe("DELETE FROM orders");
await prisma.connection.$disconnect();
});
|
import React, { useEffect, useState } from 'react'
import './inex.scss'
import SpeakerImg from '../../../imgs/Frame 694.png'
const EnhanceYourMusicExperience = () => {
const calculateTimeLeft = () => {
const now = new Date();
const flashSaleEndDate = new Date('2023-12-31T23:59:59');
const difference = flashSaleEndDate - now;
let timeLeft = {};
if (difference > 0) {
timeLeft = {
days: Math.floor(difference / (1000 * 60 * 60 * 24)),
hours: Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes: Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)),
seconds: Math.floor((difference % (1000 * 60)) / 1000),
};
}
return timeLeft;
};
const [timeLeft, setTimeLeft] = useState(calculateTimeLeft());
useEffect(() => {
const timer = setTimeout(() => {
setTimeLeft(calculateTimeLeft());
}, 1000);
return () => clearTimeout(timer);
}, [timeLeft]);
return (
<section className='EnhanceYourMusicExperience'>
<div className='EnhanceYourMusicExperience_container'>
<div className='txt'>
<p style={{ color: '#00ff66', fontWeight: '600' }}>Categories</p>
<h2 style={{ color: 'white', fontSize: '48px' }}>Enhance Your Music Experience</h2>
<div className='ends'>
<span className='col'>
<h2>{timeLeft.days}</h2>
<p>Days</p>
</span>
<span className='col'>
<h2>{timeLeft.hours}</h2>
<p>Hours</p>
</span>
<span className='col'>
<h2>{timeLeft.minutes}</h2>
<p>Minutes</p>
</span>
<span className='col'>
<h2>{timeLeft.seconds}</h2>
<p>Seconds</p>
</span>
</div>
<button>Buy Now!</button>
</div>
<div className='EnhanceYourMusicExperience_img'>
<img src={SpeakerImg} alt="" />
{/* <div className='bg'></div> */}
</div>
</div>
</section>
)
}
export default EnhanceYourMusicExperience
|
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'CategoryBook/category_books.dart';
class CategoriesScreen extends StatefulWidget {
@override
_CategoriesScreenState createState() => _CategoriesScreenState();
}
class _CategoriesScreenState extends State<CategoriesScreen> {
List<String>? categories; // Nullable list to hold categories
@override
void initState() {
super.initState();
fetchCategories();
}
Future<void> fetchCategories() async {
setState(() {
categories = null; // Set categories to null to trigger loading indicator
});
try {
QuerySnapshot querySnapshot = await FirebaseFirestore.instance.collection('categories').get();
List<String> categoryNames = [];
querySnapshot.docs.forEach((doc) {
categoryNames.add(doc['categoryName'] as String); // Explicitly cast to String
});
setState(() {
categories = categoryNames;
});
} catch (e) {
print('Error fetching categories: $e');
setState(() {
categories = []; // Set categories to empty list if an error occurs
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Categories'),
),
body: categories == null
? Center(child: CircularProgressIndicator()) // Show loading indicator
: ListView.separated(
itemCount: categories!.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.category_outlined),
title: Text(categories![index]),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CategoryBooks(categoryName: categories![index]),
),
);
},
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
_deleteCategory(categories![index]);
},
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_showAddCategoryDialog(context);
},
child: Icon(Icons.add),
backgroundColor: Colors.orange, // Customize the color if needed
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat, // Adjust the location as needed
);
}
// Method to show dialog for adding a category
void _showAddCategoryDialog(BuildContext context) {
String newCategoryName = '';
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Add Category'),
content: TextField(
onChanged: (value) {
newCategoryName = value;
},
decoration: InputDecoration(hintText: 'Enter Category Name'),
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Cancel'),
),
TextButton(
onPressed: () {
addCategory(newCategoryName); // Call the function to add the category
Navigator.of(context).pop();
},
child: Text('OK'),
),
],
);
},
);
}
void addCategory(String categoryName) {
FirebaseFirestore.instance.collection('categories').add({'categoryName': categoryName}).then((categoryDoc) {
// Add a dummy document to create the "books" collection inside the category document
categoryDoc.collection('Book Collection').doc('Books').set({'Name': 'name','Author':'author'});
}).catchError((error) {
print('Error adding category: $error');
}).then((_) {
fetchCategories(); // Refresh the list of categories
});
}
void _deleteCategory(String categoryName) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Delete Category'),
content: Text('Are you sure you want to delete this category?'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Cancel'),
),
TextButton(
onPressed: () {
_performDeleteCategory(categoryName);
Navigator.of(context).pop();
},
child: Text('Delete'),
),
],
);
},
);
}
void _performDeleteCategory(String categoryName) {
FirebaseFirestore.instance.collection('categories').where('categoryName', isEqualTo: categoryName).get().then((querySnapshot) {
querySnapshot.docs.forEach((doc) {
doc.reference.delete().then((_) {
// Delete the subcollection
FirebaseFirestore.instance.collection('categories').doc(doc.id).collection('Book Collection').doc('Books').delete().then((_) {
print('Category deleted successfully');
fetchCategories(); // Refresh the list of categories
}).catchError((error) {
print('Error deleting subcollection: $error');
});
}).catchError((error) {
print('Error deleting category: $error');
});
});
}).catchError((error) {
print('Error fetching category to delete: $error');
});
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.