问:
why do i keep getting OverwriteModelError?
I get the following error when I start the server:

throw new _mongoose.Error.OverwriteModelError(name);
        ^ OverwriteModelError: Cannot overwrite User model once compiled.
      at new OverwriteModelError (/home/pranav/exercise-tracker/mern-exercise-tracker/backend/node_modules/mongoose/lib/error/overwriteModel.js:20:11)

my user.model.js file

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      minlength: 3
    }
  },
  {
    timestamps: true
  }
);

const User = mongoose.model("User", userSchema);
module.exports = User;
```

<p><strong>My users.js</strong> </p>

<pre class="lang-js prettyprint-override"><code>const router = require("express").Router();
let User = require("../models/user.model");

router.route("/").get((req, res) => {
  User.find()
    .then(users => res.json(users))
    .catch(err => res.status(400).json("Error: " + err));
});

router.route("/add").post((req, res) => {
  const username = req.body.username;
  const newUser = new User({ username });

  newUser
    .save()
    .then(() => res.json("User added!"))
    .catch(err => res.status(400).json("Error: " + err));
});

module.exports = router;
</code>```

server.js

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;
app.use(cors);
app.use(express.json());
const uri = process.env.ATLAS_URI;

mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;

connection.once('open', () => {
    console.log("MongoDB connection established");
})

const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);

app.listen(port, () => {
    console.log('Server is running on port : ' + port);
})
```

答:
Replace

```<code>const User = mongoose.model("User", userSchema);
</code>```

with

```<code>const User = mongoose.models['User'] || mongoose.model("User", userSchema);
</code>```

When your code is running user.model.js is probably being called again, thus calling the initial definition.

Note the models being used in the OR. That method returns an object containing all defined models. It can also be written as mongoose.models.User.

Body:
I get the following error when I start the server:

throw new _mongoose.Error.OverwriteModelError(name);
        ^ OverwriteModelError: Cannot overwrite User model once compiled.
      at new OverwriteModelError (/home/pranav/exercise-tracker/mern-exercise-tracker/backend/node_modules/mongoose/lib/error/overwriteModel.js:20:11)

my user.model.js file

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      minlength: 3
    }
  },
  {
    timestamps: true
  }
);

const User = mongoose.model("User", userSchema);
module.exports = User;

My users.js

const router = require("express").Router();
let User = require("../models/user.model");

router.route("/").get((req, res) => {
  User.find()
    .then(users => res.json(users))
    .catch(err => res.status(400).json("Error: " + err));
});

router.route("/add").post((req, res) => {
  const username = req.body.username;
  const newUser = new User({ username });

  newUser
    .save()
    .then(() => res.json("User added!"))
    .catch(err => res.status(400).json("Error: " + err));
});

module.exports = router;

server.js

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;
app.use(cors);
app.use(express.json());
const uri = process.env.ATLAS_URI;

mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;

connection.once('open', () => {
    console.log("MongoDB connection established");
})

const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);

app.listen(port, () => {
    console.log('Server is running on port : ' + port);
})

Body:
Replace

const User = mongoose.model("User", userSchema);

with

const User = mongoose.models['User'] || mongoose.model("User", userSchema);

When your code is running user.model.js is probably being called again, thus calling the initial definition.

Note the models being used in the OR. That method returns an object containing all defined models. It can also be written as mongoose.models.User.


来源: stackexchange

问:
Show an imageview instead of icon on toolbar options menu
When you override the onCreateOptionsMenu() you get a options menu which opens when you click the 3 dot icon on top right. I want to show a circular image view with image of a user instead of the 3 dot icon. How do I do this?

```<code>override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.options_menu, menu);
    return true
}
</code>```

答:
Hi @Amol you can learn more about the toolbar from codepath guide,

try to replace toolbar

```<code><androidx.appcompat.widget.Toolbar
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

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

            <androidx.appcompat.widget.AppCompatImageView
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_gravity="end"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher_round" />

        </FrameLayout>

</androidx.appcompat.widget.Toolbar>

</code>```

if you just want to replace the icon and still keep overflow menu
read from the similar answer from this

ContentLicense: CC BY-SA 4.0

Body:
When you override the onCreateOptionsMenu() you get a options menu which opens when you click the 3 dot icon on top right. I want to show a circular image view with image of a user instead of the 3 dot icon. How do I do this?

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.options_menu, menu);
    return true
}

Body:
Hi @Amol you can learn more about the toolbar from codepath guide,

try to replace toolbar

<androidx.appcompat.widget.Toolbar
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

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

            <androidx.appcompat.widget.AppCompatImageView
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_gravity="end"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher_round" />

        </FrameLayout>

</androidx.appcompat.widget.Toolbar>

if you just want to replace the icon and still keep overflow menu
read from the similar answer from this


问:
Configure Apache web server to call a app https url
Good day,

I have a Apache server (10.8.111.67), I configure it to ProxyPass to my app server http port (10.8.1.63), its work. The thing I do in httpd.conf is just as follow:

```<code>ProxyPass "/mfp" "http://10.8.1.63:9080/mfp"
ProxyPassReverse "/mfp" "http://10.8.1.63:9080/mfp"
</code>```

However, I should proxy pass to https url instead of http.

I google around, found that I need to configure something in the ssl.conf, the following is what I plan to do:

```<code><VirtualHost 10.8.111.67:80>
SSLEngine on
SSLCertificateFile ???
SSLCertificateKeyFile ???
ProxyPass "/mfp" "http://10.8.1.63:9080/mfp"
ProxyPassReverse "/mfp" "http://10.8.1.63:9080/mfp"
</VirtualHost>
</code>```

I am not sure that what cert actually I should put for SSLCertificateFile, is it cert from app server? I can use openssl command to download it?

And for the SSLCertificateKeyFile, what file I should put inside? private key from app server? May I know how to generate the private key from web server? I run ssh-keygen, I got the id_rsa.pub and id_rsa.

Kindly advise.

Kindly notify me if I am doing something wrong.

答:
You don't need to configure certificates in virtualhost just to proxy to a SSL backend.

To reverse proxy to a SSL backend you just need to make sure mod_ssl is loaded and that you have the directive: SSLProxyEngine on to let the reverse proxy do it to an SSL backend.

Loading certificates in virtualhost is for virtualhosts that will listen to SSL connections, mainly virtualhosts with 443 port.

So based in your description to reverse proxy to the SSL backend, aside from the mod_ssl module loaded what you want is:

```<code><VirtualHost 10.8.111.67:80>
    ServerName youshouldefinethisalways.example.com
    SSLProxyEngine on
    ProxyPass /mfp https://backend-server.example.com/mfp
    ProxyPassReverse /mfp https://backend-server.example.com/mfp
</VirtualHost>
</code>```

Body:
Good day,

I have a Apache server (10.8.111.67), I configure it to ProxyPass to my app server http port (10.8.1.63), its work. The thing I do in httpd.conf is just as follow:

ProxyPass "/mfp" "http://10.8.1.63:9080/mfp"
ProxyPassReverse "/mfp" "http://10.8.1.63:9080/mfp"

However, I should proxy pass to https url instead of http.

I google around, found that I need to configure something in the ssl.conf, the following is what I plan to do:

<VirtualHost 10.8.111.67:80>
SSLEngine on
SSLCertificateFile ???
SSLCertificateKeyFile ???
ProxyPass "/mfp" "http://10.8.1.63:9080/mfp"
ProxyPassReverse "/mfp" "http://10.8.1.63:9080/mfp"
</VirtualHost>

I am not sure that what cert actually I should put for SSLCertificateFile, is it cert from app server? I can use openssl command to download it?

And for the SSLCertificateKeyFile, what file I should put inside? private key from app server? May I know how to generate the private key from web server? I run ssh-keygen, I got the id_rsa.pub and id_rsa.

Kindly advise.

Kindly notify me if I am doing something wrong.

Body:
You don't need to configure certificates in virtualhost just to proxy to a SSL backend.

To reverse proxy to a SSL backend you just need to make sure mod_ssl is loaded and that you have the directive: SSLProxyEngine on to let the reverse proxy do it to an SSL backend.

Loading certificates in virtualhost is for virtualhosts that will listen to SSL connections, mainly virtualhosts with 443 port.

So based in your description to reverse proxy to the SSL backend, aside from the mod_ssl module loaded what you want is:

<VirtualHost 10.8.111.67:80>
    ServerName youshouldefinethisalways.example.com
    SSLProxyEngine on
    ProxyPass /mfp https://backend-server.example.com/mfp
    ProxyPassReverse /mfp https://backend-server.example.com/mfp
</VirtualHost>


问:
Any way to get a specific entry by key in a Java hashmap(having inserted multiple values)?
I have a Java hashmap, to which multiple variables were added(ex.):

```<code>class client {
    public static int clientIdentifier;
    public static String clientName;
    public static String clientFamilyname;
    public static String clientBirthdate;
}

</code>```

Inside the main method:

```<code>client newclient = new client();
HashMap<Integer, String> clients = new HashMap<>();

clients.put(newclient.clientIdentifier,
newclient.clientName +
newclient.clientFamilyname +
 newclient.clientBirthdate

</code>```

Where new client.clientIdentifier is the key and newClient.clientName/Familyname/Birthdate are already defined. They belong to an object newclient, it belonging to the class client

Is there any way to get only the value clientName from that hashmap, to compare later?

Looking for something like:
String requiredName = clients.get(scannedID, newclient.clientName);

(I know that it is totally wrong, but just to have an idea)

Thank you very much!

答:
You need to make all the fields in Client non-static first! You'd want each instance of Client to have a different ID, name, and birthday, right?

Instead of using a HashMap<Integer, String>, use a HashMap<Integer, Client>:

```<code>Client newclient = new Client();
HashMap<Integer, Client> clients = new HashMap<>();

clients.put(newclient.clientIdentifier, newclient);
</code>```

Now you can just do:

```<code>String requiredName = clients.get(scannedID).clientName;
</code>```

But really though, the fields in the class Client should all be private and should be accessed via getters and setters. You also should not be able to reset the client's clientIdentifier as that is the map's key.

Client should look like this:

```<code>class Client {
    private int clientIdentifier;
    private String clientName;
    private String clientFamilyname;
    private String clientBirthdate;

    public String getClientName() {
        return clientName;
    }

    public void setClientName(String clientName) {
        this.clientName = clientName;
    }

    public String getClientFamilyname() {
        return clientFamilyname;
    }

    public void setClientFamilyname(String clientFamilyname) {
        this.clientFamilyname = clientFamilyname;
    }

    public String getClientBirthdate() {
        return clientBirthdate;
    }

    public void setClientBirthdate(String clientBirthdate) {
        this.clientBirthdate = clientBirthdate;
    }

    public int getClientIdentifier() {
        return clientIdentifier;
    }

    public Client(int clientIdentifier, String clientName, String clientFamilyname, String clientBirthdate) {
        this.clientIdentifier = clientIdentifier;
        this.clientName = clientName;
        this.clientFamilyname = clientFamilyname;
        this.clientBirthdate = clientBirthdate;
    }
}
</code>```

Your hash map code will now look like:

```<code>Client newclient = new Client();
HashMap<Integer, Client> clients = new HashMap<>();

clients.put(newclient.getClientIdentifier(), newclient);

String requiredName = clients.get(scannedID).getClientName();
</code>```

Body:
I have a Java hashmap, to which multiple variables were added(ex.):

class client {
    public static int clientIdentifier;
    public static String clientName;
    public static String clientFamilyname;
    public static String clientBirthdate;
}

Inside the main method:

client newclient = new client();
HashMap<Integer, String> clients = new HashMap<>();

clients.put(newclient.clientIdentifier,
newclient.clientName +
newclient.clientFamilyname +
 newclient.clientBirthdate

Where new client.clientIdentifier is the key and newClient.clientName/Familyname/Birthdate are already defined. They belong to an object newclient, it belonging to the class client

Is there any way to get only the value clientName from that hashmap, to compare later?

Looking for something like:
String requiredName = clients.get(scannedID, newclient.clientName);

(I know that it is totally wrong, but just to have an idea)

Thank you very much!

Body:
You need to make all the fields in Client non-static first! You'd want each instance of Client to have a different ID, name, and birthday, right?

Instead of using a HashMap<Integer, String>, use a HashMap<Integer, Client>:

Client newclient = new Client();
HashMap<Integer, Client> clients = new HashMap<>();

clients.put(newclient.clientIdentifier, newclient);

Now you can just do:

String requiredName = clients.get(scannedID).clientName;

But really though, the fields in the class Client should all be private and should be accessed via getters and setters. You also should not be able to reset the client's clientIdentifier as that is the map's key.

Client should look like this:

class Client {
    private int clientIdentifier;
    private String clientName;
    private String clientFamilyname;
    private String clientBirthdate;

    public String getClientName() {
        return clientName;
    }

    public void setClientName(String clientName) {
        this.clientName = clientName;
    }

    public String getClientFamilyname() {
        return clientFamilyname;
    }

    public void setClientFamilyname(String clientFamilyname) {
        this.clientFamilyname = clientFamilyname;
    }

    public String getClientBirthdate() {
        return clientBirthdate;
    }

    public void setClientBirthdate(String clientBirthdate) {
        this.clientBirthdate = clientBirthdate;
    }

    public int getClientIdentifier() {
        return clientIdentifier;
    }

    public Client(int clientIdentifier, String clientName, String clientFamilyname, String clientBirthdate) {
        this.clientIdentifier = clientIdentifier;
        this.clientName = clientName;
        this.clientFamilyname = clientFamilyname;
        this.clientBirthdate = clientBirthdate;
    }
}

Your hash map code will now look like:

Client newclient = new Client();
HashMap<Integer, Client> clients = new HashMap<>();

clients.put(newclient.getClientIdentifier(), newclient);

String requiredName = clients.get(scannedID).getClientName();


问:
Combine [NgStyle] With Condition (if..else)
I have read NgStyle Documentation For Angular 2, and it is a little bit confusing for me. How do I use NgStyle with condition like (if...else) to set background image of any element? </p>

答:
I have used the below code in my existing project

```<code><div class="form-group" [ngStyle]="{'border':isSubmitted && form_data.controls.first_name.errors?'1px solid red':'' }">
</div>
</code>```

Body:
I have used the below code in my existing project

<div class="form-group" [ngStyle]="{'border':isSubmitted && form_data.controls.first_name.errors?'1px solid red':'' }">
</div>


问:
How to style header in react-navigation
I am trying to style the header in react-navigation where the object is automatically generated by Expo.

I am trying to style the header background and the orientation of the title.

I tried every possible place, including navigationOptions but all failed.

In below code tab bar background color is correctly changed. But same method failed for header.

Any guidance appreciated.

```<code>import React from 'react';

import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';

import LinksScreen from '../screens/LinksScreen';
import SettingsScreen from '../screens/SettingsScreen';

const LinksStack = createStackNavigator({
    Links: LinksScreen,
});

LinksStack.navigationOptions = {
    tabBarLabel: "Links",
    tabBarIcon: ...
};

const SettingsStack = createStackNavigator({
    Settings: SettingsScreen,
});

SettingsStack.navigationOptions = {
    tabBarLabel: "Settings",
    tabBarIcon: ...,
};

export default createBottomTabNavigator(
    {
        LinksStack,
        SettingsStack,
    },
    {
        tabBarOptions: {
            style: {
                backgroundColor: '#123456',
            },
        }
    },
);

</code>```

答:
You can try this by passing using headerStyle inside each screen by

export default createBottomTabNavigator({
  LinkStack: {
    screen: LinkScreen,
    navigationOptions: { // you need to call LinkStack.navigationOptions here
      headerTitle: 'LinkScreen',
      headerStyle: {
        backgroundColor: 'red',
        ...otherStyles,
      },
    },
  }
})

Or you can make use of defaultNavigationOptions inside your stackNavigator if you don't have specific header styles for your different screens.

In your case, you need to call LinkStack.navigationOptions for navigationOptions.

Title: How to style header in react-navigation

Body:
I am trying to style the header in react-navigation where the object is automatically generated by Expo.

I am trying to style the header background and the orientation of the title.

I tried every possible place, including navigationOptions but all failed.

In below code tab bar background color is correctly changed. But same method failed for header.

Any guidance appreciated.

import React from 'react';

import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';

import LinksScreen from '../screens/LinksScreen';
import SettingsScreen from '../screens/SettingsScreen';

const LinksStack = createStackNavigator({
    Links: LinksScreen,
});

LinksStack.navigationOptions = {
    tabBarLabel: "Links",
    tabBarIcon: ...
};

const SettingsStack = createStackNavigator({
    Settings: SettingsScreen,
});

SettingsStack.navigationOptions = {
    tabBarLabel: "Settings",
    tabBarIcon: ...,
};

export default createBottomTabNavigator(
    {
        LinksStack,
        SettingsStack,
    },
    {
        tabBarOptions: {
            style: {
                backgroundColor: '#123456',
            },
        }
    },
);


问:
Why don't I get an integer overflow when adding two chars?

Possible Duplicate:

  Addition of two chars produces int

Given the following C++ code:

```<code>unsigned char a = 200;
unsigned char b = 100;

unsigned char c = (a + b) / 2;
</code>```

The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)?

Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn't rely on in terms of integer promotion and overflow.

答:
Per other answers, it's not an error on x86 and other (sane) 32bit and 16bit architectures.

However, on smaller or less sane architectures (typically very small microcontrollers) things like this will probably start to cause trouble, especially if whoever implemented your compiler doesn't have the testing/validation budget of some of the larger companies out there (again, microcontrollers).

Body:
Possible Duplicate:

  Addition of two chars produces int

Given the following C++ code:

unsigned char a = 200;
unsigned char b = 100;

unsigned char c = (a + b) / 2;

The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)?

Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn't rely on in terms of integer promotion and overflow.

ContentLicense: CC BY-SA 3.0


问:
React prop being marked as undefined
So I have been working on a nodejs website until I ran until a really stupid error which had me stopped for a solid hour. All of my other redux actions work except for the logout which gives me this error.
Failed prop type: The prop logout is marked as required in Logout, but its value is undefined.
Here is the code for the logout component

```<code>import React, { Component, Fragment } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { logout } from "../../actions/authActions";
import PropTypes from "prop-types";

export class Logout extends Component {
  static propTypes = {
    logout: PropTypes.func.isRequired
  };

  render() {
    return (
      <div>
        <Link onClick={this.props.logout} to="#">
          Logout
        </Link>
      </div>
    );
  }
}

export default connect(null, { logout })(Logout);
</code>```

Here is the action code

```<code>export const logout = () => {
  return {
    type: LOGOUT_SUCCESS
  };
};
</code>```

The value is clearly defined. Please let me know what here is not working

答:
Found the issue,

If my redux understanding is correct, I cannot export the class and connect as well. So I had to remove the class export and change it to this

```<code>import React, { Component } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { logout } from "../../actions/authActions";
import PropTypes from "prop-types";

class Logout extends Component {
  static propTypes = {
    logout: PropTypes.func.isRequired
  };

  render() {
    return (
      <div>
        <Link onClick={this.props.logout} to="#">
          Logout
        </Link>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  isAuthenticated: state.auth.isAuthenticated
  // error: state.error
});

export default connect(mapStateToProps, { logout })(Logout);
</code>```

Title: React prop being marked as undefined

Body:
So I have been working on a nodejs website until I ran until a really stupid error which had me stopped for a solid hour. All of my other redux actions work except for the logout which gives me this error.
Failed prop type: The prop logout is marked as required in Logout, but its value is undefined.
Here is the code for the logout component

import React, { Component, Fragment } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { logout } from "../../actions/authActions";
import PropTypes from "prop-types";

export class Logout extends Component {
  static propTypes = {
    logout: PropTypes.func.isRequired
  };

  render() {
    return (

        <Link onClick={this.props.logout} to="#">
          Logout
        </Link>

    );
  }
}

export default connect(null, { logout })(Logout);

Here is the action code

export const logout = () => {
  return {
    type: LOGOUT_SUCCESS
  };
};

The value is clearly defined. Please let me know what here is not working

Body:
Found the issue,

If my redux understanding is correct, I cannot export the class and connect as well. So I had to remove the class export and change it to this

import React, { Component } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { logout } from "../../actions/authActions";
import PropTypes from "prop-types";

class Logout extends Component {
  static propTypes = {
    logout: PropTypes.func.isRequired
  };

  render() {
    return (
      <div>
        <Link onClick={this.props.logout} to="#">
          Logout
        </Link>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  isAuthenticated: state.auth.isAuthenticated
  // error: state.error
});

export default connect(mapStateToProps, { logout })(Logout);


问:
Count Elements Selected Within a Slicer
I have started to work on an excel sheet and to run some calculated field I need a public function that returns the number of items selected within a single slicer.
I surfed the internet, but unfortunately I was only able to find VBA codes that actually do not work at all.
I have started to work with VBA only recently for the first time, so I have no experience with it.

I managed to use this code, which however is not a public function, so it cannot be used within calculated fields in pivot tables:

```<code>    Private Sub Worksheet_PivotTableChangeSync(ByVal Target As PivotTable)
        Const sSlicerName As String = "Producer"
        On Error Resume Next
        If Not IsError(Target.Slicers(sSlicerName).Name) Then _
            Range("A1") = ActiveWorkbook.SlicerCaches("Slicer_" & sSlicerName) _
             .VisibleSlicerItems.Count
    End Sub
</code>```

Did any of you face this issue and find a way to solve the problem?

Thank you in advance!

答:
This should do the trick:

```<code>Public Function CountProducers()
    Dim lngCount As Long
    Const sSlicerName As String = "Producer"

    Application.Volatile

    On Error Resume Next
        If Not IsError(Sheet1.PivotTables("PivotTable1").Slicers(sSlicerName).Name) Then
            lngCount = ThisWorkbook.SlicerCaches("Slicer_" & sSlicerName) _
             .VisibleSlicerItems.Count
        End If
    On Error GoTo 0

    CountProducers = lngCount
End Function
</code>```

As you can see your initial attempt was almost correct. A few things to note:

I added Application.Volatile part to make the formula dynamic, i.e. it will always re-calculate whenever you change your slicer selections.

On Error ... and If Not IsError... parts are not really required, you can simply leave lngCount part all by itself. If the formula won't find a slicer called "Producer" it will simply return #VALUE! error.

Title: Count Elements Selected Within a Slicer

Body:
I have started to work on an excel sheet and to run some calculated field I need a public function that returns the number of items selected within a single slicer.
I surfed the internet, but unfortunately I was only able to find VBA codes that actually do not work at all.
I have started to work with VBA only recently for the first time, so I have no experience with it.

I managed to use this code, which however is not a public function, so it cannot be used within calculated fields in pivot tables:

    Private Sub Worksheet_PivotTableChangeSync(ByVal Target As PivotTable)
        Const sSlicerName As String = "Producer"
        On Error Resume Next
        If Not IsError(Target.Slicers(sSlicerName).Name) Then _
            Range("A1") = ActiveWorkbook.SlicerCaches("Slicer_" & sSlicerName) _
             .VisibleSlicerItems.Count
    End Sub

Did any of you face this issue and find a way to solve the problem?

Thank you in advance!

Body:
This should do the trick:

Public Function CountProducers()
    Dim lngCount As Long
    Const sSlicerName As String = "Producer"

    Application.Volatile

    On Error Resume Next
        If Not IsError(Sheet1.PivotTables("PivotTable1").Slicers(sSlicerName).Name) Then
            lngCount = ThisWorkbook.SlicerCaches("Slicer_" & sSlicerName) _
             .VisibleSlicerItems.Count
        End If
    On Error GoTo 0

    CountProducers = lngCount
End Function

As you can see your initial attempt was almost correct. A few things to note:

I added Application.Volatile part to make the formula dynamic, i.e. it will always re-calculate whenever you change your slicer selections.

On Error ... and If Not IsError... parts are not really required, you can simply leave lngCount part all by itself. If the formula won't find a slicer called "Producer" it will simply return #VALUE! error.


问:
SQL join greater than / less then
I have 2 tables

I
So i need to get a table in which rows will be excluded for which the date for each "id" is more than in the second table "datestop"

I tried inner join with double condition:
id = id and Date < DateStop, but in this way also excluded rows which not contained in table 2 (id1)

For imagine, thats what i want to get:

答:
Consider:

```<code>select a.*
from tablea a
left join tableb b on b.id = a.id
where b.id is null or b.datestop > a.date
</code>```

This phrases as: get all records in tablea for which either there is no record with the same id in tableb, or whose date is less than the datestop of the corresponding record in tableb.

Title: SQL join greater than / less then

Body:
Consider:

select a.*
from tablea a
left join tableb b on b.id = a.id
where b.id is null or b.datestop > a.date

This phrases as: get all records in tablea for which either there is no record with the same id in tableb, or whose date is less than the datestop of the corresponding record in tableb.


问:
JavaScript - Caesar Cipher
I know there have been a few posts about Caesar Ciphers in the past, which I have had a look at, but I haven't found an answer which has helped me to solve this kata, hence my post.

The language is JavaScript. I've written 3 tests, 2 of which are passing so far, but the third is not. I tried to use a nested for loop to loop over the alphabet and the str, and compare them, then shift the alphabet index up/down according to whatever the number was, then push that letter into a new array, and return the joined array at the end.

It's working for positive numbers, but not negatives. (I should also point out that I haven't thought of how to handle spaces yet, I just wanted to get it working for single words first, then take it from there, thanks!)

Any pointers in the right direction would be appreciated.

Kata Instructions:

The function caesarCipher should take a string and a number (n) and return a new string with a Caesar cipher applied. A Caesar cipher replaces each plaintext letter with a different one a fixed number of places up or down the alphabet. N represents the number of shifts up or down the alphabet should be applied. It may be negative or positive.

```<code>  E.g.
  caesarCipher('hello', 2)
    --> 'jgnnq'
  caesarCipher('hello world!', -3)
    --> 'ebiil tloia!'
</code>```

My tests:

const caesarCipher = require("../katas/caesar-cipher");
const { expect } = require("chai");

describe.only("caesarCipher", () => {
  it("returns an empty string when passed an empty string", () => {
    const alphabet = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z"
    ];
    const str = "";
    const num = 2;
    const actualResults = caesarCipher(alphabet, str, num);
    const expectedResults = "";
    expect(actualResults).to.equal(expectedResults);
  });
  it("returns a string with the letters replaced by the number of shifts up the alphabet", () => {
    const alphabet = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z"
    ];
    const str = "hi";
    const num = 2;
    const actualResults = caesarCipher(alphabet, str, num);
    const expectedResults = "jk";
    expect(actualResults).to.equal(expectedResults);
  });
  it("returns a string with the letters replaced by the number of shifts down the alphabet", () => {
    const alphabet = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z"
    ];
    const str = "dog";
    const num = -3;
    const actualResults = caesarCipher(alphabet, str, num);
    const expectedResults = "ald";
    expect(actualResults).to.equal(expectedResults);
  });
});```
</div>
</div>
</p>

<p>My Solution:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function caesarCipher(alphabet, str, num) {
  const strToArray = str.split("");
  console.log(strToArray);
  const cipheredStr = [];
  for (let i = 0; i < strToArray.length; i++) {
    for (let j = 0; j < alphabet.length; j++) {
      if (strToArray[i] === alphabet[j] && Math.sign(num) === 1) {
        console.log(Math.sign(num));
        cipheredStr.push(alphabet[(j += num)]);
      } else if (strToArray[i] === alphabet[j] && Math.sign(num) === -1) {
        console.log(Math.sign(num));
        console.log(alphabet[(j -= num)]);
        cipheredStr.push(alphabet[(j -= num)]);
      }
    }
  }
  console.log(cipheredStr.join(""));
  return cipheredStr.join("");
}</code>```

The Results:

caesarCipher
[]

    ✓ returns an empty string when passed an empty string
[ 'h', 'i' ]
1
1
jk
    ✓ returns a string with the letters replaced by the number of shifts up the alphabet
[ 'd', 'o', 'g' ]
-1
g
-1
r
-1
j
jum
    1) returns a string with the letters replaced by the number of shifts down the alphabet

  2 passing (15ms)
  1 failing

  1) caesarCipher
       returns a string with the letters replaced by the number of shifts down the alphabet:

      AssertionError: expected 'jum' to equal 'ald'
      + expected - actual

      -jum
      +ald

      at Context.<anonymous> (spec/caesar-cipher.spec.js:108:30)
      at processImmediate (internal/timers.js:456:21)```

答:
The problem is that when num is negative, you are doing the mapping:

```<code>cipheredStr.push(alphabet[(j -= num)]);
</code>```

But num is negative. When you subtract a negative number what you are doing is adding its absolute value.

Instead, you should do:

```<code>cipheredStr.push(alphabet[j + num]);
</code>```

Also, note that to compute the index in the alphabet you don't need to put the = in there.

Side notes

I understand that your solution is a work in progress. You have to take into consideration:

What happens when you sum j + num to do the translation and it goes out of boundaries of your alphabet. Same thing could happen with a negative value of num.

In the declaration of the problem, it states that caesarCipher should only accept two parameters, but you are passing the alphabet as first parameter!

Good luck with your code and keep trying :)

Title: JavaScript - Caesar Cipher

Body:
I know there have been a few posts about Caesar Ciphers in the past, which I have had a look at, but I haven't found an answer which has helped me to solve this kata, hence my post.

The language is JavaScript. I've written 3 tests, 2 of which are passing so far, but the third is not. I tried to use a nested for loop to loop over the alphabet and the str, and compare them, then shift the alphabet index up/down according to whatever the number was, then push that letter into a new array, and return the joined array at the end.

It's working for positive numbers, but not negatives. (I should also point out that I haven't thought of how to handle spaces yet, I just wanted to get it working for single words first, then take it from there, thanks!)

Any pointers in the right direction would be appreciated.

Kata Instructions:

The function caesarCipher should take a string and a number (n) and return a new string with a Caesar cipher applied. A Caesar cipher replaces each plaintext letter with a different one a fixed number of places up or down the alphabet. N represents the number of shifts up or down the alphabet should be applied. It may be negative or positive.

  E.g.
  caesarCipher('hello', 2)
    --> 'jgnnq'
  caesarCipher('hello world!', -3)
    --> 'ebiil tloia!'

My tests:

const caesarCipher = require("../katas/caesar-cipher");
const { expect } = require("chai");

describe.only("caesarCipher", () => {
  it("returns an empty string when passed an empty string", () => {
    const alphabet = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z"
    ];
    const str = "";
    const num = 2;
    const actualResults = caesarCipher(alphabet, str, num);
    const expectedResults = "";
    expect(actualResults).to.equal(expectedResults);
  });
  it("returns a string with the letters replaced by the number of shifts up the alphabet", () => {
    const alphabet = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z"
    ];
    const str = "hi";
    const num = 2;
    const actualResults = caesarCipher(alphabet, str, num);
    const expectedResults = "jk";
    expect(actualResults).to.equal(expectedResults);
  });
  it("returns a string with the letters replaced by the number of shifts down the alphabet", () => {
    const alphabet = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z"
    ];
    const str = "dog";
    const num = -3;
    const actualResults = caesarCipher(alphabet, str, num);
    const expectedResults = "ald";
    expect(actualResults).to.equal(expectedResults);
  });
});

My Solution:

function caesarCipher(alphabet, str, num) {
  const strToArray = str.split("");
  console.log(strToArray);
  const cipheredStr = [];
  for (let i = 0; i < strToArray.length; i++) {
    for (let j = 0; j < alphabet.length; j++) {
      if (strToArray[i] === alphabet[j] && Math.sign(num) === 1) {
        console.log(Math.sign(num));
        cipheredStr.push(alphabet[(j += num)]);
      } else if (strToArray[i] === alphabet[j] && Math.sign(num) === -1) {
        console.log(Math.sign(num));
        console.log(alphabet[(j -= num)]);
        cipheredStr.push(alphabet[(j -= num)]);
      }
    }
  }
  console.log(cipheredStr.join(""));
  return cipheredStr.join("");
}

The Results:

caesarCipher
[]

    ✓ returns an empty string when passed an empty string
[ 'h', 'i' ]
1
1
jk
    ✓ returns a string with the letters replaced by the number of shifts up the alphabet
[ 'd', 'o', 'g' ]
-1
g
-1
r
-1
j
jum
    1) returns a string with the letters replaced by the number of shifts down the alphabet

  2 passing (15ms)
  1 failing

  1) caesarCipher
       returns a string with the letters replaced by the number of shifts down the alphabet:

      AssertionError: expected 'jum' to equal 'ald'
      + expected - actual

      -jum
      +ald

      at Context.<anonymous> (spec/caesar-cipher.spec.js:108:30)
      at processImmediate (internal/timers.js:456:21)

Body:
The problem is that when num is negative, you are doing the mapping:

cipheredStr.push(alphabet[(j -= num)]);

But num is negative. When you subtract a negative number what you are doing is adding its absolute value.

Instead, you should do:

cipheredStr.push(alphabet[j + num]);

Also, note that to compute the index in the alphabet you don't need to put the = in there.

Side notes

I understand that your solution is a work in progress. You have to take into consideration:

What happens when you sum j + num to do the translation and it goes out of boundaries of your alphabet. Same thing could happen with a negative value of num.

In the declaration of the problem, it states that caesarCipher should only accept two parameters, but you are passing the alphabet as first parameter!

Good luck with your code and keep trying :)


问:
'TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined'
I'm working on a project in React and ran into a problem that has me stumped.

Whenever I run yarn start I get this error:

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type
string. Received type undefined

I have no idea why this is happening.

答:
I've also faced this problem and figure out it by upgrading the react-scripts package from "react-scripts": "3.x.x" to "react-scripts": "^3.4.1" (or the latest available version).

Delete node_modules\ folder

Delete package-lock.json file

Rewrite the package.json file from "react-scripts": "3.x.x" to "react-scripts": "^3.4.1"

Install node packages again npm i

Now, start the project npm start

And it works!!


问:
Detecting single vs multiple selections in Delphi TStringGrid
This is a follow up to my previous question  Delphi TStringGrid multi select, determining selected rows regarding Delphi String Grids.  It's a different question.

I was looking more closely at the ONSelectCell Event
TSelectCellEvent = procedure (Sender: TObject; ACol, ARow: Longint; var CanSelect: Boolean) of object;

I noticed that the TStringGrid.Selection.Top,Bottom properties are not necessarily accurate (within the event itself).  Basically, if someone goes from selecting multiple rows to just one row, the selection.* properties do not get updated, whereas if one selects multiple rows, they do.

The ARow parameter does get updated regardless of whether one or more rows are selected, but this will only help me if I can determine that one and only one row was selected.

Eg, If it's just one row that was selected, then use Arow parameter, if more than one row then use Selection.* properties to determine which row(s) are currently selected.

There must be an easier way....

Thank you!

答:
```<code>for RowIndex := StringGrid1.Selection.Top to StringGrid1.Selection.Bottom do
begin
  DoSomethingWithRow(RowIndex);
end;
</code>```

Yes, I see your point. It seems the Selection property is updated after the OnSelectCell event so inside the event you only have the old values (ie. before the select event). The answer to that is to move the code above to the stringgrid's OnMouseUp event. It seems to work fine.

LastEditorDisplayName: Мסž

Body:
for RowIndex := StringGrid1.Selection.Top to StringGrid1.Selection.Bottom do
begin
  DoSomethingWithRow(RowIndex);
end;

Yes, I see your point. It seems the Selection property is updated after the OnSelectCell event so inside the event you only have the old values (ie. before the select event). The answer to that is to move the code above to the stringgrid's OnMouseUp event. It seems to work fine.


问:
Fast dataframe normalization in Python/Pandas
In Python/Pandas, I am trying to normalize all numeric columns of a dataframe to counts per million using the following code:

```<code>import pandas as pd
def normalize(df):
    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
    numeric_cols = [col for col in df.columns if df[col].dtype in numerics]
    sums = df.sum(axis=0, skipna = True)
    for col in numeric_cols:
        df.insert(df.columns.get_loc(col)+1, col+'_norm', ((df[col]/sums[col])*1000000)+1)
    return df
dataset = pd.read_csv(csv_file, index_col=['Guide1', 'Guide2'], sep=',')
dataset = normalize(dataset)
</code>```

This is a short example input:

```<code>Guide1,Guide2,Gene1,Gene2,NHT1,NHT2,hart_essential_1,hart_essential_2,lib,RPE1_n1,RPE1_n2,RPE1_n3
Gene_1-KO-3,Non-Human-Target-150-KO-26,Gene_1,Non-Human-Target-150,False,True,False,False,12426.0,10634.0,8701.0,8084.0
Gene_2-KO-3,Non-Human-Target-150-KO-26,Gene_2,Non-Human-Target-150,False,True,False,False,12300.0,12383.0,6252.0,5388.0
Gene_1-KO-3,Gene_4-KO-2,Gene_1,Gene_4,False,False,False,False,11685.0,10006.0,10621.0,7002.0
Gene_1-KO-3,Gene_5-KO-2,Gene_1,Gene_5,False,False,False,False,11347.0,6726.0,3927.0,3943.0
Gene_1-KO-3,Gene_6-KO-1,Gene_1,Gene_6,False,False,False,False,11250.0,12469.0,3552.0,3334.0
</code>```

The code works as intended and normalizes all numeric columns of that dataframe, but it seems to work very slow, also with other normalization methods. I am regularly working with dataframes that contain up to several millions of rows. For ~1 million rows and only 4 numeric columns, normalization takes almost 10 minutes on my mobile computer with an Intel Core i7-6600U @ 2.6GHz, although I precompute the sums for every column.
Is there a way to speed this up, e.g., parallelization or some neat Pandas trick?

Any help and/or pointers are much appreciated!

答:
Thank you for taking time to answer me! I came up with another solution that I would like to share. YaoYao inspired me to test the multiprocessing library to tackle my problem. The following solution runs extremely fast. The script starts by reading the .csv file, determines the names of the numeric columns and computes their sums. Then it splits the dataset into equally sized chunks and maps the normalizing function to each chunk. The resulting normalized dataframes are concatenated back to yield the entire normalized dataset.

```<code>import pandas as pd
import math
import numpy as np
from multiprocessing import Pool

def index_marks(nrows, chunk_size):
    return range(chunk_size, math.ceil(nrows / chunk_size) * chunk_size, chunk_size)

def split(dfm, chunk_size):
    indices = index_marks(dfm.shape[0], chunk_size)
    return np.split(dfm, indices)

def normalize(df, sums, numeric_cols):
    for col in numeric_cols:
        df.insert(df.columns.get_loc(col)+1, col+'_norm', ((df[col]/sums[col])*1000000)+1)
    return df

def parallel_normalize(data):
    df = data[0]
    sums = data[1]
    numeric_cols = data[2]

    df = normalize(df, sums, numeric_cols)
    return df

numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
dataset_file = '/path/to/file.csv'

cores = 3

dataset = pd.read_csv(dataset_file, index_col=['Guide1', 'Guide2'], sep=',')
dataset = dataset.fillna(0.0)

numeric_cols = [col for col in dataset.columns if dataset[col].dtype in numerics]
sums = dataset[numeric_cols].sum(axis=0, skipna = True)

chunks = split(dataset, int(round(dataset.shape[0]/cores)))
pool = Pool(cores)
dataset = pd.concat(pool.map(parallel_normalize, [[x, sums, numeric_cols] for x in chunks]))
pool.close()
pool.join()
</code>```

I do not know why the speedup is that enormous, though. I would have expected a speedup of maybe 60%, because I split the data into 3 chunks. But it literally runs instantaneously. If anyone could comment and give some insight here, I'd be more than happy!

Body:
In Python/Pandas, I am trying to normalize all numeric columns of a dataframe to counts per million using the following code:

import pandas as pd
def normalize(df):
    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
    numeric_cols = [col for col in df.columns if df[col].dtype in numerics]
    sums = df.sum(axis=0, skipna = True)
    for col in numeric_cols:
        df.insert(df.columns.get_loc(col)+1, col+'_norm', ((df[col]/sums[col])*1000000)+1)
    return df
dataset = pd.read_csv(csv_file, index_col=['Guide1', 'Guide2'], sep=',')
dataset = normalize(dataset)

This is a short example input:

Guide1,Guide2,Gene1,Gene2,NHT1,NHT2,hart_essential_1,hart_essential_2,lib,RPE1_n1,RPE1_n2,RPE1_n3
Gene_1-KO-3,Non-Human-Target-150-KO-26,Gene_1,Non-Human-Target-150,False,True,False,False,12426.0,10634.0,8701.0,8084.0
Gene_2-KO-3,Non-Human-Target-150-KO-26,Gene_2,Non-Human-Target-150,False,True,False,False,12300.0,12383.0,6252.0,5388.0
Gene_1-KO-3,Gene_4-KO-2,Gene_1,Gene_4,False,False,False,False,11685.0,10006.0,10621.0,7002.0
Gene_1-KO-3,Gene_5-KO-2,Gene_1,Gene_5,False,False,False,False,11347.0,6726.0,3927.0,3943.0
Gene_1-KO-3,Gene_6-KO-1,Gene_1,Gene_6,False,False,False,False,11250.0,12469.0,3552.0,3334.0

The code works as intended and normalizes all numeric columns of that dataframe, but it seems to work very slow, also with other normalization methods. I am regularly working with dataframes that contain up to several millions of rows. For ~1 million rows and only 4 numeric columns, normalization takes almost 10 minutes on my mobile computer with an Intel Core i7-6600U @ 2.6GHz, although I precompute the sums for every column.
Is there a way to speed this up, e.g., parallelization or some neat Pandas trick?

Any help and/or pointers are much appreciated!

Body:
Thank you for taking time to answer me! I came up with another solution that I would like to share. YaoYao inspired me to test the multiprocessing library to tackle my problem. The following solution runs extremely fast. The script starts by reading the .csv file, determines the names of the numeric columns and computes their sums. Then it splits the dataset into equally sized chunks and maps the normalizing function to each chunk. The resulting normalized dataframes are concatenated back to yield the entire normalized dataset.

import pandas as pd
import math
import numpy as np
from multiprocessing import Pool

def index_marks(nrows, chunk_size):
    return range(chunk_size, math.ceil(nrows / chunk_size) * chunk_size, chunk_size)

def split(dfm, chunk_size):
    indices = index_marks(dfm.shape[0], chunk_size)
    return np.split(dfm, indices)

def normalize(df, sums, numeric_cols):
    for col in numeric_cols:
        df.insert(df.columns.get_loc(col)+1, col+'_norm', ((df[col]/sums[col])*1000000)+1)
    return df

def parallel_normalize(data):
    df = data[0]
    sums = data[1]
    numeric_cols = data[2]

    df = normalize(df, sums, numeric_cols)
    return df

numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
dataset_file = '/path/to/file.csv'

cores = 3

dataset = pd.read_csv(dataset_file, index_col=['Guide1', 'Guide2'], sep=',')
dataset = dataset.fillna(0.0)

numeric_cols = [col for col in dataset.columns if dataset[col].dtype in numerics]
sums = dataset[numeric_cols].sum(axis=0, skipna = True)

chunks = split(dataset, int(round(dataset.shape[0]/cores)))
pool = Pool(cores)
dataset = pd.concat(pool.map(parallel_normalize, [[x, sums, numeric_cols] for x in chunks]))
pool.close()
pool.join()

I do not know why the speedup is that enormous, though. I would have expected a speedup of maybe 60%, because I split the data into 3 chunks. But it literally runs instantaneously. If anyone could comment and give some insight here, I'd be more than happy!


问:
Javascript - Create a currying function returning the list of parameters
I'm trying to create a currying function returning the list of parameters but I don't how to make it.
This is my code :

const getParameters = arg => {
  const parameters = [];

  const innerFunction = arg => {
    parameters.push(arg);
    return innerFunction;
  };
  return innerFunction(arg);
};

getParameters(1)(2)(5); // => expected value [1,2,5]
getParameters(1)(2)(5)(20); // => expected value [1,2,5,20]
```

答:
Not very good solution, but... Try this one if you want to have a string in output.

function getParameters(a) {

  let parameters = '[';
  parameters += `${a}`;

  function innerFunction(b) {
    parameters += `,${b}`;
    return innerFunction;
  }

  innerFunction.toString = function() {
    return `${parameters}]`;
  };

  return innerFunction;
}

console.log(getParameters(1)(3)(4)); //[1,3,4]
```


问:
When i add a widget it overides the previous widget
Im working on a Chat Screen and ive successful put in a Scrollview and a box layout inside it but when the function to send message is called, it adds to the Scrollview but it overides what is already written in the scrollview. i want when i add a widget to the Scrollview it adds to the previous items on the scrollview rather than overriding it. Here is the code from my python file.

```<code>class Chat(Screen):

    def on_enter(self, *args):
        app = App.get_running_app()
        self.chatdestination = Label(
            text=firebase.get("/users/" + app.localId, 'first name') + " " + firebase.get('/users/' + app.localId,
                                                                                'last name'),
            pos_hint={"center_x": 0.5, "center_y": 0.95}, size_hint=[0.8, 0.1], color=(0, 0, 0, 1),
            font_name="fonts/Qanelas-Light.otf")

        self.add_widget(self.chatdestination)

    def __init__(self, **kwargs):
        super(Chat, self).__init__(**kwargs)
        self.localId = None
        self.messagebutton = Button(text="Send", font_size = 20, font_name= "fonts/Qanelas-Heavy.otf", background_color= (0.082, 0.549, 0.984, 1.0), background_normal= '', pos_hint= {"right": 1,"down": 1}, size_hint= [0.2, 0.1])
        self.messagebutton.bind(on_release = self.send_message)
        self.add_widget(self.messagebutton)

        self.messagetextinput = TextInput(width=Window.size[0]*0.8, hint_text= "Write a message", font_name= "fonts/Qanelas-Light.otf", size_hint= [0.8, 0.1], pos_hint= {"left": 1,"down": 1})
        self.add_widget(self.messagetextinput)

        Window.bind(on_key_down=self.on_key_down)

        Clock.schedule_once(self.focus_text_input, 1)

    def on_key_down(self, instance, keyboard, keycode, text, modifiers):
        if keycode == 40:
            self.send_message(None)

    def send_message(self, _):
        app = App.get_running_app()
        message = self.messagetextinput.text
        if len(message) > 0:
            database.child("messages").child(app.localId).update({self.localId: message})
            self.chatbubble = Button(text=self.messagetextinput.text, background_color = [0.082, 0.549, 0.984, 1.0], background_normal = "",
                                      pos_hint= {"center_x": 1}, color = (1, 1, 1, 1))
            self.chatbubble.size = self.chatbubble.texture_size

            self.ids.chatlayout.add_widget(self.chatbubble)
            self.ids.scrollview.scroll_to(self.chatbubble)
            self.messagetextinput.text = ""

            Clock.schedule_once(self.focus_text_input, 0.1)

    def focus_text_input(self, _):
        self.messagetextinput.focus = True

class MyApp(App):
    refresh_token_file = "refresh_token.txt"
    placementtext = None
    id1 = None
    local1d = None
    placementid = None
    notification = None

    def build(self):
        self.refresh_token_file = self.user_data_dir + self.refresh_token_file
        self.thefirebase = MyFireBase()

        return sm

</code>```

Here is my code from my kivy file

```<code>
<Chat>

    canvas.before:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

    ScrollView:
        id: scrollview
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        size_hint: 1, 0.8

        canvas.before:
            Color:
                rgba: 0, 0, 0, 0
            Rectangle:
                pos: self.pos
                size: self.size

        BoxLayout:
            id: chatlayout
            orientation: "vertical"
            spacing: 5
            padding: 10, 10
            size_hint_y: None
</code>```

Any help would be appreciated

答:
Looks like it should work but I have an idea to try. At first add size_hint_y=None to your button:

```<code>self.chatbubble = Button(text=self.messagetextinput.text, background_color = [0.082, 0.549, 0.984, 1.0], background_normal = "",
                                      pos_hint= {"center_x": 1}, color = (1, 1, 1, 1), size_hint_y=None)
</code>```

And now BoxLayout is without any hints about sizes, so add this thing to set height of it's rows, usually it really helps:

```<code>        BoxLayout:
            id: chatlayout
            orientation: "vertical"
            spacing: 5
            padding: 10, 10
            size_hint_y: None
            # add this
            height: self.minimum_height
</code>```

Body:
Im working on a Chat Screen and ive successful put in a Scrollview and a box layout inside it but when the function to send message is called, it adds to the Scrollview but it overides what is already written in the scrollview. i want when i add a widget to the Scrollview it adds to the previous items on the scrollview rather than overriding it. Here is the code from my python file.

class Chat(Screen):

    def on_enter(self, *args):
        app = App.get_running_app()
        self.chatdestination = Label(
            text=firebase.get("/users/" + app.localId, 'first name') + " " + firebase.get('/users/' + app.localId,
                                                                                'last name'),
            pos_hint={"center_x": 0.5, "center_y": 0.95}, size_hint=[0.8, 0.1], color=(0, 0, 0, 1),
            font_name="fonts/Qanelas-Light.otf")

        self.add_widget(self.chatdestination)

    def __init__(self, **kwargs):
        super(Chat, self).__init__(**kwargs)
        self.localId = None
        self.messagebutton = Button(text="Send", font_size = 20, font_name= "fonts/Qanelas-Heavy.otf", background_color= (0.082, 0.549, 0.984, 1.0), background_normal= '', pos_hint= {"right": 1,"down": 1}, size_hint= [0.2, 0.1])
        self.messagebutton.bind(on_release = self.send_message)
        self.add_widget(self.messagebutton)

        self.messagetextinput = TextInput(width=Window.size[0]*0.8, hint_text= "Write a message", font_name= "fonts/Qanelas-Light.otf", size_hint= [0.8, 0.1], pos_hint= {"left": 1,"down": 1})
        self.add_widget(self.messagetextinput)

        Window.bind(on_key_down=self.on_key_down)

        Clock.schedule_once(self.focus_text_input, 1)

    def on_key_down(self, instance, keyboard, keycode, text, modifiers):
        if keycode == 40:
            self.send_message(None)

    def send_message(self, _):
        app = App.get_running_app()
        message = self.messagetextinput.text
        if len(message) > 0:
            database.child("messages").child(app.localId).update({self.localId: message})
            self.chatbubble = Button(text=self.messagetextinput.text, background_color = [0.082, 0.549, 0.984, 1.0], background_normal = "",
                                      pos_hint= {"center_x": 1}, color = (1, 1, 1, 1))
            self.chatbubble.size = self.chatbubble.texture_size

            self.ids.chatlayout.add_widget(self.chatbubble)
            self.ids.scrollview.scroll_to(self.chatbubble)
            self.messagetextinput.text = ""

            Clock.schedule_once(self.focus_text_input, 0.1)

    def focus_text_input(self, _):
        self.messagetextinput.focus = True

class MyApp(App):
    refresh_token_file = "refresh_token.txt"
    placementtext = None
    id1 = None
    local1d = None
    placementid = None
    notification = None

    def build(self):
        self.refresh_token_file = self.user_data_dir + self.refresh_token_file
        self.thefirebase = MyFireBase()

        return sm

Here is my code from my kivy file

<Chat>

    canvas.before:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

    ScrollView:
        id: scrollview
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        size_hint: 1, 0.8

        canvas.before:
            Color:
                rgba: 0, 0, 0, 0
            Rectangle:
                pos: self.pos
                size: self.size

        BoxLayout:
            id: chatlayout
            orientation: "vertical"
            spacing: 5
            padding: 10, 10
            size_hint_y: None

Any help would be appreciated

Body:
Looks like it should work but I have an idea to try. At first add size_hint_y=None to your button:

self.chatbubble = Button(text=self.messagetextinput.text, background_color = [0.082, 0.549, 0.984, 1.0], background_normal = "",
                                      pos_hint= {"center_x": 1}, color = (1, 1, 1, 1), size_hint_y=None)

And now BoxLayout is without any hints about sizes, so add this thing to set height of it's rows, usually it really helps:

        BoxLayout:
            id: chatlayout
            orientation: "vertical"
            spacing: 5
            padding: 10, 10
            size_hint_y: None
            # add this
            height: self.minimum_height


问:
How can I duplicate slots within a Vuejs render function?
I have a component which is passed content via a slot. I'm using a render function to output the content. The reason I'm using a render function is because I want to duplicate the content multiple times. When I use this code, everything works fine:

```<code>render(createElement){
    return createElement('div', {}, this.$slots.default);
}
</code>```

When I data that is being passed changes, the output changes as well.

However, since I want to duplicate the slot content, I'm now trying this:

```<code>return createElement(
    'div', {},
        [
            createElement('div', { }, this.$slots.default),
            createElement('div', { }, this.$slots.default)
        ]
    )
</code>```

Now the problem is, when the slot content changes from outside the component, only the content in the second div gets updated, the content in the first div stays the same..

Am I missing something here?

答:
I found this SO question searching for a way to render the content of a slot multiple times like e.g. for a generic list that can have a template for the content of a list row, which is used for each item.

As of 2020 (in fact earlier) multiple rendering of a slot can be achieved using scoped slots. This is documented here:

https://v2.vuejs.org/v2/guide/components-slots.html#Other-Examples

The documentation says:

Slot props allow us to turn slots into reusable templates that can render different content based on input props

(obviously, if we can use the template to render different content based on props, we can also use it to render the same content)

The example given right there uses a template instead of a render function, but how to use scoped slots in a render function is fortunately also documented:

https://v2.vuejs.org/v2/guide/render-function.html#Slots

Body:
I have a component which is passed content via a slot. I'm using a render function to output the content. The reason I'm using a render function is because I want to duplicate the content multiple times. When I use this code, everything works fine:

render(createElement){
    return createElement('div', {}, this.$slots.default);
}

When I data that is being passed changes, the output changes as well.

However, since I want to duplicate the slot content, I'm now trying this:

return createElement(
    'div', {},
        [
            createElement('div', { }, this.$slots.default),
            createElement('div', { }, this.$slots.default)
        ]
    )

Now the problem is, when the slot content changes from outside the component, only the content in the second div gets updated, the content in the first div stays the same..

Am I missing something here?


问:
Sass @extend to consider imported css during build
I have a global CSS file that contains all generic CSS.

I want to be able to extend all the classes present in this global CSS file in any of my SCSS files.

Right now it throws an error .xyz class does not exist and build fails. I tried importing this file but still build fails.

Adding !options next to class is one way for the build to pass but is there any other better way?

Bit more context for Vue users. I use VueCli3. I use

Body:
It sounds like you want to globally include a CSS file with content that the SCSS blocks in each component can read. (Variables, style definitions, etc).

@extend works like a variable, meaning SCSS needs the definition style to be available as part of its compilation. So that means getting "SCSS Global Variables" working should solve your Extend problem too.

In that case, you need to tweak how Webpack deals with your components. You can do it manually as described here. Or my preference is to use a Vue Cli plugin called vue-cli-plugin-sass-resources-loader. Make sure that your component <style> section contains lang="SCSS" though I assume you're already doing that.