I can’t import my font folder –Cannot find module ‘./assets/fonts’–

Why is my Font folder not being imported?

Also, this issue applies to the icons and images folders as well.

File stucture

  • assets/
    • fonts/
      • nunito/
      • poppins/
      • index.ts
    • icons/
      • android/
      • ios/
      • index.ts
    • images
      • splash-screen/
      • index.ts
  • app.config.ts
  • metro.config.js
  • declarations.d.ts
  • ts.config.json
  • src/

Code Review

assets/fonts/index.ts

import NunitoBold from './nunito/Nunito-Bold.ttf';
import NunitoLight from './nunito/Nunito-Light.ttf';
import NunitoMedium from './nunito/Nunito-Medium.ttf';
import NunitoRegular from './nunito/Nunito-Regular.ttf';
import NunitoSemiBold from './nunito/Nunito-SemiBold.ttf';
import PoppinsBold from './poppins/Poppins-Bold.ttf';
import PoppinsLight from './poppins/Poppins-Light.ttf';
import PoppinsMedium from './poppins/Poppins-Medium.ttf';
import PoppinsRegular from './poppins/Poppins-Regular.ttf';
import PoppinsSemiBold from './poppins/Poppins-SemiBold.ttf';

export const APP_FONTS = {
  nunito: {
    bold: NunitoBold,
    light: NunitoLight,
    medium: NunitoMedium,
    regular: NunitoRegular,
    semibold: NunitoSemiBold,
  },
  poppins: {
    bold: PoppinsBold,
    light: PoppinsLight,
    medium: PoppinsMedium,
    regular: PoppinsRegular,
    semibold: PoppinsSemiBold,
  },
};

assets/images/index.ts

import splashDark from './splash-screen/dark.png';
import splashLight from './splash-screen/light.png';

export const APP_SPLASH_SCREEN = {
  dark: splashDark,
  light: splashLight,
};

same thing assets/icons/index.ts

...

tsconfig.json

{
  "extends": "expo/tsconfig.base",
  "compilerOptions": {
    "strict": true,
    "baseUrl": ".",
    "paths": {
      "src/*": ["src/*"]
    }
  }
}

declarations.d.ts

declare module '*.ttf' {
  const content: string;
  export default content;
}

declare module '*.png' {
  import type { ImageURISource } from 'react-native';
  const content: ImageURISource['uri'];
  export default content;
}

metro.config.js

const { getDefaultConfig } = require('@expo/metro-config');
const path = require('path');
const withStorybook = require('@storybook/react-native/metro/withStorybook');

const defaultConfig = getDefaultConfig(__dirname);

module.exports = withStorybook(defaultConfig, {
  ...defaultConfig,
  enabled: process.env.WITH_STORYBOOK,
  configPath: path.resolve(__dirname, '.storybook'),
});

app.config.ts

import type { ExpoConfig } from '@expo/config';

import { APP_FONTS } from './assets/fonts';
import { APP_ICONS } from './assets/icons';
import { APP_SPLASH_SCREEN } from './assets/images';

const isStorybookEnabled: boolean =
  process.env.STORYBOOK_ENABLED?.toLowerCase() === 'true';

const getSplashConfig = (): ExpoConfig['splash'] => ({
  image: APP_SPLASH_SCREEN.dark,
  resizeMode: 'contain',
  backgroundColor: '#F5F5F5',
});

const getAndroidConfig = (): ExpoConfig['android'] => ({
  adaptiveIcon: {
    foregroundImage: APP_ICONS.android.adaptiveIcon,
    backgroundImage: APP_ICONS.android.adaptiveIcon,
    monochromeImage: APP_ICONS.android.adaptiveIcon,
    backgroundColor: '#151718',
  },
  package: 'com.mces58.hangmanify',
});

const getIosConfig = (): ExpoConfig['ios'] => ({
  icon: {
    dark: APP_ICONS.ios.darkIcon,
    light: APP_ICONS.ios.lightIcon,
    tinted: APP_ICONS.ios.tintedIcon,
  },
});

const getWebConfig = (): ExpoConfig['web'] => ({
  favicon: APP_ICONS.web.favIcon,
});

const splashScreenPlugin: [string, Record<string, unknown>] = [
  'expo-splash-screen',
  {
    image: APP_SPLASH_SCREEN.dark,
    resizeMode: 'contain',
    backgroundColor: '#F5F5F5',
    dark: {
      image: APP_SPLASH_SCREEN.light,
      backgroundColor: '#151718',
    },
  },
];

const fontPlugin: [string, Record<string, unknown>] = [
  'expo-font',
  {
    fonts: [
      APP_FONTS.nunito.bold,
      APP_FONTS.nunito.light,
      APP_FONTS.nunito.medium,
      APP_FONTS.nunito.regular,
      APP_FONTS.nunito.semibold,
      APP_FONTS.poppins.bold,
      APP_FONTS.poppins.light,
      APP_FONTS.poppins.medium,
      APP_FONTS.poppins.regular,
      APP_FONTS.poppins.semibold,
    ],
  },
];

export default ({ config }: { config: ExpoConfig }): ExpoConfig => ({
  ...config,
  name: process.env.STORYBOOK_ENABLED ? 'Hangmanify Storybook' : config.name,
  splash: getSplashConfig(),
  android: getAndroidConfig(),
  ios: getIosConfig(),
  web: getWebConfig(),
  plugins: ['expo-localization', splashScreenPlugin, fontPlugin],
  extra: {
    ...config.extra,
    storybookEnabled: isStorybookEnabled,
    eas: {
      projectId: '...',
    },
  },
});

Output:

yarn start
yarn run v1.22.22
$ expo start
env: load .env
env: export GOOGLE_GENERATIVE_AI_API_KEY WITH_STORYBOOK
Starting project at /home/mces58/Desktop/Hangmanify
Error: Error reading Expo config at /home/mces58/Desktop/Hangmanify/app.config.ts:

Cannot find module './assets/fonts'
Require stack:
- /home/mces58/Desktop/Hangmanify/app.config.ts
- /home/mces58/Desktop/Hangmanify/node_modules/@expo/config/build/evalConfig.js
- /home/mces58/Desktop/Hangmanify/node_modules/@expo/config/build/getConfig.js
- /home/mces58/Desktop/Hangmanify/node_modules/@expo/config/build/Config.js
- /home/mces58/Desktop/Hangmanify/node_modules/@expo/config/build/index.js
- /home/mces58/Desktop/Hangmanify/node_modules/@expo/cli/build/src/start/detectDevClient.js
- /home/mces58/Desktop/Hangmanify/node_modules/@expo/cli/build/src/start/resolveOptions.js
- /home/mces58/Desktop/Hangmanify/node_modules/@expo/cli/build/src/start/index.js
- /home/mces58/Desktop/Hangmanify/node_modules/@expo/cli/build/bin/cli
- /home/mces58/Desktop/Hangmanify/node_modules/expo/bin/cli

Is there a way to detect what ‘page number’ text in a google docs document is on?

I’m trying to find a way to detect what ‘page number’ text in a google docs document is on. I want to know this so I can determine page breaks accordingly if text would flow over onto the next page in a sequence of text I may have.

I have asked the AI and it claims this is impossible to do, but I doubt that. It claims the only way to do this is through heuristic methods like counting how many characters there is and so forth which will not work for me because content may have various font sizes or indentions and newlines etc… I need to reliably know for sure if something is on the next page or not.

So I looked into some different ways to do this.

1.) Maybe google app script? – Apparently there is no method for this?

2.) Google API’s? – Apparently there is no API to detect this for text in the document.

3.) Using Chrome Extension and looking at the DOM. I studied the DOM structure of Google Docs and I could not for the life of me see how it’s rendering the page. The AI claims it might be using iframes but this is not clear as I could not see where it’s actually rendering the content. This would have been nice since I could just see if the text appears in some DOM element that represents the next page, but alas I can not seem to figure this out either.

So this brings me to you the community to see if you have any ideas I have not thought of that might be used to answer this seemingly simple question.

Always getting segmentation fault [closed]

I’m using Node.js with these packages:

{
  "name": "templatetailwind",
  "license": "MIT",
  "scripts": {
    "dev": "parcel src/**/*.html",
    "build": "parcel build src/*.html --no-cache",
    "buildNotRoot": "parcel build --public-url /dadpool/ src/**/*.html"
  },
  "dependencies": {
    "autoprefixer": "^10.4.21",
    "daisyui": "^2.52.0",
    "flowbite": "^1.8.1",
    "parcel": "^2.14.4",
    "postcss": "^8.5.3",
    "postcss-purgecss": "^2.0.3",
    "tailwindcss": "^3.4.17"
  }
}

I was using this fine 2 months ago but now every time I’m trying to build it it’s always getting segmentation fault.

Full code: https://github.com/MoonLGH/dadpool

Build report: https://github.com/MoonLGH/dadpool/actions/runs/14227212281

Handling Date in express & Mysql [closed]

In mySql database the date is storeded in date datatype as 2011-11-17 but while retriving it using Express js i get it as 2011-11-16T18:30:00.000Z a date jumps to before date. How to handle correct date with global timezone with the correct specified date ?

Opposite of class.toString [duplicate]

So I’m making a online PC sorta thing using JS and HTML, and I came across the issue of JSON.stringify(System) for storing things in localStorage not stringifying it properly, where System is a class with sub-classes within (class File extends System, etc.), so I found the solution of using System.toString. Is there a reverse toString method I can use to set my System class to what I keep in localStorage?
I will update y’all if I find a solution.
(Note, I have checked all of the similar questions, and they are either using things that my measly little pea-sized brain cannot understand, or they aren’t what I’m looking for)

problemas com a suma de valores de mi coluna totalItem que nao estao indo para cartao de credito onde preciso dos valores completos: [closed]

async findOne(id: string) {
const budget = await this.budgetEntity
.findById(id)
.populate([
{ path: ‘seller’, select: ‘name phone’ },
{ path: ‘clients’, select: ‘name’ },
{
path: ‘packages.package’,
populate: [
{
path: ‘package’,
model: ‘Packages’,
select: ‘name showInPdf description photo url’,
},
{ path: ‘clients.client’, model: ‘Clients’, select: ‘name’ },
],
},
])
.lean();

// Verificacao inicial de seguranca
if (!budget || !budget.packages) {
  return null;
}

// Geração de colunas da tabela
const tableHead = checkRulesForTable(budget.packages);
const tableHeaderArray = generateTableHeader(tableHead);

let total = 0;

// Calculo dos totais por item
const packagesWithPricing = budget.packages.map((section) => {
  const sectionPackages = section.package.map((subPkg) => {
    const pricingObj = getTotalPricingByType(
      subPkg.clients,
      tableHeaderArray,
    );

    const totalItem = Object.values(pricingObj).reduce(
      (acc: number, val: any) =>
        typeof val === 'number' ? acc + val : acc,
      0,
    );

    total += totalItem;

    return {
      ...subPkg,
      pricing: pricingObj,
    };
  });

  return {
    ...section,
    package: sectionPackages,
  };
});

const discountRate = 0.1;
const totalCard = +total.toFixed(2);
const totalPix = +(total * (1 - discountRate)).toFixed(2);

return {
  ...budget,
  packages: packagesWithPricing,
  table_head: tableHead,
  totalPricing: {
    totalCard,
    totalPix,
    discountPercent: discountRate * 100,
  },
};

}

How do I get my JavaScript cash machine simulator to work in my Node.js terminal?

I am currently making a JavaScript Node.js cash machine simulator using the ‘readline-sync’ library to handle terminal input/output. It allows the user to check their balance, deposit or withdraw money. I have used a loop to keep the application running until the user decides to exit. I’ve also included error handling for invalid inputs e.g. withdrawing more than the total balance. However, when I run the application in my VS Code, it doesn’t work. Can anyone help me make my code ‘readline-sync’ friendly, please?

Here’s my code so far:

const cashMachine = require('readline-sync');

let name,
correct_pass = (/^[0-9]{4}£/),
passTry = 3,
currentBalance = 20000;

// Input a username
function cashMachineName() {
    name = cashMachine.question("Enter your name");
    if (name !== "" && name !== null) {
        cashMachinePassword();
    } else {
        cashMachineName();
    }
}
// Input a valid password
function cashMachinePassword() {
    let passwordEntry = questionInt("Hello " + name + ", please enter your 4-digit PIN");
    checkPassword(passwordEntry);
}
// Verify password meets requirements
function checkPassword(userInput) {
    if (correct_pass.test(userInput)){
        selectAccountType();
    } else {
        while (!(correct_pass.test(userInput))) {
            if (passTry === 1) {
                console.log("Incorrect PIN");
                console.log("Maximum tries exceeded! Your account has been locked. Contact your bank for support.");
                exit();
                break;
 } else {
    passTry -= 1;
    alert("Incorrect PIN. Please try again.");
                alert("You have " + passTry + " chance/s to try");
                cashMachinePassword();
 }
        }
    }
}
// Select which account to use
function selectAccountType() {
    let accountType = questionInt("Which type of account do you have? n 1. Savings n 2. Current n 3. Credit");
    if (accountType !== "" && accountType !== null && !isNan(accountType)) {
        switch (accountType) {
            case 1: 
            balance();
            break;

            case 2:
                withdrawal();
                break;

                case 3:
                    deposit();
                    break;

                    case 4:
                        exit();
                        break;

                        default: 
                        cashMachine.questionInt("Please make a valid operation");
                        selectFunction();
        }
    } else {
        cashMachine.questionInt("Please make a valid selection");
        selectFunction();
    }
}
// Balance 
function balance() {
    cashMachine.questionInt("Your current balance is £" + currentBalance);
    toContinue();
}
// Deposit
function deposit() {
    let depositAmount = questionInt("How much do you want to deposit?");
    if (depositAmount !== "" && depositAmount !== null && !isNaN(depositAmount)) {
        currentBalance += depositAmount;
        console.log("You have successfully deposited £" + depositAmount + "n" + "You know have £" + currentBalance);
        toContinue();
    } else {
        console.log("Error: Please enter a number!");
        deposit();
    }
} 
// Withdrawal
function withdrawal() {
    let withdrawalAmount = questionInt("How much do you want to withdraw? n" + "The minimum amount you can withdraw is £5");
    if (withdrawalAmount !== "" && withdrawalAmount !== null && !isNaN(withdrawalAmount)) {
        if (withdrawalAmount >= 5) {
            if (withdrawalAmount <= currentBalance) {
                currentBalance -= withdrawalAmount;
                console.log("Transaction successful!");
                console.log("Your remaining balance is £" + currentBalance);
                toContinue();
            } else {
                console.log("You do not have sufficent funds!");
                withdrawal();
            }
        } else {
            console.log("You must withdraw at least £5");
            withdrawal();
        }
    } else {
        console.log("Error: Please enter a number!");
        withdrawal();
    }
}
// Check if the user wants to perform another transaction
function toContinue() {
    let yesOrNo = questionInt("Do you want to perform another transaction? n 1. Yes n 2. No");
    if (yesOrNo !== "" && yesOrNo !== null) {
        if (yesOrNo === 2) {
            exit();
        }
        else {
            selectAccountType();
        }
    } else {
        console.log("Please make a valid selection");
        toContinue();
    }
}
// Exit the cash machine simulator
function exit() {
    console.log("Thank you for using our cash machine");
    // To simulate a real cash machine, get ready for next user
    // cashMachineName();
}

javascript allows array[0] values to be referenced as an object [closed]

I am going through an old app cleaning and aligning code and came across an array element being referenced as an object and am wondering how it is working.

Specifically, an array is being returned from an API in the following format:

//PHP
$returnInfo[] = array("success"=>true,"reviews"=>$reviews,"iCount"=>$resCount) ;
...
sendResponse(200, json_encode($returnInfo));

//JS
service.getReviews
.then(function(response) {
   let resData = response.data ;
   console.log(resData) ;

   // prints to console
   //
   // [{…}]
   //      0: 
   //          iCount: 0
   //        > reviews: (3) [{…}, {…}, {…}]
   //          success: true
   //        > [[Prototype]]: Object
   //        length: 1
   //      > [[Prototype]]: Array(0)
   // 

   var allReviews = null ;
   if (resData.iCount == 0) { 
      allReviews = resData.reviews ;
   }

My expectation is that this would have thrown an error because it should be referenced as:

var allReviews = null ;
if (resData[0].iCount == 0) { 
   allReviews = resData[0].reviews ;
}

So how is the object reference working?

I changed the code in the app to use resData[0].iCount and resData[0].reviews and it continues to work – so its working in both formats and I don’t understand how. Those array[0] values do not exist at the root of the array or outside the element list so how can they still be referenced as a traditional object?

On a side note, I have found several instances of this working in the app but am unable to replicate the issue using online JS testing sites like jsbin (.) com. As well, in my google searches I have not found any threads/articles that is explaining what I am seeing.

Handling async errors on Node.js and express

I’m creating a Node.js app with Express and trying to implement an error handling routine. It works with test errors I throw from my controller, but when a real error occurs, my error handling middleware doesn’t catch it. Instead, the console prints the error and the server stops. This would be a major problem in production if any error causes the server to crash.

I think the issue might be related to the async methods I’m calling. Here’s what I’ve done:

In my index.js, I’ve registered the error handling middleware:

// Error handler middleware (must be after all routes)
app.use(errorHandler);

My errorHandler middleware (works when the test error was thrown):

const errorHandler = async (err, req, res, next) => {
    let errorId = saveErrorToDatabase();
    return Responses.internalError(res, `Internal Server Error (ID: ${errorId})`);
};

Then I have my controller class that my route points to:

async create(req, res, next) {
    const { name, type } = req.body;                
    const inserted_id = await (new Account()).insert(name, type);        
    Responses.success(res, 201, { id: inserted_id, message: 'Account created successfully' });
},

My Account object:

async insert(name, type) {
    return this.#crudDBUtil.insert({ name, type });        
}

CrudDBUtil is a class I created to handle database operations. The insert operation is generating an error (a required field wasn’t provided). I expected the API to respond with “Internal Server Error: ID 9999” and save the error in the database. Instead, I’m getting this error (parts omitted for clarity and privacy):

{my full path}pool.js:36
    const localErr = new Error();
                     ^

Error: Field 'user_id' doesn't have a default value
    at {Full Call stack} {
  code: 'ER_NO_DEFAULT_FOR_FIELD',
  errno: 1364,
  sql: '{sql sentence}",
  sqlState: 'HY000',
  sqlMessage: "Field 'user_id' doesn't have a default value"
}

Node.js v20.17.0

My issue isn’t with the error itself – I know what it is and how to fix it. However, I want future errors to be registered in the database and, most importantly, not cause the server to stop running. How can I make sure my error handler catches all errors, including those from async operations?

i want to set scrolling animation using gsap [closed]

I want to apply scrolling effect like in Wix https://pt.wix.com/studio/enterprise image scrolling
please view and open this url and chec https://pt.wix.com/studio/enterprise see

this is my website
https://medisuggest.com/

here is my code

 gsap.fromTo(".surgery-video-p",
        { scale: 1 }, 
        { 
            scale: 1.45, 
            ease: "none", 
            scrollTrigger: {
                trigger: ".surgery-video-p",
                start: "top 20%",
                end: "bottom center",
                scrub: true,
                pin: true 
            }
        }
    );
    gsap.fromTo(".image-box-top",
        {         
            x: 4912.8,  
            y: -405.6, 
            rotate: 0,  
        }, 
        { 
            x: 0, 
            y: 0, 
            rotate: 0,  // Keep rotation at 0
            ease: "power2.out", 
            scrollTrigger: {
                trigger: ".image-box-top",
                start: "top 20%",
                end: "bottom center",
                scrub: true,
                pin: true,
                pinSpacing: false,
                onUpdate: (self) => {
                    if (self.progress === 1) { 
                        gsap.set('.image-box-top', { clearProps: "transform" }); // Reset transform
                    } 
                  },
            }
        }
    );

error using jinja and flask in external javascript file

We are being required to move all css and javascript to external files.
The css works fine. The javascript files only works in a particular way which is not approved.
The following line works:

    '''
    <script>{% include 'js/region_data.js' %}</script>
    '''

This line does NOT work: Gets the following error in the dev tools console,
region_data.js:7 Uncaught SyntaxError: Unexpected token % (at region_data.js:7:6)

    '''
    <script src="/static/js/region/region_data.js" type="text/javascript"></script>
    '''

This is their location in the html file, the line that doesn’t work is commented out:

    '''
    {% extends "layout_bs5.html" %}
    {% import 'macros.html' as data_macros %}
    {% block head %}
        {{ super() }}
        <link rel="stylesheet" type="text/css" href="/static/css/region/region_data.css">
        <script>{% include 'js/region_data.js' %}</script>
        <!-- <script src="/static/js/region/region_data.js" type="text/javascript"></script> -->
    {% endblock %}
    '''

The {% is where the error occurs when using the <script src=…

    '''
    $( document ).ready(function() {
      {% for parameter in parameters %}
          {{ data_macros.generate_js(parameter) }}
      {% endfor %}
    '''

folder structure for file that works:

    '''
    region_data/trunk/src/templates/js/region_data.js
    region_data/trunk/src/templates/index.html
    region_data/trunk/src/templates/macros.html
    '''

folder structure for file that does NOT work

    '''
    static/trunk/src/static/js/region/region_data.js
    '''

I have heard that anything to do with flask needs to be loaded with the flask templates and I can’t use an external file in static if it has flask or jinja in it.
Is that why the static file gets an error but the one in the templates/js folder does not??

I don’t understand why.
I am not allowed to use the ‘include’. It has to be in the static folder but I don’t see a way of doing that. Any ideas?

How to show specific shipping method only for certain shipping class?

in our shop we use wp-blocks scheme for the cart and checkout page.

What I would like to achieve is:

  1. Show specific shipping method only for certain shipping class (or group of products) and hide other methods.
  2. Show specific payment method only for certain product ids and/or certain product categories. (This is an extra question, I guess if I get how to achieve the first one, this one will be similar)

I tried to achieve it using JQuery, in custom theme script, but it seems like JQuery scripts are not applied to wp-blocks.

I used this php method to get info if the products from the cart are only from ‘my-custom-shipping-class’ shipping class.
If the answer is true, then I would like to show only one specific shipping (let’s say ‘shipping-method-1’) method and hide others.
If the answer is false, I would like to show all the mothods, except the ‘shipping-method-1’.

function show_shipping_method() {
    $slug = 'my-custom-shipping-class';
    global $woocommerce;
    $product_in_cart = false;
    $other_product_in_cart = false;
    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
        $_product = $values['data'];
        $terms    = get_the_terms($_product->id, 'product_shipping_class');
        if ($terms) {
            foreach ($terms as $term) {
                $_shippingclass = $term->slug;
                if ($slug === $_shippingclass) {
                    $product_in_cart = true;
                } else {
                    $other_product_in_cart = true;
                }
            }
        } else {
            $other_product_in_cart = true;
        }
    }
    return ($product_in_cart && !$other_product_in_cart);
    
}

Then in theme html I’d add custom class:

<section id="service-page" class="<?php echo apply_filters( 'shipping_class_to_add') ? 'hide-all-shipping-except-my-custom-shipping-class' : 'hide-my-custom-shipping-class';
                                  ?>">

Then in CSS:

.hide-all-shipping-except-my-custom-shipping-class label[for="radio-control-0-flat_rate:5"],
.hide-all-shipping-except-my-custom-shipping-class label[for="radio-control-0-flat_rate:4"],
.hide-all-shipping-except-my-custom-shipping-class label[for="radio-control-0-flat_rate:1"]{
    display:none;
} 

.hide-my-custom-shipping-class label[for="radio-control-0-flat_rate:11"] {
    display: none;
}

An then, finally, JQuery code, to check the radio button of the desired shipping method (this part doesn’t work):

jQuery('document').ready(function() {
// escaping the colon doesn't change anything, none of the JQuery code works with wp-blocks
    $('input[id="radio-control-0-flat_rate:11"]').prop('checked', true);
});

Thank you in advance for help.