问:
Angular how to show live value of json object
In angular , I am trying to display one json object to client html. Using below route on server side.

```<code>const express = require('express');
const jsonRoute = express.Router();

jsonRoute .route('/json').get(function (req, res) {
    var JsonObj = { rank: 73 } ;
  res.end(JSON.stringify(JsonObj));
});

setInterval(function(){
    JsonObj.rank = parseInt(Math.random()*100);
}, 1000); // this interval may be anything.from ms to minutes.

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

this works on http://localhost:4000/json and displays ,

```<code>{"rank":73}
</code>```

But does not show the values changed in setInterval. And same route i am using in a angular service (using http).

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class getjsonService {
  uri = "http://localhost:4000/json";
  constructor(private http: HttpClient) { }
  jsondata(){
    return this.http.get(`${this.uri}`);
  }
}
</code>```

This value i am displaying in component html page. The problem is, it is not showing updated value of json. Please suggest how can i show live json value in angular. Please note, in realtime my json object going to be big in size , around 100 keys and value and i want to show live value for all key. And also change value interval may not be fix as one second. it may be in milliseconds as well.

Thanks

答:
Your problem is a structural one with how RESTful architecture works. Your server only sends the new data to your angluar app when your app asks for it, not when your server detects a change. What you will need to do is either add a set timeout in your angular project that will call the server for the new data every few seconds.

```<code>setInterval(function(){ var JsonData = getJsonService.jsondata() }, 3000);
console.log(JsonData);
//This will refetch the data every 3 seconds you can lower this number to make it refresh more often
</code>```

The other option is to rewrite your server to use web-sockets as Ravin pointed out.

Body:
In angular , I am trying to display one json object to client html. Using below route on server side.

const express = require('express');
const jsonRoute = express.Router();

jsonRoute .route('/json').get(function (req, res) {
    var JsonObj = { rank: 73 } ;
  res.end(JSON.stringify(JsonObj));
});

setInterval(function(){
    JsonObj.rank = parseInt(Math.random()*100);
}, 1000); // this interval may be anything.from ms to minutes.

module.exports = jsonRoute ;

this works on http://localhost:4000/json and displays ,

{"rank":73}

But does not show the values changed in setInterval. And same route i am using in a angular service (using http).

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class getjsonService {
  uri = "http://localhost:4000/json";
  constructor(private http: HttpClient) { }
  jsondata(){
    return this.http.get(`${this.uri}`);
  }
}

This value i am displaying in component html page. The problem is, it is not showing updated value of json. Please suggest how can i show live json value in angular. Please note, in realtime my json object going to be big in size , around 100 keys and value and i want to show live value for all key. And also change value interval may not be fix as one second. it may be in milliseconds as well.

Thanks

Body:
Your problem is a structural one with how RESTful architecture works. Your server only sends the new data to your angluar app when your app asks for it, not when your server detects a change. What you will need to do is either add a set timeout in your angular project that will call the server for the new data every few seconds.

setInterval(function(){ var JsonData = getJsonService.jsondata() }, 3000);
console.log(JsonData);
//This will refetch the data every 3 seconds you can lower this number to make it refresh more often

The other option is to rewrite your server to use web-sockets as Ravin pointed out.


来源: stackexchange

问:
How do you balance working for a living and contributing to open source projects?
I have been a working programmer since the turn of the century and I have always been fascinated by the open source world. I have wanted to contribute to these projects but I find it difficult to find the time that I think these projects would require.

I find professional software development to be a huge time sink. Almost every project I have worked on has a familiar litany inflexible deadlines and inevitable round the clock last minute pushes that eat up your nights and weekends and everything else in sight. Even in the project that don't have this - the typical work day is 10 to 12 hours and after that one has errands and chores, reading up on the latest stuff, etc...

Since this happens with a fair amount of regularity - I am hesitant to join projects since I can't promise to devote a regular number of hours every week.

My question is how do you people do it?

Do you work at open source companies? Am I exaggerating the amount of time I need to spend (I am thinking a couple of hours everyday)? Am I way off base and simply not managing my time efficiently? How do you manage your time?

答: I keep it simple when I'm working, I'm working, and when I'm not working, I can work on Open Source stuff.</p>

OwnerDisplayName: Nikhil

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Unkwntech


问:
Android aes encryption pad block corrupted
I am using the methods below and if I enter the right key everything works fine.
But if I enter a wrong key I am receiving a BadPaddingException:pad block corrupted...
Am I doing something wrong? </p>

```<code>public  void initKey(String passwd, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException{

    byte[] localsalt = salt;
   PBEKeySpec password = new PBEKeySpec(passwd.toCharArray(),localsalt, 1024,128);//, localsalt, 1000, 128);  //128bit enc aes
   SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5And128BitAES-CBC-OpenSSL","BC");
   PBEKey key = (PBEKey) factory.generateSecret(password);
   encKey = new SecretKeySpec(key.getEncoded(), "AES");
}

public   String txt2enc(String etxt) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {

       final Cipher cipher = Cipher.getInstance("AES");//AES
       cipher.init(Cipher.ENCRYPT_MODE, encKey);

       byte[] encrypted = cipher.doFinal((etxt).getBytes("UTF-8"));
       return Base64.encodeToString(encrypted, 0);
}

//decryption
public  String txt2dec(String dtxt) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{

    final Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, encKey);
    byte[] decrypt = cipher.doFinal(Base64.decode(dtxt, 0));
    return new String(decrypt);//return Base64.encodeToString(decrypt, 0);
}
</code>```

答:
Other than supplying the wrong key, I don't think so :)

A stack trace would help, so we can see which function is throwing the BadPaddingException.

This may well be because the 'bad' key is a different length to the 'good' key - does the 'bad' key come out of initKey() or somewhere else?

Best wishes,

Phil Lello

ContentLicense: CC BY-SA 3.0

Body:
I am using the methods below and if I enter the right key everything works fine.
But if I enter a wrong key I am receiving a BadPaddingException:pad block corrupted...
Am I doing something wrong?

public  void initKey(String passwd, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException{

    byte[] localsalt = salt;
   PBEKeySpec password = new PBEKeySpec(passwd.toCharArray(),localsalt, 1024,128);//, localsalt, 1000, 128);  //128bit enc aes
   SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5And128BitAES-CBC-OpenSSL","BC");
   PBEKey key = (PBEKey) factory.generateSecret(password);
   encKey = new SecretKeySpec(key.getEncoded(), "AES");
}

public   String txt2enc(String etxt) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {

       final Cipher cipher = Cipher.getInstance("AES");//AES
       cipher.init(Cipher.ENCRYPT_MODE, encKey);

       byte[] encrypted = cipher.doFinal((etxt).getBytes("UTF-8"));
       return Base64.encodeToString(encrypted, 0);
}

//decryption
public  String txt2dec(String dtxt) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{

    final Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, encKey);
    byte[] decrypt = cipher.doFinal(Base64.decode(dtxt, 0));
    return new String(decrypt);//return Base64.encodeToString(decrypt, 0);
}


问:
What happens if i don't pass a parameter in .then() function, what will it return
i have learned that .then() is a higher-order function— it takes two callback functions as arguments. We refer to these callbacks as handlers. When the promise settles, the appropriate handler will be invoked with that settled value.
i want to know that what will .then() method will return if neither parameter is passed.</p>

答:
Than that part of the chain gets skipped completely, and the chained promise will resolve to what the previous promise resolved.

Promise.resolve(1).then().then(console.log); // 1
Promise.reject(1).then().catch(console.log); // 1```

ContentLicense: CC BY-SA 4.0


问:
When JHipster create the dummy data starting from JDL?
I'm new to JHipster and I'm doing some experiment.

I created my fist JHipster App and imported the "default" JDL that can be downloaded from here: JDL Studio (without any modification).

After the import, I see my entity filled with some demo data and
some csv file has been created under config/liquidbase/data with the same info.

I checked the jhipster-jdl.jh file and there is no data specification there.

I don't understand where that data is created and what is the logic that allows creating that dummy data.

答:
The values are generated by Faker.js in the table.csv template.  They are based on the column name, and are not configurable at this point.

If you don't want the data to be inserted into the database, you can remove the faker context from the config in application-dev.yml


问:
How to get the domain in a variable?
I'm running multiple codes with different domains. I do not want to put the domain manually.
For example:
var domainName = 'domain.com.br';

I would like to know if it is possible to get the domain (G Suite) through a variable.
For example:
var domainName = get.domain ();

答:
Use Session.getActiveUser().getEmail() / Session.getEffectiveUser().getEmail() to get the active/effective user email address  and JavaScript string handling techniques like using regular expressions:

```<code> var domain = Session.getActiveUser().getEmail().match('\@(.*)$')[1]
</code>```

Validation of regex expression

var match = 'useraname@example.com'.match('\@(.*)$');
console.info(match[1])```

Title: How to get the domain in a variable?

Body:
Use Session.getActiveUser().getEmail() / Session.getEffectiveUser().getEmail() to get the active/effective user email address  and JavaScript string handling techniques like using regular expressions:

 var domain = Session.getActiveUser().getEmail().match('\@(.*)$')[1]

Validation of regex expression

var match = 'useraname@example.com'.match('\@(.*)$');
console.info(match[1])


问:
Adding a custom made JPanel from a separate class file in another JPanel on runtime
I have a custom made JPanel made in a separate class file with some parameters, named itemCard and I am trying to add an instance of it by giving values in the parameters in another jpanel(contentAreaPane) in another jframe(mainPage.java) class file on the actionPerformed event of a button (jButton1)

itemCard.java

import javax.swing.*;
import Resources.colors.MaterialColor;
import Resources.fonts.*;

/**
 *
 * @author Aditya
 */
public class itemCard extends JPanel {

    /**
     * Creates new form itemCard
     */

    public String name,price,retailer, prodID;

    /**
     * Takes four parameters, first is product ID which is a String, second is product
     * name which is a String, third is price which is a String,
     *  fourth is retailer name which is a String.
     */
    public itemCard(String prodID, String productName, String price, String retailer) {
        this.name = productName;
        this.price = price;
        this.retailer = retailer;
        this.prodID = prodID;

        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        imageIconHolder = new javax.swing.JLabel();
        detailPane = new javax.swing.JPanel();
        priceTag = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(new javax.swing.border.LineBorder(MaterialColor.BLUE_200, 2, true));
        setPreferredSize(new java.awt.Dimension(250, 300));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                formMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                formMouseExited(evt);
            }
        });
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        imageIconHolder.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        imageIconHolder.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        imageIconHolder.setMaximumSize(new java.awt.Dimension(250, 200));
        imageIconHolder.setMinimumSize(new java.awt.Dimension(250, 200));
        imageIconHolder.setPreferredSize(new java.awt.Dimension(250, 200));
        add(imageIconHolder, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 250, 200));

        detailPane.setBackground(MaterialColor.LIGHTBLUE_800);
        detailPane.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        priceTag.setBackground(MaterialColor.PURPLE_800);
        priceTag.setFont(Montserrat.REGULAR.deriveFont(25f));
        priceTag.setForeground(new java.awt.Color(255, 255, 255));
        priceTag.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        priceTag.setText(price);
        priceTag.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        priceTag.setMaximumSize(new java.awt.Dimension(70, 100));
        priceTag.setMinimumSize(new java.awt.Dimension(70, 100));
        priceTag.setOpaque(true);
        priceTag.setPreferredSize(new java.awt.Dimension(70, 100));
        detailPane.add(priceTag, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 70, 100));

        jScrollPane2.setBorder(null);
        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        jScrollPane2.setEnabled(false);
        jScrollPane2.setPreferredSize(new java.awt.Dimension(180, 100));

        jTextArea1.setEditable(false);
        jTextArea1.setBackground(MaterialColor.DEEPPURPLE_700);
        jTextArea1.setColumns(20);
        jTextArea1.setFont(Roboto.THIN.deriveFont(20f)
        );
        jTextArea1.setForeground(new java.awt.Color(51, 51, 51));
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setText(((name.length()>51)?(name.substring(0, 48)+"...") : (name)) +"\n"+ ((retailer.length()>14)?(retailer.substring(0, 14)+"...") : (retailer)));
        jTextArea1.setToolTipText(name+"\n"+retailer);
        jTextArea1.setWrapStyleWord(true);
        jTextArea1.setBorder(null);
        jTextArea1.setMargin(new java.awt.Insets(7, 5, 7, 5));
        jTextArea1.setRequestFocusEnabled(false);
        jScrollPane2.setViewportView(jTextArea1);

        detailPane.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 0, 180, 100));

        add(detailPane, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 200, 250, 100));
    }// </editor-fold>

    private void formMouseEntered(java.awt.event.MouseEvent evt) {
        this.setBorder(new javax.swing.border.LineBorder(MaterialColor.BLUE_400, 3, true));
        detailPane.setBackground(MaterialColor.LIGHTBLUE_900);
    }

    private void formMouseExited(java.awt.event.MouseEvent evt) {
        this.setBorder(new javax.swing.border.LineBorder(MaterialColor.BLUE_200, 2, true));
        detailPane.setBackground(MaterialColor.LIGHTBLUE_800);
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel detailPane;
    private javax.swing.JLabel imageIconHolder;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JLabel priceTag;
    // End of variables declaration
}
```

<p>and here's the actionperformed event listener of my button:</p>

<pre class="lang-java prettyprint-override"><code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            JPanel itemcard = new itemCard("123456789AB","Inspiron 7567 Intel Core i5 DELL Laptop","68K","CloudTail Pvt. Ltd.");
            contentAreaPane.add(itemcard);
            contentAreaPane.revalidate();
            contentAreaPane.repaint();

        }catch(Exception e){
            e.printStackTrace();
        }
    }
</code>```

However, this isn't working, that is no new itemCard JPanel gets created and showed in contentAreaPane JPanel when clicked on jButton1 and is giving the following error:

```<code>java.lang.IllegalArgumentException
at org.netbeans.lib.awtextra.AbsoluteLayout.addLayoutComponent(Unknown Source)
at java.desktop/java.awt.Container.addImpl(Container.java:1152)
at java.desktop/java.awt.Container.add(Container.java:436)
at AppFrames.mainPage.jButton1ActionPerformed(mainPage.java:887)
at AppFrames.mainPage$31.actionPerformed(mainPage.java:619)
</code>```

How I can resolve it?

答:
In the documentation for Container, it lists these exceptions:

```<code>IllegalArgumentException - if index is invalid; if comp is a child of this container, the valid range is [-1, getComponentCount()-1]; if component is not a child of this container, the valid range is [-1, getComponentCount()]
IllegalArgumentException - if comp is an ancestor of this container
IllegalArgumentException - if adding a window to a container
</code>```

I think you must be getting this on condition 2 or 3

Body:
I have a custom made JPanel made in a separate class file with some parameters, named itemCard and I am trying to add an instance of it by giving values in the parameters in another jpanel(contentAreaPane) in another jframe(mainPage.java) class file on the actionPerformed event of a button (jButton1)

itemCard.java

import javax.swing.*;
import Resources.colors.MaterialColor;
import Resources.fonts.*;

/**
 *
 * @author Aditya
 */
public class itemCard extends JPanel {

    /**
     * Creates new form itemCard
     */

    public String name,price,retailer, prodID;

    /**
     * Takes four parameters, first is product ID which is a String, second is product
     * name which is a String, third is price which is a String,
     *  fourth is retailer name which is a String.
     */
    public itemCard(String prodID, String productName, String price, String retailer) {
        this.name = productName;
        this.price = price;
        this.retailer = retailer;
        this.prodID = prodID;

        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        imageIconHolder = new javax.swing.JLabel();
        detailPane = new javax.swing.JPanel();
        priceTag = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(new javax.swing.border.LineBorder(MaterialColor.BLUE_200, 2, true));
        setPreferredSize(new java.awt.Dimension(250, 300));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                formMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                formMouseExited(evt);
            }
        });
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        imageIconHolder.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        imageIconHolder.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        imageIconHolder.setMaximumSize(new java.awt.Dimension(250, 200));
        imageIconHolder.setMinimumSize(new java.awt.Dimension(250, 200));
        imageIconHolder.setPreferredSize(new java.awt.Dimension(250, 200));
        add(imageIconHolder, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 250, 200));

        detailPane.setBackground(MaterialColor.LIGHTBLUE_800);
        detailPane.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        priceTag.setBackground(MaterialColor.PURPLE_800);
        priceTag.setFont(Montserrat.REGULAR.deriveFont(25f));
        priceTag.setForeground(new java.awt.Color(255, 255, 255));
        priceTag.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        priceTag.setText(price);
        priceTag.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        priceTag.setMaximumSize(new java.awt.Dimension(70, 100));
        priceTag.setMinimumSize(new java.awt.Dimension(70, 100));
        priceTag.setOpaque(true);
        priceTag.setPreferredSize(new java.awt.Dimension(70, 100));
        detailPane.add(priceTag, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 70, 100));

        jScrollPane2.setBorder(null);
        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        jScrollPane2.setEnabled(false);
        jScrollPane2.setPreferredSize(new java.awt.Dimension(180, 100));

        jTextArea1.setEditable(false);
        jTextArea1.setBackground(MaterialColor.DEEPPURPLE_700);
        jTextArea1.setColumns(20);
        jTextArea1.setFont(Roboto.THIN.deriveFont(20f)
        );
        jTextArea1.setForeground(new java.awt.Color(51, 51, 51));
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setText(((name.length()>51)?(name.substring(0, 48)+"...") : (name)) +"\n"+ ((retailer.length()>14)?(retailer.substring(0, 14)+"...") : (retailer)));
        jTextArea1.setToolTipText(name+"\n"+retailer);
        jTextArea1.setWrapStyleWord(true);
        jTextArea1.setBorder(null);
        jTextArea1.setMargin(new java.awt.Insets(7, 5, 7, 5));
        jTextArea1.setRequestFocusEnabled(false);
        jScrollPane2.setViewportView(jTextArea1);

        detailPane.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 0, 180, 100));

        add(detailPane, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 200, 250, 100));
    }// </editor-fold>

    private void formMouseEntered(java.awt.event.MouseEvent evt) {
        this.setBorder(new javax.swing.border.LineBorder(MaterialColor.BLUE_400, 3, true));
        detailPane.setBackground(MaterialColor.LIGHTBLUE_900);
    }

    private void formMouseExited(java.awt.event.MouseEvent evt) {
        this.setBorder(new javax.swing.border.LineBorder(MaterialColor.BLUE_200, 2, true));
        detailPane.setBackground(MaterialColor.LIGHTBLUE_800);
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel detailPane;
    private javax.swing.JLabel imageIconHolder;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JLabel priceTag;
    // End of variables declaration
}

and here's the actionperformed event listener of my button:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            JPanel itemcard = new itemCard("123456789AB","Inspiron 7567 Intel Core i5 DELL Laptop","68K","CloudTail Pvt. Ltd.");
            contentAreaPane.add(itemcard);
            contentAreaPane.revalidate();
            contentAreaPane.repaint();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

However, this isn't working, that is no new itemCard JPanel gets created and showed in contentAreaPane JPanel when clicked on jButton1 and is giving the following error:

java.lang.IllegalArgumentException
at org.netbeans.lib.awtextra.AbsoluteLayout.addLayoutComponent(Unknown Source)
at java.desktop/java.awt.Container.addImpl(Container.java:1152)
at java.desktop/java.awt.Container.add(Container.java:436)
at AppFrames.mainPage.jButton1ActionPerformed(mainPage.java:887)
at AppFrames.mainPage$31.actionPerformed(mainPage.java:619)

How I can resolve it?

Body:
In the documentation for Container, it lists these exceptions:

IllegalArgumentException - if index is invalid; if comp is a child of this container, the valid range is [-1, getComponentCount()-1]; if component is not a child of this container, the valid range is [-1, getComponentCount()]
IllegalArgumentException - if comp is an ancestor of this container
IllegalArgumentException - if adding a window to a container

I think you must be getting this on condition 2 or 3


问:
An invalid character was found when trying to add multiple MailMessage.To addresses
I'm getting an error when I add two or more TO email addresses in the method below.

If I only have one email it works fine, but it errors when there is more than one email in the string.

Error: An invalid character was found in the mail header: ','

I tried different methods online but nothing is working.

```<code>EmailSender.SendMailMessage("test1@yahoo.org,test2@yahoo.org", "test3@test.org",
    changeContro_test.subject, body, AttachementList, ChangeId);

public static void SendMailMessage(string toEmail, string fromEmail, string subject,
    string body, List<string> attachmentFullPath,int ChangeId)
{
    MailMessage mMailMessage = new MailMessage();

    mMailMessage.From = new MailAddress(fromEmail);

    // set the recipient address of the mail message
    mMailMessage.To.Add(new MailAddress(toEmail)); //error happens here
</code>```

答:
You can split your string

Something like this:

foreach(var email in toEmail.Split(','))
   mMailMessage.To.Add(new MailAddress(email));
```

<p>or </p>

```foreach(var email in toEmail.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries))
   mMailMessage.To.Add(new MailAddress(email));
```

as RufusL said

Obs:
To is a MailAddressCollection, so you can add how many addresses you need.

Body:
I'm getting an error when I add two or more TO email addresses in the method below.

If I only have one email it works fine, but it errors when there is more than one email in the string.

Error: An invalid character was found in the mail header: ','

I tried different methods online but nothing is working.

EmailSender.SendMailMessage("test1@yahoo.org,test2@yahoo.org", "test3@test.org",
    changeContro_test.subject, body, AttachementList, ChangeId);

public static void SendMailMessage(string toEmail, string fromEmail, string subject,
    string body, List<string> attachmentFullPath,int ChangeId)
{
    MailMessage mMailMessage = new MailMessage();

    mMailMessage.From = new MailAddress(fromEmail);

    // set the recipient address of the mail message
    mMailMessage.To.Add(new MailAddress(toEmail)); //error happens here

Body:
You can split your string

Something like this:

foreach(var email in toEmail.Split(','))
   mMailMessage.To.Add(new MailAddress(email));

or

foreach(var email in toEmail.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries))
   mMailMessage.To.Add(new MailAddress(email));

as RufusL said

Obs:
To is a MailAddressCollection, so you can add how many addresses you need.


问:
Julia Array with different sized vectors
When creating an array of various sized vectors(e.g. arrays) I am generating an error msg.

```<code>julia> A = [[1,2] [1,2,3] [1,4] [1] [1,5,6,7]]
ERROR: DimensionMismatch("vectors must have same lengths")
Stacktrace:
 [1] hcat(::Array{Int64,1}, ::Array{Int64,1}, ::Array{Int64,1}, ::Vararg{Array{Int64,1},N} where N) at .\array.jl:1524
 [2] top-level scope at none:0
</code>```

Although, if I initalize an array and assign the vectors 'its okay'...

```<code>julia> A = Array{Any}(undef,5)
5-element Array{Any,1}:
 #undef
 #undef
 #undef
 #undef
 #undef

pseudo code> A[i] = [x,y...]
2-element Array{Int64,1}:
 1
 2

julia> A
5-element Array{Any,1}:
 [1, 2]
 [1, 2, 3]
 [1]
 [1, 5]
 [1, 2, 6, 4, 5]

</code>```

Is there a way to initialize the array with the variously sized arrays or is Julia configured this way to prevent errors.

答:
The space-separated syntax you're using for the outermost array is specifically for horizontal concatenation of matrices, so your code is trying to concatenate all of these vectors into a matrix, which doesn't work since they have different lengths. Use commas in the outer array like the inner one to get an array of arrays:</p>

```<code>julia> A = [[1,2], [1,2,3], [1,4], [1], [1,5,6,7]]
5-element Array{Array{Int64,1},1}:
 [1, 2]
 [1, 2, 3]
 [1, 4]
 [1]
 [1, 5, 6, 7]
</code>```

Body:
When creating an array of various sized vectors(e.g. arrays) I am generating an error msg.

julia> A = [[1,2] [1,2,3] [1,4] [1] [1,5,6,7]]
ERROR: DimensionMismatch("vectors must have same lengths")
Stacktrace:
 [1] hcat(::Array{Int64,1}, ::Array{Int64,1}, ::Array{Int64,1}, ::Vararg{Array{Int64,1},N} where N) at .\array.jl:1524
 [2] top-level scope at none:0

Although, if I initalize an array and assign the vectors 'its okay'...

julia> A = Array{Any}(undef,5)
5-element Array{Any,1}:
 #undef
 #undef
 #undef
 #undef
 #undef

pseudo code> A[i] = [x,y...]
2-element Array{Int64,1}:
 1
 2

julia> A
5-element Array{Any,1}:
 [1, 2]
 [1, 2, 3]
 [1]
 [1, 5]
 [1, 2, 6, 4, 5]

Is there a way to initialize the array with the variously sized arrays or is Julia configured this way to prevent errors.

Body:
The space-separated syntax you're using for the outermost array is specifically for horizontal concatenation of matrices, so your code is trying to concatenate all of these vectors into a matrix, which doesn't work since they have different lengths. Use commas in the outer array like the inner one to get an array of arrays:

julia> A = [[1,2], [1,2,3], [1,4], [1], [1,5,6,7]]
5-element Array{Array{Int64,1},1}:
 [1, 2]
 [1, 2, 3]
 [1, 4]
 [1]
 [1, 5, 6, 7]


问:
Comma in return value
I know the desired syntax lies in the first function but I for the life of me can't find where it is.

I've attempted to remove commas and add spaces to each .split() each has yielded an undesired return value.

```<code>def get_country_codes(prices):
    price_list = prices.split(',')
    results = ''
    for price in price_list:
        results += price.split('$')[0]
    return results

def main():
    prices = "US$40, AU$89, JP$200"
    price_result = get_country_codes(prices)
    print(price_result)

if __name__ == "__main__":
    main()
</code>```

The current output:

```<code>US AU JP
</code>```

The desired output:

```<code>US, AU, JP
</code>```

答:
You could also use regex if you want to. Since you know country codes will be two capital letters only (A-Z), you can look for a match of two capital letters that precede a dollar sign. </p>

```<code>def get_country_codes(prices):
    country_codes = re.findall(r'([A-Z]{2})\$', prices)
    return ', '.join(country_codes)
</code>```

<p>See regex demo here. </p>

Title: Comma in return value

Body:
I know the desired syntax lies in the first function but I for the life of me can't find where it is.

I've attempted to remove commas and add spaces to each .split() each has yielded an undesired return value.

def get_country_codes(prices):
    price_list = prices.split(',')
    results = ''
    for price in price_list:
        results += price.split('$')[0]
    return results

def main():
    prices = "US$40, AU$89, JP$200"
    price_result = get_country_codes(prices)
    print(price_result)

if __name__ == "__main__":
    main()

The current output:

US AU JP

The desired output:

US, AU, JP

Body:
You could also use regex if you want to. Since you know country codes will be two capital letters only (A-Z), you can look for a match of two capital letters that precede a dollar sign.

def get_country_codes(prices):
    country_codes = re.findall(r'([A-Z]{2})\$', prices)
    return ', '.join(country_codes)

See regex demo here.


问:
how I can add a css file correctly to a php file
My css file import in the header of the html not work. It don't show any changes on the page. I have tried to add the type="text/css" to the link object of the html header but this has no effect.

login.php

<?php

?>

<!DOCTYPE html>

    <title>Login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <link ref="stylesheet" href="login.css">

Test

    <form class="form-signin">

Bitte anmelden

...
        <button class="btn btn-lg btn-primary btn-block" type="submit">Anmelden</button>
    </form>

```

<p>login.css</p>

<pre class="lang-css prettyprint-override"><code>html,
body {
    height: 100%;
}

p {
    background-color: chartreuse;
}

body {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    padding-top: 40px;
    padding-bottom: 40px;
    background-color: #f5f5f5;
}

.form-signin {
    width: 100%;
    max-width: 330px;
    padding: 15px;
    margin: auto;
}
.form-signin .checkbox {
    font-weight: 400;
}
.form-signin .form-control {
    position: relative;
    box-sizing: border-box;
    height: auto;
    padding: 10px;
    font-size: 16px;
}
...
</code>```

How I can import the css file correctly. To change the design of the html site.

答:
you need to change:

```<code> <link ref="stylesheet" href="login.css">
</code>```

to

```<code> <link rel="stylesheet" href="login.css">
</code>```

you've typed ref and not rel in line 12

your css file is correct :)

Body:
My css file import in the header of the html not work. It don't show any changes on the page. I have tried to add the type="text/css" to the link object of the html header but this has no effect.

login.php

<?php

?>

<!DOCTYPE html>

    <title>Login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <link ref="stylesheet" href="login.css">

Test

    <form class="form-signin">

Bitte anmelden

...
        <button class="btn btn-lg btn-primary btn-block" type="submit">Anmelden</button>
    </form>

login.css

html,
body {
    height: 100%;
}

p {
    background-color: chartreuse;
}

body {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    padding-top: 40px;
    padding-bottom: 40px;
    background-color: #f5f5f5;
}

.form-signin {
    width: 100%;
    max-width: 330px;
    padding: 15px;
    margin: auto;
}
.form-signin .checkbox {
    font-weight: 400;
}
.form-signin .form-control {
    position: relative;
    box-sizing: border-box;
    height: auto;
    padding: 10px;
    font-size: 16px;
}
...

How I can import the css file correctly. To change the design of the html site.

Body:
you need to change:

 <link ref="stylesheet" href="login.css">

to

 <link rel="stylesheet" href="login.css">

you've typed ref and not rel in line 12

your css file is correct :)


问:
Script to list all files each time I change directory for bashrc?
I would like to list all files each time I execute the "change directory" command.

I have already tried adding this to my ~/.bashrc:

```<code>function cdl { cd $1; ls;}
</code>```

and running this in terminal:

```<code>cdl directorytoswitchto
</code>```

Long story short: I would like to do cd and ls in the same command.

答:
To override a builtin function with a different version, you typically will call the original via command. For example,

```<code>cd() { command cd "$@" && ls; }
</code>```

Body:
I would like to list all files each time I execute the "change directory" command.

I have already tried adding this to my ~/.bashrc:

function cdl { cd $1; ls;}

and running this in terminal:

cdl directorytoswitchto

Long story short: I would like to do cd and ls in the same command.

Body:
To override a builtin function with a different version, you typically will call the original via command. For example,

cd() { command cd "$@" && ls; }


问:
Error implementing child routes in Angular 6
I'm getting below error while implementing child routes for my project. I didn't find any help on GitHub and other sites.

ERROR Error: Uncaught (in promise): SecurityError: Failed to execute
  'pushState' on 'History': A history state object with URL
  'http://%28routes%29/' cannot be created in a document with origin
  'http://localhost:4200' and URL 'http://localhost:4200/'. Error:
  Failed to execute 'pushState' on 'History': A history state object
  with URL 'http://%28routes%29/' cannot be created in a document with
  origin 'http://localhost:4200' and URL 'http://localhost:4200/'.

答:
I had the same issue and it was caused by missing slash '/' in front of the router link string. To be more clear I had the problem when the link was defined as:

<mat-list-item>About</mat-list-item>

The problem disappeared when I corrected it to:

<mat-list-item>About</mat-list-item>

Body:
I had the same issue and it was caused by missing slash '/' in front of the router link string. To be more clear I had the problem when the link was defined as:

<mat-list-item><a class="mat-h3 menu-link" [routerLink]="['about']">About</a></mat-list-item>

The problem disappeared when I corrected it to:

<mat-list-item><a class="mat-h3 menu-link" [routerLink]="['/about']">About</a></mat-list-item>


问:
How to update array value in Laravel
My controller code:

```<code>        $userBasicInfoId = $this->userBasicInfo->where('user_id', $userProfile['id'])->value('id');
        if($userBasicInfoId) {
            $userBasicInfo = $this->userBasicInfo->find($userBasicInfoId);
            $userBasicInfo->fill($userProfile)->save();
        } else {
            $userBasicInfo = $this->userBasicInfo->create($request->only($this->userBasicInfo->getModel()->fillable));
        }
</code>```

This is my userBasicInfo model values:

```<code>        protected $table = "user_basic_info";

protected $fillable = [
    'first_name', 'middle_name', 'last_name', 'profile_pic', 'date_of_birth', 'gender', 'area_id', 'user_id', 'created_by', 'updated_by', 'created_at', 'deletedAt','title','cell_no','address','ssn','work_phone','fax','extension','primary_facility','affiliated_facility','employed_by','emergency_phone','designation','department','employment_type','biography','hiring_date','from','to'
];
</code>```

I can update the values but the issue is there is only one field which I am sending as array that is affiliated_facility, how I can update this value?

My body request:

```<code>                  "user_profile": {

    "id": 38,
    "email": "shahzad124@ovadamd.com",
    "status": 0,
    "first_name": "shahzad12",
    "middle_name": "Admin",
    "last_name": "super",
    "date_of_birth": "2015-01-01",
    "gender": "M",
    "address": "Minhatten NY",
    "city": "New York",
    "state": "Washington",
    "zip": "12312",
    "fax": "111-111-1111",
    "extension": "2471",
    "work_phone": "111-111-1111",
    "social_security": "111-11-1111",
    "module_id": 2,
    "title": "Mr",
    "cell_no": "124788",
    "ssn": "256",
    "primary_facility": 1,
    "affiliated_facility":  [1],
    "employed_by": "john",
    "emergency_phone": "57744",
    "designation": " supervisor",
    "department": "facility",
    "employment_type": "Temporary",
    "biography": "I am Doctor",
    "hiring_date": "2015-01-01",
    "from": "2015-01-01",
    "to": "2015-01-01",
    "image": ""
    },
</code>```

You can see in my body request I am sending "affiliated_facility" (marked with [1] above). When I hit request it says:

```<code>   "Array to string conversion (SQL: update `user_basic_info` set `gender` = M, `updated_at` = 2019-05-29 18:19:34, `affiliated_facility` = 1 where `id` = 36)"
</code>```

How can I update this specific field which I am sending as array?

答:
Unless you have that field set up as a JSON or similar in SQL, changing your architecture may be the easiest solution.  That affiliated_facility field looks like it should be a relation, not a single field on your userBasicInfo model, since it could be many facilities (since an array may return).

If you set up a relation on the userBasicInfo model, something like:

```<code>public function affiliatedFacilities(){
    return $this->belongsToMany("App\AffiliatedFacility");
}
</code>```

Then when you update, you can attach / sync automatically:

```<code>$userBasicInfo->affiliatedFacilities()->sync($request->get('affiliated_facility', []));
</code>```

Title: How to update array value in Laravel

Body:
My controller code:

        $userBasicInfoId = $this->userBasicInfo->where('user_id', $userProfile['id'])->value('id');
        if($userBasicInfoId) {
            $userBasicInfo = $this->userBasicInfo->find($userBasicInfoId);
            $userBasicInfo->fill($userProfile)->save();
        } else {
            $userBasicInfo = $this->userBasicInfo->create($request->only($this->userBasicInfo->getModel()->fillable));
        }

This is my userBasicInfo model values:

        protected $table = "user_basic_info";

protected $fillable = [
    'first_name', 'middle_name', 'last_name', 'profile_pic', 'date_of_birth', 'gender', 'area_id', 'user_id', 'created_by', 'updated_by', 'created_at', 'deletedAt','title','cell_no','address','ssn','work_phone','fax','extension','primary_facility','affiliated_facility','employed_by','emergency_phone','designation','department','employment_type','biography','hiring_date','from','to'
];

I can update the values but the issue is there is only one field which I am sending as array that is affiliated_facility, how I can update this value?

My body request:

                  "user_profile": {

    "id": 38,
    "email": "shahzad124@ovadamd.com",
    "status": 0,
    "first_name": "shahzad12",
    "middle_name": "Admin",
    "last_name": "super",
    "date_of_birth": "2015-01-01",
    "gender": "M",
    "address": "Minhatten NY",
    "city": "New York",
    "state": "Washington",
    "zip": "12312",
    "fax": "111-111-1111",
    "extension": "2471",
    "work_phone": "111-111-1111",
    "social_security": "111-11-1111",
    "module_id": 2,
    "title": "Mr",
    "cell_no": "124788",
    "ssn": "256",
    "primary_facility": 1,
    "affiliated_facility":  [1],
    "employed_by": "john",
    "emergency_phone": "57744",
    "designation": " supervisor",
    "department": "facility",
    "employment_type": "Temporary",
    "biography": "I am Doctor",
    "hiring_date": "2015-01-01",
    "from": "2015-01-01",
    "to": "2015-01-01",
    "image": ""
    },

You can see in my body request I am sending "affiliated_facility" (marked with [1] above). When I hit request it says:

   "Array to string conversion (SQL: update `user_basic_info` set `gender` = M, `updated_at` = 2019-05-29 18:19:34, `affiliated_facility` = 1 where `id` = 36)"

How can I update this specific field which I am sending as array?

Body:
Unless you have that field set up as a JSON or similar in SQL, changing your architecture may be the easiest solution.  That affiliated_facility field looks like it should be a relation, not a single field on your userBasicInfo model, since it could be many facilities (since an array may return).

If you set up a relation on the userBasicInfo model, something like:

public function affiliatedFacilities(){
    return $this->belongsToMany("App\AffiliatedFacility");
}

Then when you update, you can attach / sync automatically:

$userBasicInfo->affiliatedFacilities()->sync($request->get('affiliated_facility', []));


问:
dart constructor copyWith argument shows null
I have a variable title which I initialised with a string value.

```<code>class NameState{
 List name;
 var title = 'this is a default one';
 NameState({this.title,this.name});

 NameState copyWith({title, name}) {

     print(title); // this one should be null as there is no data.
     print(this.title); // null => why this one null as i have title defined

    return new NameState(
        title: title ?? this.title,
        name: name ?? this.name,
    );
  }
}
</code>```

Here my title variable has a value. but if I don't pass any value for title in the constructor, the value of this.title become null. How can I get the current value this is a default one in this.title ?

Thank you.

答:
You need to use this

```<code>NameState({this.title = 'this is a default one', this.name});
</code>```

instead of

```<code> NameState({this.title,this.name});
</code>```

Body:
I have a variable title which I initialised with a string value.

class NameState{
 List name;
 var title = 'this is a default one';
 NameState({this.title,this.name});

 NameState copyWith({title, name}) {

     print(title); // this one should be null as there is no data.
     print(this.title); // null => why this one null as i have title defined

    return new NameState(
        title: title ?? this.title,
        name: name ?? this.name,
    );
  }
}

Here my title variable has a value. but if I don't pass any value for title in the constructor, the value of this.title become null. How can I get the current value this is a default one in this.title ?

Thank you.

Body:
You need to use this

NameState({this.title = 'this is a default one', this.name});

instead of

 NameState({this.title,this.name});


问:
Server Error '/" Application C# asp.net

Parser Error Description: An error
  occurred during the parsing of a
  resource required to service this
  request. Please review the following
  specific parse error details and
  modify your source file appropriately.

Parser Error Message: Could not load
  type 'SafeNet_WebPage.admin.project'.

Source Error:

```<code>Line 1:  <%@ Page Language="C#" AutoEventWireup="false" CodeBehind="project.aspx.cs" Inherits="SafeNet_WebPage.admin.project" %>
Line 2:
Line 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code>```

This project.aspx are locating in one folder with other news.aspx and when I load news it s all ok, it does what it make to do, but when i load project i get this?

答:
As I have Viewed your issue on TeamViewer, your button is not added in your form Designer class as you have copied the button and event handler from another page.

What I did for you was to add a button from the toolbox and its Designer class. After it is refreshed and your problem will be resolved.

Title: Server Error '/" Application C# asp.net

Body:
Parser Error Description: An error
  occurred during the parsing of a
  resource required to service this
  request. Please review the following
  specific parse error details and
  modify your source file appropriately.

Parser Error Message: Could not load
  type 'SafeNet_WebPage.admin.project'.

Source Error:

Line 1:  <%@ Page Language="C#" AutoEventWireup="false" CodeBehind="project.aspx.cs" Inherits="SafeNet_WebPage.admin.project" %>
Line 2:
Line 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

This project.aspx are locating in one folder with other news.aspx and when I load news it s all ok, it does what it make to do, but when i load project i get this?


问:
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'
I just want to install socket.io to my project which is located on 3.chat folder. But when I run following command it shows following Warnings.And its not created a node_modules directory inside my project folder. How to fix this?</p>

```<code>C:\Users\Nuwanst\Documents\NodeJS\3.chat>npm install socket.io
C:\Users\Nuwanst
`-- socket.io@2.0.3

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'
npm WARN Nuwanst No description
npm WARN Nuwanst No repository field.
npm WARN Nuwanst No README data
npm WARN Nuwanst No license field.
</code>```

答:
if your node_modules got installed in say /home/UserName/ like in my case,
your package-lock.json file will also be there. just delete this file, go back to your app folder and run npm init and then npm install <pkgname> (e.g express) and a new node_modules folder will be created for your.

Body:
I just want to install socket.io to my project which is located on 3.chat folder. But when I run following command it shows following Warnings.And its not created a node_modules directory inside my project folder. How to fix this?

C:\Users\Nuwanst\Documents\NodeJS\3.chat>npm install socket.io
C:\Users\Nuwanst
`-- socket.io@2.0.3

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'
npm WARN Nuwanst No description
npm WARN Nuwanst No repository field.
npm WARN Nuwanst No README data
npm WARN Nuwanst No license field.


问:
How to check that reduceByKey efficiently executed at spark-streaming
I'm running Spark 2.3.1 standalone cluster. My job is consuming from Kafka mini batches every 2 minutes and writing aggregation to some store. Job looks like as following:

```<code>val stream = KafkaUtils.createDirectStream(...)
stream.map(x=> Row(...))
   .flatMap(r=> ... List[Row] )
   .map(r=> (k,r))
   .reduceByKey((r1, r2) => r)
   .map { case (_, v) => v}
   .foreachRDD { (rdd, time) => // write data}
</code>```

When I look into the DAG the picture is as following

My question - as far as I understand spark should use a combiner for reduceByKey operation, that should significantly reduce the shuffle size. Why DAG doesn't show this, and how can I check that?

Additional question - if shuffle size is 2.5G does it hit disk? What configuration properties/metrics should I look into to check that job configured and run optimally.
For this job the executors run with 10G memory

答:
First question: reduceByKey internally calls combineBykey. You will not see a difference on the DAG execution as a result, i.e. tasks the same.

2nd question, please make a new posting. Since you have not, Details for Stage, Shuffle Spill Disk should give you an indication.

Body:
I'm running Spark 2.3.1 standalone cluster. My job is consuming from Kafka mini batches every 2 minutes and writing aggregation to some store. Job looks like as following:

val stream = KafkaUtils.createDirectStream(...)
stream.map(x=> Row(...))
   .flatMap(r=> ... List[Row] )
   .map(r=> (k,r))
   .reduceByKey((r1, r2) => r)
   .map { case (_, v) => v}
   .foreachRDD { (rdd, time) => // write data}

When I look into the DAG the picture is as following

My question - as far as I understand spark should use a combiner for reduceByKey operation, that should significantly reduce the shuffle size. Why DAG doesn't show this, and how can I check that?

Additional question - if shuffle size is 2.5G does it hit disk? What configuration properties/metrics should I look into to check that job configured and run optimally.
For this job the executors run with 10G memory


问:
R - Tallying up number of new individuals encountered as days go by based on ID
I am monitoring an animal population. I have their individual IDs as numbers, the date they were encountered on, and the number of individuals encountered on that day. I want to sum up the total number of different individuals encountered as the days go by, so I need it to recognize same IDs and only add new individuals to the total encountered.

This is my dataset, the last column being my desired outcome:

```<code>Month Day   ID    N. individuals that day     Total encountered
5     13    44    3                           3
5     13    58    3                           3
5     13    57    3                           3
5     14    58    1                           3
5     15    44    2                           4
5     15    06    2                           4
</code>```

答:
An option </p>

```<code>library(tidyverse)
df %>%
   add_count(Month, Day) %>%
   mutate(n1 = duplicated(ID)) %>%
   group_by(Month, Day) %>%
   mutate(n1 = c(min(n - n1), rep(0, n()-1))) %>%
   ungroup %>%
   mutate(n1 = cumsum(n1))
# A tibble: 6 x 5
#  Month   Day    ID     n    n1
#  <int> <int> <int> <int> <dbl>
#1     5    13    44     3     3
#2     5    13    58     3     3
#3     5    13    57     3     3
#4     5    14    58     1     3
#5     5    15    44     2     4
#6     5    15     6     2     4
</code>```

Body:
I am monitoring an animal population. I have their individual IDs as numbers, the date they were encountered on, and the number of individuals encountered on that day. I want to sum up the total number of different individuals encountered as the days go by, so I need it to recognize same IDs and only add new individuals to the total encountered.

This is my dataset, the last column being my desired outcome:

Month Day   ID    N. individuals that day     Total encountered
5     13    44    3                           3
5     13    58    3                           3
5     13    57    3                           3
5     14    58    1                           3
5     15    44    2                           4
5     15    06    2                           4

Body:
An option

library(tidyverse)
df %>%
   add_count(Month, Day) %>%
   mutate(n1 = duplicated(ID)) %>%
   group_by(Month, Day) %>%
   mutate(n1 = c(min(n - n1), rep(0, n()-1))) %>%
   ungroup %>%
   mutate(n1 = cumsum(n1))
# A tibble: 6 x 5
#  Month   Day    ID     n    n1
#  <int> <int> <int> <int> <dbl>
#1     5    13    44     3     3
#2     5    13    58     3     3
#3     5    13    57     3     3
#4     5    14    58     1     3
#5     5    15    44     2     4
#6     5    15     6     2     4


问:
F# XUnit test does not print output
I have the following XUnit test in a project created with dotnet new xunit:

```<code>type Scenarios(output : ITestOutputHelper) =

  [<Fact>]
  member __.``Output shows up`` () =
    output.WriteLine("I'm here")
</code>```

This approach seems to have worked before, but running the tests doesn't show any output, regardless of whether I use dotnet test or dotnet xunit:

```<code>> dotnet test
Build started, please wait...
Build completed.

Test run for C:\Work\OSS\Streamstone.fs\tests\StreamstoneFs.Tests\bin\Debug\netcoreapp2.0\StreamstoneFs.Tests.dll(.NETCoreApp,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 15.6.0-preview-20180109-01
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:00:00.4295013]   Discovering: StreamstoneFs.Tests
[xUnit.net 00:00:00.4750480]   Discovered:  StreamstoneFs.Tests
[xUnit.net 00:00:00.4792986]   Starting:    StreamstoneFs.Tests
[xUnit.net 00:00:00.5964013]   Finished:    StreamstoneFs.Tests

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1.1835 Seconds

> dotnet xunit
Detecting target frameworks in StreamstoneFs.Tests.fsproj...
Building for framework netcoreapp2.0...
  StreamstoneFs -> C:\Work\OSS\Streamstone.fs\src\StreamstoneFs\bin\Debug\netstandard2.0\StreamstoneFs.dll
  StreamstoneFs.Tests -> C:\Work\OSS\Streamstone.fs\tests\StreamstoneFs.Tests\bin\Debug\netcoreapp2.0\StreamstoneFs.Tests.dll
Running .NET Core 2.0.0 tests for framework netcoreapp2.0...
xUnit.net Console Runner (64-bit .NET Core 4.6.00001.0)
  Discovering: StreamstoneFs.Tests
  Discovered:  StreamstoneFs.Tests
  Starting:    StreamstoneFs.Tests
  Finished:    StreamstoneFs.Tests
=== TEST EXECUTION SUMMARY ===
   StreamstoneFs.Tests  Total: 1, Errors: 0, Failed: 0, Skipped: 0, Time: 0.109s
</code>```

What am I doing wrong here?

答:
This works in VS Code with a .NET Core project, though it's a bit noisy: </p>

```<code>dotnet test --logger:"console;verbosity=detailed"
</code>```

Title: F# XUnit test does not print output

Body:
I have the following XUnit test in a project created with dotnet new xunit:

type Scenarios(output : ITestOutputHelper) =

  [<Fact>]
  member __.``Output shows up`` () =
    output.WriteLine("I'm here")

This approach seems to have worked before, but running the tests doesn't show any output, regardless of whether I use dotnet test or dotnet xunit:

> dotnet test
Build started, please wait...
Build completed.

Test run for C:\Work\OSS\Streamstone.fs\tests\StreamstoneFs.Tests\bin\Debug\netcoreapp2.0\StreamstoneFs.Tests.dll(.NETCoreApp,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 15.6.0-preview-20180109-01
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:00:00.4295013]   Discovering: StreamstoneFs.Tests
[xUnit.net 00:00:00.4750480]   Discovered:  StreamstoneFs.Tests
[xUnit.net 00:00:00.4792986]   Starting:    StreamstoneFs.Tests
[xUnit.net 00:00:00.5964013]   Finished:    StreamstoneFs.Tests

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1.1835 Seconds

> dotnet xunit
Detecting target frameworks in StreamstoneFs.Tests.fsproj...
Building for framework netcoreapp2.0...
  StreamstoneFs -> C:\Work\OSS\Streamstone.fs\src\StreamstoneFs\bin\Debug\netstandard2.0\StreamstoneFs.dll
  StreamstoneFs.Tests -> C:\Work\OSS\Streamstone.fs\tests\StreamstoneFs.Tests\bin\Debug\netcoreapp2.0\StreamstoneFs.Tests.dll
Running .NET Core 2.0.0 tests for framework netcoreapp2.0...
xUnit.net Console Runner (64-bit .NET Core 4.6.00001.0)
  Discovering: StreamstoneFs.Tests
  Discovered:  StreamstoneFs.Tests
  Starting:    StreamstoneFs.Tests
  Finished:    StreamstoneFs.Tests
=== TEST EXECUTION SUMMARY ===
   StreamstoneFs.Tests  Total: 1, Errors: 0, Failed: 0, Skipped: 0, Time: 0.109s

What am I doing wrong here?

Body:
This works in VS Code with a .NET Core project, though it's a bit noisy:

dotnet test --logger:"console;verbosity=detailed"


问:
How do i use PSGSUITE PS module to add google groups?
Ok so I work for a small business, and they use a google spread sheet as the "Phone list"
for finding and contacting employees. I installed the PSGSUITE powershell module and it seems to work very well, but im new to powershell and coding in general. The filter sheet i made along with the phone list places the employees in there respective groups. Example then The code.

```<code>"phone list"
Name    #   Company code    Ext.    Department  Job Title   Email
Hayden  111-222-333 JOP     IT  Technician  example@example.com
</code>```

"filter 2sheet"

```<code>JOP SPD
hayden@.com lisa@.com
john@.com   arron@.com
david@.com  mike@.com
</code>```

I want to add these emails to there respective google groups

```<code>## NOVA BEAZ ##
## add groups in google based on company title
###
####
# Import Modules
Import-Module PSGSuite
# Create Array of Groups
$Title = (Import-GSSheet -SpreadsheetId "1NtCT5ruoL4Kf4-ec55xe-L8esXcSY8orfd-zOFK4q4k" -SheetName "Filter" -Headers "None"  -Range "A1:1")
$Title = $Title | % { $_ }
$Groups = (Get-GSgroup -Fields "Name" )
    if($Title = $Groups)
        #{add that users email to the group}
    #else
        {echo "there is now group that matches that"}
</code>```

The main issue is I really just dont know how to correctly run through the arrays and select all the emails in that row to add to the google groups, I think I need a array or object list form of storing my emails, I want this to be dynamic.

答:
Excerpts from my blog post on how to use the PSGusite module.

Please check if the following answers your question. If not, let me know.

User Process

To begin, we need to import the module and then use the command Get-GSDriveFileList to find the Google Sheet where our data is stored.

Next, we use the command Import-GSSheet to import our user and group data.

Get Data from GSheet

```<code># Import module
Import-Module -Name PSGSuite

# Discover spreadsheet Id in drive file list
$Spreadsheet = Get-GSDriveFileList -Filter "name = 'UserManagement'"

# Get data from each sheet from Google spreadsheet
$UserData = Import-GSSheet -SpreadsheetId $Spreadsheet.Id -SheetName 'Users'
$GroupData = Import-GSSheet -SpreadsheetId $Spreadsheet.Id -SheetName 'Groups'
</code>```

Create Organization Units

We use Get-GSOrganizationalUnit to determine if the OU exists. And then we use New-GSOrganizationalUnit to create it if it does not.

```<code>foreach ($Group in $GroupData) {
    $SplitPath = $Group.OrgUnitPath -Split '/'
    $ParentPath = $SplitPath[0..($SplitPath.Count -2)] -join '/'
    $OUPath = $SplitPath[-1]

    $OrgUnit = Get-GSOrganizationalUnit -SearchBase $Group.OrgUnitPath -SearchScope Base -ErrorAction SilentlyContinue
    if ($OrgUnit) {
        "Org Unit {0} exists at {1}" -f $OrgUnit.OrgUnitPath,$OrgUnit.ParentOrgUnitPath
    } else {
        "Org Unit {0} does not exist; attempting to create in {1}" -f $Group.OrgUnitPath,$ParentPath
        try {
            $GSOrgUnit = New-GSOrganizationalUnit -Name $OUPath.ToLower() -ParentOrgUnitPath $ParentPath -Description $Group.Description
            "Created {0} : {1}" -f $GSOrgUnit.OrgUnitPath,$GSOrgUnit.Description
        }
        catch {
            "Unable to create {0}" -f $Group.OrgUnitPath
        }
    }
}
</code>```

Create Groups

Using the command Get-GSGroup, we check if the group exists. If the group does not already exist, use New-GSGroup to create the group from the spreadsheet.

```<code>foreach ($Group in $GroupData) {
    $GSGroup = Get-GSGroup -Group $Group.Name -ErrorAction SilentlyContinue
    if ($GSGroup) {
        "Group {0} exists" -f $Group.Name
    } else {
        "Group {0} does not exist; attempting to create" -f $Group.Name
        try {
            $NewGSGroup = New-GSGroup -Name $Group.Name -Email $Group.Email -Description $Group.Description
            "Created {0} : {1}" -f $NewGSGroup.Name,$NewGSGroup.Description
        }
        catch {
            "Unable to create {0}" -f $Group.Name
        }
    }
}
</code>```

Create Users

Create the users listed in the spreadsheet.

First, determine the department based on the user type.

Using the department, set the variable for the org unit path.

Create the required hashtable for CustomSchemas to add the EmployeeType to the user.

Generate a random secure password.

Using the command New-GSUser, create the new user.

If the user is successfully created, use the command New-GSUserAlias for best effort to create an email alias based on the user’s full name.

```<code>foreach ($User in $UserData) {
    $Domain = $User.Email.Split('@')[1]
    switch ($User.UserType) {
        'Faculty' { $Department = 'Academics'}
        'Staff'   { $Department = 'Business' }
    }

    # Set OU path
    $OrgUnitPath = $GroupData.Where({$_.Name -eq $Department}).OrgUnitPath

    # Set employee type custom schema
    $CustomSchemas = @{
        CustomUniversity = @{
            EmployeeType = $User.UserType
        }
    }

    # Set a random secure string
    $Password = ConvertTo-SecureString -String (Get-RandomPassword) -AsPlainText -Force

    $NewGSUserParams = @{
        PrimaryEmail = $User.Email
        FullName = $User.FullName
        GivenName = $User.GivenName
        FamilyName = $User.FamilyName
        OrgUnitPath = $OrgUnitPath
        CustomSchemas = $CustomSchemas
        Password = $Password
    }
    $NewUser = New-GSUser @NewGSUserParams -ErrorAction SilentlyContinue
    if ($NewUser) {
        'Created user {0} with primary email {1}' -f $User.FullName,$User.Email
    } else {
        'Failed to create user {0}' -f $User.Email
    }

    New-GSUserAlias -User $NewUser.PrimaryEmail -Alias ( $NewUser.Name.FullName.Replace(' ',''),$Domain -join '@') -ErrorAction SilentlyContinue | Out-Null
}
</code>```

The Get-RandomPassword function is a mock-up. You would need to provide your own password method.

You can omit CustomSchemas from the hashtable. The blog post shows how to manually create new attributes, if you are interested.

Assign Users to Groups

Next, we use Get-GSUserList to get a list of all users in the parent OU, and then add the user to the group with Add-GSGroupMember.

```<code>$UserToGroupList = Get-GSUserList -SearchBase '/test' -SearchScope Subtree
foreach ($User in $UserToGroupList) {
    switch -regex ($User.OrgUnitPath) {
        'academics' { $GroupName = 'Academics'}
        'business' { $GroupName = 'Business'}
    }
    try {
        Add-GSGroupMember -Identity $GroupName -Member $User.User -ErrorAction Stop | Out-Null
        'Added {0} to group {1}' -f $User.User,$GroupName
    }
    catch {
        'Failed to add {0} to group {1}' -f $User.User,$GroupName
    }
}
</code>```

Note: I manually created a /test organizational unit and blocked automatic assignment of a license since I’m using my personal G Suite account. I don’t want any surprises at the end of the month.

Body:
Ok so I work for a small business, and they use a google spread sheet as the "Phone list"
for finding and contacting employees. I installed the PSGSUITE powershell module and it seems to work very well, but im new to powershell and coding in general. The filter sheet i made along with the phone list places the employees in there respective groups. Example then The code.

"phone list"
Name    #   Company code    Ext.    Department  Job Title   Email
Hayden  111-222-333 JOP     IT  Technician  example@example.com

"filter 2sheet"

JOP SPD
hayden@.com lisa@.com
john@.com   arron@.com
david@.com  mike@.com

I want to add these emails to there respective google groups

## NOVA BEAZ ##
## add groups in google based on company title
###
####
# Import Modules
Import-Module PSGSuite
# Create Array of Groups
$Title = (Import-GSSheet -SpreadsheetId "1NtCT5ruoL4Kf4-ec55xe-L8esXcSY8orfd-zOFK4q4k" -SheetName "Filter" -Headers "None"  -Range "A1:1")
$Title = $Title | % { $_ }
$Groups = (Get-GSgroup -Fields "Name" )
    if($Title = $Groups)
        #{add that users email to the group}
    #else
        {echo "there is now group that matches that"}

The main issue is I really just dont know how to correctly run through the arrays and select all the emails in that row to add to the google groups, I think I need a array or object list form of storing my emails, I want this to be dynamic.

Body:
Excerpts from my blog post on how to use the PSGusite module.

Please check if the following answers your question. If not, let me know.

User Process

To begin, we need to import the module and then use the command Get-GSDriveFileList to find the Google Sheet where our data is stored.

Next, we use the command Import-GSSheet to import our user and group data.

Get Data from GSheet

# Import module
Import-Module -Name PSGSuite

# Discover spreadsheet Id in drive file list
$Spreadsheet = Get-GSDriveFileList -Filter "name = 'UserManagement'"

# Get data from each sheet from Google spreadsheet
$UserData = Import-GSSheet -SpreadsheetId $Spreadsheet.Id -SheetName 'Users'
$GroupData = Import-GSSheet -SpreadsheetId $Spreadsheet.Id -SheetName 'Groups'

Create Organization Units

We use Get-GSOrganizationalUnit to determine if the OU exists. And then we use New-GSOrganizationalUnit to create it if it does not.

foreach ($Group in $GroupData) {
    $SplitPath = $Group.OrgUnitPath -Split '/'
    $ParentPath = $SplitPath[0..($SplitPath.Count -2)] -join '/'
    $OUPath = $SplitPath[-1]

    $OrgUnit = Get-GSOrganizationalUnit -SearchBase $Group.OrgUnitPath -SearchScope Base -ErrorAction SilentlyContinue
    if ($OrgUnit) {
        "Org Unit {0} exists at {1}" -f $OrgUnit.OrgUnitPath,$OrgUnit.ParentOrgUnitPath
    } else {
        "Org Unit {0} does not exist; attempting to create in {1}" -f $Group.OrgUnitPath,$ParentPath
        try {
            $GSOrgUnit = New-GSOrganizationalUnit -Name $OUPath.ToLower() -ParentOrgUnitPath $ParentPath -Description $Group.Description
            "Created {0} : {1}" -f $GSOrgUnit.OrgUnitPath,$GSOrgUnit.Description
        }
        catch {
            "Unable to create {0}" -f $Group.OrgUnitPath
        }
    }
}

Create Groups

Using the command Get-GSGroup, we check if the group exists. If the group does not already exist, use New-GSGroup to create the group from the spreadsheet.

foreach ($Group in $GroupData) {
    $GSGroup = Get-GSGroup -Group $Group.Name -ErrorAction SilentlyContinue
    if ($GSGroup) {
        "Group {0} exists" -f $Group.Name
    } else {
        "Group {0} does not exist; attempting to create" -f $Group.Name
        try {
            $NewGSGroup = New-GSGroup -Name $Group.Name -Email $Group.Email -Description $Group.Description
            "Created {0} : {1}" -f $NewGSGroup.Name,$NewGSGroup.Description
        }
        catch {
            "Unable to create {0}" -f $Group.Name
        }
    }
}

Create Users

Create the users listed in the spreadsheet.

First, determine the department based on the user type.

Using the department, set the variable for the org unit path.

Create the required hashtable for CustomSchemas to add the EmployeeType to the user.

Generate a random secure password.

Using the command New-GSUser, create the new user.

If the user is successfully created, use the command New-GSUserAlias for best effort to create an email alias based on the user’s full name.

foreach ($User in $UserData) {
    $Domain = $User.Email.Split('@')[1]
    switch ($User.UserType) {
        'Faculty' { $Department = 'Academics'}
        'Staff'   { $Department = 'Business' }
    }

    # Set OU path
    $OrgUnitPath = $GroupData.Where({$_.Name -eq $Department}).OrgUnitPath

    # Set employee type custom schema
    $CustomSchemas = @{
        CustomUniversity = @{
            EmployeeType = $User.UserType
        }
    }

    # Set a random secure string
    $Password = ConvertTo-SecureString -String (Get-RandomPassword) -AsPlainText -Force

    $NewGSUserParams = @{
        PrimaryEmail = $User.Email
        FullName = $User.FullName
        GivenName = $User.GivenName
        FamilyName = $User.FamilyName
        OrgUnitPath = $OrgUnitPath
        CustomSchemas = $CustomSchemas
        Password = $Password
    }
    $NewUser = New-GSUser @NewGSUserParams -ErrorAction SilentlyContinue
    if ($NewUser) {
        'Created user {0} with primary email {1}' -f $User.FullName,$User.Email
    } else {
        'Failed to create user {0}' -f $User.Email
    }

    New-GSUserAlias -User $NewUser.PrimaryEmail -Alias ( $NewUser.Name.FullName.Replace(' ',''),$Domain -join '@') -ErrorAction SilentlyContinue | Out-Null
}

The Get-RandomPassword function is a mock-up. You would need to provide your own password method.

You can omit CustomSchemas from the hashtable. The blog post shows how to manually create new attributes, if you are interested.

Assign Users to Groups

Next, we use Get-GSUserList to get a list of all users in the parent OU, and then add the user to the group with Add-GSGroupMember.

$UserToGroupList = Get-GSUserList -SearchBase '/test' -SearchScope Subtree
foreach ($User in $UserToGroupList) {
    switch -regex ($User.OrgUnitPath) {
        'academics' { $GroupName = 'Academics'}
        'business' { $GroupName = 'Business'}
    }
    try {
        Add-GSGroupMember -Identity $GroupName -Member $User.User -ErrorAction Stop | Out-Null
        'Added {0} to group {1}' -f $User.User,$GroupName
    }
    catch {
        'Failed to add {0} to group {1}' -f $User.User,$GroupName
    }
}

Note: I manually created a /test organizational unit and blocked automatic assignment of a license since I’m using my personal G Suite account. I don’t want any surprises at the end of the month.


问:
Angular 6 how to get count of the particular column based on same value from an array of object
I have an array of object and also I am using foreach loop in typescript.Here as per my array it contains 2 columns having value progress:100 and others are less that 100.So here I need to calculate the count of columns having progress:100,for ex here it should be 2.Also I need to get the count of all columns having progress value is less or not 100.for ex here 2.Then I need to append into div.I have tried but its adding not counting.Here is the code below

app.component.html

```<code><div>Progress : 2{{count}}</div><div>completed : 2{{count}}</div>
</code>```

app.component.ts

```<code>declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

      arrayVal:any;
      currentVal : any;
  title = 'projectchart';
  public array = [{"id":1,"progress":100},{"id":3,"progress":70},{"id":5,"progress":50},{"id":6,"progress":100}];
  ngOnInit(){
     let count=0;
     this.array.forEach((item, index) => {
     console.log(item.progress) ;
     count +=item.progress ;
});
     console.log(count);
  }

}
</code>```

答:
Change this line

```<code>count +=item.progress;
</code>```

To

```<code>if (item.progress === 100) {count += 1;}
</code>```

Body:
I have an array of object and also I am using foreach loop in typescript.Here as per my array it contains 2 columns having value progress:100 and others are less that 100.So here I need to calculate the count of columns having progress:100,for ex here it should be 2.Also I need to get the count of all columns having progress value is less or not 100.for ex here 2.Then I need to append into div.I have tried but its adding not counting.Here is the code below

app.component.html

Progress : 2{{count}}

completed : 2{{count}}

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

      arrayVal:any;
      currentVal : any;
  title = 'projectchart';
  public array = [{"id":1,"progress":100},{"id":3,"progress":70},{"id":5,"progress":50},{"id":6,"progress":100}];
  ngOnInit(){
     let count=0;
     this.array.forEach((item, index) => {
     console.log(item.progress) ;
     count +=item.progress ;
});
     console.log(count);
  }

}

Body:
Change this line

count +=item.progress;

To

if (item.progress === 100) {count += 1;}


问:
Can't update php database with a flash application
I am having some problem here. I am trying to develop a flash database manager for my company, and I already have the insert and "search" functions working okay. The problem comes up when trying to get the UPDATE working. Ill post both codes here:

PHP (UPDATED)

```<code><?php
//connect to the local MySQL
$connect=mysql_connect("localhost", "****", "****");

//select your database
mysql_select_db("****");

//Variables
$ID=$_POST[IDPost];

$Nome=$_POST[Nome];
$Tipo=$_POST[Tipo];
$Empresa=$_POST[Empresa];
$Morada=$_POST[Morada];
$CodPostal=$_POST[CodPostal];
$Email=$_POST[Email];
$Contacto1=$_POST[Contacto1];
$Contacto2=$_POST[Contacto2];
$DataNascimento=$_POST[DataNascimento];
$Profissao=$_POST[Profissao];
$Notas1=$_POST[Notas1];
$Notas2=$_POST[Notas2];

//query the database
$query="

UPDATE
    GestaoClientes
SET
    Nome = '$Nome',
    Tipo = '$Tipo',
    Empresa = '$Empresa',
    Morada = '$Morada',
    CodPostal = '$CodPostal',
    Email = '$Email',
    Contacto1 = '$Contacto1',
    Contacto2 = '$Contacto2',
    DataNascimento = '$DataNascimento',
    Profissao = '$Profissao',
    Notas1 = '$Notas1',
    Notas2 = '$Notas2'
WHERE
    ID = '$ID'";

$result=mysql_query($query);

if (!mysql_query($query,$connect))
{
    die('Error: ' . mysql_error());
    echo "Result=NotOk";
}else{
    echo "Result=Ok";
}

mysql_close($connect);
?>
</code>```

Flash

```<code>public function editInfo(MouseEvent):void
        {
            var request:URLRequest = new URLRequest ("link.php");
                request.method = URLRequestMethod.POST;
                trace("called");

                var variables:URLVariables = new URLVariables();

                variables.IDPost = NField.text;

                variables.Nome = NomeField.text;
                variables.Email = NomeField.text;
                variables.Morada = MoradaField.text;
                variables.CodPostal = CodPostalField.text;
                variables.Tipo = TipoField.text;
                variables.Empresa = EmpresaField.text;
                variables.Profissao = ProfissaoField.text
                variables.DataNascimento = DataNascimentoField.text;
                variables.Notas1 = Notas1Field.text;
                variables.Notas2 = Notas2Field.text;

                request.data = variables;

                var loader:URLLoader = new URLLoader (request);
                loader.addEventListener(Event.COMPLETE, onComplete);
                loader.dataFormat = URLLoaderDataFormat.VARIABLES;
                loader.load(request);

            function onComplete(e:Event):void
            {
                trace("ok");
            }
</code>```

}

When I try going to the php in the browser if just gives me the error:

```<code>Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Nome' = '', 'Tipo' = '', 'Empresa' = '', 'Morada' = '', 'CodPostal' = '', 'Emai' at line 4
</code>```

This although is probably normal, since Im not passing any "POST" variables through the browser.

The flash doesent return any errors when trying this code, so I assume the connection itself is okay, but it doesent do the update either. Is there something wrong with this code? Thanks.

UPDATE: I now changed my code, and it does not show the syntax error, but still doesent update within the flash. Any ideias why? :/ thanks

答:
I suggest you take a close look at escaping your external input! Inserting variables directly into your query exposes you to injection, which is an enormous security issue. (read this).

the problem you have is that you use single quotes around the field names, this is incorrect.

MySQL uses backticks ( ` ), but I do not recommend using those since they limit portability to other sql applications.

Body:
I am having some problem here. I am trying to develop a flash database manager for my company, and I already have the insert and "search" functions working okay. The problem comes up when trying to get the UPDATE working. Ill post both codes here:

PHP (UPDATED)

<?php
//connect to the local MySQL
$connect=mysql_connect("localhost", "****", "****");

//select your database
mysql_select_db("****");

//Variables
$ID=$_POST[IDPost];

$Nome=$_POST[Nome];
$Tipo=$_POST[Tipo];
$Empresa=$_POST[Empresa];
$Morada=$_POST[Morada];
$CodPostal=$_POST[CodPostal];
$Email=$_POST[Email];
$Contacto1=$_POST[Contacto1];
$Contacto2=$_POST[Contacto2];
$DataNascimento=$_POST[DataNascimento];
$Profissao=$_POST[Profissao];
$Notas1=$_POST[Notas1];
$Notas2=$_POST[Notas2];

//query the database
$query="

UPDATE
    GestaoClientes
SET
    Nome = '$Nome',
    Tipo = '$Tipo',
    Empresa = '$Empresa',
    Morada = '$Morada',
    CodPostal = '$CodPostal',
    Email = '$Email',
    Contacto1 = '$Contacto1',
    Contacto2 = '$Contacto2',
    DataNascimento = '$DataNascimento',
    Profissao = '$Profissao',
    Notas1 = '$Notas1',
    Notas2 = '$Notas2'
WHERE
    ID = '$ID'";

$result=mysql_query($query);

if (!mysql_query($query,$connect))
{
    die('Error: ' . mysql_error());
    echo "Result=NotOk";
}else{
    echo "Result=Ok";
}

mysql_close($connect);
?>

Flash

public function editInfo(MouseEvent):void
        {
            var request:URLRequest = new URLRequest ("link.php");
                request.method = URLRequestMethod.POST;
                trace("called");

                var variables:URLVariables = new URLVariables();

                variables.IDPost = NField.text;

                variables.Nome = NomeField.text;
                variables.Email = NomeField.text;
                variables.Morada = MoradaField.text;
                variables.CodPostal = CodPostalField.text;
                variables.Tipo = TipoField.text;
                variables.Empresa = EmpresaField.text;
                variables.Profissao = ProfissaoField.text
                variables.DataNascimento = DataNascimentoField.text;
                variables.Notas1 = Notas1Field.text;
                variables.Notas2 = Notas2Field.text;

                request.data = variables;

                var loader:URLLoader = new URLLoader (request);
                loader.addEventListener(Event.COMPLETE, onComplete);
                loader.dataFormat = URLLoaderDataFormat.VARIABLES;
                loader.load(request);

            function onComplete(e:Event):void
            {
                trace("ok");
            }

}

When I try going to the php in the browser if just gives me the error:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Nome' = '', 'Tipo' = '', 'Empresa' = '', 'Morada' = '', 'CodPostal' = '', 'Emai' at line 4

This although is probably normal, since Im not passing any "POST" variables through the browser.

The flash doesent return any errors when trying this code, so I assume the connection itself is okay, but it doesent do the update either. Is there something wrong with this code? Thanks.

UPDATE: I now changed my code, and it does not show the syntax error, but still doesent update within the flash. Any ideias why? :/ thanks


问:
Whether the current Tensorflow Federated can be deployed across multiple physical machines?
I am wondering whether there is a way to run tff across multiple distributed physical devices (e.g., virtual machines). I haven’t figured out how to deploy this so far, and the tutorial shows this version is for simulation only.</p>

答: As of release 0.5.0 TFF only supports simulation.


问:
Cannot open (GPIO) Pin 6 in Windows 10 Iot Core
I want to let the red LED of my RainbowHAT shine. That requires that I send a high signal to the BCM 6 pin.

(Shortend) Source

Class constant:

```<code>private static readonly int GPIO_NUMBER_RED = 22;
</code>```

Called in the constructor:

```<code>    var gpioController = GpioController.GetDefault();

    redPin = gpioController.OpenPin(GPIO_NUMBER_RED);
    redPin.Write(GpioPinValue.High);
    redPin.SetDriveMode(GpioPinDriveMode.Output);
</code>```

I tried the values 6 (BCM), 31 (Pin number) and 22 (Wiring pin number) for my class global constant GPIO_NUMBER_RED but I get always the error:

```<code>    WinRT information: Pin ' is not available. It is reserved by the system or in use for another function.
</code>```

Pin layout

https://pinout.xyz/pinout/rainbow_hat

Full source

GitHub

Package Info

```<code>    <Capabilities>
        <Capability Name="internetClient" />
        <DeviceCapability Name="lowLevel"/>
    </Capabilities>
</code>```

I also restarted the Pi to "reset" maybe other application that access this Pin - without success.

答:
Solution #2

After @michaelxu-msft pointed out, that I miss used the Singelton pattern, I removed it and voila, now I can call the Init from my Constructor. I've to research why.

Body:
I want to let the red LED of my RainbowHAT shine. That requires that I send a high signal to the BCM 6 pin.

(Shortend) Source

Class constant:

private static readonly int GPIO_NUMBER_RED = 22;

Called in the constructor:

    var gpioController = GpioController.GetDefault();

    redPin = gpioController.OpenPin(GPIO_NUMBER_RED);
    redPin.Write(GpioPinValue.High);
    redPin.SetDriveMode(GpioPinDriveMode.Output);

I tried the values 6 (BCM), 31 (Pin number) and 22 (Wiring pin number) for my class global constant GPIO_NUMBER_RED but I get always the error:

    WinRT information: Pin ' is not available. It is reserved by the system or in use for another function.

Pin layout

https://pinout.xyz/pinout/rainbow_hat

Full source

GitHub

Package Info

    <Capabilities>
        <Capability Name="internetClient" />
        <DeviceCapability Name="lowLevel"/>
    </Capabilities>

I also restarted the Pi to "reset" maybe other application that access this Pin - without success.


问:
Vectorizable FIND function with if statement MATLAB
I have a matrix u, I want to go across all rows and all columns and do the following. If the element is non zero, I return the value of the row index. If the element is zero, find the row index the next non zero element after this element. I can do this easily using two for loops with a find function. But I need to do this many many times (not because of the size of the matrix but because this is called many times). How can I do it faster?

here is the for loop code:

```<code>     for w=scenario_size:-1:1
            for t=1:time_size
                l = u(t,w) ;
                if l~=0
                    tprime = t ;
                else
                    tprime = t+ find(u(t:end,w),1,'first') -1 ;
                end
                i(t,w)       = tprime ;
                boo(t,w)     = number(tprime,w)/u(tprime,w) ;
            end
end
</code>```

Example if one column is [0,0,5,1,0,3], the i is [3,3,3,4,6,6]. The last element of any column of u is always non-zero (I forced this by artificially adding a row of ones at the end).

Then boo is the corresponding entry to tprime for some matrix number divided by the corresponding u (which is non zero by construction).

答:
You can solve this using find, cummin, and some logical indexing. Starting with this example case:

```<code>>> u = randi([0 1], 10);
>> u(end, :) = 1

u =

     0     0     0     0     1     0     1     0     1     1
     1     0     1     1     1     0     0     0     0     1
     0     0     0     0     0     1     0     1     1     0
     1     1     1     0     1     1     0     0     0     0
     0     0     1     0     0     0     0     0     1     0
     1     1     1     0     0     0     0     0     0     0
     0     1     0     1     0     0     1     1     0     1
     1     1     0     1     0     1     1     1     1     1
     1     0     0     1     0     0     1     1     1     1
     1     1     1     1     1     1     1     1     1     1
</code>```

The following will do what you want:

```<code>i = nan(size(u));  % Start with all nan values
[r, ~] = find(u);  % Get row indices of non-zero values
i(u ~= 0) = r;     % Place row indices in locations of non-zero values
i = cummin(i, 1, 'reverse');  % Column-wise cumulative minimum, starting from bottom
</code>```

And the result:

```<code>i =

     2     4     2     2     1     3     1     3     1     1
     2     4     2     2     2     3     7     3     3     2
     4     4     4     7     4     3     7     3     3     7
     4     4     4     7     4     4     7     7     5     7
     6     6     5     7    10     8     7     7     5     7
     6     6     6     7    10     8     7     7     8     7
     8     7    10     7    10     8     7     7     8     7
     8     8    10     8    10     8     8     8     8     8
     9    10    10     9    10    10     9     9     9     9
    10    10    10    10    10    10    10    10    10    10
</code>```

And you can then calculate your matrix boo by converting i to a linear index:

```<code>index = i+time_size.*repmat(0:(scenario_size-1), time_size, 1);  % Create linear index
boo = number(index)./u(index);
</code>```

Alternatively, you can compute i as a linear index from the start:

```<code>i = nan(size(u));  % Start with all nan values
index = find(u);   % Get linear indices of non-zero values
i(index) = index;  % Place linear indices in locations of non-zero values
i = cummin(i, 1, 'reverse');  % Column-wise cumulative minimum, starting from bottom
boo = number(i)./u(i);
</code>```

Body:
I have a matrix u, I want to go across all rows and all columns and do the following. If the element is non zero, I return the value of the row index. If the element is zero, find the row index the next non zero element after this element. I can do this easily using two for loops with a find function. But I need to do this many many times (not because of the size of the matrix but because this is called many times). How can I do it faster?

here is the for loop code:

     for w=scenario_size:-1:1
            for t=1:time_size
                l = u(t,w) ;
                if l~=0
                    tprime = t ;
                else
                    tprime = t+ find(u(t:end,w),1,'first') -1 ;
                end
                i(t,w)       = tprime ;
                boo(t,w)     = number(tprime,w)/u(tprime,w) ;
            end
end

Example if one column is [0,0,5,1,0,3], the i is [3,3,3,4,6,6]. The last element of any column of u is always non-zero (I forced this by artificially adding a row of ones at the end).

Then boo is the corresponding entry to tprime for some matrix number divided by the corresponding u (which is non zero by construction).

Body:
You can solve this using find, cummin, and some logical indexing. Starting with this example case:

>> u = randi([0 1], 10);
>> u(end, :) = 1

u =

     0     0     0     0     1     0     1     0     1     1
     1     0     1     1     1     0     0     0     0     1
     0     0     0     0     0     1     0     1     1     0
     1     1     1     0     1     1     0     0     0     0
     0     0     1     0     0     0     0     0     1     0
     1     1     1     0     0     0     0     0     0     0
     0     1     0     1     0     0     1     1     0     1
     1     1     0     1     0     1     1     1     1     1
     1     0     0     1     0     0     1     1     1     1
     1     1     1     1     1     1     1     1     1     1

The following will do what you want:

i = nan(size(u));  % Start with all nan values
[r, ~] = find(u);  % Get row indices of non-zero values
i(u ~= 0) = r;     % Place row indices in locations of non-zero values
i = cummin(i, 1, 'reverse');  % Column-wise cumulative minimum, starting from bottom

And the result:

i =

     2     4     2     2     1     3     1     3     1     1
     2     4     2     2     2     3     7     3     3     2
     4     4     4     7     4     3     7     3     3     7
     4     4     4     7     4     4     7     7     5     7
     6     6     5     7    10     8     7     7     5     7
     6     6     6     7    10     8     7     7     8     7
     8     7    10     7    10     8     7     7     8     7
     8     8    10     8    10     8     8     8     8     8
     9    10    10     9    10    10     9     9     9     9
    10    10    10    10    10    10    10    10    10    10

And you can then calculate your matrix boo by converting i to a linear index:

index = i+time_size.*repmat(0:(scenario_size-1), time_size, 1);  % Create linear index
boo = number(index)./u(index);

Alternatively, you can compute i as a linear index from the start:

i = nan(size(u));  % Start with all nan values
index = find(u);   % Get linear indices of non-zero values
i(index) = index;  % Place linear indices in locations of non-zero values
i = cummin(i, 1, 'reverse');  % Column-wise cumulative minimum, starting from bottom
boo = number(i)./u(i);


问:
Equivalent Encryption for MCRYPT - To preserve client side code
I'm using the following code to perform encryption using mcrypt

```<code><?PHP

    define('SECURE_KEY','Somekey');

    function encrypt($value){
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv);
    }

    function decrypt($value){
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv));
    }
    $temp=encrypt("teststring");
    printf($temp);
    ?>
</code>```

The newer versions of php depreciates mcrypt,im looking for a replacement for the same that works with the same key and produces the same result,so that i dont need to change client side code.

答:
I'm the author of the RFC to deprecate then remove mcrypt from PHP.

What you should absolutely do is migrate your data to use the new Sodium extension instead. Learn how to get started with libsodium in PHP. The code examples are safe to use.

```<code><?php
/**
 * Wrap crypto_aead_*_encrypt() in a drop-dead-simple encryption interface
 *
 * @link https://paragonie.com/b/kIqqEWlp3VUOpRD7
 * @param string $message
 * @param string $key
 * @return string
 */
function simpleEncrypt($message, $key)
{
    $nonce = random_bytes(24); // NONCE = Number to be used ONCE, for each message
    $encrypted = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
        $message,
        $nonce,
        $nonce,
        $key
    );
    return $nonce . $encrypted;
}

/**
 * Wrap crypto_aead_*_decrypt() in a drop-dead-simple decryption interface
 *
 * @link https://paragonie.com/b/kIqqEWlp3VUOpRD7
 * @param string $message - Encrypted message
 * @param string $key     - Encryption key
 * @return string
 * @throws Exception
 */
function simpleDecrypt($message, $key)
{
    $nonce = mb_substr($message, 0, 24, '8bit');
    $ciphertext = mb_substr($message, 24, null, '8bit');
    $plaintext = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
        $ciphertext,
        $nonce,
        $nonce,
        $key
    );
    if (!is_string($plaintext)) {
        throw new Exception('Invalid message');
    }
    return $plaintext;
}

$secretKey = random_bytes(32);
$message = 'Test message';

/* Encrypt the message: */
$ciphertext = simpleEncrypt($message, $secretKey);

/* Decrypt the message: */
try {
    $decrypted = simpleDecrypt($ciphertext, $secretKey);
    var_dump(hash_equals($decrypted, $message));
    /* bool(true) */
} catch (Exception $ex) {
    /* Someone is up to no good */
    exit(255);
}
</code>```

If you need a "transition" step between PHP 7.1 and older, and PHP 7.2 and newer, mcrypt_compat is a polyfill library created by the phpseclib developers to facilitate migrations between mcrypt and non-abandonware libraries (OpenSSL, Sodium).

Only use it for migrations. Don't rely on it to "just work" and be secure.

Body:
I'm using the following code to perform encryption using mcrypt

<?PHP

    define('SECURE_KEY','Somekey');

    function encrypt($value){
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv);
    }

    function decrypt($value){
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv));
    }
    $temp=encrypt("teststring");
    printf($temp);
    ?>

The newer versions of php depreciates mcrypt,im looking for a replacement for the same that works with the same key and produces the same result,so that i dont need to change client side code.

Body:
I'm the author of the RFC to deprecate then remove mcrypt from PHP.

What you should absolutely do is migrate your data to use the new Sodium extension instead. Learn how to get started with libsodium in PHP. The code examples are safe to use.

<?php
/**
 * Wrap crypto_aead_*_encrypt() in a drop-dead-simple encryption interface
 *
 * @link https://paragonie.com/b/kIqqEWlp3VUOpRD7
 * @param string $message
 * @param string $key
 * @return string
 */
function simpleEncrypt($message, $key)
{
    $nonce = random_bytes(24); // NONCE = Number to be used ONCE, for each message
    $encrypted = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
        $message,
        $nonce,
        $nonce,
        $key
    );
    return $nonce . $encrypted;
}

/**
 * Wrap crypto_aead_*_decrypt() in a drop-dead-simple decryption interface
 *
 * @link https://paragonie.com/b/kIqqEWlp3VUOpRD7
 * @param string $message - Encrypted message
 * @param string $key     - Encryption key
 * @return string
 * @throws Exception
 */
function simpleDecrypt($message, $key)
{
    $nonce = mb_substr($message, 0, 24, '8bit');
    $ciphertext = mb_substr($message, 24, null, '8bit');
    $plaintext = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
        $ciphertext,
        $nonce,
        $nonce,
        $key
    );
    if (!is_string($plaintext)) {
        throw new Exception('Invalid message');
    }
    return $plaintext;
}

$secretKey = random_bytes(32);
$message = 'Test message';

/* Encrypt the message: */
$ciphertext = simpleEncrypt($message, $secretKey);

/* Decrypt the message: */
try {
    $decrypted = simpleDecrypt($ciphertext, $secretKey);
    var_dump(hash_equals($decrypted, $message));
    /* bool(true) */
} catch (Exception $ex) {
    /* Someone is up to no good */
    exit(255);
}

If you need a "transition" step between PHP 7.1 and older, and PHP 7.2 and newer, mcrypt_compat is a polyfill library created by the phpseclib developers to facilitate migrations between mcrypt and non-abandonware libraries (OpenSSL, Sodium).

Only use it for migrations. Don't rely on it to "just work" and be secure.


答:
Try like this:

```<code>progressCount:number = 0;
completedCount:number = 0;

ngOnInit() {
this.array.forEach(item => {
  if (item.progress < 100) {
    this.progressCount ++;
  } else {
    this.completedCount ++;
  }
});
}
</code>```

HTML:

```<code><div>Progress : 2{{progressCount}}</div><div>completed : 2{{completedCount}}</div>
</code>```

Title: Angular 6 how to get count of the particular column based on same value from an array of object

Body:
Try like this:

progressCount:number = 0;
completedCount:number = 0;

ngOnInit() {
this.array.forEach(item => {
  if (item.progress < 100) {
    this.progressCount ++;
  } else {
    this.completedCount ++;
  }
});
}

HTML:

<div>Progress : 2{{progressCount}}</div><div>completed : 2{{completedCount}}</div>