问:
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
How do I prevent the following error:

Too many re-renders. React limits the number of renders to prevent an infinite loop.'

I just changed a class based component to functional component and its not working

My source code

```<code>import React, {Fragment, useState} from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Navbar from './Components/Layout/Navbar';
import Users from './Components/users/Users';
import User from './Components/users/User';
import Search from './Components/users/Search';
import Alert from './Components/Layout/Alert';
import About from './Components/pages/About';
import './App.css';
import Axios from 'axios';

const  App  = () => {
 const [users, setUsers] = useState( [] );
 const [user, setUser] = useState( {} );
 const [repos, setRepos] = useState( [] );
 const [loading, setLoading] = useState( false );
 const [alert, setAlert] = useState( null );

// Search Github Users
  const  searchUsers = async text  => {
    setLoading(true);

    const res = await Axios.get(`https://api.github.com/search/users?q=${text}&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);

   setUsers(res.data.items);
   setLoading(false);
  };

  // GEt single github user
  const  getUser = async username => {
    setLoading(true);

    const res = await Axios.get(`https://api.github.com/users/${username}?&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);

    setUser(res.data);
    setLoading(false);
  };

  // Get users repos
  const  getUserRepos = async username => {
    setLoading(true);

    const res = await Axios.get(`https://api.github.com/users/${username}/repos?per_page=5&sort=created:asc&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);

    setRepos(res.data);
    setLoading(false);

  };

  // Clear users from state
  const  clearUsers = () =>
  setUsers([]);
  setLoading(false);

  // Set ALert
  const  showAlert = (msg, type) => {
   setAlert({msg, type});

  setTimeout(()=> setAlert(null),3000);
  };

    return (
      <Router>
      <div className="App">
       <Navbar />
       <div className="container">
          <Alert alert={alert} />
          <Switch>
          <Route exact path='/' render={props => (
            <Fragment>
                <Search
                searchUsers={searchUsers}
                clearUsers={clearUsers}
                showClear={ users.length>0? true : false }
                  setAlert={showAlert}
                />
                <Users loading={loading} users={users}  />
          </Fragment>
          )} />
          <Route exact path = '/about'  component={About} />
          <Route exact path= '/user/:login' render={props => (
            <User
            {...props}
            getUser={getUser}
            getUserRepos={getUserRepos}
            user={user}
            repos={repos}
            loading={loading} />
          )} />
          </Switch>
       </div>
      </div>
    </Router>
    );
}

export default App;

</code>```

I just change a class based component to functional component and i get these error.

0

How do I prevent the following error:

Too many re-renders. React limits the number of renders to prevent an infinite loop.'

答:
As from the comment,

There was error in the declaration of function clearUsers

```<code> const clearUsers = () => setUsers([]);
 setLoading(false);
</code>```

which should be.

```<code> const clearUsers = () => {
   setUsers([]);
   setLoading(false);
 }
</code>```

because of this small typo. The setLoading function was being called on the first render which would then call setLoading triggering react to call render again and in return call setLoading and caused the infinite renders.

Body:
How do I prevent the following error:

Too many re-renders. React limits the number of renders to prevent an infinite loop.'

I just changed a class based component to functional component and its not working

My source code

import React, {Fragment, useState} from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Navbar from './Components/Layout/Navbar';
import Users from './Components/users/Users';
import User from './Components/users/User';
import Search from './Components/users/Search';
import Alert from './Components/Layout/Alert';
import About from './Components/pages/About';
import './App.css';
import Axios from 'axios';

const  App  = () => {
 const [users, setUsers] = useState( [] );
 const [user, setUser] = useState( {} );
 const [repos, setRepos] = useState( [] );
 const [loading, setLoading] = useState( false );
 const [alert, setAlert] = useState( null );

// Search Github Users
  const  searchUsers = async text  => {
    setLoading(true);

    const res = await Axios.get(`https://api.github.com/search/users?q=${text}&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);

   setUsers(res.data.items);
   setLoading(false);
  };

  // GEt single github user
  const  getUser = async username => {
    setLoading(true);

    const res = await Axios.get(`https://api.github.com/users/${username}?&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);

    setUser(res.data);
    setLoading(false);
  };

  // Get users repos
  const  getUserRepos = async username => {
    setLoading(true);

    const res = await Axios.get(`https://api.github.com/users/${username}/repos?per_page=5&sort=created:asc&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);

    setRepos(res.data);
    setLoading(false);

  };

  // Clear users from state
  const  clearUsers = () =>
  setUsers([]);
  setLoading(false);

  // Set ALert
  const  showAlert = (msg, type) => {
   setAlert({msg, type});

  setTimeout(()=> setAlert(null),3000);
  };

    return (
      <Router>

       <Navbar />

          <Alert alert={alert} />
          <Switch>
          <Route exact path='/' render={props => (
            <Fragment>
                <Search
                searchUsers={searchUsers}
                clearUsers={clearUsers}
                showClear={ users.length>0? true : false }
                  setAlert={showAlert}
                />
                <Users loading={loading} users={users}  />
          </Fragment>
          )} />
          <Route exact path = '/about'  component={About} />
          <Route exact path= '/user/:login' render={props => (
            <User
            {...props}
            getUser={getUser}
            getUserRepos={getUserRepos}
            user={user}
            repos={repos}
            loading={loading} />
          )} />
          </Switch>

    </Router>
    );
}

export default App;

I just change a class based component to functional component and i get these error.

0

How do I prevent the following error:

Too many re-renders. React limits the number of renders to prevent an infinite loop.'

Body:
As from the comment,

There was error in the declaration of function clearUsers

 const clearUsers = () => setUsers([]);
 setLoading(false);

which should be.

 const clearUsers = () => {
   setUsers([]);
   setLoading(false);
 }

because of this small typo. The setLoading function was being called on the first render which would then call setLoading triggering react to call render again and in return call setLoading and caused the infinite renders.


来源: stackexchange

问:
Converting a material-ui class to a function
I am learning material-ui, and most of the code available uses classes (which I'm more familiar with since object-oriented background).  But the new paradigm is supposedly to use functions i/o classes because of the introduction of hooks.

I see all kinds of questions about converting functions to classes but can't find ONE example of converting a class to a function.

I'm trying to convert this code to a function:

```<code>
class MouseTracker extends React.Component {
  constructor(props) {
    super(props);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.state = { x: 0, y: 0 };
  }

  handleMouseMove(event) {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>
        <h1>Move the mouse around!</h1>
        <p>The current mouse position is ({this.state.x}, {this.state.y})</p>
      </div>
    );
  }
}

</code>```

I have zero clue how to deal with the super(props) statement.  Here's my attempt that doesn't work.

```<code>
function MouseTracker(props) = {
{
    super(props);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.state = { x: 0, y: 0 };
  }

  handleMouseMove(event) {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>
        <h1>Move the mouse around!</h1>
        <p>The current mouse position is ({this.state.x}, {this.state.y})</p>
      </div>
    );
  }
}

export default MouseTracker

</code>```

Thanks so much for any help!

答:
I think you can search for online material based on "React Functional Components" to find out how to convert classes to functions. These components are written as if they are javascript functions and uses React hooks to handle states and other kinds of things

The "super(props)" is a React constructor class syntax. So it's not needed when you write functional components

Also, note the difference between es6 syntax and js, function MouseTracker(props) = {..} is invalid.

Here's a working example based on the mouse tracker: https://codesandbox.io/s/react-functional-component-demo-ytbrn?file=/demo.js

Here's some examples from ReactJs' documentation, and its hooks pattern:

https://reactjs.org/docs/components-and-props.html

https://reactjs.org/docs/hooks-intro.html

ContentLicense: CC BY-SA 4.0

Body:
I am learning material-ui, and most of the code available uses classes (which I'm more familiar with since object-oriented background).  But the new paradigm is supposedly to use functions i/o classes because of the introduction of hooks.

I see all kinds of questions about converting functions to classes but can't find ONE example of converting a class to a function.

I'm trying to convert this code to a function:

class MouseTracker extends React.Component {
  constructor(props) {
    super(props);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.state = { x: 0, y: 0 };
  }

  handleMouseMove(event) {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (

Move the mouse around!

The current mouse position is ({this.state.x}, {this.state.y})

    );
  }
}

I have zero clue how to deal with the super(props) statement.  Here's my attempt that doesn't work.

function MouseTracker(props) = {
{
    super(props);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.state = { x: 0, y: 0 };
  }

  handleMouseMove(event) {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (

Move the mouse around!

The current mouse position is ({this.state.x}, {this.state.y})

    );
  }
}

export default MouseTracker

Thanks so much for any help!


问:
Find given row in a matrix
I have an m by n matrix in MATLAB, say M. I have an n-element row vector, i.e. a one by n column matrix, say X.

I know X is a row somewhere in M. How can I find the index in M?

答:
This is a non-loop version. It is only suitable, if M (your matrix) is not very large, ie. n and m are small. X is your row:

```<code>function ind = findRow(M,X)
    tmp = M - repmat(X,size(M,1),1);
    ind = find(tmp,1);
end
</code>```

If M is too large, it might be faster, to iterate the rows of M and compare every row with your vector.

@Edit: renamed variables to match the names used in the question.

ContentLicense: CC BY-SA 3.0

Title: Find given row in a matrix

Body:
This is a non-loop version. It is only suitable, if M (your matrix) is not very large, ie. n and m are small. X is your row:

function ind = findRow(M,X)
    tmp = M - repmat(X,size(M,1),1);
    ind = find(tmp,1);
end

If M is too large, it might be faster, to iterate the rows of M and compare every row with your vector.

@Edit: renamed variables to match the names used in the question.


问:
Showing Errors on CardCornerRadius and CardElevation
I've defined my layout as below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    tools:context=".MainActivity">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="32dp"
        card_view:cardCornerRadius="8dp"
        card_view:cardElevation="16dp">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="16dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question1title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question1"
                    style="@style/questionAndAnswers"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerMario"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerMario"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerDonkey"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerDonkeyKong"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerPortal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPortal"/>
                </LinearLayout>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question2title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question2"
                    style="@style/questionAndAnswers"/>

                <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                    <RadioButton android:id="@+id/radio_1979"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1979"/>
                    <RadioButton android:id="@+id/radio_1989"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1989"/>
                    <RadioButton android:id="@+id/radio_1999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1999"/>
                </RadioGroup>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question3title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question3"
                    style="@style/questionAndAnswers"/>

                <EditText
                    android:id="@+id/answerInputUserLastName"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/LastNameLaraHint"
                    android:inputType="text"
                    android:maxLength="10"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question4title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question4"
                    style="@style/questionAndAnswers"/>

                <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                    <RadioButton android:id="@+id/radio_bioShock"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerBioShock"/>
                    <RadioButton android:id="@+id/radio_borderlands"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerBorderlands"/>
                    <RadioButton android:id="@+id/radio_portal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPortal"/>
                </RadioGroup>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question5title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question5"
                    style="@style/questionAndAnswers"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest5GameBoy"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerGameBoy"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuestPSP"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPSP"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest5Wii"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerWii"/>
                </LinearLayout>

                <Button
                    android:id="@+id/submitButton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/submit"
                    android:layout_gravity="center_horizontal"/>
            </LinearLayout>

        </ScrollView>

    </android.support.v7.widget.CardView>

</RelativeLayout>
```

I am getting the following errors in CardCornerRadius and CardElevation:

Android resource linking failed
  D:\AndroidStudioProjects\App\app\src\main\res\layout\activity_main.xml:12:
  AAPT: error: attribute cardCornerRadius (aka
  com.ksaitarun.app:cardCornerRadius) not found.

D:\AndroidStudioProjects\App\app\src\main\res\layout\activity_main.xml:12:
  AAPT: error: attribute cardElevation (aka
  com.ksaitarun.app:cardElevation) not found.

答:
Make sure you have added this library in build.gradle file

```<code>implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
</code>```

Body:
I've defined my layout as below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    tools:context=".MainActivity">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="32dp"
        card_view:cardCornerRadius="8dp"
        card_view:cardElevation="16dp">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="16dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question1title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question1"
                    style="@style/questionAndAnswers"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerMario"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerMario"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerDonkey"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerDonkeyKong"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerPortal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPortal"/>
                </LinearLayout>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question2title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question2"
                    style="@style/questionAndAnswers"/>

                <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                    <RadioButton android:id="@+id/radio_1979"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1979"/>
                    <RadioButton android:id="@+id/radio_1989"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1989"/>
                    <RadioButton android:id="@+id/radio_1999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1999"/>
                </RadioGroup>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question3title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question3"
                    style="@style/questionAndAnswers"/>

                <EditText
                    android:id="@+id/answerInputUserLastName"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/LastNameLaraHint"
                    android:inputType="text"
                    android:maxLength="10"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question4title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question4"
                    style="@style/questionAndAnswers"/>

                <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                    <RadioButton android:id="@+id/radio_bioShock"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerBioShock"/>
                    <RadioButton android:id="@+id/radio_borderlands"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerBorderlands"/>
                    <RadioButton android:id="@+id/radio_portal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPortal"/>
                </RadioGroup>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question5title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question5"
                    style="@style/questionAndAnswers"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest5GameBoy"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerGameBoy"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuestPSP"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPSP"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest5Wii"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerWii"/>
                </LinearLayout>

                <Button
                    android:id="@+id/submitButton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/submit"
                    android:layout_gravity="center_horizontal"/>
            </LinearLayout>

        </ScrollView>

    </android.support.v7.widget.CardView>

</RelativeLayout>

I am getting the following errors in CardCornerRadius and CardElevation:

Android resource linking failed
  D:\AndroidStudioProjects\App\app\src\main\res\layout\activity_main.xml:12:
  AAPT: error: attribute cardCornerRadius (aka
  com.ksaitarun.app:cardCornerRadius) not found.

D:\AndroidStudioProjects\App\app\src\main\res\layout\activity_main.xml:12:
  AAPT: error: attribute cardElevation (aka
  com.ksaitarun.app:cardElevation) not found.

Body:
Make sure you have added this library in build.gradle file

implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'


问:
How to apply media query for iPads?
I'm optimizing my website across most popular devices using media queries in CSS file.
The problem the line below isn't working on iPads:

```<code>@media only screen and (min-device-width: 415px) and (max-device-width: 768px) {
</code>```

even though iPads comes with 768px width the CSS is all messed up. Interestingly, when I use mobile device simulator in dev tools everything looks fine.

Is there some gotchas I should be aware of ?

答:
Have you tried it so it is like this. Leave out device and just put min-width or max-width:</p>

```<code>@media (min-width: 415px) and (max-width: 768px) { css here }
</code>```

Title: How to apply media query for iPads?

Body:
I'm optimizing my website across most popular devices using media queries in CSS file.
The problem the line below isn't working on iPads:

@media only screen and (min-device-width: 415px) and (max-device-width: 768px) {

even though iPads comes with 768px width the CSS is all messed up. Interestingly, when I use mobile device simulator in dev tools everything looks fine.

Is there some gotchas I should be aware of ?

Body:
Have you tried it so it is like this. Leave out device and just put min-width or max-width:

@media (min-width: 415px) and (max-width: 768px) { css here }


问:
subFolder is empty when using a Google IoT Core gateway and Pub/Sub
I have a device publishing through a gateway on the events topic (/devices/<dev_id>/events/motion) to PubSub. It's landing in PubSub correctly but subFolder is just an empty string.

On the gateway I'm publishing using the code below. f"mb.{device_id}" is the device_id (not the gateway ID and attribute could be anything - motion, temperature, etc

def report(self, device_id, attribute, value):
    topic = f"/devices/mb.{device_id}/events/{attribute}"
    timestamp = datetime.utcnow().timestamp()
    client.publish(topic, json.dumps({"v": value, "ts": timestamp}))

```

<p>And this is the <strong>cloud function</strong> listening on the PubSub queue.</p>

<pre class="lang-py prettyprint-override"><code>def iot_to_bigtable(event, context):
    payload = json.loads(base64.b64decode(event["data"]).decode("utf-8"))
    timestamp = payload.get("ts")
    value = payload.get("v")
    if not timestamp or value is None:
        raise BadDataException()
    attributes = event.get("attributes", {})
    device_id = attributes.get("deviceId")
    registry_id = attributes.get("deviceRegistryId")
    attribute = attributes.get("subFolder")
    if not device_id or not registry_id or not attribute:
        raise BadDataException()
</code>```

A sample of the event in Pub/Sub:

{
    @type: 'type.googleapis.com/google.pubsub.v1.PubsubMessage',
    attributes: {
        deviceId: 'mb.26727bab-0f37-4453-82a4-75d93cb3f374',
        deviceNumId: '2859313639674234',
        deviceRegistryId: 'mb-staging',
        deviceRegistryLocation: 'europe-west1',
        gatewayId: 'mb.42e29cd5-08ad-40cf-9c1e-a1974144d39a',
        projectId: 'mb-staging',
        subFolder: ''
    },
    data: 'eyJ2IjogImxvdyIsICJ0cyI6IDE1OTA3NjgzNjcuMTMyNDQ4fQ=='
}
```

Why is subFolder empty? Based on the docs I was expecting it to be the attribute (i.e. motion or temperature)

答:
This issue has nothing to do with Cloud IoT Core. It is instead caused by how Pub/Sub handles failed messages. It was retrying messages from ~12 hours ago that had failed (and didn't have an attribute).

You fix this by purging the Subscription in Pub/Sub.

Body:
I have a device publishing through a gateway on the events topic (/devices/<dev_id>/events/motion) to PubSub. It's landing in PubSub correctly but subFolder is just an empty string.

On the gateway I'm publishing using the code below. f"mb.{device_id}" is the device_id (not the gateway ID and attribute could be anything - motion, temperature, etc

def report(self, device_id, attribute, value):
    topic = f"/devices/mb.{device_id}/events/{attribute}"
    timestamp = datetime.utcnow().timestamp()
    client.publish(topic, json.dumps({"v": value, "ts": timestamp}))

And this is the cloud function listening on the PubSub queue.

def iot_to_bigtable(event, context):
    payload = json.loads(base64.b64decode(event["data"]).decode("utf-8"))
    timestamp = payload.get("ts")
    value = payload.get("v")
    if not timestamp or value is None:
        raise BadDataException()
    attributes = event.get("attributes", {})
    device_id = attributes.get("deviceId")
    registry_id = attributes.get("deviceRegistryId")
    attribute = attributes.get("subFolder")
    if not device_id or not registry_id or not attribute:
        raise BadDataException()

A sample of the event in Pub/Sub:

{
    @type: 'type.googleapis.com/google.pubsub.v1.PubsubMessage',
    attributes: {
        deviceId: 'mb.26727bab-0f37-4453-82a4-75d93cb3f374',
        deviceNumId: '2859313639674234',
        deviceRegistryId: 'mb-staging',
        deviceRegistryLocation: 'europe-west1',
        gatewayId: 'mb.42e29cd5-08ad-40cf-9c1e-a1974144d39a',
        projectId: 'mb-staging',
        subFolder: ''
    },
    data: 'eyJ2IjogImxvdyIsICJ0cyI6IDE1OTA3NjgzNjcuMTMyNDQ4fQ=='
}

Why is subFolder empty? Based on the docs I was expecting it to be the attribute (i.e. motion or temperature)


问:
Is there a way to covert all columns with int to float
I want to convert all the columns of dataframe with dtype as int to float. How can I achieve this? I dont know the name of the columns which are int so might need to use if == int or something.

答:
try this, select_dtypes</p>

```<code>columns = df.select_dtypes(include='int').columns

df[columns] = df[columns].astype(float)
</code>```

Body:
try this, select_dtypes

columns = df.select_dtypes(include='int').columns

df[columns] = df[columns].astype(float)


问:
How to specify a Composite Primary Key while defining a Custom Interface as a JpaRepository?
I have two Entity class with below attributes:

```<code>class Parent {
    @Id
    string columnA;

    string columnB;
}

class Child {
    //confused here: ManyToOne with Parent class

    string columnC;
    string columnD;
}
</code>```

I want SQL Tables as below:

Parent ( columnA(Primary Key), columnB )

Child ( columnA(Foreign Key), columnC, columnD ) where,

primary key = (columnA, columnC) and,

(Child -> ManyToOne -> Parent) relationship.

Question1: How can I create the correct Entity class for the Child?

Question2: I want to have a childRepository interface that extends JpaRepository. I am confused, how to specify the composite primary key?

```<code>public interface childRepository extends JpaRepository<Child, 'What to write here?'>{
}
</code>```

答:
Question-1: It depends on your business logic.

Question-2: Create new class in order to store child entity's ids

```<code>@Embeddable
public class ChildId implements Serializable{

   private String columnA;
   private String columnC;

   // getters and setters
}
</code>```

In your child class:

```<code>@EmbeddedId
private ChildId childId;

@MapsId(value = "columnA")
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "columnA")
private Parent parent;
</code>```

In your ChildRepository:

```<code>public interface ChildRepository extends JpaRepository<Child, ChildId>{}
</code>```

PS: you can apply other ways according to business logic

Body:
I have two Entity class with below attributes:

class Parent {
    @Id
    string columnA;

    string columnB;
}

class Child {
    //confused here: ManyToOne with Parent class

    string columnC;
    string columnD;
}

I want SQL Tables as below:

Parent ( columnA(Primary Key), columnB )

Child ( columnA(Foreign Key), columnC, columnD ) where,

primary key = (columnA, columnC) and,

(Child -> ManyToOne -> Parent) relationship.

Question1: How can I create the correct Entity class for the Child?

Question2: I want to have a childRepository interface that extends JpaRepository. I am confused, how to specify the composite primary key?

public interface childRepository extends JpaRepository<Child, 'What to write here?'>{
}

Body:
Question-1: It depends on your business logic.

Question-2: Create new class in order to store child entity's ids

@Embeddable
public class ChildId implements Serializable{

   private String columnA;
   private String columnC;

   // getters and setters
}

In your child class:

@EmbeddedId
private ChildId childId;

@MapsId(value = "columnA")
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "columnA")
private Parent parent;

In your ChildRepository:

public interface ChildRepository extends JpaRepository<Child, ChildId>{}

PS: you can apply other ways according to business logic


问:
String.IsNullOrEmpty like function for VARCHARs in SQL?
Say I've got a function or stored procedure that takes in several VARCHAR parameters.  I've gotten tired of writing SQL like this to test if these parameters have a value:

```<code>IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
BEGIN
    -- do stuff
END
</code>```

There's gotta be a better way to do this.  Isn't there?

答:
please use case command.case structure is:

case when condition then 'some value' else 'some other value' end

some example:

```<code>declare @SomeVarcharParm as nvarchar(20)=''
declare @SomeVarcharParm2 as nvarchar(20)=''

--select 1 or 2
select case when @SomeVarcharParm is null or @SomeVarcharParm='' then 1 else 2 end

--if null or empty set 'empty' value else set @SomeVarcharParm value
select @SomeVarcharParm2=case when @SomeVarcharParm is null or @SomeVarcharParm='' then 'empty' else @SomeVarcharParm end

--use null or empty in update command
update tbl1
set field1=case when field1 is null or field1='' then @SomeVarcharParm2 else field1 end
where id=1
</code>```

Body:
Say I've got a function or stored procedure that takes in several VARCHAR parameters.  I've gotten tired of writing SQL like this to test if these parameters have a value:

IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
BEGIN
    -- do stuff
END

There's gotta be a better way to do this.  Isn't there?

Body:
please use case command.case structure is:

case when condition then 'some value' else 'some other value' end

some example:

declare @SomeVarcharParm as nvarchar(20)=''
declare @SomeVarcharParm2 as nvarchar(20)=''

--select 1 or 2
select case when @SomeVarcharParm is null or @SomeVarcharParm='' then 1 else 2 end

--if null or empty set 'empty' value else set @SomeVarcharParm value
select @SomeVarcharParm2=case when @SomeVarcharParm is null or @SomeVarcharParm='' then 'empty' else @SomeVarcharParm end

--use null or empty in update command
update tbl1
set field1=case when field1 is null or field1='' then @SomeVarcharParm2 else field1 end
where id=1


问:
How to draw a grouped barplot of two dataframes?
I have two things I want to compare:

Data from a questionaire that I collected myself.

The distribution of the norm sample from the people that have developed the questionaire.

Here is a barplot of my data:

```<code>ggplot(myData) +
  geom_bar(mapping = aes(x = DepriSymptoms, y = ..prop..,  group = 1)) +
  theme_bw() +
  scale_y_continuous(labels = scales::percent_format()) +
  labs(y = "Participant Count",
       x = "Symptoms",
       title = "Depression Symptom Severity")
</code>```

Barplot of my data

I don't have the actual data of the norm sample, I only know the precentages:

none: 70%

suspected: 9%

light: 15%

medium: 4%

severe: 1%

My goal is a grouped ggplot2 barplot that looks similar to this:

Mockup of grouped barplot

One color would be my data, the other color would be the norm sample.

Here is my Question: What is the best way to get ggplot2 to draw the bars for the norm sample, since I don't have the data?

I thought of creating a new dataframe with "fake" data that has the right percentages and using two geom_bar layers, but now they are on top of each other and I can't use a fill variable to group by, since they are from different dataframes.

```<code>
ggplot() +
  geom_bar(data = myData, mapping = aes(x = DepriSymptoms, y = ..prop..,  group = 1), alpha = 0.5, fill = 'blue') +
  geom_bar(data = fakeData, mapping = aes(x = DepriSymptoms, y = ..prop..,  group = 2), alpha = 0.5, fill = 'red') +
  scale_y_continuous(labels = scales::percent_format())

</code>```

I'm sure there has to be a more elegant way to do this.

I hope I managed to explain my situation somewhat understandable.

答:
What I got from your question is that you have one type of data for which you have individual cases, and one type of data for which you have proportions. These data should be represented on the same bar graph.

Since I don't have a sample of your data I'll use a standard dataset and reshape it a bit to reflect your case.

library(tidyverse)

# Suppose df1 is the equivalent of DepriSymptoms
df1 <- mpg[mpg$year == 1999,]

# And we'll shape df2 to be similar to DepriNorm (proportion data)
df2 <- mpg[mpg$year == 2008,]
df2 <- df2 %>% group_by(class) %>%
  summarise(n = n()) %>%
  ungroup() %>%
  mutate(prop = n / sum(n))

head(df2)
#> # A tibble: 6 x 3
#>   class          n   prop
#>   <chr>      <int>  <dbl>
#> 1 2seater        3 0.0256
#> 2 compact       22 0.188
#> 3 midsize       21 0.179
#> 4 minivan        5 0.0427
#> 5 pickup        17 0.145
#> 6 subcompact    16 0.137
```

<p>So in the data above we can count the cases in <code>df1</code> but must use the <code>prop</code> column in <code>df2</code>. You can totally use the two layers approach, but you'd have to be mindful that layers can't see into other layers and thus the dodging from the bar groups is absent. Two tips here:</p>

<ul>
<li>You can use <code>geom_col()</code> as a shortcut for <code>geom_bar(..., stat = "identity")</code>, so it will not try to count your proportion data.</li>
<li>You can use <code>position = position_nudge(x = ...)</code> to offset your bars so that they appear grouped, even though they are on different layers. You'd also have to change the width of the bars.</li>
</ul>

```ggplot(df1, aes(class)) +
  geom_bar(aes(y = after_stat(prop), group = 1, fill = "A"),
           width = 0.4, position = position_nudge(0.22)) +
  geom_col(aes(y = prop, fill = "B"), data = df2,
           width = 0.4, position = position_nudge(-0.22))
```

Created on 2020-05-30 by the reprex package (v0.3.0)

Body:
I have two things I want to compare:

Data from a questionaire that I collected myself.

The distribution of the norm sample from the people that have developed the questionaire.

Here is a barplot of my data:

ggplot(myData) +
  geom_bar(mapping = aes(x = DepriSymptoms, y = ..prop..,  group = 1)) +
  theme_bw() +
  scale_y_continuous(labels = scales::percent_format()) +
  labs(y = "Participant Count",
       x = "Symptoms",
       title = "Depression Symptom Severity")

Barplot of my data

I don't have the actual data of the norm sample, I only know the precentages:

none: 70%

suspected: 9%

light: 15%

medium: 4%

severe: 1%

My goal is a grouped ggplot2 barplot that looks similar to this:

Mockup of grouped barplot

One color would be my data, the other color would be the norm sample.

Here is my Question: What is the best way to get ggplot2 to draw the bars for the norm sample, since I don't have the data?

I thought of creating a new dataframe with "fake" data that has the right percentages and using two geom_bar layers, but now they are on top of each other and I can't use a fill variable to group by, since they are from different dataframes.

ggplot() +
  geom_bar(data = myData, mapping = aes(x = DepriSymptoms, y = ..prop..,  group = 1), alpha = 0.5, fill = 'blue') +
  geom_bar(data = fakeData, mapping = aes(x = DepriSymptoms, y = ..prop..,  group = 2), alpha = 0.5, fill = 'red') +
  scale_y_continuous(labels = scales::percent_format())

I'm sure there has to be a more elegant way to do this.

I hope I managed to explain my situation somewhat understandable.

Body:
What I got from your question is that you have one type of data for which you have individual cases, and one type of data for which you have proportions. These data should be represented on the same bar graph.

Since I don't have a sample of your data I'll use a standard dataset and reshape it a bit to reflect your case.

library(tidyverse)

# Suppose df1 is the equivalent of DepriSymptoms
df1 <- mpg[mpg$year == 1999,]

# And we'll shape df2 to be similar to DepriNorm (proportion data)
df2 <- mpg[mpg$year == 2008,]
df2 <- df2 %>% group_by(class) %>%
  summarise(n = n()) %>%
  ungroup() %>%
  mutate(prop = n / sum(n))

head(df2)
#> # A tibble: 6 x 3
#>   class          n   prop
#>   <chr>      <int>  <dbl>
#> 1 2seater        3 0.0256
#> 2 compact       22 0.188
#> 3 midsize       21 0.179
#> 4 minivan        5 0.0427
#> 5 pickup        17 0.145
#> 6 subcompact    16 0.137

So in the data above we can count the cases in df1 but must use the prop column in df2. You can totally use the two layers approach, but you'd have to be mindful that layers can't see into other layers and thus the dodging from the bar groups is absent. Two tips here:

You can use geom_col() as a shortcut for geom_bar(..., stat = "identity"), so it will not try to count your proportion data.

You can use position = position_nudge(x = ...) to offset your bars so that they appear grouped, even though they are on different layers. You'd also have to change the width of the bars.

ggplot(df1, aes(class)) +
  geom_bar(aes(y = after_stat(prop), group = 1, fill = "A"),
           width = 0.4, position = position_nudge(0.22)) +
  geom_col(aes(y = prop, fill = "B"), data = df2,
           width = 0.4, position = position_nudge(-0.22))

Created on 2020-05-30 by the reprex package (v0.3.0)


问:
Unable to install Deno in Ubuntu 18.04
I am trying to install Deno in my Ubuntu machine but I can't. Ubuntu Version is 18.04.

I am using this command:

```<code>curl -fsSL https://deno.land/x/install/install.sh | sh
</code>```

It has provided by Deno's official page. After installing Deno, I set below configuration in .bash_profile.

```<code>export DENO_INSTALL="/home/azmul/.local"
export PATH="$DENO_INSTALL/bin:$PATH"
</code>```

After doing this when I try to run deno command on my terminal. I always found 'deno' not found  on my terminal. I don't know what should i do. If anyone has a good sound about this please give me an answer.

答:
Edit ~/.bashrc file

Do the following changes

gedit ~/.bashrc

Add the following code to end of the line

export PATH="$PATH:$HOME/.deno/bin:$PATH"

source .bashrc file

source ~/.bashrc

Now check

deno -V

It will show the version of deno like

deno 1.0.3

Title: Unable to install Deno in Ubuntu 18.04

Body:
I am trying to install Deno in my Ubuntu machine but I can't. Ubuntu Version is 18.04.

I am using this command:

curl -fsSL https://deno.land/x/install/install.sh | sh

It has provided by Deno's official page. After installing Deno, I set below configuration in .bash_profile.

export DENO_INSTALL="/home/azmul/.local"
export PATH="$DENO_INSTALL/bin:$PATH"

After doing this when I try to run deno command on my terminal. I always found 'deno' not found  on my terminal. I don't know what should i do. If anyone has a good sound about this please give me an answer.


问:
Python script inside Online PowerBI Pro
I have read some tutorials about the Python integration inside Power BI reports. This tutorials works on Power BI Desktop.

I have only tried on online version of Power BI (power BI pro). The "P" icon is avaiable in visualization tool box but it does not show me python prompt in the bottom of the screen.

I suppose python is supported on Power BI pro because the icon is present ?

Any idea ?

答:
The python editing experience is limited in the Web service, as well as other report creation tools.

You use Power BI Desktop to create your report which has the Python editor and access to the Python installation on your PC. Once created you load it to the service, then it will work. You may need to use a Personal Data Gateway if you are using a Python script in Power Query.

Limitations are outlined here:

https://powerbi.microsoft.com/en-us/blog/python-visualizations-in-power-bi-service/

Pro doesn't replace desktop, the device is mainly used for collaboration and sharing, as it has limited report editing and creation tools and can only link to a limited number of data sources.

Title: Python script inside Online PowerBI Pro


问:
Why would counting instances of vector values using sum() in R return NA
I imported the 2018 BRFSS data (available online) into R using the read.xport() and upon inspecting variable values, I'm unable to comprehend how r is handling the imported values. For example, in the imported data frame, the the class for the diabetes variable (DIABETE3) is numeric but when I attempt counting the specific values for each level using, say  sum(BRFSS$DIABETE3==1), the result is NA. Here is a small vector for the first 20 values of DIABETE3 variable to demonstrate:

diabetes <-c(3, 3, 1, 3, 3, 4, 3, 3, 1, 3, 3, 3, 3, 1, 3, 3, 1, 3, 3, 3). If I use, sum(BRFSS$DIABETE3==1) to count instances of value 1, the result is NA, but clearly that's not the case.

However, using sum(is.na(BRFSS$DIABETE3)) returns the correct number of NA values. Using table(BRFSS$DIABETE3) also returns the proper frequency distribution for this variable.

答:
When there are no NA values you can count instances of particular value by using

```<code>diabetes <- c(3, 3, 1, 3, 3, 4, 3, 3, 1, 3, 3, 3, 3, 1, 3, 3, 1, 3, 3, 3)
sum(diabetes == 1)
#[1] 4
</code>```

But if you have NA's in your vector, this will fail

```<code>diabetes <- c(diabetes, NA)
sum(diabetes == 1)
#[1] NA
</code>```

Because when you compare NA values with == it returns NA and to remove them you can set na.rm parameter as TRUE.

```<code>sum(diabetes == 1, na.rm = TRUE)
#[1] 4
</code>```

Body:
When there are no NA values you can count instances of particular value by using

diabetes <- c(3, 3, 1, 3, 3, 4, 3, 3, 1, 3, 3, 3, 3, 1, 3, 3, 1, 3, 3, 3)
sum(diabetes == 1)
#[1] 4

But if you have NA's in your vector, this will fail

diabetes <- c(diabetes, NA)
sum(diabetes == 1)
#[1] NA

Because when you compare NA values with == it returns NA and to remove them you can set na.rm parameter as TRUE.

sum(diabetes == 1, na.rm = TRUE)
#[1] 4


问:
CStdioFile cannot work with files larger than 2GB?
I am using Visual C++ 2008. In VC++ 2008, CFile supports 2^64 huge files. So I think CStdioFile should also support.

However, when using CStdioFile::GetLength() on a file larger than 2GB, I get a CFileException, below is the code snippet:

```<code>void CTestCStdioFileDlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    CStdioFile MyFile;
    CString strLine;
    ULONGLONG uLength;

    strLine = _T("This is a line.");

    if (MyFile.Open(_T("C:\\Temp\\MyTest.dat"), CFile::modeCreate | CFile::modeWrite | CFile::shareExclusive | CFile::typeBinary))
    {
        for (UINT uIndex = 0; uIndex = 200000000; uIndex ++)
        {
            MyFile.WriteString(strLine);
            uLength = MyFile.GetLength();
        }

        MyFile.Close();
    }
}
</code>```

After tracing into the CStdio::GetLength(), I find the following code snippet will raise exception, as below:

```<code>   nCurrent = ftell(m_pStream);            -> This will return -1
   if (nCurrent == -1)
      AfxThrowFileException(CFileException::invalidFile, _doserrno,
         m_strFileName);
</code>```

It is amazing that CStdioFile still use ftell instead of _ftelli64 to deal with the stream.

I then search the document for CStdioFile, I cannot find any document on CStdioFile::GetLength, the only related is https://learn.microsoft.com/en-us/cpp/mfc/reference/cstdiofile-class?view=vs-2019#seek, and it asks me to see fseek document. But in fseek document, I still not find any related to file size limit.

Finally I find a third-party site that indicates CStdioFile::GetLength contains error: http://www.flounder.com/msdn_documentation_errors_and_omissions.htm#CStdioFile::GetLength, but it does not provide a solution.

Other than these, there are hardly any questions or posts on the 2GB limit of CStdioFile online. That is really strange.

I try to check the source code of CStdioFile iN VC++ 2017 and it is same as that for 2008.

So whether there is a simple solution for the problem without rewriting the whole CStdioFile class?

答:
CStdioFile exists primarily for a single reason: It's constructor taking a FILE* argument. The purpose of this class is to wrap a C Runtime file and expose it through a CFile-compatible interface. The implementation inherits all of the C Runtime limitations, in particular the file size limit of 2GB.

To address this, there are several options:

If possible, drop the use of CStdioFile altogether. Unless you are interfacing with (legacy) C code, there's no striking reason to ever use it.

If that is not an option, derive a custom implementation from CStdioFile and override all class members that surface file-relative offsets (GetPosition(), GetLength(), Seek()). All other class members are unaffected, and can simply be inherited. (Note: Make sure to restore the current file pointer when implementing GetLength().)

Microsoft provides extensions to its C Runtime that offer 64-bit wide offsets (_ftelli64 and _fseeki64).

If you need to go with option 2, the following extension to CStdioFile can be used as a drop-in replacement with support for files larger than 2GB.

CStdioFileExt.h:

#pragma once

#include <afx.h>

class CStdioFileExt : public CStdioFile
{
    DECLARE_DYNAMIC(CStdioFileExt)
public:
    ULONGLONG GetPosition() const override;
    ULONGLONG GetLength() const override;
    ULONGLONG Seek(LONGLONG lOff, UINT nFrom) override;
};
```
<p><em>CStdioFileExt.cpp:</em></p>
<pre class="lang-cpp prettyprint-override"><code>#include "CStdioFileExt.h"

ULONGLONG CStdioFileExt::GetPosition() const
{
    ASSERT_VALID(this);
    ASSERT(m_pStream != NULL);

    auto const pos = _ftelli64(m_pStream);
    if (pos == -1L)
        AfxThrowFileException(CFileException::invalidFile, _doserrno, m_strFileName);
    return static_cast<ULONGLONG>(pos);
}

ULONGLONG CStdioFileExt::GetLength() const
{
    ASSERT_VALID(this);

    auto const nCurrent = _ftelli64(m_pStream);
    if (nCurrent == -1L)
        AfxThrowFileException(CFileException::invalidFile, _doserrno, m_strFileName);

    auto nResult = _fseeki64(m_pStream, 0, SEEK_END);
    if (nResult != 0)
        AfxThrowFileException(CFileException::badSeek, _doserrno, m_strFileName);

    auto const nLength = _ftelli64(m_pStream);
    if (nLength == -1L)
        AfxThrowFileException(CFileException::invalidFile, _doserrno, m_strFileName);
    nResult = _fseeki64(m_pStream, nCurrent, SEEK_SET);
    if (nResult != 0)
        AfxThrowFileException(CFileException::badSeek, _doserrno, m_strFileName);

    return static_cast<ULONGLONG>(nLength);
}

ULONGLONG CStdioFileExt::Seek(LONGLONG lOff, UINT nFrom)
{
    ASSERT_VALID(this);
    ASSERT(nFrom == begin || nFrom == end || nFrom == current);
    ASSERT(m_pStream != NULL);

    if (_fseeki64(m_pStream, lOff, nFrom) != 0)
        AfxThrowFileException(CFileException::badSeek, _doserrno, m_strFileName);

    auto const pos = _ftelli64(m_pStream);
    return static_cast<ULONGLONG>(pos);
}

IMPLEMENT_DYNAMIC(CStdioFileExt, CStdioFile)
</code>```

Body:
I am using Visual C++ 2008. In VC++ 2008, CFile supports 2^64 huge files. So I think CStdioFile should also support.

However, when using CStdioFile::GetLength() on a file larger than 2GB, I get a CFileException, below is the code snippet:

void CTestCStdioFileDlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    CStdioFile MyFile;
    CString strLine;
    ULONGLONG uLength;

    strLine = _T("This is a line.");

    if (MyFile.Open(_T("C:\\Temp\\MyTest.dat"), CFile::modeCreate | CFile::modeWrite | CFile::shareExclusive | CFile::typeBinary))
    {
        for (UINT uIndex = 0; uIndex = 200000000; uIndex ++)
        {
            MyFile.WriteString(strLine);
            uLength = MyFile.GetLength();
        }

        MyFile.Close();
    }
}

After tracing into the CStdio::GetLength(), I find the following code snippet will raise exception, as below:

   nCurrent = ftell(m_pStream);            -> This will return -1
   if (nCurrent == -1)
      AfxThrowFileException(CFileException::invalidFile, _doserrno,
         m_strFileName);

It is amazing that CStdioFile still use ftell instead of _ftelli64 to deal with the stream.

I then search the document for CStdioFile, I cannot find any document on CStdioFile::GetLength, the only related is https://learn.microsoft.com/en-us/cpp/mfc/reference/cstdiofile-class?view=vs-2019#seek, and it asks me to see fseek document. But in fseek document, I still not find any related to file size limit.

Finally I find a third-party site that indicates CStdioFile::GetLength contains error: http://www.flounder.com/msdn_documentation_errors_and_omissions.htm#CStdioFile::GetLength, but it does not provide a solution.

Other than these, there are hardly any questions or posts on the 2GB limit of CStdioFile online. That is really strange.

I try to check the source code of CStdioFile iN VC++ 2017 and it is same as that for 2008.

So whether there is a simple solution for the problem without rewriting the whole CStdioFile class?

Body:
CStdioFile exists primarily for a single reason: It's constructor taking a FILE* argument. The purpose of this class is to wrap a C Runtime file and expose it through a CFile-compatible interface. The implementation inherits all of the C Runtime limitations, in particular the file size limit of 2GB.

To address this, there are several options:

If possible, drop the use of CStdioFile altogether. Unless you are interfacing with (legacy) C code, there's no striking reason to ever use it.

If that is not an option, derive a custom implementation from CStdioFile and override all class members that surface file-relative offsets (GetPosition(), GetLength(), Seek()). All other class members are unaffected, and can simply be inherited. (Note: Make sure to restore the current file pointer when implementing GetLength().)

Microsoft provides extensions to its C Runtime that offer 64-bit wide offsets (_ftelli64 and _fseeki64).

If you need to go with option 2, the following extension to CStdioFile can be used as a drop-in replacement with support for files larger than 2GB.

CStdioFileExt.h:

#pragma once

#include <afx.h>

class CStdioFileExt : public CStdioFile
{
    DECLARE_DYNAMIC(CStdioFileExt)
public:
    ULONGLONG GetPosition() const override;
    ULONGLONG GetLength() const override;
    ULONGLONG Seek(LONGLONG lOff, UINT nFrom) override;
};

CStdioFileExt.cpp:

#include "CStdioFileExt.h"

ULONGLONG CStdioFileExt::GetPosition() const
{
    ASSERT_VALID(this);
    ASSERT(m_pStream != NULL);

    auto const pos = _ftelli64(m_pStream);
    if (pos == -1L)
        AfxThrowFileException(CFileException::invalidFile, _doserrno, m_strFileName);
    return static_cast<ULONGLONG>(pos);
}

ULONGLONG CStdioFileExt::GetLength() const
{
    ASSERT_VALID(this);

    auto const nCurrent = _ftelli64(m_pStream);
    if (nCurrent == -1L)
        AfxThrowFileException(CFileException::invalidFile, _doserrno, m_strFileName);

    auto nResult = _fseeki64(m_pStream, 0, SEEK_END);
    if (nResult != 0)
        AfxThrowFileException(CFileException::badSeek, _doserrno, m_strFileName);

    auto const nLength = _ftelli64(m_pStream);
    if (nLength == -1L)
        AfxThrowFileException(CFileException::invalidFile, _doserrno, m_strFileName);
    nResult = _fseeki64(m_pStream, nCurrent, SEEK_SET);
    if (nResult != 0)
        AfxThrowFileException(CFileException::badSeek, _doserrno, m_strFileName);

    return static_cast<ULONGLONG>(nLength);
}

ULONGLONG CStdioFileExt::Seek(LONGLONG lOff, UINT nFrom)
{
    ASSERT_VALID(this);
    ASSERT(nFrom == begin || nFrom == end || nFrom == current);
    ASSERT(m_pStream != NULL);

    if (_fseeki64(m_pStream, lOff, nFrom) != 0)
        AfxThrowFileException(CFileException::badSeek, _doserrno, m_strFileName);

    auto const pos = _ftelli64(m_pStream);
    return static_cast<ULONGLONG>(pos);
}

IMPLEMENT_DYNAMIC(CStdioFileExt, CStdioFile)


问:
Print local html file from uiwebview (iOs)
i need to introduce printing feature to my app, that is made with phonegap framework. there is a solution to implement airprint from javascript or use native method? thanks.</p>

答:
Create a plugin for phonegap using the code suggested here...

https://groups.google.com/forum/#!topic/phonegap/nAt0TqsStgc

which will point you to

http://marceloprogramming.blogspot.com/2010/12/resolving-runtime-issues-with-airprint.html


问:
Actually delete a git commit in such a way that it disappears from the log
I cannot find a way to delete a targeted commit from the log. Documentation about deleting commits either just resets a pointer using reset (which does not delete anything, it just resets pointers), or rebase, which creates a new structure of some sort at the deleted commit. The hash of the targeted commit still appears. There may be old documentation out there related to

```<code>git rebase -i fork1~1 fork1~3
</code>```

because in older messages, it states to delete a line in the editor, that is, the line corresponding to the targeted commit. When I get into the interactive editor, one of the choices is "drop", which it says removes the commit. However, I have not successfully removed any commits in the sense that they disappear from the log. I insert the word drop, and it creates some sort of fork-looking thing in the log output. But I can still see the hash of the commit I am trying to remove. Simply put, I want to identify a hash to remove and have it no longer appear in the log.

So, the idea here is to drop 1bc7112:

```<code>*   4518859 (refs/stash) WIP on fork3: 8c438a9 Added first.bsh back in
|\
| * 1bc7112 index on fork3: 8c438a9 Added first.bsh back in
|/
* 8c438a9 Added first.bsh back in
* eef828f (HEAD -> fork4) Removed using git rm
* c21cda0 Third change.
</code>```

答:
reset to older commit:
git reset --hard <old commit>

Body:
I cannot find a way to delete a targeted commit from the log. Documentation about deleting commits either just resets a pointer using reset (which does not delete anything, it just resets pointers), or rebase, which creates a new structure of some sort at the deleted commit. The hash of the targeted commit still appears. There may be old documentation out there related to

git rebase -i fork1~1 fork1~3

because in older messages, it states to delete a line in the editor, that is, the line corresponding to the targeted commit. When I get into the interactive editor, one of the choices is "drop", which it says removes the commit. However, I have not successfully removed any commits in the sense that they disappear from the log. I insert the word drop, and it creates some sort of fork-looking thing in the log output. But I can still see the hash of the commit I am trying to remove. Simply put, I want to identify a hash to remove and have it no longer appear in the log.

So, the idea here is to drop 1bc7112:

*   4518859 (refs/stash) WIP on fork3: 8c438a9 Added first.bsh back in
|\
| * 1bc7112 index on fork3: 8c438a9 Added first.bsh back in
|/
* 8c438a9 Added first.bsh back in
* eef828f (HEAD -> fork4) Removed using git rm
* c21cda0 Third change.


问:
"rvest" not fetching the product details using html_nodes()
I was using rvest for scraping the details of the product (Names, Price, and Availability) on amazon's product search results. I was able to fetch the webpage with read_html(), but I am not able to fetch the details of the product (Names, Price, and Availability). The page has  tag with class as class = "a-size-medium a-color-base a-text-normal". I have used html_nodes("span.a-size-medium a-color-base a-text-normal"), but got NA.

Here is the reproducible code:

```<code>library(rvest)
library(xml2)

url <- "https://www.amazon.in/s?k=Smartphone&rh=n%3A1389401031&ref=nb_sb_noss"

page <- read_html(url)

data <- page%>%
  html_node("span.a-size-medium a-color-base a-text-normal") %>%
  html_text()

print(data)
</code>```

答:
You just need to change the css selector a little bit. I was able to get the names and the prices, the availability was a little bit trickier :/</p>

```<code>library(rvest)
library(xml2)

url <- "https://www.amazon.in/s?k=Smartphone&rh=n%3A1389401031&ref=nb_sb_noss"

page <- read_html(url)

name <- page %>% html_nodes(".a-size-medium.a-color-base.a-text-normal") %>% html_text()

price <- page %>% html_nodes(".a-price-whole") %>% html_text()
</code>```

Body:
I was using rvest for scraping the details of the product (Names, Price, and Availability) on amazon's product search results. I was able to fetch the webpage with read_html(), but I am not able to fetch the details of the product (Names, Price, and Availability). The page has  tag with class as class = "a-size-medium a-color-base a-text-normal". I have used html_nodes("span.a-size-medium a-color-base a-text-normal"), but got NA.

Here is the reproducible code:

library(rvest)
library(xml2)

url <- "https://www.amazon.in/s?k=Smartphone&rh=n%3A1389401031&ref=nb_sb_noss"

page <- read_html(url)

data <- page%>%
  html_node("span.a-size-medium a-color-base a-text-normal") %>%
  html_text()

print(data)

Body:
You just need to change the css selector a little bit. I was able to get the names and the prices, the availability was a little bit trickier :/

library(rvest)
library(xml2)

url <- "https://www.amazon.in/s?k=Smartphone&rh=n%3A1389401031&ref=nb_sb_noss"

page <- read_html(url)

name <- page %>% html_nodes(".a-size-medium.a-color-base.a-text-normal") %>% html_text()

price <- page %>% html_nodes(".a-price-whole") %>% html_text()


问:
why is the transformation matrices behaving differently
I get different results when scaling objects.

The  objects have four different glm::vec3 values

```<code> 1) Position , Rotation , Scaling , Center Point
</code>```

This is the  Transformation Matrix of the object

```<code>   TransformationMatrix = PositionMatrix() * RotationMatrix() * ScalingMatrix();
</code>```

The rotation and scaling Matrix looks like this.

```<code>glm::vec3 pivotVector(pivotx, pivoty, pivotz);
glm::mat4 TransPivot = glm::translate(glm::mat4x4(1.0f), pivotVector);
glm::mat4 TransPivotInverse = glm::translate(glm::mat4x4(1.0f), -pivotVector);
glm::mat4 TransformationScale = glm::scale(glm::mat4(1.0), glm::vec3(scax, scay, scaz));
return   TransPivot * TransformationScale * TransPivotInverse;
</code>```

In the first case.

I move the rectangle object to 200 units in x.

Than i scale the group which is at position x = 0.0

so the final matrix for the rectangle object is

```<code> finalMatrix = rectangleTransformationMatrix * groupTransformationMatrix
</code>```

The result i what i expected.The rectangle scales and moves towards the center of the screen.

Now if i do the same thing with three containers.

Here i move the group container to 200 and scale the Top container which is at position 0.0

```<code>   finalMatrix = rectangleTransformationMatrix * groupTransformationMatrix * TopTransformationMatrix
</code>```

the rectangle scales at its own position as if the center point of the screen has also moved 200 units.

If i add -200 units to the pivot point x of the top container than i get the result what i expected.

where rectangle moves towards the center of the screen and scales.

If someone can please explain me why i need to add -200 units to the center point of the Top container.Whereas in the first case i did not need to add any value to the pivot point of the scaling container.

when both the operations are identical in nature.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

First case

```<code>Rectangle - > position( x = 200 , y = 0, z = 0) , scaling( 1.0 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
glm::mat4 PositionMatrix = glm::position( // fill the values);
glm::mat4 ScalingMatrix = glm::scaling( // fill the values);
glm::mat4 RotationMatrix = glm::rotate( // fill the values);
RectangleMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();
</code>```

the matrix for group

```<code> froup - > position( x = 0.0 , y = 0, z = 0) , scaling( 0.5 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
groupMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();
</code>```

final result
 finalMatrix = RectangleMatrix * groupMatrix

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Second case

```<code>Rectangle - > position( x = 0 , y = 0, z = 0) , scaling( 1.0 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
glm::mat4 PositionMatrix = glm::position( // fill the values);
glm::mat4 ScalingMatrix = glm::scaling( // fill the values);
glm::mat4 RotationMatrix = glm::rotate( // fill the values);
RectangleMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();
</code>```

the matrix for group

```<code> group - > position( x = 200.0 , y = 0, z = 0) , scaling( 1.0 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
groupMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();
</code>```

the matrix for Top

```<code> Top - > position( x = 0.0 , y = 0, z = 0) , scaling( 0.5 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
TopMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();
</code>```

final result
 finalMatrix = RectangleMatrix * groupMatrix *  TopMatrix

答:
Matrix operations are not Commutative. scale * translate is not the same as translate * scale

If you have a translation of 200 and and a scale of 0.2, then

```<code>translate(200) * scale(0.2)
</code>```

gives object scaled by 0.2 and translated by 200. But

```<code>scale(0.2) * translate(200)
</code>```

gives object scaled by 0.2 and translated by 40 (0.2*200).

If you have 2 matrices:

groupMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();
TopMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();
```

<p>Then <code>groupMatrix * TopMatrix</code> is the same as</p>

<pre class="lang-cpp prettyprint-override"><code>groupPositionMatrix * groupRotationMtrix * groupScalingMatrix * topPositionMatrix * topRotationMtrix * topScalingMatrix
</code>```

The result is different if the scale is encoded in groupScalingMatrix or topScalingMatrix respectively the translation is encoded in groupPositionMatrix or topPositionMatrix.

Body:
I get different results when scaling objects.

The  objects have four different glm::vec3 values

 1) Position , Rotation , Scaling , Center Point

This is the  Transformation Matrix of the object

   TransformationMatrix = PositionMatrix() * RotationMatrix() * ScalingMatrix();

The rotation and scaling Matrix looks like this.

glm::vec3 pivotVector(pivotx, pivoty, pivotz);
glm::mat4 TransPivot = glm::translate(glm::mat4x4(1.0f), pivotVector);
glm::mat4 TransPivotInverse = glm::translate(glm::mat4x4(1.0f), -pivotVector);
glm::mat4 TransformationScale = glm::scale(glm::mat4(1.0), glm::vec3(scax, scay, scaz));
return   TransPivot * TransformationScale * TransPivotInverse;

In the first case.

I move the rectangle object to 200 units in x.

Than i scale the group which is at position x = 0.0

so the final matrix for the rectangle object is

 finalMatrix = rectangleTransformationMatrix * groupTransformationMatrix

The result i what i expected.The rectangle scales and moves towards the center of the screen.

Now if i do the same thing with three containers.

Here i move the group container to 200 and scale the Top container which is at position 0.0

   finalMatrix = rectangleTransformationMatrix * groupTransformationMatrix * TopTransformationMatrix

the rectangle scales at its own position as if the center point of the screen has also moved 200 units.

If i add -200 units to the pivot point x of the top container than i get the result what i expected.

where rectangle moves towards the center of the screen and scales.

If someone can please explain me why i need to add -200 units to the center point of the Top container.Whereas in the first case i did not need to add any value to the pivot point of the scaling container.

when both the operations are identical in nature.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

First case

Rectangle - > position( x = 200 , y = 0, z = 0) , scaling( 1.0 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
glm::mat4 PositionMatrix = glm::position( // fill the values);
glm::mat4 ScalingMatrix = glm::scaling( // fill the values);
glm::mat4 RotationMatrix = glm::rotate( // fill the values);
RectangleMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();

the matrix for group

 froup - > position( x = 0.0 , y = 0, z = 0) , scaling( 0.5 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
groupMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();

final result
 finalMatrix = RectangleMatrix * groupMatrix

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Second case

Rectangle - > position( x = 0 , y = 0, z = 0) , scaling( 1.0 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
glm::mat4 PositionMatrix = glm::position( // fill the values);
glm::mat4 ScalingMatrix = glm::scaling( // fill the values);
glm::mat4 RotationMatrix = glm::rotate( // fill the values);
RectangleMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();

the matrix for group

 group - > position( x = 200.0 , y = 0, z = 0) , scaling( 1.0 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
groupMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();

the matrix for Top

 Top - > position( x = 0.0 , y = 0, z = 0) , scaling( 0.5 , 1.0 , 1.0 ) , Rotation( 0.0 , 0.0 , 0.0 )
TopMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();

final result
 finalMatrix = RectangleMatrix * groupMatrix *  TopMatrix

Body:
Matrix operations are not Commutative. scale * translate is not the same as translate * scale

If you have a translation of 200 and and a scale of 0.2, then

translate(200) * scale(0.2)

gives object scaled by 0.2 and translated by 200. But

scale(0.2) * translate(200)

gives object scaled by 0.2 and translated by 40 (0.2*200).

If you have 2 matrices:

groupMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();
TopMatrix = PositionMatrix() * RotationMtrix() * ScalingMatrix();

Then groupMatrix * TopMatrix is the same as

groupPositionMatrix * groupRotationMtrix * groupScalingMatrix * topPositionMatrix * topRotationMtrix * topScalingMatrix

The result is different if the scale is encoded in groupScalingMatrix or topScalingMatrix respectively the translation is encoded in groupPositionMatrix or topPositionMatrix.


问:
Handling with sqllite3 and sqllite script
I have a simple SQLite file with SQLite extension.

I can connect to ":memory:" by a simple statement which is written in docs

```<code>con = sqlite3.connect(":memory:")
</code>```

but if I have an outer SQLite script (let's say example.sqlite) and if I want to connect to this DB what should I do?

Should I execute this script by some side software and then establish a connection somehow? But how in this case?

I understand that if I go with

```<code>con = sqlite3.connect(":memory:")
</code>```

then I can create DB in my RAM and manipulate with this somehow. But I cannot understand how can I connect to the "existing" SQLite database? At first, I must create it, but how? I cannot find a command to execute the SQL script inside of the python-module.

For example, in case of MySQL DB, I use PyMySql driver, then I enter credentials and good to go

hope I made it clear.. this is my first question and I am ready for the worst.

答:
At first I must create it, but how?

You don't need to create database files first in SQLite. If the file exists, a connection will be opened. If the file doesn't exist, it will be created for you.

```<code>con = sqlite3.connect('path/to/some/file.db')  # or use :memory:
</code>```

but if I have an outer sqlite script (lets say example.sqlite) and if I want to connect to this db what should I do?

If the file is just regular SQL (creating tables etc, inserting data), you can execute it on the connection:

```<code>with open('path/to/example.sqlite', encoding='utf8') as file:
    sql = file.read()
    con.executescript(sql)
    con.commit()
</code>```

This creates the DB as described by the SQL and of course it only needs to be done once.

If your script file contains "dot commands" such as .import some.txt some_table - these can only be understood by the sqlite command line client, you can't execute them through Python. Use a shell script/batch file to execute them.

Body:
I have a simple SQLite file with SQLite extension.

I can connect to ":memory:" by a simple statement which is written in docs

con = sqlite3.connect(":memory:")

but if I have an outer SQLite script (let's say example.sqlite) and if I want to connect to this DB what should I do?

Should I execute this script by some side software and then establish a connection somehow? But how in this case?

I understand that if I go with

con = sqlite3.connect(":memory:")

then I can create DB in my RAM and manipulate with this somehow. But I cannot understand how can I connect to the "existing" SQLite database? At first, I must create it, but how? I cannot find a command to execute the SQL script inside of the python-module.

For example, in case of MySQL DB, I use PyMySql driver, then I enter credentials and good to go

hope I made it clear.. this is my first question and I am ready for the worst.

Body:
At first I must create it, but how?

You don't need to create database files first in SQLite. If the file exists, a connection will be opened. If the file doesn't exist, it will be created for you.

con = sqlite3.connect('path/to/some/file.db')  # or use :memory:

but if I have an outer sqlite script (lets say example.sqlite) and if I want to connect to this db what should I do?

If the file is just regular SQL (creating tables etc, inserting data), you can execute it on the connection:

with open('path/to/example.sqlite', encoding='utf8') as file:
    sql = file.read()
    con.executescript(sql)
    con.commit()

This creates the DB as described by the SQL and of course it only needs to be done once.

If your script file contains "dot commands" such as .import some.txt some_table - these can only be understood by the sqlite command line client, you can't execute them through Python. Use a shell script/batch file to execute them.


问:
How to push array position in the array faster
I have a google spreadsheet data in form of array. Now I want to push the array position I used for loop which is working fine on small data but when the data length is increased it result in delay.
Is there a faster way to push the array position in the array.

Here is the code which I am currently using:-

```<code> var ss = SpreadsheetApp.openById('19zxxxxxxxxxxxxxxxxxxxxxxxxOI');
 var sheet1 = ss.getSheetByName('Sheet2');
 var data = sheet1.getRange("A:H").getValues();
 var email = Session.getActiveUser().getEmail();

  for(var i = 0; i < data.length; i++)
  {
  data.unshift(i+1);
 } // this for loop takes too much time.

  data = data.filter(function(item){return item[7] == email});

  var x = data.map(function(val){
    return val.slice(0, -7);
 })
  Logger.log(x)
  return x;

}
</code>```

答:
I believe your goal as follows.

If data.unshift(i+1) is data[i].unshift(i+1) as TheMaster's comment, you want to retrieve the values of the column "A" when the value of column "G" is the same with email. At that time, you want to add the row number to the 1st index of the row value.

From your script, I understood like this.

You want to reduce the process cost of this situation.

For this problem, how about this solution?

Pattern 1:

In this pattern, your script is modified. In this case, the result values are retrieve by one loop.

Sample script:

```<code>function myFunction() {
  var ss = SpreadsheetApp.openById('19zxxxxxxxxxxxxxxxxxxxxxxxxOI');
  var sheet1 = ss.getSheetByName('Sheet2');
  var data = sheet1.getRange("A1:H" + sheet1.getLastRow()).getValues();  // Modified
  var email = Session.getActiveUser().getEmail();

  const res = data.reduce((ar, [a,,,,,,g], i) => {  // Modified
    if (g == email) ar.push([i + 1, a]);
    return ar;
  }, []);

  Logger.log(res)
  return res;
}
</code>```

Pattern 2:

In this pattern, as other method, TextFinder and Sheets API are used. In this case, the size of base data by searching email with TextFinder can be reduced. And each values are retrieved by one API call using Sheets API.

Sample script:

Before you use this script, please enable Sheets API at Advanced Google services.

```<code>function myFunction() {
  const spreadsheetId = '19zxxxxxxxxxxxxxxxxxxxxxxxxOI';
  const ss = SpreadsheetApp.openById(spreadsheetId);
  const sheet = ss.getSheetByName('Sheet2');
  const email = Session.getActiveUser().getEmail();

  // 1. Retrieve the ranges of rows by searching "email" at the column "G".
  const ranges = sheet.getRange("G1:G" + sheet.getLastRow()).createTextFinder(email).findAll();

  // 2. Create an object for using with Sheets API.
  const reqs = ranges.reduce((o, e) => {
    const row = e.getRow();
    o.rows.push(row);
    o.ranges.push("A" + row);
    return o;
  }, {rows: [], ranges: []});

  // 3. Retrieve values and add the row number.
  const res = Sheets.Spreadsheets.Values.batchGet(spreadsheetId, {ranges: reqs.ranges})
    .valueRanges
    .map((e, i) => ([reqs.rows[i], e.values[0][0]]));

  Logger.log(res)
  return res;
}
</code>```

If email is included other string, please use matchEntireCell(true) to TextFinder.

References:

reduce()

Advanced Google services

Method: spreadsheets.values.batchGet

Body:
I have a google spreadsheet data in form of array. Now I want to push the array position I used for loop which is working fine on small data but when the data length is increased it result in delay.
Is there a faster way to push the array position in the array.

Here is the code which I am currently using:-

 var ss = SpreadsheetApp.openById('19zxxxxxxxxxxxxxxxxxxxxxxxxOI');
 var sheet1 = ss.getSheetByName('Sheet2');
 var data = sheet1.getRange("A:H").getValues();
 var email = Session.getActiveUser().getEmail();

  for(var i = 0; i < data.length; i++)
  {
  data.unshift(i+1);
 } // this for loop takes too much time.

  data = data.filter(function(item){return item[7] == email});

  var x = data.map(function(val){
    return val.slice(0, -7);
 })
  Logger.log(x)
  return x;

}

Body:
I believe your goal as follows.

If data.unshift(i+1) is data[i].unshift(i+1) as TheMaster's comment, you want to retrieve the values of the column "A" when the value of column "G" is the same with email. At that time, you want to add the row number to the 1st index of the row value.

From your script, I understood like this.

You want to reduce the process cost of this situation.

For this problem, how about this solution?

Pattern 1:

In this pattern, your script is modified. In this case, the result values are retrieve by one loop.

Sample script:

function myFunction() {
  var ss = SpreadsheetApp.openById('19zxxxxxxxxxxxxxxxxxxxxxxxxOI');
  var sheet1 = ss.getSheetByName('Sheet2');
  var data = sheet1.getRange("A1:H" + sheet1.getLastRow()).getValues();  // Modified
  var email = Session.getActiveUser().getEmail();

  const res = data.reduce((ar, [a,,,,,,g], i) => {  // Modified
    if (g == email) ar.push([i + 1, a]);
    return ar;
  }, []);

  Logger.log(res)
  return res;
}

Pattern 2:

In this pattern, as other method, TextFinder and Sheets API are used. In this case, the size of base data by searching email with TextFinder can be reduced. And each values are retrieved by one API call using Sheets API.

Sample script:

Before you use this script, please enable Sheets API at Advanced Google services.

function myFunction() {
  const spreadsheetId = '19zxxxxxxxxxxxxxxxxxxxxxxxxOI';
  const ss = SpreadsheetApp.openById(spreadsheetId);
  const sheet = ss.getSheetByName('Sheet2');
  const email = Session.getActiveUser().getEmail();

  // 1. Retrieve the ranges of rows by searching "email" at the column "G".
  const ranges = sheet.getRange("G1:G" + sheet.getLastRow()).createTextFinder(email).findAll();

  // 2. Create an object for using with Sheets API.
  const reqs = ranges.reduce((o, e) => {
    const row = e.getRow();
    o.rows.push(row);
    o.ranges.push("A" + row);
    return o;
  }, {rows: [], ranges: []});

  // 3. Retrieve values and add the row number.
  const res = Sheets.Spreadsheets.Values.batchGet(spreadsheetId, {ranges: reqs.ranges})
    .valueRanges
    .map((e, i) => ([reqs.rows[i], e.values[0][0]]));

  Logger.log(res)
  return res;
}

If email is included other string, please use matchEntireCell(true) to TextFinder.

References:

reduce()

Advanced Google services

Method: spreadsheets.values.batchGet