Jest Mock Imported constant in unit test

Writing unit test on piece of code that uses imported boolean constant. Not able to mock the constant value.

  1. index.d.ts
    export const SOMETHING_OVERWRITE: boolean;

2.Mapper.test.ts

it(‘TEST expected output’, () => {

SOMETHING_OVERWRITE = true;


});

Getting error :
Cannot assign to ‘SOMETHING_OVERWRITE’ because it is an import.ts

How to download images from WKWebView to app not in user gallery iOS swift

I have browser in my app when for which I am using WKWebView. All I want when user long pressed on image I wanna show custom action sheet instead default alert and also when user tapped on download I should be downloaded in app instead of user gallery. I tried different ways none is working exactly as I want below is my code using long press gesture from this code I can get some of images and for some of images its generate error which says

Error Domain=WKErrorDomain Code=4 “A JavaScript exception occurred” UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SecurityError: The operation is insecure., WKJavaScriptExceptionColumnNumber=198, WKJavaScriptExceptionSourceURL=https://www.google.com/search?q=go&prmd=vni&source=lnms&tbm=isch&sa=X&ved=2ahUKEwj9rKbv3uT9AhXlR_EDHeCxDLMQ_AUoA3oECAIQAw&biw=393&bih=588&dpr=3#imgrc=R7mqldixWHBs7M&imgdii=FBBt5tzUNeKRwM, NSLocalizedDescription=A JavaScript exception occurred}

Below is my code which I tried to get images:

  @objc func webViewLongPressed(_ sender: UILongPressGestureRecognizer) {
        longpress = true
        if sender.state == .ended {
            print("Long press Ended")
            let tapLocation = sender.location(in: webView)
            let scaleFactor = webView.frame.width / webView.scrollView.contentSize.width
            let convertedTapLocation = CGPoint(x: tapLocation.x * scaleFactor, y: tapLocation.y * scaleFactor)
            
            webView.evaluateJavaScript("var c = document.createElement('canvas'); var ctx = c.getContext('2d'); var img = document.elementFromPoint((convertedTapLocation.x), (convertedTapLocation.y)); ctx.drawImage(img, 0, 0); var value = c.toDataURL(); value.split(',')[1];") { (result, error) in
                if let imageBase64 = result as? String {
                    let imageData = Data(base64Encoded: imageBase64, options: [])
                    let selectedImage = UIImage(data: imageData!)
                    self.imageView.image = selectedImage
                }
            }

            
        } else if sender.state == .began {
            print("Long press detected.")
        }
    }

can someone please tell me where I am wrong or any other approach for doing this.
help will be appreciated Thanks 🙂

Webpack module not found in react typescript manual set up

I am trying to set up a react project from scratch using typescript, babel and webpack. But when I am trying start my application using npm start it is showing me Webpack module not found error.

This is the error which I am getting

This is my package.json file

{
  "name": "react-ts-nextjs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack serve --config webpack.config.js --open",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.21.3",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "@babel/preset-typescript": "^7.21.0",
    "@types/react": "^18.0.28",
    "@types/react-dom": "^18.0.11",
    "babel-loader": "^9.1.2",
    "html-webpack-plugin": "^5.5.0",
    "typescript": "^5.0.2",
    "webpack": "^5.76.2",
    "webpack-cli": "^5.0.1",
    "webpack-dev-middleware": "^6.0.1",
    "webpack-dev-server": "^4.12.0"
  }
}

This is my webpack.config.js

webpack / webpack.common.js;
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = (env) => {
  const isDevelopment = env.env !== "production";
  return {
    entry: path.resolve(__dirname, "..", "./src/index.tsx"),
    resolve: {
      extensions: [".tsx", ".ts", ".js"],
    },
    module: {
      rules: [
        {
          test: /.(ts|js)x?$/,
          exclude: /node_modules/,
          use: [
            {
              loader: require.resolve("babel-loader"),
              options: {
                plugins: [
                  isDevelopment && require.resolve("react-refresh/babel"),
                ],
              },
            },
          ],
        },
        {
          test: /.css$/,
          use: ["style-loader", "css-loader"],
        },
        {
          test: /.(png|svg|jpg|jpeg|gif)$/i,
          type: "asset/resource",
        },
      ],
    },
    output: {
      path: path.resolve(__dirname, "..", "./build"),
      filename: "bundle.js",
    },
    devServer: {
      contentBase: path.resolve(__dirname, "..", "./build"),
      hot: true,
    },
    plugins: [
      new CleanWebpackPlugin(),
      new HtmlWebpackPlugin({
        template: path.resolve(__dirname, "..", "./src/index.html"),
      }),
      isDevelopment && new ReactRefreshWebpackPlugin(),
    ],
  };
};

This is tsconfig.js

{
  "compilerOptions": {
    "target": "ES5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
    "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
    "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ /* Type declaration files to be included in compilation. */,
    "lib": [
      "DOM",
      "ESNext"
    ] /* Specify library files to be included in the compilation. */,
    "jsx": "react-jsx" /* Specify JSX code generation: 'preserve', 'react-native', 'react' or 'react-jsx'. */,
    "noEmit": true /* Do not emit outputs. */,
    "isolatedModules": true /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */,
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
    "strict": true /* Enable all strict type-checking options. */,
    "skipLibCheck": true /* Skip type checking of declaration files. */,
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
    "resolveJsonModule": true,
    "baseUrl": "src"

    // "allowJs": true /* Allow javascript files to be compiled. Useful when migrating JS to TS */,
    // "checkJs": true /* Report errors in .js files. Works in tandem with allowJs. */,
  },
  "include": ["src/**/*"]
}

Please help me if anyone has any solution for this

Angle to cursor, with different orientation of zero degrees

I’m trying to make a utility function to determine the angle from an element to the mouse cursor, but allow our devs to change where 0 is located. So this needs to work with 0deg through to 360degs.

So I’m trying to write a function that can do that. I have it working for zero at due west, but need to get it working for zero at north, east and south.

It’ surprisingly difficult. I have tried just adding 90deg to the radians with 90° × Ï€/180 = 1.571rad but then struggled to get it back to degrees for the return.

function getAngleToCursor(el, evt, orientation = "north") {
    const mouseX = evt.clientX
    const mouseY = evt.clientY
    
    const elRect = el.getBoundingClientRect()
    const elX = elRect.left + elRect.width / 2
    const elY = elRect.top + elRect.height / 2

    const rads = Math.atan2(mouseY-elY, mouseX-elX)
    let angle = 0

    // Change where zero is located
    switch(orientation) {
        case "west":
            angle = rads * 180 / Math.PI + 180
            break;

        case "north":
            angle = ?
            break;  

        case "east":
            angle = ?
            break;  
        
        case "south":            
            angle = ?
            break;
    }

    return angle
}

Codepen here

make a chrome extension

I’d like to create a Chrome extension that will find the flowing buttons on the current tab and activate them when I press a dedicated key on my keyboard, but the website is not mine! 

{
  "name": "Hotpage Down Extension",
  "version": "1.0",
  "description": "Press 1 to trigger the Hotpage Down button.",
  "manifest_version": 2,
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["content.js"]
  }]
}

chrome.commands.onCommand.addListener(function(command) {
  if (command === "hotpagedown") {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.executeScript(
        tabs[0].id,
        {code: 'document.getElementsByName("Hotpage Down")[0].click();'}
      );
    });
  }
});

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.action === "injectScript") {
      chrome.tabs.executeScript({
        code: request.script
      });
    }
  }
);

How to set default image for dropzone?

I want to set default image to dropzone in Angular 13. I’m using [email protected].

From the backend I get page objects.

I want to set default image dynamically from page object.

Here is my dropzone in HTML:

<dropzone
                      class="col-md-12"
                      style="height: 150px"
                      [config]="imageConfig"
                      (error)="(onUploadError)"
                      (success)="(onUploadSuccess)"
                      (thumbnail)="onThumbnail($event)"
                      #dropzone1
                    >
                    </dropzone>

And here is my init function inside config in TS file:

init: function () {
      const mockFile = { name: 'Filename', size: 12345 };
      const dropzone = this;
      dropzone.emit('addedfile', mockFile);
      dropzone.emit(
        'thumbnail',
        mockFile,
        'http://localhost:8080/generated/attachments/000546000001page.imageSource1on0k07xxe3.png'
      );
    },

How I can pass page object from HTML file to TS init function to set imageSource dynamically?

Thank you!

Fabric.js Dynamic Pattern Brick Layout

I am currently working on converting an image object to a Pattern object using Fabric.js’s dynamic pattern feature. However, I have encountered an issue where the images are being created with a grid layout by default, whereas I want them to be created with a vertical or horizontal brick layout. Unfortunately, I am unable to set the offset value for each row individually and have been unable to find a way to do so. Ideally, I would like to define this offset as adjustable, but I am not sure how to achieve this.


var imageObj = canvas.getActiveObject();

fabric.Image.fromURL(imageObj.img_data.src, function (img) {

  var padding = 0;
  var canvas = canvas;
  var imageObj = canvas.getActiveObject();
  img.scaleToWidth(50);
  var patternSourceCanvas = new fabric.StaticCanvas();
  patternSourceCanvas.add(img);
  patternSourceCanvas.renderAll();
  var pattern = new fabric.Pattern({
      source: patternSourceCanvas.getElement(),
      repeat: 'repeat',
  });
  var rect = new fabric.Rect({
      id: imageObj.id,
      width: imageObj.width, 
      height: imageObj.height,
      fill: pattern
  });
  document.getElementById('img-width').oninput = function () {
      img.scaleToWidth(parseInt(this.value, 10));
      patternSourceCanvas.setDimensions({
        width: img.getScaledWidth() + padding,
        height: img.getScaledHeight() + padding,
      });
      canvas.requestRenderAll();
    };
    document.getElementById('img-angle').oninput = function () {
      img.set('angle', this.value);
      patternSourceCanvas.renderAll();
      canvas.requestRenderAll();
    };
    document.getElementById('img-padding').oninput = function () {
      padding = parseInt(this.value, 10);
      patternSourceCanvas.setDimensions({
        width: img.getScaledWidth() + padding,
        height: img.getScaledHeight() + padding,
      });
      canvas.requestRenderAll();
    };
    document.getElementById('img-offset-x').oninput = function () {
      pattern.offsetX = parseInt(this.value, 10);
      canvas.requestRenderAll();
    };
    document.getElementById('img-offset-y').oninput = function () {
      pattern.offsetY = parseInt(this.value, 10);
      canvas.requestRenderAll();
    };
    document.getElementById('img-repeat').onclick = function () {
      pattern.repeat = this.checked ? 'repeat' : 'no-repeat';
      canvas.requestRenderAll();
    };
  canvas.add(rect);
  canvas.remove(imageObj);
  canvas.setActiveObject(rect);
  canvas.renderAll();
 });

The offset value is applied for the whole pattern, I tried to create it separately for each row or column, but failed.
I want to set an offset value for each row or each column separately. So I want to create brick layout.

How do I store a state object to async storage in React Native?

I’m building a running app in React Native and I want to be able to track daily miles throughout the week. How can I save each day’s milage to local storage when state is an object? The miles are entered in a TextInput and I want to submit them with an onPress in the TouchableOpacity. Also how would I retrieve the day’s milage from async storage?

    const [miles, setMiles] = useState({

    monday: 0,
    tuesday: 0,
    wednesday: 0,
    thursday: 0,
    friday: 0,
    saturday: 0,
    sunday: 0,

});

<View style={styles.weekDayContainer}>
            <View style={styles.milesInput}>
                <Text style={styles.weekDayText}>Monday</Text>
                <TextInput style={styles.weekDayInput}
                    type="number"
                    placeholder="enter miles"
                    keyboardType="numeric"
                    value={miles.monday}
                    onChangeText={(value) => handleChange('monday',value)}
                />
                <TouchableOpacity>
                    <Text>Submit</Text>
                </TouchableOpacity>
            </View>
            <View style={styles.milesInput}>
                <Text style={styles.weekDayText}>Tuesday</Text>
                <TextInput style={styles.weekDayInput}
                    type="number"
                    placeholder="enter miles"
                    keyboardType="numeric"
                    value={miles.tuesday}
                    onChangeText={(value) => handleChange('tuesday', value)}
                />
                <TouchableOpacity>
                    <Text>Submit</Text>
                </TouchableOpacity>
            </View>
            <View style={styles.milesInput}>
                <Text style={styles.weekDayText}>Wednesday</Text>
                <TextInput style={styles.weekDayInput}
                    type="number"
                    placeholder="enter miles"
                    keyboardType="numeric"
                    value={miles.wednesday}
                    onChangeText={(value) => handleChange('wednesday', value)}
                />
                <TouchableOpacity>
                    <Text>Submit</Text>
                </TouchableOpacity>
            </View>
            <View style={styles.milesInput}>
                <Text style={styles.weekDayText}>Thursday</Text>
                <TextInput style={styles.weekDayInput}
                    type="number"
                    placeholder="enter miles"
                    keyboardType="numeric"
                    value={miles.thursday}
                    onChangeText={(value) => handleChange('thursday', value)}
                />
                <TouchableOpacity>
                    <Text>Submit</Text>
                </TouchableOpacity>
            </View>
            <View style={styles.milesInput}>
                <Text style={styles.weekDayText}>Friday</Text>
                <TextInput style={styles.weekDayInput}
                    type="number"
                    placeholder="enter miles"
                    keyboardType="numeric"
                    value={miles.friday}
                    onChangeText={(value) => handleChange('friday', value)}
                />
                <TouchableOpacity>
                    <Text>Submit</Text>
                </TouchableOpacity>
            </View>
            <View style={styles.milesInput}>
                <Text style={styles.weekDayText}>Saturday</Text>
                <TextInput style={styles.weekDayInput}
                    type="number"
                    placeholder="enter miles"
                    keyboardType="numeric"
                    value={miles.saturday}
                    onChangeText={(value) => handleChange('saturday', value)}
                />
                <TouchableOpacity>
                    <Text>Submit</Text>
                </TouchableOpacity>
            </View>
            <View style={styles.milesInput}>
                <Text style={styles.weekDayText}>Sunday</Text>
                <TextInput style={styles.weekDayInput}
                    type="number"
                    placeholder="enter miles"
                    keyboardType="numeric"
                    value={miles.sunday}
                    onChangeText={(value) => handleChange('sunday', value)}
                />
                <TouchableOpacity>
                    <Text>Submit</Text>
                </TouchableOpacity>
            </View>
        </View>

Should I build everytime I make a change in react?

I am trying to experiment with Apache superset, especially the front-end. One thing I am concerned about is the longer time to build. In documentation, they had specified two commands

1. npm run dev-server = cross-env NODE_ENV=development BABEL_ENV=development node –max_old_space_size=4096 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js –mode=development

2. npm run dev = webpack –mode=development –color –watch

When I run the first one, it takes 3 mins to build and I guess I need to build it everytime to look at my changes. Second command builds the files, but there seems to be no server.

What is the way to make it hot reload as I make changes in the code?

Text is cut off when capturing div with html2canvas

//script

case "btn-download": {
        html2canvas(document.getElementById("container-image")).then(function (canvas) {
          var a = document.createElement("a");
          a.href = canvas.toDataURL("image/png");
          a.download = "New image.png";
          a.click();
        });
        break;
      }

//html

<div id="container-image">
      <input id="tab-title" placeholder="Set Title"></textarea>
    </div>

//css

#container-image {
  width: fit-content;
  height: fit-content;
  min-height: 20px;
  background-color: rgb(124, 124, 124);
  text-align: center;
  margin: 0 auto;
  padding: 10px;
  border: 2px solid rgb(255, 255, 255);
  border-radius: 5px;
}

#tab-title {
  font-size: 30px;
  font-weight: bold;
  text-align: center;
  background: none;
  border: none;
  margin-bottom: 10px;
}
#tab-title::placeholder {
  color: rgb(68, 68, 68);
}

In page

Downloaded

I’m creating a button that captures a div, but when I increase the font-size of the input, it cuts off the top of the text.

I tried changing the padding, margin, line-height, etc… in the css, but it didn’t work, and the only way to fix it was to reduce the font size. How can I fix this?

traverse through input and check for blanks. All input must be valid before the form can be submitted

I am using jQuery/javascript. The objective is to make sure that the input time are valid and the form can be submitted if there is no blank and the input is valid. There is a checkbox that overrides the input and makes it valid for submitting.

I tried indexing the row as well as each input to check if it’s valid. one issue is that if I enter one input the form is able to submit. I want to prevent it from submitting until all the input field is filled in and each row start and end time is valid.

screen shot

Overcoming performance issues with background-image for thumbnails

I have a webapp that allows users to take and upload a variable number of photos. It is designed to be offline first since users may not have cell coverage or wifi when using it. I’m currently base64 encoding the pictures they take and storing them both in an in-memory array and persisting them to LocalStorage.

To render the images in the UI, I take the base64 encoded image and use it as a data-url for the background-image property in CSS.

This works fine, except initially rendering the page can take several seconds if the user has uploaded a few large images. It seems like the issue is the data-url.

Since the images do not exist on a server, is there any way to address the performance issues of data-urls client side?

How I’m getting the data-url and rendering it:

{
    const file = this.input.files[0];
    if (!file) {
      return;
    }
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      this.input.value = "";
      this.thumbnail.style["background-image"] = `url(${reader.result})`;
    });
    reader.readAsDataURL(file);
}

This is a simplified snippet. I also store the result and when the user refreshes I do something like this:

for(const image of images) {
  this.thumbnail.style["background-image"] = `url(${image})`;
}

Is there a more performant way to render images from an in-memory array?

How to get random number in range (from 0 to 51) javascript

Is there anyway to generate random number in range?
I’m making Shuffle function for my audio player using React. I got my song.id works well.
But I want to randomly generate a number start with 0 and end with 51 (It can generate 0 and 51).
I tried these but it keep getting dupes:

Math.floor(Math.random() * 52))

jQuery checking dynamically created checkboxes/radiobuttons

I have a form that has dynamically created checkboxes. The checkboxes are stored in the database. Some of the checkboxes can have child items. These will be displayed as soon as we check the checkbox. Check example below
enter image description here

The code for generating these is

function DrawMinorCaseFileCheckboxList() {
var result = "";
$.ajax({
    type: "Post",
    url: "UACWebServices.asmx/GetMinorCaseFileTree",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        var obj = JSON.parse(data.d);
        var parentDivData = '<div class="container">';
        var iii = 0;
        $.each(obj.children, function (i, parentItem) {
            //parentDivData = parentItem.children && parentItem.children.length > 0 ? parentDivData += '<span></span>' : parentDivData
            //if (parentItem.children && parentItem.children.length > 0) {
            //    parentDivData += '<ul style="list-style:none;margin:0;" ><li><input type="checkbox" id="' + parentItem.id + '" class="minor-casefile-info"><label for="option"><strong>' + parentItem.text + '</strong></label>';
            //}
            //else {
            //    parentDivData += '<ul style="list-style:none;margin:0;" ><li><input type="checkbox" id="' + parentItem.id + '" class="minor-casefile-info"><label for="option">' + parentItem.text + '</label>';
            //}

            parentDivData += '<ul class="spCasefileSummaries" style="list-style:none;margin:0;" ><li><input type="checkbox" name="spCasefileSummaries_' + parentItem.id + '" id="spCasefileSummaries_' + parentItem.id + '" idd="' + parentItem.id + '" txt="' + parentItem.text+'" class="minor-casefile-info" > <label for="option">' + parentItem.text + '</label>';
            
            if (parentItem.children && parentItem.children.length > 0) {
                parentDivData += '<ul style="list-style:none;display:none;padding-inline:20px;" ulParentID=' + parentItem.id +'>';
                $.each(parentItem.children, function (i, childItem) {
                    parentDivData += '<li><label><input type="radio" parentId="radiobutton_' + parentItem.id + '" id="minor-casefile-info_' + childItem.id + '" name="minor-casefile-info_' + parentItem.id + '"  value="' + childItem.id +'" class="minor-casefile-info-sub' + parentItem.id + '"> ' + childItem.text + '</label></li>';
                });
                parentDivData += '</ul>';
            }
            parentDivData += '</li></ul>';
            iii++;
        });
        parentDivData += '</div>';
        
        $('#dCaseFile').html(parentDivData);

        $('.minor-casefile-info').change(function () {
            var str = '';
            var id = $(this).attr("idd");
            //console.log($(this));
            //console.log($(this).attr("txt"));

            if (this.checked) {
                $('[ulParentID=' + id + ']').show();
            }
            else {   
                $('[ulParentID=' + id + ']').hide();
                $('[parentId = radiobutton_' + id + ']').prop("checked", false);
                $("#tbCaseFile").valid();
            }
            $(".minor-casefile-info").each(function (i, obj) {
                var headerTitle = $(this).attr("txt");
                if ($(this).prop('checked')) {
                    if ($("[parentid = radiobutton_" + $(this).attr("idd") + "]").length > 0) {
                        str += 'Please select a description of the ' + headerTitle + '<br/>';
                    }
                }
            });
            if (str) {
                $('.trCaseFileInfoMessage').show();
                $('#sCaseFileInfoMessage').html(str);
            }
            else {
                $('.trCaseFileInfoMessage').hide();
                $('#sCaseFileInfoMessage').html('');
            }
        });
    }
});
   }

This is all working fine. When I save the data and come back to the page by clicking Edit I need to populate all the fields on the page that were saved. In my code behind (.cs) I have a function that loads the data from the database and prepopulates all the fields. For the dynamic checkboxes I am calling a JS function to check the checkboxes and radiobuttons but they are coming as undefined

The .cs method calling the js function

ClientScript.RegisterStartupScript(this.GetType(), "populateCaseFileSummaries", "populateCaseFileSummaries('" + LIST_Minor_Casefile_Info + "', '" + LIST_Minor_Casefile_Info_Sub + "');", true);

and the js function

function populateCaseFileSummaries(parentCheckbox, childRadioBtn) {
var parentItems = parentCheckbox.split(",");
console.log('parentItems = ' + parentItems);
$.each(parentItems, function (index, value) {
    $("#spCasefileSummaries_" + value).prop("checked", true);
    //document.getElementById('spCasefileSummaries_' + value).checked = true;
    console.log('parent: - ' + '#spCasefileSummaries_' + value);
    console.log('isChecked: ' + $('#spCasefileSummaries_' + value).prop('checked'));
});
var childItems = childRadioBtn.split(",");
$.each(childItems, function (index, value) {
    console.log('Child: - ' + value);
});
}

Here is the console logs

enter image description here

Can someone please tell me how I can access these checkboxes and radiobuttons? Thanks