Snippets Collections
import io
import pandas as pd
import requests
if 'data_loader' not in globals():
    from mage_ai.data_preparation.decorators import data_loader
if 'test' not in globals():
    from mage_ai.data_preparation.decorators import test


@data_loader
def load_data_from_api(*args, **kwargs):
    """
    Template for loading data from API
    """
    url = 'https://github.com/DataTalksClub/nyc-tlc-data/releases/download/yellow/yellow_tripdata_2021-01.csv.gz'
    
    taxi_dtypes = {
        'VendorID': pd.Int64Dtype(),
        'passenger_count': pd.Int64Dtype(),
        'trip_distance': float,
        'RatecodeID': pd.Int64Dtype(),
        'store_and_fwd_flag': str,
        'PULocationID': pd.Int64Dtype(),
        'DOLocationID': pd.Int64Dtype(),
        'payment_type': pd.Int64Dtype(),
        'fare_amount': float,
        'extra': float,
        'mta_tax': float,
        'tip_amount': float,
        'tolls_amount': float,
        'improvement_surcharge': float,
        'total_amount': float,
        'congestion_surcharge': float
    }

    parse_dates = ['tpep_pickup_datetime', 'tpep_dropoff_datetime']

    return pd.read_csv(url, sep=",", compression="gzip", dtype=taxi_dtypes, parse_dates=parse_dates)

@test
def test_output(output, *args) -> None:
    """
    Template code for testing the output of the block.
    """
    assert output is not None, 'The output is undefined'
    //Use the ability if it is ready.
    public bool Use(int abilityNum)
    {
        //Is it ready?
        if (IsReady() == false)
            return false;
        //Use the power.
        ParentHero.UsePower(PowerUsed);
        //Apply the damage (or healing is the damage is negative).
        if (ParentHero.Target.TakeDamage(DamageDone) == true)
            ParentHero.Target = ParentHero.FindTarget(); //If the target is dead, find a new one.

        //TODO: Add needed flags or other functionality for abilities that don't just do
        //damage or affect more than one target (AoE, heals, dodges, blocks, stuns, etc.)
        abilityUses += 1.0f;
        
        //if the ability is the Flipper Smash, Knockback the enemy
        if(abilityNum == 2)
        {
            //change position of enemy 2 units to the right
            ParentHero.Target.transform.position = new Vector3(ParentHero.Target.transform.position.x + 2.0f, ParentHero.Target.transform.position.y, ParentHero.Target.transform.position.z);
        }

        //if ability is Fur Bomb, AoE attack
        if(abilityNum == 5)
        {
            //find all enemies
            var enemies = FindObjectsOfType<Enemy>();
            //go check all the enemies in round
            foreach (Enemy enemy in enemies)
            {
                //if there are other enemies within range
                if (enemy.transform.position.x <= (ParentHero.transform.position.x + 10.0f) && enemy.transform.position.x >= (ParentHero.transform.position.x - 10.0f))
                {
                    //and is not the already targetted enemy
                    if(enemy != ParentHero.Target)
                    {
                        //take decreased damage
                        enemy.TakeDamage(DamageDone - 5.0f);
                    }
                }
            }
        }

        //Put the ability on cooldown.
        CooldownLeft = CooldownTime;
        return true;
    }
<div class="col-xs-3">
    <?= $form->field($model, 'fecha')->widget(
            DatePicker::classname(),
            [
                'language' => 'es',
                'removeButton' => false,
                'options' => [
                    'placeholder' => 'Fecha:',
                    'class' => 'form-control',
                    'id' => 'fecha_desde-input',
                    'onchange' => 'buscarProyeccion(this.value)'
                ],
                'pluginOptions' =>
                [
                    'startDate' => '01-01-2000',
                    //'startDate' => date('d-m-Y'),
                    'autoclose' => true,
                    'format' => 'dd-mm-yyyy',
                ]
            ]
            )->label('Fecha'); ?>

    </div>
SELECT
  `tabGL Entry`.`posting_date` AS `posting_date`,                -- 1
  `tabGL Entry`.`voucher_type` AS `voucher_type`,                -- 2
  `tabGL Entry`.`voucher_no` AS `voucher_no`,                    -- 3
  `tabGL Entry`.`account` AS `account`,                          -- 4
  `tabGL Entry`.`party` AS `party`,                              -- 5
  `tabGL Entry`.`against` AS `against`,                          -- 6
  `tabSales Invoice Item`.`item_name` AS `sales_item`,           -- 7
  LPAD(FORMAT(`tabSales Invoice Item`.`qty`, 2), 15, ' ') AS `sales_qty`,  -- 8 (right-aligned)
  FORMAT(`tabSales Invoice Item`.`rate`, 2) AS `sales_rate`,     -- 9
  `tabPurchase Invoice Item`.`item_name` AS `pur_item`,          -- 10
  LPAD(FORMAT(`tabPurchase Invoice Item`.`qty`, 2), 15, ' ') AS `pur_qty`,  -- 11 (right-aligned)
  FORMAT(`tabPurchase Invoice Item`.`rate`, 2) AS `pur_rate`,    -- 12
  LPAD(FORMAT(`tabGL Entry`.`debit`, 2), 15, ' ') AS `debit`,    -- 13 (right-aligned)
  LPAD(FORMAT(`tabGL Entry`.`credit`, 2), 15, ' ') AS `credit`,  -- 14 (right-aligned)
  LPAD(
    FORMAT(
      SUM(`tabGL Entry`.`debit` - `tabGL Entry`.`credit`) OVER (
        PARTITION BY `tabGL Entry`.`account`, `tabGL Entry`.`party`
        ORDER BY `tabGL Entry`.`posting_date`, `tabGL Entry`.`voucher_no`, `tabGL Entry`.`name`
      ),
      2
    ),
    15,
    ' '
  ) AS `balance`                                                 -- 15 (right-aligned)
FROM
  `tabGL Entry`
LEFT JOIN `tabSales Invoice Item` ON `tabGL Entry`.`voucher_no` = `tabSales Invoice Item`.`parent`
LEFT JOIN `tabPurchase Invoice Item` ON `tabGL Entry`.`voucher_no` = `tabPurchase Invoice Item`.`parent`
WHERE
  `tabGL Entry`.`posting_date` BETWEEN %(start_date)s AND %(end_date)s
  AND `tabGL Entry`.`account` LIKE %(account)s
  AND `tabGL Entry`.`company` = %(company)s
  AND `tabGL Entry`.`party_type` = %(party_type)s
  AND `tabGL Entry`.`party` = %(party)s
  AND `tabGL Entry`.`is_cancelled` = 0
ORDER BY
  `tabGL Entry`.`posting_date` ASC,
  `tabGL Entry`.`voucher_no` ASC,
  `tabGL Entry`.`name` ASC;
------------------------------------------------------------------------------


Filters:::::

No.
Label
Fieldtype
Fieldname
Mandatory
Options

1
start_date
Date
start_date


2
end_date
Date
end_date


3
company
Link
company

Company

4
Account
Link
account

Account

5
party_type
Link
party_type

Party Type

6
Party
Dynamic Link
party

party_type

SELECT
  `tabGL Entry`.`posting_date` AS `posting_date`,                -- 1
  `tabGL Entry`.`voucher_type` AS `voucher_type`,                -- 2
  `tabGL Entry`.`voucher_no` AS `voucher_no`,                    -- 3
  `tabGL Entry`.`account` AS `account`,                          -- 4
  `tabGL Entry`.`party` AS `party`,                              -- 5
  `tabGL Entry`.`against` AS `against`,                          -- 6
  `tabSales Invoice Item`.`item_name` AS `sales_item`,           -- 7
  LPAD(FORMAT(`tabSales Invoice Item`.`qty`, 2), 15, ' ') AS `sales_qty`,  -- 8 (right-aligned)
  FORMAT(`tabSales Invoice Item`.`rate`, 2) AS `sales_rate`,     -- 9
  LPAD(FORMAT(`tabGL Entry`.`debit`, 2), 15, ' ') AS `debit`,    -- 13 (right-aligned)
  LPAD(FORMAT(`tabGL Entry`.`credit`, 2), 15, ' ') AS `credit`,  -- 14 (right-aligned)
  LPAD(
    FORMAT(
      SUM(`tabGL Entry`.`debit` - `tabGL Entry`.`credit`) OVER (
        PARTITION BY `tabGL Entry`.`account`, `tabGL Entry`.`party`
        ORDER BY `tabGL Entry`.`posting_date`, `tabGL Entry`.`voucher_no`, `tabGL Entry`.`name`
      ),
      2
    ),
    15,
    ' '
  ) AS `balance`                                                 -- 15 (right-aligned)
FROM
  `tabGL Entry`
LEFT JOIN `tabSales Invoice Item` ON `tabGL Entry`.`voucher_no` = `tabSales Invoice Item`.`parent`
WHERE
  `tabGL Entry`.`posting_date` BETWEEN %(start_date)s AND %(end_date)s
  AND `tabGL Entry`.`account` LIKE %(account)s
  AND `tabGL Entry`.`company` = %(company)s
  AND `tabGL Entry`.`party_type` = %(party_type)s
  AND `tabGL Entry`.`party` = %(party)s
  AND `tabGL Entry`.`is_cancelled` = 0
ORDER BY
  `tabGL Entry`.`posting_date` ASC,
  `tabGL Entry`.`voucher_no` ASC,
  `tabGL Entry`.`name` ASC;

--------------------------------------------------


No.
Label
Fieldtype
Fieldname
Mandatory
Options

1
start_date
Date
start_date


2
end_date
Date
end_date


3
company
Link
company

Company

4
Account
Link
account

Account

5
party_type
Link
party_type

Party Type

6
Party
Dynamic Link
party

party_type
SELECT
  `tabGL Entry`.`posting_date` AS `posting_date`,                -- 1
  `tabGL Entry`.`voucher_type` AS `voucher_type`,                -- 2
  `tabGL Entry`.`voucher_no` AS `voucher_no`,                    -- 3
  `tabGL Entry`.`account` AS `account`,                          -- 4
  `tabGL Entry`.`party` AS `party`,                              -- 5
  `tabGL Entry`.`against` AS `against`,                          -- 6
  `tabPurchase Invoice Item`.`item_name` AS `pur_item`,          -- 10
  LPAD(FORMAT(`tabPurchase Invoice Item`.`qty`, 2), 15, ' ') AS `pur_qty`,  -- 11 (right-aligned)
  FORMAT(`tabPurchase Invoice Item`.`rate`, 2) AS `pur_rate`,    -- 12
  LPAD(FORMAT(`tabGL Entry`.`debit`, 2), 15, ' ') AS `debit`,    -- 13 (right-aligned)
  LPAD(FORMAT(`tabGL Entry`.`credit`, 2), 15, ' ') AS `credit`,  -- 14 (right-aligned)
  LPAD(
    FORMAT(
      SUM(`tabGL Entry`.`debit` - `tabGL Entry`.`credit`) OVER (
        PARTITION BY `tabGL Entry`.`account`, `tabGL Entry`.`party`
        ORDER BY `tabGL Entry`.`posting_date`, `tabGL Entry`.`voucher_no`, `tabGL Entry`.`name`
      ),
      2
    ),
    15,
    ' '
  ) AS `balance`                                                 -- 15 (right-aligned)
FROM
  `tabGL Entry`
LEFT JOIN `tabPurchase Invoice Item` ON `tabGL Entry`.`voucher_no` = `tabPurchase Invoice Item`.`parent`
WHERE
  `tabGL Entry`.`posting_date` BETWEEN %(start_date)s AND %(end_date)s
  AND `tabGL Entry`.`account` LIKE %(account)s
  AND `tabGL Entry`.`company` = %(company)s
  AND `tabGL Entry`.`party_type` = %(party_type)s
  AND `tabGL Entry`.`party` = %(party)s
  AND `tabGL Entry`.`is_cancelled` = 0
ORDER BY
  `tabGL Entry`.`posting_date` ASC,
  `tabGL Entry`.`voucher_no` ASC,
  `tabGL Entry`.`name` ASC;






No.
Label
Fieldtype
Fieldname
Mandatory
Options

1
start_date
Date
start_date


2
end_date
Date
end_date


3
company
Link
company

Company

4
Account
Link
account

Account

5
party_type
Link
party_type

Party Type

6
Party
Dynamic Link
party

party_type

SELECT
  `tabGL Entry`.`posting_date` AS `posting_date`,                -- 1
  `tabGL Entry`.`voucher_type` AS `voucher_type`,                -- 2
  `tabGL Entry`.`voucher_no` AS `voucher_no`,                    -- 3
  `tabGL Entry`.`account` AS `account`,                          -- 4
  `tabGL Entry`.`party` AS `party`,                              -- 5
  `tabGL Entry`.`against` AS `against`,                          -- 6
  `tabSales Invoice Item`.`item_name` AS `sales_item`,           -- 7
  LPAD(FORMAT(`tabSales Invoice Item`.`qty`, 2), 15, ' ') AS `sales_qty`,  -- 8 (right-aligned)
  FORMAT(`tabSales Invoice Item`.`rate`, 2) AS `sales_rate`,     -- 9
  `tabPurchase Invoice Item`.`item_name` AS `pur_item`,          -- 10
  LPAD(FORMAT(`tabPurchase Invoice Item`.`qty`, 2), 15, ' ') AS `pur_qty`,  -- 11 (right-aligned)
  FORMAT(`tabPurchase Invoice Item`.`rate`, 2) AS `pur_rate`,    -- 12
  LPAD(FORMAT(`tabGL Entry`.`debit`, 2), 15, ' ') AS `debit`,    -- 13 (right-aligned)
  LPAD(FORMAT(`tabGL Entry`.`credit`, 2), 15, ' ') AS `credit`,  -- 14 (right-aligned)
  LPAD(
    FORMAT(
      SUM(`tabGL Entry`.`debit` - `tabGL Entry`.`credit`) OVER (
        PARTITION BY `tabGL Entry`.`account`, `tabGL Entry`.`party`
        ORDER BY `tabGL Entry`.`posting_date`, `tabGL Entry`.`voucher_no`, `tabGL Entry`.`name`
      ),
      2
    ),
    15,
    ' '
  ) AS `balance`                                                 -- 15 (right-aligned)
FROM
  `tabGL Entry`
LEFT JOIN `tabSales Invoice Item` ON `tabGL Entry`.`voucher_no` = `tabSales Invoice Item`.`parent`
LEFT JOIN `tabPurchase Invoice Item` ON `tabGL Entry`.`voucher_no` = `tabPurchase Invoice Item`.`parent`
WHERE
  `tabGL Entry`.`posting_date` BETWEEN %(start_date)s AND %(end_date)s
  AND `tabGL Entry`.`account` LIKE %(account)s
  AND `tabGL Entry`.`company` = %(company)s
  AND `tabGL Entry`.`is_cancelled` = 0
ORDER BY
  `tabGL Entry`.`posting_date` ASC,
  `tabGL Entry`.`voucher_no` ASC,
  `tabGL Entry`.`name` ASC;
-------------------------------------------------


Filters:
Label		start_date
Fieldtype	Date
Fieldname	start_date
Mandatory	
Options	
	
	
Label		end_date
Fieldtype	Date
Fieldname	end_date
Mandatory	
Options	
	
	
Label		company
Fieldtype	Link
Fieldname	company
Mandatory	
Options		Company
	
	
Label		Account
Fieldtype	Link
Fieldname	account
Mandatory	
Options		Account
Dim dbsCurrent As Database, dbsContacts As Database 
Set dbsCurrent = CurrentDb 
Set dbsContacts = DBEngine.Workspaces(0).OpenDatabase("Contacts.mdb")
// Genereer een random veelvoud van 10 tussen min (inclusief) en max (exclusief)
37
function randomMultipleOf10(min, max) {
38
  let randomNumber = random(min / 10, max / 10);
39
  let roundedNumber = Math.floor(randomNumber);
40
  return roundedNumber * 10;
41
}
<style>
.content-hide {
    display: none;
}

.details-area {
    max-height: 70px;
    overflow: hidden;
    transition: max-height 0.5s ease;
}

.show-more, .show-less {
cursor: pointer;
}

</style>

<script type="text/javascript">
var $ = jQuery;
$(document).ready(function() {
    $('.show-more').on('click', function(event) {
        event.preventDefault();
        var profileCard = $(this).closest('.profile-card');
        var detailsArea = profileCard.find('.details-area');
        
        $(this).addClass('content-hide');
        profileCard.find('.show-less').removeClass('content-hide');

        detailsArea.css('max-height', detailsArea[0].scrollHeight + 'px'); // Rozwijanie
    });

    $('.show-less').on('click', function(event) {
        event.preventDefault();
        var profileCard = $(this).closest('.profile-card');
        var detailsArea = profileCard.find('.details-area');
        
        $(this).addClass('content-hide');
        profileCard.find('.show-more').removeClass('content-hide');
        
        detailsArea.css('max-height', '70px'); // Zwijanie
    });
});
</script>
    function showPreview(event){
  if(event.target.files.length > 0){
    var src = URL.createObjectURL(event.target.files[0]);
    var preview = document.getElementById("file-ip-1-preview");
    preview.src = src;
    preview.style.display = "block";
  }
}
//profilepage component
//html
<div class="container-fluid" style="margin-top: 60px;">
  <div class="row justify-content-start">
    <!-- Back Button -->
    <div class="col-6">
      <button class="btn btn-link" (click)="goBack()">
        <i class="bi bi-arrow-left-circle"></i> Back
      </button>
    </div>

    <!-- My Profile Heading -->
    <div class="col-6">
      <h2 class="text-left">My Profile</h2>
    </div>

    <!-- Left Side Menu -->
    <div class="col-md-3">
      <h5 class="small-heading">
        <i class="bi bi-bell-fill"></i>
        Notifications
      </h5>
      <!-- Notification placeholder -->
      <div class="card mt-3">
        <div class="card-body">
          <div *ngIf="unredeemedRewards.length === 0" class="notification-item">
            <span>No Notifications</span>
          </div>
          <div *ngFor="let reward of unredeemedRewards" class="notification-item">
            <span>{{ reward.reward_Type_Name }}</span>
            <button class="btn btn-sm btn-primary" (click)="openRedeemModal(reward)">Redeem</button>
          </div>
        </div>
      </div>
    </div>

    

    <!-- Vertical Line Separator -->
    <div class="col-md-1">
      <div class="vertical-line"></div>
    </div>

    <!-- Right Side Form -->
    <div class="col-md-6">
      <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
        <h5 class="small-heading">
          <i class="bi bi-house-gear-fill"></i>
          Personal Details
        </h5>
        <div class="text-center mb-3">
          <div class="profile-photo-wrapper">
            <img [src]="userProfileImage" alt="Profile Photo" class="img-fluid rounded-circle profile-photo" *ngIf="userProfileImage">
            <div class="edit-photo-wrapper">
              <a href="#" (click)="enableEditMode($event)" class="edit-link">Edit</a>
              <label [class.disabled-icon]="!isEditMode" for="photoUpload" class="photo-upload-icon">
                <i class="bi bi-camera"></i>
              </label>
            </div>
            <input type="file" id="photoUpload" formControlName="photo" class="d-none" (change)="onPhotoChange($event)" [readonly]="!isEditMode" >
          </div>
        </div>
        

        <br>

      
        <div class="row">
          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="name" class="form-label">Name</label>
              <input type="text" class="form-control" id="name" formControlName="name" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['name'].invalid && (profileForm.controls['name'].dirty || profileForm.controls['name'].touched)" class="alert">
                <div *ngIf="profileForm.controls['name'].errors?.['required']">Name is required.</div>
                <div *ngIf="profileForm.controls['name'].errors?.['minlength']">Name must be at least 3 characters long.</div>
                <div *ngIf="profileForm.controls['name'].errors?.['maxlength']">Name must be at most 50 characters long.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">            
              <label for="surname" class="form-label">Surname</label>
              <input type="text" class="form-control" id="surname" formControlName="surname" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['surname'].invalid && (profileForm.controls['surname'].dirty || profileForm.controls['surname'].touched)" class="alert">
                <div *ngIf="profileForm.controls['surname'].errors?.['required']">Surname is required.</div>
                <div *ngIf="profileForm.controls['surname'].errors?.['minlength']">Surname must be at least 3 characters long.</div>
                <div *ngIf="profileForm.controls['surname'].errors?.['maxlength']">Surname must be at most 50 characters long.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="email" class="form-label">Email Address</label>
              <input type="email" class="form-control" id="email" formControlName="email" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['email'].invalid && (profileForm.controls['email'].dirty || profileForm.controls['email'].touched)" class="alert">
                <div *ngIf="profileForm.controls['email'].errors?.['required']">Email is required.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="phoneNumber" class="form-label">Contact Number</label>
              <input type="text" class="form-control" id="phoneNumber" formControlName="phoneNumber" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['phoneNumber'].invalid && (profileForm.controls['phoneNumber'].dirty || profileForm.controls['phoneNumber'].touched)" class="alert">
                <div *ngIf="profileForm.controls['phoneNumber'].errors?.['required']">Contact number is required.</div>
                <div *ngIf="profileForm.controls['phoneNumber'].errors?.['maxlength']">Contact number must be a valid 10-digit number.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="physical_Address" class="form-label">Physical Address</label>
              <input type="text" class="form-control" id="physical_Address" formControlName="physical_Address" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['physical_Address'].invalid && (profileForm.controls['physical_Address'].dirty || profileForm.controls['physical_Address'].touched)" class="alert">
                <div *ngIf="profileForm.controls['physical_Address'].errors?.['required']">Physical address is required.</div>
                <div *ngIf="profileForm.controls['physical_Address'].errors?.['maxlength']">Physical address must be at most 255 characters long.</div>
              </div>
            </div>
          </div>
        </div>

        <div class="d-flex justify-content-end">
          <button type="button" class="btn btn-primary me-2" (click)="openSaveModal()" [disabled]="!isEditMode">Save</button>
          <button type="button" class="btn btn-info" (click)="changePassword()" [disabled]="!isEditMode">Change Password</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Save Confirmation Modal -->
<div class="modal fade" id="saveConfirmationModal" tabindex="-1" role="dialog" aria-labelledby="saveConfirmationModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="saveConfirmationModalTitle">Save Changes</h5>
      </div>
      <div class="modal-body">
        Are you sure you want to update your profile details?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="dismissModal()">Cancel</button>
        <button type="button" class="btn btn-primary" (click)="confirmSave()">Confirm</button>
      </div>
    </div>
  </div>
</div>

<!-- Error Modal -->
<div class="modal fade" id="errorModal" tabindex="-1" role="dialog" aria-labelledby="errorModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="errorModalTitle">Error</h5>
      </div>
      <div class="modal-body">
        Please enter a valid input for the following fields:
        <ul id="errorList"></ul>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" (click)="dismissErrorModal()">OK</button>
      </div>
    </div>
  </div>
</div>

<!-- Redeem Reward Modal -->
<div class="modal fade" id="redeemRewardModal" tabindex="-1" role="dialog" aria-labelledby="redeemRewardModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="redeemRewardModalTitle">Redeem Reward</h5>
      </div>
      <div class="modal-body">
        Are you sure you want to redeem the reward {{ selectedReward?.reward_Type_Name }}?
        <p>{{ selectedReward?.reward_Criteria }}</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="dismissRedeemModal()">No</button>
        <button type="button" class="btn btn-primary" (click)="confirmRedeem()">Yes</button>
      </div>
    </div>
  </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="successModalTitle">Success</h5>
        <button type="button" class="close" (click)="dismissSuccessModal()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        Congratulations! You've successfully redeemed this reward {{ selectedReward?.reward_Type_Name }}. Please contact the gym for further instructions.
      </div>
    </div>
  </div>
</div>

//ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { UserService } from '../Services/userprofile.service';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { Member, updateUser } from '../shared/update-user';
import { Subscription, catchError } from 'rxjs';
import { RewardRedeemViewModel, UnredeemedRewardModel } from '../shared/reward';
import { RewardService } from '../Services/reward.service';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

declare var $: any; // Import jQuery

@Component({
  selector: 'app-profile-page',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './profile-page.component.html',
  styleUrls: ['./profile-page.component.css']
})
export class ProfilePageComponent implements OnInit, OnDestroy {
  profileForm: FormGroup;
  user: updateUser | undefined;
  member: Member | undefined;
  isEditMode = false;
  errorMessage = '';  
  userProfileImage: string | null = null;
  unredeemedRewards: UnredeemedRewardModel[] = [];
  selectedReward: UnredeemedRewardModel | null = null;

  private userSubscription: Subscription | undefined;
  private memberSubscription: Subscription | undefined;
  private redeemSubscription: Subscription | undefined;
  
  constructor(
    private userService: UserService,
    private rewardService: RewardService,
    private router: Router,
    private fb: FormBuilder
  ) {
    this.profileForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      name: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]],
      surname: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]],
      phoneNumber: ['', [Validators.required, Validators.maxLength(10)]],
      physical_Address: ['', [Validators.required, Validators.maxLength(255)]],
      photo: ['']
    });
  }

  ngOnInit(): void {
    const userId = JSON.parse(localStorage.getItem('User') || '{}').userId;
    console.log('User ID from local storage:', userId);
    this.loadUserProfile(userId);
    this.isEditMode = false;
  }

  ngOnDestroy(): void {
    // Clean up subscriptions
    if (this.userSubscription) {
      this.userSubscription.unsubscribe();
    }
    if (this.memberSubscription) {
      this.memberSubscription.unsubscribe();
    }
    if (this.redeemSubscription) {
      this.redeemSubscription.unsubscribe();
    }
  }

  loadUserProfile(userId: number): void {
    this.userSubscription = this.userService.getUserById(userId).pipe(
      catchError(error => {
        console.error('Error fetching user profile:', error);
        return [];
      })
    ).subscribe({
      next: (result) => {
        console.log('User data received:', result);
        this.user = result; 
        // Log photo to debug
        console.log('Photo:', this.user.photo);        
        // Set user profile image
        this.userProfileImage = `data:image/jpeg;base64,${this.user.photo}`;
        this.profileForm.patchValue(this.user);
        console.log('User:', this.user);

        if (this.user.user_Type_ID === 3) {
          this.loadMemberProfile(userId);
        }
      },
      complete: () => {
        console.log('getUserById subscription completed');
      }
    });
  }

  loadMemberProfile(userId: number): void {
    this.memberSubscription = this.userService.getMemberByUserId(userId).pipe(
      catchError(error => {
        console.error('Error fetching member profile:', error);
        return [];
      })
    ).subscribe({
      next: (result) => {
        this.member = result;
        if (this.member) {
          this.loadUnredeemedRewards(this.member.Member_ID);
        }
      },
      complete: () => {
        console.log('getMemberByUserId subscription completed');
      }
    });
  }

  clearForm() {
    this.profileForm.reset();
  }

  enableEditMode(event: Event) {
    event.preventDefault();
    this.isEditMode = true;
    this.profileForm.enable();
  }

  openSaveModal() {
    if (this.profileForm.invalid) {
      this.showValidationErrors();
      $('#errorModal').modal('show');
      return;
    }
    $('#saveConfirmationModal').modal('show');
  }

  showValidationErrors() {
    const invalidFields: string[] = [];
    Object.keys(this.profileForm.controls).forEach(key => {
      const controlErrors = this.profileForm.get(key)?.errors;
      if (controlErrors) {
        Object.keys(controlErrors).forEach(errorKey => {
          invalidFields.push(`${key}: ${errorKey}`);
        });
      }
    });
    this.errorMessage = `Please enter a valid input: ${invalidFields.join(', ')}`;
  }

  dismissModal() {
    $('#saveConfirmationModal').modal('hide');
  }

  dismissErrorModal() {
    $('#errorModal').modal('hide');
  }

  confirmSave() {
    this.dismissModal();
    this.onSubmit();
    this.isEditMode = false; // Disable edit mode after confirmation
  }

  onSubmit() {
    if (this.profileForm.valid) {
      const userId = JSON.parse(localStorage.getItem('User')!).userId;
      this.userService.updateUser(userId, this.profileForm.value).subscribe({
        next: (result) => {
          console.log('User to be updated:', result);
          this.router.navigateByUrl(`/ProfilePage/${userId}`);
          alert('Successfully updated profile');
        },
        error: () => {
          console.error('Error updating user profile:');
          alert('Error updating profile');
        }
      });
    }
  }

  onPhotoChange(event: Event): void {
    if (!this.isEditMode) return;

    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const reader = new FileReader();
      reader.onload = (e: any) => {
        this.userProfileImage = e.target.result; // Update the image source
        this.profileForm.patchValue({ photo: e.target.result }); // Update the form control
      };
      reader.readAsDataURL(input.files[0]);
    }
  }

  goBack() {
    const userTypeId = JSON.parse(localStorage.getItem('User')!).userTypeId;
    const userId = JSON.parse(localStorage.getItem('User')!).userId;
    if (userTypeId === 1) {  // Ensure userTypeID is compared as string
      this.router.navigateByUrl(`/OwnerHome/${userId}`);
    } else if (userTypeId === 2) {
      this.router.navigateByUrl(`/EmployeeHome/${userId}`);
    } else if (userTypeId === 3) {
      this.router.navigateByUrl(`/Home/${userId}`);
    }
  }

  changePassword() {
    this.router.navigateByUrl('/ChangePasswordPage');
  }

  // Method to load rewards for the current user
  loadUnredeemedRewards(memberId: number): void {
    this.rewardService.getUnredeemedRewardsForMember(memberId).subscribe(
      rewards => {
        this.unredeemedRewards = rewards;
      },
      error => {
        console.error('Error fetching unredeemed rewards:', error);
      }
    );
  }

  // Method to open redeem modal for a reward
  openRedeemModal(reward: UnredeemedRewardModel): void {
    this.selectedReward = reward;
    $('#redeemRewardModal').modal('show');
  }

  // Method to dismiss redeem modal
  dismissRedeemModal(): void {
    $('#redeemRewardModal').modal('hide');
  }

  // Method to confirm redeeming a reward
  confirmRedeem(): void {
    if (!this.selectedReward) {
      return;
    }
    const redeemRequest = new RewardRedeemViewModel();
    redeemRequest.MemberId = this.member?.Member_ID ?? 0;
    redeemRequest.RewardId = this.selectedReward.reward_ID;

    // Call backend service to redeem the reward
    this.redeemSubscription = this.rewardService.redeemReward(redeemRequest).subscribe({
      next: () => {
        // Show success modal on successful redemption
        $('#successModal').modal('show');
        // Remove redeemed reward from the list
        this.unredeemedRewards = this.unredeemedRewards.filter(r => r.reward_ID !== this.selectedReward?.reward_ID);
      },
      error: (error) => {
        console.error('Error redeeming reward:', error);
        // Handle error
      }
    });
    this.dismissRedeemModal();
  }

  // Method to dismiss success modal
  dismissSuccessModal(): void {
    $('#successModal').modal('hide');
  }
}


//models
export class updateUser
{
   name!: string;
   surname!: string;
   email!: string;
   physical_Address!: string;
   phoneNumber!: string;
   photo!: string;
   user_Type_ID!: number;
}
export class UserProfile
{   
   User_ID !: number
   Id!: number
   Name!: string
   Surname!: string
   ID_Number!: string
   Email!: string
   Physical_Address!: string
   PhoneNumber!: string
   Photo!: string
   UserName!: string
   PasswordHash!: string
   Date_of_Birth!: Date
   User_Status_ID !: number
   User_Type_ID!: number
}

//service
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, catchError, map, throwError } from 'rxjs';
import { UserProfile } from '../Models/UserProfile';
import { LoginUser } from '../shared/login-user';
import { User } from '../shared/user';
import { updateUser } from '../shared/update-user';
import { UserTypeViewModel } from '../shared/user-type-vm';
import { UserViewModel } from '../shared/search-user';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  constructor(private http: HttpClient) {}
  endPoint: string = "https://localhost:7185/api/";

  //User EndPoints
  // RegisterUser(registerUser: RegisterUser) {
  //   return this.http.post(`${this.endPoint}User/Register`, registerUser, this.httpOptions);
  // }

  RegisterUser(formData: FormData): Observable<any> {
    return this.http.post(`${this.endPoint}User/Register`, formData);
  }

  
  LoginUser(loginUser: LoginUser): Observable<User> {
    return this.http.post<User>(`${this.endPoint}User/Login`, loginUser, this.httpOptions);
  }

  getAllUsers(): Observable<UserProfile[]> {
    return this.http.get<UserProfile[]>(this.endPoint + "User/getAllUsers");
  }

  getUserById(userId: number): Observable<updateUser> {
    return this.http.get<updateUser>(`${this.endPoint}User/getUserById/${userId}`)
    .pipe(map(result => result))
  }

  getMemberByUserId(userId: number): Observable<any> {
    return this.http.get<any>(`${this.endPoint}User/GetMemberByUserId/${userId}`, this.httpOptions);
  }

  updateUser(userId: string, user: updateUser): Observable<any> {
    return this.http.put(`${this.endPoint}User/editUser/${userId}`, user, { responseType: 'text' })
    .pipe(
      map((response: string) => {
        try {
          // Attempt to parse as JSON if the response is in JSON format
          return JSON.parse(response);
        } catch {
          // Return as plain text if not JSON
          return response;
        }
      }),
      catchError(this.handleError)
    );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(() => new Error('Something bad happened; please try again later.'))    
  }
  
  searchUsers(criteria: string): Observable<UserViewModel[]> {
    return this.http.get<UserViewModel[]>(`${this.endPoint}User/SearchUsers?criteria=${criteria}`);
  }

  deleteUser(userId: number): Observable<string> {
    return this.http.delete<string>(`${this.endPoint}User/deleteUser/${userId}`);
  }

  //UserType EndPoints
  addUserType(userType: UserTypeViewModel): Observable<UserTypeViewModel> {
    return this.http.post<UserTypeViewModel>(`${this.endPoint}UserType/addUserType`, userType, this.httpOptions);
  }

  getAllUserTypes(): Observable<UserTypeViewModel[]> {
    return this.http.get<UserTypeViewModel[]>(`${this.endPoint}UserType/getAllUserTypes`, this.httpOptions);
  }

  getUserTypeById(id: number): Observable<UserTypeViewModel> {
    return this.http.get<UserTypeViewModel>(`${this.endPoint}UserType/getUserTypeById/${id}`, this.httpOptions);
  }

  updateUserType(userTypeId: number, userTypeName: string): Observable<void> {
    const body = { user_Type_Name: userTypeName }; // Correctly format the body as JSON
    return this.http.put<void>(`${this.endPoint}UserType/updateUserType/${userTypeId}`, body, this.httpOptions);
  }

  deleteUserType(id: number): Observable<void> {
    return this.http.delete<void>(`${this.endPoint}UserType/deleteUserType/${id}`, this.httpOptions);
  }
}
selector:hover .elementor-heading-title {
     color: #F9F2E8;
     transition-duration: 300ms
}
<a href="https://maticz.com/ecommerce-app-development">Ecommerce App Development</a>
function clearRow() {
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();  
  var editSheet = ss.getSheetByName("EDIT"); 
  var lastRowEdit = editSheet.getLastRow();
  
  for(var i = 2; i <= lastRowEdit; i++)
  {  
   
   if(editSheet.getRange(i,1).getValue() == 'TRAIN')
   {
     editSheet.getRange('A' + i + ':C' + i).clear();     
   }    
  }    
}

function deleteRow() {
  
  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var editSheet = ss.getSheetByName("EDIT"); 
  var lastRowEdit = editSheet.getLastRow();
  
  for(var i = 2; i <= lastRowEdit; i++)
  {  
   
   if(editSheet.getRange(i,1).getValue() == 'TRAIN')
   {
     editSheet.deleteRow(i);    
   }
    
  }    
}

function insertRow() {
  
  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var editSheet = ss.getSheetByName("EDIT"); 
  var lastRowEdit = editSheet.getLastRow();
  
  for(var i = 2; i <= lastRowEdit; i++)
  {  
   
   if(editSheet.getRange(i,1).getValue() == 'TRAIN')
   {
     editSheet.insertRowAfter(i);    
   }
    
  }   
}

function replaceRow() {
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();  
  var editSheet = ss.getSheetByName("EDIT"); 
  var lastRowEdit = editSheet.getLastRow();
  
  for(var i = 2; i <= lastRowEdit; i++)
  {  
   
   if(editSheet.getRange(i,1).getValue() == 'TRAIN')
   {
     editSheet.getRange('A' + i + ':C' + i).setValues([['AIRPLANE', 'ORANGE', 30]]);     
   }    
  }   
}

https://codewithcurt.com/how-to-clear-delete-insert-and-replace-row-using-google-apps-script/
<a href="https://maticz.com/insurance-software-development">Insurance Software Development</a>
SHOW search_path;
SET search_path TO Schema1, public;
<a href="https://maticz.com/enterprise-blockchain-development”>Enterprise Blockchain Development </a>
Binance Exchange Clone script is a pre-fabricated software package that permits entrepreneurs to embark on their own crypto exchange platform like Binance. Like any other business, the revenue streams of Binance clone rely on various aspects, including the business model, target audience, and services they offer. 

Trading Fees

Users pay a charge to the platform for every trade they make. The fee varies depending on the exchange platform, and it can be a fixed amount or percentage of trading volume. 

Listing Fees

The Fee can vary depending on the crypto exchange platform and the popularity of the project. These fees generated from the binance clone can be the source of revenue for the platform, especially if the platform gains popularity among crypto projects. 

Withdrawal Fees

Withdrawal fees are charged to users when they withdraw their cryptocurrencies from the platform. The fee can vary depending on the cryptocurrency and the platform. 

Margin trading fees

Margin trading is a feature that allows users to trade with borrowed funds. The platform charges a fee for providing the margin trading feature. 

Security token offerings (STOs)

STOs are a type of fundraising method where investors buy security tokens in exchange for funds. The platform charges a fee for hosting STOs. 

Initial Exchange Offering (IEO)

Initial Exchange Offering (IEO) is a fundraising method where cryptocurrency projects sell their tokens directly on an exchange platform. The platform charges a fee for hosting IEOs. 

Advertising and sponsorships

Cryptocurrency exchange platforms can generate revenue from advertising and sponsorships. Projects in the cryptocurrency industry pay for advertising space on the platform.

If you are planning to launch your own cryptocurrency exchange platform and are looking for a Binance clone script, Maticz Technologies is a leading technology solutions provider offering a ready-made Binance clone script solution.
Expand your business potential with Our AI Development Services
Receive scalable AI software development services with Maticz. Our experts are focused in helping our clients to achieve a transformational output by incorporating the latest technologies like machine learning, large language models, deep learning, and augmented reality.
Harness the potential of our experts to fulfill your AI-related business needs.
{
  "pollId": 166,
  "associationId": 58,
  "domainTypeId": 15,
  "title": "Travel Preferences Surve",
  "description": "Understand the health and wellness habits of participants to develop programs that promote better lifestyle choices.",
  "startDate": "2024-07-22T18:30:00",
  "endDate": "2024-07-28T18:30:00",
 
  "pollQuestions": [
    {
      "pollQuestionId": 210,
      "pollId": 0,
      "pollOrSurveyAnswerTypeId": 104,
      "questionContent": "What type of exercise do you prefer or not? ",
      "answers": [
        {
          "pollAnswerId": 1018,
          "answerContent": "Cardio",
          "noOfVotes": 0
        },
        {
          "pollAnswerId": 1019,
          "answerContent": "Strength training",
          "noOfVotes": 0
        },
        {
          "pollAnswerId": 1020,
          "answerContent": "Yoga/Pilates",
          "noOfVotes": 0
        }
      ],
      "answerObj": null
    },
    {
      "pollQuestionId": 211,
      "pollId": 0,
      "pollOrSurveyAnswerTypeId": 104,
      "questionContent": "How many days a week do you engage in physical activity?",
      "answers": [
        {
          "pollAnswerId": 1021,
          "answerContent": "One",
          "noOfVotes": 0
        },
        {
          "pollAnswerId": 1022,
          "answerContent": "Two",
          "noOfVotes": 0
        }
      ],
      "answerObj": null
    }
  ],
  "pollTargetAudience": {
    "pollTargetAudienceId": 139,
    "pollId": 166,
    "pollOrSurveyTargetTypeId": 100,
    "pollTargetId": [
      145,
      140
    ]
  },
  "isPollCreator": true,
  "status": "string",
  "noOfVotes": 0,
  "noOfReports": 0,
  "creatorName": "kiran Reddy",
  "domainTypeName": "Survey"
}
{
  "pollId": 166,
  "associationId": 58,
  "domainTypeId": 15,
  "title": "Travel Preferences Surve",
  "description": "Understand the health and wellness habits of participants to develop programs that promote better lifestyle choices.",
  "startDate": "2024-07-22T18:30:00",
  "endDate": "2024-07-28T18:30:00",
 
  "pollQuestions": [
    {
      "pollQuestionId": 210,
      "pollId": 0,
      "pollOrSurveyAnswerTypeId": 104,
      "questionContent": "What type of exercise do you prefer or not? ",
      "answers": [
        {
          "pollAnswerId": 1018,
          "answerContent": "Cardio",
          "noOfVotes": 0
        },
        {
          "pollAnswerId": 1019,
          "answerContent": "Strength training",
          "noOfVotes": 0
        },
        {
          "pollAnswerId": 1020,
          "answerContent": "Yoga/Pilates",
          "noOfVotes": 0
        }
      ],
      "answerObj": null
    },
    {
      "pollQuestionId": 211,
      "pollId": 0,
      "pollOrSurveyAnswerTypeId": 104,
      "questionContent": "How many days a week do you engage in physical activity?",
      "answers": [
        {
          "pollAnswerId": 1021,
          "answerContent": "One",
          "noOfVotes": 0
        },
        {
          "pollAnswerId": 1022,
          "answerContent": "Two",
          "noOfVotes": 0
        }
      ],
      "answerObj": null
    }
  ],
  "pollTargetAudience": {
    "pollTargetAudienceId": 139,
    "pollId": 166,
    "pollOrSurveyTargetTypeId": 100,
    "pollTargetId": [
      145,
      140
    ]
  },
  "isPollCreator": true,
  "status": "string",
  "noOfVotes": 0,
  "noOfReports": 0,
  "creatorName": "kiran Reddy",
  "domainTypeName": "Survey"
}
#include <stdio.h>

void interchange(int a[], int i, int j) {
    
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

int partition(int a[], int m, int p) {
    int v = a[m];
    int i = m;
    int j = p;

    do {
        while (a[i] <= v && i < j) {
            i++;
        }

        while (a[j] > v && j > i) {
            j--;
        }

        if (i < j) {
            interchange(a, i, j);
        }
    } while (i < j);

    a[m] = a[j];
    a[j] = v;
    return j;
}


void quick_sort(int a[], int p, int q) {
 
    if (p < q) {
      
        int j = partition(a, p, q);

   
        quick_sort(a, p, j - 1);
        quick_sort(a, j + 1, q);
    }
}

int main() {
    int a[] = {3, 6, 8, 10, 1, 2, 1};
    int n = sizeof(a) / sizeof(a[0]);

    quick_sort(a, 0, n - 1);

 
    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");

    return 0;
}
PUT event_heatmap/_settings
{
  "index":{
    "max_result_window": 100000
  }
}
--------------------
const lufthanza = {
  airline: "Lufthanza",
  iataCode: "LH",
  bookings: [],
  book: function (flightNumber, name) {
    this.bookings.push({ flightCode: flightNumber, passenger: name });
    return `${name} booked a flight with this ${this.iataCode} on
	${this.airline} with this ${flightNumber}`;
  },
};

console.log(lufthanza);
console.log(lufthanza.book("KIG808", "David"));


//second object without the function BUT it has the same keys
const etihad = {
  airline: "Etihad",
  iataCode: "EH",
  bookings: [],
};

// create the variable for the book function
const bookingCalc = lufthanza.book;

// create the call on the object that needs that function
bookingCalc.call(etihad, "HLSMSJ", "John");



// using call() to spread into the bookings array from the existing call
const passengerInfo = ['gktu78', 'Kevin']

bookingCalc.call(etihad, ...passengerInfo);

console.log(etihad)
 # dd if=spi.installer.img of=/dev/XXX bs=1M oflag=direct,sync status=progress
<?php get_header(); ?>
 
         
          <div class="page-title page-title-default title-size-large title-design-centered color-scheme-light" style="">
                    <div class="container">
                <h1 class="entry-title title"><?php the_title(); ?>    </h1>
                     <div class="breadcrumbs"><a href="<?php echo get_home_url(); ?>" rel="v:url" property="v:title">Home</a> » <span class="current">Services</span></div><!-- .breadcrumbs -->                                                                        </div>
                </div>
 
 
    <div class="container">
        <div class="row single_serviceSection">
            <div class="col-lg-6">
                <div class="singleServiceContent">
                    <h3>
                        <?php the_title(); ?>
                    </h3>
                    <p>
                        <?php the_content(); ?>
                    </p>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="singleServiceThumbnail">
                    <?php the_post_thumbnail("full"); ?>
                </div>
            </div>
        </div>
        <?php// comments_template(); ?>
    </div>
 
 
 
<?php 
 
get_footer();
 
?>


////////STYLING CSS///////

.single-services .main-page-wrapper > .container {
    max-width: 100%;
}

.single-services .page-title-default {
    width: 100%;
}
.single_serviceSection {
    display: flex;
    flex-direction: row-reverse;
    padding: 100px 0;
} 
<!DOCTYPE html>
<html>
​
<body>
  
<script>
class Car {
  constructor(name) {
    this.brand = name;
  }
​
  present() {
    return 'I have a ' + this.brand;
  }
}
​
class Model extends Car {
  constructor(name, mod) {
    super(name);
    this.model = mod;
  }  
  show() {
    return this.present() + ', it is a ' + this.model
  }
}
​
const mycar = new Model("Ford", "Mustang");
document.write(mycar.show());
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
​
<body>
  
<script>
class Car {
  constructor(name) {
    this.brand = name;
  }
}
​
const mycar = new Car("Ford");
​
document.write(mycar.brand);
</script>
​
</body>
</html>
​
new Card(cardContainer, {
    id: 'instructions',
    icon: 'fa-solid fa-medal',
    title: 'Contests',
    description: 'Where the magic happens! Manage contests and their teams.',
}).click(async () => {
    const modal = await new Modal(null, { id: 'instructions' }).loadContent('index-instructions');
    modal.addButton({
        text: 'OK, got it!',
        close: true,
    })
});
ol.elementor-toc__list-wrapper .elementor-toc__list-item-text-wrapper:before {
    content-visibility: hidden;
}
JavaScript
<script>
document.addEventListener('scroll', function(e) {
var header = document.getElementById('sticky-header');
var scrollTop = window.scrollY || document.documentElement.scrollTop;

if (scrollTop > lastScrollTop) {
// Scroll Down
header.style.transform = 'translateY(-100%)';
} else {
// Scroll Up
header.style.transform = 'translateY(0)';
}
lastScrollTop = scrollTop <= 0 ? 0 : scrollTop; // For Mobile or negative scrolling
}, false);

var lastScrollTop = 0;
</script>

CSS
#sticky-header {
transition: transform 0.3s ease-in-out;
}
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { UserService } from '../Services/userprofile.service';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { Member, updateUser } from '../shared/update-user';
import { Subscription, catchError } from 'rxjs';
import { RewardRedeemViewModel, RewardViewModel, UnredeemedRewardModel } from '../shared/reward';
import { RewardService } from '../Services/reward.service';
import { RewardTypeViewModel } from '../shared/reward';

declare var $: any; // Import jQuery

@Component({
  selector: 'app-profile-page',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './profile-page.component.html',
  styleUrls: ['./profile-page.component.css']
})
export class ProfilePageComponent implements OnInit, OnDestroy {
  profileForm: FormGroup;
  user: updateUser | undefined;
  member!: Member;
  isEditMode = false;
  errorMessage = '';
  userProfileImage: string | ArrayBuffer = ''; // Add this property to store the Base64 image data
  unredeemedRewards: UnredeemedRewardModel[] = [];
  selectedReward: UnredeemedRewardModel | null = null;

  private userSubscription: Subscription | undefined;
  private redeemSubscription: Subscription | undefined;
  

  constructor(
    private userService: UserService,
    private rewardService: RewardService,
    private router: Router,
    private fb: FormBuilder
  ) {
    this.profileForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      name: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]],
      surname: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]],
      phoneNumber: ['', [Validators.required, Validators.maxLength(10)]],
      physical_Address: ['', [Validators.required, Validators.maxLength(255)]],
      photo: ['']
    });
  }

  ngOnInit(): void {
    const userId = JSON.parse(localStorage.getItem('User') || '').userId;
    console.log('User ID from local storage:', userId);
    
    this.userSubscription = this.userService.getUserById(userId).pipe(
      catchError(error => {
        console.error('Error fetching user profile:', error);
        // Handle error
        return []; // Return empty array or default value as per your logic
      })
    ).subscribe({
      next: (result) => {
        console.log('User data received:', result);
        this.user = result;
        this.profileForm.patchValue(this.user);
        
        // Assign userProfileImage
        this.userProfileImage = `data:image/jpeg;base64,${this.user.Photo}`; // Ensure this.user.Photo contains the Base64 data
        
        // Log userProfileImage and user for debugging
        console.log('User Profile Image:', this.userProfileImage);
        console.log('User:', this.user);

        // Check if the user is a member and fetch member details
      if (this.user.User_Type_ID !== 3) {
        this.userService.getMemberByUserId(userId).subscribe(
          memberResult => {
            this.member = memberResult;
            console.log('Member data received:', this.member);
            this.loadUnredeemedRewards(); // Load rewards if the user is a member
          },
          memberError => {
            console.error('Error fetching member data:', memberError);
          }
        );
      }
      },
      complete: () => {
        console.log('getUserById subscription completed');
      }
    });
  
    this.isEditMode = false;
    this.loadUnredeemedRewards();
  }

  ngOnDestroy(): void {
    // Clean up subscriptions
    if (this.userSubscription) {
      this.userSubscription.unsubscribe();
    }
    if (this.redeemSubscription) {
      this.redeemSubscription.unsubscribe();
    }
  }

  clearForm() {
    this.profileForm.reset();
  }

  enableEditMode(event: Event) {
    event.preventDefault();
    this.isEditMode = true;
    this.profileForm.enable();
  }

  openSaveModal() {
    if (this.profileForm.invalid) {
      this.showValidationErrors();
      $('#errorModal').modal('show');
      return;
    }
    $('#saveConfirmationModal').modal('show');
  }

  showValidationErrors() {
    const invalidFields: string[] = [];
    Object.keys(this.profileForm.controls).forEach(key => {
      const controlErrors = this.profileForm.get(key)?.errors;
      if (controlErrors) {
        Object.keys(controlErrors).forEach(errorKey => {
          invalidFields.push(`${key}: ${errorKey}`);
        });
      }
    });
    this.errorMessage = `Please enter a valid input: ${invalidFields.join(', ')}`;
  }

  dismissModal() {
    $('#saveConfirmationModal').modal('hide');
  }

  dismissErrorModal() {
    $('#errorModal').modal('hide');
  }

  confirmSave() {
    this.dismissModal();
    this.onSubmit();
    this.isEditMode = false; // Disable edit mode after confirmation
  }

  onSubmit() {
    if (this.profileForm.valid) {
      const userId = JSON.parse(localStorage.getItem('User')!).userId;
      this.userService.updateUser(userId,this.profileForm.value).subscribe({
        next: (result) => {
          console.log('User to be updated:', result);
          this.router.navigateByUrl(`/ProfilePage/${userId}`);
          alert('Successfully updated profile');
        },
        error: () => {
          console.error('Error updating user profile:');
          alert('Error updating profile');
        }
      });
    }
  }

  onPhotoChange(event: Event): void {
    if (!this.isEditMode) return;

    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const reader = new FileReader();
      reader.onload = (e: any) => {
        this.userProfileImage = e.target.result; // Update the image source
        this.profileForm.patchValue({ photo: e.target.result }); // Update the form control
      };
      reader.readAsDataURL(input.files[0]);
    }
  }

  goBack() {
    const userTypeId = JSON.parse(localStorage.getItem('User')!).userTypeId;
    const userId = JSON.parse(localStorage.getItem('User')!).userId;
    if (userTypeId === 1) {  // Ensure userTypeID is compared as string
      this.router.navigateByUrl(`/OwnerHome/${userId}`);
    } else if (userTypeId === 2) {
      this.router.navigateByUrl(`/EmployeeHome/${userId}`);
    } else if (userTypeId === 3) {
      this.router.navigateByUrl(`/Home/${userId}`);
    }
  }

  changePassword() {
    this.router.navigateByUrl('/ChangePasswordPage');
  }


  // Method to load rewards for the current user
  loadUnredeemedRewards(): void {
    const memberId = this.member.Member_ID;
    this.rewardService.getUnredeemedRewardsForMember(memberId).subscribe(
      rewards => {
        this.unredeemedRewards = rewards;
        console.log('Unredeemed Rewards:', this.unredeemedRewards);
      },
      error => {
        console.error('Error fetching unredeemed rewards:', error);
      }
    );
  }

  // Method to open redeem modal for a reward
  openRedeemModal(reward: UnredeemedRewardModel): void {
    this.selectedReward = reward;
    $('#redeemRewardModal').modal('show');
  }

  // Method to dismiss redeem modal
  dismissRedeemModal(): void {
    $('#redeemRewardModal').modal('hide');
  }

  // Method to confirm redeeming a reward
  confirmRedeem(): void {
    if (!this.selectedReward) {
      return;
    }
    const redeemRequest = new RewardRedeemViewModel();
    redeemRequest.MemberId = this.member?.Member_ID ?? 0;
    redeemRequest.RewardId = this.selectedReward.reward_ID;

    // Call backend service to redeem the reward
    this.redeemSubscription = this.rewardService.redeemReward(redeemRequest).subscribe({
      next: () => {
        // Show success modal on successful redemption
        $('#successModal').modal('show');
        // Remove redeemed reward from the list
        this.unredeemedRewards = this.unredeemedRewards.filter(r => r.reward_ID !== this.selectedReward?.reward_ID);
      },
      error: (error) => {
        console.error('Error redeeming reward:', error);
        // Handle error
      }
    });
    this.dismissRedeemModal();
  }

  // Method to dismiss success modal
  dismissSuccessModal(): void {
    $('#successModal').modal('hide');
  }
}
<script src="https://cdn.jsdelivr.net/gh/studio-freight/lenis@0.2.28/bundled/lenis.js"></script>

<script>
const lenis = new Lenis({
  duration: 1.2,
  easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)), // https://www.desmos.com/calculator/brs54l4xou
  direction: 'vertical', // vertical, horizontal
  gestureDirection: 'vertical', // vertical, horizontal, both
  smooth: true,
  mouseMultiplier: 1,
  smoothTouch: false,
  touchMultiplier: 2,
  infinite: false,
})

//get scroll value
lenis.on('scroll', ({ scroll, limit, velocity, direction, progress }) => {
  console.log({ scroll, limit, velocity, direction, progress })
})

function raf(time) {
  lenis.raf(time)
  requestAnimationFrame(raf)
}

requestAnimationFrame(raf)
</script>
const allValid = [...this.template.querySelectorAll('lightning-input')].reduce((validSoFar, inputField) => {
            inputField.reportValidity();
            return validSoFar && inputField.checkValidity();
        }, true);

        if (allValid) {
            console.log('All fields are valid');
        } else {
            console.log('Please complete all required fields.');
        }
selector {
overflow-x: auto; /* Enables horizontal scrolling if content overflows */
-webkit-overflow-scrolling: touch; /* Smooth scrolling for touch devices */
}
const playBoard = document.querySelector(".play-board");

const scoreElement = document.querySelector(".score");

const highScoreElement = document.querySelector(".high-score");

const controls = document.querySelectorAll(".controls i");

​

let gameOver = false;

let foodX, foodY;

let snakeX = 5, snakeY = 5;

let velocityX = 0, velocityY = 0;

let snakeBody = [];

let setIntervalId;

let score = 0;

​

// Getting high score from the local storage

let highScore = localStorage.getItem("high-score") || 0;

highScoreElement.innerText = `High Score: ${highScore}`;

​

const updateFoodPosition = () => {

    // Passing a random 1 -  value as food position

    foodX = Math.floor(Math.random() * 30) + 1;

    foodY = Math.floor(Math.random() * 30) + 1;

}

​

const handleGameOver = () => {

    // Clearing the timer and reloading the page on game over

    clearInterval(setIntervalId);

    alert("Game Over! Press OK to replay...");

    location.reload();

}
30
​

const changeDirection = e => {

    // Changing velocity value based on key press

    if(e.key === "ArrowUp" && velocityY != 1) {

        velocityX = 0;

        velocityY = -1;

    } else if(e.key === "ArrowDown" && velocityY != -1) {

        velocityX = 0;

        velocityY = 1;

    } else if(e.key === "ArrowLeft" && velocityX != 1) {

        velocityX = -1;

        velocityY = 0;

    } else if(e.key === "ArrowRight" && velocityX != -1) {

        velocityX = 1;

        velocityY = 0;

    }
// Online C compiler to run C program online
#include <stdio.h>

int main() {
    int limit,i,j,tmp;
    int a[1000];
    printf("enter the size of an array\n");
    scanf("%d",&limit);
    printf("enter the value of array\n");
    for(i=0;i<limit;i++){
        scanf("%d",&a[i]);
    }
    for(i=0;i<limit-1;i++){
        for(j=i+1;j<limit;j++){
            if(a[i]>a[j]){
                tmp=a[i];
                a[i]=a[j];
                a[j]=tmp;
            }
        }
    }
    printf("sorted array\n");
    for(i=0;i<limit;i++){
        printf("%d,\t",a[i]);
    }
    
    
    
    return 0;
}
function clearContent() {
  var app = SpreadsheetApp;
  var clearContent = app.getActiveSpreadsheet().getActiveSheet();
  //clearContent.getRange("A1:F11").clear();
  clearContent.getRange("A1:F11").clearFormat();
}
function SetOtherSheets() {
  var app = SpreadsheetApp;
  var SetOtherSheets = app.getActiveSpreadsheet().getActiveSheet();
  
  // เลือกชีทตามชื่อ
  var targetSheet = app.getActiveSpreadsheet().getSheetByName('Sheet20');
  //targetSheet.getRange(1,1).setValue(7);
  var tempNumber = targetSheet.getRange(1,1).getValue();
  // นำค่าไปเขียนไว้ที่ชีทอื่น
  var secondSheet = app.getActiveSpreadsheet().getSheetByName('Sheet19');
  secondSheet.getRange(10,1).setValue(tempNumber);
}
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );

// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );
star

Sat Jul 13 2024 09:37:49 GMT+0000 (Coordinated Universal Time) https://medium.com/analytics-vidhya/getting-started-with-brain-js-39748358aea2

@ZCOMStudios #javascript #brainjs #bash #npm #nodejs

star

Sat Jul 13 2024 08:38:40 GMT+0000 (Coordinated Universal Time)

@hd310

star

Sat Jul 13 2024 08:09:33 GMT+0000 (Coordinated Universal Time) https://tapitra.com/

@outemux

star

Sat Jul 13 2024 06:01:37 GMT+0000 (Coordinated Universal Time)

@mry2khuu #c# #ability #attack

star

Sat Jul 13 2024 00:07:43 GMT+0000 (Coordinated Universal Time)

@roamtravel

star

Fri Jul 12 2024 19:00:10 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Fri Jul 12 2024 18:19:24 GMT+0000 (Coordinated Universal Time)

@Taimoor

star

Fri Jul 12 2024 18:18:25 GMT+0000 (Coordinated Universal Time)

@Taimoor

star

Fri Jul 12 2024 18:17:40 GMT+0000 (Coordinated Universal Time)

@Taimoor

star

Fri Jul 12 2024 18:15:51 GMT+0000 (Coordinated Universal Time)

@Taimoor

star

Fri Jul 12 2024 16:27:39 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/office/vba/api/access.application.currentdb

@rmdnhsn

star

Fri Jul 12 2024 15:55:12 GMT+0000 (Coordinated Universal Time) https://editor.p5js.org/seb_prjcts.be/sketches/dgoadQ2h8

@seb_prjcts_be

star

Fri Jul 12 2024 15:26:52 GMT+0000 (Coordinated Universal Time)

@webisko #javascript

star

Fri Jul 12 2024 15:15:14 GMT+0000 (Coordinated Universal Time)

@alamin005 #javascript

star

Fri Jul 12 2024 15:13:48 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Fri Jul 12 2024 13:25:49 GMT+0000 (Coordinated Universal Time)

@webisko #css

star

Fri Jul 12 2024 13:05:14 GMT+0000 (Coordinated Universal Time) https://maticz.com/ecommerce-app-development

@Ameliasebastian #ecommerceappdevelopmentcompany

star

Fri Jul 12 2024 13:01:33 GMT+0000 (Coordinated Universal Time)

@roamtravel

star

Fri Jul 12 2024 12:40:28 GMT+0000 (Coordinated Universal Time) https://maticz.com/insurance-software-development

@Ameliasebastian #insurancesoftwaredevelopment

star

Fri Jul 12 2024 11:02:41 GMT+0000 (Coordinated Universal Time)

@ClemensBerteld #postgres #postgis #sql

star

Fri Jul 12 2024 10:59:19 GMT+0000 (Coordinated Universal Time) https://maticz.com/enterprise-blockchain-development

@Ameliasebastian #enterpriseblockchain development

star

Fri Jul 12 2024 10:30:32 GMT+0000 (Coordinated Universal Time) https://maticz.com/binance-clone-script

@jamielucas #drupal

star

Fri Jul 12 2024 10:19:41 GMT+0000 (Coordinated Universal Time) https://maticz.com/ai-development-services

@carolinemax ##maticz ##usa #ai_development_company #ai_software_development

star

Fri Jul 12 2024 10:15:10 GMT+0000 (Coordinated Universal Time)

@Ranjith

star

Fri Jul 12 2024 10:09:46 GMT+0000 (Coordinated Universal Time)

@Ranjith

star

Fri Jul 12 2024 09:37:11 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Jul 12 2024 06:42:51 GMT+0000 (Coordinated Universal Time)

@StephenThevar #elasticsearch

star

Fri Jul 12 2024 02:13:42 GMT+0000 (Coordinated Universal Time)

@davidmchale #call() #object

star

Fri Jul 12 2024 00:25:30 GMT+0000 (Coordinated Universal Time) https://tow-boot.org/devices/libreComputer-rocRk3399PcMezzanine.html

@Dewaldt

star

Thu Jul 11 2024 21:37:54 GMT+0000 (Coordinated Universal Time) https://www.makeuseof.com/windows-d3d11-gpu-error/

@mosk_1990

star

Thu Jul 11 2024 20:58:13 GMT+0000 (Coordinated Universal Time)

@wasim_mm1

star

Thu Jul 11 2024 19:37:44 GMT+0000 (Coordinated Universal Time) https://activescienceparts.com/how-many-ribs-do-males-and-females-have/

@darkwebmarket

star

Thu Jul 11 2024 19:11:39 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/tryit.asp?filename

@Black_Shadow #javascript #react.js #html #output #text

star

Thu Jul 11 2024 19:07:48 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/tryit.asp?filename

@Black_Shadow #react.js #javascript #html

star

Thu Jul 11 2024 18:57:24 GMT+0000 (Coordinated Universal Time)

@werlang #javascript

star

Thu Jul 11 2024 18:51:03 GMT+0000 (Coordinated Universal Time) http://127.0.0.1:4111/

@gyg85nax

star

Thu Jul 11 2024 18:49:25 GMT+0000 (Coordinated Universal Time)

@webisko #css

star

Thu Jul 11 2024 18:17:42 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Thu Jul 11 2024 18:10:43 GMT+0000 (Coordinated Universal Time) https://www.vinjegaard.com/tutorial/lenis-smooth-scroll-in-elementor

@webisko #javascript

star

Thu Jul 11 2024 17:47:23 GMT+0000 (Coordinated Universal Time)

@gbritgs

star

Thu Jul 11 2024 17:14:27 GMT+0000 (Coordinated Universal Time)

@webisko #css

star

Thu Jul 11 2024 15:37:50 GMT+0000 (Coordinated Universal Time) http://goatgames.unaux.com/wp-admin/admin.php?page

@rajat #undefined

star

Thu Jul 11 2024 15:30:23 GMT+0000 (Coordinated Universal Time)

@dorado #c

star

Thu Jul 11 2024 15:30:23 GMT+0000 (Coordinated Universal Time) http://goatgames.unaux.com/wp-admin/admin.php?page

@rajat #undefined

star

Thu Jul 11 2024 15:29:44 GMT+0000 (Coordinated Universal Time) http://goatgames.unaux.com/wp-admin/admin.php?page

@rajat #undefined

star

Thu Jul 11 2024 15:29:17 GMT+0000 (Coordinated Universal Time) http://goatgames.unaux.com/wp-admin/admin.php?page

@rajat #undefined

star

Thu Jul 11 2024 15:23:46 GMT+0000 (Coordinated Universal Time)

@roamtravel

star

Thu Jul 11 2024 14:21:01 GMT+0000 (Coordinated Universal Time)

@tokoyami_ds

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension