text
stringlengths 184
4.48M
|
---|
/*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <mutex>
#include "oneflow/core/device/cuda_util.h"
#include "oneflow/core/common/singleton.h"
#include "oneflow/core/hardware/node_device_descriptor_manager.h"
#include "oneflow/core/hardware/cuda_device_descriptor.h"
#include "oneflow/core/rpc/include/global_process_ctx.h"
#include "oneflow/core/job/env_global_objects_scope.h"
#include "oneflow/core/job/lazy_mode.h"
#include "oneflow/core/platform/include/pthread_fork.h"
#include "oneflow/core/ep/cuda/cuda_stream.h"
#include "oneflow/core/vm/vm_util.h"
#ifdef WITH_CUDA
#include <cuda.h>
#endif // WITH_CUDA
#ifdef WITH_ROCM
#include <hip/hip_runtime.h>
#endif // WITH_ROCM
namespace oneflow {
#ifdef WITH_CUDA
const char* CublasGetErrorString(cublasStatus_t error) {
switch (error) {
case CUBLAS_STATUS_SUCCESS: return "CUBLAS_STATUS_SUCCESS";
case CUBLAS_STATUS_NOT_INITIALIZED: return "CUBLAS_STATUS_NOT_INITIALIZED";
case CUBLAS_STATUS_ALLOC_FAILED: return "CUBLAS_STATUS_ALLOC_FAILED";
case CUBLAS_STATUS_INVALID_VALUE: return "CUBLAS_STATUS_INVALID_VALUE";
case CUBLAS_STATUS_ARCH_MISMATCH: return "CUBLAS_STATUS_ARCH_MISMATCH";
case CUBLAS_STATUS_MAPPING_ERROR: return "CUBLAS_STATUS_MAPPING_ERROR";
case CUBLAS_STATUS_EXECUTION_FAILED: return "CUBLAS_STATUS_EXECUTION_FAILED";
case CUBLAS_STATUS_INTERNAL_ERROR: return "CUBLAS_STATUS_INTERNAL_ERROR";
#if CUDA_VERSION >= 6000
case CUBLAS_STATUS_NOT_SUPPORTED: return "CUBLAS_STATUS_NOT_SUPPORTED";
#endif
#if CUDA_VERSION >= 6050
case CUBLAS_STATUS_LICENSE_ERROR: return "CUBLAS_STATUS_LICENSE_ERROR";
#endif
default: return "Unknown cublas status";
}
}
const char* CurandGetErrorString(curandStatus_t error) {
switch (error) {
case CURAND_STATUS_SUCCESS: return "CURAND_STATUS_SUCCESS";
case CURAND_STATUS_VERSION_MISMATCH: return "CURAND_STATUS_VERSION_MISMATCH";
case CURAND_STATUS_NOT_INITIALIZED: return "CURAND_STATUS_NOT_INITIALIZED";
case CURAND_STATUS_ALLOCATION_FAILED: return "CURAND_STATUS_ALLOCATION_FAILED";
case CURAND_STATUS_TYPE_ERROR: return "CURAND_STATUS_TYPE_ERROR";
case CURAND_STATUS_OUT_OF_RANGE: return "CURAND_STATUS_OUT_OF_RANGE";
case CURAND_STATUS_LENGTH_NOT_MULTIPLE: return "CURAND_STATUS_LENGTH_NOT_MULTIPLE";
case CURAND_STATUS_DOUBLE_PRECISION_REQUIRED: return "CURAND_STATUS_DOUBLE_PRECISION_REQUIRED";
case CURAND_STATUS_LAUNCH_FAILURE: return "CURAND_STATUS_LAUNCH_FAILURE";
case CURAND_STATUS_PREEXISTING_FAILURE: return "CURAND_STATUS_PREEXISTING_FAILURE";
case CURAND_STATUS_INITIALIZATION_FAILED: return "CURAND_STATUS_INITIALIZATION_FAILED";
case CURAND_STATUS_ARCH_MISMATCH: return "CURAND_STATUS_ARCH_MISMATCH";
case CURAND_STATUS_INTERNAL_ERROR: return "CURAND_STATUS_INTERNAL_ERROR";
default: return "Unknown curand status";
}
}
const char* CuFFTGetErrorString(cufftResult_t error) {
switch (error) {
case CUFFT_SUCCESS: return "CUFFT_SUCCESS";
case CUFFT_INVALID_PLAN: return "CUFFT_INVALID_PLAN";
case CUFFT_ALLOC_FAILED: return "CUFFT_ALLOC_FAILED";
case CUFFT_INVALID_TYPE: return "CUFFT_INVALID_TYPE";
case CUFFT_INVALID_VALUE: return "CUFFT_INVALID_VALUE";
case CUFFT_INTERNAL_ERROR: return "CUFFT_INTERNAL_ERROR";
case CUFFT_EXEC_FAILED: return "CUFFT_EXEC_FAILED";
case CUFFT_SETUP_FAILED: return "CUFFT_SETUP_FAILED";
case CUFFT_INVALID_SIZE: return "CUFFT_INVALID_SIZE";
case CUFFT_UNALIGNED_DATA: return "CUFFT_UNALIGNED_DATA";
case CUFFT_INCOMPLETE_PARAMETER_LIST: return "CUFFT_INCOMPLETE_PARAMETER_LIST";
case CUFFT_INVALID_DEVICE: return "CUFFT_INVALID_DEVICE";
case CUFFT_PARSE_ERROR: return "CUFFT_PARSE_ERROR";
case CUFFT_NO_WORKSPACE: return "CUFFT_NO_WORKSPACE";
case CUFFT_NOT_IMPLEMENTED: return "CUFFT_NOT_IMPLEMENTED";
case CUFFT_NOT_SUPPORTED: return "CUFFT_NOT_SUPPORTED";
default: return "Unknown cufft status";
}
}
#if CUDA_VERSION >= 11000
const char* CusovlerGetErrorString(cusolverStatus_t error) {
switch (error) {
case CUSOLVER_STATUS_SUCCESS: return "CUSOLVER_STATUS_SUCCESS";
case CUSOLVER_STATUS_NOT_INITIALIZED: return "CUSOLVER_STATUS_NOT_INITIALIZED";
case CUSOLVER_STATUS_ALLOC_FAILED: return "CUSOLVER_STATUS_ALLOC_FAILED";
case CUSOLVER_STATUS_INVALID_VALUE: return "CUSOLVER_STATUS_INVALID_VALUE";
case CUSOLVER_STATUS_ARCH_MISMATCH: return "CUSOLVER_STATUS_ARCH_MISMATCH";
case CUSOLVER_STATUS_EXECUTION_FAILED: return "CUSOLVER_STATUS_EXECUTION_FAILED";
case CUSOLVER_STATUS_INTERNAL_ERROR: return "CUSOLVER_STATUS_INTERNAL_ERROR";
case CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED:
return "CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED";
default: return "Unknown cusolver status";
}
}
#endif
#if CUDA_VERSION >= 10020
const char* NvjpegGetErrorString(nvjpegStatus_t error) {
switch (error) {
case NVJPEG_STATUS_SUCCESS: return "NVJPEG_STATUS_SUCCESS";
case NVJPEG_STATUS_NOT_INITIALIZED: return "NVJPEG_STATUS_NOT_INITIALIZED";
case NVJPEG_STATUS_INVALID_PARAMETER: return "NVJPEG_STATUS_INVALID_PARAMETER";
case NVJPEG_STATUS_BAD_JPEG: return "NVJPEG_STATUS_BAD_JPEG";
case NVJPEG_STATUS_JPEG_NOT_SUPPORTED: return "NVJPEG_STATUS_JPEG_NOT_SUPPORTED";
case NVJPEG_STATUS_ALLOCATOR_FAILURE: return "NVJPEG_STATUS_ALLOCATOR_FAILURE";
case NVJPEG_STATUS_EXECUTION_FAILED: return "NVJPEG_STATUS_EXECUTION_FAILED";
case NVJPEG_STATUS_ARCH_MISMATCH: return "NVJPEG_STATUS_ARCH_MISMATCH";
case NVJPEG_STATUS_INTERNAL_ERROR: return "NVJPEG_STATUS_INTERNAL_ERROR";
case NVJPEG_STATUS_IMPLEMENTATION_NOT_SUPPORTED:
return "NVJPEG_STATUS_IMPLEMENTATION_NOT_SUPPORTED";
default: return "Unknown nvjpeg status";
}
}
#endif
size_t GetAvailableGpuMemSize(int dev_id) {
cudaDeviceProp prop{};
cudaGetDeviceProperties(&prop, dev_id);
return prop.totalGlobalMem;
}
namespace {
std::function<cudaError_t(void**, size_t)> GetCudaMallocHostFn(int32_t dev) {
auto default_fn = [](void** ptr, size_t size) { return cudaMallocHost(ptr, size); };
auto manager = Singleton<hardware::NodeDeviceDescriptorManager>::Get();
if (manager == nullptr) { return default_fn; }
auto node_desc = manager->GetLocalNodeDeviceDescriptor();
auto cuda_device = std::dynamic_pointer_cast<const hardware::CudaDeviceDescriptor>(
node_desc->GetDevice(hardware::kCudaDeviceDescriptorClassName, dev));
if (!cuda_device) { return default_fn; }
auto saved_affinity = node_desc->Topology()->GetMemoryAffinity();
if (!saved_affinity) { return default_fn; }
auto device_affinity =
node_desc->Topology()->GetMemoryAffinityByPCIBusID(cuda_device->PCIBusID());
if (!device_affinity) { return default_fn; }
return [device_affinity, saved_affinity, node_desc, default_fn](void** ptr, size_t size) {
node_desc->Topology()->SetMemoryAffinity(device_affinity);
cudaError_t err = default_fn(ptr, size);
node_desc->Topology()->SetMemoryAffinity(saved_affinity);
return err;
};
}
} // namespace
cudaError_t NumaAwareCudaMallocHost(int32_t dev, void** ptr, size_t size) {
auto fn = GetCudaMallocHostFn(dev);
return fn(ptr, size);
}
CudaCurrentDeviceGuard::CudaCurrentDeviceGuard(int32_t dev_id) {
CHECK(!pthread_fork::IsForkedSubProcess()) << pthread_fork::kOfCudaNotSupportInForkedSubProcess;
OF_CUDA_CHECK(cudaGetDevice(&saved_dev_id_));
OF_CUDA_CHECK(cudaSetDevice(dev_id));
}
CudaCurrentDeviceGuard::CudaCurrentDeviceGuard() { OF_CUDA_CHECK(cudaGetDevice(&saved_dev_id_)); }
CudaCurrentDeviceGuard::~CudaCurrentDeviceGuard() { OF_CUDA_CHECK(cudaSetDevice(saved_dev_id_)); }
CublasMathModeGuard::CublasMathModeGuard(cublasHandle_t handle, cublasMath_t new_mode)
: CublasMathModeGuard(handle) {
SetMathMode(new_mode);
}
CublasMathModeGuard::CublasMathModeGuard(cublasHandle_t handle) : handle_(handle) {
OF_CUBLAS_CHECK(cublasGetMathMode(handle_, &saved_mode_));
new_mode_ = saved_mode_;
}
CublasMathModeGuard::~CublasMathModeGuard() {
if (new_mode_ != saved_mode_) { OF_CUBLAS_CHECK(cublasSetMathMode(handle_, saved_mode_)); }
}
void CublasMathModeGuard::SetMathMode(cublasMath_t new_mode) {
new_mode_ = new_mode;
if (new_mode_ != saved_mode_) { OF_CUBLAS_CHECK(cublasSetMathMode(handle_, new_mode_)); }
}
void CudaSynchronize(int device_id) {
CudaCurrentDeviceGuard dev_guard(device_id);
OF_CUDA_CHECK(cudaDeviceSynchronize());
}
void SetCudaDeviceIndex(int device_id) { OF_CUDA_CHECK(cudaSetDevice(device_id)); }
int GetCudaDeviceIndex() { return GlobalProcessCtx::LocalRank(); }
int GetCudaDeviceCount() {
/* static */ int cuda_device_count = 0;
OF_CUDA_CHECK(cudaGetDeviceCount(&cuda_device_count));
return cuda_device_count;
}
// NOTE(lixiang): Get the memory of the current device.
Maybe<double> GetCUDAMemoryUsed() {
JUST(vm::CurrentRankSync());
int deviceCount = 0;
cudaError_t error_id = cudaGetDeviceCount(&deviceCount);
if (error_id != cudaSuccess) {
return Error::RuntimeError() << "Error: GetCUDAMemoryUsed fails :"
<< cudaGetErrorString(error_id);
}
CHECK_OR_RETURN(deviceCount > 0) << "GPU device does not exist";
size_t gpu_total_size;
size_t gpu_free_size;
cudaError_t cuda_status = cudaMemGetInfo(&gpu_free_size, &gpu_total_size);
CHECK_OR_RETURN(cudaSuccess == cuda_status)
<< "Error: GetCUDAMemoryUsed fails :" << cudaGetErrorString(cuda_status);
double total_memory = double(gpu_total_size) / (1024.0 * 1024.0);
double free_memory = double(gpu_free_size) / (1024.0 * 1024.0);
return (total_memory - free_memory);
}
static std::once_flag prop_init_flag;
static std::vector<cudaDeviceProp> device_props;
void InitDevicePropVectorSize() {
int device_count = GetCudaDeviceCount();
device_props.resize(device_count);
}
void InitDeviceProperties(int device_id) {
std::call_once(prop_init_flag, InitDevicePropVectorSize);
cudaDeviceProp prop{};
OF_CUDA_CHECK(cudaGetDeviceProperties(&prop, device_id));
device_props[device_id] = prop;
}
cudaDeviceProp* GetDeviceProperties(int device_id) {
InitCudaContextOnce(device_id);
return &device_props[device_id];
}
void InitCudaContextOnce(int device_id) {
static int device_count = GetCudaDeviceCount();
static std::vector<std::once_flag> init_flags = std::vector<std::once_flag>(device_count);
if (LazyMode::is_enabled()) { return; }
if (device_id == -1) { device_id = GetCudaDeviceIndex(); }
std::call_once(init_flags[device_id], [&]() {
OF_CUDA_CHECK(cudaSetDevice(device_id));
OF_CUDA_CHECK(cudaDeviceSynchronize());
InitDeviceProperties(device_id);
});
}
cudaError_t CudaDriverGetPrimaryCtxActive(int dev, int* active) {
#if CUDA_VERSION >= 11030
CUdevice cu_device{};
{
CUresult (*fnCuDeviceGet)(CUdevice*, int) = nullptr;
cudaError_t err =
cudaGetDriverEntryPoint("cuDeviceGet", (void**)&fnCuDeviceGet, cudaEnableDefault);
if (err != cudaSuccess) { return err; }
CUresult result = fnCuDeviceGet(&cu_device, dev);
if (result == CUDA_SUCCESS) {
// do nothing
} else if (result == CUresult::CUDA_ERROR_INVALID_DEVICE) {
return cudaErrorInvalidDevice;
} else {
return cudaErrorUnknown;
}
}
{
CUresult (*fnCuDevicePrimaryCtxGetState)(CUdevice, unsigned int*, int*) = nullptr;
cudaError_t err = cudaGetDriverEntryPoint(
"cuDevicePrimaryCtxGetState", (void**)&fnCuDevicePrimaryCtxGetState, cudaEnableDefault);
if (err != cudaSuccess) { return err; }
unsigned int flags{};
CUresult result = fnCuDevicePrimaryCtxGetState(cu_device, &flags, active);
if (result == CUDA_SUCCESS) {
return cudaSuccess;
} else {
return cudaErrorUnknown;
}
}
#else
return cudaErrorNotSupported;
#endif // CUDA_VERSION < 11030
}
#endif // WITH_CUDA
#ifdef WITH_ROCM
const char* CublasGetErrorString(hipblasStatus_t error) {
switch (error) {
case HIPBLAS_STATUS_SUCCESS: return "HIPBLAS_STATUS_SUCCESS";
case HIPBLAS_STATUS_NOT_INITIALIZED: return "HIPBLAS_STATUS_NOT_INITIALIZED";
case HIPBLAS_STATUS_ALLOC_FAILED: return "HIPBLAS_STATUS_ALLOC_FAILED";
case HIPBLAS_STATUS_INVALID_VALUE: return "HIPBLAS_STATUS_INVALID_VALUE";
case HIPBLAS_STATUS_ARCH_MISMATCH: return "HIPBLAS_STATUS_ARCH_MISMATCH";
case HIPBLAS_STATUS_MAPPING_ERROR: return "HIPBLAS_STATUS_MAPPING_ERROR";
case HIPBLAS_STATUS_EXECUTION_FAILED: return "HIPBLAS_STATUS_EXECUTION_FAILED";
case HIPBLAS_STATUS_INTERNAL_ERROR: return "HIPBLAS_STATUS_INTERNAL_ERROR";
case HIPBLAS_STATUS_NOT_SUPPORTED: return "HIPBLAS_STATUS_NOT_SUPPORTED";
default: return "Unknown hipblas status";
}
}
const char* CurandGetErrorString(hiprandStatus_t error) {
switch (error) {
case HIPRAND_STATUS_SUCCESS: return "HIPRAND_STATUS_SUCCESS";
case HIPRAND_STATUS_VERSION_MISMATCH: return "HIPRAND_STATUS_VERSION_MISMATCH";
case HIPRAND_STATUS_NOT_INITIALIZED: return "HIPRAND_STATUS_NOT_INITIALIZED";
case HIPRAND_STATUS_ALLOCATION_FAILED: return "HIPRAND_STATUS_ALLOCATION_FAILED";
case HIPRAND_STATUS_TYPE_ERROR: return "HIPRAND_STATUS_TYPE_ERROR";
case HIPRAND_STATUS_OUT_OF_RANGE: return "HIPRAND_STATUS_OUT_OF_RANGE";
case HIPRAND_STATUS_LENGTH_NOT_MULTIPLE: return "HIPRAND_STATUS_LENGTH_NOT_MULTIPLE";
case HIPRAND_STATUS_DOUBLE_PRECISION_REQUIRED: return "HIPRAND_STATUS_DOUBLE_PRECISION_REQUIRED";
case HIPRAND_STATUS_LAUNCH_FAILURE: return "HIPRAND_STATUS_LAUNCH_FAILURE";
case HIPRAND_STATUS_PREEXISTING_FAILURE: return "HIPRAND_STATUS_PREEXISTING_FAILURE";
case HIPRAND_STATUS_INITIALIZATION_FAILED: return "HIPRAND_STATUS_INITIALIZATION_FAILED";
case HIPRAND_STATUS_ARCH_MISMATCH: return "HIPRAND_STATUS_ARCH_MISMATCH";
case HIPRAND_STATUS_INTERNAL_ERROR: return "HIPRAND_STATUS_INTERNAL_ERROR";
default: return "Unknown hiprand status";
}
}
const char* CuFFTGetErrorString(hipfftResult_t error) {
switch (error) {
case HIPFFT_SUCCESS: return "HIPFFT_SUCCESS";
case HIPFFT_INVALID_PLAN: return "HIPFFT_INVALID_PLAN";
case HIPFFT_ALLOC_FAILED: return "HIPFFT_ALLOC_FAILED";
case HIPFFT_INVALID_TYPE: return "HIPFFT_INVALID_TYPE";
case HIPFFT_INVALID_VALUE: return "HIPFFT_INVALID_VALUE";
case HIPFFT_INTERNAL_ERROR: return "HIPFFT_INTERNAL_ERROR";
case HIPFFT_EXEC_FAILED: return "HIPFFT_EXEC_FAILED";
case HIPFFT_SETUP_FAILED: return "HIPFFT_SETUP_FAILED";
case HIPFFT_INVALID_SIZE: return "HIPFFT_INVALID_SIZE";
case HIPFFT_UNALIGNED_DATA: return "HIPFFT_UNALIGNED_DATA";
case HIPFFT_INCOMPLETE_PARAMETER_LIST: return "HIPFFT_INCOMPLETE_PARAMETER_LIST";
case HIPFFT_INVALID_DEVICE: return "HIPFFT_INVALID_DEVICE";
case HIPFFT_PARSE_ERROR: return "HIPFFT_PARSE_ERROR";
case HIPFFT_NO_WORKSPACE: return "HIPFFT_NO_WORKSPACE";
case HIPFFT_NOT_IMPLEMENTED: return "HIPFFT_NOT_IMPLEMENTED";
case HIPFFT_NOT_SUPPORTED: return "HIPFFT_NOT_SUPPORTED";
default: return "Unknown hipfft status";
}
}
const char* CusovlerGetErrorString(hipsolverStatus_t error) {
switch (error) {
case HIPSOLVER_STATUS_SUCCESS: return "HIPSOLVER_STATUS_SUCCESS";
case HIPSOLVER_STATUS_NOT_INITIALIZED: return "HIPSOLVER_STATUS_NOT_INITIALIZED";
case HIPSOLVER_STATUS_ALLOC_FAILED: return "HIPSOLVER_STATUS_ALLOC_FAILED";
case HIPSOLVER_STATUS_INVALID_VALUE: return "HIPSOLVER_STATUS_INVALID_VALUE";
case HIPSOLVER_STATUS_ARCH_MISMATCH: return "HIPSOLVER_STATUS_ARCH_MISMATCH";
case HIPSOLVER_STATUS_EXECUTION_FAILED: return "HIPSOLVER_STATUS_EXECUTION_FAILED";
case HIPSOLVER_STATUS_INTERNAL_ERROR: return "HIPSOLVER_STATUS_INTERNAL_ERROR";
// case HIPSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED:
// return "HIPSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED";
default: return "Unknown hipsolver status";
}
}
size_t GetAvailableGpuMemSize(int dev_id) {
hipDeviceProp_t prop{};
hipGetDeviceProperties(&prop, dev_id);
return prop.totalGlobalMem;
}
namespace {
std::function<hipError_t(void**, size_t)> GetCudaMallocHostFn(int32_t dev) {
auto default_fn = [](void** ptr, size_t size) { return hipMallocHost(ptr, size); };
auto manager = Singleton<hardware::NodeDeviceDescriptorManager>::Get();
if (manager == nullptr) { return default_fn; }
auto node_desc = manager->GetLocalNodeDeviceDescriptor();
auto cuda_device = std::dynamic_pointer_cast<const hardware::CudaDeviceDescriptor>(
node_desc->GetDevice(hardware::kCudaDeviceDescriptorClassName, dev));
if (!cuda_device) { return default_fn; }
auto saved_affinity = node_desc->Topology()->GetMemoryAffinity();
if (!saved_affinity) { return default_fn; }
auto device_affinity =
node_desc->Topology()->GetMemoryAffinityByPCIBusID(cuda_device->PCIBusID());
if (!device_affinity) { return default_fn; }
return [device_affinity, saved_affinity, node_desc, default_fn](void** ptr, size_t size) {
node_desc->Topology()->SetMemoryAffinity(device_affinity);
hipError_t err = default_fn(ptr, size);
node_desc->Topology()->SetMemoryAffinity(saved_affinity);
return err;
};
}
} // namespace
hipError_t NumaAwareCudaMallocHost(int32_t dev, void** ptr, size_t size) {
auto fn = GetCudaMallocHostFn(dev);
return fn(ptr, size);
}
CudaCurrentDeviceGuard::CudaCurrentDeviceGuard(int32_t dev_id) {
CHECK(!pthread_fork::IsForkedSubProcess()) << pthread_fork::kOfCudaNotSupportInForkedSubProcess;
OF_CUDA_CHECK(hipGetDevice(&saved_dev_id_));
OF_CUDA_CHECK(hipSetDevice(dev_id));
}
CudaCurrentDeviceGuard::CudaCurrentDeviceGuard() { OF_CUDA_CHECK(hipGetDevice(&saved_dev_id_)); }
CudaCurrentDeviceGuard::~CudaCurrentDeviceGuard() { OF_CUDA_CHECK(hipSetDevice(saved_dev_id_)); }
void CudaSynchronize(int device_id) {
CudaCurrentDeviceGuard dev_guard(device_id);
OF_CUDA_CHECK(hipDeviceSynchronize());
}
void SetCudaDeviceIndex(int device_id) { OF_CUDA_CHECK(hipSetDevice(device_id)); }
int GetCudaDeviceIndex() { return GlobalProcessCtx::LocalRank(); }
int GetCudaDeviceCount() {
/* static */ int cuda_device_count = 0;
OF_CUDA_CHECK(hipGetDeviceCount(&cuda_device_count));
return cuda_device_count;
}
// NOTE(lixiang): Get the memory of the current device.
Maybe<double> GetCUDAMemoryUsed() {
JUST(vm::CurrentRankSync());
int deviceCount = 0;
hipError_t error_id = hipGetDeviceCount(&deviceCount);
if (error_id != hipSuccess) {
return Error::RuntimeError() << "Error: GetCUDAMemoryUsed fails :"
<< hipGetErrorString(error_id);
}
CHECK_OR_RETURN(deviceCount > 0) << "GPU device does not exist";
size_t gpu_total_size;
size_t gpu_free_size;
hipError_t cuda_status = hipMemGetInfo(&gpu_free_size, &gpu_total_size);
CHECK_OR_RETURN(hipSuccess == cuda_status)
<< "Error: GetCUDAMemoryUsed fails :" << hipGetErrorString(cuda_status);
double total_memory = double(gpu_total_size) / (1024.0 * 1024.0);
double free_memory = double(gpu_free_size) / (1024.0 * 1024.0);
return (total_memory - free_memory);
}
static std::once_flag prop_init_flag;
static std::vector<hipDeviceProp_t> device_props;
void InitDevicePropVectorSize() {
int device_count = GetCudaDeviceCount();
device_props.resize(device_count);
}
void InitDeviceProperties(int device_id) {
std::call_once(prop_init_flag, InitDevicePropVectorSize);
hipDeviceProp_t prop{};
OF_CUDA_CHECK(hipGetDeviceProperties(&prop, device_id));
device_props[device_id] = prop;
}
hipDeviceProp_t* GetDeviceProperties(int device_id) {
InitCudaContextOnce(device_id);
return &device_props[device_id];
}
void InitCudaContextOnce(int device_id) {
static int device_count = GetCudaDeviceCount();
static std::vector<std::once_flag> init_flags = std::vector<std::once_flag>(device_count);
if (LazyMode::is_enabled()) { return; }
if (device_id == -1) { device_id = GetCudaDeviceIndex(); }
std::call_once(init_flags[device_id], [&]() {
OF_CUDA_CHECK(hipSetDevice(device_id));
OF_CUDA_CHECK(hipDeviceSynchronize());
InitDeviceProperties(device_id);
});
}
#endif // WITH_ROCM
} // namespace oneflow
|
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset='utf-8' name='viewport' content='width=device-width, user-scalable=no'>
<title>TP3 | Earth</title>
<style>
body{
margin:0;
overflow:hidden;
}
</style>
</head>
<body>
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://threejs.org//examples/js/loaders/GLTFLoader.js"></script>
<script type="text/javascript">
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.set(2,0,3);
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//Création geometry and material Terre
const geometry = new THREE.SphereGeometry(1, 50, 50);
const texture = new THREE.TextureLoader().load( 'textures/monde.jpg' );
const materialTex = new THREE.MeshBasicMaterial( { map: texture } );
const sphere = new THREE.Mesh( geometry, materialTex );
scene.add( sphere );
//OrbitControls
const controls = new THREE.OrbitControls( camera, renderer.domElement );
//Directionelle
const directionalLight = new THREE.DirectionalLight( 0xffffff, 1.5 );
scene.add( directionalLight );
//Géolocalisation
navigator.geolocation.getCurrentPosition(function(pos){
var position = convertLatLonToVec(pos.coords.latitude, pos.coords.longitude);
//Marqueur
const geo = new THREE.SphereGeometry(0.01, 50, 50);
const mat = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
const mark = new THREE.Mesh( geo, mat );
mark.position.set(position[0], position[1], position[2]);
scene.add( mark );
})
//Requete Pays
var xml = new XMLHttpRequest();
xml.addEventListener("load", function(){
var json = JSON.parse(this.responseText);
var geo, texture, mark, material;
for (let i = 0; i < json.length; i++) {
var position = convertLatLonToVec(json[i].latlng[0], json[i].latlng[1]);
geo = new THREE.SphereGeometry(0.01, 32, 32);
texture = new THREE.TextureLoader().load( json[i].flag );
material = new THREE.MeshBasicMaterial( { map: texture } );
mark = new THREE.Mesh( geo, material );
mark.position.set(position[0], position[1], position[2]);
scene.add( mark );
}
})
xml.open("GET", "https://restcountries.eu/rest/v2/");
xml.send();
const animate = function () {
requestAnimationFrame( animate );
renderer.render( scene, camera );
};
animate();
//Conversion
var convertLatLonToVec = function(l, lo){
var lat = l * Math.PI / 180.0;
var long = -lo * Math.PI / 180.0;
var res = [];
const rayon = 1;
var x = rayon * Math.cos(lat) * Math.cos(long);
res.push(x);
var y = rayon * Math.sin(lat)
res.push(y)
var z = rayon * Math.cos(lat) * Math.sin(long);
res.push(z);
return res;
}
</script>
</body>
</html>
|
import React from "react";
import { useNavigate } from "react-router-dom";
const Card = ({ movie }) => {
const navigate = useNavigate();
return (
<div>
<div
onClick={() => {
if (movie?.seriesid) {
navigate(`/series/${movie.url}`);
} else {
navigate(`/movie/${movie.url}`);
}
}}
class="rounded-md bg-gray-800 shadow-lg group cursor-pointer py-3 h-full"
>
<div class="md:flex md:px-4 px-2 leading-none max-w-4xl">
<div class="flex-none ">
<img
src={movie.poster}
alt="pic"
class="md:h-60 h-[100px] w-full md:w-44 md:rounded-md rounded shadow-2xl transform md:-translate-y-6 md:group-hover:translate-y-6 border-4 border-gray-300 shadow-lg"
/>
</div>
<div class="flex-col md:pt-4 pt-[-15px] text-gray-300">
<p class=" md:text-[20px] text-[12px] md:font-bold">
{movie.title} {`(${movie?.release_year})`}
</p>
<hr class="hr-text md:my-0 my-1" data-content="" />
<div class="text-md md:flex md:px-4 px-1 md:my-2 my-1">
<p class="md:font-bold md:text-sm text-[10px]">
{movie.runtime} <span className="md:inline hidden">|</span>{" "}
</p>
<div className="md:ml-1">
{movie.genres.slice(0, 2).map((a, i) => (
<span className="md:text-sm text-[10px]">
{a} {i < 1 ? "," : ""}{" "}
</span>
))}
</div>
</div>
<p class="hidden md:block px-4 my-4 text-sm text-left">
{movie.overview.slice(0, 130)}
</p>
<div class="md:flex items-center md:text-[12px] md:px-4 px-1 text-[10px] md:my-2 my-1">
<p className="">Rating: {movie.average_rating}</p>
<span class="font-bold px-2 md:inline hidden ">|</span>
<p className="my-1"> {movie?.release_date}</p>
</div>
<p class="flex md:text-[12px] md:block hidden md:px-4 px-1 text-[10px] my-2">
Director: {movie.director}
</p>
{/* <div class="text-xs md:block hidden">
<button
type="button"
class="border border-gray-400 text-gray-400 md:rounded-md rounded md:px-2 px-1 md:py-2 md:m-2 m-[2px] text-[8px] transition duration-500 ease select-none hover:bg-gray-900 focus:outline-none focus:shadow-outline"
>
TRAILER
</button>
<button
type="button"
class="border border-gray-400 text-gray-400 md:rounded-md rounded md:px-2 px-1 md:py-2 md:m-2 m-[2px] text-[8px] transition duration-500 ease select-none hover:bg-gray-900 focus:outline-none focus:shadow-outline"
>
IMDB
</button>
<button
type="button"
class="border border-gray-400 text-gray-400 md:rounded-md rounded md:px-2 px-1 md:py-2 md:m-2 m-[2px] text-[8px] transition duration-500 ease select-none hover:bg-gray-900 focus:outline-none focus:shadow-outline"
>
AMAZON
</button>
</div> */}
</div>
</div>
</div>
</div>
);
};
export default Card;
|
package com.umairkhalid.i210455
import android.os.Parcel
import android.os.Parcelable
data class user_data(val name: String = "", val email: String = "",
val contact: String = "", val country: String = "",
val city: String = "", val password: String = ""): Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString() ?: "",
parcel.readString() ?: "",
parcel.readString() ?: "",
parcel.readString() ?: "",
parcel.readString() ?: "",
parcel.readString() ?: "",
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(name)
parcel.writeString(email)
parcel.writeString(contact)
parcel.writeString(country)
parcel.writeString(city)
parcel.writeString(password)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<user_data> {
override fun createFromParcel(parcel: Parcel): user_data {
return user_data(parcel)
}
override fun newArray(size: Int): Array<user_data?> {
return arrayOfNulls(size)
}
}
}
|
# Super Merryo Trolls #
**An Adventure From The Days Before VRAM**

It's the year 1991. You're a teenage computer geek.
You've just upgraded to your first "16-bit" computer, and the possibilities are infinite. To relieve the crushing boredom of your High School coursework, you and your friends embark on the computer geek equivalent of forming a heavy metal band: You create your own video game.
You meet on the benches during lunch hour, and pass around crude plans scribbled on graph paper. You assign each other impressive titles like "Master Programmer", "Sound Designer", and "Area Data Input". You draw circles and arrows all over fuzzy dot-matrix printouts of code, and argue over them between episodes of "Ren and Stimpy". You swap 3.5" disks around like furtive secret agents. You consume incredible quantities of soda. Your parents look at your owlish eyes - and possibly your slipping grades - and wonder aloud if you're "on drugs".
If that sounds familiar to you, then this project will be amusing. It's the Apple IIgs game my friends and I started - but didn't finish - in high-school. Thanks to emulators and modern versions of ancient development tools, you can actually compile and run this game, in its not-quite-finished form.
For a lot more background, and a tour through the bizarre code shenanigans we employed to make a console-style game playable on the notoriously slow Apple IIgs hardware, check out [this expanded writeup](http://garote.bdmonkeys.net/merryo_trolls/index.html).
## Giving it a whirl ##
2024 is a unique year to be resurrecting this game, and not just because it's the 30th anniversary of its death. This year has seen the release of [Crossrunner](https://www.crossrunner.gs/), the very first <i>cycle accurate</i> emulator for the Apple IIgs. Up until this point, Super Merryo Trolls either didn't launch at all in emulators, or was unplayably fast. At long last you can now play this game in its original screen-tearing single-digit frames-per-second glory.
All you need is the [pre-built disk image](Merryo_Trolls.2mg) from this repo, and some kind of joystick device. (The Apple IIgs supports analog joysticks but you can play it just fine with something simple like the <b>8Bitdo Zero 2 Mini Bluetooth Gamepad</b>.) Double-click on the disk and Crossrunner will boot and launch the game. At the title screen, hit "1" to start World 1.
## Further development ##
You can use this code as a starting point for your own work. For me, any commercial use it may have here in the crazy future of 2024 is frankly <i>inconceivable</i>[^1], but if you find an angle, get in touch with me so I can congratulate you and mention it to my other two "co-developers" and we can all have a good laugh.
Meanwhile, you should know that in the process of stitching the levels from 1994 together into something playable, I wrote and included a set of modern game editing tools that run in any WebKit-based browser.

They work directly on the various crude binary file formats that the game uses natively, and may be a good reference for similar forensics tools in other projects.
## Building the game from source ##
A build script is included that compiles all the assembly files, then copies all the assets onto a bootable disk image, resulting in something immediately playable.
You need two external tools to make this work:
* The [Merlin32 assembler](https://brutaldeluxe.fr/products/crossdevtools/merlin/index.html), for building the code.
* The [CiderPress II](https://ciderpress2.com) utility, for constructing the a disk image suitable for running with an Apple IIgs.
Both of these have Windows and Mac versions, and the build script that drives them is written in Python, so it's all theoretically cross-platform, but the script needs tweaking for a Windows environment.
Download and install these tools somewhere near your checked-out copy of this repo, then modify the paths in `build.sh` to point to them.
Note that on MacOS you may need to de-quarantine them first, by going into their folders and running `sudo xattr -r -d com.apple.quarantine *` .
With the right tools, you can take the resulting disk image and write it to an 800k 3.5-inch disk, and play the game on a stock Apple IIgs. Or you can just double-click it, and it will open in Crossrunner.
[^1]: But really, who knows what's possible? There's currently a land war in Asia going on.
|
import {
Button,
ModalBody,
ModalCloseButton,
ModalFooter,
ModalHeader,
} from "@chakra-ui/react";
import {CustomInput} from "@/components/CustomInput/CustomInput";
import {IModalAddCustomer} from "@/types/ModalTypes/ModalTypes";
import {CustomFileInput} from "@/components/CustomFileInput/CustomFileInput";
export function ModalAddCustomer({onClose, title}: IModalAddCustomer) {
return (
<>
<ModalHeader>{title}</ModalHeader>
<ModalCloseButton/>
<ModalBody>
<form className={'flex flex-col gap-5 mb-3'}>
{/*<CustomInput width={'5rem'} placeholder={'ADD'} label={'Avatar'}/>*/}
<CustomFileInput></CustomFileInput>
<div className={'flex gap-5'}>
<CustomInput required={true} label={'First Name'}/>
<CustomInput required={true} label={'Last Name'}/>
</div>
<div className={'flex gap-5'}>
<CustomInput required={true} label={'Email'}/>
<CustomInput required={true} label={'Phone'}/>
</div>
<CustomInput required={true} label={'Address'} placeholder={'Street Address'}/>
<div className={'flex gap-4'}>
<CustomInput required={true} label={'City'} width={'12rem'}/>
<CustomInput required={true} label={'State/Province'} width={'10rem'}/>
<CustomInput required={true} label={'Zip Code'} width={'6.8rem'}/>
</div>
</form>
</ModalBody>
<ModalFooter>
<footer className={'flex gap-3 items-center'}>
<Button mr={3} background={'transparent'} onClick={onClose}>
Close
</Button>
<button className="w-[150px] h-[50px] px-6 py-2.5 bg-indigo-600 rounded-[70px] justify-center items-center gap-4 inline-flex">
<div className="text-white font-medium font-['Inter'] leading-[30px]">Save Customer</div>
</button>
</footer>
</ModalFooter>
</>
)
}
|
// Exposes a light sensor and servo motor over serial ()
// Written by Collin Conrad
#include <Servo.h>
#define LDR_PIN A0
#define SERVO_PIN 9
const float FILTER_FACTOR = 0.05;
const unsigned long LDR_RESEND_DELAY = 2000; // Every 2 seconds
Servo blindActuator;
bool ldrLastReportedState = false;
unsigned long ldrLastSent = 0;
float sensorSmoothed = 0;
void setup() {
Serial.begin(9600);
blindActuator.attach(SERVO_PIN);
}
void loop() {
while(Serial.available()) {
int inByte = Serial.read();
if(inByte == 'o')
blindActuator.write(180);
else if(inByte == 'c')
blindActuator.write(0);
}
int sensorValue = analogRead(A0);
sensorSmoothed += ((float) sensorValue - sensorSmoothed) * FILTER_FACTOR;
bool isLDRTriggered = sensorSmoothed >= 500;
if(isLDRTriggered != ldrLastReportedState || millis() - ldrLastSent >= LDR_RESEND_DELAY) {
ldrLastReportedState = isLDRTriggered;
ldrLastSent = millis();
Serial.print(isLDRTriggered ? 'l' : 'd');
}
delay(10);
}
|
#!/usr/bin/python3
from datetime import date, datetime
from flask import Flask, jsonify, make_response, request, abort
from flask_cors import CORS
import sys
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
# Add the parent directory (which contains 'project_directory') to the Python path
parent_dir = os.path.dirname(script_dir)
sys.path.append(parent_dir)
from models.user import User
from models import storage
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({"error": "Not found"}), 404)
@app.errorhandler(400)
def bad_request(error):
return make_response(jsonify({"error": "Bad Request"}), 400)
@app.route("/api", methods=["POST"], strict_slashes=False)
def create_user():
"""Creates a new user"""
if not request.get_json() or "name" not in request.get_json():
abort(400)
data = request.get_json()
user = User(**data)
storage.save(user)
return jsonify(user.to_dict())
@app.route("/api/<string:id>", methods=["GET"], strict_slashes=False)
def get_user(id):
"""Retrieves an user"""
user = storage.get_details(id)
if user == None:
abort(404)
return jsonify(user.to_dict())
@app.route("/api/<string:id>", methods=["DELETE"], strict_slashes=False)
def delete_user(id):
"""deletes a user"""
user = storage.get_details(id)
if user == None:
abort(404)
storage.delete(user)
return jsonify({"Delete": "success"})
@app.route("/api/<string:id>", methods=["PUT"], strict_slashes=False)
def update_user(id):
"""Update a user"""
if not request.get_json() or "name" not in request.get_json():
abort(400)
data = request.get_json()
user = storage.get_details(id)
if not user:
abort(404)
for k, v in data.items():
if k == "name":
user.name = v
storage.save(user)
return jsonify(user.to_dict())
@app.teardown_appcontext
def close_db(error):
"""Close Storage"""
storage.close()
if __name__ == "__main__":
app.run(host="0.0.0.0", port="5000", debug=True)
|
import axios from 'axios';
import API from '..';
import { OkResponse } from '../types';
import {
LoginDto,
LoginResponse,
RegisterDto,
ResetPasswordDto
} from './types';
export const register = async (data: RegisterDto): Promise<OkResponse> => {
try {
const res = await API.post('/auth/register', data);
return res.data;
} catch (error) {
console.error(error);
return { ok: false };
}
};
export const login = async (data: LoginDto): Promise<LoginResponse> => {
try {
const res = await API.post('/auth/login', data);
return res.data;
} catch (error) {
console.error(error);
return { accessToken: '' };
}
};
export const logout = async (): Promise<OkResponse> => {
try {
const res = await API.post('/auth/logout');
return res.data;
} catch (error) {
console.error(error);
return { ok: false };
}
};
export const confirmEmail = async (token: string): Promise<OkResponse> => {
try {
const res = await API.post(`/auth/confirm-email/${token}`);
return res.data;
} catch (error) {
console.error(error);
return { ok: false };
}
};
export const forgotPassword = async (email: string): Promise<OkResponse> => {
try {
const res = await API.post('/auth/forgot-password', { email });
return res.data;
} catch (error) {
if (axios.isAxiosError(error)) {
return error.response?.data;
}
console.error(error);
return { ok: false };
}
};
export const resetPassword = async ({
token,
password
}: ResetPasswordDto): Promise<OkResponse> => {
try {
const res = await API.post(`/auth/reset-password/${token}`, {
password
});
return res.data;
} catch (error) {
if (axios.isAxiosError(error)) {
return error.response?.data;
}
console.error(error);
return { ok: false };
}
};
|
import 'package:flutter/material.dart';
import 'package:test_recorder_flow/core/extensions/offset_extensions.dart';
import 'package:test_recorder_flow/core/extensions/record_extensions.dart';
import 'package:test_recorder_flow/test_recorder_flow.dart';
class TestRecorderFlowWrapper extends StatefulWidget {
final Widget child;
const TestRecorderFlowWrapper({super.key, required this.child});
@override
State<TestRecorderFlowWrapper> createState() => _TestRecorderFlowWrapperState();
}
class _TestRecorderFlowWrapperState extends State<TestRecorderFlowWrapper> {
Offset _pointerUpPosition = Offset.zero;
Offset _pointerCancelPosition = Offset.zero;
bool isTestRecording = false;
@override
void initState() {
super.initState();
Future.microtask(() => TestRocerderFlow.setScreenSize(context));
}
void setTestRecording(bool value) {
setState(() {
isTestRecording = value;
});
}
void _addRecordedEvent() {
if (_pointerUpPosition == _pointerCancelPosition) {
final event = """
- tapOn:
point: ${_pointerUpPosition.convertPercentage.toPercentageString}
""";
TestRocerderFlow.addRecordEvent(event);
} else {
final event = """
- swipe:
start: ${_pointerUpPosition.convertPercentage.toPercentageString}
end: ${_pointerCancelPosition.convertPercentage.toPercentageString}
""";
TestRocerderFlow.addRecordEvent(event);
}
_pointerUpPosition = Offset.zero;
_pointerCancelPosition = Offset.zero;
}
@override
Widget build(BuildContext context) {
return Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (event) {
if (!isTestRecording) return;
print('onPointerUp');
_pointerUpPosition = event.position;
},
onPointerUp: (event) {
if (!isTestRecording) return;
print('onPointerCancel');
_pointerCancelPosition = event.position;
_addRecordedEvent();
},
child: Stack(
children: [
widget.child,
Positioned(
top: 60,
right: 0,
child: Row(
children: [
ElevatedButton(
onPressed: () {
if (isTestRecording) {
TestRocerderFlow.saveRecordedEvents();
}
setTestRecording(!isTestRecording);
},
child: Text(isTestRecording ? 'Stop Recording' : 'Start Recording'),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: () {
TestRocerderFlow.clearRecordedEvents();
},
child: const Text('Clear Records'),
),
],
)),
],
),
);
}
}
|
const {ethers} = require("hardhat");
const {expect} = require("chai");
describe("[Challenge] Naive receiver", function () {
let deployer, user, attacker;
// Pool has 1000 ETH in balance
const ETHER_IN_POOL = ethers.utils.parseEther("1000");
// Receiver has 10 ETH in balance
const ETHER_IN_RECEIVER = ethers.utils.parseEther("10");
before(async function () {
/** SETUP SCENARIO - NO NEED TO CHANGE ANYTHING HERE */
[deployer, user, attacker] = await ethers.getSigners();
const LenderPoolFactory = await ethers.getContractFactory(
"NaiveReceiverLenderPool",
deployer
);
const FlashLoanReceiverFactory = await ethers.getContractFactory(
"FlashLoanReceiver",
deployer
);
this.pool = await LenderPoolFactory.deploy();
await deployer.sendTransaction({to: this.pool.address, value: ETHER_IN_POOL});
expect(await ethers.provider.getBalance(this.pool.address)).to.be.equal(ETHER_IN_POOL);
expect(await this.pool.fixedFee()).to.be.equal(ethers.utils.parseEther("1"));
this.receiver = await FlashLoanReceiverFactory.deploy(this.pool.address);
await deployer.sendTransaction({to: this.receiver.address, value: ETHER_IN_RECEIVER});
expect(await ethers.provider.getBalance(this.receiver.address)).to.be.equal(
ETHER_IN_RECEIVER
);
});
it("Exploit", async function () {
const exploit = await (
await ethers.getContractFactory("NaiveReceiverExploit")
).deploy(this.pool.address, this.receiver.address);
await exploit.attack();
});
after(async function () {
/** SUCCESS CONDITIONS */
// All ETH has been drained from the receiver
expect(await ethers.provider.getBalance(this.receiver.address)).to.be.equal("0");
expect(await ethers.provider.getBalance(this.pool.address)).to.be.equal(
ETHER_IN_POOL.add(ETHER_IN_RECEIVER)
);
});
});
|
import { DateTime } from 'luxon'
import { BaseModel, BelongsTo, belongsTo, column } from '@ioc:Adonis/Lucid/Orm'
import Conversation from 'App/Models/Conversation'
import User from 'App/Models/User'
export default class Message extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public senderId: number
@column()
public conversationId: number
@column()
public content: string
@column()
public status: string
@column.dateTime({ autoCreate: true })
public createdAt: DateTime
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime
/*
* Relationship
*/
@belongsTo(() => User, {
localKey: 'senderId',
})
public sender: BelongsTo<typeof User>
@belongsTo(() => Conversation, {
localKey: 'conversationId',
})
public conversation: BelongsTo<typeof Conversation>
}
|
// Copyright (c) 2022 Braden Nicholson
import {reactive} from "vue";
import {v4 as uuidv4} from "uuid";
export interface NotifyBody {
name: string,
message: string,
trace?: string,
severity: number,
priority: number,
duration: number,
uuid: string,
}
interface NotifyState {
log: NotifyBody[];
queue: NotifyBody[];
active: boolean;
interval: number;
current: NotifyBody;
currentWait: number;
begin: number;
}
export interface Notify {
success(name: string, message: string): void
fail(name: string, message: string, trace?: string): void
show(name: string, message: string, severity: number, duration: number): void
isActive(): boolean
current(): NotifyBody
queued(): number
logs(): NotifyBody[]
clearLog(): void
}
let state = reactive<NotifyState>({
log: [] as NotifyBody[],
queue: [] as NotifyBody[],
active: false,
interval: 0,
current: {} as NotifyBody,
begin: 0,
currentWait: 0,
})
function queued(): number {
return state.queue.length
}
function logs(): NotifyBody[] {
return state.log
}
// Clears the logged notifications
function clearLog() {
state.log = state.log.filter(_ => false)
}
// Promotes the first element in the queue to the new current
function dequeue() {
// Pop an element from the front of the queue
let next = state.queue.shift()
// Make sure the element is not null
if (!next) return
// Update the current element
state.current = next
state.log.push(next)
if (state.log.length > 10) {
state.log.slice(1)
}
// Update the start time
state.begin = Date.now().valueOf()
// Update the countdown duration
state.currentWait = next.duration
}
// Begins the countdown for the current element
function countdown() {
// Request the next animation frame
state.interval = requestAnimationFrame(countdown)
// Check if the queue is currently active
if (state.active) {
// Set the current elapsed duration to the time since the beginning minus the original timeout
state.current.duration = state.currentWait - (Date.now().valueOf() - state.begin)
// Check if the duration has fully elapsed
if (state.current.duration <= 0) {
// Check if the queue is empty
if (state.queue.length <= 0) {
// Disable the notification queue
state.active = false
// Cancel the animation from to stop updated
cancelAnimationFrame(state.interval)
// Reset the animation frame variable
state.interval = 0
} else {
// Promote the next node to be the current
dequeue()
}
}
}
}
// Forces an update on the notifications queue
function updateQueue() {
// Check if the queue is not empty and the queue is not active (not is use)
if (state.queue.length > 0 && !state.active) {
// Enable the queue
state.active = true
// Dequeue the next in row to be the current
dequeue()
// Return now if the countdown is already going
if (state.interval != 0) return
// Begin countdown
countdown()
}
}
// Push a notification into the viewing queue
function pushQueue(toast: NotifyBody) {
state.queue.push(toast)
updateQueue()
}
// Sends a success notification to the user
function success(name: string, message: string): void {
pushQueue({
name: name,
message: message,
severity: 1,
priority: 1,
duration: 3000,
uuid: uuidv4()
})
}
// Sends a failure notification to the user
function fail(name: string, message: string, trace?: string): void {
pushQueue({
name: name,
message: message,
severity: 3,
priority: 2,
duration: 3000,
trace: trace,
uuid: uuidv4()
})
}
// Send a custom message to the user
function show(name: string, message: string, severity: number, duration: number) {
pushQueue({
priority: 0,
name: name,
message: message,
severity: severity,
duration: duration,
uuid: uuidv4()
})
}
// Send a custom message to the user
function current(): NotifyBody {
return state.current
}
// Send a custom message to the user
function isActive(): boolean {
return state.active
}
export default {
success,
fail,
show,
current,
isActive,
logs,
queued,
clearLog
}
|
import Layout from "@/components/Layout";
import PersonCard from "@/components/PersonCard";
import { getPerson } from "@/utils/request";
import { useQuery } from "@tanstack/react-query";
import { Pagination } from "flowbite-react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback } from "react";
import { ClipLoader } from "react-spinners";
export default function People() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const pageParams = searchParams.get("page") ?? "1";
const { data, isLoading, isError, isSuccess } = useQuery({
queryKey: ["person", pageParams],
queryFn: async () => {
const movies = getPerson(Number(pageParams));
const response = await fetch(movies);
return response.json();
},
keepPreviousData: true,
});
const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams);
params.set(name, value);
return params.toString();
},
[searchParams]
);
const onPageChange = (selected: number) => {
router.push(pathname + "?" + createQueryString("page", String(selected)));
};
return (
<Layout title="Lista de atores">
<section>
<div className="text-2xl font-sans font-semibold mb-4">Pessoas</div>
<div className="grid xs:grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
{isLoading && <ClipLoader />}
{isError && <div>Ops! Algo deu errado.</div>}
{isSuccess &&
data?.results.map((item: IPerson) => (
<PersonCard key={item.id} result={item} />
))}
</div>
{data?.results.length > 0 && (
<div className="flex items-start justify-start pt-4">
<Pagination
currentPage={Number(pageParams)}
layout="pagination"
onPageChange={(e) => onPageChange(e)}
totalPages={data?.total_pages}
/>
</div>
)}
</section>
</Layout>
);
}
|
import React, { Fragment } from 'react';
import './Register.less';
import { withRouter } from 'react-router-dom';
import { Form, Icon, Input, Button, message, Row, Col, Tooltip, Card } from 'antd';
import { connect } from 'react-redux';
import { COMMON_URL } from '../CommonData/api';
import CryptoJS from 'crypto-js'
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {
blogData: [],
commentsNum: {},
loading: false,
btnText: '获取验证码',
canRealname: false,
successRe: false,
};
this.codeTime = null
}
componentDidMount() {
}
componentWillUnmount() {
clearInterval(this.time)
this.setState = (state, callback) => {
return
}
}
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
if (!this.state.canRealname) {
message.warning('用户名已被使用')
return
}
this.setState({
loading: true
})
let url = `${COMMON_URL}/user/register`
let username = values.usernameReg
let password = CryptoJS.AES.encrypt(values.passwordReg, '').toString();
let realname = values.realnameReg
let code = parseInt(values.code)
let opts = {
method: 'POST',
credentials: 'include',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
username,
password,
realname,
code
})
}
fetch(url, opts)
.catch((err) => {
console.error(err)
this.setState({
loading: false
})
})
.then((response) => {
this.setState({
loading: false
})
return response.json();
})
.then((myJson) => {
if (myJson.ErrCode !== 0) {
message.error(myJson.ErrMsg)
return
}
clearInterval(this.time)
this.codeTime = null
message.success(`${myJson.data.realname},注册成功,欢迎您!`)
this.setState({
successRe: true,
btnText: '获取验证码'
})
});
}
});
};
/**
*获取验证码
*/
getCode = () => {
if (this.codeTime !== null) {
return
}
this.props.form.validateFields(['usernameReg'], (err, values) => {
if (!err) {
this.codeTime = 60
let url = `${COMMON_URL}/user/code`
let username = values.usernameReg
let opts = {
method: 'POST',
credentials: 'include',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
username
})
}
fetch(url, opts)
.catch((err) => {
console.error(err)
this.codeTime = null
})
.then((response) => {
return response.json();
})
.then((myJson) => {
if (myJson.ErrCode !== 0) {
message.error(myJson.ErrMsg)
this.codeTime = null
this.setState({
btnText: '获取验证码'
})
return
}
this.setState({
btnText: this.codeTime
})
this.time = setInterval(() => {
if (this.codeTime === 0) {
clearInterval(this.time)
this.codeTime = null
this.setState({
btnText: '获取验证码'
})
} else {
this.codeTime -= 1;
this.setState({
btnText: this.codeTime
})
}
}, 1000)
message.success(`验证码已发送,请查收`)
});
}
});
}
/**
* 判断用户名是否存在
*/
getRealname = () => {
this.props.form.validateFields(['realnameReg'], (err, values) => {
if (!err) {
let realnameReg = values.realnameReg
let url = `${COMMON_URL}/user/realname?realname=${realnameReg}`
let opts = {
method: 'GET',
credentials: 'include',
headers: {
'content-type': 'application/json'
},
}
fetch(url, opts)
.catch((err) => {
console.log(err)
})
.then((response) => {
return response.json();
})
.then((myJson) => {
if (myJson.ErrCode !== 0) {
this.setState({
canRealname: false
})
} else {
this.setState({
canRealname: true
})
}
});
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
const { loading, btnText, canRealname, successRe } = this.state
return (
<div className="login-regi">
{
successRe ? <Fragment>
<Card className="regi-suss" title="注册成功" bordered={false} style={{ width: 300 }}>
<p><a href="https://www.passerma.com/center">前往个人中心</a></p>
<p><a href="https://www.passerma.com">前往PASSERMA博客</a></p>
<p><a href="https://go.passerma.com">前往PM极简导航</a></p>
<Button type="primary" onClick={() => {
window.opener = null;
window.open('', '_self');
window.close()
}}>关闭当前页</Button>
</Card>
</Fragment> : <Fragment>
<div className="login-register-title">欢迎您注册「PASSERMA」博客</div>
<Form onSubmit={this.handleSubmit} className="login-form">
<Form.Item className="login-form-realname">
{
getFieldDecorator('realnameReg', {
rules: [{
required: true,
message: '请输入用户名!'
},
{
max: 10,
message: '最大不能超过10个字符!'
},
{
pattern: /^((?!^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$).)*$/,
message: '用户名不能是邮箱!'
}],
})(
<Input
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="用户名"
onBlur={this.getRealname}
addonAfter={canRealname ? <Icon type="check-circle" theme="twoTone" twoToneColor="#52c41a" />
: <Icon title="用户名已被使用" type="close-circle" theme="twoTone" twoToneColor="red" />}
/>,
)}
{
}
</Form.Item>
<span className="login-from-realname-tip">
<Tooltip title="用户名设置后无法修改噢">
<Icon type="warning" theme="twoTone" />
</Tooltip>
</span>
<Form.Item>
{
getFieldDecorator('usernameReg', {
rules: [{
required: true,
message: '请输入邮箱!'
},
{
pattern: /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/,
message: '请输入正确的邮箱!'
}],
})(
<Input
prefix={<Icon type="mail" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="邮箱"
/>,
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('passwordReg', {
rules: [{
required: true,
message: '请输入密码!'
},
{
pattern: /(?=.*([a-zA-Z].*))(?=.*[0-9].*)[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,20}$/,
message: '密码至少包含数字和字母!'
},
{
min: 6,
message: '密码长度需在6-20位!'
},
{
max: 20,
message: '密码长度需在6-20位!'
}],
})(
<Input.Password
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="密码"
visibilityToggle
/>,
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('passwordRegCom', {
rules: [{
validator: (rule, value, callback) => {
if (value === this.props.form.getFieldValue('passwordReg')) {
callback()
} else {
callback('两次密码输入不一样!')
}
}
}],
})(
<Input.Password
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="再次输入密码"
/>,
)}
</Form.Item>
<Form.Item>
<Row>
<Col span={12}>
{getFieldDecorator('code', {
rules: [{
required: true,
message: '请输入验证码!'
}],
})(<Input
prefix={<Icon type="safety" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="验证码"
/>)}
</Col>
<Col span={12}>
<Button disabled={this.codeTime === null ? false : true} onClick={this.getCode}>{btnText}</Button>
</Col>
</Row>
</Form.Item>
<Form.Item style={{ textAlign: 'center' }}>
<Button loading={loading}
type="primary"
htmlType="submit"
className="login-form-button">注册</Button>
</Form.Item>
</Form>
</Fragment>
}
</div>
);
}
}
const Login = Form.create({})(LoginForm);
export default connect()(withRouter(Login));
|
package main
func solution(s string) int {
// Inicializa um mapa para armazenar a posição do último caractere visto
lastSeen := make(map[rune]int)
// Inicializa variáveis para armazenar o início da substring e o tamanho máximo
start := 0
maxLength := 0
// Percorre a string
for i, char := range s {
// Se o caractere já foi visto e está dentro da janela atual,
// atualiza o início da substring para a posição após a última ocorrência do caractere
if idx, ok := lastSeen[char]; ok && idx >= start {
start = idx + 1
}
// Atualiza a posição do último caractere visto
lastSeen[char] = i
// Atualiza o tamanho máximo da substring sem caracteres repetidos
if length := i - start + 1; length > maxLength {
maxLength = length
}
}
return maxLength
}
func main() {
// Testa a função com exemplos
examples := []string{"abcabcbb", "zzzabcdzzz"}
for _, ex := range examples {
result := solution(ex)
println("Entrada:", ex, "\nSaída:", result, "\n")
}
}
|
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use Monken\CIBurner\OpenSwoole\Worker;
use OpenSwoole\Http\Request;
use OpenSwoole\Http\Response;
use OpenSwoole\WebSocket\Frame;
use OpenSwoole\WebSocket\Server;
class OpenSwoole extends BaseConfig
{
/**
* Swoole Http Driver.
* You can use OpenSwoole\Http\Server or OpenSwoole\WebSocket\Server .
*
* @var string
*/
public $httpDriver = Server::class;
/**
* TCP HTTP service listening ip
*
* @var string
*/
public $listeningIp = '0.0.0.0';
/**
* TCP HTTP service listening port
*
* @var int
*/
public $listeningPort = 8080;
/**
* Which mode to start the server in SWOOLE_PROCESS or SWOOLE_BASE
*
* @var int
*
* @see https://openswoole.com/docs/modules/swoole-server-construct
*/
public $mode = SWOOLE_PROCESS;
/**
* The socket type of the server.
*
* @var int
*
* @see https://openswoole.com/docs/modules/swoole-server-construct
*/
public $type = SWOOLE_SOCK_TCP;
/**
* Swoole Setting Configuration Options
*
* @var array
*
* @see https://openswoole.com/docs/modules/swoole-http-server/configuration
* @see https://openswoole.com/docs/modules/swoole-server/configuration
*/
public $config = [
'worker_num' => 1,
'daemonize' => false,
'max_request' => 0,
'document_root' => '{{static_path}}',
'enable_static_handler' => true,
'log_level' => 0,
'log_file' => '{{log_path}}',
];
/**
* Maximum number of connections that can be stored in the Websocket pool at the same time.
* It is recommended that this value be as large as memory allows.
*
* @var int
*/
public $websocketPoolSize = 10240;
/**
* Whether to open the Key/Value Cache provided by Burner.
* Shared high-speed caching with Swoole-Table implementation.
*
* @var bool
*/
public $fastCache = false;
/**
* Buerner Swoole-Table Driver Settings
*
* @var string[]
*/
public $fastCacheConfig = [
// Periodically check the interval of expired data in the cache in ms.
'ttlRecyclerTimer' => 1000,
// Number of rows of the burner cache table
'tableSize' => 4096,
// Key/value key Maximum length of string
'keyLength' => 1024,
// The maximum length of the key/value (if the save type is object, array, string).
'valueStringLength' => 1024,
];
/**
* Auto-scan changed files
*
* @var bool
*/
public $autoReload = false;
/**
* Auto Reload Mode
*
* @var string restart or reload
*/
public $autoReloadMode = 'restart';
/**
* Auto-scan of the root directory
*
* @var string
*/
public $autoReloadDir = '{{reload_path}}';
/**
* Files with these filename-extension will be auto-scanned.
*
* @var array
*/
public $autoReloadScanExtensions = ['php', 'env'];
/**
* The Swoole-Start event is registered by Burner.
* If you need to use the Start event, please declare it in this method.
*
* @return void
*/
public function serverStart(Server $server)
{
}
/**
* You can declare some additional server setting in this method.
*
* @return void
*/
public function server(Server $server)
{
// Please do not register the 'start' event repeatedly.
$server->on('open', static function (Server $server, Request $request) {
Worker::setWebsocket($request);
Worker::push(
data: 'hi! It\'s Burner Websocket!',
fd: $request->fd
);
});
$server->on('message', static function (Server $server, Frame $frame) {
// Burner handles CodeIgniter4 entry points.
Worker::websocketProcesser($frame, static function (Server $server, Frame $frame) {
// Not Found Handling
});
});
$server->on('request', static function (Request $swooleRequest, Response $swooleResponse) {
// Burner handles CodeIgniter4 entry points.
Worker::httpProcesser($swooleRequest, $swooleResponse);
});
$server->on('close', static function (Server $server, int $fd) {
Worker::unsetWebsocket($fd);
fwrite(STDOUT, sprintf(
"client-%d is closed\n",
$fd,
));
});
}
}
|
import axios, { AxiosRequestConfig, AxiosInstance } from 'axios';
interface AxiosConfig extends AxiosRequestConfig {
baseURL: string | undefined;
withCredentials: boolean;
// headers: {
// [key: string]: string | undefined;
// };
}
// const readTokenFromCookies = (): string | undefined => {
// const cookies = document.cookie.split(";");
// const token = cookies.find((cookie) => cookie.includes("token"));
// return token?.split("=")[1];
// };
const clearTokenFromCookies = (): void => {
document.querySelectorAll('cookie').forEach((cookie) => cookie.remove());
};
const axiosConfig: AxiosConfig = {
baseURL: 'import.meta.env.VITE_BASE_API_URL',
withCredentials: true,
// headers: {
// Authorization: `Basic ${btoa(
// `${import.meta.env.VITE_BASE_API_USERNAME}:${
// import.meta.env.VITE_BASE_API_PASSWORD
// }`
// )}`,
// },
};
const client: AxiosInstance = axios.create(axiosConfig);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleFailedRequest = (error: any): Promise<never> => {
const status = error?.response?.status;
if (status === 401 || status === 403) {
clearTokenFromCookies();
window.location.replace('/login');
}
return Promise.reject(error);
};
const request = async function (options: AxiosRequestConfig) {
try {
const response = await client(options);
return response.data;
} catch (error) {
return handleFailedRequest(error);
}
};
export default request;
|
<script lang="ts" setup>
import type { Task } from '@/types.ts';
import BaseCheckbox from '@/components/ui/Checkbox/BaseCheckbox.vue';
import Styles from './style.module.scss';
import { useTaskStore } from '@/stores/task';
const props = defineProps<{ task: Task }>();
const newTitle = defineModel('title', { type: String, default: '' });
const newDescription = defineModel('description', { type: String, default: '' });
const checked = defineModel('checked', { type: Boolean, default: false });
let isEdit: boolean = false;
const taskStore = useTaskStore();
newTitle.value = props.task.title;
newDescription.value = props.task.description;
checked.value = props.task.isDone;
function deleteTask() {
taskStore.taskDelete(props.task.id);
}
function editTask() {
taskStore.taskEdit({
id: props.task.id,
description: newDescription.value,
title: newTitle.value,
isDone: checked.value
});
isEdit = !isEdit;
}
function taskMake() {
taskStore.taskMake(props.task.id, checked.value);
}
</script>
<template>
<div :class="[Styles.task, 'qd-shadow']">
<div :class="Styles.bodyTask">
<BaseCheckbox v-model="checked" @on-change="taskMake" />
<div :class="Styles.text">
<label :class="Styles.label">
Задача:
<input class="qd-input" v-if="isEdit" type="text" v-model="newTitle" />
<span v-else>{{ task.title }}</span>
</label>
<label :class="Styles.label">
Описание:
<textarea class="qd-input" v-if="isEdit" type="text" v-model="newDescription" />
<span v-else>{{ task.description }}</span>
</label>
</div>
</div>
<div :class="Styles.buttons">
<button type="button" class="qd-button" @click="editTask">
<span v-if="isEdit">Изменить</span>
<span v-else>Редактировать</span>
</button>
<button type="button" class="qd-button" @click="deleteTask">Удалить</button>
</div>
</div>
</template>
|
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define RED_LED_ON HAL_GPIO_WritePin(GPIOB, LED_Red_Pin, GPIO_PIN_SET)
#define RED_LED_OFF HAL_GPIO_WritePin(GPIOB, LED_Red_Pin, GPIO_PIN_RESET)
#define RED_LED_TOGLE HAL_GPIO_TogglePin(GPIOB, LED_Red_Pin)
#define GREEN_LED_ON HAL_GPIO_WritePin(GPIOB, LED_Green_Pin, GPIO_PIN_SET)
#define GREEN_LED_OFF HAL_GPIO_WritePin(GPIOB, LED_Green_Pin, GPIO_PIN_RESET)
#define GREEN_LED_TOGLE HAL_GPIO_TogglePin(GPIOB, LED_Green_Pin)
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
RTC_HandleTypeDef hrtc;
UART_HandleTypeDef huart1;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_RTC_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
// -----------------------------------------------------------------------------------------------
void led_test_blink(uint16_t times, uint16_t delay)
{
for(int i = 0; i <= times; i++)
{
RED_LED_ON;
GREEN_LED_ON;
HAL_Delay(delay);
RED_LED_OFF;
GREEN_LED_OFF;
HAL_Delay(delay);
}
}
// -----------------------------------------------------------------------------------------------
void read_time_internal_RTC(void)
{
RTC_TimeTypeDef sTime;
RTC_DateTypeDef sDate;
HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN);
HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN);
uint8_t buffer = 0;
uint8_t time_RTC[10] = {0,};
char buf_uart_tx[70] = {0,};
memset(buf_uart_tx, 0, sizeof(buf_uart_tx));
sprintf(buf_uart_tx, "TIME %d:%d:%d \n\r", sTime.Hours, sTime.Minutes, sTime.Seconds);
HAL_UART_Transmit(&huart1, buf_uart_tx, sizeof(buf_uart_tx), 1000);
}
// -----------------------------------------------------------------------------------------------
void set_time_internal_RTC(void)
{
RTC_TimeTypeDef sTime;
RTC_DateTypeDef sDate;
sTime.Hours = 0x0B; // 11
sTime.Minutes = 0x0C; // 12
sTime.Seconds = 0x0D; // 13
sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
sTime.StoreOperation = RTC_STOREOPERATION_RESET;
if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
}
// --------------------------------------------------------------------------------------
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_RTC_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
read_time_internal_RTC();
HAL_Delay(1000);
set_time_internal_RTC();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
read_time_internal_RTC();
HAL_Delay(1000);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSE;
RCC_OscInitStruct.LSEState = RCC_LSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 64;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 4;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief RTC Initialization Function
* @param None
* @retval None
*/
static void MX_RTC_Init(void)
{
/* USER CODE BEGIN RTC_Init 0 */
/* USER CODE END RTC_Init 0 */
RTC_TimeTypeDef sTime = {0};
RTC_DateTypeDef sDate = {0};
/* USER CODE BEGIN RTC_Init 1 */
/* USER CODE END RTC_Init 1 */
/** Initialize RTC Only
*/
hrtc.Instance = RTC;
hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
hrtc.Init.AsynchPrediv = 127;
hrtc.Init.SynchPrediv = 255;
hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
if (HAL_RTC_Init(&hrtc) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN Check_RTC_BKUP */
/* USER CODE END Check_RTC_BKUP */
/** Initialize RTC and set the Time and Date
*/
sTime.Hours = 0x0;
sTime.Minutes = 0x0;
sTime.Seconds = 0x0;
sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
sTime.StoreOperation = RTC_STOREOPERATION_RESET;
if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
sDate.WeekDay = RTC_WEEKDAY_MONDAY;
sDate.Month = RTC_MONTH_JANUARY;
sDate.Date = 0x1;
sDate.Year = 0x0;
if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN RTC_Init 2 */
/* USER CODE END RTC_Init 2 */
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, LED_Red_Pin|LED_Green_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : LED_Red_Pin LED_Green_Pin */
GPIO_InitStruct.Pin = LED_Red_Pin|LED_Green_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
|
import { ConfigService } from '@nestjs/config';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { PassportStrategy } from '@nestjs/passport';
import { Model } from 'mongoose';
import { User } from '../schemas';
import { JwtPayload } from '../interfaces';
/**
* Estrategia de autenticación JWT.
*
* Esta estrategia se utiliza para validar el token JWT
* y devolver el usuario correspondiente.
*/
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectModel(User.name)
private readonly userModel: Model<User>,
configService: ConfigService,
) {
super({
secretOrKey: configService.get('JWT_SECRET'),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
});
}
/**
* Valida el token JWT y devuelve el usuario correspondiente.
* @param payload El objeto de carga útil del token JWT.
* @throws UnauthorizedException si el usuario no existe o si no esta ACTIVE.
* @returns El usuario correspondiente.
*/
async validate(payload: JwtPayload): Promise<User> {
const { UUID } = payload;
const user = await this.userModel.findById({ _id: UUID });
if (!user) throw new UnauthorizedException('Unauthorized');
if (user.status !== 'ACTIVE') {
const code = user.status.toLowerCase();
throw new UnauthorizedException(`Unauthorized, user ${code}`);
}
return user;
}
}
|
import gymnasium as gym
import numpy as np
from data_generator import generate_data
from stable_baselines3 import PPO, DQN, DDPG
from stable_baselines3.ppo.policies import MlpPolicy
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.noise import NormalActionNoise
import argparse
def CartPole():
env = gym.make("CartPole-v1", render_mode='rgb_array')
model = PPO(MlpPolicy, env, verbose=1)
# -------------------------------
mean_reward, std_reward = evaluate_policy(model, env, n_eval_episodes=100, warn=False)
print(f"mean_reward: {mean_reward:.2f} +/- {std_reward:.2f}")
# -------------------------------
model.learn(total_timesteps=int(1.0e5), log_interval=5)
mean_reward, std_reward = evaluate_policy(model, env, n_eval_episodes=100)
print(f"mean_reward:{mean_reward:.2f} +/- {std_reward:.2f}")
generate_data('CartPole', env, model)
env.close()
def MountainCar():
env = gym.make("MountainCar-v0", render_mode="rgb_array")
dqn_model = DQN(
"MlpPolicy",
env,
verbose=1,
train_freq=16,
gradient_steps=8,
gamma=0.99,
exploration_fraction=0.2,
exploration_final_eps=0.07,
target_update_interval=600,
learning_starts=1000,
buffer_size=10000,
batch_size=128,
learning_rate=4e-3,
policy_kwargs=dict(net_arch=[256, 256]),
seed=2,
)
mean_reward, std_reward = evaluate_policy(
dqn_model,
dqn_model.get_env(),
deterministic=True,
n_eval_episodes=20,
)
print(f"mean_reward:{mean_reward:.2f} +/- {std_reward:.2f}")
dqn_model.learn(int(1.2e5), log_interval=10)
mean_reward, std_reward = evaluate_policy(dqn_model, dqn_model.get_env(), deterministic=True, n_eval_episodes=20)
print(f"mean_reward:{mean_reward:.2f} +/- {std_reward:.2f}")
generate_data('MountainCar', env, dqn_model)
env.close()
def Pendulum():
env = gym.make("Pendulum-v1", render_mode="rgb_array")
# The noise objects for DDPG
n_actions = env.action_space.shape[-1]
action_noise = NormalActionNoise(mean=np.zeros(n_actions), sigma=0.1 * np.ones(n_actions))
model = DDPG("MlpPolicy", env, action_noise=action_noise, verbose=1)
model.learn(total_timesteps=10000, log_interval=10)
vec_env = model.get_env()
generate_data('Pendulum', vec_env, model, vec_env=True)
env.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--env', type=str, default='CartPole', choices=['CartPole', 'MountainCar', 'Pendulum'])
args = parser.parse_args()
if args.env == 'CartPole':
CartPole()
elif args.env == 'MountainCar':
MountainCar()
elif args.env == 'Pendulum':
Pendulum()
else:
print('invalid env')
exit(1)
|
-- Exercise 1 (done for you): Selecting all columns
SELECT * FROM users;
-- Exercise 2 (done for you): Selecting some columns
SELECT id, first_name, last_name
FROM users;
-- Exercise 3: Sorting
SELECT id, first_name, last_name FROM users ORDER BY last_name;
-- Exercise 4: Filtering
SELECT id, user_id, image_url FROM posts WHERE user_id = 26;
-- Exercise 5: Filtering with logical operators
SELECT id, user_id, image_url FROM posts WHERE user_id = 26 OR user_id = 12;
-- Exercise 6: Using functions in a select statement
SELECT count(posts) FROM posts;
-- Exercise 7: Aggregating data
SELECT user_id, COUNT(*) as count
FROM comments
GROUP BY user_id
ORDER BY count DESC;
-- Exercise 8: Joining: two tables
SELECT p.id, p.image_url, p.user_id, u.username, u.first_name, u.last_name
FROM posts p
JOIN users u
ON p.user_id = u.id
WHERE p.user_id = 26 OR p.user_id = 12;
-- Exercise 9: More joining practice: two tables
SELECT p.id, p.pub_date, f.following_id
FROM posts p
JOIN following f
ON p.user_id = f.following_id
WHERE f.user_id = 26;
-- Exercise 10: More joining practice: three tables (Optional)
-- Exercise 11: Inserting records
INSERT INTO bookmarks (user_id, post_id, timestamp)
VALUES(26, 219, CURRENT_TIMESTAMP);
INSERT INTO bookmarks (user_id, post_id, timestamp)
VALUES(26, 220, CURRENT_TIMESTAMP);
INSERT INTO bookmarks (user_id, post_id, timestamp)
VALUES(26, 221, CURRENT_TIMESTAMP);
-- Exercise 12: Deleting records
DELETE FROM bookmarks
WHERE post_id=219;
DELETE FROM bookmarks
WHERE post_id=220;
DELETE FROM bookmarks
WHERE post_id=221;
-- Exercise 13: Updating records
UPDATE users
SET email = '[email protected]'
WHERE id=26;
-- Exercise 14: More Querying Practice (Optional)
|
package zad2;
public class StringTask implements Runnable{
private final String threadLetter;
private volatile int numberOfDuplicates;
private TaskState state;
private volatile String concatString;
private Thread thread;
public StringTask(String threadLetter, int numberOfDuplicated) {
this.threadLetter = threadLetter;
this.numberOfDuplicates = numberOfDuplicated;
state = TaskState.CREATED;
concatString = "";
}
public void start() {
thread = new Thread(this);
thread.start();
state = TaskState.RUNNING;
}
public void abort(){
state = TaskState.ABORTED;
thread.interrupt();
}
public TaskState getState() {
return state;
}
public boolean isDone() {
return state == TaskState.READY || state == TaskState.ABORTED;
}
public String getResult() {
return concatString;
}
@Override
public void run() {
for (int i = 0; i < numberOfDuplicates; i++) {
if (Thread.currentThread().isInterrupted()) {
return;
}
concatString += threadLetter;
}
state = TaskState.READY;
}
}
enum TaskState{
CREATED, RUNNING, ABORTED, READY
}
|
import { useDispatch, useSelector } from 'react-redux';
import './App.css';
import { fetchCustomers } from './asyncAction/customers';
import { acyncAddCashAction, acyncGetCashAction, addCashAction, getCashAction } from './store/cashReducer';
import { acyncAddManyCustomersAction, addCustomerAction, removeCustomerAction } from './store/customerReducer';
function App() {
const dispatch = useDispatch()
const cash = useSelector(state => state.cash.cash)
const customers = useSelector(state => state.customers.customers)
const removeCustomer = (customer) => {
dispatch(removeCustomerAction(customer.id))
}
return (
<div className="app">
<div>{cash}</div>
<div style={{display: 'flex', justifyContent: 'center'}}>
<button onClick={() => dispatch(acyncAddCashAction())}>Пополнить счет</button>
<button onClick={() => dispatch(acyncGetCashAction())}>Снять со счета</button>
<button onClick={() => dispatch(acyncAddManyCustomersAction())}>Получить клиентов из базы</button>
</div>
{customers.length > 0 ?
<div>
{customers.map(customer =>
<div onClick={() => removeCustomer(customer)} style={{fontSize: '2rem', border: '1px solid black', padding: '10px 10px'}}>
{customer.name}
</div>
)}
</div> :
<div style={{fontSize: '2rem'}}>
Клиенты отсутствуют!
</div>
}
</div>
);
}
export default App;
|
import React, { ChangeEventHandler } from 'react'
type Props = {
id?: string
name?: string
checked?: boolean
onChange?: ChangeEventHandler<HTMLInputElement>
}
const Checkbox = ({ id, name, checked, onChange }: Props) => {
return (
<input
type="checkbox"
id={id}
name={name || id}
checked={checked}
onChange={onChange}
className='w-4 h-4 text-blue-600 bg-gray-100 rounded border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' />
)
}
export default Checkbox
|
import { useContext } from "react";
import { CartContext } from "../../contexts/cart.context";
import Button from "../button/button.component";
import "./product-card.styles.scss";
const ProductCard = ({ product }) => {
const { title, price, image } = product;
const { addItemToCart } = useContext(CartContext);
const addProductToCart = () => addItemToCart(product);
return (
<div className="product-card-container">
<img src={image} alt={title} />
<div className="footer">
<span className="name">{title.slice(0, 20)}</span>
<span className="price">$ {price}</span>
</div>
<Button buttonType="inverted" onClick={addProductToCart}>
Add to card
</Button>
</div>
);
};
export default ProductCard;
|
% Final Project – Analysis of Motor Imagery Data
% submitted by; 208394502 & 315341685
%%
clear; %clear all variables
close all; %close all figures
clc; %clear command window
%% setting parameters
freq = 1:0.1:40; % [Hz]
TITLE_FONT = 22;
channel_vec = {'C3' , 'C4'};
n_channel = length(channel_vec); % num of Channels
c3 = 1;
c4 = 2;
left_row = 3;
right_row = 4;
sub_plots_for_vis = 20;
%% Part 1 - Visualization
% Part 1.1 Loading the training data
load('motor_imagery_train_data.mat');
fs = P_C_S.samplingfrequency; % [Hz]
class_vec = (P_C_S.attributename(left_row:right_row))'; % Left & Right Hands
n_class = length(class_vec); % num of Classes
left_hand_trials = P_C_S.attribute(left_row, :);
right_hand_trials = P_C_S.attribute(right_row, :);
training_data = P_C_S.data(:, :, 1 : n_channel); % extracting data only for C3 & C4
n_trials = size(training_data, 1); % num of Trials
time_samples = size(training_data, 2); % num of Samples
time_vec_sec = (1:time_samples) / fs; % time vector in seconds
% Left Hand
left_trial = find(left_hand_trials == 1); % finding the trials tagged - Left hand
left_hand_matrix = training_data(left_trial, :, :); % data matrix specifcly for left hand tagged trials
left_rand_trials = left_trial(randperm(sub_plots_for_vis));
% Right Hand
right_trial = find(right_hand_trials == 1); % finding the trials tagged - Right hand
right_hand_matrix = training_data(right_trial, :, :); % data matrix specifcly for right hand tagged trials
right_rand_trials = right_trial(randperm(sub_plots_for_vis));
% part 1.2 - Visualizing the EEG signal in a single channel for trials from a single class
title_str = ['Visualizing EEG signal in a single channel'];
n_rows = 5;
n_cols = 4;
figure('Name', [title_str ' - left hand'], ...
"Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
plot_EEG(left_hand_matrix, title_str, n_rows, n_cols, time_vec_sec, left_rand_trials, class_vec{1});
figure('Name', [title_str ' - right hand'], ...
"Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
plot_EEG(right_hand_matrix, title_str, n_rows, n_cols, time_vec_sec, right_rand_trials, class_vec{2});
%% Part 2 - Power Spectra
% Difining parameters
title_power = ['Power spectrum using Welchs method for both hands'];
n_rows = 2;
n_cols = 1;
time_seg = 3*fs : time_samples; % imagine time of trials
window = 1*fs; % length of window time
overlap = 0.9 * window; % size of overlap between windows
% Part 2.1 Calculating Power Spectrim from trials in each class
pwelch_left_c3 = pwelch(left_hand_matrix(:, time_seg, c3)', window, overlap, freq, fs);
pwelch_left_c4 = pwelch(left_hand_matrix(:, time_seg, c4)', window, overlap, freq, fs);
pwelch_right_c3 = pwelch(right_hand_matrix(:, time_seg, c3)', window, overlap, freq, fs);
pwelch_right_c4 = pwelch(right_hand_matrix(:, time_seg, c4)', window, overlap, freq, fs);
cell_left = {pwelch_left_c3, pwelch_left_c4};
cell_right = {pwelch_right_c3, pwelch_right_c4};
% Part 2.2 Plot a spectrum for each class and each channel
% added a 1-standart_deviation confidence interval onto the plots
figure('Name', title_power, "Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
plot_power_spec(cell_left, cell_right, title_power, freq, time_vec_sec(time_seg(1)), ...
time_vec_sec(time_seg(end)));
% Part 2.3 Spectograms
title_specto = ['Spectrograms for each channel and hand'];
n_rows = 2;
n_cols = 2;
cell_spec = cell(n_channel, n_class);
num_of_windows = floor((time_samples - window) / (window - overlap)); % num of windows the data will divide into
% Spectrograms of each class and each channel
figure('Name', title_specto, "Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
sgtitle(title_specto, "FontSize", TITLE_FONT, "FontWeight", "bold");
subplot_pos = 1;
for which_channel = 1 : n_channel
[cell_spec{left_row-2, which_channel}, f, t] = compute_spec(left_hand_matrix, which_channel, ...
window, floor(overlap), freq, fs, num_of_windows);
plot_spectro(cell_spec{left_row-2, which_channel}, f, t, n_rows, n_cols, subplot_pos, "Left", ...
which_channel);
subplot_pos = subplot_pos + 1;
[cell_spec{right_row-2, which_channel}, f, t] = compute_spec(right_hand_matrix, which_channel, ...
window, floor(overlap), freq, fs, num_of_windows);
plot_spectro(cell_spec{right_row-2, which_channel}, f, t, n_rows, n_cols, subplot_pos, "Right", ...
which_channel);
subplot_pos = subplot_pos + 1;
end
% Spectrogram of the mean difference between the 2 Channels; C3 & C4
% - were helpful during our features selection process
diff_cell = cell(n_channel, 1);
diff_str = ['Difference between Left hand to Right hand Spectrograms in both Channels'];
figure("Name",diff_str,"Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
sgtitle(diff_str, "FontSize", TITLE_FONT, "FontWeight", "bold");
for channel = 1 : n_channel
diff_cell{channel} = abs(cell_spec{1, channel} - cell_spec{2, channel});
plot_spectro(diff_cell{channel}, f, t, n_channel, size(diff_cell,2), -1, ...
"Left hand to Right hand Spectrograms", channel);
end
%% Part 3 - Features - finding features for motor imagery
% Part 3.1 Choosing informative frequency bands
n_bands = 3;
info_bands = cell(n_bands, 2);
% frequency [Hz] % Which Electrode
info_bands{1,1} = [15 18.3]; info_bands{1,2} = "C3";
info_bands{2,1} = [15 17.2]; info_bands{2,2} = "C4";
info_bands{3,1} = [30.5 33]; info_bands{3,2} = "C4";
band_power_cell = cell(n_bands, n_bands);
for bp = 1 : n_bands
[band_power_cell{bp,1}, band_power_cell{bp,2}, band_power_cell{bp,3}] = compute_band(training_data, ...
left_hand_matrix(:, time_seg, :), right_hand_matrix(:, time_seg, :), fs, info_bands{bp,1}, info_bands{bp,2});
end
% Part 3.2 plot Histograms depicting the power distribution
title_histo = ['Band-Power feature histograms in 3 different frequency bands'];
figure('Name', title_histo, "Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
sgtitle(title_histo, "FontSize", TITLE_FONT, "FontWeight", "bold");
plot_histo(band_power_cell, info_bands, n_bands);
%% Part 3.2 adding more features besides power-bands
% Root Total Power - adding another feature
% for every class every Channel (C3 & C4) we'll compute the total root power, this
% std gives proportionnal assumption to the distance of the signal from avg
% we compute pwelch in windows from second 4 to 6
RTP_time = 4* fs : 6*fs; % Root Total Power computation time
RTP_window = 0.5 * fs; % length of RTP window
RTP_overlap = floor(49 / 50 * RTP_window); % size of overlap between windows in RTP computation
[RT_left_c3, RT_right_c3, RT_data_c3, RT_left_c4, RT_right_c4, RT_data_c4] = compute_rtp(training_data, ...
left_hand_matrix, right_hand_matrix, RTP_time, RTP_window, RTP_overlap, freq, fs);
%% Spectral Entropy - adding another feature
se_start_time = 4*fs; % Spectral Entropy start time - SE computation between second 4 to 6
[left_se_c3, time_se] = compute_se(left_hand_matrix, se_start_time, size(left_hand_matrix,1), fs, c3);
[right_se_c3, ~] = compute_se(right_hand_matrix, se_start_time, size(right_hand_matrix,1), fs, c3);
[feat_se_c3, ~] = compute_se(training_data, se_start_time, size(training_data,1), fs, c3);
%% STD in EEG Signal - adding another feature
% chosen time % channel
std_time1 = floor(4.25*fs : 4.9*fs); %C4
std_time2 = 5*fs : 6*fs; %C4
[~, ~, data_sig_std1] = compute_std(training_data, left_hand_matrix, right_hand_matrix, ...
std_time1, c4);
[left_sig_std2, right_sig_std2, data_sig_std2] = compute_std(training_data, left_hand_matrix, right_hand_matrix, ...
std_time2, c4);
%% STD in Power Spectrum - adding another feature
% chosen frequencies % chosen time % Channel
std_freq3 = [18: 0.05 : 21]; std_time3 = 2*fs : 3*fs; % C4
std_freq4 = [30: 0.05 : 33.5]; std_time4 = floor(4.5*fs : 5.5*fs); % C3
std_freq5 = [15: 0.05 : 17.3]; std_time5 = floor(4.5*fs : 6*fs); % C4
% feature of STD in the Power Spectrum between the 2 hands in freq
% 18 : 21 [Hz] in second 2 till 2 in Channel C4
[std_feat_ps_data1, std_feat_ps_left1, std_feat_ps_right1] = compute_ps_std(training_data, ...
left_hand_matrix, right_hand_matrix, std_time3, std_freq3, c4, window, overlap, fs);
% feature of std in power spectrum between the 2 hands in freq
% 30 : 33.5 [Hz] in second 4.5 till 5.5 in Channel C3
[std_feat_ps_data2, ~, ~] = compute_ps_std(training_data, left_hand_matrix, right_hand_matrix, std_time4, ...
std_freq4, c3, window, overlap, fs);
% feature of std in power spectrum between the 2 hands in freq
% 15 : 17.3 [Hz] in second 4.5 till 6 in Channel C4
[std_feat_ps_data3, std_feat_ps_left3, std_feat_ps_right3] = compute_ps_std(training_data, left_hand_matrix, ...
right_hand_matrix, std_time5, std_freq5, c4, window, overlap, fs);
%% Addintionnal BAND POWER feature
% chosen frequencies % Channel
bp_freq = [18.5 21]; % [Hz] % C4
bp_left_c4 = 10*log10(bandpower(left_hand_matrix(:,:,c4)', fs, bp_freq));
bp_right_c4 = 10*log10(bandpower(right_hand_matrix(:,:,c4)', fs, bp_freq));
bp_data_c4 = 10*log10(bandpower(training_data(:,:,c4)', fs, bp_freq));
%% Part 3.3 Ploting Histograms of additional features chosen
YL = '# Trials';
n_bins = 15;
figure("Name",'Additional Feature Histograms',"Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
sgtitle('Additional Feature Histograms', 'FontSize', TITLE_FONT, 'FontWeight', 'bold');
subplot(2,3,1);
plot_hist_feat(RT_left_c4, RT_right_c4, channel_vec{c4}, time_vec_sec(RTP_time(1)), ...
time_vec_sec(RTP_time(end)), 'Root Total Power', 'square sum of PS from mean', YL, ...
n_bins, 0.45);
subplot(2,3,2);
plot_hist_feat(left_se_c3, right_se_c3, channel_vec{c3}, time_vec_sec(se_start_time(1)), ...
time_vec_sec(end), 'Spectral Entropy in EEG signal', 'Spectral Entropy', YL, ...
n_bins, 0.006);
subplot(2,3,3);
plot_hist_feat(left_sig_std2, right_sig_std2, channel_vec{c4}, time_vec_sec(std_time2(1)), ...
time_vec_sec(std_time2(end)), 'STD in EEG signal', 'std', YL, ...
n_bins, 0.3);
subplot(2,3,4);
plot_hist_feat(std_feat_ps_left3, std_feat_ps_right3, channel_vec{c4}, time_vec_sec(std_time5(1)), ...
time_vec_sec(std_time5(end)), 'STD in PS frequencies 15:17.3 [Hz]', 'std', YL, ...
n_bins, 0.3);
subplot(2,3,5);
plot_hist_feat(std_feat_ps_left1, std_feat_ps_right1, channel_vec{c4}, time_vec_sec(std_time3(1)), ...
time_vec_sec(std_time3(end)), 'STD in PS frequencies 18:21 [Hz]', 'std', YL, ...
n_bins, 0.05);
subplot(2,3,6);
plot_hist_feat(bp_left_c4, bp_right_c4, channel_vec{c4}, 0, ...
time_vec_sec(end), 'Band Power in frequencies 18.5:21 [Hz]', 'dB', YL, ...
n_bins, 0.4);
legend('Left Hand', 'Right Hand', 'FontSize', 13, 'Position', [0.93 0.8 0.05 0.08]);
%% Part 3.4 features matrix including all features on all 128 trials % PCA
n_feat = 12; % num of features
features_matrix = zeros(n_trials,n_feat);
features_matrix(:, 1) = band_power_cell{1,3}(:);
features_matrix(:, 2) = band_power_cell{2,3}(:);
features_matrix(:, 3) = band_power_cell{3,3}(:);
features_matrix(:, 4) = feat_se_c3(:);
features_matrix(:, 5) = data_sig_std1(:);
features_matrix(:, 6) = data_sig_std2(:);
features_matrix(:, 7) = RT_data_c3(:);
features_matrix(:, 8) = RT_data_c4(:);
features_matrix(:, 9) = std_feat_ps_data1(:);
features_matrix(:, 10) = std_feat_ps_data2(:);
features_matrix(:, 11) = std_feat_ps_data3(:);
features_matrix(:, 12) = bp_data_c4(:);
features_matrix_norm = zscore(features_matrix, 0, 1); % normalizing feature matrix :)
% PCA
title_pca = ['Principal Components Analysis on Normalized Features Classified by Hand'];
[coeff, score, ~, ~, explained] = pca(features_matrix_norm);
figure("Name",title_pca,"Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
sgtitle(title_pca, 'FontSize', TITLE_FONT, 'FontWeight', 'bold');
plot_pca(score(:,1:2), score(:,1:3), left_trial, right_trial);
disp(sum(explained(1:3))); % displaying percentage of variance explained in the 3 PC selected
%% Part 4 - Calssification
% Defining parmaters
n_selected_features = 4; % num of selected features (from the total 12 features)
labels_vec = zeros(n_trials, 1); % we'll tag left hand trials with 1 and right hand trials with 0
labels_vec(left_trial) = 1;
feat_names = {'Band Power 15 : 18.3 in C3', 'Band Power 15 : 17.2 in C4', 'Band Power 30.5 : 33 in C4', ...
'Spectral Entropy fron second 4 to 6 in C3', 'std from second 4.25 to 4.9 in C4', ...
'std from second 5 to 6 in C4', 'Root Total Power in C3', ...
'Root Total Power in C4', 'std in PS freq 18 : 21 from second 2 to 3 in C4', ...
'std in PS freq 30 : 33.5 from second 4.5 to 5.5 in C3', ...
'std in PS freq 15 : 17.3 from second 4.5 to 6 in C4', 'Band Power 18.5 : 21 in C4'};
feat_channel = {channel_vec{c3}, channel_vec{c4}, channel_vec{c4}, channel_vec{c3}, channel_vec{c4}, ...
channel_vec{c4}, channel_vec{c3}, channel_vec{c4}, channel_vec{c4}, channel_vec{c3}, ...
channel_vec{c4}, channel_vec{c4}};
var_names = {'Feat_importance_ranking', 'Feat_channel', 'Feat_name'};
% Ranking our features & Selecting the best features in order to train our Classifier
[selected_features, selected_features_rank, features_rank] = select_features(features_matrix_norm, ...
n_selected_features, labels_vec, feat_names, feat_channel, var_names);
% Part 4.1 Training our Classifier
k = 5; % chosen k for the k-fold croos-validation algorithm
decimal2percent = 100; % var for displaying reasons
k_fold_sz = floor(n_trials / k); % set size of each k-fold group
% Randomizing trials
samples_rand = randperm(n_trials);
labels_rand = labels_vec(samples_rand);
feat_by_rank_rand_trials = selected_features(samples_rand, :);
% Let's train our Classifier & display it's results :)
train_my_classifier(feat_by_rank_rand_trials, labels_rand, k);
%% Part 4.3 Testing our Calssifier
testing_data = load("motor_imagery_test_data.mat").data(:, :, 1 : n_channel);
n_samples = size(testing_data, 1);
testing_features = zeros(n_samples, n_feat);
% Band Power Features
testing_band_cell = cell(1, n_bands);
for bp = 1 : n_bands
[~, ~, testing_band_cell{bp,3}] = compute_band(testing_data, ...
left_hand_matrix(:, time_seg, :), right_hand_matrix(:, time_seg, :), fs, info_bands{bp,1}, info_bands{bp,2});
end
% Spectral entropy Feature
[testing_se, ~] = compute_se(testing_data, time_seg, size(testing_data,1), fs, c3);
% STD in EEG signal Feature
[~, ~, test_sig_std1] = compute_std(testing_data, left_hand_matrix, right_hand_matrix, ...
std_time1, c4);
[~, ~, test_sig_std2] = compute_std(testing_data, left_hand_matrix, right_hand_matrix, ...
std_time2, c4);
% Root Total Power Feature
[~, ~, RT_test_c3, ~, ~, RT_test_c4] = compute_rtp(testing_data, ...
left_hand_matrix, right_hand_matrix, RTP_time, RTP_window, RTP_overlap, freq, fs);
% STD in Power Spectrum Feature
[test_ps_std1, ~, ~] = compute_ps_std(testing_data, left_hand_matrix, right_hand_matrix, std_time3, ...
std_freq3, c4, window, overlap, fs);
[test_ps_std2, ~, ~] = compute_ps_std(testing_data, left_hand_matrix, right_hand_matrix, std_time4, ...
std_freq4, c3, window, overlap, fs);
[test_ps_std3, ~, ~] = compute_ps_std(testing_data, left_hand_matrix, right_hand_matrix, ...
std_time5, std_freq5, c4, window, overlap, fs);
% Band Power Feature
test_bp = 10*log10(bandpower(testing_data(:,:,c4)', fs, bp_freq));
testing_features(:, 1) = testing_band_cell{1, 3}(:);
testing_features(:, 2) = testing_band_cell{2, 3}(:);
testing_features(:, 3) = testing_band_cell{3, 3}(:);
testing_features(:, 4) = testing_se(:);
testing_features(:, 5) = test_sig_std1(:);
testing_features(:, 6) = test_sig_std2(:);
testing_features(:, 7) = RT_test_c3(:);
testing_features(:, 8) = RT_test_c4(:);
testing_features(:, 9) = test_ps_std1(:);
testing_features(:, 10) = test_ps_std2(:);
testing_features(:, 11) = test_ps_std3(:);
testing_features(:, 12) = test_bp(:);
testing_features_norm = zscore(testing_features, 0, 1);
testing_features_selected = testing_features_norm(:, selected_features_rank);
testing_data_classify = classify(testing_features_selected, selected_features, labels_vec, 'linear');
% Displaying parameters;
fprintf(['Num of Channels -\t ' num2str(n_channel) ...
'\nNum of training samples -\t ' num2str(size(training_data,1)) ...
'\nNum of testing samples -\t ' num2str(size(testing_data,1)) ...
'\nSampling rate -\t ' num2str(fs) ...
'\nWindow size -\t ' num2str(window) ...
'\nOverlap size -\t ' num2str(overlap) ...
'\nDisplayed Frequencies :\t ' num2str(freq(1)) ' - ' num2str(freq(end)) ...
'\nK fold -\t ' num2str(k) ...
'\n\n']);
%% Part 4.2 Improving Accuracy
% why we chose set of 4 features for training our classifier
for test = 1 : 4
n_selected_features = n_selected_features + 2;
feat_test = features_matrix_norm(:, features_rank(1:n_selected_features));
samples_rand = randperm(n_trials);
labels_rand = labels_vec(samples_rand);
feat_by_rank_rand_trials = feat_test(samples_rand, :);
train_my_classifier(feat_by_rank_rand_trials, labels_rand, k);
end
%% Apendix Plots
% Histograms of Root Total Power, why we chose it's own window and overlap
% val -- shows better sicrimination:
[RT_left_c3_reg, RT_right_c3_reg, ~, RT_left_c4_reg, RT_right_c4_reg, ~] = compute_rtp(training_data, ...
left_hand_matrix, right_hand_matrix, RTP_time, window, overlap, freq, fs);
XL = 'square sum of PS from mean';
appendix_str = 'Root Total Power with 1 sec window and 0.9 overlap size';
appendix_str_C3 = [appendix_str ' in Channel ' channel_vec{1}];
figure("Name", appendix_str_C3, "Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
histogram(RT_left_c3_reg, n_bins, "BinWidth", 0.35);
hold on;
histogram(RT_right_c3_reg, n_bins, "BinWidth", 0.35);
title(appendix_str_C3, "FontSize", TITLE_FONT, "FontWeight", "bold");
xlabel(XL, "FontSize", 18);
ylabel(YL, "FontSize", 18);
hold off;
appendix_str_C4 = [appendix_str ' in Channel ' channel_vec{2}];
figure("Name", appendix_str_C4, "Color", 'w', 'Units', 'normalized', 'windowstate','maximized');
histogram(RT_left_c4_reg, n_bins, "BinWidth", 0.35);
hold on;
histogram(RT_right_c4_reg, n_bins, "BinWidth", 0.35);
title(appendix_str_C4, "FontSize", TITLE_FONT, "FontWeight", "bold");
xlabel(XL, "FontSize", 18);
ylabel(YL, "FontSize", 18);
hold off;
% end
|
'use client';
import { BrowserRouter, Route, Routes } from "react-router-dom";
import MobileNavigation from "./Menucomps/MobileNavigation";
import SideNavigation from "./Menucomps/SideNavigation";
import TopNavigation from "./Menucomps/TopNavigation";
import Signup from "./Pages/Signup";
import Dashboard from "./Pages/Dashboard";
import Search from "./Pages/Search";
import Projects from "./Pages/Projects";
import Saved from "./Pages/Saved";
import Settings from "./Pages/Settings";
import EditProfile from "./Components/EditProfile";
import Notifications from "./Components/Notifications";
import FilteredContent from "./Components/FilteredContent";
import SecuritySettings from "./Components/SecuritySettings";
import { UserProvider } from "./Context/UserContext";
import Login from "./Pages/Login";
import EducationProjects from "./Projectscategory/EducationProjects";
import AgricProjects from "./Projectscategory/AgricProjects";
import FinanceProjects from "./Projectscategory/FinanceProjects";
import HealthProjects from "./Projectscategory/HealthProjects"
import SportsProjects from "./Projectscategory/SportsProjects"
import TourismProjects from "./Projectscategory/TourismProjects"
function App() {
return (
<UserProvider>
<BrowserRouter>
<>
<div className="">
<div className="fixed w-full z-50 bg-slate-50 md:px-10 lg:px-5">
<TopNavigation/>
</div>
<SideNavigation/>
<MobileNavigation/>
<Routes>
<Route path="/" element={<Signup/>}/>
<Route path="/login" element={<Login/>}/>
<Route path="/dashboard" element={<Dashboard/>} />
<Route path="/search" element={<Search/>} />
<Route path="/projects" element={<Projects/>} />
<Route path="/saved" element={<Saved/>} />
<Route path="/settings" element={<Settings/>} />
<Route path="/editprofile" element={<EditProfile/>}/>
<Route path="/notifications" element={<Notifications/>}/>
<Route path="/FilteredContent" element={<FilteredContent/>}/>
<Route path="/securitysettings" element={<SecuritySettings/>}/>
<Route path="/educationprojects" element={<EducationProjects/>}/>
<Route path="/agricprojects" element={<AgricProjects/>}/>
<Route path="/financeprojects" element={<FinanceProjects/>}/>
<Route path="/healthprojects" element={<HealthProjects/>}/>
<Route path="/sportsprojects" element={<SportsProjects/>}/>
<Route path="/tourismprojects" element={<TourismProjects/>}/>
</Routes>
</div>
</>
</BrowserRouter>
</UserProvider>
)
}
export default App
|
import { Chart as ChartJS, defaults } from "chart.js/auto";
import "./index1.css";
import React, { useState, useEffect } from 'react';
import { Bar } from 'react-chartjs-2';
defaults.responsive = true;
defaults.plugins.title.display = true;
defaults.plugins.title.align = "start";
defaults.plugins.title.font.size = 30;
defaults.plugins.title.color = "black";
const CountryContainer = () => {
//Hocks
const [countries, setCountries] = useState([]);
//UseState for End_Year
const [selectedYear, setSelectedYear] = useState('');
//UseState for Sector
const [selectedSector, setSelectedSector] = useState('');
//UseState for Country
const [selectedCountry, setSelectedCountry] = useState('India');
useEffect(() => {
// Fetch data from your local API endpoint
fetch('http://localhost:8080/data/api')
//Promise Chain
.then((response) => response.json())
.then((data) => setCountries(data))
.catch((error) => console.error('Error fetching data:', error));
}, []);
//Fetch Data like End_Year, Sector, Country all Data column should not be empty.
const filteredCountries = countries.filter((country) => {
return (
(selectedYear === '' || country.end_year === selectedYear) &&
(selectedSector === '' || country.sector === selectedSector) &&
(selectedCountry === '' || country.country === selectedCountry) &&
country.end_year && country.country && country.sector
);
});
//Onchange Event Handler
const handleYearChange = (event) => {
setSelectedYear(event.target.value);
};
const handleSectorChange = (event) => {
setSelectedSector(event.target.value);
};
const handleCountryChange = (event) => {
setSelectedCountry(event.target.value);
};
const countryOptions = [
'Arabia','Greece','Sweden','Poland','India','Nigeria','Venezuela','Germany','Panama','Libya',
'Botswana','Ireland','Equatorial Guinea','New Zealand','Latvia','Turkey','Pakistan','Guyana','Mexico',
'South Sudan','Austria','Belgium','South Africa','Taiwan','Chile','North Korea','Russia','Italy',
'United Arab Emirates','France','Bahrain','Indonesia','Brazil','South Korea','Qatar','Yemen',
'Estonia','Afghanistan'
];
const Sectors=["Information Technology","Manufacturing","Financial services","Energy","Retail",
"Support services","Government","Transport","Food & agriculture","Media & entertainment"];
return (
<div>
<h1 className="CI">Country Information</h1>
<div>
<label className="F1">
Filter by Year:
<select value={selectedYear} onChange={handleYearChange} className="F1" >
<option value="">All</option>
{Array.from({ length: 8 }, (_, index) => 2018 + index).map((year) => (
<option key={year} value={year}>
{year}
</option>
))}
</select>
</label>
<label className="F2">
Filter by Sector:
<select value={selectedSector} onChange={handleSectorChange}>
<option value="">All</option>
{Sectors.map((sector) => (
<option key={sector} value={sector}>
{sector}
</option>
))}
</select>
</label>
<label className="F3">
Filter by Country:
<select value={selectedCountry} onChange={handleCountryChange} >
<option value="">All</option>
{countryOptions.map((country) => (
<option key={country} value={country}>
{country}
</option>
))}
</select>
</label>
</div>
<div className="article-list">
<h1 className="artlist">Article List</h1>
{filteredCountries.length > 0 ? (
<div className="article-container">
{filteredCountries.map(article => (
<div key={article.id} className="article-card">
<Bar
data = {{
labels: ["Country: "+article.country],
datasets: [{
label: 'likelihood',
data:article.likelihood,
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4CAF50', '#9966FF'],
hoverOffset: 4
},
{
label: 'Relevance',
data:article.relevance,
backgroundColor: ['#36A2EB', '#FFCE56', '#4CAF50', '#9966FF'],
hoverOffset: 4
}
]
}}
options={{
elements: {
line: {
tension: 0.5,
},
},
plugins: {
title: {
text: "Yearly progress of "+article.country+": "+article.end_year,
},
},
}}
/>
<p>Sector: {article.sector}</p>
<p>Topic: {article.topic.toUpperCase()}</p>
{/* Add more fields as needed */}
</div>
))}
</div>
) : (
<div className="empty-message">
<p>No Data!
No Progress!</p>
</div>
)}
</div>
</div>
);
};
export default CountryContainer;
|
import React from 'react';
import { connect } from 'react-redux';
import { setStepJoinStep } from '../../actions/stepjoin_actions';
import SignupForm from '../session_form/SignUpForm';
import PlanForm from './PlanForm';
import BillingForm from './BillingForm';
import SignupSectionHeader from './SignupSectionHeader';
class StepJoin extends React.Component {
constructor(props) {
super(props);
this.state = {
step: null
}
this.setStep = this.setStep.bind(this);
}
async componentDidMount() {
let policyType = this.props.currentUser ? this.props.currentUser.policyType : null
if (policyType == 'Visitor'){
this.props.setStepJoin('plan')
} else if (policyType == 'Lead'){
this.props.setStepJoin('billing')
} else {
this.props.setStepJoin('account')
}
}
setStep(nextForm) {
this.props.setStepJoin(nextForm)
}
render(){
let content;
let policyType = this.props.currentUser ? this.props.currentUser.policyType : null
if (this.props.stepJoin == 'plan' || policyType == 'Visitor'){
content = <PlanForm setStep={this.setStep} />
} else if ( this.props.stepJoin == 'billing' || policyType == 'Lead'){
content = <BillingForm setStep={this.setStep} />
} else {
content = <SignupForm setStep={this.setStep} />
}
return(
<div className="login-page">
<div className="login-form-main">
<div className="login-form-container">
<SignupSectionHeader form={this.props.stepJoin} />
{content}
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
currentUser: state.entities.currentUser,
schools: Object.values(state.entities.schools),
stepJoin: state.ui.stepJoin || ''
};
};
const mapDispatchToProps = dispatch => {
return {
setStepJoin: (step) => dispatch(setStepJoinStep(step)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(StepJoin);
|
<?xml version="1.0" encoding="utf-8"?>
<!-- This LinearLayout contains everything in this layout -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Create the toolbar that uses the attributes set in AppTheme (in styles.xml) -->
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<!-- ScrollView allows the user to scroll through content if it doesn't not fill all on the same screen -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The ScrollView can only have one child so all elements must be inside a LinearLayout -->
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Textbox for the question. The hint text appears when the EditText is empty so the user knows what the EditText is for -->
<EditText
android:id="@+id/cardQuestionEditText"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Question"
android:maxLength="200"/>
<!-- Textview for error messages about the question EditText. Hidden by default -->
<TextView
android:id="@+id/cardQuestionErrorMessage"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="5sp"
android:textColor="#ff0000"/>
<!-- TextView that displays the formatted preview of the HTML text in the question EditText -->
<TextView
android:id="@+id/questionFormattedTextView"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="5sp"
android:layout_marginRight="5sp"
android:textSize="16sp"
android:visibility="gone"/>
<!-- Textbox for the answer. The hint text appears when the EditText is empty so the user knows what the EditText is for -->
<EditText
android:id="@+id/cardAnswerEditText"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Answer"
android:maxLength="200"/>
<!-- Textview for error messages about the answer EditText. Hidden by default -->
<TextView
android:id="@+id/cardAnswerErrorMessage"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="5sp"
android:textColor="#ff0000"/>
<!-- TextView that displays the formatted preview of the HTML text in the answer EditText -->
<TextView
android:id="@+id/answerFormattedTextView"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="5sp"
android:layout_marginRight="5sp"
android:textSize="16dp"
android:visibility="gone"/>
<!-- Horizontal ScrollView that contains the common formatting controls to automatically add HTML tags -->
<HorizontalScrollView
android:id="@+id/formattingControlsHorizontalScrollView"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<!-- ScrollViews can only have 1 child, so everything is put inside a LinearLayout, also with a horizontal layout -->
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<!-- Button that toggles the bold tag on the selected text -->
<Button
android:id="@+id/boldButton"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Bold"/>
<!-- Button that toggles the italics tag on the selected text -->
<Button
android:id="@+id/italicButton"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Italic"/>
<!-- Button that toggles the span tag with underlining attribute on the selected text -->
<Button
android:id="@+id/underlineButton"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Underline"/>
<!-- A spinner is a multiple choice list. This spinner contains a list of colours, which when selected will apply to the
selected text in HTML -->
<Spinner
android:id="@+id/colourPickerSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/colours_prompt"/>
<!-- This spinner contains a list of fonts, which when selected will apply to the selected text in HTML -->
<Spinner
android:id="@+id/fontPickerSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/font_prompt"/>
</LinearLayout>
</HorizontalScrollView>
<!-- Checkbox that determines whether or not to show the TextViews defined above to display the previews -->
<CheckBox
android:id="@+id/showPreviewCheckBox"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Show previews"/>
<!-- TextView that informs the user that they can use any standard HTML in the EditTexts above -->
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Use any standard HTML formatting"
android:layout_marginLeft="5sp"
android:layout_marginRight="5sp"
android:layout_marginBottom="5sp"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
|
---
title: "書籍「チームジャーニー」を読んだので\"超ざっくり\"でまとめてみた"
emoji: "📘"
type: "tech" # tech: 技術記事 / idea: アイデア
topics: ["チーム開発"]
published: true
---
チーム・ジャーニー 逆境を越える、変化に強いチームをつくりあげるまで
[購入リンク](https://www.amazon.co.jp/%E3%83%81%E3%83%BC%E3%83%A0%E3%83%BB%E3%82%B8%E3%83%A3%E3%83%BC%E3%83%8B%E3%83%BC-%E9%80%86%E5%A2%83%E3%82%92%E8%B6%8A%E3%81%88%E3%82%8B%E3%80%81%E5%A4%89%E5%8C%96%E3%81%AB%E5%BC%B7%E3%81%84%E3%83%81%E3%83%BC%E3%83%A0%E3%82%92%E3%81%A4%E3%81%8F%E3%82%8A%E3%81%82%E3%81%92%E3%82%8B%E3%81%BE%E3%81%A7-%E5%B8%82%E8%B0%B7-%E8%81%A1%E5%95%93/dp/4798163635/ref=sr_1_2?adgrpid=57356695670&dchild=1&gclid=Cj0KCQjw16KFBhCgARIsALB0g8IBYmdeS_fRTC-GJPNif_YkIl893LVR0tss27ybNKZ8VW7Z5oOrcYMaAhTfEALw_wcB&hvadid=338526277335&hvdev=c&hvlocphy=1009292&hvnetw=g&hvqmt=b&hvrand=16356652092072954100&hvtargid=kwd-411248453985&hydadcr=15819_11177362&jp-ad-ap=0&keywords=%E3%82%AB%E3%82%A4%E3%82%BC%E3%83%B3%E3%82%B8%E3%83%A3%E3%83%BC%E3%83%8B%E3%83%BC&qid=1621685046&sr=8-2)
# 前提
プロダクトバックログ・・・今後やることリスト
PBI・・・プロダクトバックログアイテム、リストのうちの一つを指す
ミッション・・・理想の状態
PM・・・製品の品質や開発コストや、リリーススケジュールの管理など・・・プロダクト単位寄り
PO・・・開発プロセスを管理、開発メンバーを牽引など・・・メンバー単位寄り
PDM・・・ロードマップの作成(目標や目的の作成等)、ビジネスケースの作成(ビジネスモデルやKPIの作成等)、新商品の立案、開発(実務の仕切り)など・・・ビジネス単位寄り
# 第一部
## 基本編
### 1章
#### チームとグループの違い
チーム・・・一人では不可能な成果をあげ、ミッションが共有されており、相互作用に与える影響に注意を払いながら、ルールは自分たちで決める集団
グループ・・・人の集合を外部から見分けやすくラベルを貼られた、相互連絡をしながら決められたルールの中で行動する集団
#### チームになるための条件
いきなりチームにはなれないから少しづつ成長していこうよ
1. チームの目的を揃える・・・「我々はなぜここにいるのか?」、自分たちでミッションを決めて言語化する
2. 共通の目標を認識する・・・ミッションを複数の目標に細分化、目標を達成することでミッションの達成に近づけ、思考や行動の基礎になるよう全員で共有する
3. お互いの持ち味を把握する・・・何に興味があって、何にを重要視し、やる気を見出すのかを知る
4. 共同で仕事するためのやり方を整える・・・まず共通理解を得やすいフレームワークを使い、そこからやり方を少しづつ変えていく、その他に前提として具体的な内容のルールも取り付けるが、最小限にする
このセクションで出たワーク「星取表」「ドラッカー風エクササイズ」
### 2章
#### 問題提唱とリーダーシップ
理想と現状のギャップが問題になる、その問題を提唱するのは決められた役職の人間でなく、「気づいた人」
「リーダーとは目標を定め、優先順位を決め、基準を定め、それを維持する者」byピータードラッカー
何「ファースト」かを決めることでチームの意思決定の基準を言語化する👈リーダーの独断で決めない
ワークショップをすることによって得られる効果は大きいが、ワークショップが目的にならないようにし、現実に合わせた場の設定(ワークショップと思わせない)が重要
#### 出発のための3つの問い
ゴールデンサークルというフレームワークが元
1. 自分はなぜここにいるのか?(個人のwhy)
2. 私たちは何をする者たちなのか?(チームとしてのwhy)
3. そのために何を大事にするのか?(チームとしてのhow)
### 3章
#### 段階の設計
初期の理想イメージでは正確性に欠けるため、状況に応じて段階を組み直すことが必要
1. 理想とする状態をイメージして最初の目的地とする
2. 目的地に至るために必要な前段階を逆算し、段階を構想する
3. 各段階で理想とする状態を言語化し、そうなるために何に取り組むべきかを見立てる
👉段階を経ていく過程で方向性自体を見直す必要もある
#### チーム・ジャーニー
タックマンモデルと成功循環モデルを掛け合わせたフレームを使用
1. チーム形成期に自分は何が不得意、苦手でどんな仕事をしてしまうのかの共有をする
2. チーム混乱期には小さな仕事を短期間で一巡させ、正すべきことを早く明らかにし、できる限り早く最初の結果を出し、結果をチームで分かち合うことが必要、成功循環を初めは小さく始めていく
具体的にはタスクをモブプログラミングなどで行い、初めは1日単位でタスクを一巡させる
3. 統一期には次に目指すべき状態を見定め、役割の再定義、ルールの見直しなども行う
### 4章
#### チームの構造と状態
チームは4つの要素で成り立つ
1. 共有ミッション・・・ミッション定義+チームのファースト設定
2. 役割・・・役職定義とリードの設定
リードとはその領域の意思決定やコミュニケーションを先導する役
3. コミュニケーションの場・・・レトロやデイリースクラムなど状況共有や改善目的のためのもの
4. ルール・・・お互いの活動を制約する取り決め
上記4つのうち何かが一つが欠けている場合
共有ミッションが欠けている・・・個人商店状態、個々人が責任を果たすだけの状態
役割が欠けている・・・仲良しこよし状態、成果を出すことよりもお互いの期待する動きになっているかを重視してしまう状態
コミュニケーションの場が欠けている・・・塹壕状態、状況の同期はリーダーが握っておけば良いという状態
ルールが欠けている・・・烏合の衆状態、お互いの活動が噛み合わず成果が上がらない状態
#### ゴールデンサークルとミッション・ジャーニー
ゴールデンサークル
1. why・・・ファーストに基づくミッション定義
2. how・・・whyを実現する作戦
3. what・・・作戦に基づく具体的なタスク
4. when・・・達成に必要な期間、タイムボックスの設定(元々のゴールデンサークルにはない)
ミッションジャーニーとは3章の段階のこと
ジャーニーの達成期間をタイムボックスといい、その中にスプリントがいくつもあるというイメージ
スプリントの期間は固定だが、ジャーニー(タイムボックス)は可変、ミッションによって変わるため
着地の予測が重要になる、いつまでに終わるのか何スプリントあれば終わるのか
あくまで予測、スプリントが終了する際にこのままでは終わる終わらないが見立てられるようになってくる
終わらないようなら状況の理解を関係者とすり合わせたり、スプリントを増やしたりして応じる
### 基本編まとめ
1. 目的地を定める・・・「3つの問い」に向き合う
2. ジャーニー(段階)を設計する
3. ジャーニーのミッションの定義・・・ゴールデンサークル
4. チームのファーストを選択・・・リーダーシップ
5. チームのフォーメーションを変更・・・6章にて説明
6. ジャーニーの遂行
7. ジャーニーのふりかえり・・・状況によって1、2、3に戻る
## 応用編
### 5章
#### 現状のチームとDIFF
DIFFの種類
1. 前方とのDIFF・・・チームの理想的な状態を描き、それとのDIFFをとる、大きな変更点がないと描きにくい
2. 後方とのDIFF・・・過去の自分達に比べてできるようになったことから次の方向性を決める、安易で意義の低いものになる可能性
3. 平行とのDIFF・・・他のチームとのDIFFをとる、チームによって状況が違うので慎重にDIFFを測り、チームそれぞれの前提と背景を捉える
DIFFを撮る際の観点・・・DIFFの種類と組み合わせてDIFFをとる
1. ユーザーへの価値提供
2. ビジネスの成果
3. プロセスや技術、コミュニケーションの練度
4. 新たな領域の学習
DIFFをとった後に自分達が具体的な行動を起こせる内容にするために必要
その内容をもとにジャーニーを切り替える
### 6章
#### コミュニケーションの分断による6つの問題
フレックスやリモートワーク、技術経験の差からなる
1. 稼働時間帯が合わない・・・同期できない
2. 稼働時間に偏りがある・・・PBI開発へのコミュニケーションコストが高い
3. メンバーに経験の幅がある・・・やり方がバラバラ
4. 非言語コミュニケーションがない・・・伝わる内容分量が少ない
5. 相手の様子がわからない・・・異常検知がしにくい
6. 背景が見えずタスク志向になる・・・whyがないため、間違いに気づかない
#### 雁行陣開発
フォーメーション・パターンの一つ
プロダクトリード・・・中核の機能、背骨のPBIを先行して開発する役割、方針は決め切る前にメンバーからFBをもらう
チームリード・・・チームの運営、プロダクトリードの代わりにチーム内情報共有、相互作用が十分に行き渡るよう働きかける役割
メンバー・・・適宜PBIを開発、背骨に対してのお肉のPBIの実装
チームリードは負担があるので適宜交代するべきで、ジャーニーごとにどのようなフォーメーションで挑むのかはチームで確認するべき
### 7章
#### チームでの分断
1. 開発チーム内部の分断・・・バックエンドとフロントエンド、デザイナーと開発者など
2. 開発チームとPO間での分断・・・技術に関するリテラシーの差があり、認識齟齬が発生しやすい
3. プロダクトチーム(開発チーム×PO)と外側との分断
#### 共通理解を深める
チームがどういう状況なのか安易に把握できるように透明性を高める、3つの原則
1. 見える化・・・情報を得られやすいように情報や状況の整理を行う
2. 場づくり・・・情報を伝え合うようにするために定期的に時間を設ける
3. 一緒にやる・・・一つのタスクに全員で取り掛かり、互いの理解を深める
自分達が何を知っていて何を知らないのかを知ることが重要
このセクションで出たワーク「仮設キャンバス」
### 8章
#### 再・出発のための3つの問い
同調圧力を生みやすいので、チームビルドが進んだ段階で使用
1. 私たちは何をする者たちなのか?(チームとしてのwhy)
2. そのために何を大事にするのか?(チームとしてのhow)
3. 自分はなぜここにいるのか?(個人のwhy)
#### 開発チームとPOの境界にPO代行を置く
両者のリテラシーの差を埋めるために、つなぎ合わせる役割がPO代行で2種類の代理を行う
翻訳の代理・・・開発チームとPOそれぞれの説明する状況が相互に理解できるよう知識補完する
コミュニケーションの代理・・・時間や場所のずれを吸収する
プロダクトとしてどうあるべきかという基準をPOと常時すり合わせる
### 応用編まとめ
仮説検証とアジャイル開発を組み合わせた一人の人間のようなチームづくりをして、速度をあげよう
頭・・・何を作るか整理する
目・・・観察する
口・・・質問する、言語化する
耳・・・インタビューする
手・・・つくる
足・・・コミュニケーション
血液・・・情報
チームのあり方に完璧はない、何回もミッションの再定義をしよう
# 第二部
## 基本編
### 9章
#### チーム間の情報流通の不全
経路設計の複雑性・・・複数チームになると情報の伝わる頻度が足らなくなる
解釈の多様性・・・情報の解釈にばらつきがある
プロダクトづくりにおける3つの価値・・・情報を価値のあるものに加工する
1. ユーザーにとっての価値・・・ある状況を解決するためにプロダクトがあり、このある状況に置かれている人が理想的な状況に変わることが価値
2. ビジネスにとっての価値・・・事業の持続可能性、ビジネス的成果が求められる
3. プロダクトにとっての価値・・・変更可能性が必要な取り組みとなる
#### 情報流通のための境界
1. ミッション・・・プロダクトチーム全体で到達したい目標
2. 戦略・・・ミッションを実現するためのプロダクトチーム全体での方針
3. チーム・ミッション・・・チームれべるのミッション
4. 作戦・・・チームミッションを達成するためのジャーニー
### 10章
#### チーム別で見るコミュニケーション
一つの開発チームと一人のPO・・・「自分は何をする人なのか?」に向き合うことで分断の境界に気づき、乗り越える
複数の開発チームと一人のPO・・・POの練度が試される、「越境のデザイン」が求められる
複数の開発チームと各チームのPO・・・より分断を生む、「越境のデザイン」が求められる
#### 越境のデザイン
1. リードというある状況において全身を先導する役割をチームに持ち込み、これをチーム内で交代制にすることでリードのスペア化を目指し、できるだけ全体のスキル向上を求める
2. コミュニケーションの構造化、チーム同期のコミュニケーションから始まり、リード別の同期コミュニケーションへ、最後に代表者の同期コミュニケーションへ、ただし代表者の同期コミュニケーションを意思決定機関しないことを気をつける
3. カンバンの運用、それぞれの上記構造によってレイヤーを合わせる必要がある
### 11章
#### 他チームの境界
WIP制限・・・チームが捌けるタスクの限界
WIP制限はカンバンで見える化し管理する
チーム感依存度が高い・・・チーム単体の生産性は低いが、チーム同士の意思疎通は撮りやすい
チーム感依存度が低い・・・チーム単体の生産性は高いが、チーム同士の意思疎通は取りにくい
状況によって依存度を変える
#### 5つの作戦
1. リソース配分に意思を込める・・・チームが何に対して時間を使うのかをあらかじめ決め、状況をみて割合を調整する
2. 番頭の輪番化・・・外部の依頼を受け取り処理する番頭を交代で行う
3. 順序付の基準を合わせる・・・ミッションの到達に遅れを出さないようにタスクの順序付けを行う
4. チーム外部への表明・・・チームが外部にどういったスタンスで動いているのかを発信する
5. チーム間のふりかえり・・・チーム間の問題や改善に対してできるだけ関係してるメンバーを集めて話し合う
### 12章
#### 横断チーム
専門性の不足やこぼれ球が山積みの状態が発生した際に構築を検討
専門特化型チーム・・・専門性に特化したチーム(アーキテクチャ設計、SREなど)
状況特化型チーム・・・状況に特化したチーム(共通機能開発、以降チームなど)
2つの問題
1. 開発チームと横断チームの確執が発生しうる可能性
2. 他チームからメンバーを引き抜いて結成、稼動できるかの問題
適宜ミッションが片付いたらチームを解散するか永続化する判断をする必要がある
チームで対立したら「我々はなぜここにいるのか」を両チームで応える機会を設ける
ミッションの主管が既存チームにある場合・・・チーム一体となるためゴールデンサークル、スクラムイベント、プロダクトバックログを完全同期
ミッションの主管が横断チームにある場合・・・チームを独立させ、必要に応じて同期のコミュニケーションを行う
## 応用編
### 13章
#### 対象を1ユーザーに絞る
チームそれぞれが別々のユーザーに対してプロダクトを提供していたらペルソナが固まっておらず、意味がない
ユーザー行動フローを描くための方法
- プロダクトがまだなく、ユーザーに関する共通理解を作りたい
1.ユーザーの大まかな行動か状況を書き出す
2.対応する行動を細かく書き出し、書き出せないところは行動の観察余地が残ってるということになる
3.ユーザー行動に伴い発生する問題、不都合を書き出す(そもそも〇〇しないなど)
4.問題や不都合を解消する解決策を挙げる
5.現状の行動フローを踏まえ、理想的なフローを描く
- 既にプロダクトがあり、ユーザー体験の最適化を進めたい
1. そのプロダクトを利用する際のユーザーの状況をざっとあげる
2. 状況に対応する行動を細かく書き出し、流れをきちんと把握する
3. それぞれの行動に伴い発生している障害を書き出す(ユーザー調査、ログ調査などを行う)
4. 障害に対する解決策を挙げていく
チームの足並みを揃えるために共同のカンバンを使用し、状況を把握する
スループット・・・ある一定の機関あたりに創出できた価値(プロダクトやバグ改善など)の数
スループットまでのリードタイムを計測し、データをとっておくことで、ボトルネック発見の大事なヒントになる
### 14章
#### マネジメントリード
チーム内の情報の流れ、問題予測、障害の始末を継続的に追いかける役割
1. 自分の目の前から自分がやらなければならないタスクを一掃する
2. チームの目の前からやらなければならないタスクを片付ける
意思決定を決める際に選択肢と前提と時間軸(過去、現在、未来)を意識する
#### 蜘蛛型チームからヒトデ型チームへ
蜘蛛型・・・リーダーを中心として、チームを運営する・・・まとめやすいが、意思決定に時間がかかり、速度に限界がある
ヒトデ型・・・チームが個別に動き、必要に応じて会議する・・・各チームのリード練度、自立性がある程度必要、速度が出る
各チームの標準化から各チームの課題解決共同化へ
1. 時間と場所を共にする、一日限定の同席開発や合宿などが有効
2. 仕事を共にする、モブワークなど理解を深めるために他人に説明したりする
最終的にミッションを共有し、お互い協力し合える相互作用、協働化へ
### 15章
#### チームが持つべき視点
考え、決め、動く、を状況に応じて適したものにするには"どこから""どこまで"を見るかで変わる
- 視座(どこから)・・・目的、自分の立ち位置をどこにおくかで変わる(ジャーニーの視座、事業の視座など)
- 視野(どこまで)・・・対象、何を捉えるかは状況とテーマによって変わる(ユーザー、チーム、経営者など)
例:"プロダクト"に置き、"ユーザー"を捉える・・・プロダクトの機能について現状利用している人たちのフィードバックを集め、何を価値と置くのかを整理する
同じ範囲を見ていても視座変われば見えるものが変わることを理解する
視座と視野の移動を難しくする要因
- (自分たちにとっての)現状の最適化・・・自分たちが現状に合わせた思考、行為をとってしまうため、視座と視野の偏りがおこってしまう、「この仕事で何を実現し、なんのために必要なのか」を問う
- 役割による固定化・・・役割によって視座と視野の偏りがおこってしまう、リードの概念を取り入れて動的ににリードを動かし、解決する
プロダクトオーナーの民主化・・・プロダクトとして何を作っていくべきなのかという観点をメンバー全員が持つ、その代わり専門性が求められるリードが必要になる
#### 多次元からの捉え
一人でものごとを捉えるに限界があるため、チームで臨むことが必要、チーム総体としてあらゆる観点から物事を捉え考えられるようにする
自分たちに問う・・・チームの思考や行動に問いをぶつけ、現状の最適化による思考の停止や安易な好悪によって選択肢を絞ってないかに向き合う
わかりきっているということでも頑固にならず、もう一度頭の中に通してみることが重要
自分たちが気づいていないことに気づくために、今一度「正しいものを正しく作れているか」という問いにも向き合う
容易なことではないし、答えはない
### 16章
#### 仮説、検証
プロダクトで何をもたらすのかという仮説を立てることが必要👉仮説キャンバスを使う
1. 調査、分析、観察
2. 仮説立案
3. 検証・・・ユーザーインタビューやアンケート、MVP検証など
検証活動で重要なのは"いかに時間をかけず"に"利用者から濃い反応を得れる"か、活動にできるだけ多くのメンバーの関わりが必要
MVPを用いいたユーザーテストには、ユーザーにもできるだけふりかえりに参加してもらう
|
<?php
namespace Drupal\example_field\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'ExampleFieldFormattor' formatter.
*
* @FieldFormatter(
* id = "example_field_examplefieldformattor",
* label = @Translation("ExampleFieldFormattor"),
* field_types = {
* "string",
* "text_long",
* "example_fieldtype",
* }
* )
*/
class Examplefieldformattor extends FormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings(){
return [
'concatenated' => 1,
//Implement default settings
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state){
return [
//Implement settings form.
'concatenated' => [
'#type' => 'checkbox',
'#title' => $this->t('Concatenated'),
'#description' => $this->t('Whether to concatenate the code and number into a single string separated by a space. Otherwise the two are broken up into separate span tags.'),
'#default_value' => $this->getSetting('concatenated'),
],
] + parent::settingsForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function settingsSummary(){
$summary = [];
//Implement settings summary.
$summary[] = $this->t('Concatenated: @value', ['@value' =>(bool) $this->getSetting('concatenated') ? $this->t('Yes') : $this->t('No')]);
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
// dump($items);
// dump($element);
foreach ($items as $delta => $item) {
$element[$delta] = [
'#markup' => '<h1>'. $item->value . '</h1>',
];
// dump($item);
}
// dump($element);
// exit;
return $element;
}
/**
* Generate the output appropriate for one field item.
*
* @param \Drupal\Core\Field\FieldItemInterface $item
* one field item.
*
* @return string
* The textual output generated.
*/
public function viewValue(FieldItemInterface $item){
return [
'#markup' => $item->value,
];
}
}
|
import { Card, Button, Label } from "@aws-amplify/ui-react";
import { LocalNotifications } from "@capacitor/local-notifications";
import { CapacitorHealthkit } from "@perfood/capacitor-healthkit";
import { useState } from "react";
export const RequestPermission = (props: {
onPermissionGranted: () => Promise<void>;
}) => {
const [loading, setLoading] = useState<boolean>(false);
const onPermissionClick = async () => {
setLoading(true);
const readPermissions = ["calories", "steps", "weight", "activity"];
await CapacitorHealthkit.requestAuthorization({
all: [],
read: readPermissions,
write: [],
});
await LocalNotifications.requestPermissions();
await LocalNotifications.schedule({
notifications: [
{
title: "Have you logged lunch?",
body: "Log your food",
id: 13,
schedule: {
allowWhileIdle: true,
on: {
hour: 13,
},
},
},
{
title: "Have you logged dinner?",
body: "Log your food",
id: 20,
schedule: {
allowWhileIdle: true,
on: {
hour: 20,
},
},
},
],
});
localStorage.setItem("hasPermission", "hasPermission");
await props.onPermissionGranted();
setLoading(false);
};
const onLaunchHealthkitClick = async () => {
const readPermissions = ["calories", "steps", "weight", "activity"];
await CapacitorHealthkit.requestAuthorization({
all: [],
read: readPermissions,
write: [],
});
window.location.href = "x-apple-health://Sources/jpc.fit";
};
return (
<Card>
<Label as="div">
HealthKit data and notifications provide the best experience for this
app. Grant permission?
</Label>
<br />
{!localStorage.getItem("hasPermission") ? (
<Button
variation="primary"
isLoading={loading}
margin={"10px"}
onClick={onPermissionClick}
>
Grant Permission
</Button>
) : (
<Button margin={"10px"} onClick={onLaunchHealthkitClick}>
Launch Healthkit
</Button>
)}
</Card>
);
};
|
import { FormikErrors } from 'formik';
import {
BecomeLectorTypes,
ErrorLectorsTypes,
} from 'components/BecomeLector/BecomeLector.types';
import { isNumeric } from 'helpers/isNumeric';
const emailCheck = /^[A-Z0-9._%+-]+@[A-Z0-9-]+.+.[A-Z]{2,4}$/gi;
export const BecomeLectorsValidate = (values: BecomeLectorTypes) => {
const errors: FormikErrors<ErrorLectorsTypes> = {};
if (values.jobTitle !== '' && !values.job) {
errors.jobTitle = 'Обязательное поле';
}
if (values.patronymic === '') {
errors.patronymic = 'Обязательное поле';
} else if (isNumeric(values.patronymic)) {
errors.patronymic = 'не может содержать цифры';
}
if (values.name === '') {
errors.name = 'Обязательное поле';
} else if (isNumeric(values.name)) {
errors.name = 'не может содержать цифры';
}
if (values.surname === '') {
errors.surname = 'Обязательное поле';
} else if (isNumeric(values.surname)) {
errors.surname = 'не может содержать цифры';
}
if (values.address?.id === 0) {
errors.address = 'Обязательное поле';
}
if (values.education.id === 0) {
errors.education = 'Обязательное поле';
}
if (values.educationEnd === '') {
errors.educationEnd = 'Обязательное поле';
} else if (values?.educationEnd?.length < 4) {
errors.educationEnd = 'Должно содержать 4 цифры';
}
if (values.speciality === '') {
errors.speciality = 'Обязательное поле';
}
if (values.email === '') {
errors.email = 'Обязательное поле';
} else if (!values?.email?.match(emailCheck)?.length && values.email) {
errors.email = 'некорректный email';
}
if (values.job === '') {
errors.job = 'Обязательное поле';
} else if (isNumeric(values.job)) {
errors.job = 'не может содержать цифры';
}
if (values.jobTitle === '') {
errors.jobTitle = 'Обязательное поле';
} else if (isNumeric(values.jobTitle)) {
errors.jobTitle = 'не может содержать цифры';
}
return errors;
};
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
//VRFConsumerBase > valor random dado por chainlink
//ownable para hacer funciones onlyowner
contract Lottery is VRFConsumerBase, Ownable {
address payable[] public players;
address payable public recentWinner;
uint256 public randomness;
uint256 public usdEntryFee;
AggregatorV3Interface internal ethUsdPriceFeed;
enum LOTTERY_STATE {
OPEN,
CLOSED,
CALCULATING_WINNER
}
//declaro la variable lottery_state que se va a inicializar en el constructor
LOTTERY_STATE public lottery_state;
// 0 : OPEN
// 1 : CLOSED
// 2 : CALCULATING_WINNER
uint256 public fee;
bytes32 public keyhash;
//para guardar el id de request del numero aleatorio solicitado cuando en se llama a requestRandomness
//en end lottery
event RequestedRandomness(bytes32 requestId);
constructor(
address _priceFeedAddress,
address _vrfCoordinator,
address _link,
uint256 _fee,
bytes32 _keyhash
) public VRFConsumerBase(_vrfCoordinator, _link) {
usdEntryFee = 50 * (10**18);
ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
lottery_state = LOTTERY_STATE.CLOSED;
fee = _fee;
keyhash = _keyhash;
}
function enter() public payable {
// $50 minimum
require(lottery_state == LOTTERY_STATE.OPEN);
require(msg.value >= getEntranceFee(), "Not enough ETH!");
players.push(msg.sender);
}
function getEntranceFee() public view returns (uint256) {
(, int256 price, , , ) = ethUsdPriceFeed.latestRoundData(); //el pricefeed vienen con 8 decimales
uint256 adjustedPrice = uint256(price) * 10**10; // 18 decimals - 8 que viene el price + 10**10
// $50, $2,000 / ETH
// 50/2,000
// 50 * 100000 / 2000
uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
return costToEnter;
}
function startLottery() public onlyOwner {
require(
lottery_state == LOTTERY_STATE.CLOSED,
"Can't start a new lottery yet!"
);
lottery_state = LOTTERY_STATE.OPEN;
}
function endLottery() public onlyOwner {
// uint256(
//el keccack256 saca el valor hash dentro de lo que se ponga
// keccack256(
// abi.encodePacked(
// nonce, // nonce is preditable (aka, transaction number)
// msg.sender, // msg.sender is predictable
// block.difficulty, // can actually be manipulated by the miners!
// block.timestamp // timestamp is predictable
// )
// )
// ) % players.length;
lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
// la funcion que genera el numero aleatorio desde link es la funcion
// requestedRandomness que viene desde
//https://github.com/smartcontractkit/chainlink/blob/develop/contracts/src/v0.6/VRFConsumerBase.sol
//importado mediante > import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
bytes32 requestId = requestRandomness(keyhash, fee);
emit RequestedRandomness(requestId);
}
function fulfillRandomness(bytes32 _requestId, uint256 _randomness)
internal
override
{
require(
lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
"You aren't there yet!"
);
require(_randomness > 0, "random-not-found");
uint256 indexOfWinner = _randomness % players.length;
recentWinner = players[indexOfWinner];
recentWinner.transfer(address(this).balance);
// Reset
players = new address payable[](0);
lottery_state = LOTTERY_STATE.CLOSED;
randomness = _randomness;
}
}
|
import { speak } from "./voice.js";
import { bytes2int16, log } from "./utils.js";
import { voiceState } from "./index.js";
// add new
let serviceUuid = 0x181A;
// let serviceUuid = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
let accUuid = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
let gyroUuid = "d2912856-de63-11ed-b5ea-0242ac120002";
let switchUuid = "4e1c00da-57b6-4cfd-83f8-6b1e2beae05d";
let voiceUuid = "a0451b3a-f056-4ce5-bc13-0838e26b2d68";
let ultrasoundUuid = "f064e521-de21-4027-a7da-b83241ba8fd1";
let thresholdUuid = "b51ff51f-0f0e-4406-b9be-92f40c1a14e8";
// 宣告一個包含兩個 UUID 的陣列
// let UuidTargets = [accUuid, gyroUuid, switchUuid, voiceUuid, ultrasoundUuid, thresholdUuid];
let UuidTargets = [accUuid, gyroUuid, switchUuid, voiceUuid, ultrasoundUuid];
let server;
let service;
let device;
const Acc = [], Gyro = [], US = [];
export async function bleSearch() {
try {
log('Requesting Bluetooth Device...');
device = await navigator.bluetooth.requestDevice({
// add newDD
// optionalServices: [serviceUuid, accUuid, gyroUuid, voiceUuid, ultrasoundUuid, thresholdUuid],
optionalServices: [serviceUuid, accUuid, gyroUuid, voiceUuid, ultrasoundUuid],
// acceptAllDevices: true
filters: [{ name: "WhiteCane" }]
});
connectDevice();
device.addEventListener('gattserverdisconnected', reConnect);
return "success"
} catch (error) {
speak('連接錯誤,請重新連接');
log('Argh! ' + error);
}
}
export async function bleDisconnect() {
// 停止所有 characteristic 的通知功能
for (const [index, UuidTarget] of UuidTargets.entries()) {
const characteristicTarget = await service.getCharacteristic(UuidTarget);
await characteristicTarget.stopNotifications();
characteristicTarget.removeEventListener('characteristicvaluechanged',
callback);
}
device.removeEventListener('gattserverdisconnected', reConnect);
await server.disconnect(); // 需要手動斷開 GATT 伺服器的連線
speak('已斷開連接');
log('> Notifications stopped');
}
async function connectDevice() {
try {
time('Connecting to Bluetooth Device... ');
log('Connecting to GATT Server...');
server = await device.gatt.connect();
log('Getting Service...');
service = await server.getPrimaryService(serviceUuid);
log('Getting Characteristic...');
// add new
// 使用 for...of 迴圈遍歷陣列中的元素,取得每個 UUID 對應的 characteristic 並啟用通知
for (const [index, UuidTarget] of UuidTargets.entries()) {
// 使用 service.getCharacteristic() 方法來取得指定 UUID 對應的 characteristic
let characteristicTarget = await service.getCharacteristic(UuidTarget);
// 當 characteristic 的值發生改變時,執行 callback 函數
characteristicTarget.addEventListener("characteristicvaluechanged", callback);
// 啟用 characteristic 的通知功能,這樣當 characteristic 的值改變時,就會發送通知
await characteristicTarget.startNotifications();
};
speak('成功連接');
} catch (error) {
console.log("連接錯誤", error);
}
}
async function reConnect() {
exponentialBackoff(3 /* max retries */, 2 /* seconds delay */,
async function toTry() {
},
function success() {
log('> Bluetooth Device connected. Try disconnect it now.');
speak('成功連接');
log('> Notifications started');
},
function fail() {
time('Failed to reconnect.');
});
}
function callback(event) {
if (event.currentTarget.uuid === voiceUuid) {
let value = event.currentTarget.value;
console.log(value);
let a = [];
for (let i = 0; i < value.byteLength; i++) {
a.push('0x' + ('00' + value.getUint8(i).toString(16)).slice(-2));
}
console.log(a);
let voiceMode = parseInt(a, 16);
if (voiceMode == 4) {
if (voiceState == "Ring") {
document.getElementById('b_mp3').play();
}else{
speak("注意高低差");
}
}
if (voiceMode == 0) {
if (voiceState == "Ring"){
document.getElementById('g_mp3').play();
}else{
// speak("發現導盲磚");
speak("發現斑馬線");
}
}
console.log(voiceMode);
}
if (event.currentTarget.uuid === accUuid ||
event.currentTarget.uuid === gyroUuid) {
let value = event.currentTarget.value;
let a = [];
for (let i = 0; i < value.byteLength; i++) {
a.push('0x' + ('00' + value.getUint8(i).toString(16)).slice(-2));
}
let bytes = a;
let X = bytes2int16([bytes[0], bytes[1]]) / 100
let Y = bytes2int16([bytes[2], bytes[3]]) / 100
let Z = bytes2int16([bytes[4], bytes[5]]) / 100
if (event.currentTarget.uuid === accUuid) {
Acc.push(["acc", X, Y, Z]);
}
if (event.currentTarget.uuid === gyroUuid) {
Gyro.push(["gyro", X, Y, Z]);
}
}
if (event.currentTarget.uuid == ultrasoundUuid) {
let value = event.currentTarget.value;
let a = [];
for (let i = 0; i < value.byteLength; i++) {
a.push('0x' + ('00' + value.getUint8(i).toString(16)).slice(-2));
}
let bytes = a;
let val = bytes2int16([bytes[0], bytes[1]]) / 100
US.push(["US", val])
}
}
export async function sendModeEvent(message, Uuid) {
try {
// 傳送訊息
console.log(message);
const encoder = new TextEncoder(); // 文字編碼器
const data = encoder.encode(message); // 將字串轉換為Uint8Array數據
let characteristicBle = await service.getCharacteristic(Uuid);
await new Promise((resolve, reject) => {
characteristicBle.writeValue(data)
.then(() => {
console.log('訊息傳送成功');
resolve();
})
.catch((error) => {
console.error('Argh! ' + error);
reject(error);
});
});
} catch (error) {
log('Argh! ' + error);
}
}
/* Utils */
// This function keeps calling "toTry" until promise resolves or has
// retried "max" number of times. First retry has a delay of "delay" seconds.
// "success" is called upon success.
async function exponentialBackoff(max, delay, toTry, success, fail) {
try {
const result = await toTry();
success(result);
console.log(result);
} catch (error) {
if (max === 0) {
return fail();
}
time('Retrying in ' + delay + 's... (' + max + ' tries left)');
setTimeout(function () {
exponentialBackoff(--max, delay * 2, toTry, success, fail);
}, delay * 1000);
}
}
function time(text) {
log('[' + new Date().toJSON().substring(11, 8) + '] ' + text);
}
|
package com.gpteam.shopmanager.time;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* Created by masmix on 14.05.2017.
*
* <p> {@code GregorianCalendar} wrapper class. Main difference from {@code GregorianCalendar} is
* that this class starts counting {@code Calendar.MONTH} from 1 to 12, instead of 0 to 11.
*/
public class Date {
private Calendar calendar;
/**
* Constructs a default {@code Date} ({@code GregorianCalendar} using current time and date.
*/
public Date() {
calendar = new GregorianCalendar();
calendar.set(Calendar.MONTH, Calendar.MONTH + 1);
}
/**
*
* @param day 1 - 31
*/
public Date(int day) {
calendar = new GregorianCalendar();
calendar.set(Calendar.DAY_OF_MONTH, day);
}
/**
* Month argument starts at 1 (January) and ends at 12(December)
*
* @param day
* @param month 1 - 12
*/
public Date (int day, int month) {
calendar = new GregorianCalendar();
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.MONTH, month - 1);
}
/**
* Format: YYYY.MM.DDDD
*
* @param year XXXX
* @param month 1 - 12
* @param day 1 - 31
*/
public Date(int year, int month, int day) {
calendar = new GregorianCalendar(year, month - 1, day);
}
public boolean equals(Date otherDate) {
return getYear() == otherDate.getYear()
&& getMonth() == otherDate.getMonth()
&& getDay() == otherDate.getDay();
}
public boolean equalsYear(int year) {
return getYear() == year;
}
public boolean equalsMonth(int month) {
return getMonth() == month;
}
public boolean equalsDay(int day) {
return getDay() == day;
}
@Override
public String toString() {
return calendar.get(Calendar.DAY_OF_MONTH) + "."
+ calendar.get(Calendar.MONTH + 1) + "."
+ calendar.get(Calendar.YEAR); // TODO test if month call is working properly
}
public long getTime() {
return calendar.getTimeInMillis();
}
public int getYear() {
return calendar.get(Calendar.YEAR);
}
public void setYear(int year) {
calendar.set(Calendar.YEAR, year);
}
public int getMonth() {
return calendar.get(Calendar.MONTH) + 1;
}
/**
* @param month 1 - 12
*/
public void setMonth(int month) {
calendar.set(Calendar.MONTH, month - 1);
}
public int getDay() {
return calendar.get(Calendar.DAY_OF_MONTH);
}
public void setDay(int day) {
calendar.set(Calendar.DAY_OF_MONTH, day);
}
public Calendar getCalendar() {
return calendar;
}
public void setCalendar(Calendar calendar) {
this.calendar = calendar;
}
public int getHour() {
return calendar.get(Calendar.HOUR_OF_DAY);
}
public int getMinute() {
return calendar.get(Calendar.MINUTE);
}
public int getSecond() {
return calendar.get(Calendar.SECOND);
}
public void plusSeconds(int seconds) {
calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + seconds);
}
public void plusMinutes(int minutes) {
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + minutes);
}
public void plusHours(int hours) {
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + hours);
}
public void plusDays(int days) {
calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + days);
}
}
|
import { useDispatch, useSelector } from 'react-redux';
import Button from '../../ui/Button';
import { formatCurrency } from '../../utils/helpers';
import { addItem } from '../cart/cartSlice';
import Deleteitem from '../cart/Deleteitem';
import { getItemQuantity } from '../cart/cartSlice';
function MenuItem({ pizza }) {
const dispatch = useDispatch();
const { id, name, unitPrice, ingredients, soldOut, imageUrl } = pizza;
const itemQuantity = useSelector(getItemQuantity(id));
console.log(itemQuantity);
const quant = itemQuantity > 0;
function handleAddtoCart(){
console.log(id);
const newItem={
pizzaId:id,
name,
quantity:1,
unitPrice,
totalPrice:unitPrice * 1,
}
dispatch(addItem(newItem));
}
return (
<li className="flex gap-4 py-2">
<img
src={imageUrl}
alt={name}
className={`h-24 ${soldOut ? 'opacity-70 grayscale' : ''}`}
/>
<div className="flex grow flex-col pt-0.5">
<p className="font-medium">{name}</p>
<p className="text-sm capitalize italic text-stone-500">
{ingredients.join(', ')}
</p>
<div className="mt-auto flex items-center justify-between">
{!soldOut ? (
<p className="text-sm">{formatCurrency(unitPrice)}</p>
) : (
<p className="text-sm font-medium uppercase text-stone-500">
Sold out
</p>
)}
{quant && <Deleteitem pizzaId={id}/> }
{!soldOut && !quant && (<Button onClick={handleAddtoCart} type="small">Add to cart</Button>) }
</div>
</div>
</li>
);
}
export default MenuItem;
|
package com.bookshop.demo.services.author;
import com.bookshop.demo.domain.entities.Author;
import com.bookshop.demo.repositories.AuthorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
@Service
public class AuthorServiceImpl implements AuthorService{
private final AuthorRepository authorRepository;
@Autowired
public AuthorServiceImpl(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Override
public void seedAuthors(List<Author> authors) {
this.authorRepository.saveAll(authors);
}
@Override
public boolean isDataSeeded() {
return this.authorRepository.count() > 0;
}
@Override
public Author findRandomAuthorId() {
long count = this.authorRepository.count();
if (count != 0) {
long randomAuthorId = new Random().nextLong(1, count);
return this.authorRepository.findAuthorById(randomAuthorId).orElseThrow(NoSuchElementException::new);
}
throw new RuntimeException();
}
@Override
public List<Author> findByFirstNameEndingWith(String endingWith) {
return this.authorRepository.findByFirstNameEndingWith(endingWith);
}
}
|
import { render, screen, userEvent } from '@common/test';
import { ActionMenu, DropdownTypeEnum, type ActionMenuProps } from '@common/dropdown';
import { EllipsisVerticalIcon } from '@heroicons/react/20/solid';
const actions = [
{
text: 'Action 1',
srText: 'Action 1',
icon: EllipsisVerticalIcon,
handleOnClick: jest.fn(),
},
{
text: 'Action 2',
srText: 'Action 2',
icon: EllipsisVerticalIcon,
handleOnClick: jest.fn(),
},
];
const DEFAULT_PROPS = {
name: 'Test Menu',
actions,
};
const setupProps = (props: ActionMenuProps) => ({
...DEFAULT_PROPS,
...props,
});
const Component = (props?: any) => <ActionMenu {...setupProps(props)} />;
const renderComponent = (props?: any) => {
render(Component(props), { shouldHaveNoWrapper: true });
};
describe('<ActionMenu />', () => {
it('renders the correct button content by type', () => {
// given
renderComponent({ type: DropdownTypeEnum.sort });
// when
const button = screen.getByRole('button', { name: /Open Test Menu options/i });
// then
expect(button).toHaveTextContent('Sort');
});
it('renders the correct number of action items', async () => {
// given
renderComponent();
const button = screen.getByRole('button', { name: /Open Test Menu options/i });
// when
userEvent.click(button);
const buttonAndSrOnly = await screen.findAllByText(/Action/i);
const buttonsWithoutScreenReaderElements = buttonAndSrOnly.length / 2;
// then
expect(buttonsWithoutScreenReaderElements).toBe(2);
});
});
|
import FormatStylePolyfill
import XCTest
final class ListFormatStyleTests: XCTestCase {
func test_orList() {
let style = _polyfill_ListFormatStyle<_polyfill_StringStyle, [String]>.list(type: .or, width: .standard).locale(.init(identifier: "en_US"))
XCTAssertEqual(["one", "two"]._polyfill_formatted(style), "one or two")
XCTAssertEqual(["one", "two", "three"]._polyfill_formatted(style), "one, two, or three")
}
func test_andList() {
let style = _polyfill_ListFormatStyle<_polyfill_StringStyle, [String]>.list(type: .and, width: .standard).locale(.init(identifier: "en_US"))
XCTAssertEqual(["one", "two"]._polyfill_formatted(style), "one and two")
XCTAssertEqual(["one", "two", "three"]._polyfill_formatted(style), "one, two, and three")
}
func test_narrowList() {
let style = _polyfill_ListFormatStyle<_polyfill_StringStyle, [String]>.list(type: .and, width: .narrow).locale(.init(identifier: "en_US"))
XCTAssertEqual(["one", "two"]._polyfill_formatted(style), "one, two")
XCTAssertEqual(["one", "two", "three"]._polyfill_formatted(style), "one, two, three")
}
func test_shortList() {
let style = _polyfill_ListFormatStyle<_polyfill_StringStyle, [String]>.list(type: .and, width: .short).locale(.init(identifier: "en_US"))
XCTAssertEqual(["one", "two"]._polyfill_formatted(style), "one & two")
XCTAssertEqual(["one", "two", "three"]._polyfill_formatted(style), "one, two, & three")
}
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hgandar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/10 10:21:55 by hgandar #+# #+# */
/* Updated: 2023/12/14 18:59:45 by hgandar ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "libft/libft.h"
#include "pipex.h"
#include <fcntl.h>
//attendre que le dernier child ai termine pour renvoye pour statut
int wait_last(int last_pid)
{
int status;
int pid;
while (1)
{
pid = waitpid(-1, &status, WNOHANG);
if (pid == -1)
break ;
else if (pid == last_pid)
return (WEXITSTATUS(status));
}
return (42);
}
//recherche le path et l'environnement puis executer
void execute(char *argv, char *envp[])
{
char **cmd_split;
char **env_paths;
char *path;
cmd_split = ft_split(argv, ' ');
if (cmd_split == NULL)
error_message(4);
env_paths = get_env_path(envp);
if (env_paths == NULL)
{
free(cmd_split);
error_message(5);
}
path = get_path(cmd_split[0], env_paths);
if (execve(path, cmd_split, envp) < 0)
{
free(cmd_split);
free(env_paths);
error_message(6);
}
}
// fork process: check si child (==0) et une fois dedans check la condition de l'argv
// en fonction de ces conditions, dup des fils differents car au debut lit de infile (remplace par temp) et ecrit dans pipe
// et ensuite lit et ecrit dans les pipe
//qu'importe les condition au dessu, ensuite on execute
void fork_process(char *argv, char *envp[], t_fd *fd, int i)
{
fd->pid = fork();
if (fd->pid < 0)
error_message(3);
if (fd->pid == 0)
{
if (i == 2)
{
dup2(fd->tmp, 0);
dup2(fd->pipe[1], 1);
close(fd->tmp);
}
else
{
dup2(fd->pipe[0], 0);
dup2(fd->out_file, 1);
close(fd->out_file);
}
(void) close(fd->pipe[0]);
(void) close(fd->pipe[1]);
execute(argv, envp);
}
close(fd->pipe[1]);
}
//ouverture des fichiers, initialisation du pipe et iteration de fork process
int pipex(int argc, char *argv[], char *envp[])
{
t_fd fd;
int i;
i = 2;
if (pipe(fd.pipe) == -1)
error_message(2);
fd.tmp = open(argv[1], O_RDONLY);
fd.out_file = open(argv[4], O_CREAT | O_WRONLY | O_TRUNC, 0644);
while (i < argc - 1)
{
fork_process(argv[i], envp, &fd, i);
i++;
}
close(fd.tmp);
close(fd.out_file);
close(fd.pipe[0]);
return (wait_last(fd.pid));
}
int main(int argc, char *argv[], char *envp[])
{
if (argc < 5)
error_message(1);
return (pipex(argc, argv, envp));
}
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:study_app/configs/themes/app_icons.dart';
import 'package:study_app/configs/themes/custom_text.styles.dart';
import 'package:study_app/configs/themes/ui_parameters.dart';
import 'package:study_app/controllers/question_paper/question_paper_controller.dart';
import 'package:study_app/models/question_paper_model.dart';
import 'package:get/get.dart';
import 'package:study_app/widgets/app_icon_text.dart';
class QuestionCard extends GetView<QuestionPaperController> {
final QuestionPaperModel model;
const QuestionCard({Key? key, required this.model}) : super(key: key);
@override
Widget build(BuildContext context) {
const double _padding = 10.0;
return Container(
decoration: BoxDecoration(
borderRadius: UIParameters.cardBorderRadius,
color: Theme.of(context).cardColor),
child: InkWell(
onTap: () {
controller.navigateToQuestions(paper: model);
},
child: Padding(
padding: const EdgeInsets.all(_padding),
child: Stack(
clipBehavior: Clip.none,
children: [
Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: ColoredBox(
color: Theme.of(context).primaryColor.withOpacity(0.2),
child: SizedBox(
height: Get.width * 0.15,
width: Get.width * 0.15,
child: CachedNetworkImage(
imageUrl: model.imageUrl!,
placeholder: (context, url) => Container(
alignment: Alignment.center,
child: const CircularProgressIndicator(),
),
errorWidget: (context, url, error) =>
Image.asset("assets/images/app_splash_logo.png"),
),
),
),
),
const SizedBox(
width: 12,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
model.title,
style: cardTitle(context),
),
Padding(
padding: const EdgeInsets.only(top: 10, bottom: 15),
child: Text(model.description)),
Row(
children: [
AppIconText(
icon: Icon(
Icons.help_outline_sharp,
color: UIParameters.isDarkMode()
? Colors.white
: Theme.of(context).primaryColor,
),
text: Text(
'${model.questionCount} questions',
style: detailText.copyWith(
color: UIParameters.isDarkMode()
? Colors.white
: Theme.of(context).primaryColor),
)),
const SizedBox(
width: 15,
),
AppIconText(
icon: Icon(
Icons.timer,
color: UIParameters.isDarkMode()
? Colors.white
: Theme.of(context).primaryColor,
),
text: Text(
model.timeInMinutes(),
style: detailText.copyWith(
color: UIParameters.isDarkMode()
? Colors.white
: Theme.of(context).primaryColor),
)),
],
)
],
),
)
],
),
Positioned(
bottom: -_padding,
right: -_padding,
child: GestureDetector(
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 12, horizontal: 20),
child: const Icon(
AppIcons.trophyOutline,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(cardBorderRadius),
bottomRight: Radius.circular(cardBorderRadius)),
color: Theme.of(context).primaryColor),
),
))
],
),
),
),
);
}
}
|
### 第五节 死锁
- 死锁问题
- 定义与示例
- 死锁是指两个或更多的进程在执行过程中,因争夺资源而造成的一种僵局。
- 示例: 桥梁问题,桥只能单向通行,可能出现两车对面相遇的情况。
- 死锁的必要条件
- 必需同时满足以下四个条件:
- 互斥:资源不能被共享,只能由一个进程使用。
- 请求与保持:进程已经保持至少一个资源,又提出新的资源请求,该资源被其他进程占有。
- 非抢占:资源只能由占有它的进程释放。
- 循环等待:发生死锁时,必然存在一个进程—资源的闭环链。
- 资源分配图
- 描述了进程与资源之间的分配关系。
- 图中节点表示进程和资源,边表示请求或分配。
- 资源分类
- 可重用资源
- 可消耗资源
- 死锁处理办法
- 预防
- 破坏死锁的四个必要条件中的一个或多个。
- 方法包括:一次性分配所有资源、可剥夺资源、顺序分配资源等。
- 避免
- 动态地考察资源分配状态,避免系统进入不安全状态。
- 安全状态:一定没有死锁;不安全状态:可能出现死锁
- 银行家算法:动态地检查资源分配是否安全,只在安全的情况下才分配资源给进程。
- 检测与恢复
- 定期检查系统是否进入死锁状态,并采取措施解除死锁。
- 死锁检测算法。
- 恢复方法包括杀死进程、回滚进程等。
- 忽略
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" >
<title>20190925MySQL集群结构说明 | quansen88.cn</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="shortcut icon" href="https://kill0es.github.io/favicon.ico?v=1623995355721">
<link rel="stylesheet" href="https://kill0es.github.io/styles/main.css">
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<meta name="description" content="完全参考:https://www.cnblogs.com/f-ck-need-u/p/9278900.html
在以前,数据库的集群配置一直很难,难点在于MySQL主从结构的高可用和读写分离。万幸的是,Galera/GR的出现,让整个集群的..." />
<meta name="keywords" content="mysql" />
</head>
<body>
<div id="app" class="main">
<div class="sidebar" :class="{ 'full-height': menuVisible }">
<div class="top-container" data-aos="fade-right">
<div class="top-header-container">
<a class="site-title-container" href="https://kill0es.github.io">
<img src="https://kill0es.github.io/images/avatar.png?v=1623995355721" class="site-logo">
<h1 class="site-title">quansen88.cn</h1>
</a>
<div class="menu-btn" @click="menuVisible = !menuVisible">
<div class="line"></div>
</div>
</div>
<div>
<a href="/" class="site-nav">
首页
</a>
<a href="/archives" class="site-nav">
归档
</a>
<a href="/tags" class="site-nav">
标签
</a>
<a href="/post/about" class="site-nav">
关于
</a>
</div>
</div>
<div class="bottom-container" data-aos="flip-up" data-aos-offset="0">
<div class="social-container">
</div>
<div class="site-description">
linux运维
</div>
<div class="site-footer">
Powered by <a href="https://github.com/kill0es/" target="_blank">kill0es</a> | <a class="rss" href="https://kill0es.github.io/atom.xml" target="_blank">RSS</a>
</div>
</div>
</div>
<div class="main-container">
<div class="content-container" data-aos="fade-up">
<div class="post-detail">
<h2 class="post-title">20190925MySQL集群结构说明</h2>
<div class="post-date">2021-04-27</div>
<div class="feature-container" style="background-image: url('https://www.runoob.com/wp-content/uploads/2014/03/mysql.jpg')">
</div>
<div class="post-content" v-pre>
<p>完全参考:https://www.cnblogs.com/f-ck-need-u/p/9278900.html</p>
<p>在以前,数据库的集群配置一直很难,难点在于MySQL主从结构的高可用和读写分离。万幸的是,Galera/GR的出现,让整个集群的配置都极大程度地简化了。</p>
<p>以下是一个简单的MySQL集群拓扑图:</p>
<figure data-type="image" tabindex="1"><img src="https://raw.githubusercontent.com/52cto/PictureGo/master/img/20190925162442.png" alt="" loading="lazy"></figure>
<p><strong>1.MySQL中间件:对MySQL Server的读写操作进行路由(即读写分离);分库分表(sharding)</strong></p>
<ul>
<li>(1).MySQL Router:MySQL官方提供的轻量级MySQL代理(路由),只提供读写分离功能,前身为SQL Proxy。</li>
<li>(2).ProxySQL:类似于MySQL Router,轻量级MySQL代理,提供读写分离功能,也支持一些sharding功能。有percona版和官方版两个版本。</li>
<li>(3).MaxScale:MariaDB的中间件,和MySQL Router、ProxySQL类似。
<ul>
<li>这三者类似,都是轻量级数据库中间件。</li>
</ul>
</li>
<li>(4).Amoeba、Cobar、MyCAT:提供很多功能,最主要的功能包括读写分离、sharding。
<ul>
<li>这三者的渊源较深,都是开源的。Amoeba后继无人,于是Cobar出来,Cobar后继无人,加上2013年出现了一次较严重的问题,于是MyCAT站在Cobar的肩膀上出来了。</li>
</ul>
</li>
</ul>
<p><strong>2.MySQL主从复制的高可用:至少要实现主从切换或故障时选举新master节点</strong></p>
<ul>
<li>(1).MMM:淘汰了,在一致性和高并发稳定性等方面有些问题。</li>
<li>(2).MHA:有些人还在用,但也有些问题,也是趋于淘汰的MySQL主从高可用方案。</li>
<li>(3).Galera:引领时代的主从复制高可用技术。</li>
<li>(4).MariaDB Galera Cluster:MariaDB对Galera的实现。</li>
<li>(5).PXC:Percona XtraDB Cluster,是Percona对Galera的自我实现,用的人很多。</li>
<li>(6).GR:Group Replication,MySQL官方提供的组复制技术(MySQL 5.7.17引入的技术),基于Paxos算法。
<ul>
<li>MariaDB Galera Cluster、PXC、GR是类似的,都各有优点。但GR是革命性的,基于原生复制技术,据传很多方面都优于PXC。</li>
<li>MariaDB Galera Cluster、PXC、GR为了安全性和性能考虑,做出了很多强制性的限制。例如基于GTID复制、只能InnoDB表,每表都必须有主键等。要使用它们提供主从复制的高可用,必须要了解它们的各项限制。</li>
</ul>
</li>
</ul>
</div>
<div class="tag-container">
<a href="https://kill0es.github.io/tag/0aHXx4YXw/" class="tag">
mysql
</a>
</div>
<div class="next-post">
<div class="next">下一篇</div>
<a href="https://kill0es.github.io/20190925mysql-de-ban-tong-bu-fu-zhi/">
<h3 class="post-title">
20190925MySQL的半同步复制
</h3>
</a>
</div>
</div>
</div>
</div>
</div>
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script type="application/javascript">
AOS.init();
var app = new Vue({
el: '#app',
data: {
menuVisible: false,
},
})
</script>
</body>
</html>
|
//
// IncomeViewModel.swift
// BudgetPlanner
//
// Created by Iulia Groza on 30.10.2023.
//
import Foundation
class IncomeViewModel: ObservableObject {
@Published var incomes: [Income] = []
init() {
// Prepopulate with 5 incomes
self.incomes = [
Income(id: UUID().uuidString, amount: 5000, category: "Salary", date: Date(), notes: "Salary from month May"),
Income(id: UUID().uuidString, amount: 1500, category: "Pension", date: Date().addingTimeInterval(-86400), notes: ""),
Income(id: UUID().uuidString, amount: 300, category: "Investments", date: Date().addingTimeInterval(-2 * 86400), notes: "Stocks investments"),
Income(id: UUID().uuidString, amount: 1200, category: "Salary", date: Date().addingTimeInterval(-3 * 86400), notes: ""),
Income(id: UUID().uuidString, amount: 450, category: "Other", date: Date().addingTimeInterval(-4 * 86400), notes: "Gift from a friend")
]
}
func addIncome(_ income: Income) {
incomes.append(income)
}
func updateIncome(_ updatedIncome: Income) {
if let index = incomes.firstIndex(where: { $0.id == updatedIncome.id }) {
incomes[index] = updatedIncome
}
}
func deleteIncome(_ income: Income) {
incomes.removeAll { $0.id == income.id }
}
}
|
class Human {
constructor(name, address) {
this.name = name;
this.address = address;
}
introduce() {
console.log(`halo, nama saya adalah ${this.name}`);
}
work() {
console.log('working');
}
}
class Programmer extends Human {
constructor(name, address, programmingLanguage) {
super(name, address);
this.programmingLanguage = programmingLanguage;
};
introduce() {
super.introduce();
console.log(`i can write ${this.programmingLanguage}`);
}
code() {
console.log(`code some ${this.programmingLanguage[Math.random() * this.programmingLanguage.length]} language`);
}
}
let Obama = new Human('Barrack Obama', 'Washington DC');
Obama.introduce();
Obama.work();
console.log('\n\n');
let Isyana = new Programmer('Isyana', 'Jakarta', ['php', 'js', 'golang', 'python']);
Isyana.introduce();
Isyana.code();
Isyana.work();
|
"""
Author: Aarya
Description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
Time Complexity: O(n), where n is the length of the string
"""
class Solution:
def isValid(self, s: str) -> bool:
# intialize an empty stack to store open brackets
stack = []
"""
create a hashmap that stores the closing brackets as the key and the opening brackets as the values
this will be utilized later to check for valid parentheses
key => closing bracket, value => opening bracket
"""
bracket_map = {")" : "(", "}" : "{", "]" : "["}
# loop through the string
for bracket in s:
"""
if the current bracket is one of the opening brackets then add it to the stack
all the opening brackets are stored as the values in the bracket_map
"""
if bracket in bracket_map.values():
stack.append(bracket)
# if the current bracket is not an opening bracket then it must be a closing bracket
else:
"""
if the stack is empty or
if the closing bracket is not the same as it's corresponding opening bracket then return False
- use stack.pop() to pop out(remove) the last item in the stack
e.g. if the current bracket is "]" and the bracket that was popped out isn't "[", then return False
"""
if not stack or stack.pop() != bracket_map[bracket]:
return False
"""
if the stack is empty by the end of the string then return True, as all brackets are closed
if the stack is not empty by the end of the string then return False,
as there some open brackets are still present in the stack
"""
return True if not stack else False
|
//
// Data.swift
// CoreDataGenerics
//
// Created by Ievgen Keba on 1/12/17.
// Copyright © 2017 Harman Inc. All rights reserved.
//
import Foundation
protocol CoreDataProtocol {
func get<Entity: ManagedObjectConvertible>
(with predicate: NSPredicate?,
sortDescriptors: [NSSortDescriptor]?,
fetchLimit: Int?,
completion: @escaping (Result<[Entity]>) -> Void)
func upsert<Entity: ManagedObjectConvertible>
(entities: [Entity],
completion: @escaping (Error?) -> Void)
}
extension CoreDataProtocol {
func get<Entity: ManagedObjectConvertible>
(with predicate: NSPredicate? = nil,
sortDescriptors: [NSSortDescriptor]? = nil,
fetchLimit: Int? = nil,
completion: @escaping (Result<[Entity]>) -> Void) {
get(with: predicate,
sortDescriptors: sortDescriptors,
fetchLimit: fetchLimit,
completion: completion)
}
}
enum CoreDataWorkerError: Error{
case cannotFetch(String)
case cannotSave(Error)
}
class Data: CoreDataProtocol {
let coreData: CoreDataStackProtocol
init(coreData: CoreDataStackProtocol = CoreDataStack.shared) {
self.coreData = coreData
}
func get<Entity : ManagedObjectConvertible>(with predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?, fetchLimit: Int?, completion: @escaping (Result<[Entity]>) -> Void) {
coreData.performForegroundTask { (context) in
do {
let fetchRequest = Entity.ManagedObject.fetchRequest()
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sortDescriptors
if let fetchLimit = fetchLimit {
fetchRequest.fetchLimit = fetchLimit
}
let results = try context.fetch(fetchRequest) as? [Entity.ManagedObject]
let items: [Entity] = results?.flatMap { $0.toEntity() as? Entity } ?? []
completion(.success(items))
} catch {
let fetchError = CoreDataWorkerError.cannotFetch("Cannot fetch error: \(error))")
completion(.failure(fetchError))
}
}
}
func upsert<Entity: ManagedObjectConvertible>(entities: [Entity], completion: @escaping (Error?) -> Void) {
coreData.performBackgroundTask { context in
_ = entities.flatMap({ (entity) -> Entity.ManagedObject? in
return entity.toManagedObject(in: context)
})
do {
try context.save()
completion(nil)
} catch {
completion(CoreDataWorkerError.cannotSave(error))
}
}
}
}
|
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
/* 돋보기 아이콘과 input 텍스트 박스가 겹쳐도, 클릭 시 input 텍스트 박스가 강조되게. */
const searchEl = document.querySelector('.search');
const searchInputEl = searchEl.querySelector('input');
searchEl.addEventListener('click', function () {
searchInputEl.focus();
});
/* input요소가 focus 되었을 때. */
searchInputEl.addEventListener('focus', function() {
searchEl.classList.add('focused');
searchInputEl.setAttribute('placeholder', '통합검색');
});
/* input요소가 blur 되었을 때. */
searchInputEl.addEventListener('blur', function() {
searchEl.classList.remove('focused');
searchInputEl.setAttribute('placeholder', '');
});
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
/* 스크롤을 아래로 일정 수준 이상 내리면, 화면 좌측의 뱃지가 사라지게 하는 코드 */
const badgeEl = document.querySelector('header .badges');
const toTopEl = document.querySelector('#to-top');
window.addEventListener('scroll', _.throttle(function () {
console.log(window.scrollY);
if (window.scrollY > 500) {
// 뱃지 숨기기
gsap.to(badgeEl, .6, {
opacity: 0,
display: 'none'
});
/** GO TO TOP 버튼 보이기 !! **/
gsap.to(toTopEl, .2, {
x: 0
});
/** GO TO TOP 버튼 보이기 !! **/
}
else {
// 뱃지 보이기
gsap.to(badgeEl, .6, {
opacity: 1,
display: 'block'
});
/** GO TO TOP 버튼 숨기기 !! **/
gsap.to(toTopEl, .2, {
x: 100
});
/** GO TO TOP 버튼 숨기기 !! **/
}
}, 300));
/** GO TO TOP 버튼 클릭시, 화면 상단으로 이동 기능 **/
toTopEl.addEventListener('click', function () {
gsap.to(window, .7, {
scrollTo: 0
});
});
/** GO TO TOP 버튼 클릭시, 화면 상단으로 이동 기능 **/
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
// visual title 부분 순차 애니메이션 적용
const fadeEls = document.querySelectorAll('.visual .fade-in');
fadeEls.forEach(function (fadeEl, index) {
gsap.to(fadeEl, 1, {
delay: (index + 1) * .7,
opacity: 1
});
});
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
// NOTICE 부분 슬라이드 기능 적용.
new Swiper('.notice-line .swiper-container', {
direction: 'vertical',
autoplay: true,
loop: true
});
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
// PROMOTION 부분 슬라이드 적용
new Swiper('.promotion .swiper-container', {
slidesPerView: 3,
spaceBetween: 10,
centeredSlides: true,
loop: true,
autoplay: {
delay: 5000
},
pagination: {
el: '.promotion .swiper-pagination',
clickable: true
},
navigation: {
prevEl: '.promotion .swiper-prev',
nextEl: '.promotion .swiper-next'
}
});
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
// Promotion 페이지 드랍다운 효과 설정.
const promotionEl = document.querySelector('.promotion');
const promotionToggleBtn = document.querySelector('.toggle-promotion');
let isHidePromotion = false;
promotionToggleBtn.addEventListener('click', function () {
isHidePromotion = !isHidePromotion;
if (isHidePromotion) {
// 숨김 처리 실행.
promotionEl.classList.add('hide');
}
else {
// 드랍다운 실행.
promotionEl.classList.remove('hide');
}
});
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
// 둥둥 떠다니는 이미지 효과 구현
// 범위 랜덤 함수.
function random(min, max) {
return parseFloat((Math.random() * (max - min) + min).toFixed(2));
}
function floatingObject (selector, delay, size) {
gsap.to(selector, random(1.5, 2.5), {
y: size,
repeat: -1,
yoyo: true,
ease: Power1.easeInOut,
delay: random(0, delay)
});
}
floatingObject('.floating1', 1, 15);
floatingObject('.floating2', .5, 15);
floatingObject('.floating3', 1.5, 20);
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
// Scroll Magic
const spyEls = document.querySelectorAll('section.scroll-spy');
spyEls.forEach(function (spyEl, index) {
// 메소드 체이닝
new ScrollMagic
.Scene({
triggerElement: spyEl,
triggerHook: .8,
})
.setClassToggle(spyEl, 'show')
.addTo(new ScrollMagic.Controller());
});
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
// Awards 부분 슬라이드 효과.
new Swiper('.awards .swiper-container', {
autoplay: true,
loop: true,
spaceBetween: 30,
slidesPerView: 5,
navigation: {
prevEl: '.awards .swiper-prev',
nextEl: '.awards .swiper-next'
}
});
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
// 올해가 몇년도인지 자동으로 계산해주는 코드.
const thisYear = document.querySelector('.this-year');
thisYear.textContent = new Date().getFullYear();
/**********************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************/
|
package model;
import java.util.ArrayList;
import fileIO.FileIO;
import java.nio.file.Paths;
import java.util.Scanner;
import model.Customer;
import Control.Method;
import myException.MyException;
public class Company {
public static String str= Paths.get("").toAbsolutePath().toString();
public static String path=str+"/src/model/company.txt";
public static ArrayList<Customer> cusList= new ArrayList<>();
public static void readFile(){
FileIO IO= new FileIO();
cusList.addAll(IO.readFile(path));
}
public static void printAll(){
System.out.println("List of Customer");
System.out.println("--------------------------");
for(int i=0; i<cusList.size(); i++)
System.out.println(cusList.get(i).toString());
System.out.println("--------------------------");
System.out.println("Total : "+cusList.size()+" customers");
}
public static int findID(String str){
for(int i=0; i< cusList.size(); i++)
if(str.equalsIgnoreCase(cusList.get(i).getCustomerID()))
return i;
return -1;
}
public static void insertCus(){
String ID="", name="", phone="";
Method method= new Method();
try {
Scanner sc= new Scanner(System.in);
while(true){
try {
System.out.print("Enter CustomerID: ");
ID= sc.nextLine();
if(findID(ID)!=-1) throw new MyException("!!!ID MUST BE UNIQUE!!!");
break;
} catch(MyException e){
System.out.println(e.getMessage());
}catch (Exception e) {
System.out.println("!!!ID wrong format!!!");
}
}
System.out.print("Enter Name: ");
name= sc.nextLine();
while(true){
try {
System.out.print("Enter Phone: ");
phone= sc.nextLine();
if(method.checkPhone(phone)==false) throw new MyException("!!!PHONE WRONG FORMAT EX:/0xxxxxxxxx/with x is number!!!");
break;
} catch(MyException e){
System.out.println(e.getMessage());
}catch (Exception e) {
System.out.println("!!!ID wrong format!!!");
}
}
} catch (Exception e) {
}
cusList.add(new Customer(ID, method.standard(name), phone));
System.out.println("!!!ADD SUCCESSFULL!!!");
}
public static void cusSearch(int k){
String str;
int j=0;
Scanner sc= new Scanner(System.in);
if(k==1){
System.out.print("Enter ID of Customer: ");
str= sc.nextLine();
System.out.println("----------------------------");
for(int i=0; i< cusList.size(); i++){
if(str.equalsIgnoreCase(cusList.get(i).getCustomerID())){
System.out.println(cusList.get(i).toString());
j++;
}
}
System.out.println("----------------------------");
}else{
System.out.print("Enter Name of Customer: ");
str= sc.nextLine();
System.out.println("----------------------------");
for(int i=0; i< cusList.size(); i++){
if(cusList.get(i).getName().toLowerCase().contains(str.toLowerCase())){
System.out.println(cusList.get(i).toString());
j++;
}
}
System.out.println("----------------------------");
}
System.out.println("Total : "+j+" customers");
}
public static void satic(int k){
System.out.println("List of Customer");
int j=0;
System.out.println("--------------------------");
if(k==1)
for(int i=0; i<cusList.size(); i++){
if(cusList.get(i).getPhone().contains("098")){
System.out.println(cusList.get(i).toString());
j++;
}
}
else if(k==2)
for(int i=0; i<cusList.size(); i++){
if(cusList.get(i).getPhone().contains("091")){
System.out.println(cusList.get(i).toString());
j++;
}
}
else
for(int i=0; i<cusList.size(); i++){
if(cusList.get(i).getPhone().contains("090")){
System.out.println(cusList.get(i).toString());
j++;
}
}
System.out.println("--------------------------");
System.out.println("Total : "+j+" Customer");
}
}
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:triwarna_rebuild/app/components/base_button.dart';
import 'package:triwarna_rebuild/app/components/base_formgrouppin.dart';
import 'package:triwarna_rebuild/app/components/base_text.dart';
import 'package:triwarna_rebuild/app/core/values/colors.dart';
import 'package:triwarna_rebuild/app/modules/forgot_pin/verify_otp/controller.dart';
class VerifyOtpBody extends StatelessWidget {
VerifyOtpBody({super.key});
final controller = Get.find<VerifyOtpController>();
@override
Widget build(BuildContext context) {
return Obx(
() => Padding(
padding: const EdgeInsets.all(15),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Align(
alignment: Alignment.centerLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const BaseText(
text: 'Verifikasi OTP',
size: 20,
color: Colors.white,
bold: FontWeight.w600,
),
BaseText(
text: controller.type.value == 'wa'
? 'Masukkan kode OTP yang sudah kami kirimkan ke whatsapp anda'
: 'Masukkan kode OTP yang sudah kami kirimkan ke email anda',
size: 12,
color: Colors.white70,
),
],
),
),
const SizedBox(height: 20),
BaseText(
text: controller.type.value == 'wa'
? 'Kode OTP sudah dikirim ke whatsapp dengan no. telepon\n${controller.noTelp.value}'
: 'Kode OTP sudah dikirim ke email\n${controller.email.value}',
color: Colors.white,
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
Form(
key: controller.formKey.value,
child: Column(
children: [
BaseFormGroupForgotPin(
label: 'Kode OTP',
controller: controller.otpController.value,
obscureText: false,
validator: (value) {
if (value!.isEmpty) {
return 'Kode OTP tidak boleh kosong';
}
return null;
},
),
const SizedBox(height: 40),
SizedBox(
width: Get.width,
child: BaseButton(
bgColor: softPurpleColor,
fgColor: purpleColor,
label: 'Submit',
onPressed: () {
if (controller.formKey.value.currentState!.validate()) {
controller.verifyOtp();
}
},
),
),
const SizedBox(height: 5),
controller.tunggu.value
? const Text(
'Maaf anda sudah melakukan 3 kali request. Silahkan tunggu beberapa saat untuk melakukan request lagi.\nTerima kasih',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white70),
)
: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const BaseText(
text: 'Tidak menerima kode? ',
color: Colors.white,
),
GestureDetector(
onTap: controller.resendOtp,
child: const BaseText(
text: 'Kirim Ulang',
color: yellowColor,
bold: FontWeight.w500,
),
)
],
),
],
),
),
],
),
),
);
}
}
|
#include<iostream>
using namespace std;
class Point {
int x;
public:
Point(int x) { this->x = x; }
Point(const Point p) { x = p.x;}
int getX() { return x; }
};
int main()
{
Point p1(10);
Point p2 = p1;
cout << p2.getX();
return 0;
}
//output
//Compiler Error: p must be passed by reference
//The reason is simple, if we don't pass by reference, then argument p1 will be copied to p. So there will be a copy constructor call to call the copy constructor, which is not possible.
|
import React from "react";
import { supportedPlatforms } from "../custom";
import { Container, Grid, Typography } from "@mui/material";
import Image from "next/image";
import ItemAsGridChild from "../components/ItemAsGridChild";
export default function SupportedPlatforms() {
const SupportedPlatforms = supportedPlatforms.map((supportPlatform) => (
<Grid item xs={2} key={supportPlatform.id}>
<ItemAsGridChild sx={{ background: "transparent", boxShadow: 0 }}>
<Image
src={supportPlatform.iconPath}
width={40}
height={42}
alt={supportPlatform.label}
placeholder="supported platform"
blurDataURL={supportPlatform.iconPath}
/>
<Typography
align="center"
sx={{
fontWeight: "bold",
color: "#fff",
marginTop: "22px",
fontFamily: "Raleway",
}}
>
{supportPlatform.label}
</Typography>
</ItemAsGridChild>
</Grid>
));
return (
<Container
maxWidth={false}
sx={{
background: "#217FCE",
minHeight: "50vh",
paddingTop: "72px",
paddingBottom: "38px",
}}
>
<Grid
container
sx={{
maxWidth: "1280px",
margin: "auto",
}}
>
<Grid item xs={12}>
<Typography
sx={{
color: "#FFF",
fontSize: "30px",
fontFamily: "Raleway",
fontWeight: 800,
textAlign: "center",
}}
mb={5}
>
Saungpokki is a learning platform and supports
</Typography>
</Grid>
<Grid container item spacing={10}>
{SupportedPlatforms}
</Grid>
</Grid>
</Container>
);
}
|
import { useAppDispatch, useAppSelector } from "@/hooks/reduxHooks";
import { setModules } from "@/redux/slices/settingSlice";
import React from "react";
import { MODULE_OPTIONS } from "@/constants/constants";
import { handleDropdownOptionClick } from "@/utils/handleDropdownOptionClick";
type Props = {
moduleNumber: number;
};
const moduleMap = {
0: "moduleOne",
1: "moduleTwo",
2: "moduleThree",
3: "moduleFour",
4: "moduleFive",
};
const ModuleSelect = ({ moduleNumber }: Props) => {
const dispatch = useAppDispatch();
const { modules } = useAppSelector((state) => state.setting);
const handleModuleSelect = (module: string) => {
const newModules = modules.map((m, i) => {
if (i === moduleNumber) {
return module;
}
return m;
});
dispatch(setModules(newModules));
handleDropdownOptionClick();
};
return (
<div className="dropdown">
<div
tabIndex={0}
className="m-1 btn btn-xs bg-primary text-neutral-50 hover:bg-primary-focus">
{modules[moduleNumber]}
</div>
<ul
tabIndex={0}
className="p-0 menu dropdown-content border-base-300 border-2 bg-base-100 rounded-box w-40 max-h-64 overflow-y-auto block">
{Object.entries(MODULE_OPTIONS).map(([key, value]) => (
<li
value={key}
key={key}
onClick={() => handleModuleSelect(key)}
className="hover:bg-base-300">
<button>{value}</button>
</li>
))}
</ul>
</div>
);
};
export default ModuleSelect;
|
import 'package:app_dev_client_project_1/consts/consts.dart';
import 'package:app_dev_client_project_1/widgets/care_plan_widgets/paragraph_card.dart';
import 'package:app_dev_client_project_1/widgets/care_plan_widgets/paragraph_card_small.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gap/gap.dart';
class CarePlanPage extends StatelessWidget {
const CarePlanPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20.w),
decoration: BoxDecoration(
//give border color line only at top
border: Border(
top: BorderSide(
color: Color(0xfe0075FF),
width: 1,
),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(width: double.infinity),
Text(
"Care Plan",
style: Theme.of(context).textTheme.headlineLarge?.copyWith(
color: Color(0xfe0075FF), fontWeight: FontWeight.bold),
),
Gap(25.h),
ParagraphCard(text: carePlanMain),
Gap(20.h),
Text("Benefits", style: Theme.of(context).textTheme.displayLarge),
Gap(10.h),
SmallParagraphCard(text: costSaving, title: "Cost Savings"),
SmallParagraphCard(text: convenience, title: "Convenience"),
SmallParagraphCard(text: comprehensiveCoverage, title: "Comprehensive Coverage"),
SmallParagraphCard(text: additionalFeatures, title: "Additional Features"),
Gap(20.h),
Text("Select your plan",style: Theme.of(context).textTheme.displayLarge),
Gap(10.h),
Image.asset("assets/images/health_plans.png"),
Gap(10.h)
],
),
),
),
);
}
}
|
from typing import List
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from sqlalchemy.orm import Session
from . import crud, models, schemas
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
# @app.middleware("http")
# async def db_session_middleware(request: Request, call_next):
# response = Response("Internal server error", status_code=500)
# try:
# request.state.db = SessionLocal()
# response = await call_next(request)
# finally:
# request.state.db.close()
# return response
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
db_user = crud.get_user_by_email(db, email=user.email)
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
return crud.create_user(db=db, user=user)
@app.get("/users/", response_model=List[schemas.User])
def get_users(db: Session = Depends(get_db)):
users = crud.get_users(db)
return users
@app.get("/users/{user_id}", response_model=schemas.User)
def get_user(user_id: int, db: Session = Depends(get_db)):
db_user = crud.get_user(db, user_id=user_id)
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return db_user
#employee
# @app.post("/employees/", response_model=schemas.Employee)
# def create_user(employee: schemas.EmployeeCreate, db: Session = Depends(get_db)):
# db_user = crud.get_emp_by_email(db, email=employee.email)
# if db_user:
# raise HTTPException(status_code=400, detail="Email already registered")
# return crud.create_employee(db=db, user=employee)
# @app.post("/employees/{emp_id}/workhist/", response_model=schemas.Item)
# def create_item_for_user(
# user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
# ):
# return crud.create_user_item(db=db, item=item, user_id=user_id)
# @app.get("/users/", response_model=List[schemas.User])
# def get_users(db: Session = Depends(get_db)):
# users = crud.get_users(db)
# return users
# @app.get("/users/{user_id}", response_model=schemas.User)
# def get_user(user_id: int, db: Session = Depends(get_db)):
# db_user = crud.get_user(db, user_id=user_id)
# if db_user is None:
# raise HTTPException(status_code=404, detail="User not found")
# return db_user
@app.post("/users/{user_id}/items/", response_model=schemas.Item)
def create_item_for_user(
user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
):
return crud.create_user_item(db=db, item=item, user_id=user_id)
@app.get("/items/", response_model=List[schemas.Item])
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
items = crud.get_items(db, skip=skip, limit=limit)
return items
|
library(ggplot2)
n_numbers <- 5000
# 1. Completa el marco de datos de números aleatorios.
# - Genera `n_numbers`
## a partir de una distribución uniforme que varía de `3` a `3`.
# - Genera `n_numbers`
## a partir de una distribución normal con media `5` y desviación estándar `2`.
# Generate random numbers from ...
randoms <- data.frame(
# a uniform distribution from -3 to 3
uniform = runif(n_numbers, min = -3, max = 3),
# a normal distribution with mean 5 and sd 2
normal = rnorm(n_numbers, mean = 5, sd = 2)
)
# 2. Usando `randoms`, traza un histograma de la columna `uniform`,
## usando un ancho de bin de `0.25`.
# Plot a histogram of uniform values, binwidth 0.25
ggplot(randoms, aes(uniform)) +
geom_histogram(binwidth = 0.25)
# 3. Usando `randoms`, traza un histograma de la columna `normal`,
## usando un ancho de bin de `0.5`.
# Plot a histogram of normal values, binwidth 0.5
ggplot(randoms, aes(normal)) +
geom_histogram(binwidth = 0.5)
|
using Application;
using Application.Clients;
using Application.Instructors;
using Application.Rutinas;
using Application.Weekdays;
using Domain.Configuration;
using Domain.Instructors;
using Persistence;
using System.ComponentModel;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddPersistenceServices(builder.Configuration);
builder.Services.AddApplicationServices(builder.Configuration);
var endpoints = builder.Configuration.GetSection
(nameof(EndpointConfiguration)).Get<List<EndpointConfiguration>>();
builder.Services.Configure<List<EndpointConfiguration>>
(options => { options.AddRange(endpoints); });
builder.Services.AddHttpClient<IClientClient, ClientClient>((provider, client) =>
{
var endpoint = endpoints.Where
(s => s.Name.Equals("DefaultApi", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
client.BaseAddress = new Uri(endpoint.Uri);
});
builder.Services.AddHttpClient<IInstructorInstructor, InstructorInstructor>((provider, instructor) =>
{
var endpoint = endpoints.Where
(s => s.Name.Equals("DefaultApi", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
instructor.BaseAddress = new Uri(endpoint.Uri);
});
builder.Services.AddHttpClient<IRutinaClient, RutinaClient>((provider, rutina) =>
{
var endpoint = endpoints.Where
(s => s.Name.Equals("DefaultApi", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
rutina.BaseAddress = new Uri(endpoint.Uri);
});
builder.Services.AddHttpClient<IWeekdayClient, WeekdayWeekday>((provider, weekday) =>
{
var endpoint = endpoints.Where
(s => s.Name.Equals("DefaultApi", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
weekday.BaseAddress = new Uri(endpoint.Uri);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
|
import React from "react";
import FooterItem from "./FooterItem";
import { Link } from "react-router-dom";
const FooterMenu = () => {
return (
<div className="footer__menu">
<ul className="footer__list">
<FooterItem>
<Link to="/pages/about" className="footer__link">
About Us
</Link>
</FooterItem>
<FooterItem>
<Link to="/pages/faq" className="footer__link">
Faq
</Link>
</FooterItem>
<FooterItem>
<Link to="/pages/contact" className="footer__link">
Contact Us
</Link>
</FooterItem>
</ul>
<ul className="footer__list">
<FooterItem>
<Link to="/pages/privacy-policy" className="footer__link">
Privacy Policy
</Link>
</FooterItem>
<FooterItem>
<Link to="/pages/faq" className="footer__link">
Refund Policy
</Link>
</FooterItem>
<FooterItem>
<Link to="/pages/terms-and-conditions" className="footer__link">
Terms of Service
</Link>
</FooterItem>
</ul>
<ul className="footer__list">
<FooterItem>
<Link to="/pages/faq" className="footer__link">
How to Order
</Link>
</FooterItem>
<FooterItem>
<a
href="https://www.ram.co.za/contact/TrackYourParcel"
className="footer__link"
>
Track Your Order
</a>
</FooterItem>
<FooterItem>
<Link to="/pages/faq" className="footer__link">
Return & Exchanges
</Link>
</FooterItem>
</ul>
<ul className="footer__list footer__list--mobile">
<FooterItem>
<a href="https://www.instagram.com/lemkus_/" className="footer__link">
Instagram
</a>
</FooterItem>
<FooterItem>
<a href="https://twitter.com/lemkus_" className="footer__link">
Twitter
</a>
</FooterItem>
<FooterItem>
<a
href="https://www.facebook.com/jacklemkus"
className="footer__link"
>
Facebook
</a>
</FooterItem>
</ul>
</div>
);
};
export default FooterMenu;
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fluttercompoundapp/core/models/post.dart';
class PostItem extends StatelessWidget {
final Post post;
final Function onDeleteItem;
const PostItem({Key? key, required this.post, required this.onDeleteItem})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
height: post.imageUrl != null ? null : 60,
margin: const EdgeInsets.only(top: 20),
alignment: Alignment.center,
child: Row(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
post.imageUrl != null
? SizedBox(
height: 250,
child: CachedNetworkImage(
imageUrl: post.imageUrl!,
placeholder: (context, url) =>
const CircularProgressIndicator(),
errorWidget: (context, url, error) => const Icon(Icons.error),
),
)
: Container(),
Text(post.title),
],
),
),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () {
onDeleteItem();
},
),
],
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
boxShadow: [
BoxShadow(blurRadius: 8, color: Colors.grey.shade200, spreadRadius: 3)
],
),
);
}
}
|
# RAG-Tutorial Codebase
This is the repository containing the code base from the tutorial about RAG for STEM scientists.
## Who is this tutorial for?
This tutorial is for STEM scientists that are interested in learning about the general concept of RAG.
We will apply this concept to the problem of creating a personalized chatbot, which answers questions in the context of your reasearch by using documents from your own (PDF) document library.
## Prerequisits
This tutorial is trageting STEM scientists, so you should have a scientific background and some basic knowledge of Python.
Furthermore it is required to have a Huggingface account, if you don't have one yet, you can create it [here](https://huggingface.co/join).
## What you'll learn
### Basic understanding of retrival augmented generation
First we touch on the general concept of retrival augmented generation (RAG).
The interaction between the different base-technologies is explained on a conceptual level.
### Technology Stack
In terms of technology, we will use:
- ChromaDB as a database
- Mistral AI as a large language model
- Langchain to manage the flow
- All-mpnet as a wordembedding
Most of the machine learning related components will be handeled via the Huggingface platfrom.
### Usage example and perfromance assessment
Finally the RAG portotpye is being tested. The aim is to understand what are the capabilities and the limitations of our system. and how to benchmark systems in the context of our scientific use-case.
|
import { DataTypes } from "sequelize";
import sequelize from "../dbConfig/index.js";
const db = sequelize;
const User = db.sequelize.define(
"User",
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
},
first_name: {
type: DataTypes.STRING,
allowNull: false,
},
last_name: {
type: DataTypes.STRING,
allowNull: false,
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true,
},
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
verificationToken: {
type: DataTypes.UUID,
allowNull: true,
},
verificationTokenExpires: {
type: DataTypes.DATE,
allowNull: true,
},
isVerified: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
emailSent: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
emailSentTime: {
type: DataTypes.DATE,
allowNull: true,
},
},
{
timestamps: true,
createdAt: "account_created",
updatedAt: "account_updated",
}
);
export default User;
|
import requests
from typing import Any
from .regulators import WikiJSExceptions
from .methods.analytics import AnalyticsQuery, AnalyticsMutation
from .methods.assets import AssetQuery, AssetMutation
from .methods.authentication import AuthenticationQuery, AuthenticationMutation
from .methods.comments import CommentQuery, CommentMutation
from .methods.contribute import ContributeQuery
from .methods.groups import GroupQuery, GroupMutation
from .methods.localization import LocalizationQuery, LocalizationMutation
from .methods.logging import LoggingQuery, LoggingMutation
from .methods.mail import MailQuery, MailMutation
from .methods.navigation import NavigationQuery, NavigationMutation
from .methods.pages import PageQuery, PageMutation
from .methods.rendering import RenderingQuery, RenderingMutation
from .methods.search import SearchQuery, SearchMutation
from .methods.site import SiteQuery, SiteMutation
from .methods.storage import StorageQuery, StorageMutation
from .methods.system import SystemQuery, SystemMutation
from .methods.theming import ThemingQuery, ThemingMutation
from .methods.users import UserQuery, UserMutation
class WikiJS(
AnalyticsQuery, AnalyticsMutation,
AssetQuery, AssetMutation,
AuthenticationQuery, AuthenticationMutation,
CommentQuery, CommentMutation,
ContributeQuery,
GroupQuery, GroupMutation,
LocalizationQuery, LocalizationMutation,
LoggingQuery, LoggingMutation,
MailQuery, MailMutation,
NavigationQuery, NavigationMutation,
PageQuery, PageMutation,
RenderingQuery, RenderingMutation,
SearchQuery, SearchMutation,
SiteQuery, SiteMutation,
StorageQuery, StorageMutation,
SystemQuery, SystemMutation,
ThemingQuery, ThemingMutation,
UserQuery, UserMutation,
):
def __init__(self, url: str, token: str) -> None:
self.endpoint = f"{url}/graphql"
self.auth = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}"
}
def gql_post(self, gql_query: str, params: dict[str, Any]) -> dict[str, Any]:
response = requests.post(
url=self.endpoint,
headers=self.auth,
json={
"query": gql_query,
"variables": params
}
).json()
if response.get("errors"):
err = response.get("errors")[0]
raise WikiJSExceptions( #noqa: IICE (Immediately Invoked Class Expression) was used
err['extensions']['code'],
err['message']
)
return response.get("data")
|
<%# local variables taken in account: %>
<%# - watched_param_name - string in format 'something'[] that will receive selected ids %>
<%# - watched_obj - object that is watched, could be omitted %>
<%# - watched_dom_id - html id of the section with all watchers, could be omitted %>
<%# - watched_users_preset - array of ids that should be on on startup, could be omitted %>
<%# - watched_project - project from which retrieve list of watchers, could be omitted %>
<% content_for :header_tags do %>
<%= javascript_include_tag('boards_watchers.js', :plugin => 'redmine_boards_watchers') %>
<% end %>
<% project = defined?(watched_project).nil? ? @project : watched_project%>
<% dom_id = defined?(watched_dom_id).nil? ? "bw" : watched_dom_id.to_s %>
<div class="tabular">
<div class="box" id="<%= "#{dom_id}-users" %>">
<p id="watchers_form">
<label><%= l(:label_issue_watchers) %></label>
<span id="watchers_inputs">
<% project.users.sort.each do |user| -%>
<label class="bw-floating floating" full_text="<%= h(user) %>">
<% watched_already = (defined?(watched_obj).nil? ? false : watched_obj.watched_by?(user)) %>
<% unless watched_already %>
<% if defined?(watched_users_preset).nil? == false && watched_users_preset.include?(user.id) %>
<% watched_already = true %>
<% end %>
<% end %>
<%= check_box_tag watched_param_name, user.id, watched_already, :id => sanitize_to_id(watched_param_name + user.id.to_s) %> <%=h user %>
</label>
<% end -%>
</span>
</p>
</div>
<p>
<%= label_tag "#{dom_id}-search", l(:label_user_search) %>
<%= text_field_tag "#{dom_id}-search", nil, :size => 40, :onkeyup => "highlightWatchers('#{dom_id}')" %>
<span class='bw-check-selected'>
<%= link_to_function(h(l(:label_bw_check_selected)),"toggleSelectedWatchers('1','#{dom_id}')") %>
</span>
<span class='bw-uncheck-selected'>
<%= link_to_function(h(l(:label_bw_uncheck_selected)),"toggleSelectedWatchers('0','#{dom_id}')", :class => 'bw-uncheck-selected') %>
</span>
</p>
</div>
<% groups = project.principals.select { |m| m.is_a?(Group) }.sort %>
<div class="tabular">
<div class="box" id="<%= "#{dom_id}-groups" %>">
<p class="bw-toggle-link">
<label><%= l(:label_bw_toggle_group) %></label>
<%= link_to_function(h(l(:label_bw_toggle_all)),"toggleWatchersCheckBoxes('#{[-1].to_json}','-1','#{dom_id}')") %>
<% if groups && groups.size > 0 %>
<% groups.each do |group| -%>
<%= link_to_function(h(group.name),"toggleWatchersCheckBoxes('#{group.users.collect(&:id).to_json}','-1','#{dom_id}')") %>
<% end -%>
<% end %>
</p>
</div>
</div>
|
# Doc2Vec TensorFlow Implementation
This project implements the Doc2Vec model using TensorFlow. Doc2Vec is an extension of Word2Vec that learns document embeddings in addition to word embeddings. In this implementation, we focus on training a Doc2Vec model for document similarity tasks.
## Table of Contents
- [Overview](#overview)
- [Dependencies](#dependencies)
- [Project Structure](#project-structure)
- [References](#references)
## Overview
The Doc2Vec model is a neural network-based approach to learn vector representations of documents in an unsupervised manner. This implementation uses TensorFlow to build and train the Doc2Vec model.
## Dependencies
Ensure you have the following dependencies installed:
- Python 3.x
- TensorFlow (>=2.0)
- Pandas
- NumPy
## Project structure
The project structure is organized as follows:
- Dataset/: Directory to store input datasets and link to the dataset.
- Doc2VecTensorflow.ipynb: Contains the source code and script for the Doc2Vec model implemented in Tensowflow.
- Deep_Learnin_Presentation.pptx: Project Presentation
- Linear_model_for_evaluation.py: Contains the linear model implemented for evaluation of the Doc2vec model.
## References
- Blog Post on "Practical Guide to Doc2Vec" by Radim Řehůřek: Radim Řehůřek, the creator of Gensim, has written a comprehensive blog post that serves as a practical guide to implementing Doc2Vec. It covers various aspects, from data preprocessing to model training and evaluation.
https://rare-technologies.com/doc2vec-tutorial/
- "Doc2Vec Tutorial" on Kaggle: Kaggle, a platform for data science and machine learning, offers a step-by-step tutorial on implementing Doc2Vec. This tutorial includes a Python notebook with code examples and explanations, making it a great resource for hands-on learning. https://www.kaggle.com/code/pierremegret/gensim-word2vec-tutorial/notebook
- Doc2Vec: Understanding Document Embeddings for Natural Language Processing https://medium.com/@evertongomede/doc2vec-understanding-document-embeddings-for-natural-language-processing-ba244e55eba3
- Doc2Vec in NLP https://www.geeksforgeeks.org/doc2vec-in-nlp/
- Tensorflow and Machine Learning Cookbook https://dl.ebooksworld.ir/motoman/Packt.TensorFlow.Machine.Learning.Cookbook.www.EBooksWorld.ir.pdf
- https://github.com/PacktPublishing/TensorFlow-Machine-Learning-Cookbook/blob/master/Chapter%2007/doc2vec.py
|
import java.util.HashMap;
import java.util.Vector;
public class EdgeWeightedDiGraph extends WeightedGraph {
/**
* You will need some variables for internal storage,
* but the details are up to you. You may make use
* of build in Java data structures to provide array/list
* and map(/symbol table/dictionary) support,
* or implement your own.
*
* If you implement your own classes for internal storage,
* make sure to include them in this file. You can only
* submit one file to Autolab, and it doesn't know how
* to unpack things.
*
* BE SURE TO READ THE ASSIGNMENT HANDOUT, AS ADDITIONAL
* IMPLEMENTATION REQUIREMENTS ARE SPECIFIED THERE.
*
*/
private HashMap<Integer, Double>[] graphData;
private int edges;
/**
* Part 1: Implement this
*
* Make sure to call super(V) before doing anything else;
* the code won't compile without that ;)
*
* Do any other initialization work you need here.
*
* As with the example in the slides, we assume that we will
* be given a number of vertices when we create the object,
* and that this cannot be changed after the fact.
*
* @param V -- Number of vertices in the graph
*/
public EdgeWeightedDiGraph(int V) {
// Calls the superclass
// Initialize Hashmap
//Sets edges to 0
//Iterate through and add a new HashMap
super(V);
graphData = new HashMap[V];
edges = 0;
for (int i = 0; i < V; i++) {
graphData[i] = new HashMap<>();
}
}
/**
* Part 3: Implement this
*
* Do something sensible here. An instance variable you can return
* in this method is probably a good call.
*
* Be sure that you deal with the rules for updating edge count correctly.
*
* @return -- Total number of edges in the graph
*/
@Override public int E() {
// Resets edges to 0
// Adds the number of edges per vertex to edges and returns
int edges = 0;
for (int i = 0; i < graphData.length; i++) {
edges += graphData[i].size();
}
return edges;
}
/**
* Part 2: Implement this
*
* This method is used to add an edge or update its weight.
*
* Throw an IndexOutOfBoundsException if the user specifies
* a starting or ending vertex that does not exist.
*
* If an edge already exists between v and u, replace its weight.
* At no time should you end up with more than one edge between
* any pair of vertices.
*
* Loops are not permitted. Throw an IllegalArgumentException
* if the user tries to specify a loop (i.e. if v == u).
*
* negative edge weights are permitted.
*
* Replacing a weight should not affect the number of edges
* in the graph.
*
* @param v -- Starting vertex of the edge
* @param u -- Ending vertex of the edge
* @param w -- Weight to be given to the edge
*/
@Override public void addEdge(int v, int u, double w) {
// Throws an Exception if it loops
// Checks to see if edges already exist and adds them if not
// Otherwise updates the weight
if (v == u) {
throw new IllegalArgumentException("Self-loops are not allowed.");
}
if (u < 0 || u >= V()) {
throw new IndexOutOfBoundsException("Vertex " + u + " is out of range.");
}
if (!graphData[v].containsKey(u)) {
graphData[v].put(u, w);
edges++;
} else {
graphData[v].put(u, w);
}
}
/**
* Part 5: Implement this
*
* Remove the specified edge from the graph, assuming it exists.
*
* Throw an IndexOutOfBoundsException if the user specifies
* a starting or ending vertex that does not exist.
*
* If the specified edge does not exist, do nothing.
*
* @param v -- Starting vertex of the edge
* @param u -- Ending vertex of the edge
*/
@Override public void removeEdge(int v, int u) {
// Checks if the start vertex is in the graph and
// If the edge exists, remove it
// Otherwise throw an Exception
if (v >= 0 && u >= 0 && v < V() && u < V()) {
if (graphData[v].containsKey(u)) {
graphData[v].remove(u);
}
} else {
throw new IndexOutOfBoundsException("The Vertex " + v + " does not exist");
}
}
/**
* Part 4: Implement this
*
* Return the weight of the edge from v to u, or null if no such
* edge exists.
*
* Throw an IndexOutOfBoundsException if the user specifies
* a starting or ending vertex that does not exist.
*
* @param v -- Starting vertex of the edge
* @param u -- Ending vertex of the edge
* @return -- Weight of edge (v,u) or null if no edge exists
*/
@Override public Double edgeWeight(int v, int u) {
// Checks to see if the vertices are out of bounds and
// If so, throw an Exception
// Otherwise, returns the weight of the edge, or null if not
if (v < 0 || v >= V()) {
throw new IndexOutOfBoundsException("Vertex v is out of bounds.");
}
if (u < 0 || u >= V()) {
throw new IndexOutOfBoundsException("Vertex u is out of bounds.");
}
if (graphData[v].containsKey(u)) {
return graphData[v].get(u);
} else {
return null;
}
}
/**
* Part 6: Implement this
*
* Return an iterable object containing the vertices
* adjacent to v.
*
* DO NOT include edge weights in the results.
*
* Throw an IndexOutOfBoundsException if the user
* specifies a vertex that does not exist.
*
* Return an empty iterable object if the vertex has
* no adjacent vertices.
*
* @param v -- Vertex whose adjacenies we wish to know
* @return -- Iterable object with vertices adjacent to v
*/
@Override public Iterable<Integer> adj(int v) {
// Checks to see if the vertex is out of bounds,
// If so, throws an Exception
// Creates a Vector to store the adj vertices and
// Iterates over all the vertices and
// Adds the adj vertices to the Vector
// Returns the Vector
if (v < 0 || v >= V()) {
throw new IndexOutOfBoundsException("The Vertex " + v + " does not exist in the graph");
}
Vector<Integer> adj = new Vector<>();
for (int i = 0; i < V(); i++) {
if (graphData[v].containsKey(i)) {
adj.add(i);
}
}
return adj;
}
}
|
import React from 'react'
import Image from 'next/image'
import Carousel from 'react-bootstrap/Carousel'
import styles from './event-carousel.module.scss'
export default function EventCarousel() {
return (
<>
<Carousel>
<Carousel.Item interval={1000} className={`${styles.CarouselItem}`}>
<Image
src={'/images/event/banner1.jpg'}
alt="環保"
fill
style={{ objectFit: 'cover' }}
priority
/>
<Carousel.Caption className={`${styles.info}`}>
<h3>愛護海洋,由你我開始!</h3>
<p>
每一個人都可以成為海洋保護者!加入我們的淨灘活動,為美麗的海洋生態盡一份心力!
</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item interval={500} className={`${styles.CarouselItem}`}>
<Image
src={'/images/event/banner2.jpg'}
alt="海洋"
fill
style={{ objectFit: 'cover' }}
priority
/>
<Carousel.Caption>
{/* <h3></h3>
<p></p> */}
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item className={`${styles.CarouselItem}`}>
<Image
src={'/images/event/banner3.jpg'}
alt="潛水"
fill
style={{ objectFit: 'cover' }}
priority
/>
<Carousel.Caption className={`${styles.info}`}>
<h3>潛水不只是活動,是一種生活方式</h3>
<p>
將潛水融入您的生活中!我們的課程和裝備將助您開啟潛水之旅,成為海洋世界的一部分。
</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</>
)
}
|
require "spec_helper.rb"
feature "homepage" do
scenario "should have a button" do
visit "/"
expect(page).to have_content("Register")
end
end
feature "registration_form" do
scenario "links to registration form" do
visit "/"
click_link "Register"
expect(page).to have_content("username")
end
end
feature "User Authentication" do
before(:each) do
visit "/"
click_link "Register"
fill_in "username", :with => "pgrunde"
fill_in "password", :with => "drowssap"
click_button "Register"
click_link "Register"
fill_in "username", :with => "natalie"
fill_in "password", :with => "renee"
click_button "Register"
click_link "Register"
fill_in "username", :with => "luke"
fill_in "password", :with => "evan"
click_button "Register"
click_link "Register"
fill_in "username", :with => "tom"
fill_in "password", :with => "jerry"
click_button "Register"
fill_in "Username", :with => "pgrunde"
fill_in "Password", :with => "drowssap"
click_button "Login"
end
scenario "allows user to login" do
expect(page).to have_content("Welcome, pgrunde!")
expect(page).to have_content("Logout")
expect(page).to have_no_content("Login")
expect(page).to have_no_content("Register")
end
scenario "allows user to log out" do
click_link "Logout"
expect(page).to have_content("Register")
expect(page).to have_content("Username")
end
scenario "A logged in user can view and sort a list of ALL users on the homepage" do
expect(page).to have_content("natalie luke")
select "Ascending", from: "sort_menu"
click_button "Sort"
expect(page).to have_content("luke natalie pgrunde tom")
select "Descending", from: "sort_menu"
click_button "Sort"
expect(page).to have_content("tom pgrunde natalie luke")
end
end
|
import os
import torch
import torch.nn as nn
import bitsandbytes as bnb
import transformers as transformers
from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM
from transformers import BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
from datasets import load_dataset
#Setup the model
model_id="bigscience/bloom-1b7"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", load_in_8bit=True)
print(model.get_memory_footprint())
'''
Change the compute dtype
The compute dtype is used to change the dtype that will be used during computation.
For example, hidden states could be in float32 but computation can be set to bf16 for speedups. By default, the compute dtype is set to float32.
quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
'''
'''
Using NF4 (Normal Float 4) data type
You can also use the NF4 data type, which is a new 4bit datatype adapted for weights that have been initialized using a normal distribution. For that run:
nf4_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
)
model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=nf4_config)
'''
'''
Use nested quantization for more memory efficient inference
We also advise users to use the nested quantization technique. This saves more memory at no additional performance - from our empirical observations,
this enables fine-tuning llama-13b model on an NVIDIA-T4 16GB with a sequence length of 1024, batch size of 1 and gradient accumulation steps of 4.
double_quant_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=double_quant_config)
'''
#Freezing the original weights
for param in model.parameters():
param.requires_grad = False
if param.ndim ==1:
param.data = param.data.to(torch.float32)
model.gradient_checkpointing_enable()
model.enable_input_require_grads()
class CastOutputToFloat(nn.Sequential):
def forward(self, x): return super().forward(x).to(torch.float32)
model.lm_head = CastOutputToFloat(model.lm_head)
#Setting up the LoRa Adapters
def print_trainable_parameters(model):
trainable_params = 0
all_param = 0
for _, param in model.named_parameters():
all_param += param.numel()
if param.requires_grad:
trainable_params += param.numel()
print(
f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}"
)
config = LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
bias = 'none',
task_type="CAUSAL_LM"
)
model = get_peft_model(model, config)
print_trainable_parameters(model)
data = load_dataset("Abirate/english_quotes")
def merge_colunms(example):
example['prediction'] = example['quote'] + " ->: " + str(example["tags"])
return example
data['train'] = data['train'].map(merge_colunms)
print(data['train']["prediction"][:5])
print(data['train'][0])
data = data.map(lambda samples: tokenizer(samples['prediction']), batched=True)
print(data)
#Training
trainer = transformers.Trainer(
model=model,
train_dataset=data['train'],
args=transformers.TrainingArguments(
per_gpu_train_batch_size=4,
gradient_accumulation_steps=4,
warmup_steps=100,
max_steps=200,
learning_rate=2e-4,
fp16=True,
logging_steps=1,
output_dir='outputs'
),
data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False)
)
model.config.use_cache = False
trainer.train()
model.push_to_hub("meetrais/bloom-7b1-lora-tagger",
token="HuggingFace-app-key",
commit_message="basic training",
private=True)
|
import { Link, useParams, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import axios from "axios";
import { Footer } from "./Footer";
export default function Sessions() {
const { movieID } = useParams();
const navigate = useNavigate();
const [sessions, setSessions] = useState(null);
function handleClick() {
navigate(-1);
}
useEffect(() => {
const request = axios.get(
`https://mock-api.driven.com.br/api/v5/cineflex/movies/${movieID}/showtimes`
);
request.then((resposta) => {
setSessions({ ...resposta.data });
});
request.catch((err) => {
console.error(err);
});
}, [movieID]);
if (sessions === null) {
return (
<div className="loading-spinner">
<div className="spinner">
<div className="ripple primary"></div>
<div className="ripple secondary"></div>
</div>
</div>
);
} else {
return (
<>
<ion-icon
onClick={handleClick}
class="return-btn"
name="chevron-back-outline"
></ion-icon>
<main id="movie">
<h4>Selecione o horário</h4>
{sessions.days.map((session, index) => {
const {
// eslint-disable-next-line no-unused-vars
id,
weekday,
date,
showtimes: [firstOption, secondOption],
} = session;
return (
<section key={index} className="schedule">
<p className="schedule__date">{`${weekday} ${date}`}</p>
<Link
to={`/session/${firstOption.id}`}
className="schedule__time-option default-btn"
>
{firstOption.name}
</Link>
<Link
to={`/session/${secondOption.id}`}
className="schedule__time-option default-btn"
>
{secondOption.name}
</Link>
</section>
);
})}
<Footer sessions={sessions}></Footer>
</main>
</>
);
}
}
|
import React, { useState } from "react";
import Grid from "@mui/material/Grid";
import { useLocation } from "react-router";
import TextField from "@mui/material/TextField";
import { outlinedInputClasses } from "@mui/material/OutlinedInput";
import { createTheme, ThemeProvider, useTheme } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
const customTheme = (outerTheme) =>
createTheme({
palette: {
mode: outerTheme.palette.mode,
},
components: {
MuiTextField: {
styleOverrides: {
root: {
"--TextField-brandBorderColor": "#E0E3E7",
"--TextField-brandBorderHoverColor": "#B2BAC2",
"--TextField-brandBorderFocusedColor": "#6F7E8C",
"& label.Mui-focused": {
color: "var(--TextField-brandBorderFocusedColor)",
},
},
},
},
MuiOutlinedInput: {
styleOverrides: {
notchedOutline: {
borderColor: "var(--TextField-brandBorderColor)",
},
root: {
[`&:hover .${outlinedInputClasses.notchedOutline}`]: {
borderColor: "var(--TextField-brandBorderHoverColor)",
},
[`&.Mui-focused .${outlinedInputClasses.notchedOutline}`]: {
borderColor: "var(--TextField-brandBorderFocusedColor)",
},
},
},
},
},
});
function Common(props) {
const [flag, setFlag] = useState(false);
const [inputEvents, setInputEvents] = useState({
fName: "",
email: "",
phoneNumber: "",
message: "",
});
let checkLocation = useLocation();
const outerTheme = useTheme();
// event handle onchange
const eventHandler = (event) => {
const { name, value } = event.target;
setInputEvents((prevValue) => {
return {
...prevValue,
[name]: value,
};
});
};
// event handel submit
const submitValue = (e) => {
e.preventDefault();
setFlag((prevState) => {
if (inputEvents.fName !== "" && inputEvents.email !== "" && inputEvents.phoneNumber !== "") {
return (prevState = true);
}
});
};
return (
<>
{checkLocation.pathname === "/contacts" ? (
<>
<form className="form-control" onSubmit={submitValue}>
<Box
sx={{
display: "grid",
gridTemplateColumns: { sm: "1fr 1fr 1fr" },
gap: 2,
}}
>
<ThemeProvider theme={customTheme(outerTheme)}>
<TextField color="secondary" label="Name" variant="outlined" value={inputEvents.fName} name="fName" onChange={eventHandler} />
<TextField label="Email" variant="outlined" name="email" value={inputEvents.email} onChange={eventHandler} />
<TextField label="Phone Number" variant="outlined" name="phoneNumber" value={inputEvents.phoneNumber} onChange={eventHandler} />
<TextField label="Message" multiline rows={6} variant="outlined" value={inputEvents.message} className="fullwidth" name="message" onChange={eventHandler} />
</ThemeProvider>
</Box>
<Button className="btn" variant="contained" size="large" type="submit">
Submit
</Button>
</form>
{flag ? (
<div className="show-area">
<h4>Name: {inputEvents.fName}</h4>
<h4>Email: {inputEvents.email}</h4>
<h4>Phone Number: {inputEvents.phoneNumber}</h4>
<h4>Message: {inputEvents.message}</h4>
</div>
) : null}
</>
) : (
<Grid container spacing={8} className="design-controller">
<Grid item xs={6} className="left-panel">
<img src={props.ImgUrl} alt="" />
</Grid>
<Grid item xs={6} className="right-panel">
<h1>{props.title}</h1>
<p>{props.content}</p>
</Grid>
</Grid>
)}
</>
);
}
export default Common;
|
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const getCompanies = async (req, res) => {
const companies = await prisma.company.findMany();
res.json(companies);
};
const getCompanyById = async (req, res) => {
const { id } = req.params;
const company = await prisma.company.findUnique({
where: { id: parseInt(id) },
});
res.json(company);
};
const createCompany = async (req, res) => {
const {
name, domainName, address, prefix, suffix, hrLoginUsername, hrLoginPassword,
hrEmployeeId, hrEmployeeEmail, hrEmployeeName, hrEmployeeGender, hrEmployeeMobile,
hrEmployeeExtension, hrEmployeeTitle, hrEmployeeNickName
} = req.body;
const company = await prisma.company.create({
data: {
name,
domainName,
address,
prefix,
suffix,
hrLoginUsername,
hrLoginPassword,
hrEmployeeId,
hrEmployeeEmail,
hrEmployeeName,
hrEmployeeGender,
hrEmployeeMobile,
hrEmployeeExtension,
hrEmployeeTitle,
hrEmployeeNickName,
},
});
res.json(company);
};
const updateCompany = async (req, res) => {
const { id } = req.params;
const {
name, domainName, address, prefix, suffix, hrLoginUsername, hrLoginPassword,
hrEmployeeId, hrEmployeeEmail, hrEmployeeName, hrEmployeeGender, hrEmployeeMobile,
hrEmployeeExtension, hrEmployeeTitle, hrEmployeeNickName
} = req.body;
const company = await prisma.company.update({
where: { id: parseInt(id) },
data: {
name,
domainName,
address,
prefix,
suffix,
hrLoginUsername,
hrLoginPassword,
hrEmployeeId,
hrEmployeeEmail,
hrEmployeeName,
hrEmployeeGender,
hrEmployeeMobile,
hrEmployeeExtension,
hrEmployeeTitle,
hrEmployeeNickName,
},
});
res.json(company);
};
const deleteCompany = async (req, res) => {
const { id } = req.params;
await prisma.company.delete({
where: { id: parseInt(id) },
});
res.status(204).send();
};
module.exports = {
getCompanies,
getCompanyById,
createCompany,
updateCompany,
deleteCompany,
};
|
import { IScript } from "../../models/IScript";
import { ScriptId } from "../../models/ScriptId";
import { Uri } from "vscode";
import { inject, injectable } from "inversify";
import TYPES from '../../Types';
import { IScriptChangedEventListener as IScriptChangedEventListener } from './IScriptChangedListener';
import { IScriptIdService } from '../scriptId/IScriptIdService';
import { IScriptRemoteService } from './IScriptRemoteService';
import { IConnectionEventListener } from "../connection/IConnectionEventListener";
import { IDirectory } from "../../models/IDirectory";
import { IDirectoryService } from "../directory/IDirectoryService";
import { IConnectionServiceProvider } from "../connectionServiceProvider/IConnectionServiceProvider";
import { EngineType } from "../../models/EngineType";
import { IConfigRepositoryService } from "../configRepository/IConfigRepositoryService";
@injectable()
export class ScriptRemoteService implements IScriptRemoteService, IConnectionEventListener {
private scriptEventListeners: Array<IScriptChangedEventListener> = new Array();
constructor(
@inject(TYPES.services.connectionServiceProvider) private connectionServiceProvider: IConnectionServiceProvider,
@inject(TYPES.services.scriptId) private scriptIdService: IScriptIdService,
@inject(TYPES.services.directory) private directoryService: IDirectoryService,
@inject(TYPES.services.configRepository) private configRepositoryService: IConfigRepositoryService
) { }
init(): void {
this.connectionServiceProvider.getConnectionService().registerConnectionEventListener(this);
if (this.connectionServiceProvider.getConnectionService().isConnected) {
this.registerSocketEvents();
}
}
registerScriptChangedEventListener(listener: IScriptChangedEventListener): void {
this.scriptEventListeners.push(listener);
}
downloadAllScripts(): Promise<IScript[]> {
return this.connectionServiceProvider.getConnectionService().getSystemObjectView<IScript>("script", "script.js.", "script.js.");
}
async downloadScriptWithUri(scriptUri: Uri): Promise<IScript> {
const scriptId = this.scriptIdService.getIoBrokerId(scriptUri);
return await this.downloadScriptWithId(scriptId);
}
downloadScriptWithId(scriptId: ScriptId): Promise<IScript> {
return this.connectionServiceProvider.getConnectionService().getObject<IScript>(scriptId);
}
async uploadScript(script: IScript): Promise<void> {
script.common.engineType = this.getFixedEngineTypeCasing(script.common.engineType);
if (this.configRepositoryService.config.scriptAutoRun) {
script.common.enabled = true;
}
await this.directoryService.createDirectoriesRecursively(script._id);
await this.connectionServiceProvider.getConnectionService().setObject(<string>script._id, script);
}
startScript(scriptId: ScriptId): Promise<void> {
return this.setScriptState(scriptId, true);
}
stopScript(scriptId: ScriptId): Promise<void> {
return this.setScriptState(scriptId, false);
}
async rename(scriptId: ScriptId, name: string): Promise<void> {
const splittedId = scriptId.split(".");
const sanatizedName = (name || '').replace(/[\\/\][*,;'"`<>?\s]/g, '_'); // Taken from https://github.com/ioBroker/ioBroker.javascript/blob/be43a91e002cb13f7c24aac4eebd482159bc4390/src/src/Dialogs/Rename.js#L47
splittedId.splice(-1, 1);
splittedId.push(sanatizedName);
const newId = splittedId.join(".");
const script = await this.downloadScriptWithId(scriptId);
script._id = new ScriptId(newId);
script.common.name = name;
await this.delete(scriptId);
await this.uploadScript(script);
}
async move(scriptId: ScriptId, targetDirectory: IDirectory): Promise<void> {
const script = await this.downloadScriptWithId(scriptId);
const scriptIdName = scriptId.substring(scriptId.lastIndexOf(".") + 1);
await this.delete(scriptId);
script._id = new ScriptId(`${targetDirectory._id}.${scriptIdName}`);
await this.uploadScript(script);
}
async update(scriptId: ScriptId, script: IScript): Promise<void> {
const existingScript = await this.downloadScriptWithId(scriptId);
if (existingScript) {
await this.connectionServiceProvider.getConnectionService().extendObject(scriptId, script);
} else {
throw new Error(`Could not update script '${scriptId}', because it is not known to ioBroker`);
}
}
async delete(scriptId: ScriptId): Promise<void> {
return this.connectionServiceProvider.getConnectionService().deleteObject(scriptId);
}
onConnected(): void {
this.registerSocketEvents();
}
onDisconnected(): void {
this.unregisterSocketEvents();
this.scriptEventListeners.forEach(listener => listener.onNoScriptAvailable());
}
onReAuthenticate(): void {
}
private registerSocketEvents(): void {
this.connectionServiceProvider.getConnectionService().registerForObjectChange("script.js.*", (id: string) => {
this.scriptEventListeners.forEach(listener => listener.onScriptChanged(id));
});
}
private unregisterSocketEvents(): void {
this.connectionServiceProvider.getConnectionService().unregisterObjectChange("script.js.*");
}
private async setScriptState(scriptId: ScriptId, isEnabled: boolean): Promise<void> {
const script: IScript = {
_id: scriptId,
common: {
enabled: isEnabled
}
};
this.update(scriptId, script);
}
private getFixedEngineTypeCasing(engineType: string | undefined): string {
switch (engineType?.toLowerCase()) {
case EngineType.typescript:
return "TypeScript/ts";
case EngineType.javascript:
return "JavaScript/js";
case EngineType.blockly:
return "Rules";
case EngineType.rules:
return "Blockly";
}
return "";
}
}
|
---
title: 插件描述清单 Schema
group: Schema
atomId: pluginManifestSchema
description: 插件描述文件的 Schema
nav: API
---
## pluginManifestSchema
**描述**:插件的清单文件(Manifest)数据模式定义。
### 使用示例
```typescript
import { pluginManifestSchema } from '@lobehub/chat-plugin-sdk';
const manifestData = {
api: [
{
description: 'API 描述',
name: 'API 名称',
parameters: {
properties: {},
type: 'object',
},
url: 'http://example.com/api',
},
],
gateway: 'http://example.com/gateway',
identifier: 'plugin-identifier',
openapi: 'http://example.com/openapi',
settings: {
properties: {},
type: 'object',
},
ui: {
height: 500,
mode: 'iframe',
url: 'http://example.com/plugin',
width: 800,
},
};
const result = pluginManifestSchema.parse(manifestData);
console.log(result);
// 输出:{ api: [ { description: 'API 描述', name: 'API 名称', parameters: { properties: {}, type: 'object' }, url: 'http://example.com/api' } ], gateway: 'http://example.com/gateway', identifier: 'plugin-identifier', openapi: 'http://example.com/openapi', settings: { properties: {}, type: 'object' }, ui: { height: 500, mode: 'iframe', url: 'http://example.com/plugin', width: 800 } }
```
## `pluginApiSchema`
**描述**:插件 API 的数据模式定义。
```typescript
import { z } from 'zod';
const JSONSchema = z.object({
properties: z.object({}),
type: z.enum(['object']),
});
const pluginApiSchema = z.object({
description: z.string(),
name: z.string(),
parameters: JSONSchema,
url: z.string().url(),
});
export default pluginApiSchema;
```
### 使用示例
```typescript
import { pluginApiSchema } from '@lobehub/chat-plugin-sdk';
const apiData = {
description: 'API 描述',
name: 'API 名称',
parameters: {
properties: {},
type: 'object',
},
url: 'http://example.com/api',
};
const result = pluginApiSchema.parse(apiData);
console.log(result);
// 输出:{ description: 'API 描述', name: 'API 名称', parameters: { properties: {}, type: 'object' }, url: 'http://example.com/api' }
```
## Schema 定义
### pluginManifestSchema
| 属性 | 类型 | 描述 |
| ------------ | ------------------- | ----------------------- |
| `api` | `pluginApiSchema[]` | 插件的 API 列表 |
| `gateway` | `string` (可选) | 插件的网关 URL |
| `identifier` | `string` | 插件的标识符 |
| `openapi` | `string` (可选) | 插件的 OpenAPI 文档 URL |
| `settings` | `JSONSchema` (可选) | 插件的设置数据定义 |
| `ui` | `object` (可选) | 插件的 UI 配置 |
| `ui.height` | `number` (可选) | 插件 UI 的高度 |
| `ui.mode` | `'iframe'` (可选) | 插件 UI 的模式 |
| `ui.url` | `string` | 插件 UI 的 URL |
| `ui.width` | `number` (可选) | 插件 UI 的宽度 |
### pluginApiSchema
| 属性 | 类型 | 描述 |
| ------------- | ------------ | ------------------- |
| `description` | `string` | 插件 API 的描述 |
| `name` | `string` | 插件 API 的名称 |
| `parameters` | `JSONSchema` | 插件 API 的参数定义 |
| `url` | `string` | 插件 API 的 URL |
|
<template>
<div>
<hero-bar>
Manage My Routine
</hero-bar>
<section class="section is-main-section">
<b-message v-if="formData.profile_status == 'pending'"
title="Message"
type="is-warning"
aria-close-label="Close message">
You cannot manage your Routine untill the admin will apprve your account
</b-message>
<b-message v-if="formData.profile_status == 'rejected'"
title="Warning"
type="is-danger"
aria-close-label="Close message">
Your profile is rejected by admin. You cannot manage your Routine untill the admin will apprve your account <br>
<strong>Reason : {{ formData.comment }}</strong>
</b-message>
<tiles v-if="formData.profile_status == 'approved'">
<card-component :loading="isLoading" :title="formCardTitle" icon="account-edit" class="tile is-child">
<b-field label="Select a date" horizontal>
<b-datepicker
v-model="selected"
:show-week-number="showWeekNumber"
:locale="locale"
placeholder="Click to select..."
icon="calendar-today"
:icon-right="selected ? 'close-circle' : ''"
icon-right-clickable
@icon-right-click="clearDate"
trap-focus>
</b-datepicker>
</b-field>
<b-field label="Select Start time" horizontal>
<b-timepicker v-model="startTime"
placeholder="Click to select...">
</b-timepicker>
</b-field>
<b-field label="Select End time" horizontal>
<b-timepicker v-model="endTime"
placeholder="Click to select...">
</b-timepicker>
</b-field>
<div style="display: flex;justify-content: flex-end;">
<b-button :loading="isLoading" type="is-success" @click="submitForm()">Save Date & Time</b-button>
</div>
</card-component>
</tiles>
<tiles v-if="formData.profile_status == 'approved'">
<card-component class="has-table has-mobile-sort-spaced" title="Time Table" icon="account-multiple">
<card-toolbar>
<button slot="right" type="button" class="button is-danger is-small has-checked-rows-number" @click="trashModal(null)" :disabled="!checkedRows.length">
<b-icon icon="trash-can" custom-size="default"/>
<span>Delete</span>
<span v-show="!!checkedRows.length">({{ checkedRows.length }})</span>
</button>
</card-toolbar>
<modal-box
:is-active="isModalActive"
:trash-object-name="trashSubject"
@confirm="trashConfirm"
@cancel="trashCancel"
/>
<b-table
:checked-rows.sync="checkedRows"
:checkable="true"
:loading="isLoading"
:paginated="paginated"
:per-page="perPage"
:striped="true"
:hoverable="true"
default-sort="name"
:data="timeSlots">
<b-table-column label="Name" field="name" sortable v-slot="props">
{{ props.row.available_date }}
</b-table-column>
<b-table-column label="Start Time" field="start_time" sortable v-slot="props">
{{ props.row.start_time }}
</b-table-column>
<b-table-column label="End Time" field="end_time" sortable v-slot="props">
{{ props.row.end_time }}
</b-table-column>
<b-table-column label="Created" v-slot="props">
<small class="has-text-grey is-abbr-like" title="created">{{ formatDate(props.row.created_at) }}</small>
</b-table-column>
<b-table-column custom-key="actions" class="is-actions-cell" v-slot="props">
<div class="buttons is-right">
<router-link :to="{name:'rejected.view', params: {id: props.row.id}}" class="button is-small is-primary">
<b-icon icon="account-edit" size="is-small"/>
</router-link>
<button class="button is-small is-danger" type="button" @click.prevent="trashModal(props.row)">
<b-icon icon="trash-can" size="is-small"/>
</button>
</div>
</b-table-column>
<section class="section" slot="empty">
<div class="content has-text-grey has-text-centered">
<template v-if="isLoading">
<p>
<b-icon icon="dots-horizontal" size="is-large"/>
</p>
<p>Fetching data...</p>
</template>
<template v-else>
<p>
<b-icon icon="emoticon-sad" size="is-large"/>
</p>
<p>Nothing's here…</p>
</template>
</div>
</section>
</b-table>
</card-component>
</tiles>
</section>
</div>
</template>
<script>
import { mapState } from 'vuex'
import map from 'lodash/map'
import TitleBar from '@/components/TitleBar'
import CardComponent from '@/components/CardComponent'
import HeroBar from '@/components/HeroBar'
import Tiles from '@/components/Tiles'
import CardToolbar from '@/components/CardToolbar'
import ModalBox from '@/components/ModalBox'
export default {
name:'Routine',
components: {TitleBar,CardComponent,HeroBar,Tiles,CardToolbar,ModalBox},
computed:{
...mapState(['userId']),
trashSubject () {
if (this.trashObject) {
return this.trashObject.name
}
if (this.checkedRows.length) {
return `${this.checkedRows.length} entries`
}
return null
}
},
data () {
return {
isLoading:false,
formCardTitle:"Create or update your Daily Routine",
formData:{
doctor_id:'',
profile_status:false,
},
selected: new Date(),
showWeekNumber: false,
locale: undefined, // Browser locale
startTime:new Date(),
endTime:new Date(),
paginated: false,
perPage: 10,
checkedRows: [],
isModalActive: false,
trashObject: null,
Doctortypes:[],
timeSlots:[],
isprofileImageUpdate:false,
isMedicalProfileUpdate:false,
invalidFileds:{
doctor_id:'',
}
}
},
methods: {
clearDate () {
this.selected = null
},
formatDate: function (dateTime){
var date = new Date(dateTime)
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const joined = [year, month,day ].join('-');
return joined;
},
formatTime: function (dateTime){
const dateObject = new Date(dateTime);
const hours = String(dateObject.getHours()).padStart(2, '0');
const minutes = String(dateObject.getMinutes()).padStart(2, '0');
// const seconds = String(dateObject.getSeconds()).padStart(2, '0');
const joined = [hours, minutes ].join(':');
return joined;
},
getTimeTable(){
this.isLoading = true
axios
.post('/doctor/getTimeTable',{doctor_id: this.userId })
.then(r => {
this.isLoading = false
if (r.data) {
if (r.data.length > this.perPage) {
this.paginated = true
}
this.timeSlots = r.data
}
})
.catch( err => {
this.isLoading = false
this.$buefy.toast.open({
message: `Error: ${err.message}`,
type: 'is-danger',
queue: false
})
})
},
getData () {
this.isLoading = true
axios
.post('/doctor/getProfileData',{doctor_id: this.userId })
.then(r => {
this.isLoading = false
this.formData.doctor_id = r.data.data[0].doctor_id
this.formData.profile_status = r.data.data[0].status
})
.catch( err => {
this.isLoading = false
this.$buefy.toast.open({
message: `Error: ${err.message}`,
type: 'is-danger',
queue: false
})
})
},
resetInvalidStatus: function(key){
this.invalidFileds[key] = ''
},
submitForm(){
if(this.formatTime(this.startTime) == this.formatTime(this.endTime)){
this.$buefy.toast.open({
message: 'Start Time and End Time cannot be same',
type: 'is-danger',
queue: false
})
}else{
this.isLoading = true
var formData = new FormData();
formData.append('doctor_id', this.userId);
formData.append('date', this.formatDate(this.selected));
formData.append('start_time', this.formatTime(this.startTime));
formData.append('end_time', this.formatTime(this.endTime));
axios
.post('/doctor/storeDateAndTime',formData)
.then(r => {
this.isLoading = false
if(r.data.success == true){
this.getTimeTable();
this.$buefy.toast.open({
message: r.data.message,
type: 'is-success',
queue: false
})
}else{
this.$buefy.toast.open({
message: r.data.message,
type: 'is-danger',
queue: false
})
}
})
.catch( err => {
this.isLoading = false
this.$buefy.toast.open({
message: `Error: ${err.message}`,
type: 'is-danger',
queue: false
})
})
}
},
trashModal (trashObject = null) {
if (trashObject || this.checkedRows.length) {
this.trashObject = trashObject
this.isModalActive = true
}
},
trashConfirm () {
let url
let method
let data = null
this.isModalActive = false
if (this.trashObject) {
method = 'delete'
url = `/clients/${this.trashObject.id}/destroy`
} else if (this.checkedRows.length) {
method = 'post'
url = '/clients/destroy'
data = {
ids: map(this.checkedRows, row => row.id)
}
}
axios({
method,
url,
data
}).then( r => {
this.getData()
this.trashObject = null
this.checkedRows = []
this.$buefy.snackbar.open({
message: `Deleted`,
queue: false
})
}).catch( err => {
this.$buefy.toast.open({
message: `Error: ${err.message}`,
type: 'is-danger',
queue: false
})
})
},
trashCancel () {
this.isModalActive = false
}
},
mounted (){
this.getData()
this.getTimeTable()
}
}
</script>
<style scoped>
.flex-container{
justify-content: flex-end;
}
</style>
|
import CardGroup from "react-bootstrap/CardGroup";
import ProgressBar from "react-bootstrap/ProgressBar";
import OrderCard from "./OrderCard";
import React from "react";
import { returnOrderTime } from "../../api/OrderApi";
// Current order card component in orders page
function CurrentOrder({ index, element, menu }) {
const center = {
display: "flex",
justifyContent: "center",
};
const [orderTime, setOrderTime] = React.useState(0);
const [estimateTime, setEstimateTime] = React.useState(0);
// Obtains estimated time of order and calculates remaining time using current time.
React.useEffect(() => {
returnOrderTime(element.id).then((data) => {
let tempTime = Math.ceil(
element.time_ordered / 60000 + data / 60 - Date.now() / 60000
);
if (tempTime < 0 || isNaN(data)) {
tempTime = 0;
}
setOrderTime(tempTime);
setEstimateTime(data / 60);
});
}, [element]);
// Creates an interval which updates the estimated time every minute
React.useEffect(() => {
const timer = setInterval(() => changeTime(), 60000);
return () => clearInterval(timer);
}, []);
// Updates the estimated time to decrease by 1 minute
function changeTime() {
setOrderTime((s) => (s === 0 ? 0 : s - 1));
}
return (
<>
<div
style={{
width: "100%",
paddingBottom: "30px",
backgroundColor: "white",
marginBottom: "30px",
borderBottom: "1px solid #e5e5e5",
borderTop: "1px solid #e5e5e5",
}}
>
<div style={{ ...center, marginTop: "20px" }}>
<p style={{ fontSize: "20px", fontWeight: "500" }}>
Order {index + 1}
</p>
</div>
<div style={{ ...center, marginBottom: "20px" }}>
<div style={{ ...center, width: "30%", flexDirection: "column" }}>
<div style={{ ...center }}>Estimated Time:</div>
<div style={{ ...center, fontSize: "70px" }}>
{orderTime} {orderTime === 1 ? "minute" : "minutes"}
</div>
</div>
</div>
<div style={center}>
<div style={{ display: "inline-block", width: "30%" }}>
<div style={center}>
<p>Cooking</p>
</div>
<CardGroup
style={{ marginBottom: "16px", justifyContent: "center" }}
>
{element.food_ordered.map((food, index) => (
<OrderCard key={index} menu={menu} food={food} />
))}
</CardGroup>
</div>
<div style={{ ...center, display: "inline-block", width: "30%" }}>
<div style={center}>
<p>To be delivered</p>{" "}
</div>
<CardGroup
style={{ marginBottom: "16px", justifyContent: "center" }}
>
{element.food_prepared.map((food, index) => (
<OrderCard key={index} menu={menu} food={food} />
))}
</CardGroup>
</div>
<div style={{ ...center, display: "inline-block", width: "30%" }}>
<div style={center}>
<p>Delivered</p>{" "}
</div>
<CardGroup
style={{ marginBottom: "16px", justifyContent: "center" }}
>
{element.food_delivered.map((food, index) => (
<OrderCard key={index} menu={menu} food={food} />
))}
</CardGroup>
</div>
</div>
<div style={{ ...center, paddingTop: "20px" }}>
<ProgressBar
animated={orderTime !== 0}
now={
estimateTime === 0
? 0
: ((estimateTime - orderTime) / estimateTime) * 100
}
style={{ width: "90%", backgroundColor: "#edeff3" }}
/>
</div>
</div>
</>
);
}
export default CurrentOrder;
|
from project.computer_types.desktop_computer import DesktopComputer
from project.computer_types.laptop import Laptop
def return_obj(computer_type):
if computer_type == "Desktop Computer":
return DesktopComputer
elif computer_type == "Laptop":
return Laptop
else:
return None
class ComputerStoreApp:
def __init__(self):
self.warehouse = []
self.profits = 0
def build_computer(self, type_computer: str, manufacturer: str, model: str, processor: str, ram: int):
get_computer = return_obj(type_computer)
if get_computer:
computer = get_computer(manufacturer, model)
self.warehouse.append(computer)
return computer.configure_computer(processor, ram)
else:
raise ValueError(f"{type_computer} is not a valid type computer!")
def sell_computer(self, client_budget: int, wanted_processor: str, wanted_ram: int):
for computer in self.warehouse:
if computer.price <= client_budget and computer.processor == wanted_processor and computer.ram >= wanted_ram:
self.profits += client_budget - computer.price
self.warehouse.remove(computer)
return f"{computer} sold for {client_budget}$."
else:
raise Exception(f"Sorry, we don't have a computer for you.")
|
//
// File.swift
//
//
// Created by Jia Chen Yee on 09/06/23.
//
import SwiftUI
import CoreLocation
@available(iOS 16.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public enum Framework {
case healthKit
case speech
case machineLearning
case vision
case watch
case multipeerConnectivity
case shareplay
case coreHaptics
case siriKit
case messages
case coreLocation
case liveActivities
case pencilKit
case coreMotion
case gameKit
case swiftUIAnimations
case augmentedReality
case spriteKit
public var name: String {
switch self {
case .healthKit:
return "HealthKit"
case .speech:
return "Speech"
case .machineLearning:
return "Machine Learning"
case .vision:
return "Vision"
case .watch:
return "Apple Watch"
case .multipeerConnectivity:
return "Multipeer Connectivity"
case .shareplay:
return "SharePlay"
case .coreHaptics:
return "CoreHaptics"
case .siriKit:
return "SiriKit"
case .messages:
return "Messages"
case .coreLocation:
return "CoreLocation"
case .liveActivities:
return "Live Activities"
case .pencilKit:
return "PencilKit"
case .coreMotion:
return "CoreMotion"
case .gameKit:
return "GameKit"
case .swiftUIAnimations:
return "SwiftUI Animations"
case .augmentedReality:
return "Augmented Reality"
case .spriteKit:
return "SpriteKit"
}
}
public var subtitle: String {
switch self {
case .healthKit:
return "Integrate with the Health App"
case .speech:
return "Perform speech recognition on audio"
case .machineLearning:
return "Create intelligent features by leveraging on-device machine learning"
case .vision:
return "Apply computer vision algorithms on images and videos"
case .watch:
return "Implement communication between an iOS app a watchOS app"
case .multipeerConnectivity:
return "Support connectivity and the discovery of nearby devices"
case .shareplay:
return "Create activities your users can share and experience together"
case .coreHaptics:
return "Compose and play haptic patterns to customize your iOS app’s haptic feedback"
case .siriKit:
return "Allow users to interact with their devices through voice, intelligent suggestions, and personalized workflows"
case .messages:
return "Create apps that allow users to send text, stickers, media files, and interactive messages"
case .coreLocation:
return "Obtain the geographic location and orientation of a device"
case .liveActivities:
return "Extend the reach of your app by creating widgets, watch complications, and Live Activities"
case .pencilKit:
return "Capture touch and Apple Pencil input as a drawing, and display that content from your app"
case .coreMotion:
return "Process accelerometer, gyroscope, pedometer, and environment-related events"
case .gameKit:
return "Enable players to interact with friends, compare leaderboard ranks, earn achievements, and participate in multiplayer games"
case .swiftUIAnimations:
return "Build stunning animations that bring your app to life in SwiftUI."
case .augmentedReality:
return "Integrate hardware sensing features to produce augmented reality apps and games."
case .spriteKit:
return "Add high-performance 2D content with smooth animations to your app, or create a game with a high-level set of 2D game-based tools."
}
}
public var icon: String {
switch self {
case .healthKit:
return "heart.text.square"
case .speech:
return "waveform"
case .machineLearning:
return "brain.head.profile"
case .vision:
return "eye"
case .watch:
return "applewatch"
case .multipeerConnectivity:
return "antenna.radiowaves.left.and.right"
case .shareplay:
return "shareplay"
case .coreHaptics:
return "iphone.gen3.radiowaves.left.and.right"
case .siriKit:
return "mic"
case .messages:
return "message"
case .coreLocation:
return "location"
case .liveActivities:
return "platter.filled.top.iphone"
case .pencilKit:
return "scribble.variable"
case .coreMotion:
return "move.3d"
case .gameKit:
return "gamecontroller"
case .swiftUIAnimations:
return "figure.walk.motion"
case .augmentedReality:
return "arkit"
case .spriteKit:
return "square.on.circle"
}
}
public var color: Color {
switch self {
case .healthKit:
return .red
case .speech:
return .yellow
case .machineLearning:
return .teal
case .vision:
return .blue
case .watch:
return .teal
case .multipeerConnectivity:
return .mint
case .shareplay:
return .green
case .coreHaptics:
return .mint
case .siriKit:
return .purple
case .messages:
return .green
case .coreLocation:
return .blue
case .liveActivities:
return .pink
case .pencilKit:
return .orange
case .coreMotion:
return .green
case .gameKit:
return .purple
case .swiftUIAnimations:
return .blue
case .augmentedReality:
return .orange
case .spriteKit:
return .orange
}
}
public var description: String {
switch self {
case .healthKit:
return "HealthKit provides a central repository for health and fitness data on iPhone and Apple Watch. With the user’s permission, apps can access and share the user's health data allowing them to create personalized health and fitness experiences.\n\nHealthKit apps take a collaborative approach to building this experience. Your app doesn’t need to provide all of these features. Instead, you can focus just on the subset of tasks that most interests you."
case .speech:
return "The Speech framework recognizes spoken words in recorded or live audio. The iOS keyboard’s dictation functionality uses this framework to translate audio content into text.\n\nYou may use speech recognition to recognize verbal commands or to handle text dictation in other parts of your app."
case .machineLearning:
return "Core ML applies a provided machine learning algorithm to a set of training data to create a model. Model can be used to make predictions based on new input data.\n\nModels can accomplish a wide variety of tasks that would be difficult or impractical to write in code. For example, you can train a model to categorize photos, or detect specific objects within a photo directly from its pixels, or even create AI-generated images on iPhone."
case .vision:
return "The Vision framework performs face detection, text detection, barcode recognition, image registration, and general feature tracking.\n\nVision also allows the use of custom machine learning models for tasks like classification or object detection."
case .watch:
return "Transfer data between your iOS app and a watchOS app. You can pass small amounts of data or entire files. You also use this framework to trigger an update to your watchOS app's complication."
case .multipeerConnectivity:
return "The Multipeer Connectivity framework allows nearby devices to communicate with one another. This allows you to share message-based data, streaming data, and resources (such as files) between devices.\n\nThe framework uses infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks for the underlying transport."
case .shareplay:
return "SharePlay lets people share experiences while connecting in a FaceTime call or a Messages conversation. With this framework, you can bring movies, TV, music, games, workouts, and other shared activities from your app into a space where people are already connecting with each other."
case .coreHaptics:
return "Core Haptics lets you add customized haptic and audio feedback to your app. Use haptics to engage users physically, with tactile and audio feedback that gets attention and reinforces actions.\n\nSome system-provided interface elements—like pickers, switches, and sliders—automatically provide haptic feedback as users interact with them."
case .siriKit:
return "This framework drives interactions that start with “Hey Siri…” and Shortcuts actions. This allows you to extend the functionality of Siri and Shortcuts by integrating your app into it."
case .messages:
return "The Messages framework allows you to create sticker packs and iMessage apps.\n\nSticker packs provide static sets of stickers, images that users can send inline as messages or peel off and attach to message bubbles in the transcript. Sticker packs don’t require any code.\n\niMessage apps allow you to create custom user interfaces within iMessage and send text, stickers, media files, or custom interactive messages."
case .coreLocation:
return "Core Location provides services that determine a device’s geographic location, altitude, and orientation, or its position relative to a nearby iBeacon device.\n\nThe framework gathers data using all available components on the device, including the Wi-Fi, GPS, Bluetooth, magnetometer, barometer, and cellular hardware."
case .liveActivities:
return "Using WidgetKit, you can make your app’s content available in contexts outside the app and extend its reach by building an ecosystem of glanceable, up-to-date experiences through widgets, watch complications, and live activities."
case .pencilKit:
return "PencilKit makes it easy to incorporate hand-drawn content into your apps. PencilKit provides a canvas for uesrs to draw with an Apple Pencil or their finger. The environment comes with tools for creating, erasing, and selecting lines. You can even inspect, edit, and export PencilKit drawings."
case .coreMotion:
return "Core Motion reports motion- and environment-related data from the onboard hardware, including from the accelerometers and gyroscopes, and from the pedometer, magnetometer, and barometer.\n\nYou use this framework to access hardware-generated data so that you can use it in your app. For example, a game might use accelerometer and gyroscope data to control onscreen game behavior."
case .gameKit:
return "GameKit allows you to implement Game Center social-gaming network features. Game Center is an Apple service that provides a single account that identifies players across all their games and devices. After players sign in to Game Center on their device, they can access their friends and use Game Center features you implement."
case .swiftUIAnimations:
return "You tell SwiftUI how to draw your app’s user interface for different states, and then rely on SwiftUI to make interface updates when the state changes."
case .augmentedReality:
return "Augmented reality (AR) describes user experiences that add 2D or 3D elements to the live view from a device’s sensors in a way that makes those elements appear to inhabit the real world. ARKit/RealityKit combines device motion tracking, world tracking, scene understanding, and display conveniences to simplify building an AR experience."
case .spriteKit:
return "SpriteKit is a general-purpose framework for drawing shapes, particles, text, images, and video in two dimensions. It leverages Metal to achieve high-performance rendering, while offering a simple programming interface to make it easy to create games and other graphics-intensive apps. Using a rich set of animations and physics behaviors, you can quickly add life to your visual elements and gracefully transition between screens."
}
}
static let all: [Self] = [
.healthKit,
.speech,
.machineLearning,
.vision,
.watch,
.multipeerConnectivity,
.shareplay,
.coreHaptics,
.siriKit,
.messages,
.coreLocation,
.liveActivities,
.pencilKit,
.coreMotion,
.gameKit,
.swiftUIAnimations,
.augmentedReality,
.spriteKit
]
// Index used for iBeacon
var index: UInt16 {
UInt16(Self.all.firstIndex(of: self)!)
}
}
|
// Copyright 2023 The Perses Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { VariableDefinition } from '@perses-dev/core';
import { ExternalVariableDefinition } from '@perses-dev/dashboards';
import { VariableStoreStateMap } from '@perses-dev/plugin-system';
import { checkSavedDefaultVariableStatus, mergeVariableDefinitions } from './utils';
describe('checkSavedDefaultVariableStatus', () => {
it('should check whether saved variable definitions are out of date with current default values state', () => {
const savedVariables: VariableDefinition[] = [
{
kind: 'ListVariable',
spec: {
name: 'interval',
defaultValue: '1m',
allowAllValue: false,
allowMultiple: false,
plugin: {
kind: 'StaticListVariable',
spec: {
values: ['1m', '5m'],
},
},
},
},
{
kind: 'ListVariable',
spec: {
name: 'NewListVariable',
display: {
name: 'Test display label',
hidden: false,
},
defaultValue: 'second list value',
allowAllValue: true,
allowMultiple: false,
plugin: {
kind: 'StaticListVariable',
spec: {
values: [
{
label: 'test list value',
value: 'test list value',
},
{
label: 'second list value',
value: 'second list value',
},
{
label: 'another list value',
value: 'another list value',
},
],
},
},
},
},
{
kind: 'TextVariable',
spec: {
name: 'NewTextVariable',
display: {
name: 'Text display',
hidden: false,
},
constant: true,
value: 'first text value',
},
},
];
const variableState = new VariableStoreStateMap();
variableState.set(
{ name: 'interval' },
{
value: '5m',
loading: false,
options: [
{
label: '1m',
value: '1m',
},
{
label: '5m',
value: '5m',
},
],
}
);
variableState.set(
{ name: 'NewListVariable' },
{
value: 'last list value',
loading: false,
options: [
{
label: 'test list value',
value: 'test list value',
},
{
label: 'second list value',
value: 'second list value',
},
{
label: 'last list value',
value: 'last list value',
},
],
defaultValue: 'test list value',
}
);
variableState.set(
{ name: 'NewTextVariable' },
{
value: 'New text value',
loading: false,
}
);
const { isSavedVariableModified } = checkSavedDefaultVariableStatus(savedVariables, variableState);
expect(isSavedVariableModified).toBe(true);
});
it('should confirm list variable default value was not modified', () => {
const savedVariables: VariableDefinition[] = [
{
kind: 'ListVariable',
spec: {
name: 'interval',
defaultValue: '5m',
allowAllValue: false,
allowMultiple: false,
plugin: {
kind: 'StaticListVariable',
spec: {
values: ['1m', '5m'],
},
},
},
},
];
const variableState = new VariableStoreStateMap();
variableState.set(
{ name: 'interval' },
{
value: '5m',
defaultValue: '5m',
loading: false,
options: [
{
label: '1m',
value: '1m',
},
{
label: '5m',
value: '5m',
},
],
}
);
const { isSavedVariableModified } = checkSavedDefaultVariableStatus(savedVariables, variableState);
expect(isSavedVariableModified).toBe(false);
});
it('should confirm null list variable was not modified', () => {
const savedVariables: VariableDefinition[] = [
{
kind: 'ListVariable',
spec: {
allowAllValue: false,
allowMultiple: false,
plugin: {
kind: 'StaticListVariable',
spec: {
values: [],
},
},
name: 'EmptyListVariableTest',
},
},
];
const variableState = new VariableStoreStateMap();
variableState.set(
{ name: 'EmptyListVariableTest' },
{
value: null,
loading: false,
options: [],
}
);
const { isSavedVariableModified } = checkSavedDefaultVariableStatus(savedVariables, variableState);
expect(isSavedVariableModified).toBe(false);
});
it('should confirm text variable value was not modified', () => {
const savedVariables: VariableDefinition[] = [
{
kind: 'TextVariable',
spec: {
name: 'NewTextVariable',
display: {
name: 'Text display',
hidden: false,
},
constant: true,
value: 'first text value',
},
},
];
const variableState = new VariableStoreStateMap();
variableState.set(
{ name: 'NewTextVariable' },
{
value: 'first text value',
loading: false,
}
);
const { isSavedVariableModified } = checkSavedDefaultVariableStatus(savedVariables, variableState);
expect(isSavedVariableModified).toBe(false);
});
it('should confirm text variable value was modified', () => {
const savedVariables: VariableDefinition[] = [
{
kind: 'TextVariable',
spec: {
name: 'NewTextVariable',
value: 'Lorem ipsum',
},
},
];
const variableState = new VariableStoreStateMap();
variableState.set(
{ name: 'NewTextVariable' },
{
value: 'updated text value',
loading: false,
}
);
const { isSavedVariableModified } = checkSavedDefaultVariableStatus(savedVariables, variableState);
expect(isSavedVariableModified).toBe(true);
});
it('should merge variable definitions giving priority on local over externals', () => {
const localVariables: VariableDefinition[] = [
{
kind: 'TextVariable',
spec: {
name: 'NewTextVariable',
value: 'Lorem ipsum',
},
},
];
const externalVariables: ExternalVariableDefinition[] = [
{
source: 'project',
definitions: [
{
kind: 'TextVariable',
spec: {
name: 'project_greetings',
display: {
name: 'Greetings(project)',
},
constant: false,
value: 'hello',
},
},
{
kind: 'TextVariable',
spec: {
name: 'overridden',
value: 'project scope value',
},
},
],
},
{
source: 'global',
definitions: [
{
kind: 'TextVariable',
spec: {
name: 'global_greetings',
display: {
name: 'Greetings(global)',
},
constant: true,
value: 'hello',
},
},
{
kind: 'TextVariable',
spec: {
name: 'overridden',
value: 'global scope value',
},
},
],
},
];
const expected = [
{
kind: 'TextVariable',
spec: {
name: 'NewTextVariable',
value: 'Lorem ipsum',
},
},
{
kind: 'TextVariable',
spec: {
name: 'project_greetings',
display: {
name: 'Greetings(project)',
},
constant: false,
value: 'hello',
},
},
{
kind: 'TextVariable',
spec: {
name: 'overridden',
value: 'project scope value',
},
},
{
kind: 'TextVariable',
spec: {
name: 'global_greetings',
display: {
name: 'Greetings(global)',
},
constant: true,
value: 'hello',
},
},
];
expect(mergeVariableDefinitions(localVariables, externalVariables)).toEqual(expected);
});
});
|
import React, { useState, useContext, useEffect } from 'react'
import { signInWithEmailAndPassword } from "firebase/auth";
import { auth } from "../api/api";
import { useNavigate } from "react-router-dom"
import logo from '../logo.png';
import "../assets/scss/_files/_login.scss";
import { GiEnvelope,GiKeyLock } from "react-icons/gi";
import {AuthContext} from "../contexts/authContext";
const Login = () => {
const [error, setError] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const navitage = useNavigate();
const {dispatch,currentUser} = useContext(AuthContext)
const handleLogin = (e) => {
e.preventDefault();
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = {
"uid":userCredential.user.uid,
"email":userCredential.user.email,
"phoneNumber":userCredential.user.phoneNumber,
"photoURL":userCredential.user.photoURL,
"displayName":userCredential.user.displayName,
}
dispatch({type:"LOGIN", payload:user})
navitage("/admin")
})
.catch((error) => {
setError(true);
});
};
useEffect(() => {
if(currentUser){
navitage("/admin")
}
}, [])
return (
<div className='login'>
<form onSubmit={handleLogin}>
<div className='img'>
<img src={logo}/>
<h2>MWANA PWO</h2>
<h3>Faça o Login 🧑🏿💻</h3>
</div>
<label>E-mail</label>
<div className='inputs'>
<GiEnvelope size={30} color="#bc7e29"/>
<input
type="email"
placeholder="Insira o E-mail"
onChange={(e) => setEmail(e.target.value)}/>
</div>
<label>Senha</label>
<div className='inputs'>
<GiKeyLock size={30} color="#bc7e29"/>
<input
type="password"
placeholder="************"
onChange={(e) => setPassword(e.target.value)}/>
</div>
<button type='submit'>Entrar</button>
{error && <span>Wrong email or password!</span>}
</form>
</div>
)
}
export default Login
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./js/three.js"></script>
<title>three-js动画2</title>
<style>
body {
margin: 0;
overflow: hidden;
/* 隐藏body窗口区域滚动条 */
}
</style>
</head>
<body>
<script>
/**
* 创建场景对象
* @type {Scene}
*/
let scene = new THREE.Scene();
/**
* 创建网格模型
* @type {BoxGeometry}
*/
let geometry = new THREE.BoxGeometry(100, 100, 100); //立方体
let geometry2 = new THREE.BoxGeometry(50, 50, 300); //立方体
let meterial = new THREE.MeshLambertMaterial({color: 0x0000ff}); //材质
let mesh = new THREE.Mesh(geometry, meterial);//网格对象
let mesh2 = new THREE.Mesh(geometry2, meterial);//网格对象
scene.add(mesh); //将网格对象添加到场景中
scene.add(mesh2); //将网格对象添加到场景中
/**
* 光源
*/
let point = new THREE.PointLight(0xffffff);
point.position.set(400, 200, 200); //设置点光源位置
scene.add(point); //将光源添加到场景中
let ambient = new THREE.AmbientLight(0x444444); //环境光
scene.add(ambient);
/**
*
*相机设置
*/
let width = window.innerWidth;
let height = window.innerHeight;
let k = width / height;
let s = 200; //三维场景显示范围控制系数,系数越大,显示的范围越大
let camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
camera.position.set(200, 300, 200); // 设置相机位置
camera.lookAt(scene.position); //设置相机方向 (指向的场景对象)
/**
* 创建渲染器对象
*/
let render = new THREE.WebGLRenderer();
render.setSize(width, height); // 设置渲染区域尺寸
render.setClearColor(0xb9d3ff, 1); // 设置背景颜色
/**
* 将canva对象插入到body中
*/
document.body.appendChild(render.domElement);
/**
* 执行渲染操作 执行场景,相机作为参数
*/
render.render(scene, camera);
function renderByTime() {
requestAnimationFrame(renderByTime); //动画
render.render(scene, camera);
mesh.rotateX(0.02); //每次绕y轴旋转0.01弧度
mesh.rotateY(0.02); //每次绕y轴旋转0.01弧度
mesh.rotateZ(0.02); //每次绕y轴旋转0.01弧度
mesh2.rotateZ(0.02); //每次绕Z轴旋转0.01弧度
}
renderByTime();
</script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="ko">
<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">
<link rel="stylesheet" href="">
<title></title>
<style>
</style>
</head>
<body>
<h1>JS parameter and argument</h1>
<ul>
<li>parameter : 함수나 메서드가 외부에서 데이터를 받아 내부에서 사용할 매개변수</li>
<li>argument : 외부에서 함수나 메서드에게 전달하려는 데이터들</li>
</ul>
<script>
// optinal parameter
// 반드시 일반 파라미터 뒤에 있어야 함!
function myFunc(a, b = 100) {
return a * b;
}
console.log(myFunc(2));
// arguments keyword
// 내부에서 사용할 파라미터를 배열객체처럼 활용가능한 통합 키워드
function myFunc2() {
return `${arguments.length}개의 파라미터 곱은 ${arguments[0] * arguments[1]}이다`;
}
console.log(myFunc2(2, 5));
// rest parameter
// ...others에서 ...은 필수이고, others는 사용자설정이다.
function myFunc3(a, b, ...others) {
console.log(`첫 파라미터: ${a}`);
console.log(`두 번째 파라미터: ${b}`);
console.log(`나머지는: ${others}`);
for (let arg of others) {
console.log(`나머지 중 하나: ${arg}`);
}
}
console.log(myFunc3("a", "b", "c", "d", "e"));
</script>
</body>
</html>
|
#include "GameManager.h"
#include "StageScene.h"
#include "TitleScene.h"
#include "ClearScene.h"
#include "WindowSIze.h"
#include <Novice.h>
#include <Windows.h>
GameManager::GameManager() {
// 各シーンの配列
sceneArr_[TITLE] = std::make_unique<TitleScene>();
sceneArr_[STAGE] = std::make_unique<StageScene>();
sceneArr_[CLEAR] = std::make_unique<ClearScene>();
currentSceneNo_ = TITLE;
}
int GameManager::Run() {
const char kWindowTitle[] = "LE2B_02_イノウエ_ハヤト_PG3_03_01";
// ライブラリの初期化
Novice::Initialize(kWindowTitle, kWindowWidth, kWindowHeight);
inputManager_ = InputManager::GetInstance();
sceneArr_[currentSceneNo_]->Init();
while (Novice::ProcessMessage() == 0) {
Novice::BeginFrame(); // フレームの開始
inputManager_->Update();
// シーンのチェック
prevSceneNo_ = currentSceneNo_;
currentSceneNo_ = sceneArr_[currentSceneNo_]->GetSceneNo();
// シーン変更チェック
if (prevSceneNo_ != currentSceneNo_) {
sceneArr_[currentSceneNo_]->Init();
}
/// 更新処理
sceneArr_[currentSceneNo_]->Update();
/// 描画処理
sceneArr_[currentSceneNo_]->Draw();
Novice::EndFrame(); // フレームの終了
if (inputManager_->ReleaseKey(DIK_ESCAPE)) {
break;
}
}
// ライブラリの終了
Novice::Finalize();
return 0;
}
|
import 'package:flutter/material.dart';
class ExplicitAnimationScreen extends StatefulWidget {
const ExplicitAnimationScreen({super.key});
@override
State<ExplicitAnimationScreen> createState() =>
_ExplicitAnimationScreenState();
}
class _ExplicitAnimationScreenState extends State<ExplicitAnimationScreen>
with SingleTickerProviderStateMixin {
late final Animation<Decoration> _decoration = DecorationTween(
begin: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(
30,
),
),
end: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(100),
),
).animate(_curve);
late final Animation<double> _rotation = Tween(
begin: 0.0,
end: 0.5,
).animate(_curve);
late final Animation<double> _size = Tween(
begin: 1.0,
end: 0.5,
).animate(_curve);
late final Animation<Offset> _slide = Tween(
begin: Offset.zero,
end: const Offset(-0.1, 0),
).animate(_curve);
late final CurvedAnimation _curve = CurvedAnimation(
parent: _animationController,
curve: Curves.elasticOut,
reverseCurve: Curves.easeOut,
);
late final AnimationController _animationController = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
reverseDuration: const Duration(seconds: 1),
);
void _play() {
_animationController.forward();
}
void _pause() {
_animationController.stop();
}
void _rewind() {
_animationController.reverse();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Explicit Animation'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SlideTransition(
position: _slide,
child: ScaleTransition(
scale: _size,
child: RotationTransition(
turns: _rotation,
child: DecoratedBoxTransition(
decoration: _decoration,
child: SizedBox(
height: MediaQuery.of(context).size.width * 0.8,
width: MediaQuery.of(context).size.width * 0.8,
),
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _play,
child: const Text('play'),
),
ElevatedButton(
onPressed: _pause,
child: const Text('pause'),
),
ElevatedButton(
onPressed: _rewind,
child: const Text('rewind'),
),
],
)
],
),
),
);
}
}
|
'use client'
import React, { createContext, useContext, useState } from 'react'
// Create the context
const AuthContext = createContext()
// Custom hook to use the auth context
export const useAuth = () => useContext(AuthContext)
// AuthProvider component
export const AuthProvider = ({ children }) => {
const [authUser, setAuthUser] = useState(null)
const login = (userData) => {
// Logic to set the authenticated user
setAuthUser(userData)
sessionStorage.setItem('user', userData)
}
const logout = () => {
// Logic to clear the authenticated user
setAuthUser(null)
}
return (
<AuthContext.Provider value={{ authUser, login, logout }}>
{children}
</AuthContext.Provider>
)
}
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty } from 'class-validator';
import { IResource, Permission } from '@fdgn/share-ecm';
export class CreateResourceDTO implements Partial<IResource> {
@ApiProperty()
@IsNotEmpty()
name?: string;
@ApiPropertyOptional({ type: 'enum', enum: Permission })
permission?: Permission;
@ApiProperty()
roleIds?: string[];
@ApiPropertyOptional()
description?: string;
}
|
//
// ViewController.swift
// CommunityList
//
// Created by 박형환 on 2022/10/06.
//
import UIKit
import SnapKit
import RxCocoa
import RxSwift
import RxDataSources
class ViewController: UIViewController {
private var viewModel: RxViewModelType
private var disposeBag = DisposeBag()
lazy var containerTableView: UITableView = {
let tableview = UITableView(frame: .zero, style: .grouped)
tableview.allowsSelection = false
tableview.backgroundColor = .tertiarySystemBackground
tableview.separatorStyle = .none
tableview.register(TableViewCell.self, forCellReuseIdentifier: TableViewCell.identify)
tableview.register(HorizonSectionCell.self, forCellReuseIdentifier: HorizonSectionCell.identify)
return tableview
}()
private lazy var sectionHeader: TableViewHeader = {
let view = TableViewHeader(frame: .zero)
return view
}()
private lazy var footerView: NoneDataFooterView = {
let view = NoneDataFooterView()
return view
}()
enum TableViewSectionType: Int{
case collection = 0
case table = 1
case none = 2
}
var tableDataSource = RxTableViewSectionedReloadDataSource<RxDataSection>(configureCell: {
dataSource, tableView, indexPath, item in
let section = TableViewSectionType(rawValue: indexPath.section)
switch section{
case .collection:
guard let collectionViewcell = tableView.dequeueReusableCell(withIdentifier: HorizonSectionCell.identify, for: indexPath) as? HorizonSectionCell else { return UITableViewCell() }
collectionViewcell.onData.onNext(item)
return collectionViewcell
case .table:
guard let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identify, for: indexPath)
as? TableViewCell else {return UITableViewCell()}
cell.onData.onNext(item)
return cell
default:
assert(false,"error")
}
})
init(_ viewModel: RxViewModelType = RxViewModel() ){
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
settingNavigation()
configureAddContentLayout()
configureEndEditing()
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel.fetchRecommendCollectionData.onNext((.all))
viewModel.fetchTableData.onNext((.all))
self.containerTableView.rx.setDelegate(self)
.disposed(by: disposeBag)
setUpBinding()
}
func setUpBinding() {
let collection = BehaviorSubject<[RxDataSection]>(value: [])
let table = BehaviorSubject<[RxDataSection]>(value: [])
viewModel.recommendCollectionViewContents
.subscribe(onNext: collection.onNext(_:))
.disposed(by: disposeBag)
viewModel.tableViewContents
.subscribe(onNext: table.onNext(_:))
.disposed(by: disposeBag)
Observable.combineLatest(collection, table, resultSelector: { collection, table in
collection + table
}).bind(to: self.containerTableView.rx.items(dataSource: tableDataSource))
.disposed(by: disposeBag)
sectionHeader
.categorySegemts
.getObservableRequestType()
.subscribe(onNext: viewModel.fetchRecommendCollectionData.onNext(_:))
.disposed(by: disposeBag)
sectionHeader
.categorySegemts
.getObservableRequestType()
.subscribe(onNext: viewModel.fetchTableData.onNext(_:))
.disposed(by: disposeBag)
}
}
extension ViewController: UITableViewDelegate{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section{
case 0:
return UITableView.automaticDimension
case 1:
return CGFloat(250)
default:
return .leastNormalMagnitude
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
switch section{
case 0:
return sectionHeader
default:
return nil
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section{
case TableViewSectionType.collection.rawValue:
return CGFloat(187.7)
default:
return CGFloat(0)
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
switch section{
case TableViewSectionType.table.rawValue:
return footerView
default:
return nil
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
switch section {
case TableViewSectionType.table.rawValue:
return CGFloat(50)
default:
return CGFloat(0)
}
}
}
|
import { useNavigate } from "react-router-dom";
import "./Landing.scss";
import { Text } from "@gravity-ui/uikit";
const Landing = () => {
const navigate = useNavigate();
return (
<main className="landing">
<div className="landing-header">
<div className="landing-title">
<Text variant="header-1">ПрофТестиум</Text>
</div>
<Text variant="body-1" className="landing-header-text">
Платформа для обучения “синих воротничков” с использованием
VR-инструментов
</Text>
<span>
<button
className="new"
onClick={() => {
navigate("/create");
}}
>
Зарегистрировать новую школу
</button>
<button
className="price"
onClick={() => {
navigate("/pricing");
}}
>
Тарифы
</button>
</span>
</div>
<div className="opportunities">
<div className="opportunities-title">
<Text variant="header-1">Преимущества платформы</Text>
</div>
<div className="opportunities-list">
<div className="opportunities-item">
<div className="img">
<img src="/images/landing/feature-icon-1.svg" alt="" />
</div>
<Text variant="header-2">Экономия времени и ресурсов</Text>
<ul>
<li>
Сокращение времени обучения: VR-технологии позволяют более
эффективно обучать сотрудников, сокращая время, затрачиваемое на
обучение.
</li>
<li>
Масштабируемость: Создавайте порталы для разных отделов и групп
сотрудников, оптимизируя обучение.
</li>
</ul>
</div>
<div className="opportunities-item">
<div className="img">
<img src="/images/landing/feature-icon-2.svg" alt="" />
</div>
<Text variant="header-2">
Более безопасное и контролируемое обучение
</Text>
<ul>
<li>
Виртуальное обучение в безопасной среде: Позволяет сотрудникам
учиться и совершенствовать навыки без риска для здоровья и
безопасности.
</li>
<li>
Удаленное обучение: Обучайте сотрудников, не вынуждая их
покидать место работы.
</li>
<li>Обновление кластера без потери прогресса вычислений.</li>
</ul>
</div>
<div className="opportunities-item">
<div className="img">
<img src="/images/landing/feature-icon-3.svg" alt="" />
</div>
<Text variant="header-2">Легкость внедрения</Text>
<ul>
<li>
Интеграция с бизнес-процессами: Мы поможем интегрировать систему
с вашими существующими процессами, что упростит внедрение.
</li>
<li>
Готовое VR-оборудование: Предоставление возможности приобретения
необходимого VR-оборудования для обучения.
</li>
</ul>
</div>
<div className="opportunities-item">
<div className="img">
<img src="/images/landing/feature-icon-4.svg" alt="" />
</div>
<Text variant="header-2">Индивидуальный контроль и анализ</Text>
<ul>
<li>
Мониторинг прогресса: Отслеживайте процесс обучения и
тестирования каждого сотрудника.
</li>
<li>
Аналитика результатов: Получайте детальные отчеты о
производительности сотрудников и уровне усвоения материала.
</li>
</ul>
</div>
<div className="opportunities-item">
<div className="img">
<img src="/images/landing/feature-icon-5.svg" alt="" />
</div>
<Text variant="header-2">Сотрудничество и обратная связь</Text>
<ul>
<li>Внутренний чат: Обеспечьте коммуникацию между сотрудниками, представителями предприятия и технической поддержкой.</li>
<li>Обратная связь: Позвольте сотрудникам и администраторам делиться мнениями и предложениями по улучшению системы.</li>
</ul>
</div>
<div className="opportunities-item">
<div className="img">
<img src="/images/landing/feature-icon-6.svg" alt="" />
</div>
<Text variant="header-2">Гибкость и настраиваемость</Text>
<ul>
<li>
Доработка под специфику: Мы адаптируем систему под уникальные потребности вашей компании, включая создание специализированных модулей и тестов.
</li>
<li>Регулярные обновления: Мы постоянно совершенствуем систему и предоставляем обновления, чтобы она оставалась актуальной.</li>
</ul>
</div>
</div>
</div>
<div className="scenarios">
<div className="scenarios-title">
<Text variant="header-1">Сценарии использования</Text>
</div>
<div className="scenarios-list">
<div className="scenarios-item">
<img src="/images/landing/1.png" alt="" />
<Text variant="header-2">Обучение новых сотрудников</Text>
<p>
Создайте портал для новых сотрудников и предоставьте им доступ к
обучающим материалам и тестированиям. Используйте VR-технологии
для симуляции рабочих ситуаций и повышения уровня подготовки.
</p>
</div>
<div className="scenarios-item">
<img src="/images/landing/2.png" alt="" />
<Text variant="header-2">
Оценка и повышение квалификации сотрудников:
</Text>
<p>
Проводите периодические тестирования и анализируйте результаты,
чтобы оценить уровень компетенции сотрудников. Предоставьте
персонализированные материалы для повышения квалификации в
соответствии с потребностями.
</p>
</div>
<div className="scenarios-item">
<img src="/images/landing/3.png" alt="" />
<Text variant="header-2">Мониторинг процесса обучения:</Text>
<p>
Следите за прогрессом каждого сотрудника, отслеживая его успехи и
результаты тестирований. Анализируйте статистику, чтобы выявить
области, требующие дополнительного внимания.
</p>
</div>
<div className="scenarios-item">
<img src="/images/landing/4.png" alt="" />
<Text variant="header-2">Индивидуальная настройка обучения:</Text>
<p>
Создайте персонализированные образовательные планы для
сотрудников, учитывая их уровень знаний и потребности.
Предоставьте дополнительные материалы и тестирования для улучшения
конкретных навыков.
</p>
</div>
<div className="scenarios-item">
<img src="/images/landing/5.png" alt="" />
<Text variant="header-2">Сотрудничество и обратная связь:</Text>
<p>
Обеспечьте коммуникацию между сотрудниками и представителями
предприятия через внутренний чат. Позвольте сотрудникам оставлять
обратную связь и предложения по улучшению системы.{" "}
</p>
</div>
<div className="scenarios-item">
<img src="/images/landing/6.png" alt="" />
<Text variant="header-2">
Создание специализированных образовательных модулей:
</Text>
<p>
Дорабатывайте систему под уникальные потребности вашей компании,
создавая специализированные образовательные модули и тесты.
Поддерживайте постоянное обновление и совершенствование
образовательного контента в соответствии с требованиями вашей
отрасли.
</p>
</div>
</div>
</div>
<div className="try">
<div className="try-title">
<Text variant="header-2">Начни бесплатно уже сейчас</Text>
<div className="buttons">
<span>
<button
className="new"
onClick={() => {
navigate("/create");
}}
>
Создать портал
</button>
<button
className="price"
onClick={() => {
navigate("/pricing");
}}
>
Тарифы
</button>
</span>
</div>
</div>
</div>
</main>
);
};
export default Landing;
|
"use strict";
// ! Coding challenge #18
// Working With Arrays
// Coding Challenge #1
// Julia and Kate are doing a study on dogs. So each of them asked 5 dog owners
// about their dog's age, and stored the data into an array (one array for each). For
// now, they are just interested in knowing whether a dog is an adult or a puppy.
// A dog is an adult if it is at least 3 years old, and it's a puppy if it's less than 3 years
// old.
// Your tasks:
//* Create a function 'checkDogs', which accepts 2 arrays of dog's ages
//* ('dogsJulia' and 'dogsKate'), and does the following things:
//* 1. Julia found out that the owners of the first and the last two dogs actually have
//* cats, not dogs! So create a shallow copy of Julia's array, and remove the cat
//* ages from that copied array (because it's a bad practice to mutate function
//* parameters)
//* 2. Create an array with both Julia's (corrected) and Kate's data
//* 3. For each remaining dog, log to the console whether it's an adult ("Dog number 1
//* is an adult, and is 5 years old") or a puppy ("Dog number 2 is still a puppy🐶")
//* 4. Run the function for both test datasets
// Test data:
//? § Data 1: Julia's data [3, 5, 2, 12, 7], Kate's data [4, 1, 15, 8, 3]
//? § Data 2: Julia's data [9, 16, 6, 8, 3], Kate's data [10, 5, 6, 1, 4]
//! Hints: Use tools from all lectures in this section so far 😉
//! GOOD LUCK 😀
const juliaDogs = [3, 5, 2, 12, 7];
const kateDogs = [4, 1, 15, 8, 3];
const juliaDogs2 = [9, 16, 6, 8, 3];
const kateDogs2 = [10, 5, 6, 1, 4];
const checkDogs = (dogsJulia, dogsKate) => {
const correctedDogsJulia = dogsJulia.slice();
correctedDogsJulia.splice(0, 1);
correctedDogsJulia.splice(-2);
const dogs = correctedDogsJulia.concat(dogsKate);
console.log(dogs);
dogs.forEach((dog, index) => {
if (dog >= 3) {
console.log(
`Dog number ${index + 1} is an adult, and ${dog} is years old.`
);
} else {
console.log(`Dog number ${index + 1} is a puppy.`);
}
});
};
checkDogs(juliaDogs, kateDogs);
checkDogs(juliaDogs2, kateDogs2);
|
# Object-Oriented Programming Assignment
## Student Information
- **Name:** Ian Omwega
- **Registration Number:** SCT221-0927/2021
## Assignment Overview
### i. Object Modeling Techniques (OMT) [1 Mark]
**Definition:**
Object Modeling Techniques (OMT) is a method for modeling and designing systems using object-oriented concepts. Developed by James Rumbaugh, OMT is a key component of object-oriented analysis and design (OOAD). It employs graphical notations to represent objects, classes, relationships, and other aspects of an object-oriented system.
### ii. Comparison of OOAD and OOP [2 Marks]
**Object-Oriented Analysis and Design (OOAD):**
- Encompasses both analysis and design phases.
- Emphasis on understanding the problem domain and defining system requirements.
**Object Analysis and Design (OOP):**
- Primarily refers to the design phase.
- Focuses on system architecture, classes, and interactions based on the analysis.
### iii. Main Goals of UML [2 Marks]
Unified Modeling Language (UML) Goals:
1. **Visual Modeling:** Standardize system visualization using diagrams.
2. **Specification:** Define system structure and behavior.
3. **Documentation:** Document design decisions and system architecture.
4. **Construction:** Assist in system implementation.
5. **Communication:** Facilitate communication among stakeholders.
### iv. Advantages of Object-Oriented Information System Development
1. **Inheritance and Code Reusability:**
- Inheritance allows new classes to inherit attributes and behaviors.
2. **Encapsulation and Information Hiding:**
- Encapsulation supports hiding internal state, exposing a well-defined interface.
3. **Modularity and Reusability:**
- Promotes modular design, breaking systems into manageable object units.
### v. Types of Associations in Object-Oriented [Relationships]
1. **Association:**
- Represents a bi-directional relationship between two or more classes.
2. **Aggregation:**
- Specific association where one class represents a whole, and another represents its part.
3. **Composition:**
- Stronger form of aggregation, indicating a "owns" relationship with parts dependent on the whole's lifetime.
### vi. Class Diagram Explanation
**Class Diagram:**
- **Definition:** A visual representation of the structure and relationships of classes in a system.
- **Usage:** Used for system visualization, design documentation, and communication among stakeholders.
**Steps to Draw a Class Diagram:**
1. **Identify Classes:** Identify the main classes in the system.
2. **Define Attributes and Methods:** For each class, define its attributes and methods.
3. **Establish Relationships:** Define relationships between classes (association, aggregation, composition).
4. **Draw Diagram:** Represent classes, attributes, methods, and relationships using UML notation.
**Example:**
Consider a "Library Management System."
- Classes: `Book`, `Library`, `Member`
- Relationships: `Book` is associated with `Library` and `Member`.
|
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private Node first;
private Node last;
private int N;
private class Node {
Item item;
Node next;
Node previous;
}
private class DequeIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() { return current != null; }
public Item next() {
if (current == null) {
throw new NoSuchElementException("No more elements");
}
Item item = current.item;
current = current.next;
return item;
}
public void remove() {
throw new UnsupportedOperationException("remve() is not supported");
}
}
public Deque() {
first = null;
last = null;
N = 0;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public void addFirst(Item item) {
validateItem(item);
Node newNode = new Node();
newNode.item = item;
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.previous = newNode;
first = newNode;
}
N++;
}
public void addLast(Item item) {
validateItem(item);
Node newNode = new Node();
newNode.item = item;
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.previous = last;
last = newNode;
}
N++;
}
public Item removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException("Deque is empty");
}
Item item = first.item;
if (N == 1) {
first = null;
last = null;
} else {
first = first.next;
first.previous = null;
}
N--;
return item;
}
public Item removeLast() {
if (isEmpty()) {
throw new NoSuchElementException(
"The deque is empty."
);
}
Item item = last.item;
if (N == 1) {
first = null;
last = null;
} else {
last = last.previous;
last.next = null;
}
N--;
return item;
}
public Iterator<Item> iterator() {
return new DequeIterator();
}
private Item getFirstItem() {
return first == null ? null : first.item;
}
private Item getLastItem() {
return last == null ? null : last.item;
}
private void validateItem(Item item) {
if (item == null) {
throw new IllegalArgumentException(
"Item to be inserted cannot be null");
}
}
}
|
"""elements URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from . import views
urlpatterns = [
path('task/<str:task_id>/status', views.get_status),
path('task/<str:task_id>/result', views.get_result),
path('admin/<str:space_id>/', admin.site.urls),
path('auth/', include('app.auth.urls')),
path('space/', include('app.space.urls')),
path('user/<str:space_id>/', include('app.user.urls')),
path('site/', include('app.site.urls')),
path('document/', include('app.document.urls')),
path('role/<str:space_id>/', include('app.role.urls')),
]
|
package org.example;
public class Node {
private String name;
private String artist;
private String genre;
private int duration;
private Node next;
// Constructor
public Node(String name, String artist, String genre, int duration) {
this.name = name;
this.artist = artist;
this.genre = genre;
this.duration = duration;
this.next = null;
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"name='" + name + '\'' +
", artist='" + artist + '\'' +
", genre='" + genre + '\'' +
", duration=" + duration +
'}';
}
}
|
import { ChangeDetectionStrategy, Component, OnInit, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Router } from '@angular/router';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
import { ShoesService } from './core/services/shoesService/shoes-service.service';
import { TesteComponent } from './components/teste/teste.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [
RouterOutlet,
HeaderComponent,
FooterComponent,
TesteComponent
],
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
changeDetection:ChangeDetectionStrategy.Default
})
export class AppComponent implements OnInit {
title = 'angularStudy';
// dessa forma deixa o codigo mais limpo mas aumenta o acomplamento porem
private router = inject(Router);
constructor() {
this.router.navigate(["/home"])
}
ngOnInit(): void {
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package accesoDatos;
import accesoDatos.exceptions.NonexistentEntityException;
import accesoDatos.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import modelo.Nota;
/**
*
* @author Chema
*/
public class NotaJpaController implements Serializable {
public NotaJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Nota nota) throws RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(nota);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Nota nota) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
nota = em.merge(nota);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = nota.getIdNota();
if (findNota(id) == null) {
throw new NonexistentEntityException("The nota with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Nota nota;
try {
nota = em.getReference(Nota.class, id);
nota.getIdNota();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The nota with id " + id + " no longer exists.", enfe);
}
em.remove(nota);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Nota> findNotaEntities() {
return findNotaEntities(true, -1, -1);
}
public List<Nota> findNotaEntities(int maxResults, int firstResult) {
return findNotaEntities(false, maxResults, firstResult);
}
private List<Nota> findNotaEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Nota.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Nota findNota(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Nota.class, id);
} finally {
em.close();
}
}
public int getNotaCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Nota> rt = cq.from(Nota.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
|
<template>
<div>
<!-- 操作栏 -->
<el-row :gutter="20" class="m10">
<el-col :span="4">
<router-link :to="{path: '/router/addPost'}" v-showBtn data-authorityType="addPost-btn">
<el-button type="primary" size="medium" icon="el-icon-plus">添加角色</el-button>
</router-link>
</el-col>
<el-col :span="20" class="text-right" style="float: right;">
<el-input size="medium" clearable placeholder="查询角色名称" prefix-icon="el-icon-search" icon="search" v-model="query.roleName"
@keyup.enter.native="loadData" style="width: 250px;"></el-input>
<el-button type="primary" size="medium" @click="loadData" class="btnTop">查询</el-button>
</el-col>
</el-row>
<!-- table -->
<el-table class="page-table" :data="listData" stripe highlight-current-row v-loading="listLoading"
:cell-style="{color:'#333'}"
@selection-change="handleSelectionChange">
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column v-for="(header, index) in tableHeader" v-if="header.show" :key="index" :prop="header.prop"
:formatter="header.formatter"
:label="header.label" :sortable="header.sortable"
:align="header.align" :min-width="header.width" :column-key="header.prop" show-overflow-tooltip>
</el-table-column>
<el-table-column label="操作" width="150" fixed="right">
<template slot-scope="scope">
<router-link v-showBtn data-authorityType="editPost-btn" :to="{path: '/router/editPost', query: {roleId: scope.row.roleId}}">
<el-button type="primary" size="mini">编辑</el-button>
</router-link>
<el-button type="primary" size="mini" v-showBtn data-authorityType="deletePost-btn" @click="deleteItem(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-row type="flex" class="page-box" justify="end">
<!-- 分页 -->
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="query.pageNum"
:page-sizes="[10, 20, 50, 100]"
:page-size="query.pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
<el-button type="primary" size="small" @click="exportExcel">导出excel</el-button>
</el-row>
</div>
</template>
<script>
import moment from 'moment'
import Api from '@/api/index'
export default {
data () {
return {
query: {
roleName: '',
pageSize: 10,
pageNum: 1
},
tableHeader: [{
prop: 'roleName',
label: '角色名称',
width: '200',
show: true
}, {
prop: 'roleDescription',
label: '描述',
width: '200',
align: 'center',
show: true
}, {
prop: 'createDt',
align: 'center',
label: '创建时间',
width: '150',
formatter: (val) => moment(val.createDt).format('YYYY-MM-DD HH:mm:ss'),
show: true
}, {
prop: 'updateDt',
align: 'center',
label: '修改时间',
formatter: (val) => moment(val.updateDt).format('YYYY-MM-DD HH:mm:ss'),
width: '150',
show: true
}, {
prop: 'ctUName',
align: 'center',
label: '创建者',
width: '100',
show: true
}],
/** 表格数据 */
listData: [],
/** 总数据数 */
total: 0,
/** 表格 loading */
listLoading: false,
multipleSelection: []
}
},
mounted () {
this.loadData()
},
methods: {
/**
* 加载数据
*/
loadData (pageNum=1) {
if(typeof pageNum =='object'){
this.query.pageNum =1
}else{
this.query.pageNum =pageNum
}
this.listLoading = true
Api.getRolePage(this.query).then(data => {
if (data) {
this.listData = data.records
this.total = data.total
this.listLoading = false
}
}).catch(function () {
this.listLoading = false
})
},
/**
* 删除
*/
deleteItem (item) {
this.$confirm('您确定要删除记录吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
Api.deleteRole({
roleId: item.roleId
}).then(data => {
if (data === true) {
this.loadData()
this.$notify.success({
title: '提示',
message: '删除成功'
})
}
})
}).catch(() => {})
},
/**
* size change
*/
handleSizeChange (val) {
this.query.pageSize = val
this.loadData()
},
/**
* current change
*/
handleCurrentChange (val) {
this.query.pageNum = val
this.loadData(val)
},
/**
* selection change
*/
handleSelectionChange (val) {
this.multipleSelection = val
},
/**
* 导出excel
*/
exportExcel () {
if (this.listData.length > 0) {
let param = {
tableHead: this.tableHeader,
data: this.listData
}
Api.downloadExcel(param).then((res) => {
if (res) {
let reader = new FileReader()
reader.readAsDataURL(res)
reader.onload = (e) => {
let a = document.createElement('a')
a.download = '列表数据.xlsx'
a.href = e.target.result
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
}
})
}
},
}
}
</script>
|
library(data.table)
library(dplyr)
library(corrplot)
library(e1071)
library(caret)
library(DMwR)
library(Hmisc)
library(stringr)
library(zipcode)
library(dummies)
library(ROCR)
library(gbm)
setwd("C:/Users/dgbudale/Downloads/Data Mining with R/Carvana")
train.data = fread("training.csv", stringsAsFactors = F)
test.data = fread("test.csv", stringsAsFactors = F)
full = rbindlist(list(train.data, test.data), use.names = T, fill = T)
full[is.na(IsBadBuy),set:="test"]
full[!is.na(IsBadBuy), set := "train"]
full[, set := factor(set, levels = c("train", "test"))]
#full_both<-full
full<-as.data.frame(full)
#full$RefId<-NULL
full$VehOdo<-as.numeric(full$VehOdo)
full$MMRAcquisitionAuctionAveragePrice<-as.numeric(full$MMRAcquisitionAuctionAveragePrice)
full$MMRAcquisitionAuctionCleanPrice<-as.numeric(full$MMRAcquisitionAuctionCleanPrice)
full$MMRAcquisitionRetailAveragePrice<-as.numeric(full$MMRAcquisitionRetailAveragePrice)
full$MMRAcquisitonRetailCleanPrice<-as.numeric(full$MMRAcquisitonRetailCleanPrice)
full$MMRCurrentAuctionAveragePrice<-as.numeric(full$MMRCurrentAuctionAveragePrice)
full$MMRCurrentAuctionCleanPrice<-as.numeric(full$MMRCurrentAuctionCleanPrice)
full$MMRCurrentRetailAveragePrice<-as.numeric(full$MMRCurrentRetailAveragePrice)
full$MMRCurrentRetailCleanPrice<-as.numeric(full$MMRCurrentRetailCleanPrice)
full$WarrantyCost<-as.numeric(full$WarrantyCost)
full$IsBadBuy<-as.factor(full$IsBadBuy)
full$Auction<-as.factor(full$Auction)
full$Make<-as.factor(full$Make)
full$Model<-as.factor(full$Model)
full$Trim<-as.factor(full$Trim)
full$SubModel<-as.factor(full$SubModel)
full$Color<-as.factor(full$Color)
full$Transmission<-as.factor(full$Transmission)
full$WheelTypeID<-as.factor(full$WheelTypeID)
full$WheelType<-as.factor(full$WheelType)
full$Nationality<-as.factor(full$Nationality)
full$Size<-as.factor(full$Size)
full$TopThreeAmericanName<-as.factor(full$TopThreeAmericanName)
full$PRIMEUNIT<-as.factor(full$PRIMEUNIT)
full$AUCGUART<-as.factor(full$AUCGUART)
full$VNST<-as.factor(full$VNST)
full$IsOnlineSale<-as.factor(full$IsOnlineSale)
full$PurchDate<-as.Date(full$PurchDate,"%m/%d/%Y")
#--------------------------------------------------------------------------------------------------------
#Handling Missing Values
full$Trim<-as.character(full$Trim)
full[full$Trim=="",]$Trim<-"Other"
full$Trim<-as.factor(full$Trim)
full$SubModel<-as.character(full$SubModel)
full[full$SubModel=="",]$SubModel<-"MISSING"
full$SubModel<-as.factor(full$SubModel)
full$Color<-as.character(full$Color)
full[full$Color=="",]$Color<-"MISSING"
full$Color<-as.factor(full$Color)
full$Transmission<-as.character(full$Transmission)
full[full$Transmission=="",]$Transmission<-"MISSING"
full$Transmission<-as.factor(full$Transmission)
#--------------------------------------------------------------------------------------------------------
##chi-sq test for each categorical variable
fact<-select_if(full,is.factor)
for(i in 2:17) {
print(names(fact)[i])
print(chisq.test(full[,names(fact)[i]],full$IsBadBuy))
}
#--------------------------------------------------------------------------------------------------------
#multicollinearity
full$IsBadBuy<-ifelse(full$IsBadBuy==0,0,1)
num<-select_if(full,is.numeric)
num<-na.omit(num)
par(mfrow=c(1,1))
cor.num<-cor(num)
corrplot(cor.num,method='number')
#--------------------------------------------------------------------------------------------------------
#Missing values for numerical variables
set.seed(1234)
model_lm1<-lm(MMRAcquisitionAuctionAveragePrice~VehBCost+VehYear+VehicleAge,data=num)
lm1<-full[is.na(full$MMRAcquisitionAuctionAveragePrice),]
pred_lm1<-predict(model_lm1,lm1)
full[is.na(full$MMRAcquisitionAuctionAveragePrice),]$MMRAcquisitionAuctionAveragePrice<-pred_lm1
set.seed(1234)
model_lm2<-lm(MMRAcquisitionAuctionCleanPrice~VehBCost+VehYear+VehicleAge,data=num)
lm2<-full[is.na(full$MMRAcquisitionAuctionCleanPrice),]
pred_lm2<-predict(model_lm2,lm2)
full[is.na(full$MMRAcquisitionAuctionCleanPrice),]$MMRAcquisitionAuctionCleanPrice<-pred_lm2
set.seed(1234)
model_lm3<-lm(MMRAcquisitionRetailAveragePrice~VehBCost+VehYear+VehicleAge,data=num)
lm3<-full[is.na(full$MMRAcquisitionRetailAveragePrice),]
pred_lm3<-predict(model_lm3,lm3)
full[is.na(full$MMRAcquisitionRetailAveragePrice),]$MMRAcquisitionRetailAveragePrice<-pred_lm3
set.seed(1234)
model_lm4<-lm(MMRAcquisitonRetailCleanPrice~VehBCost+VehYear+VehicleAge,data=num)
lm4<-full[is.na(full$MMRAcquisitonRetailCleanPrice),]
pred_lm4<-predict(model_lm4,lm4)
full[is.na(full$MMRAcquisitonRetailCleanPrice),]$MMRAcquisitonRetailCleanPrice<-pred_lm4
set.seed(1234)
model_lm5<-lm(MMRCurrentAuctionAveragePrice~VehBCost+VehYear+VehicleAge,data=num)
lm5<-full[is.na(full$MMRCurrentAuctionAveragePrice),]
pred_lm5<-predict(model_lm5,lm5)
full[is.na(full$MMRCurrentAuctionAveragePrice),]$MMRCurrentAuctionAveragePrice<-pred_lm5
set.seed(1234)
model_lm6<-lm(MMRCurrentAuctionCleanPrice~VehBCost+VehYear+VehicleAge,data=num)
lm6<-full[is.na(full$MMRCurrentAuctionCleanPrice),]
pred_lm6<-predict(model_lm6,lm6)
full[is.na(full$MMRCurrentAuctionCleanPrice),]$MMRCurrentAuctionCleanPrice<-pred_lm6
set.seed(1234)
model_lm7<-lm(MMRCurrentRetailAveragePrice~VehBCost+VehYear+VehicleAge,data=num)
lm7<-full[is.na(full$MMRCurrentRetailAveragePrice),]
pred_lm7<-predict(model_lm7,lm7)
full[is.na(full$MMRCurrentRetailAveragePrice),]$MMRCurrentRetailAveragePrice<-pred_lm7
set.seed(1234)
model_lm8<-lm(MMRCurrentRetailCleanPrice~VehBCost+VehYear+VehicleAge,data=num)
lm8<-full[is.na(full$MMRCurrentRetailCleanPrice),]
pred_lm8<-predict(model_lm8,lm8)
full[is.na(full$MMRCurrentRetailCleanPrice),]$MMRCurrentRetailCleanPrice<-pred_lm8
remove(model_lm1,model_lm2,model_lm3,model_lm4,model_lm5,model_lm6,model_lm7,model_lm8,
lm1,lm2,lm3,lm4,lm5,lm6,lm7,lm8,pred_lm1,pred_lm2,pred_lm3,pred_lm4,pred_lm5,pred_lm6,pred_lm7,pred_lm8,num,fact)
#--------------------------------------------------------------------------------------------------------
#data engineering
#----Auction
table(full$Auction)
chi_auction<-chisq.test(full$IsBadBuy,full$Auction)
chi_auction
par(mfrow=c(2,2))
corrplot(chi_auction$residuals,is.corr = FALSE)
barplot(table(full$Auction),col="blue",main="Original Distribution of Auction")
set.seed(1234)
naiveBayes(IsBadBuy ~ Auction,full)
adesa<-log(0.1913228)-log(0.2443182)
manheim<-log(0.5675629)-log(0.5252897)
other<-log(0.2411143)-log(0.2303922)
full$Auction_Prob<-0
full[full$Auction=="ADESA",]$Auction_Prob<-adesa
full[full$Auction=="MANHEIM",]$Auction_Prob<-manheim
full[full$Auction=="OTHER",]$Auction_Prob<-other
full$Auction<-NULL
#--------------------------------------------------------------------------------------------------------
#----Make
sort(table(full$Make))
chi_make<-chisq.test(full$Make,full$IsBadBuy)
chi_make
par(mfrow=c(1,1))
corrplot(chi_make$residuals,is.corr = FALSE)
full$Make<-as.character(full$Make)
full[full$Make %in% c("CADILLAC","CHRYSLER","GMC","HONDA","HUMMER","HYUNDAI","KIA","MITSUBISHI","PLYMOUTH","PONTIAC","SCION","SUBARU",
"VOLKSWAGEN","TOYOTA SCION","ISUZU","VOLVO","TOYOTA","SATURN","SUZUKI","ACURA"),]$Make<-"VOther"
full$Make<-as.factor(full$Make)
chisq.test(full$Make,full$IsBadBuy)
par(mfrow=c(1,1))
corrplot((chisq.test(full$Make,full$IsBadBuy))$residuals,is.corr = FALSE)
set.seed(1234)
mk<-naiveBayes(IsBadBuy ~ Make,full)
mk
mk_df<-as.data.frame(mk$tables)
names(mk_df)[1]<-"IsBadBuy"
names(mk_df)[2]<-"Make"
names(mk_df)[3]<-"Freq"
full$Make_Prob<-0
for(i in 1:13) {
x<-levels(full$Make)[i]
print(x)
prob<-log(mk_df[mk_df$IsBadBuy==0 & mk_df$Make==x,]$Freq)-log(mk_df[mk_df$IsBadBuy==1 & mk_df$Make==x,]$Freq)
print(prob)
full[full$Make==x,]$Make_Prob<-prob
}
full[full$Make=="VOther",]$Make_Prob<-log(0.3381505148)-log(0.3449197861)
full$Make<-NULL
#--------------------------------------------------------------------------------------------------------
#---Data engineering from Model
#--------Model Name
sort(table(full$Model))
chi_model<-chisq.test(full$IsBadBuy,full$Model)
chi_model
full$ModelName<-gsub(list('2WD|4WD|AWD|FWD|4C|6C|V6|V8'),'',full$Model)
full$ModelName<-trimws(gsub("\\b\\d+\\b", "", full$ModelName))
full$ModelName<-word(full$ModelName,1)
full[full$ModelName %in% c("",".",".0L",".5L",".7L"),]$ModelName<-"OTHER"
full$ModelName<-as.factor(full$ModelName)
sort(table(full$ModelName))
chi_modelname<-chisq.test(full$IsBadBuy,full$ModelName)
chi_modelname
df_modelname<-data.frame(chi_modelname$residuals)
names(df_modelname)[1]<-"IsBadBuy"
names(df_modelname)[2]<-"ModelName"
table(df_modelname$IsBadBuy,round(df_modelname$Freq))
x_model<-as.character(df_modelname[round(df_modelname$Freq)>=-1 & round(df_modelname$Freq)<1,]$ModelName)
tmp_model<-data.frame(sort(table(full$ModelName)))
names(tmp_model)[1]<-"model"
names(tmp_model)[2]<-"count"
x_model1<-as.character(tmp_model[tmp_model$count<=30,]$model)
full$ModelName<-as.character(full$ModelName)
full[full$ModelName %in% c(x_model,x_model1),]$ModelName<-"Other"
full[full$ModelName %in% c("ACCORD","ASCENDER","AURA","CAMRY","CHARGER",
"COBALT","DURANGO","ELANTRA","FIVE","FUSION","GALANT","JOURNEY","LACROSSE",
"MAGNUM","MILAN","NITRO","S40","SEBRING","SILVERADO","SPECTRA","STRATUS","TAHOE","TITAN","YARIS","OTHER","HHR"),]$ModelName<-"LightRed"
full$ModelName<-as.factor(full$ModelName)
chisq.test(full$IsBadBuy,full$ModelName)
par(mfrow=c(1,1))
corrplot((chisq.test(full$IsBadBuy,full$ModelName))$residuals,is.corr=FALSE)
set.seed(1234)
md<-naiveBayes(IsBadBuy ~ ModelName,full)
md
md_df<-as.data.frame(md$tables)
names(md_df)[1]<-"IsBadBuy"
names(md_df)[2]<-"Model"
names(md_df)[3]<-"Freq"
md_df
full$ModelName_Prob<-0
for(i in 1:24) {
x<-levels(full$ModelName)[i]
print(x)
prob<-log(md_df[md_df$IsBadBuy==0 & md_df$Model==x,]$Freq)-log(md_df[md_df$IsBadBuy==1 & md_df$Model==x,]$Freq)
print(prob)
full[full$ModelName==x,]$ModelName_Prob<-prob
}
full$ModelName<-NULL
#---------Drive Type
full$DriveType<-"Other"
full[grep("2WD",full$Model,ignore.case = TRUE),]$DriveType<-"2WD"
full[grep("4WD",full$Model,ignore.case = TRUE),]$DriveType<-"4WD"
full[grep("AWD",full$Model,ignore.case = TRUE),]$DriveType<-"AWD"
full[grep("FWD",full$Model,ignore.case = TRUE),]$DriveType<-"FWD"
full[grep("RWD",full$Model,ignore.case = TRUE),]$DriveType<-"RWD"
full$DriveType<-as.factor(full$DriveType)
summary(full$DriveType)
chi_dtype<-chisq.test(full$IsBadBuy,full$DriveType)
chi_dtype
corrplot(chi_dtype$residuals,is.corr = FALSE)
full$DriveType<-as.character(full$DriveType)
full[full$DriveType %in% c("FWD","RWD"),]$DriveType<-"FWD-RWD"
full$DriveType<-as.factor(full$DriveType)
set.seed(1234)
dt<-naiveBayes(IsBadBuy ~ DriveType,full)
dt
dt_df<-as.data.frame(dt$tables)
names(dt_df)[1]<-"IsBadBuy"
names(dt_df)[2]<-"DriveType"
names(dt_df)[3]<-"Freq"
dt_df
full$DriveType_Prob<-0
for(i in 1:5) {
x<-levels(full$DriveType)[i]
print(x)
prob<-log(dt_df[dt_df$IsBadBuy==0 & dt_df$DriveType==x,]$Freq)-log(dt_df[dt_df$IsBadBuy==1 & dt_df$DriveType==x,]$Freq)
print(prob)
full[full$DriveType==x,]$DriveType_Prob<-prob
}
full$DriveType<-NULL
#---------Cylinder
full$Cylinder<-"Other"
full[grep(list('I4|V4|4C'),full$Model,ignore.case = TRUE),]$Cylinder<-"4C"
full[grep(list('V5|5C'),full$Model,ignore.case = TRUE),]$Cylinder<-"5C"
full[grep(list('V6|6C'),full$Model,ignore.case = TRUE),]$Cylinder<-"6C"
#full[grep(list('V7|7C'),full$Model,ignore.case = TRUE),]$Cylinder<-"7C"
full[grep(list('V8|8C'),full$Model,ignore.case = TRUE),]$Cylinder<-"8C"
full$Cylinder<-as.factor(full$Cylinder)
summary(full$Cylinder)
chi_cylinder<-chisq.test(full$IsBadBuy,full$Cylinder)
chi_cylinder
corrplot(chi_cylinder$residuals,is.corr=FALSE)
full$Cylinder<-as.character(full$Cylinder)
full[full$Cylinder=="5C",]$Cylinder<-"Other"
full$Cylinder<-as.factor(full$Cylinder)
set.seed(1234)
cy<-naiveBayes(IsBadBuy ~ Cylinder,full)
cy
cy_df<-as.data.frame(cy$tables)
names(cy_df)[1]<-"IsBadBuy"
names(cy_df)[2]<-"Cylinder"
names(cy_df)[3]<-"Freq"
cy_df
full$Cylinder_Prob<-0
for(i in 1:4) {
x<-levels(full$Cylinder)[i]
print(x)
prob<-log(cy_df[cy_df$IsBadBuy==0 & cy_df$Cylinder==x,]$Freq)-log(cy_df[cy_df$IsBadBuy==1 & cy_df$Cylinder==x,]$Freq)
print(prob)
full[full$Cylinder==x,]$Cylinder_Prob<-prob
}
full$Cylinder<-NULL
#---------Engine Size
full$Engine1<-"Other"
str_engine<-unique(str_extract(full$Model, "\\d+\\.*\\d*\\L"))
#full$Engine<-'Other'
for (i in 2:33)
{
#print(str[i])
y<-str_engine[i]
full[grep(y,full$Model,ignore.case=TRUE),]$Engine1<-y
}
full$Engine1<-as.factor(full$Engine1)
#chi_engine<-chisq.test(full$IsBadBuy,full$Engine)
#chi_engine
#corrplot(chi_engine$residuals,is.corr = FALSE)
#full$Engine<-as.character(full$Engine)
#full[full$Engine %in% c("4.1L","5.6L","4.5L","1.5L","1.8L","2.5L","3.3L","3.6L","3.7L","3.8L","4.8L","5.3L","5.9L"),]$Engine<-"Other"
#full$Engine<-as.factor(full$Engine)
#chisq.test(full$IsBadBuy,full$Engine)
#corrplot((chisq.test(full$IsBadBuy,full$Engine))$residuals,is.corr = FALSE)
#----Injection
full$Injection<-'Other'
full$Injection<-word(full$Model,-1)
full[grep(list('EFI'),full$Model,ignore.case=TRUE),]$Injection<-'EFI'
full[grep(list('MPI'),full$Model,ignore.case=TRUE),]$Injection<-'MPI'
full[grep(list('MFI'),full$Model,ignore.case=TRUE),]$Injection<-'MFI'
full[grep(list('SPI'),full$Model,ignore.case=TRUE),]$Injection<-'SPI'
full[grep(list('SFI'),full$Model,ignore.case=TRUE),]$Injection<-'SFI'
full[grep(list('DI'),full$Model,ignore.case=TRUE),]$Injection<-'DI'
#full[full$Injection %in% c('EFI','EF'),]$Injection<-'EFI'
#full[full$Injection %in% c('MPI','MP'),]$Injection<-'MPI'
#full[full$Injection %in% c('MFI','MF'),]$Injection<-'MFI'
#full[full$Injection %in% c('SPI','SP'),]$Injection<-'SPI'
#full[full$Injection %in% c('SFI','SF'),]$Injection<-'SFI'
#full[!full$Injection %in% c('EFI','MPI','MFI','SPI','SFI'),]$Injection<-'Other'
full[!full$Injection %in% c('EFI','EF','MPI','MP','MFI','MF','SPI','SP','SFI','SF','DI'),]$Injection<-'Other'
full$Injection<-as.factor(full$Injection)
summary(full$Injection)
chi_inj<-chisq.test(full$Injection,full$IsBadBuy)
chi_inj
corrplot(chi_inj$residuals,is.corr = FALSE)
set.seed(1234)
ij<-naiveBayes(IsBadBuy ~ Injection,full)
ij
ij_df<-as.data.frame(ij$tables)
names(ij_df)[1]<-"IsBadBuy"
names(ij_df)[2]<-"Injection"
names(ij_df)[3]<-"Freq"
ij_df
full$Injection_Prob<-0
for(i in 1:11) {
x<-levels(full$Injection)[i]
print(x)
prob<-log(ij_df[ij_df$IsBadBuy==0 & ij_df$Injection==x,]$Freq)-log(ij_df[ij_df$IsBadBuy==1 & ij_df$Injection==x,]$Freq)
print(prob)
full[full$Injection==x,]$Injection_Prob<-prob
}
full$Injection<-NULL
full$Model<-NULL
#--------------------------------------------------------------------------------------------------------
#---Data engineering from SubModel
#--------Car Type
full$CarType<-"OTHER"
full[grep("HATCHBACK",full$SubModel,ignore.case=TRUE),]$CarType<-"HATCHBACK"
full[grep("SEDAN",full$SubModel,ignore.case=TRUE),]$CarType<-"SEDAN"
full[grep("SUV",full$SubModel,ignore.case=TRUE),]$CarType<-"SUV"
full[grep("CROSSOVER",full$SubModel,ignore.case=TRUE),]$CarType<-"CROSSOVER"
full[grep("COUPE",full$SubModel,ignore.case=TRUE),]$CarType<-"COUPE"
full[grep("CONVERTIBLE",full$SubModel,ignore.case=TRUE),]$CarType<-"CONVERTIBLE"
full[grep("CAB",full$SubModel,ignore.case=TRUE),]$CarType<-"CAB"
full[grep("UTILITY",full$SubModel,ignore.case=TRUE),]$CarType<-"UTILITY"
full[grep("SPORT",full$SubModel,ignore.case=TRUE),]$CarType<-"SPORT"
full[grep("MINIVAN",full$SubModel,ignore.case=TRUE),]$CarType<-"MINIVAN"
full[grep("PASSENGER",full$SubModel,ignore.case=TRUE),]$CarType<-"PASSENGER"
full[grep("CUV",full$SubModel,ignore.case=TRUE),]$CarType<-"CUV"
full[grep("WAGON",full$SubModel,ignore.case=TRUE),]$CarType<-"WAGON"
full$CarType<-as.factor(full$CarType)
summary(full$CarType)
chi_cartype<-chisq.test(full$IsBadBuy,full$CarType)
chi_cartype
corrplot(chi_cartype$residuals,is.corr = FALSE)
full$CarType<-as.character(full$CarType)
full[full$CarType %in% c("CROSSOVER","CUV","HATCHBACK","MINIVAN","PASSENGER","UTILITY"),]$CarType<-"OTHER"
full[full$CarType %in% c("CAB","WAGON"),]$CarType<-"Rem"
full$CarType<-as.factor(full$CarType)
chisq.test(full$IsBadBuy,full$CarType)
corrplot((chisq.test(full$IsBadBuy,full$CarType))$residuals,is.corr = FALSE)
set.seed(1234)
ct<-naiveBayes(IsBadBuy ~ CarType,full)
ct
ct_df<-as.data.frame(ct$tables)
names(ct_df)[1]<-"IsBadBuy"
names(ct_df)[2]<-"CarType"
names(ct_df)[3]<-"Freq"
ct_df
full$CarType_Prob<-0
for(i in 1:7) {
x<-levels(full$CarType)[i]
print(x)
prob<-log(ct_df[ct_df$IsBadBuy==0 & ct_df$CarType==x,]$Freq)-log(ct_df[ct_df$IsBadBuy==1 & ct_df$CarType==x,]$Freq)
print(prob)
full[full$CarType==x,]$CarType_Prob<-prob
}
full$CarType<-NULL
#----------Doors
full$Doors<-"Other"
full[grep("2D",full$SubModel,ignore.case=TRUE),]$Doors<-"2D"
full[grep("3D",full$SubModel,ignore.case=TRUE),]$Doors<-"3D"
full[grep("4D",full$SubModel,ignore.case=TRUE),]$Doors<-"4D"
full[grep("5D",full$SubModel,ignore.case=TRUE),]$Doors<-"5D"
full$Doors<-as.factor(full$Doors)
summary(full$Doors)
chi_doors<-chisq.test(full$IsBadBuy,full$Doors)
chi_doors
corrplot(chi_doors$residuals,is.corr = FALSE)
full$Doors<-as.character(full$Doors)
full[full$Doors=="4D",]$Doors<-"Other"
full$Doors<-as.factor(full$Doors)
set.seed(1234)
dr<-naiveBayes(IsBadBuy ~ Doors,full)
dr
dr_df<-as.data.frame(dr$tables)
names(dr_df)[1]<-"IsBadBuy"
names(dr_df)[2]<-"Doors"
names(dr_df)[3]<-"Freq"
dr_df
full$Doors_Prob<-0
for(i in 1:4) {
x<-levels(full$Doors)[i]
print(x)
prob<-log(dr_df[dr_df$IsBadBuy==0 & dr_df$Doors==x,]$Freq)-log(dr_df[dr_df$IsBadBuy==1 & dr_df$Doors==x,]$Freq)
print(prob)
full[full$Doors==x,]$Doors_Prob<-prob
}
full$Doors<-NULL
#-------Engine Size
full$Engine2<-"Other"
str_engine<-unique(str_extract(full$SubModel, "\\d+\\.*\\d*\\L"))
for (i in 2:35)
{
#print(str[i])
y<-str_engine[i]
full[grep(y,full$SubModel,ignore.case=TRUE),]$Engine2<-y
}
full$Engine2<-as.factor(full$Engine2)
#--------Final Engine Size
full$Engine1<-as.character(full$Engine1)
full$Engine2<-as.character(full$Engine2)
full$Engine<-'Other'
full$Engine<-ifelse(full$Engine1!="Other" & full$Engine2=="Other",full$Engine1,
(ifelse(full$Engine1=="Other" & full$Engine2!="Other",full$Engine2,(ifelse(full$Engine1!="Other" & full$Engine2!="Other",full$Engine2,'Other')))))
full$Engine<-as.factor(full$Engine)
full$Engine1<-NULL
full$Engine2<-NULL
chi_engine<-chisq.test(full$IsBadBuy,full$Engine)
chi_engine
corrplot(chi_engine$residuals,is.corr = FALSE)
full$Engine<-as.character(full$Engine)
full[full$Engine %in% c("4.1L","6.8L","4.5L","6.2L","5.2L","2.9L","1.5L","1.8L","1L","2.3L","3.6L","4.2L","4.3L","4.5L","5.3L","1.7L"),]$Engine<-"Other"
full$Engine<-as.factor(full$Engine)
chisq.test(full$IsBadBuy,full$Engine)
corrplot((chisq.test(full$IsBadBuy,full$Engine))$residuals,is.corr = FALSE)
par(mfrow=c(2,1))
chisq.test(full$IsBadBuy,full$Engine)
corrplot((chisq.test(full$IsBadBuy,full$Engine))$residuals,is.corr = FALSE)
full$Engine<-as.character(full$Engine)
full[full$Engine %in% c("1.6L","1.9L","2.0L","2.5L","3.2L","3.8L","6.0L"),]$Engine<-"LightBlue"
full[full$Engine %in% c("2.4L","2.8L","3.3L","3.7L","3.9L","4.7L","4.8L","5.6L"),]$Engine<-"LightRed"
full$Engine<-as.factor(full$Engine)
chisq.test(full$IsBadBuy,full$Engine)
corrplot((chisq.test(full$IsBadBuy,full$Engine))$residuals,is.corr = FALSE)
set.seed(1234)
eng<-naiveBayes(IsBadBuy ~ Engine,full)
eng
eng_df<-as.data.frame(eng$tables)
names(eng_df)[1]<-"IsBadBuy"
names(eng_df)[2]<-"Engine"
names(eng_df)[3]<-"Freq"
eng_df
full$Engine_Prob<-0
for(i in 1:14) {
x<-levels(full$Engine)[i]
print(x)
prob<-log(eng_df[eng_df$IsBadBuy==0 & eng_df$Engine==x,]$Freq)-log(eng_df[eng_df$IsBadBuy==1 & eng_df$Engine==x,]$Freq)
print(prob)
full[full$Engine==x,]$Engine_Prob<-prob
}
full$Engine<-NULL
full$SubModel<-NULL
#--------------------------------------------------------------------------------------------------------
#------------Trim
chi_trim<-chisq.test(full$IsBadBuy,full$Trim)
chi_trim
df_trim<-data.frame(chi_trim$residuals)
names(df_trim)[1]<-"IsBadBuy"
names(df_trim)[2]<-"Trim"
table(df_trim$IsBadBuy,round(df_trim$Freq))
x_trim<-as.character(df_trim[round(df_trim$Freq)==0 ,]$Trim)
tmp_trim<-data.frame(sort(table(full$Trim)))
names(tmp_trim)[1]<-"trim"
names(tmp_trim)[2]<-"count"
x_trim1<-as.character(tmp_trim[tmp_trim$count<=200,]$trim) #change from 100
full$Trim<-as.character(full$Trim)
full[full$Trim %in% c(x_trim,x_trim1),]$Trim<-"Other"
full$Trim<-as.factor(full$Trim)
sort(table(full$Trim))
chisq.test(full$IsBadBuy,full$Trim)
par(mfrow=c(1,1))
corrplot((chisq.test(full$IsBadBuy,full$Trim))$residuals,is.corr = FALSE)
set.seed(1234)
tr<-naiveBayes(IsBadBuy ~ Trim,full)
tr
tr_df<-as.data.frame(tr$tables)
names(tr_df)[1]<-"IsBadBuy"
names(tr_df)[2]<-"Trim"
names(tr_df)[3]<-"Freq"
tr_df
full$Trim_Prob<-0
for(i in 1:29) {
x<-levels(full$Trim)[i]
print(x)
prob<-log(tr_df[tr_df$IsBadBuy==0 & tr_df$Trim==x,]$Freq)-log(tr_df[tr_df$IsBadBuy==1 & tr_df$Trim==x,]$Freq)
print(prob)
full[full$Trim==x,]$Trim_Prob<-prob
}
full$Trim<-NULL
#--------------------------------------------------------------------------------------------------------
#------------Color
summary(full$Color)
chi_color<-chisq.test(full$IsBadBuy,full$Color)
chi_color
par(mfrow=c(2,1))
corrplot(chi_color$residuals,is.corr = FALSE)
full$Color<-as.character(full$Color)
full[full$Color %in% c("MISSING","PINK","NULL"),]$Color<-"OTHER"
full[full$Color=="NOT AVAIL",]$Color<-"NOT_AVAIL"
full$Color<-as.factor(full$Color)
chisq.test(full$IsBadBuy,full$Color)
corrplot((chisq.test(full$IsBadBuy,full$Color))$residuals,is.corr = FALSE)
set.seed(1234)
col<-naiveBayes(IsBadBuy ~ Color,full)
col
col_df<-as.data.frame(col$tables)
names(col_df)[1]<-"IsBadBuy"
names(col_df)[2]<-"Color"
names(col_df)[3]<-"Freq"
col_df
full$Color_Prob<-0
for(i in 1:16) {
x<-levels(full$Color)[i]
print(x)
prob<-log(col_df[col_df$IsBadBuy==0 & col_df$Color==x,]$Freq)-log(col_df[col_df$IsBadBuy==1 & col_df$Color==x,]$Freq)
print(prob)
full[full$Color==x,]$Color_Prob<-prob
}
full$Color<-NULL
#--------------------------------------------------------------------------------------------------------
#------------Transmission
summary(full$Transmission)
chi_Transmission<-chisq.test(full$IsBadBuy,full$Transmission)
chi_Transmission
par(mfrow=c(2,1))
corrplot(chi_Transmission$residuals,is.corr = FALSE)
full$Transmission<-as.character(full$Transmission)
full[full$Transmission %in% c("MISSING","Manual","NULL"),]$Transmission<-"MANUAL"
full$Transmission<-as.factor(full$Transmission)
summary(full$Transmission)
chisq.test(full$IsBadBuy,full$Transmission)
corrplot((chisq.test(full$IsBadBuy,full$Transmission))$residuals,is.corr=FALSE)
set.seed(1234)
tr<-naiveBayes(IsBadBuy ~ Transmission,full)
tr
tr_df<-as.data.frame(tr$tables)
names(tr_df)[1]<-"IsBadBuy"
names(tr_df)[2]<-"Transmission"
names(tr_df)[3]<-"Freq"
tr_df
full$Transmission_Prob<-0
for(i in 1:2) {
x<-levels(full$Transmission)[i]
print(x)
prob<-log(tr_df[tr_df$IsBadBuy==0 & tr_df$Transmission==x,]$Freq)-log(tr_df[tr_df$IsBadBuy==1 & tr_df$Transmission==x,]$Freq)
print(prob)
full[full$Transmission==x,]$Transmission_Prob<-prob
}
full$Transmission<-NULL
#--------------------------------------------------------------------------------------------------------
#------------WheelType
full$WheelTypeID<-NULL
summary(full$WheelType)
chi_wheeltype<-chisq.test(full$IsBadBuy,full$WheelType)
chi_wheeltype
par(mfrow=c(2,1))
corrplot(chi_wheeltype$residuals,is.corr = FALSE)
full$WheelType<-as.character(full$WheelType)
full[full$WheelType %in% c("NULL"),]$WheelType<-"NOT_AVAIL"
#full[full$WheelType %in% c("Alloy","Special"),]$WheelType<-"OTHER"
full$WheelType<-as.factor(full$WheelType)
summary(full$WheelType)
chisq.test(full$IsBadBuy,full$WheelType)
corrplot((chisq.test(full$IsBadBuy,full$WheelacType))$residuals,is.corr = FALSE)
set.seed(1234)
wh<-naiveBayes(IsBadBuy ~ WheelType,full)
wh
wh_df<-as.data.frame(wh$tables)
names(wh_df)[1]<-"IsBadBuy"
names(wh_df)[2]<-"WheelType"
names(wh_df)[3]<-"Freq"
wh_df
full$WheelType_Prob<-0
for(i in 1:4) {
x<-levels(full$WheelType)[i]
print(x)
prob<-log(wh_df[wh_df$IsBadBuy==0 & wh_df$WheelType==x,]$Freq)-log(wh_df[wh_df$IsBadBuy==1 & wh_df$WheelType==x,]$Freq)
print(prob)
full[full$WheelType==x,]$WheelType_Prob<-prob
}
full$WheelType<-NULL
#--------------------------------------------------------------------------------------------------------
#------------Nationality
summary(full$Nationality)
chi_nation<-chisq.test(full$IsBadBuy,full$Nationality)
chi_nation
corrplot(chi_nation$residuals,is.corr = FALSE)
full$Nationality<-as.character(full$Nationality)
full[full$Nationality=="NULL",]$Nationality<-"OTHER"
full[full$Nationality=="OTHER ASIAN",]$Nationality<-"OTHER_ASIAN"
full[full$Nationality=="TOP LINE ASIAN",]$Nationality<-"TOP_LINE_ASIAN "
full$Nationality<-as.factor(full$Nationality)
chisq.test(full$IsBadBuy,full$Nationality)
corrplot((chisq.test(full$IsBadBuy,full$Nationality))$residuals,is.corr=FALSE)
summary(full$Nationality)
set.seed(1234)
nt<-naiveBayes(IsBadBuy ~ Nationality,full)
nt
nt_df<-as.data.frame(nt$tables)
names(nt_df)[1]<-"IsBadBuy"
names(nt_df)[2]<-"Nationality"
names(nt_df)[3]<-"Freq"
nt_df
full$Nationality_Prob<-0
for(i in 1:4) {
x<-levels(full$Nationality)[i]
print(x)
prob<-log(nt_df[nt_df$IsBadBuy==0 & nt_df$Nationality==x,]$Freq)-log(nt_df[nt_df$IsBadBuy==1 & nt_df$Nationality==x,]$Freq)
print(prob)
full[full$Nationality==x,]$Nationality_Prob<-prob
}
full$Nationality<-NULL
#--------------------------------------------------------------------------------------------------------
#------------Size
summary(full$Size)
chi_size<-chisq.test(full$IsBadBuy,full$Size)
chi_size
par(mfrow=c(2,1))
corrplot(chi_size$residuals,is.corr = FALSE)
full$Size<-as.character(full$Size)
full[full$Size %in% c("NULL"),]$Size<-"VOTHER"
full[full$Size %in% c("SMALL SUV"),]$Size<-"SMALL_SUV"
full[full$Size %in% c("SMALL TRUCK"),]$Size<-"SMALL_TRUCK"
full[full$Size=="LARGE SUV",]$Size<-"LARGE_SUV"
full[full$Size=="LARGE TRUCK",]$Size<-"LARGE_TRUCK"
full[full$Size=="MEDIUM SUV",]$Size<-"MEDIUM_SUV"
full$Size<-as.factor(full$Size)
summary(full$Size)
chisq.test(full$IsBadBuy,full$Size)
corrplot((chisq.test(full$IsBadBuy,full$Size))$residuals,is.corr = FALSE)
set.seed(1234)
sz<-naiveBayes(IsBadBuy ~ Size,full)
sz
sz_df<-as.data.frame(sz$tables)
names(sz_df)[1]<-"IsBadBuy"
names(sz_df)[2]<-"Size"
names(sz_df)[3]<-"Freq"
sz_df
full$Size_Prob<-0
for(i in 1:12) {
x<-levels(full$Size)[i]
print(x)
prob<-log(sz_df[sz_df$IsBadBuy==0 & sz_df$Size==x,]$Freq)-log(sz_df[sz_df$IsBadBuy==1 & sz_df$Size==x,]$Freq)
print(prob)
full[full$Size==x,]$Size_Prob<-prob
}
full[full$Size=="VOTHER",]$Size_Prob<-log(7.811646e-05)
full$Size<-NULL
#--------------------------------------------------------------------------------------------------------
#------------Top3AmericanName
summary(full$TopThreeAmericanName)
chi_top<-chisq.test(full$IsBadBuy,full$TopThreeAmericanName)
chi_top
par(mfrow=c(2,1))
corrplot(chi_top$residuals,is.corr = FALSE)
full$TopThreeAmericanName<-as.character(full$TopThreeAmericanName)
full[full$TopThreeAmericanName=="NULL",]$TopThreeAmericanName<-"OTHER"
full$TopThreeAmericanName<-as.factor(full$TopThreeAmericanName)
chisq.test(full$IsBadBuy,full$TopThreeAmericanName)
corrplot((chisq.test(full$IsBadBuy,full$TopThreeAmericanName))$residuals,is.corr=FALSE)
set.seed(1234)
tt<-naiveBayes(IsBadBuy ~ TopThreeAmericanName,full)
tt
tt_df<-as.data.frame(tt$tables)
names(tt_df)[1]<-"IsBadBuy"
names(tt_df)[2]<-"TopThreeAmericanName"
names(tt_df)[3]<-"Freq"
tt_df
full$TopThreeAmericanName_Prob<-0
for(i in 1:4) {
x<-levels(full$TopThreeAmericanName)[i]
print(x)
prob<-log(tt_df[tt_df$IsBadBuy==0 & tt_df$TopThreeAmericanName==x,]$Freq)-log(tt_df[tt_df$IsBadBuy==1 & tt_df$TopThreeAmericanName==x,]$Freq)
print(prob)
full[full$TopThreeAmericanName==x,]$TopThreeAmericanName_Prob<-prob
}
full$TopThreeAmericanName<-NULL
#--------------------------------------------------------------------------------------------------------
#------------PrimeUnit
summary(full$PRIMEUNIT)
chi_punit<-chisq.test(full$IsBadBuy,full$PRIMEUNIT)
chi_punit
par(mfrow=c(2,1))
corrplot(chi_punit$residuals,is.corr = FALSE)
full$PRIMEUNIT<-as.character(full$PRIMEUNIT)
full[full$PRIMEUNIT=="NULL",]$PRIMEUNIT<-"NOT_AVAIL"
full[full$PRIMEUNIT!="NOT_AVAIL",]$PRIMEUNIT<-"AVAIL"
full$PRIMEUNIT<-as.factor(full$PRIMEUNIT)
chisq.test(full$IsBadBuy,full$PRIMEUNIT)
corrplot((chisq.test(full$IsBadBuy,full$PRIMEUNIT))$residuals,is.corr=FALSE)
set.seed(1234)
pu<-naiveBayes(IsBadBuy ~ PRIMEUNIT,full)
pu
pu_df<-as.data.frame(pu$tables)
names(pu_df)[1]<-"IsBadBuy"
names(pu_df)[2]<-"PRIMEUNIT"
names(pu_df)[3]<-"Freq"
pu_df
full$PRIMEUNIT_Prob<-0
for(i in 1:2) {
x<-levels(full$PRIMEUNIT)[i]
print(x)
prob<-log(pu_df[pu_df$IsBadBuy==0 & pu_df$PRIMEUNIT==x,]$Freq)-log(pu_df[pu_df$IsBadBuy==1 & pu_df$PRIMEUNIT==x,]$Freq)
print(prob)
full[full$PRIMEUNIT==x,]$PRIMEUNIT_Prob<-prob
}
full$PRIMEUNIT<-NULL
#--------------------------------------------------------------------------------------------------------
#------------AucGuart
summary(full$AUCGUART)
chi_aucg<-chisq.test(full$IsBadBuy,full$AUCGUART)
chi_aucg
par(mfrow=c(2,1))
corrplot(chi_aucg$residuals,is.corr = FALSE)
full$AUCGUART<-as.character(full$AUCGUART)
full[full$AUCGUART == "NULL",]$AUCGUART<-"NOT_AVAIL"
full[full$AUCGUART!= "NOT_AVAIL",]$AUCGUART<-"AVAIL"
full$AUCGUART<-as.factor(full$AUCGUART)
chisq.test(full$IsBadBuy,full$AUCGUART)
corrplot((chisq.test(full$IsBadBuy,full$AUCGUART))$residuals,is.corr = FALSE)
set.seed(1234)
au<-naiveBayes(IsBadBuy ~ AUCGUART,full)
au
au_df<-as.data.frame(au$tables)
names(au_df)[1]<-"IsBadBuy"
names(au_df)[2]<-"AUCGUART"
names(au_df)[3]<-"Freq"
au_df
full$AUCGUART_Prob<-0
for(i in 1:2) {
x<-levels(full$AUCGUART)[i]
print(x)
prob<-log(au_df[au_df$IsBadBuy==0 & au_df$AUCGUART==x,]$Freq)-log(au_df[au_df$IsBadBuy==1 & au_df$AUCGUART==x,]$Freq)
print(prob)
full[full$AUCGUART==x,]$AUCGUART_Prob<-prob
}
full$AUCGUART<-NULL
#--------------------------------------------------------------------------------------------------------
#------------IsOnlineSale
summary(full$IsOnlineSale)
chi_isonlinesale<-chisq.test(full$IsBadBuy,full$IsOnlineSale)
chi_isonlinesale
set.seed(1234)
io<-naiveBayes(IsBadBuy ~ IsOnlineSale,full)
io
io_df<-as.data.frame(io$tables)
names(io_df)[1]<-"IsBadBuy"
names(io_df)[2]<-"IsOnlineSale"
names(io_df)[3]<-"Freq"
io_df
full$IsOnlineSale_Prob<-0
for(i in 1:2) {
x<-levels(full$IsOnlineSale)[i]
print(x)
prob<-log(io_df[io_df$IsBadBuy==0 & io_df$IsOnlineSale==x,]$Freq)-log(io_df[io_df$IsBadBuy==1 & io_df$IsOnlineSale==x,]$Freq)
print(prob)
full[full$IsOnlineSale==x,]$IsOnlineSale_Prob<-prob
}
full$IsOnlineSale<-NULL
#--------------------------------------------------------------------------------------------------------
#------------City
names(full)[16]<-"zip"
data(zipcode)
full$zip<-clean.zipcodes(full$zip)
full<-merge(full,zipcode[,c("zip","city")],by="zip")
sort(table(full$city))
chi_city<-chisq.test(full$IsBadBuy,full$city)
chi_city
par(mfrow=c(1,1))
corrplot(chi_city$residuals,is.corr=FALSE)
df_city<-data.frame(chi_city$residuals)
names(df_city)[1]<-"IsBadBuy"
names(df_city)[2]<-"City"
table(df_city$IsBadBuy,round(df_city$Freq))
x_city<-as.character(df_city[round(df_city$Freq)>=-1 & round(df_city$Freq)<=1 ,]$City)
tmp_city<-data.frame(sort(table(full$city)))
names(tmp_city)[1]<-"city"
names(tmp_city)[2]<-"count"
x_city1<-as.character(tmp_city[tmp_city$count<=200,]$city)
full[full$city %in% c(x_city,x_city1),]$city<-"Other"
full[full$city %in% c("Belton","Carmel","Hutchins","Lexington","Plainfield","Tracy"),]$city<-"Other"
full$city<-as.factor(full$city)
chisq.test(full$IsBadBuy,full$city)
corrplot((chisq.test(full$IsBadBuy,full$city))$residuals,is.corr=FALSE)
sort(table(full$city))
full$zip<-NULL
set.seed(1234)
city<-naiveBayes(IsBadBuy ~ city,full)
city
city_df<-as.data.frame(city$tables)
names(city_df)[1]<-"IsBadBuy"
names(city_df)[2]<-"city"
names(city_df)[3]<-"Freq"
city_df
full$City_Prob<-0
for(i in 1:15) {
x<-levels(full$city)[i]
print(x)
prob<-log(city_df[city_df$IsBadBuy==0 & city_df$city==x,]$Freq)-log(city_df[city_df$IsBadBuy==1 & city_df$city==x,]$Freq)
print(prob)
full[full$city==x,]$City_Prob<-prob
}
full$city<-NULL
#--------------------------------------------------------------------------------------------------------
#------------State
summary(full$VNST)
par(mfrow=c(1,1))
chi_state<-chisq.test(full$IsBadBuy,full$VNST)
chi_state
corrplot(chi_state$residuals,is.corr = FALSE)
sort(table(full$VNST))
full$VNST<-as.character(full$VNST)
full[full$VNST %in% c("WI","NJ","NM","AL","CO","MA","UT","MI","NY"),]$VNST<-"OTHER"
full[full$VNST %in% c("ID","NH","TN","MO","NE","WV"),]$VNST<-"LightRed"
full[full$VNST %in% c("IA","IL","IN","LA","MD"),]$VNST<-"LightBlue"
full$VNST<-as.factor(full$VNST)
chisq.test(full$IsBadBuy,full$VNST)
corrplot((chisq.test(full$IsBadBuy,full$VNST))$residuals,is.corr=FALSE)
#names(full)[43]<-"City"
#names(full)[26]<-"State"
set.seed(1234)
VNST<-naiveBayes(IsBadBuy ~ VNST,full)
VNST
VNST_df<-as.data.frame(VNST$tables)
names(VNST_df)[1]<-"IsBadBuy"
names(VNST_df)[2]<-"VNST"
names(VNST_df)[3]<-"Freq"
VNST_df
str(full$VNST)
full$VNST_Prob<-0
for(i in 1:21) {
x<-levels(full$VNST)[i]
print(x)
prob<-log(VNST_df[VNST_df$IsBadBuy==0 & VNST_df$VNST==x,]$Freq)-log(VNST_df[VNST_df$IsBadBuy==1 & VNST_df$VNST==x,]$Freq)
print(prob)
full[full$VNST==x,]$VNST_Prob<-prob
}
full$VNST<-NULL
#--------------------------------------------------------------------------------------------------------
#------------BYRNO
par(mfrow=c(2,1))
chi_byr<-chisq.test(full$IsBadBuy,full$BYRNO)
chi_byr
corrplot(chi_byr$residuals,is.corr=FALSE)
byr<-as.data.frame(chisq.test(full$BYRNO,full$IsBadBuy)$residuals)
byrnum<-as.character(byr[byr$Freq>=-2 & byr$Freq<=2,]$full.BYRNO)
full$BYRNO<-as.character(full$BYRNO)
full[full$BYRNO %in% byrnum,]$BYRNO<-"Other"
full[full$BYRNO %in% c("10415","22155","53100","99742","99791"),]$BYRNO<-"Other"
full$BYRNO<-as.factor(full$BYRNO)
table(full$BYRNO)
chisq.test(full$IsBadBuy,full$BYRNO)
corrplot((chisq.test(full$IsBadBuy,full$BYRNO))$residuals,is.corr=FALSE)
set.seed(1234)
BYRNO<-naiveBayes(IsBadBuy ~ BYRNO,full)
BYRNO
BYRNO_df<-as.data.frame(BYRNO$tables)
names(BYRNO_df)[1]<-"IsBadBuy"
names(BYRNO_df)[2]<-"BYRNO"
names(BYRNO_df)[3]<-"Freq"
BYRNO_df
str(full$BYRNO)
full$BYRNO_Prob<-0
for(i in 1:6) {
x<-levels(full$BYRNO)[i]
print(x)
prob<-log(BYRNO_df[BYRNO_df$IsBadBuy==0 & BYRNO_df$BYRNO==x,]$Freq)-log(BYRNO_df[BYRNO_df$IsBadBuy==1 & BYRNO_df$BYRNO==x,]$Freq)
print(prob)
full[full$BYRNO==x,]$BYRNO_Prob<-prob
}
full$BYRNO<-NULL
#--------------------------------------------------------------------------------------------------------
#Purchase Date
full$PurchYear<-format(full$PurchDate,"%Y")
full$PurchQuarters<-quarters(full$PurchDate)
full$PurchMonth<-months(full$PurchDate)
full$WeekDay<-weekdays(full$PurchDate)
full$PurchDay<-format(full$PurchDate,"%d")
full$PurchYear<-as.factor(full$PurchYear)
full$PurchQuarters<-as.factor(full$PurchQuarters)
full$PurchMonth<-as.factor(full$PurchMonth)
full$WeekDay<-as.factor(full$WeekDay)
full$PurchDay<-as.factor(full$PurchDay)
full$PurchDate<-NULL
#----------------Purch Year
table(full$PurchYear)
chi_pyear<-chisq.test(full$IsBadBuy,full$PurchYear)
par(mfrow=c(2,2))
corrplot(chi_pyear$residuals,is.cor = FALSE)
barplot(table(full$PurchYear),col="blue",main="Original Distribution of Purchase Year")
#----------------Purch Quarters
table(full$PurchQuarters)
chi_pqtrs<-chisq.test(full$IsBadBuy,full$PurchQuarters)
par(mfrow=c(2,2))
corrplot(chi_pqtrs$residuals,is.cor = FALSE)
barplot(table(full$PurchQuarters),col="blue",main="Original Distribution of Purchase Quarter")
set.seed(1234)
PurchQuarters<-naiveBayes(IsBadBuy ~ PurchQuarters,full)
PurchQuarters
PurchQuarters_df<-as.data.frame(PurchQuarters$tables)
names(PurchQuarters_df)[1]<-"IsBadBuy"
names(PurchQuarters_df)[2]<-"PurchQuarters"
names(PurchQuarters_df)[3]<-"Freq"
PurchQuarters_df
str(full$PurchQuarters)
full$PurchQuarters_Prob<-0
for(i in 1:4) {
x<-levels(full$PurchQuarters)[i]
print(x)
prob<-log(PurchQuarters_df[PurchQuarters_df$IsBadBuy==0 & PurchQuarters_df$PurchQuarters==x,]$Freq)-log(PurchQuarters_df[PurchQuarters_df$IsBadBuy==1 & PurchQuarters_df$PurchQuarters==x,]$Freq)
print(prob)
full[full$PurchQuarters==x,]$PurchQuarters_Prob<-prob
}
full$PurchQuarters<-NULL
#----------------Purch Month
table(full$PurchMonth)
chi_pmonth<-chisq.test(full$IsBadBuy,full$PurchMonth)
par(mfrow=c(2,2))
corrplot(chi_pmonth$residuals,is.cor = FALSE)
barplot(table(full$PurchMonth),col="blue",main="Original Distribution of Purchase Month")
set.seed(1234)
PurchMonth<-naiveBayes(IsBadBuy ~ PurchMonth,full)
PurchMonth
PurchMonth_df<-as.data.frame(PurchMonth$tables)
names(PurchMonth_df)[1]<-"IsBadBuy"
names(PurchMonth_df)[2]<-"PurchMonth"
names(PurchMonth_df)[3]<-"Freq"
PurchMonth_df
str(full$PurchMonth)
full$PurchMonth_Prob<-0
for(i in 1:12) {
x<-levels(full$PurchMonth)[i]
print(x)
prob<-log(PurchMonth_df[PurchMonth_df$IsBadBuy==0 & PurchMonth_df$PurchMonth==x,]$Freq)-log(PurchMonth_df[PurchMonth_df$IsBadBuy==1 & PurchMonth_df$PurchMonth==x,]$Freq)
print(prob)
full[full$PurchMonth==x,]$PurchMonth_Prob<-prob
}
full$PurchMonth<-NULL
#-----------------Week Day
table(full$WeekDay)
chi_pweekday<-chisq.test(full$IsBadBuy,full$WeekDay)
par(mfrow=c(2,2))
corrplot(chi_pweekday$residuals,is.cor = FALSE)
barplot(table(full$WeekDay),col="blue",main="Original Distribution of Weekday")
full$WeekDay<-as.character(full$WeekDay)
full[full$WeekDay %in% c("Friday","Saturday","Sunday"),]$WeekDay<-"Weekend"
full$WeekDay<-as.factor(full$WeekDay)
corrplot(chisq.test(full$IsBadBuy,full$WeekDay)$residuals,is.cor = FALSE)
barplot(table(full$WeekDay),col="blue",main="Original Distribution of Weekday")
set.seed(1234)
WeekDay<-naiveBayes(IsBadBuy ~ WeekDay,full)
WeekDay
WeekDay_df<-as.data.frame(WeekDay$tables)
names(WeekDay_df)[1]<-"IsBadBuy"
names(WeekDay_df)[2]<-"WeekDay"
names(WeekDay_df)[3]<-"Freq"
WeekDay_df
str(full$WeekDay)
full$WeekDay_Prob<-0
for(i in 1:5) {
x<-levels(full$WeekDay)[i]
print(x)
prob<-log(WeekDay_df[WeekDay_df$IsBadBuy==0 & WeekDay_df$WeekDay==x,]$Freq)-log(WeekDay_df[WeekDay_df$IsBadBuy==1 & WeekDay_df$WeekDay==x,]$Freq)
print(prob)
full[full$WeekDay==x,]$WeekDay_Prob<-prob
}
full$WeekDay<-NULL
#---------------PurchDay
table(full$PurchDay)
chi_pday<-chisq.test(full$IsBadBuy,full$PurchDay)
chi_pday
par(mfrow=c(2,2))
corrplot(chi_pday$residuals,is.cor = FALSE)
barplot(table(full$PurchDay),col="blue",main="Original Distribution of Weekday")
full$PurchDay<-as.character(full$PurchDay)
full[full$PurchDay < 11,]$PurchDay<-"Blue"
full[full$PurchDay >= 11 & full$PurchDay<=21,]$PurchDay<-"Red"
full[!full$PurchDay %in% c("Red","Blue"),]$PurchDay<-"Other"
full$PurchDay<-as.factor(full$PurchDay)
chisq.test(full$IsBadBuy,full$PurchDay)
corrplot((chisq.test(full$IsBadBuy,full$PurchDay))$residuals,is.cor = FALSE)
barplot(table(full$PurchDay),col="blue",main="New Distribution of Purchday")
set.seed(1234)
PurchDay<-naiveBayes(IsBadBuy ~ PurchDay,full)
PurchDay
PurchDay_df<-as.data.frame(PurchDay$tables)
names(PurchDay_df)[1]<-"IsBadBuy"
names(PurchDay_df)[2]<-"PurchDay"
names(PurchDay_df)[3]<-"Freq"
PurchDay_df
str(full$PurchDay)
full$PurchDay_Prob<-0
for(i in 1:3) {
x<-levels(full$PurchDay)[i]
print(x)
prob<-log(PurchDay_df[PurchDay_df$IsBadBuy==0 & PurchDay_df$PurchDay==x,]$Freq)-log(PurchDay_df[PurchDay_df$IsBadBuy==1 & PurchDay_df$PurchDay==x,]$Freq)
print(prob)
full[full$PurchDay==x,]$PurchDay_Prob<-prob
}
full$PurchDay<-NULL
#-----------VehicleAge
table(full$VehicleAge)
chi_vage<-chisq.test(full$IsBadBuy,full$VehicleAge)
chi_vage
par(mfrow=c(2,1))
corrplot(chi_vage$residuals,is.corr = FALSE)
full[full$VehicleAge==0,"VehicleAge"]<-1
full$VehicleAge<-as.factor(full$VehicleAge)
chisq.test(full$IsBadBuy,full$VehicleAge)
corrplot(chisq.test(full$IsBadBuy,full$VehicleAge)$residuals,is.corr = FALSE)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.