Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all 141247 articles
Browse latest View live

React native (ios). "saveToCameraRoll" error - "PHPhotosErrorDomain error -1"

$
0
0

When I try to save an image to the phone (emulator IPhone 11 - iOS 13.1) gallery:

import CameraRoll from "@react-native-community/cameraroll";

...

CameraRoll.saveToCameraRoll('https://example.com/images/1.jpg', 'photo')
.then(() => {
  alert('Saved to photos');
})
.catch((err) => {
  console.log('err:', err);
});

, it gives me an error:

err: [Error: The operation couldn’t be completed. (PHPhotosErrorDomain error -1.)]

I added these lines to the file "Info.plist":

<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to the photo library</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app requires access to the photo library</string>

And run command in "ios" folder:

pod update
pod install

But the error still remains. Is there anything I have to do to clean up the error?


Data result from Axios

$
0
0

I'm new to Axio and React, I would like to know how to return my results from Axio. My console.log shows all my arrays send by PHP perfectly but it won't return in my HTML code.

Here is my code

axios.get('api.php').then(result => {
    console.log(result.data);
    return result.data
});

I tried using innerHTML but it's giving me

[object Object]

And adding .macdb after result.data gives me an undefined

issue saving / submitting a webform using selenium and python

$
0
0

i am failing for several days now to save a form once i filled all fields. I can click on the save button, but nothing happens. The page remains as is, and does not show anything saved and no errors running the script.

Here is an extract of the HTML of the website (It is an intranet website, so not accessible to the public) and extract of the python code i got together.

I tested several different ways to submit (xx.click(), xx.submit(), execute_script () etc...) to no avail. I also tried to call the javascript instead of clicking on the button, but that did not work either. Any help would be greatly appreciated.

  • Here HTML extract of the webpage:
<INPUT onclick=clearDirty();javascript:saveForm(); class=button type=button 
     value=Save> 

  • and here the Python script i am trying to use without success:

    saving = driver.find_element_by_xpath ('//input[@value = "Save"]')
    saving.click()


I have also tested executing the JS through selenium. That throws a Traceback "undefined is not a constructor", my button does not get clicked or my form not saved:


Saving = driver.find_element_by_xpath('//input[@value = "Save"]')

driver.execute_script("arguments[0].click();", Saving)

and then i tested this, thinking the JS maybe wanted to reload the page i was on and may want to "return" something. That throws a Traceback "undefined is not a constructor", my button does not get clicked or my form not saved:


nextpage = driver.execute_script("return arguments[0].click();", Saving)
print ("NEXTPAGE:", nextpage, type(nextpage))

How to call clearInterval from a different function

$
0
0

I am trying to implement a stopwatch. When the start button is pressed setInterval is called. How can I stop by running clearInterval when the stop button is pressed, without having a global variable to pass as a parameter to clearInterval

<body>
    <p class="clock">00:00:00</p>
    <button class='start'>Start</button>
    <button class="stop">Stop</button>
    <script>
      let totalMilliSeconds = 0;
      function tick(){
        totalMilliSeconds++;
          let hours = Math.floor(totalMilliSeconds/3600)
          let minutes = Math.floor(totalMilliSeconds/3600)
          let seconds = Math.floor(totalMilliSeconds/360)
          document.querySelector('.clock').textContent = `${hours}:${seconds}:${totalMilliSeconds}`
      }
      function start(){
        return setInterval(tick,1)
      }
      document.querySelector('.start').addEventListener('click',start)
      document.querySelector('.stop').addEventListener('click',start)
    </script>
    <p>
  </body>
</html>

Sabung Ayam Online Agen Sv388 Terpercaya

$
0
0

Agen Sv388 Terbentu 2012 dengan banyak pemain yang memainkannya jadi bagaimana jika anda ikut bergabung?

Having trouble understanding the question and where to start. I think i'm overthinking it

$
0
0
   /* @instructions
     * This function takes as its only argument an array 
     * containing strings,
     * and returns the index in the array of the string 'apple'.
     * 
     * You may assume the string 'apple' will appear exactly 
     * once in the array.
     * 
     * For example, if we invoke `appleIndex`
     * passing in [ 'orange', 'grape', 'apple', 'banana', 'mango' ] as the argument,
     * the returned value should be: 2.
    */

    function appleIndex([]) {
      const index = ['orange', 'grape', 'apple', 'banana', 'mango'];
      return 
    }

How to properly import MomentJS in Typescript to resolve the following error: "Type 'typeof moment' has no compatible call signatures." [duplicate]

$
0
0

Importing MomentJS is causing the following error:

ERROR in [...] Cannot invoke an expression whose type lacks a call signature. Type 'typeof moment' has no compatible call signatures.

How can I resolve this error?

How do I pass a Prop to a Navigation Screen Component - React Native

$
0
0

I'm fairly new to React native . I have created a Drawer Navigator in my App.js file.

One of my navigation Components is a component named LoginScreen.

I am trying to to pass a prop to LoginScreen to display when the user navigates to it.

App.js (Navigator)

const Tab = createMaterialBottomTabNavigator()
const Stack = createStackNavigator()
const Drawer = createDrawerNavigator()

export default class App extends Component {
    constructor(props) {
        super(props)

        this.state = {
            isAdmin: 'false',
            checked: false,
        }
    }

    async componentDidMount() {
        try {
            const adm = await AsyncStorage.getItem('is_admin')
            if (adm == null) {
                adm = await AsyncStorage.setItem('is_admin', 'false')
            }
            this.setState({ isAdmin: adm, checked: true })
        } catch (error) {
            console.log(error)
        }
    }


    render() {
        const { isAdmin } = this.state
        console.log(isAdmin)

        //is admin
        return isAdmin == 'true' ? (
            <NavigationContainer>
                <Drawer.Navigator initialRouteName="Home">
                    <Drawer.Screen name="Home" component={MyStack} />

                    <Drawer.Screen
                        name="Admin Panel"
                        component={props => {
                            return <LoginScreen props={props} propName = {'Hello'} />
                        }}
                    />
                </Drawer.Navigator>
            </NavigationContainer>
        ) : (
            //ISNOT ADMIN
            <NavigationContainer>
                <Drawer.Navigator initialRouteName="Home">
                    <Drawer.Screen name="Home" component={MyStack} />

                    <Drawer.Screen name="Login" component={LoginScreen} />
                </Drawer.Navigator>
            </NavigationContainer>
        )
    }
}

LginScreen.js

    const LoginScreen = ({ navigation, propName }) => {
       // const [bridge, setB] = useState(false)

        return (
            <SafeAreaView style={{ flex: 1, backgroundColor: '#376772' }}>
                <TopHeader
                    onRefresh={() => fetch_crossings}
                    onMenuToggle={() => navigation.toggleDrawer()}
                />

                <View style={{ flex: 1 }}>
                    <View
                        style={{
                            backgroundColor: '#fff',
                            margin: 10,
                            borderRadius: 5,
                            alignItems: 'center',
                            padding: 10,
                            paddingBottom: scale(20),
                        }}
                    >
                        <Avatar
                            rounded
                            size={'xlarge'}
                            overlayContainerStyle={{
                                backgroundColor: '#185a9d',
                            }}
                            icon={{
                                color: 'orange',
                                type: 'ionicon',
                                name: 'ios-log-in',
                            }}
                        />
                        <Input
                            placeholder="  Email"
                            placeholderTextColor={'#292b2c'}
                            style={{ margin: 5 }}
                            errorStyle={{ color: '#d9534f' }}
                            leftIcon={<Icon name="mail" color="#292b2c" />}
                            errorMessage="Enter a valid Email"
                        />

                        <Divider
                            style={{
                                backgroundColor: 'orange',
                                height: 3,
                                margin: scale(20),
                                borderRadius: 3,
                            }}
                        />
                        <Input
                            placeholder="  Password"
                            placeholderTextColor={'#292b2c'}
                            secureTextEntry={true}
                            style={{ margin: 5 }}
                            errorStyle={{ color: '#d9534f' }}
                            leftIcon={<Icon name={'lock'} color="#292b2c" />}
                            errorMessage="Enter a valid Email"
                        />
                    </View>
                    <View
                        style={{
                            backgroundColor: '#fff',
                            margin: 10,
                            marginTop: 0,
                            borderRadius: 5,

                            padding: 10,
                        }}
                    >
                        <Button
                            buttonStyle={{
                                margin: 10,
                                backgroundColor: '#5cb85c',
                                borderRadius: 4,
                                alignSelf: 'stretch',
                            }}
                            onPress={async () => {
                                try {
                                    await AsyncStorage.setItem('is_admin', 'false')
                        **console.log(propName);** //<--Right HERE

                                    navigation.navigate('Home')

                                } catch (error) {
                                    console.log(error)
                                }
                            }}
                            icon={<Icon name="send" size={15} color="white" />}
                            iconRight
                            titleStyle={{ fontWeight: 'bold' }}
                            title="Submit  "
                        />
                        <Button
                            buttonStyle={{
                                margin: 10,
                                backgroundColor: '#d9534f',
                                borderRadius: 4,
                                alignSelf: 'stretch',
                            }}
                            onPress={() => {
                                navigation.navigate('Home')
                            }}
                            icon={<Icon name="close" size={15} color="white" />}
                            iconRight
                            titleStyle={{ fontWeight: 'bold' }}
                            title={'Close '}
                        />
                    </View>
                </View>
            </SafeAreaView>
        )
    }

    export default LoginScreen

Whenever I console.log(propName), it says that its undefined.


Grab specific user data from class using jQuery

$
0
0

$(document).ready(function() {
  /*
  var $body = $('body');
  $body.html('');
  */

  //current feed
  var index = streams.home.length - 1;
  while (index >= 0) {
    var tweet = streams.home[index];
    //need to separate tweet message so only user class can be used for click event
    var $tweet = $('<div class=tweet></div>');
    var $user = $('<p id=users></p>');
    var $message = $('<p id=message></p>');
    var $time = $('<p id=time></p>');

    $time.text(tweet.created_at).appendTo($tweet);
    $user.text('@' + tweet.user + ': ').appendTo($tweet);
    $message.text(tweet.message).appendTo($tweet);
    $tweet.appendTo($('#tweets'));

    index -= 1;
  }

  //click event for new tweets
  $('button').click(function() {
    //pull a random tweet from streams.home which is an array of all tweets
    //can reuse code from current feed
    var tweet = streams.home[Math.floor(Math.random() * streams.home.length)];
    var $tweet = $('<div class=tweet></div>');
    var $user = $('<p id=users></p>');
    var $message = $('<p id=message></p>');
    var $time = $('<p id=time></p>');

    $time.text(tweet.created_at).appendTo($tweet);
    $user.text('@' + tweet.user + ': ').appendTo($tweet);
    $message.text(tweet.message).appendTo($tweet);
    $tweet.appendTo($('#tweets'));
  })

  //be able to view user profile
  //click event on user data only
  $('#tweets').on('click', '#users', function() {
    $('.container').hide();
  })

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><header><h1> Twiddler </h1><h3> Social Feed </h3></header><div class='container'><section><button id='home'> Home </button><section class='main'><p id='tweets'></p><button id='new'>Push</button></section></section></div><div class='userfeed'></div>

I'm making a Twitter look a like website as a project. I am working on a function to view a specific users history. Basically clicking on the name of the user would display their history and hide every other user. I'm not sure how to go about this and grab the data for specific users. What kind of jQuery functions should I be using to accomplish this?

Remove some element from current DOM in chrome extension using Content Script

$
0
0

If there are many <div>s in some web page like this:

<div tbinfo="ouid=1234567890&rouid=987654321"></div>
<div tbinfo="ouid=1234567891&rouid=987654321"></div>
<div tbinfo="ouid=1234567892&rouid=987654321"></div>
...

I have this content scripts, trying to remove some division(s) from them, if either ouid or rouid matches some key:

chrome.tabs.query(
    {active: true}, function(tabs) {
        var tab = tabs[0];

        let code = `document.querySelectorAll('div[tbinfo]')`;

        chrome.tabs.executeScript(tab.id, {code}, function (result) {
            const key = 1234567890;
            result.forEach(div => {
                const tbinfoArr = div.getAttribute('tbinfo');
                if (tbinfoArr.includes(key)) {
                    div.remove();
                }
            });
        });
    }
);

But chrome says Error handling response: TypeError: div.getAttribute is not a function

What's wrong here?


I read from this post that this error occurs when div is a jquery object, but I think it is not the case, maybe?

Apply three.js subdivision modifier without changing outer geometry?

$
0
0

I am trying to take any three.js geometry and subdivide its existing faces into smaller faces. This would essentially give the geometry a higher "resolution". There is a subdivision modifier tool in the examples of three.js that works great for what I'm trying to do, but it ends up changing and morphing the original shape of the geometry. I'd like to retain the original shape.

View the Subdivision Modifier Example


Example of how the current subdivision modifier behaves:

enter image description here

Rough example of how I'd like it to behave:

enter image description here


The subdivision modifier is applied like this:

let originalGeometry = new THREE.BoxGeometry(1, 1, 1);
let subdivisionModifier = new THREE.SubdivisionModifier(3);
let subdividedGeometry = originalGeometry.clone();
subdivisionModifier.modify(subdividedGeometry);

I attempted to dig around the source of the subdivision modifier, but I wasn't sure how to modify it to get the desired result.

Note: The subdivision should be able to be applied to any geometry. My example of the desired result might make it seem that a three.js PlaneGeometry with increased segments would work, but I need this to be applied to a variety of geometries.

Ag grid getLastDisplayedRow() does not work properly

$
0
0

I use getLastDisplayedRow() to get grid displyed last row index. And then display the grid by using ensureIndexVisable(lastRowIndex, 'bottom'). The issue is that it always jump down 10 rows to start display(in this case, if you scroll down to the end of the grid, then it wont jump since there is no more row to jump). I googled a little bit and get something not exactly the same but looks similar https://github.com/ag-grid/ag-grid/issues/1360, which says somehow there is a 10 rowbuffer(a 2016 thread).

I looked up the doc of getLastDisplayedRow(), it does mention

"getFirstDisplayedRow() Get the index of the first displayed row due to scrolling (includes not visible rendered rows in the buffer)"

also got https://www.ag-grid.com/javascript-grid-performance/#5-configure-row-buffer that explains why and what is about the buffer.

is there a I can config the row buffer?

Thanks in advance!

How to build: 3D Canvas objects and manipulation - tylko.com

$
0
0

Just wondering if anyone can guide me into how this site was built: https://tylko.com/shelf/bookshelves/

I've seen fabric.js in use, but not sure how to go from there. Is there any platforms or services that would assist in creating this or it's a heavy custom-build project?

Thanks Paul

Simplify similar Object Literal in javascript code

$
0
0

Is there any way to simplify this code, I appreciate any ideas. in lyerDefs I have the same value for all objects from 1 to 11.

spider = L.esri.dynamicMapLayer({
    url:API,
    layers:[1,2,3,4,5,6,7,8,9,10,11],
    layerDefs:{ // how to simplify following code?

      1:  "Site_id ='"+ activeSiteId +"'",
      2:  "Site_id ='" + activeSiteId +"'",
      3:  "Site_id ='"+ activeSiteId +"'",
      4:  "Site_id ='"+ activeSiteId +"'",
      5:  "Site_id ='"+ activeSiteId +"'",
      6:  "Site_id ='"+ activeSiteId +"'",
      7:  "Site_id ='"+ activeSiteId +"'",
      8:  "Site_id ='"+ activeSiteId +"'",
      9:  "Site_id ='"+ activeSiteId +"'",
      10:  "Site_id ='"+ activeSiteId +"'",
      11:  "Site_id ='"+ activeSiteId +"'"

    }
  } );

TS Error - Create Custom React Alert Component

$
0
0

I am trying to create a custom react material ui alert component that I can call on different pages by simply passing in the text and severity as parameters. I am trying to use this:

export default function CustomAlert(severity: string, text: string){
    <Alert style={{width:'50%'}} severity={severity}> {text}</Alert>
}

but I keep getting an error on the first severity word severity={severity}that:

Type 'string' is not assignable to type '"error" | "success" | "info" | "warning" | undefined'.ts(2322)
Alert.d.ts(25, 3): The expected type comes from property 'severity' which is declared here on type 'IntrinsicAttributes & AlertProps'

How could I fix this? Or is there an alternative method to customise this component?

Edit: I am still not being able to use it in my other page:

  function StatusMessage(){
    if (isRemoved){
      return (
      <Alert style={{width:'25%'}} severity="success"> User Removed</Alert>
        )
      }
      else{
        if(errorMessage!=''){
        if (errorMessage.includes(`Couldn't find user`)){
          return (
            <div>
            {/* <Alert style={{width:'25%'}} severity="error"> Couldn't Find User</Alert> */}
            <CustomAlert></CustomAlert>
            </div>
              )
        }       
      }}
  }

I get errors on CustomAlert that:

JSX element type 'void' is not a constructor function for JSX elements.ts(2605)
Type '{}' is not assignable to type '(IntrinsicAttributes & "success") | (IntrinsicAttributes & "info") | (IntrinsicAttributes & "warning") | (IntrinsicAttributes & "error")'.
  Type '{}' is not assignable to type '"error"'.ts(2322)

Need Help for Child Routes rendering. Parent route works fine, but child routes fall to 404

$
0
0

I am developing a static site using JSON data. I replaced the post data in the react-static default sample, and it works fine.

Problem: When I add another route /news with a bunch of messages in another JSON, the parent route /news works fine, but the child routes, such as /news/1/ or /news/2/ all go to 404 pages.

I do not think these are dynamic routes, as I can get the data before the react app mounted. What should I do to fix that?

In my static.config.js

{
  path: '/news',
  getData: async () =>  ({
    messages,
  }),
  children: messages.map(message => ({
    path: `/news/${message.ID}`,
    template: 'src/containers/Message',
    getData: () => ({
      message,
    }),
  })),
}

and I have a Message.js in /src/containers as

import React from "react";
import { useRouteData } from "react-static";

export default () => {
  const { message } = useRouteData()

  return (
       <div>
          This is a {message.Title} page!
        </div>
    )
};

Is there a simpler way to implement a probability function in JavaScript?

$
0
0

There's an existing question / answer that deals with implementing probability in JavaScript, but I've read and re-read that answer and don't understand how it works (for my purpose) or how a simpler version of probability would look.

My goal is to do:

function probability(n){
    // return true / false based on probability of n / 100 
}

if(probability(70)){ // -> ~70% likely to be true
    //do something
}

What's the simple way to achieve this?

Redirect to another page with data

$
0
0

I have a Javascript array in page 1 and i need it in page 2.

I tried with JQuery post method but i couldn't make it work :

   $.post( "{{path('result')}}", mydata );

How do i properly redirect the user from page 1 to page 2 with that array ?

Are cookies or sessions useful in this case ?

I'm using Symfony4 with Twig.

Thank you.

Show Mouse Cursor in Mobile - CSS/JS

$
0
0

I need your help because it works perfectly in desktop but in mobile the custom cursor in missing, how can i enable it thank you!

.logo-tiles-pencil {
    cursor: url(../img/logos/pencil-2.png) 10 3, auto !important;
}

Why is my local storage data not adding to an array?

$
0
0

I have a quiz that ends with logging the high score and user initials in local storage.

When the submit button is clicked for the user initials input, it takes you to the high score page, changing the location with window.location.href. The local storage is saving fine, but I'm having trouble pushing the strings to an array in order to create a high score list when the quiz is retaken. This is the function that I'm working with (the local storage was set in the previous page's JS script). It currently is overwriting instead of adding to the array. Why is this?

var storageArray = [];

function printHighscores() {

  var userInitials = JSON.parse(localStorage.getItem("userInitials"));
  var highScore = JSON.parse(localStorage.getItem('userScore'));
  storageArray.push(userInitials, highScore);
  console.log(storageArray)

Thank you.

Viewing all 141247 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>