Implementing js-script into component in Blazor

Can you please explain how to integrate the script like this:

<script type="text/javascript" charset="utf-8" async src="https://api-maps.yandex.ru/services/constructor/1.0/js/?um=constructor%3A1d532a41650954ba7f9ebe8975d9ebff1be172d29fb570d1b8c94fb9bfb45c66&amp;width=500&amp;height=720&amp;lang=ru_RU&amp;scroll=true"></script>

I want to have this script in the Blazor’s component because I need to show the map on one page

How to conditionally overwrite a style with a different style in React Native?

I have a PrimaryButton element that has 3 variants – primary, secondary and tertiary. As you can see in the style of the Pressable component, I set the default style based on the variant like this styles[variant] . Now I also want to make the backgroundColor of that Pressable component to turn red while it is being pressed if the button variant is tertiary. I already have access to isPressed boolean that tells me if the Pressable is pressed, however, I couldn’t figure out how to change the backgroundColor to red only if the variant is tertiary.

const PrimaryButton = ({ title, variant = 'primary', wide = false, style, ...rest }) => {
    const width = wide ? '100%' : undefined;
    const textColor = variant === 'primary' ? colors.white : colors.primary600;

    return (
        <Pressable
            style={({ pressed: isPressed }) => [
                styles.button,
                styles[variant],
                {
                    width,
                    elevation: isPressed ? 5 : 0,
                },
                style,
            ]}
            {...rest}
        >
        </Pressable>
    );
};

const styles = StyleSheet.create({
    button: {
        paddingVertical: 12,
        paddingHorizontal: 24,
        borderRadius: 100,
        borderWidth: 1.5,
        justifyContent: 'center',
        alignItems: 'center',
        alignSelf: 'center',
    },
    primary: {
        backgroundColor: colors.primary600,
        borderColor: colors.primary600,
    },
    secondary: {
        backgroundColor: colors.white,
        borderColor: colors.primary600,
    },
    tertiary: {
        backgroundColor: 'transparent',
        borderColor: 'transparent',
    },
    text: {
        textAlign: 'center',
    },
});

Extract date and time from datetime string in javascript

My datetime string is of below format:

var sdt = '2022-05-19T13:00:00';

I want to extract the date and time separately and below is my code:

((sdt.getMonth() > 8) ? (sdt.getMonth() + 1) : ('0' + (sdt.getMonth() + 1))) + '/' + ((sdt.getDate() > 9) ? sdt.getDate() : ('0' + sdt.getDate())) + '/' + sdt.getFullYear() + ' ' + (sdt.getHours()) + ':' + (sdt.getMinutes()) + ':00'

From the above code, date is getting extracted correctly but not the time. any help pls?

Vue component is not reactive

I have a list rendering on the screen, the list comes from an api request made in a vuex store, when i make a request to delete an item from the list the component does not rerender automatically.

my template renders the “allHouses” in the computed functions which comes from a vuex store. The item does get deleted but doesnt rerender automatically.

export default {
    name: "HouseCard",
    props: ["searchHouses", "sortHouses"],
    computed: {
    ...mapGetters(['allHouses']),
   
    },
    methods: {
 ...mapActions(['fetchHouses', 'houseDetail', 'deleteHouse']),
    },
    created(){
    this.fetchHouses()
  },

} ```

const actions = {
  async fetchHouses({ commit }) {
    const response = await api.fetchHouses();
    commit("setHouses", response.data);
    console.log(response.data);
  },
  createNewHouse(_, formData) {
    api.createNewHouse(formData);
  },
  async deleteHouse({ commit }, house) {
    await api.deleteHouse(house);
    const response = await api.fetchHouses();
    commit("setHouses", response.data);
  },
  async houseDetail({ commit }, id) {
    const response = await api.fetchHouses();

    response.data.forEach((house) => {
      if (house.id === id) {
        console.log(house);
        commit("setSelectedHouse", house);
      }
    });
  },
};


Checking intersection between two rectangles – Javascript

I am making a simple in-browser maze game using HTML and Javascript (Canvas), and am trying to make a function which will return true if the player’s hitbox intersects with one of the maze walls.
t is the player hitbox, r is one of the maze walls (they all get passed into this function one by one). For both rectangles, x1 and y1 represent the top left corner, and x4 and y4 represent the bottom right corner (x+width and y+height). This function returns true even when the player hitbox is clearly not intersecting with anything. What can I fix here?

function detectCollision(t,r) {
        intersection = true;
        
        //check if no horizontal overlap
        if ((t.x1 > r.x4) || (r.x1 > t.x4)) {
            intersection = false;
            }
        //vertical overlap
        if ((t.y1 > r.y4) || (r.y1 > t.y4)) {
            intersection = false;
            }

Tailwind-element datepicker component not working when use JQuery.load()

I have a layout page which load other html file using jquery in main content div when user click

layout.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="icon" href="/assets/favicon.png">
    <link rel="stylesheet" href="/dist/css/Shared/layoutTailWind.css">
    <title>Todo List App</title>
</head>

<body>
    <div id="layoutApp" class="h-screen w-full bg-white relative flex overflow-hidden">
        <div id="mainContentApp">

       </div>
   </div>
</body>
</html>

layout.js:

import 'tw-elements';
 $('#mainContentApp').load(`/Views/Content/Content.html`);
var script = document.createElement('script');
script.src = `/dist/js/Content/Content.entry.js`;
script.defer = "defer"
document.body.appendChild(script)

In Content page there is a tailwind-element datepicker component

Content.html:

<div class="flex items-center justify-center">
    <div class="datepicker relative form-floating mb-3 
          xl:w-96" data-mdb-toggle-button="false">
        <input type="text"
                class="form-control block w-full px-3 
                 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded transition ease-in-out m-0 focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
                    placeholder="Select a date" data-mdb-toggle="datepicker" />
        <label for="floatingInput" class="text-gray-700">Select a date</label>
    </div>
</div>

This is my tailwind.config.js:

const colors = require('tailwindcss/colors')

module.exports = {
  content: [
    "./Views/**/*.{html}",
    "./ClientApp/src/js/**/*.{js}",
    "tw-elements/dist/js/**/*.js"
  ],
  theme: {
    extend: {
      colors: {
        amber: colors.amber,
        emerald: colors.emerald,
      }
    },
  },
  plugins: [
    require('tw-elements/dist/plugin')Window
  ],
}

The problem is when I use the datepicker in layout.html, it worked fine. But when I use it in Content.html, the input is there but when I click it the date popup not showing up.

I have try putting import ‘tw-elements’ in both js files but still not working. I cant figure out why. Any help would be appreciated.

Django and React: csrf cookie is not being set in request header

To explain my situation, if I logged in from backend, csrf cookie is set in cookie tab, the problem occur in frontend, if i try to login from there, csrf cookie is not in request header (being undefined), some code provided:

settings.py:

ALLOWED_HOSTS = ['*']
ACCESS_CONTROL_ALLOW_ORIGIN = '*'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ACCESS_CONTROL_ALLOW_CREDENTIALS = True
ACCESS_CONTROL_ALLOW_METHODS = '*'
ACCESS_CONTROL_ALLOW_HEADERS = '*'

'''
SESSION_COOKIE_SECURE = True
'''
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'


CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000",'http://127.0.0.1:8000','http://localhost:3000']

setting SAMESITE protocol to anything else haven’t made any change

in views.py, we have login view (class based):

class LoginView(views.APIView):
    permission_classes = [AllowAny,]
    serializer_class = serializer.LoginSerializer
    def post(self,request):
        data = serializer.LoginSerializer(data=request.data)
        print(data.is_valid())
        if data.is_valid():
            email = data.data['email']
            password = data.data['password']
            auth = authenticate(username=email,password=password)
            if auth:
                login(request,auth)
                return HttpResponse("Success",status=200)
            else:
                print(password == "")
                if email == "" and password =="":
                    return HttpResponse('Both email and password field are empty',status=400)

                elif email == "":
                    return HttpResponse('Email field is empty',status=400)
                elif password == "":
                    return HttpResponse('Passowrd field is empty',status = 400)
        else:
            return HttpResponse("Both email and password fields are empty",status=400)

in serializer.py, we got the login serializer:

class LoginSerializer(serializers.Serializer):
    email = serializers.CharField(required=False)
    password = serializers.CharField(required=False,allow_null=True,allow_blank=True)

in react (frontend side), here is how i am making a post request:

function Login(){
    const [login,setLogin] = useState({'email':'','password':''})
    const {email,password} = login
    const navigate = useNavigate()

    let handleChange = (e)=>{
        setLogin(
            {
                ...login,
                [e.target.name]:e.target.value
            }
        )

    }

    
    let handleSubmit = (e)=>{
        e.preventDefault()
        axios.post('http://127.0.0.1:8000/login/',login,{headers: {'Content-Type': 'application/json','X-CSRFToken':Cookies.get('csrftoken')}}).then(
            (res)=>{

 
                    console.log(res)
                    console.log(Cookies.get('csrftoken')) //undefined here

            }
        ).catch((e)=>{
    console.log(e)
            }
        })

    }
}

this is part of the code btw ^.

any help is welcomed.

stdin in nodejs and adding arguments

Hello I have a question how can I read file from stdin “my program < inputFile” in node.js. Then each line of this inputFile should be the one argument to my function down here. The function should then run, and return the value then value returned from the function must be the same as outputFile. When I use node “myProgram” < inputFile it says that “<” is reserved.

const sortElephants = (
  numberOfElephants,
  massOfElephants,
  elephantsOrder,
  directorsOrder
) => {}

How do I group objects into an array, if the Date value is the same?

I have an array of objects that looks like the following:

[
    {
        "node_name": "node1",
        "external": "external_node1",
        "status": "online",
        "Date": "2022-05-26 08:20:27.022313"
    },
    {
        "node_name": "node2",
        "external": "external_node2",
        "status": "offline",
        "Date": "2022-05-26 20:20:27.022313"
    },
    {
        "node_name": "node3",
        "external": "external_node3",
        "status": "online",
        "Date": "2022-05-26 08:20:27.022313"
    },
    {
        "node_name": "node4",
        "external": "external_node4",
        "status": "online",
        "Date": "2022-05-26 20:20:27.022313"
    }
]

Using JavaScript, how would I ‘group’ and insert into its own array, all of the objects that have matching Date values?

For example, node1 & node3 both have "2022-05-26 08:20:27.022313" as its Date value, as well as node2 & node4 having the same Date value.

How would I sort these objects out and insert them into one array if the Date values matched?

How to update the same element that’s in another class

I am trying to update the same element that’s in another class. So currently the user_friendlist and activeusers are both are arrays of strings and it checks if both arrays contain a same entry. If that’s the case then I also want to update the same element so could be [0] or [1] for both different classes. But I don’t know how to do this, I know how to do it for one class but how could I do this for the other class while checking the first one. And that’s also the same element as the other one so both element0 for example but then for both different classnames.

//Display if a player is online and if he is also in the players friendlist
let friendOnlineNames = document.getElementsByClassName('friendlistentry')
let friendlistactivitystatus = document.getElementsByClassName('friendlistactivitystatus')

const filteredArray = user_friendlist.filter(value => activeusers.includes(value));

console.log(filteredArray)

let friendNamesToString = filteredArray.toString()

console.log(friendNamesToString)


for(let i=0; i< friendOnlineNames.length; i++){
  if (friendOnlineNames[i].innerHTML == friendNamesToString) {
   friendlistactivitystatus[i].innerHTML = "Online"
  }
}

Reset countdown properly – React

I have a countdown timer set at every second. Every time I would reset the counter and choose another period to countdown, the previous timer keeps counting and will have multiple timers in the background. I tried to reset the timer.

How can I stop the timer each time I go back and choose another period.

Question : You advise me to use react-native-countdown-component or that script?

Ps: I need it to push Notification.

Here is my code bellow:

useEffect(() => {

    if (isMounted) {
      
      phaseDay.current = []
      clearInterval(intervalRef.current)
      fetchData()
    } return () => {
      isMounted.current = false;
    }

  }, [itemType])

 useEffect(() => {

    startTimer()

    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current)
    }
  }, [intervalRef.current])

 const startTimer = () => {

    let { total, remainingDay, remainingHour, remainingMinute, remainingSecond } = calculateTimeLeft()

    const id = setInterval(() => {
      if (total > 0) {

        setTimer([
      ..

      } else {
        setTimer([])
        clearInterval(intervalRef.current)
        setPlantType(false)
        setItemType([])

      }
      handlerAirNotification()
    }, 1000);
    intervalRef.current = id

 
  }

const onReset = () => {

    return Alert.alert(
      "..",
      "..",
      [

        {
          text: "Oui",
          onPress: () => {
            if (intervalRef.current) {
              clearInterval(intervalRef.current)
              isMounted.current = false
              setPlantType(false)
              setSeries([])
              setTimerReset(true)
              navigation.navigate('Home')
            }

          },
        },...
reactjs

TypedError: Can not sign transactions for account andrius.testnet on network testnet, no matching key pair found in InMemorySigner

When I try to call my create_account function on near-api-js library:

        await creatorAccount.functionCall({
            contractId: process.env.NEAR_NETWORK_ID || "",
            methodName: "create_account",
            args: {
                new_account_id: newAccount,
                new_public_key: publicKey,
            },
            gas: new BN("300000000000000"),
            attachedDeposit: new BN("10000000000000000000"),
        });

I end up getting an exception:

>  {"severity":"INFO","message":"KeyStore:  /var/folders/f4/qjf99cc92k5gm4n45c98h5480000gn/T"}
i  functions: Beginning execution of "api"
>  {"severity":"INFO","message":"Signer account:  /var/folders/f4/qjf99cc92k5gm4n45c98h5480000gn/T/andrius.testnet.json exists: true"}
>  {"severity":"ERROR","message":"Exception:  TypedError: Can not sign transactions for account andrius.testnet on network testnet, no matching key pair found in InMemorySigner(UnencryptedFileSystemKeyStore(/var/folders/f4/qjf99cc92k5gm4n45c98h5480000gn/T)).n    at Account.signTransaction (/Users/bacis/Development/Catch/backend/functions/node_modules/near-api-js/lib/account.js:93:19)n    at async /Users/bacis/Development/Catch/backend/functions/node_modules/near-api-js/lib/account.js:118:34n    at async Object.exponentialBackoff [as default] (/Users/bacis/Development/Catch/backend/functions/node_modules/near-api-js/lib/utils/exponential-backoff.js:7:24)n    at async Account.signAndSendTransactionV2 (/Users/bacis/Development/Catch/backend/functions/node_modules/near-api-js/lib/account.js:117:24)n    at async createAccount (/Users/bacis/Development/Catch/backend/functions/lib/lib/nearApi.js:61:9)n    at async account (/Users/bacis/Development/Catch/backend/functions/lib/routes/account.js:13:9) {n  type: 'KeyNotFound',n  context: undefinedn}"}
>  /Users/bacis/Development/Catch/backend/functions/lib/routes/account.js:17
>          throw new Error(`Account creation error: ${ex}`);

I added some logs which confirm that the signer account does exist on that path:

> {"severity":"INFO","message":"Signer account: /var/folders/f4/qjf99cc92k5gm4n45c98h5480000gn/T/andrius.testnet.json exists: true"}

I haven’t fully figured out what is the problem there, does anyone have any ideas?

Passing Authorization in Axios Header Not Working

I am trying to dynamically generate checkout on the Coinbase Commerce API. I am following the documentation found here and porting into a javascript website using axios to make requests.

It seems like their setup requires authentication to be passed in the header of the requests, which I am doing but for some reason it is not working correctly. Their example works in curl directly on terminal, but something appears to be busted in my axios code. Could you kindly let me know how I can fix this?

Working Curl Request

curl https://api.commerce.coinbase.com/checkouts 
     -X POST 
     -H 'Content-Type: application/json' 
     -H "X-CC-Api-Key: <Your API Key>" 
     -H "X-CC-Version: 2018-03-22" 
     -d '{
         "name": "The Sovereign Individual",
         "description": "Mastering the Transition to the Information Age",
         "local_price": {
             "amount": "100.00",
             "currency": "USD"
         },
       "pricing_type": "fixed_price",
         "requested_info": ["email"]
     }'

Javascript / Axios Script

let amount = 10;
try {

    let options = {
        headers: {
            "Content-Type": "application/json",
            "x-api-key": "<Your API Key>",
            "X-CC-Version": "2018-03-22"
        }
    }

    let data = {
        "name": "US$" + amount + " Credit Refill",
        "description": "Credit refill",
        "local_price": {
            "amount": amount,
            "currency": "USD"
        },
        "pricing_type": "fixed_price"
    };

    let response = await axios.post('https://api.commerce.coinbase.com/checkouts', data, options);
    console.log(response.data);

} catch (error) {
    console.log(error)
}

Error

Error 401 / authorization_error