How to get the type of value by key?

this is a very specific question, say I have an interface Ifa like

interface Ifa {
  A: string;
  B: number;
  C: boolean;
...
}

I want to create another type from Ifa, and it should be one of the

[A, number], [B, string], [C, boolean] ...

I want to use it in a partial update function which take multiple [key, newValue] to update the original value of that key. I hope user can be told which type of newValue they should pass when they typed the key.

is this possible in typescript?

How to eliminate duplicate array of array? [duplicate]

I have array like this below

[[0,0,1],
[0,0,3]
[0,0,3]//duplicate
[0,1,3]
[1,0,0]
[1,2,1]
[1,2,1]//duplicate
[2,2,2]]

I want to make array like this below,

[[0,0,1],
[0,0,3]
[0,1,3]
[1,0,0]
[1,2,1]
[2,2,2]]

At first, I tried with this, but it returns []

 myarray = myarray.filter(
     (element,index,self) =>self.findIndex((e) => {
         e[0] == element[0] && 
         e[1] == element[1] && 
         e[2] == element[2] 
      }) === index 
 )

How can I make this work?

SVG animate tag breaks the path d tag

When we use dynamic values ​​in the D property of the Path tag and have an animation, this reactivity in the D property stops working.

Using dynamic values on D property and use animation with .
Hope the new D values still working after animation

Here’s an example
Codepen

<button id="btnStartAnimation">Start</button>
<span class="dvalue"></span>
<svg
  width="200"
  height="100"
  viewBox="0 0 52.916665 26.458333"
  version="1.1">
  
  <path id="elPath" d="m 3.0230713,3.0230713 h 8.6091807 v 3.0887902 l 30.822183,0.3285947 0.06572,-3.4173849 H 50.20927 V 23.855974 H 3.0230713 Z">
  
    <animate
      id="animation"
      attributeName="d"
      attributeType="XML"
      dur=".5s"
      fill="freeze"
      begin="indefinite"
      from="m 3.0230713,3.0230713 h 8.6091807 v 3.0887902 l 30.822183,0.3285947 0.06572,-3.4173849 H 50.20927 V 23.855974 H 3.0230713 Z"
      to="m 3.0230713,3.0230713 h 23.2645037 v 3.0887902 l 16.16686,0.3285947 0.06572,-3.4173849 H 50.20927 V 23.855974 H 3.0230713 Z" />
  </path>
    
</svg>

Blazor Arrow key prevention in combo box

when filtering the dropdown list in combo, the typed value is being replaced by the dropdown values when navigating with Arrow Up and Arrow Down keys. i want to preserve the typed value until the user explicitly selects an item.

How to do it in blazor

I have tried as below but still not work

private string _typeValue;

public async void KeyPressed(KeyboardEventArgs args)
{
    if (args.Key == "ArrowUp" || args.Key == "ArrowDown")
    {
        if (_comboSelector != null)
        {
            RestoreTypedValue();
            

        }
        else if (args.Key != "Enter")
        {
        _typedValue = SelectedDataItem?.TextValue ?? string.Empty;
        }
    }
}

private void RestoreTypedValue()
{
    
    if (!string.IsNullOrEmpty(_typedValue))
    {
        SelectedDataItem.TextValue = _typedValue;
        StateHasChanged();
    }
}
 public async Task OnFiltering(FilteringEventArgs value)
 {
     try
     {
         if (UIElement.IsCd02 == 1)
         {
             if (value.Text != null && value.Text.Length >= this.MinLengthTerm) 
             {
                  _typeValue=value.Text;
                 await this.ReadCombo(value.Text);
             }
             else 
             {
                 this.DataCollection = this.InitialCollection;
             }
         }
         else 
         {
             if (value.Text != null && value.Text.Length >= 2)
             {
                 value.PreventDefaultAction = true;
                 var query = new Query().Where(new WhereFilter()
                 {
                     Field = "TextValue",
                     Operator = "contains",
                     value = value.Text,
                     IgnoreCase = true
                 });
                 query = !string.IsNullOrEmpty(value.Text) ? query : new Query();
                 _typeValue=value.Text;
                 await _comboSelector.FilterAsync(DataCollection, query);
             }
             else
             {
                 this.DataCollection = this.InitialCollection;
             }
         }                
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }

How to hide the search results if the search input is empty in js?

Right now the search results are hidden by default/onload/onrefresh via CSS. Results will only shows up if you search in the input field and hit enter or if you hit the button. For example try to search “Social” and hit enter It will shows one item, then delete the text in the input field and hit enter the results supposed to be hidden because the input field is empty. How can i do that?

Here is the codes:

$(function() {  
    $('.stores-search-not-found').hide();
    $(".stores-input-search").on('keyup', function (e) {
        if (e.key === 'Enter' || e.keyCode === 13) {
            e.preventDefault();
            const filter = $(this).val();
            search(filter);
        }
        
    });
    $('#cta-search-button').on('click', function (e) {
        const filter = $('#stores-input-search').val();
        search(filter);
    })
});

function search(filter){    
    var count = 0;
    if (count == 0) {
        $('.stores-search-not-found').hide();
    }
    $('.stores-search-lists .card').each(function() {
        if ($(this).text().search(new RegExp(filter, "i")) < 0) {
            $(this).hide(); 
            if (count == 0) {
                $('.stores-search-not-found').show();
            } else {
                $('.stores-search-not-found').hide();
            }         
        }        
        else {
            $(this).show(); 
            //$(this).css('display','block');
            count++;
            
        }
    });  
}
.stores-search-lists {
  font-size: 1rem;
}
.stores-search-lists .card {
  background-color:gray;
  padding: 1rem;
  margin: 1rem;
  color: white;
  display: none;
}
.stores-search-not-found {
  padding: 3rem 1rem;
}



/* =========================
   GENERAL STYLES 
   NOT RELATED TO THE DEMO
============================ */

*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {  
  --clr-primary: #ee6352;
  --clr-secondary: #d16e8d;
  --clr-accent: #F7F7FF;
  --clr-gradient: linear-gradient(-90deg, var(--clr-primary), var(--clr-secondary));
  --ff-title: bungee, sans-serif;
  --ff-body: canada-type-gibson,sans-serif;
  --fw-body: 300;
  --fw-bold: 800;
  --fw-title: 400;
  --fw-number: 800;
}

body {
  min-height: 100vh;
  font-family: var(--ff-body);
  font-weight: var(--fw-body);
  font-size: 1.25rem;
  padding: 0;
  margin: 0;
}

a {
  color: inherit;
}

a:hover,
a:focus {
  color: var(--clr-accent);
}

:focus {
  outline: 5px solid var(--clr-accent);
  outline-offset: 3px;
}
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<div style="display: block;">
<!-- search input -->
  <input class="stores-input-search" type="text" id="stores-input-search" placeholder="Search for anything">
<button class="cta-search-button" id="cta-search-button">Button</button>

  <!-- list -->
  <div class="stores-search-lists">
      <div class="card">
        <h4>Social</h4>
        <p>Social Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat, ut. </p>
      </div>
      <div class="card">
        <h4>Security</h4>
        <p>Security Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto obcaecati eum reprehenderit qui deleniti pariatur suscipit labore. Veniam, magnam laboriosam. </p>
      </div>
      <div class="card">
        <h4>System</h4>
        <p> System Lorem ipsum dolor sit amet consectetur adipisicing elit. Ea, repellat praesentium magnam quis repudiandae aliquam ipsum necessitatibus quas tempora in consectetur, quibusdam porro laudantium quisquam voluptas minima officia vitae natus. </p>
      </div>
  </div>


  <!-- feedback -->
  <div class="stores-search-not-found" aria-live="polite">No matching results. Try changing your search terms.</div>
  
  </div>

How to export data to CSV with correct formatting for IDs and timestamps without converting numbers to strings?

I am working on a software application that needs to export data in CSV format. However, I’ve encountered a couple of issues:

Timestamps: When exported, the timestamp fields don’t display in the desired format.
enter image description here

Long IDs: Long numeric IDs are displayed in scientific notation, which makes them hard to read.
enter image description here

To address this, I added t (tab) after each field during export. This forces the timestamps and IDs to display correctly as text in the CSV file.

enter image description here

However, this also converts numeric fields (like integers and floats) to strings, which prevents operations like calculating averages or sums directly in the CSV.

enter image description here

Is there a better way to export data so that:

Timestamps and long IDs display correctly in their original formats.
Numeric fields remain numeric and usable for calculations?
Any advice or examples would be greatly appreciated. Thank you!

DELPHI Android: Store values ​captured in JavaScript and put in Delphi variables

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.WebBrowser, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Edit,
  Androidapi.JNIBridge, Androidapi.JNI.WebKit, Androidapi.JNI.JavaTypes;

type
  TJavaScriptResultEvent = procedure(Sender: TObject; const JavaScriptResult: string) of object;

  TJavaScriptValueCallback = class(TJavaLocal, JValueCallback)
  private
    FOnResult: TJavaScriptResultEvent;
  public
    { JValueCallback }
    procedure onReceiveValue(value: JObject); cdecl;
  public
    property OnResult: TJavaScriptResultEvent read FOnResult write FOnResult;
  end;

  TForm1 = class(TForm)
    WebBrowser: TWebBrowser;
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    FJavaScriptValueCallback: TJavaScriptValueCallback;
    procedure NewDateResultHandler(Sender: TObject; const AJavaScriptResult: string);
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

uses
  Androidapi.Helpers;

{ TJavaScriptValueCallback }

procedure TJavaScriptValueCallback.onReceiveValue(value: JObject);
begin
  if Assigned(FOnResult) then
    FOnResult(Self, JStringToString(TJString.Wrap(value)).DeQuotedString('"'));
end;

{ TForm1 }

constructor TForm1.Create(AOwner: TComponent);
begin
  inherited;
  FJavaScriptValueCallback := TJavaScriptValueCallback.Create;
end;

destructor TForm1.Destroy;
begin
  FJavaScriptValueCallback.Free;
  inherited;
end;

procedure TForm1.NewDateResultHandler(Sender: TObject; const AJavaScriptResult: string);
begin
  Edit1.Text := AJavaScriptResult;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  LWebView: JWebView;
begin
  if Supports(WebBrowser, JWebView, LWebView) then
  begin
    FJavaScriptValueCallback.OnResult := NewDateResultHandler;
    LWebView.evaluateJavascript(StringToJString('document.getElementById("ID").innerHTML;'), FJavaScriptValueCallback);
  end;
end;

end.

Until then, this code can capture “an element” of the HTML page. I need to store other values. Starting from this Script, how could you do this? store another value in Edit2.Text, Edit3.Text?

I’m using FMX.TWebBrowser.Navigate to access the page. With JavaScript, I select the element I need the value from, I play it inside the function that converts it to String, using these Androidapi libraries, that would be it.

I would like to store it in a TStringList, Array, something like that, to be able to display it in Firemonkey forms.

ER_BAD_FIELD_ERROR

I was supposed to make a new table by the name of “newtable” in the database and then add “DepartmentName” to it FROM new_dev_db.departmentmaster and once its done we have to update the isServiceable code to 2 if done properly using sequalize and the bulk create and bulk update and the hooks module. and if the creation or updtae is not done throw a error message “Database query error” and the details of the error and the error message should be displayed in the console as well.

    const http = require('http');
const { Sequelize, DataTypes } = require('sequelize');

const dbConfig = {
  host: 'h',
  user: 'pre',
  database: 'new',
  password: 'h',
};


const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
  host: dbConfig.host,
  dialect: 'mysql',
  logging: false,
});
const NewTable = sequelize.define('newtable', {
  DepartmentName: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  isServiceable: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
}, {
  tableName: 'newtable',
});

const DepartmentMaster = sequelize.define('departmentmaster', {
  DepartmentName: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  isServiceable: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
}, {
  tableName: 'departmentmaster',
});

const processBulkOperations = async () => {
  const transaction = await sequelize.transaction();
  try {
    const departments = await DepartmentMaster.findAll();
    const departmentData = departments.map(dept => ({
      DepartmentName: dept.DepartmentName,
      isServiceable: dept.isServiceable,  
    }));

    await NewTable.bulkCreate(departmentData, { transaction });

  
    await NewTable.update(
      { isServiceable: 2 },
      { where: {}, transaction }
    );

    await transaction.commit();
  } catch (error) {
    await transaction.rollback();
    console.error('Database query error:', error);
    throw new Error('Database query error');
  }
};

const server = http.createServer(async (req, res) => {
  try {
    await sequelize.authenticate();
    await sequelize.sync();

    await processBulkOperations();

    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ message: 'Bulk operations completed successfully' }));
  } catch (error) {
    res.statusCode = 500;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ error: 'Database query error', details: error.message }));
  }
});

server.listen(3001, () => {
  console.log('Server running at http://localhost:3001/');
});

But its showing error

 code: 'ER_BAD_FIELD_ERROR',
    errno: 1054,
    sqlState: '42S22',
    sqlMessage: "Unknown column 'id' in 'field list'",
    sql: 'SELECT `id`, `DepartmentName`, `isServiceable`, `createdAt`, `updatedAt` FROM `departmentmaster` AS `departmentmaster`;',
    parameters: undefined

I already tried whether this is available in the table as a field or not, and its already there

How to reuse mutler settings to specify a different folder for a route

I initialize MutlerModule to app.module:

MulterModule.registerAsync({
    imports: [ ConfigModule ],
    inject: [ ConfigService ],

    async useFactory(configService: ConfigService)
    {
        const uploadFolder = configService.get<IConfig[ "uploadFolder" ]>("uploadFolder");

        return {
            storage: diskStorage({
                destination: uploadFolder,
                filename(req, file, cb)
                {
                    const filename = `${ Date.now() }-${ file.originalname }`;

                    cb(null, filename);
                }
            })
        };
    }
}),

In uploadFolder we have uploads. Further for some route I want to save not in uploads but in uploads/category, how can I do it without duplicating the code?

What I need to change somewhere that the files that are sent to this route go to uploads/category

@Controller("category")
export class CategoryController
{
    @UseInterceptors(FileInterceptor("image"))
    @Post()
    async create(
        @UploadedFile(
            new ParseFilePipeBuilder()
                .addFileTypeValidator({ fileType: ALLOWED_IMAGE_TYPES.join() })
                .addMaxSizeValidator({ maxSize: MAX_FILE_SIZE_BYTES })
                .build({
                    fileIsRequired: false,
                    errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY
                })
        )
        image
    )
    {
        console.log(image);
    }
}

How to Get the Pixel Coordinates on a Map Image Based on Mouse Position in a Three.js 3D Globe?

I’m working on a 3D globe using a Three.js-based library, and I’ve mapped a high-resolution image (Map.jpg with dimensions 18000×9000) onto the globe as a texture.

I can already convert the mouse position on the canvas to:

Canvas coordinates.
Latitude and longitude (geographical coordinates).
Now, I need to determine the pixel coordinates on the Map.jpg image corresponding to the mouse position. Essentially, I want to map the mouse’s geographical coordinates (latitude and longitude) to the pixel coordinates of the Map.jpg file.

How can I calculate this accurately? Any tips or code examples would be greatly appreciated. Thanks!

document.getElementById('screen').addEventListener('mousemove', (event) => {
const rect = event.target.getBoundingClientRect();
const mouse = new THREE.Vector2(
((event.clientX - rect.left) / rect.width) * 2 - 1,
-((event.clientY - rect.top) / rect.height) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, map.camera);
const sphere = new THREE.Sphere(new THREE.Vector3(0, 0, 0), radius);
const intersection = new THREE.Vector3();
if (raycaster.ray.intersectSphere(sphere, intersection)) {
    let longitude = Math.atan2(intersection.z, intersection.x) * (180 / Math.PI);
    let latitude = Math.asin(intersection.y / radius) * (180 / Math.PI);
}
});

How to add CSS transition to mask

I am trying to add a transition to the mask effect like this example:
https://bricksforge.io/

I have added the transition both on co-pattern__overlay where the mask is and to the :root where the css variables updated on the mousemove are.

const cursor = document.querySelector('.hero');
cursor.addEventListener('mousemove', (event) => {
  const rect = cursor.getBoundingClientRect();
  const mouseX = ((event.clientX - rect.left) / rect.width) * 100 + '%';
  const mouseY = ((event.clientY - rect.top) / rect.height) * 100 + '%';

  document.documentElement.style.setProperty('--mouse-x', mouseX);
  document.documentElement.style.setProperty('--mouse-y', mouseY);
});
:root {
  --mouse-x: 0px;
  --mouse-y: 0px;
  transition: --mouse-x 0.3s ease, --mouse-y 0.3s ease;
}

.co-pattern__overlay {
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  pointer-events: none;
  background-color: #0f1218;
  z-index: 1;
  transition: all 0.5s ease;
}

.co-pattern__overlay {
  mask: radial-gradient(circle at var(--mouse-x) var(--mouse-y), transparent 20px, black 350px);
  -webkit-mask: radial-gradient(circle at var(--mouse-x) var(--mouse-y), transparent 20px, black 350px);
}
<div class="hero">
  <div class="co-pattern__overlay"></div>
</div>

React MUI Image src safety

The user gives the image URL for the avatar and image components. They can give svg, jpeg, and even any files such as exe. Is there a security risk if the browser is given any online resource to be loaded in the component? if so how to improve the security.

<Avatar alt={row} src={row.avatarUrl} /> 

Datatables Buttons filename prompt function not canceling

I’m using DataTables and I’m adding buttons to download the table. Since I have multiple buttons (csv, excel, etc.) and I want more than one of them to prompt for a file name with a proposed value, I want to use a common function for each to stay DRY.

When I use the code from this answer with an anonymous function, it works as I expect.

filename: function(){
    const filename = prompt("Please enter your file name", "");
    if (filename != null) {
        return filename;
    }
}

But when I move that to a named function, everything works except that when I cancel the prompt dialog, the file is downloaded with a default name download.csv. I want it to cancel the prompt and the download.

function propose_filename () {
    const date = new Date()
    const proposed = $(document).prop('title') + " " + date.toISOString()
    const filename = prompt("Please enter your file name", proposed)
    if (filename != null) {
        return filename;
    }
}

And I’m using it here:

layout: {
    bottomStart: {
        buttons: [
            {
                extend: 'csv',
                filename: propose_filename
            },
            {
                extend: 'excel',
                filename: propose_filename
            },
        ]
    }
}

For demonstration, these JSFiddles use a different table, etc., but have my propose_filename function. Both the anonymous function and the named function work correctly. One notable difference between these and my non-working code is that the JSFiddle uses the dom feature of DataTables which is deprecated while I’m using the layout feature. Since I tried to make it use layout without any luck it may imply that JSFiddle is using DataTables 1 (and I don’t know how to tell or change it. My code is using DataTables 2 and the layout option.

The Excel button is the one that prompts for a filename.

JSFiddle Anonymous function

JSFiddle Named function

How can I make the cancel flow all the way through?

Using e.clientX and e.clientX for ordering draggable elements horizontally and vertically in a single DIV container with overflow in vanilla JS

I have been spending the entire evening trying to implement e.clientX as well as e.clientY into this “drag n’ drop” code.

My draggable elements append horizontally in a high container (groupPanel) and will flow into the next row once 100% width have been used up.

The code below works only until the first draggable element flows into the next row. I have tried to work with CSS (grid and flexbox) but nothing achieved the former functionality.

I have rewritten the code to place additional DIV containers in rows as placement areas for the elements; that works just fine, but is not really what I want, as I am looking to spend quite some time into developing a logic for best dynamic usage of space before folding / flowing.

I have tried to pass e.clientY into the function getDragAfterElement as well and calculated the shortest combined offset to the closest vertical and horizontal draggable elements, but the positions of the resulting afterElements made no sense at all and flickered upon mousemovement.

Is there something that can be done, to leave the type of code below, but have it work even after elements flow to further rows?

Or should I abandon the plan and use a completely different approach with full x y control?

// Drag n Drop
function dragDropp() {
    const draggables = document.querySelectorAll('.draggable')
    const dragContainers = document.querySelectorAll('.groupPanel')

    draggables.forEach(draggable => {
        draggable.addEventListener('dragstart', () => {
            draggable.classList.add('dragging');
        })
        draggable.addEventListener('dragend', () => {
            draggable.classList.remove('dragging')
            saveOrder()
        })
    })
    dragContainers.forEach(groupPanel => {
        groupPanel.addEventListener('dragover', e => {
            e.preventDefault()
            const afterElement = getDragAfterElement(groupPanel, e.clientX)
            let draggable = document.querySelector('.dragging')

            if (afterElement == null) {
                groupPanel.appendChild(draggable)
            } else {
                groupPanel.insertBefore(draggable, afterElement)
            }
        })
    })
}

function getDragAfterElement(container, x) {
    const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')];

    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect();
        const offset = x - box.left - box.width / 2;
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child };
        } else {
            return closest;
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element
}