问:
array values with where condition in laravel query
I have an array called assetIDs as below

```<code>$assetIDs = Collection {#505 ▼
  #items: array:2 [▼
    0 => 4
    1 => 7
  ]
}
</code>```

and I have the data in the table as below shown

and I'm doing query on the above table using this

$supplier_id = SupplierAsset::whereIn('asset_id',$asset_ids)->pluck('supplier_id');

and result for the above query is below

```<code>Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
    2 => 2
  ]
}
</code>```

here whereIn is returning all the possible rows which satisfies the condition. Actually I need to get the result as like which supplier_id has both the values of assetIDs array.In my table supplier_id=1 has the both values 4 and 7 Just like below collection.

```<code>Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
  ]
}
</code>```

Can anybody suggest me the solution for this please?

答:
You can try:</p>

```<code>$supplier_id = SupplierAsset::whereIn('asset_id',$asset_ids)
               ->groupBy('supplier_id')
               ->havingRaw('count(distinct asset_id) = ' . count($assetIDs))
               ->pluck('supplier_id');
</code>```

Body:
I have an array called assetIDs as below

$assetIDs = Collection {#505 ▼
  #items: array:2 [▼
    0 => 4
    1 => 7
  ]
}

and I have the data in the table as below shown

and I'm doing query on the above table using this

$supplier_id = SupplierAsset::whereIn('asset_id',$asset_ids)->pluck('supplier_id');

and result for the above query is below

Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
    2 => 2
  ]
}

here whereIn is returning all the possible rows which satisfies the condition. Actually I need to get the result as like which supplier_id has both the values of assetIDs array.In my table supplier_id=1 has the both values 4 and 7 Just like below collection.

Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
  ]
}

Can anybody suggest me the solution for this please?

Body:
You can try:

$supplier_id = SupplierAsset::whereIn('asset_id',$asset_ids)
               ->groupBy('supplier_id')
               ->havingRaw('count(distinct asset_id) = ' . count($assetIDs))
               ->pluck('supplier_id');


来源: stackexchange

问:
Java-Swing: A problem using layout managers!
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

```<code>scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();
</code>```

答: I just want to tell that I share the same opinion as javamonkey79. Take a look at MigLayout, you'll love it, and from Java 7 on it will be standart java-onboard layout.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();


问:
Is it possible to see the source code of oracle inbuilt function
I am trying to see the source code of oracle inbuilt functions. I am doing this because i want to see how oracle implements its own functions. After doing a bit of research online i found that i can see function of standard package in the file
"stdspec.sql" and "stdbody.sql". I looked for inbuilt function "LIKE" and found
the below code:

```<code> function 'LIKE' (str VARCHAR2 CHARACTER SET ANY_CS,
                   pat VARCHAR2 CHARACTER SET str%CHARSET)
        return BOOLEAN;
</code>```

I want to see the implementation of this functions. So is it possible to see that? If yes can somebody please help me to achieve that.

答:
No, you can't see the code of the built-in SQL functions. That is compiled into the Oracle binary. And as Oracle is not an open source database, you can't get access to Oracle's source code.

You can't even see the code of most of the Oracle provided PL/SQL procedures and packages as they have been encrypted.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to see the source code of oracle inbuilt functions. I am doing this because i want to see how oracle implements its own functions. After doing a bit of research online i found that i can see function of standard package in the file
"stdspec.sql" and "stdbody.sql". I looked for inbuilt function "LIKE" and found
the below code:

 function 'LIKE' (str VARCHAR2 CHARACTER SET ANY_CS,
                   pat VARCHAR2 CHARACTER SET str%CHARSET)
        return BOOLEAN;

I want to see the implementation of this functions. So is it possible to see that? If yes can somebody please help me to achieve that.


问:
backbonejs function is is not defined
I am encountering a function is not defined .

I getting key value pairs and executing function on forEach.

the structure

```<code>var AppView = Backbone.View.extend({
  initialize: function() {
    this.render();
  },
  render: function() {
    this.$el.html("Hello World");
    this.one();
  },
  one: function() {
    this.two();
  },
  two: function() {
    var object = {
      "labname4": "423",
      "Path": "4",
      "X": "4"
    };
    console.log('two');

    Object.keys(object).map(function(objectKey, index) {
      var value = object[objectKey];
      this.three();
    });
  },
  three: function() {
    console.log('three');
  },
});

var appView = new AppView();
console.log("done");
</code>```

Using:

jquery/1.7.2

underscore.js/1.3.3

backbone.js/0.9.2

答:
This is a common mistake when using nested functions like:

```<code>Object.keys(object).map(function(objectKey, index) {
            var value = object[objectKey];
            this.three();
        });
</code>```

Here this.three(), this doesn't refer to your object anymore since it's within a nested functions scope and method three() isn't defined on it.

There are 2 possible solutions:

a) Instead of a nested function use a clojure. You can write the identical code like:

```<code>Object.keys(object).map((objectKey, index) => { // note the arrow and no 'function' keyword
            var value = object[objectKey];
            this.three();
        });
</code>```

The clojure stays within the current scope so this.three() will work, function on the other hand defines it's own scope.

b) You can bind function if you want it to execute in a specific scope like:

```<code>Object.keys(object).map(function(objectKey, index) {
            var value = object[objectKey];
            this.three();
        }.bind(this)); // note '.bind(this)'
</code>```

This way the function will use your current scope rather then making a new one.
Both approaches are valid and it's up to the user to pick one, I personally prefer clojures.

Title: backbonejs function is is not defined

Body:
I am encountering a function is not defined .

I getting key value pairs and executing function on forEach.

the structure

var AppView = Backbone.View.extend({
  initialize: function() {
    this.render();
  },
  render: function() {
    this.$el.html("Hello World");
    this.one();
  },
  one: function() {
    this.two();
  },
  two: function() {
    var object = {
      "labname4": "423",
      "Path": "4",
      "X": "4"
    };
    console.log('two');

    Object.keys(object).map(function(objectKey, index) {
      var value = object[objectKey];
      this.three();
    });
  },
  three: function() {
    console.log('three');
  },
});

var appView = new AppView();
console.log("done");

Using:

jquery/1.7.2

underscore.js/1.3.3

backbone.js/0.9.2

Body:
This is a common mistake when using nested functions like:

Object.keys(object).map(function(objectKey, index) {
            var value = object[objectKey];
            this.three();
        });

Here this.three(), this doesn't refer to your object anymore since it's within a nested functions scope and method three() isn't defined on it.

There are 2 possible solutions:

a) Instead of a nested function use a clojure. You can write the identical code like:

Object.keys(object).map((objectKey, index) => { // note the arrow and no 'function' keyword
            var value = object[objectKey];
            this.three();
        });

The clojure stays within the current scope so this.three() will work, function on the other hand defines it's own scope.

b) You can bind function if you want it to execute in a specific scope like:

Object.keys(object).map(function(objectKey, index) {
            var value = object[objectKey];
            this.three();
        }.bind(this)); // note '.bind(this)'

This way the function will use your current scope rather then making a new one.
Both approaches are valid and it's up to the user to pick one, I personally prefer clojures.


问:
How to filter an array in MS Access
I am writing an array which can compare with my database(query). May I know how can I make it so it can include a "Or" logic within my array? Because I would like to get the output like Filter = myArray(0) Or myArray(1) Or myArray(2) ... Since I don't have the number of my array because it is depends on how many inputs did the user type, so I just have a myArray(x).
Thank you.

```<code>Private Sub TestButton_Click()
Dim myArray As Variant
Dim Status_Input As Variant
Dim x As Variant
Dim i As Variant
Dim Status_Filter As Variant

Status_Input = Forms![try2].StatusInput

myArray = Split(Status_Input, ";")

For x = LBound(myArray) To UBound(myArray)
MsgBox " " & myArray(x) & " "             'MsgBox = 03 20 27 (3 MsgBoxes)

Status_Filter = _
"[Status] Like " & myArray(x)

Debug.Print Status_Filter
Me.Filter = Status_Filter
Me.FilterOn = True

Next x
</code>```

End Sub

答:
You can just append filters to eachother, separating them with OR. Also, I recommend you use Like only when you need to use wildcards.

If you don't use Like, you can optimize the code by using [Status] IN(1, 2, 3) instead of [Status] Like 1 OR [Status] Like 2 OR [Status] Like 3.

```<code>Status_Filter = "[Status] Like " & myArray(LBound(myArray)) 'Note: fails if myArray is empty
For x = LBound(myArray) + 1 To UBound(myArray)
    Status_Filter = Status_Filter & " OR [Status] Like " & myArray(x)
Next x
Me.Filter = Status_Filter
Me.FilterOn = True
</code>```

Title: How to filter an array in MS Access

Body:
I am writing an array which can compare with my database(query). May I know how can I make it so it can include a "Or" logic within my array? Because I would like to get the output like Filter = myArray(0) Or myArray(1) Or myArray(2) ... Since I don't have the number of my array because it is depends on how many inputs did the user type, so I just have a myArray(x).
Thank you.

Private Sub TestButton_Click()
Dim myArray As Variant
Dim Status_Input As Variant
Dim x As Variant
Dim i As Variant
Dim Status_Filter As Variant

Status_Input = Forms![try2].StatusInput

myArray = Split(Status_Input, ";")

For x = LBound(myArray) To UBound(myArray)
MsgBox " " & myArray(x) & " "             'MsgBox = 03 20 27 (3 MsgBoxes)

Status_Filter = _
"[Status] Like " & myArray(x)

Debug.Print Status_Filter
Me.Filter = Status_Filter
Me.FilterOn = True

Next x

End Sub

Body:
You can just append filters to eachother, separating them with OR. Also, I recommend you use Like only when you need to use wildcards.

If you don't use Like, you can optimize the code by using [Status] IN(1, 2, 3) instead of [Status] Like 1 OR [Status] Like 2 OR [Status] Like 3.

Status_Filter = "[Status] Like " & myArray(LBound(myArray)) 'Note: fails if myArray is empty
For x = LBound(myArray) + 1 To UBound(myArray)
    Status_Filter = Status_Filter & " OR [Status] Like " & myArray(x)
Next x
Me.Filter = Status_Filter
Me.FilterOn = True


问:
SQL code runs manually but not in job
I am using this code in a automated job , job got failed once it comes on this code but if I run this manually it works perfect.  Is there any  other way to write this or is there any error.

```<code>UPDATE ABC_FACT
SET ID =  CASE WHEN (PRODUCT_NAME LIKE '%ETH LE%' or PRODUCT_NAME LIKE '% SOUND %' OR PRODUCT_NAME LIKE '%NET REV%' or PRODUCT_NAME LIKE '%ETHERNET SPOKE%')
THEN ORDER_NO + (SUBSTRING(ORDER,1,CHARINDEX('/',ORDER)-1)) + C_TYPE
ELSE ORDER_NO + ORDER + C_TYPE END
WHERE FLAG LIKE 'ABC%'
</code>```

Please help on this.

答:
Try This

```<code>UPDATE ABC_FACT
SET ID =  CASE WHEN (PRODUCT_NAME LIKE '%ETH LE%' or PRODUCT_NAME LIKE '% SOUND %' OR PRODUCT_NAME LIKE '%NET REV%' or PRODUCT_NAME LIKE '%ETHERNET SPOKE%')
THEN ORDER_NO + (SUBSTRING([ORDER],1,CHARINDEX('/',[ORDER])-1)) + C_TYPE
ELSE ORDER_NO + [ORDER] + C_TYPE END
WHERE FLAG LIKE 'ABC%'
</code>```

Order is reserved word in SQL, whenever use reserved word as a column use [], but I recommend don't use reserved words as columns name, you can use it like _ before or with other combination of words

for list of SQL Server Reserved Words please visit https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql

Title: SQL code runs manually but not in job

Body:
I am using this code in a automated job , job got failed once it comes on this code but if I run this manually it works perfect.  Is there any  other way to write this or is there any error.

UPDATE ABC_FACT
SET ID =  CASE WHEN (PRODUCT_NAME LIKE '%ETH LE%' or PRODUCT_NAME LIKE '% SOUND %' OR PRODUCT_NAME LIKE '%NET REV%' or PRODUCT_NAME LIKE '%ETHERNET SPOKE%')
THEN ORDER_NO + (SUBSTRING(ORDER,1,CHARINDEX('/',ORDER)-1)) + C_TYPE
ELSE ORDER_NO + ORDER + C_TYPE END
WHERE FLAG LIKE 'ABC%'

Please help on this.

Body:
Try This

UPDATE ABC_FACT
SET ID =  CASE WHEN (PRODUCT_NAME LIKE '%ETH LE%' or PRODUCT_NAME LIKE '% SOUND %' OR PRODUCT_NAME LIKE '%NET REV%' or PRODUCT_NAME LIKE '%ETHERNET SPOKE%')
THEN ORDER_NO + (SUBSTRING([ORDER],1,CHARINDEX('/',[ORDER])-1)) + C_TYPE
ELSE ORDER_NO + [ORDER] + C_TYPE END
WHERE FLAG LIKE 'ABC%'

Order is reserved word in SQL, whenever use reserved word as a column use [], but I recommend don't use reserved words as columns name, you can use it like _ before or with other combination of words

for list of SQL Server Reserved Words please visit https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql


问:
JNI4Net, capturing java events from c#
Where I work we are using jni, to be able to run in our application (implemented in c#) a graphical viewer that is implemented in Java. To do this we use JNI and it works correctly, the problem is that now we want to capture the events that occur in this Java viewer and launch a c# method when the event occurs. It is possible to do this with JNI. I've tried using RegisterNatives () but I can't get it to work.

The code that I found on the internet is for C++ and Open JDK, we use C# and Jdk1.8.

Example of code(From stackOverflow):

```<code>static JNINativeMethod methods[] = {
{"hashCode",    "()I",                    (void *)&JVM_IHashCode},
{"wait",        "(J)V",                   (void *)&JVM_MonitorWait},
{"notify",      "()V",                    (void *)&JVM_MonitorNotify},
{"notifyAll",   "()V",                    (void *)&JVM_MonitorNotifyAll},
{"clone",       "()Ljava/lang/Object;",   (void *)&JVM_Clone},
};

JNIEXPORT void JNICALL
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
(*env)->RegisterNatives(env, cls,
                        methods, sizeof(methods)/sizeof(methods[0]));
}
</code>```

Neither Java_java_lang_Object_registerNatives, JNIEXPORT void JNICALL, nor the function pointer (void *)&JVM_IHashCode does not work as they do not know what functions are called in jdk1.8

Does anyone know if there's any way to get this?

答:
Disclaimer I completely didn't get your approach with registering natives, so maybe I understand you requirements wrong.

I see two options for you.

You can create java entry point

Here is example:

```<code>class MyEntryPoint {
    public static List<Runnable> list = new ArrayList<>();

    public void fire() {
        list.forEach(Runnable::run);
    }
    public void addListener(Runnable listener) {
        list.add(listener);
    }
}
</code>```

Then you access from .Net to this static class via JNI and add listener. Java app notify about all useful event. You should replace Runnable with appropriate interface.

Most difficult part is implement interface in C#.

Create tcp server in your Java app and connect to it from .Net.

Title: JNI4Net, capturing java events from c#

Body:
Where I work we are using jni, to be able to run in our application (implemented in c#) a graphical viewer that is implemented in Java. To do this we use JNI and it works correctly, the problem is that now we want to capture the events that occur in this Java viewer and launch a c# method when the event occurs. It is possible to do this with JNI. I've tried using RegisterNatives () but I can't get it to work.

The code that I found on the internet is for C++ and Open JDK, we use C# and Jdk1.8.

Example of code(From stackOverflow):

static JNINativeMethod methods[] = {
{"hashCode",    "()I",                    (void *)&JVM_IHashCode},
{"wait",        "(J)V",                   (void *)&JVM_MonitorWait},
{"notify",      "()V",                    (void *)&JVM_MonitorNotify},
{"notifyAll",   "()V",                    (void *)&JVM_MonitorNotifyAll},
{"clone",       "()Ljava/lang/Object;",   (void *)&JVM_Clone},
};

JNIEXPORT void JNICALL
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
(*env)->RegisterNatives(env, cls,
                        methods, sizeof(methods)/sizeof(methods[0]));
}

Neither Java_java_lang_Object_registerNatives, JNIEXPORT void JNICALL, nor the function pointer (void *)&JVM_IHashCode does not work as they do not know what functions are called in jdk1.8

Does anyone know if there's any way to get this?

Body:
Disclaimer I completely didn't get your approach with registering natives, so maybe I understand you requirements wrong.

I see two options for you.

You can create java entry point

Here is example:

class MyEntryPoint {
    public static List<Runnable> list = new ArrayList<>();

    public void fire() {
        list.forEach(Runnable::run);
    }
    public void addListener(Runnable listener) {
        list.add(listener);
    }
}

Then you access from .Net to this static class via JNI and add listener. Java app notify about all useful event. You should replace Runnable with appropriate interface.

Most difficult part is implement interface in C#.

Create tcp server in your Java app and connect to it from .Net.


问:
What is the difference between an expression and a statement in Python?
In Python, what is the difference between expressions and statements?</p>

答:
Though this isn't related to Python:

An expression evaluates to a value.
A statement does something.

```<code>>>> x + 2         # an expression
>>> x = 1         # a statement
>>> y = x + 1     # a statement
>>> print y       # a statement (in 2.x)
2
</code>```

Body:
Though this isn't related to Python:

An expression evaluates to a value.
A statement does something.

>>> x + 2         # an expression
>>> x = 1         # a statement
>>> y = x + 1     # a statement
>>> print y       # a statement (in 2.x)
2

ContentLicense: CC BY-SA 4.0


问:
how to iterate throught an array of objects and concate the contents
I have the object (obj1) that is posted below. As shown  in it, it contains an array of objects called "favoritePlayers".

what I am trying to do is, to create a function or add an array prototype so that I can iterate through each element in the array separately and get the following output:

"messi plays in barcelona"
"totti plays in roma"

I tried to solve it as shown below but what I get is

```<code>[ 'undefinedplays in[object Object]',
'undefinedplays in[object Object]' ]
</code>```

obj1:

```<code>var obj1 = {
score: [10, 22, 30, 55, 70, 90],
lettersOfMyName: ["a", "m", "r"],
avgScore: null,
favoritePlayers: [
    {
        name: "messi",
        club: "barcelona"
    },

    {
        name: "totti",
        club: "roma"
    }
],

calcAvgScore: function () {
    var sumOfScores = this.score.reduce(function (prev, cur, index, array)
{

        return prev + cur;

    })

    return (sumOfScores / this.score.length);
},

myFavoritePlayersInfo: function () {
    console.log(this.favoritePlayers.join());
},

}
</code>```

my attempts:
    //this code was added outside the scope of obj1

```<code>Array.prototype.concat1 = ( (array) => {
var tempArray = [];

for (var i = 0; i < array.length; i++) {

tempArray[i] = array.slice(i, i+1).name + "plays in" + array.slice(i,
i+1);

}

return tempArray;

});
</code>```

update_1

I added the following lines to obj1:

```<code>getPlaysIn:function() {
    this.favoritePlayers.forEach( (favoritePlayer)=> {
        return favoritePlayer.name + " plays in " + favoritePlayer.club;
</code>```

and I call it as follows:

```<code>console.log(obj1.getPlaysIn());
</code>```

but the results i get is

```<code>undefined
</code>```

答:
Iterate through the object and return it the way you see fit.</p>

```<code>let playerInfo = obj1.favoritePlayers.map(playerObj => {
   return playerObj["name"] + "plays for " + playerObj["club"];
});
</code>```

Body:
I have the object (obj1) that is posted below. As shown  in it, it contains an array of objects called "favoritePlayers".

what I am trying to do is, to create a function or add an array prototype so that I can iterate through each element in the array separately and get the following output:

"messi plays in barcelona"
"totti plays in roma"

I tried to solve it as shown below but what I get is

[ 'undefinedplays in[object Object]',
'undefinedplays in[object Object]' ]

obj1:

var obj1 = {
score: [10, 22, 30, 55, 70, 90],
lettersOfMyName: ["a", "m", "r"],
avgScore: null,
favoritePlayers: [
    {
        name: "messi",
        club: "barcelona"
    },

    {
        name: "totti",
        club: "roma"
    }
],

calcAvgScore: function () {
    var sumOfScores = this.score.reduce(function (prev, cur, index, array)
{

        return prev + cur;

    })

    return (sumOfScores / this.score.length);
},

myFavoritePlayersInfo: function () {
    console.log(this.favoritePlayers.join());
},

}

my attempts:
    //this code was added outside the scope of obj1

Array.prototype.concat1 = ( (array) => {
var tempArray = [];

for (var i = 0; i < array.length; i++) {

tempArray[i] = array.slice(i, i+1).name + "plays in" + array.slice(i,
i+1);

}

return tempArray;

});

update_1

I added the following lines to obj1:

getPlaysIn:function() {
    this.favoritePlayers.forEach( (favoritePlayer)=> {
        return favoritePlayer.name + " plays in " + favoritePlayer.club;

and I call it as follows:

console.log(obj1.getPlaysIn());

but the results i get is

undefined

Body:
Iterate through the object and return it the way you see fit.

let playerInfo = obj1.favoritePlayers.map(playerObj => {
   return playerObj["name"] + "plays for " + playerObj["club"];
});


问:
Confluent platform - basic commands need sudo?
I am trying out the open sourced Confluent platform in AWS linux server running (centOS 7.x). After doing a yum install on the oss (open source version) version as root, it was quite straight forward to start the services with

```<code>confluent start
</code>```

command.

The question I have is - when I log into same server as non-root user and I try to execute below command it returns all services are down.

```<code>confluent status
</code>```

If I execute the same with sudo access, it shows all services are up and running. Why does the basic confluent cli commands need sudo access?

If I start the services as root, shouldn't all users be able to see that the services are up and running without sudo?

答:
Confluent CLI uses a tmp folder, so my guess is that your two users (root and your own) are getting different tmp environments, and thus when it tries to determine if the stack is up or not, it does so in the scope of that tmp environment.

You can force it to use a single env by setting the environment variable CONFLUENT_CURRENT before invoking the confluent script. E.g. export CONFLUENT_CURRENT=/Users/Robin/cp/confluent-3.3.0/tmp/

https://github.com/confluentinc/confluent-cli/issues/40 / https://github.com/confluentinc/confluent-cli reference this behaviour

Body:
I am trying out the open sourced Confluent platform in AWS linux server running (centOS 7.x). After doing a yum install on the oss (open source version) version as root, it was quite straight forward to start the services with

confluent start

command.

The question I have is - when I log into same server as non-root user and I try to execute below command it returns all services are down.

confluent status

If I execute the same with sudo access, it shows all services are up and running. Why does the basic confluent cli commands need sudo access?

If I start the services as root, shouldn't all users be able to see that the services are up and running without sudo?


问:
Thousand separator while typing and decimal (with comma)
I have a problem.

```<code>        $('#value-salary').on('keyup', function(){
            if($(this).val() != ""){
                var n = parseInt($(this).val().replace(/\D/g,''),10);
                $(this).val(n.toLocaleString());
            }
        });
</code>```

This allow me to see "." as thousand separator while typing. Before submit I will replace "." with "" and for now it's all ok.

The problem is that the keyup doesn't allow me to insert "," and I need to use this as decimal separator (before sending i will replace , with . but user is not interested in rest api. He want to see "," as decimal separator).

How can i fix this problem? Keypress or keydown are not good solutions...thanks!

答:
you can use autoNumeric.js.

$(".testInput").autoNumeric('init', {
    aSep: '.',
    aDec: ',',
    aForm: true,
    vMax: '999999999',
    vMin: '-999999999'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="testInput" type="text" value="8000"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autonumeric/1.8.2/autoNumeric.js"></script></code>```

please see more information how to use numeric.

http://www.decorplanit.com/plugin/

Body:
I have a problem.

        $('#value-salary').on('keyup', function(){
            if($(this).val() != ""){
                var n = parseInt($(this).val().replace(/\D/g,''),10);
                $(this).val(n.toLocaleString());
            }
        });

This allow me to see "." as thousand separator while typing. Before submit I will replace "." with "" and for now it's all ok.

The problem is that the keyup doesn't allow me to insert "," and I need to use this as decimal separator (before sending i will replace , with . but user is not interested in rest api. He want to see "," as decimal separator).

How can i fix this problem? Keypress or keydown are not good solutions...thanks!

Body:
you can use autoNumeric.js.

$(".testInput").autoNumeric('init', {
    aSep: '.',
    aDec: ',',
    aForm: true,
    vMax: '999999999',
    vMin: '-999999999'
});

<input class="testInput" type="text" value="8000"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autonumeric/1.8.2/autoNumeric.js"></script>

please see more information how to use numeric.

http://www.decorplanit.com/plugin/


问:
getting a stringArray resource with a string variable
I am trying to get a stringArray resource with this code:

```<code>String continent = "europe";
getResources().getStringArray(R.array.continent);
</code>```

If I type R.array.europe, its ok, but I want this to be dynamic, so I'm looking for a way to use my string variable here..

This is probably a simple java problem, but I'm quite a noob both in java and android programming, and I didn't find the answer..

Thanks in advance;

edit: so here is my complete onCreate Method, did I do something wrong?

```<code>protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
       String continent = (String) getIntent().getExtras().getString("continent");

       int holderint = getResources().getIdentifier(continent, "Array",
               this.getPackageName());

       String[] items = getResources().getStringArray(holderint);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                items));

    }
</code>```

I'm not sure about the defPackage part though...

答:
You can get the array resource id using this :</p>

```<code>Sting name = "resource_array_name";
int resourceId= getResources().getIdentifier(name, "array",this.getPackageName());
String[] items = getResources().getStringArray(resourceId);
</code>```

Body:
I am trying to get a stringArray resource with this code:

String continent = "europe";
getResources().getStringArray(R.array.continent);

If I type R.array.europe, its ok, but I want this to be dynamic, so I'm looking for a way to use my string variable here..

This is probably a simple java problem, but I'm quite a noob both in java and android programming, and I didn't find the answer..

Thanks in advance;

edit: so here is my complete onCreate Method, did I do something wrong?

protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
       String continent = (String) getIntent().getExtras().getString("continent");

       int holderint = getResources().getIdentifier(continent, "Array",
               this.getPackageName());

       String[] items = getResources().getStringArray(holderint);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                items));

    }

I'm not sure about the defPackage part though...

Body:
You can get the array resource id using this :

Sting name = "resource_array_name";
int resourceId= getResources().getIdentifier(name, "array",this.getPackageName());
String[] items = getResources().getStringArray(resourceId);


问:
Implementing Queue Using LinkedList
So, i'm attempting to implement this Queue using my LinkedList that I previously created. I've provided the code for both classes. Currently, I'm work on attempting to get pop and push to work without changing the function prototype (it's for an assignment).

When looking specifically at peek(I haven't quite finished pop), for some reason, when I run the code, I get strange pointer error.

Error   C2440   'default argument': cannot convert from 'int' to 'int &'

I'm not sure exactly what that means in this context. The function is suppose to look at the object at the top of the queue without removing it, and return true or false based upon if the operation was successful or not.

Here is the info for QUEUE.

```<code>  #ifndef _QUEUE_H
#define _QUEUE_H 1

#include "QueueInterface.h"
#include "LinkedList.hpp"

template <typename T>
class Queue : public QueueInterface<T>
{
protected:
    LinkedList<T> _list;
    int count;

public:

    unsigned size() const
    {
        return count;
    }

    bool push(const T& val = T{})
    {
        _list.push(val);
        count++;
        return true;
    }

    bool empty() const
    {
        return _list.isEmpty();
    }

    bool pop(T& val = T{})
    {
        return true;
    }

    bool peek(T& val = T{}) const
    {
        std::cout << _list.last() << std::endl;
        return true;

    }

    void clear()
    {
        _list.clear();
    }

    int search(const T& target = T{}) const
    {
        return _list.search(target);
    }
    //
    // Internal consistency check
    //

    void toString()
    {
        _list.toString();
    }

public:
    virtual bool check() const
    {
        return _list.check();
    }
};

#endif
</code>```

Here is Linked List.

```<code>#ifndef _LINKED_LIST_GUARD
#define _LINKED_LIST_GUARD 1

#include <iostream>

#include "ListInterface.h"

template <typename T>
class LinkedList : public ListInterface<T>
{
public:

    int count = 0;

    LinkedList()
    {
        _head = new Node;
        _tail = new Node;

        _head->_next = _tail;
    }

private:

    //
    // Private node class to facilitate linked list
    //
    class Node
    {
    public:
        T _data;
        Node* _next;

        // Constructor: default
        Node(T d = T{}, Node* n = nullptr) : _data(d), _next(n) {}

        ~Node() { _next = nullptr; }
    };

    //
    // Prevent copying and assigning
    //
    LinkedList(const LinkedList& rhs) {}
    const LinkedList& operator=(const LinkedList& rhs) {}

public:
    //
    // LinkedList instance variables; we use dummy head and tail nodes in this implementation

    unsigned _size;
    Node* _head;
    Node* _tail;

    // Returns the first element in the list
    T& first() const
    {
        return _head->_next->_data;
    }

    // Adds an item to the LEFT side of the linked list
    void push(const T& x)
    {
        // Creates a new node with the user input data.
            Node* current = new Node;
            current->_data = x;

            current->_next = _head->_next;
            _head->_next = current;

            count++;

    }

    // ASK ABOUT
    T& operator[](unsigned n)
    {
        int position = 1;

        if (n != count)
        {
            throw("Invalid Position");
        }

        for (Node* current = _head->_next; current != _tail; current = current->_next, position++)
        {
            if (position == n)
            {
                return current -> _data;
            }
        }

    }

    void clear()
    {
        do
        {
            pop();
        } while (count != 0);

    }

    bool contains(const T& target) const
    {
        for (Node* current = _head->_next; current != _tail; current = current->_next)
        {
            if (current->_data == target)
                return true;
        }
        return false;
    }

    bool pop()
    {
        if (_head->_next == _tail)
        {
            std::cout << "unable to pop, list is empty";
            return false;
        }

        if (_head->_next != _tail)
        {
            Node* deleteNode = _head->_next;
            _head->_next = _head->_next->_next;
            delete deleteNode;
            count--;
            return true;
        }
        return false;
    }

    T& last() const
    {
        if (_head->_next == _tail)
        {
            std::cout << "LIST IS EMPTY" << std::endl;
        }

        if (_head->_next != _tail)
        {
            for (Node* current = _head->_next; current != _tail; current = current->_next)
            {
                if (current->_next == _tail)
                    return current->_data;
            }
        }
    }

    // ASK ABOUT
    int search(const T& target = T{}) const
    {
        int position = 1;
        for (Node* current = _head->_next; current != _tail; current = current->_next)
        {
            if (current->_data == target)
            {
                return position;
            }
            else  position++;
        }
        return -1;

    }

    bool isEmpty() const
    {
        if (_head->_next == _tail)
        {
            return true;
        }
        return false;
    }

    unsigned size() const
    {

        return count;
    }

    bool remove(const T& target)
    {
        Node* deleteNode = nullptr;
        Node* trailer = _head;
        Node* current = _head->_next;

        while (current != _tail && current-> _data != target)
        {
            trailer = current;
            current = current->_next;
        }

        if (current->_data == target)
        {
            deleteNode = current;
            current = current->_next;
            trailer->_next = current;

            delete deleteNode;
            count--;
            return true;
        }
        else
            std::cout << "unable to remove, item not in list" << std::endl;
        return false;

    }

    //FOR TESTING
    void toString()
    {
        for (Node* current = _head->_next; current != _tail; current = current->_next)
        {
            std::cout << current->_data << std::endl;
        }
    }

    //
    // Internal consistency check
    //
public:
    virtual bool check() const
    {
        bool sizeConsistent = isSizeConsistent();
        bool headTailConsistent = isEndConsistent();

        if (!sizeConsistent) std::cerr << "Size inconsistent" << std::endl;
        if (!headTailConsistent) std::cerr << "Head / Tail inconsistent" << std::endl;

        return sizeConsistent && headTailConsistent;
    }

    //
    // Stated size is accurate to the entire list
    //
    bool isSizeConsistent() const
    {
        int count = 0;
        for (Node* current = _head->_next; current != _tail; current = current->_next)
        {
            count++;
        }

        return size() == count;
    }

    //
    // Checks that the head and tail are defaulted properly and the
    // respective next pointers are appropriate.
    //
    bool isEndConsistent() const
    {
        if (_head->_data != T{}) return false;

        if (_tail->_data != T{}) return false;

        if (_head->_next == nullptr) return false;

        if (_tail->_next != nullptr) return false;

        if (isEmpty() && _head->_next != _tail) return false;

        if (!isEmpty() && _head->_next == _tail) return false;

        return true;
    }
};

#endif
</code>```

And finally, here is my main. The top portion is to test the functionality for LinkedList. The bottom portion is what I was working with to test queue.

```<code>#include "Queue.hpp"
#include "LinkedList.hpp"
#include <string>
#include <iostream>

int main()
{
    LinkedList<int> list;
    LinkedList<int> listEmpty;
    Queue<int> list2;

    list.push(1);
    list.push(2);
    list.push(3);
    list.push(4);
    list.push(5);

    list.remove(1);

    std::cout << "List contains 4? " << list.contains(4) << std::endl;
    std::cout << "List empty? " << list.isEmpty() << std::endl;
    std::cout << "List size: " << list.size() << std::endl;
    std::cout << "Last in list? " << list.last() << std::endl;
    std::cout << "What is in position 4? " << list[4] << std::endl;
    std::cout << "Search " << list.search(10) << std::endl;
    //std::cout << "3 is in position " << list.search() << std::endl;
    std::cout << " " << std::endl;

    list.toString();
    list.clear();
    std::cout << "///////////////////////////////////////////////////////////////////////////////" << std::endl;
    list.push(4);

    list.toString();
    std::cout << "///////////////////////////////////////////////////////////////////////////////" << std::endl;
    std::cout << "QUEUE STUFF" << std::endl;
    std::cout << "///////////////////////////////////////////////////////////////////////////////" << std::endl;

    list2.push(1);
    list2.push(2);
    list2.push(6);
    list2.push(3);
    list2.push(4);
    list2.push(5);

    std::cout << "Queue empty? " << list2.empty() << std::endl;
    std::cout << "Queue size: " << list2.size() << std::endl;

    std::cout << "First in Queue? " << list2.peek() << std::endl;
    std::cout << "What position is 6 in? : " << list2.search(6) << std::endl;

    list2.toString();

    std::cout << " " << std::endl;

    system("pause");
</code>```

I guess my question is this, what steps can I take to go about fixing this particular function?

Thanks in advance!

答:
The problem with your code is that peek, as you said, should not modify the Queue and neither take any parameter because it merely looks at the top of the structure and returns either true or false.

So a solution is to remove the parameter in peak as follows and everything compiles and runs.

```<code>bool peek() const
{
    std::cout << _list.last() << std::endl;
    return true;

}
</code>```

Specifically, the error you get is because you cannot assign to a non-const lvalue reference an rvalue reference.
This is exactly what you are doing in T& val = T{}. T{} is an rvalue and clearly, val is a non-const reference to T.

You can try using bool peek(const T& val = T{}) const and see by yourself that everything compiles fine.

Title: Implementing Queue Using LinkedList

Body:
So, i'm attempting to implement this Queue using my LinkedList that I previously created. I've provided the code for both classes. Currently, I'm work on attempting to get pop and push to work without changing the function prototype (it's for an assignment).

When looking specifically at peek(I haven't quite finished pop), for some reason, when I run the code, I get strange pointer error.

Error   C2440   'default argument': cannot convert from 'int' to 'int &'

I'm not sure exactly what that means in this context. The function is suppose to look at the object at the top of the queue without removing it, and return true or false based upon if the operation was successful or not.

Here is the info for QUEUE.

  #ifndef _QUEUE_H
#define _QUEUE_H 1

#include "QueueInterface.h"
#include "LinkedList.hpp"

template <typename T>
class Queue : public QueueInterface<T>
{
protected:
    LinkedList<T> _list;
    int count;

public:

    unsigned size() const
    {
        return count;
    }

    bool push(const T& val = T{})
    {
        _list.push(val);
        count++;
        return true;
    }

    bool empty() const
    {
        return _list.isEmpty();
    }

    bool pop(T& val = T{})
    {
        return true;
    }

    bool peek(T& val = T{}) const
    {
        std::cout << _list.last() << std::endl;
        return true;

    }

    void clear()
    {
        _list.clear();
    }

    int search(const T& target = T{}) const
    {
        return _list.search(target);
    }
    //
    // Internal consistency check
    //

    void toString()
    {
        _list.toString();
    }

public:
    virtual bool check() const
    {
        return _list.check();
    }
};

#endif

Here is Linked List.

#ifndef _LINKED_LIST_GUARD
#define _LINKED_LIST_GUARD 1

#include <iostream>

#include "ListInterface.h"

template <typename T>
class LinkedList : public ListInterface<T>
{
public:

    int count = 0;

    LinkedList()
    {
        _head = new Node;
        _tail = new Node;

        _head->_next = _tail;
    }

private:

    //
    // Private node class to facilitate linked list
    //
    class Node
    {
    public:
        T _data;
        Node* _next;

        // Constructor: default
        Node(T d = T{}, Node* n = nullptr) : _data(d), _next(n) {}

        ~Node() { _next = nullptr; }
    };

    //
    // Prevent copying and assigning
    //
    LinkedList(const LinkedList& rhs) {}
    const LinkedList& operator=(const LinkedList& rhs) {}

public:
    //
    // LinkedList instance variables; we use dummy head and tail nodes in this implementation

    unsigned _size;
    Node* _head;
    Node* _tail;

    // Returns the first element in the list
    T& first() const
    {
        return _head->_next->_data;
    }

    // Adds an item to the LEFT side of the linked list
    void push(const T& x)
    {
        // Creates a new node with the user input data.
            Node* current = new Node;
            current->_data = x;

            current->_next = _head->_next;
            _head->_next = current;

            count++;

    }

    // ASK ABOUT
    T& operator[](unsigned n)
    {
        int position = 1;

        if (n != count)
        {
            throw("Invalid Position");
        }

        for (Node* current = _head->_next; current != _tail; current = current->_next, position++)
        {
            if (position == n)
            {
                return current -> _data;
            }
        }

    }

    void clear()
    {
        do
        {
            pop();
        } while (count != 0);

    }

    bool contains(const T& target) const
    {
        for (Node* current = _head->_next; current != _tail; current = current->_next)
        {
            if (current->_data == target)
                return true;
        }
        return false;
    }

    bool pop()
    {
        if (_head->_next == _tail)
        {
            std::cout << "unable to pop, list is empty";
            return false;
        }

        if (_head->_next != _tail)
        {
            Node* deleteNode = _head->_next;
            _head->_next = _head->_next->_next;
            delete deleteNode;
            count--;
            return true;
        }
        return false;
    }

    T& last() const
    {
        if (_head->_next == _tail)
        {
            std::cout << "LIST IS EMPTY" << std::endl;
        }

        if (_head->_next != _tail)
        {
            for (Node* current = _head->_next; current != _tail; current = current->_next)
            {
                if (current->_next == _tail)
                    return current->_data;
            }
        }
    }

    // ASK ABOUT
    int search(const T& target = T{}) const
    {
        int position = 1;
        for (Node* current = _head->_next; current != _tail; current = current->_next)
        {
            if (current->_data == target)
            {
                return position;
            }
            else  position++;
        }
        return -1;

    }

    bool isEmpty() const
    {
        if (_head->_next == _tail)
        {
            return true;
        }
        return false;
    }

    unsigned size() const
    {

        return count;
    }

    bool remove(const T& target)
    {
        Node* deleteNode = nullptr;
        Node* trailer = _head;
        Node* current = _head->_next;

        while (current != _tail && current-> _data != target)
        {
            trailer = current;
            current = current->_next;
        }

        if (current->_data == target)
        {
            deleteNode = current;
            current = current->_next;
            trailer->_next = current;

            delete deleteNode;
            count--;
            return true;
        }
        else
            std::cout << "unable to remove, item not in list" << std::endl;
        return false;

    }

    //FOR TESTING
    void toString()
    {
        for (Node* current = _head->_next; current != _tail; current = current->_next)
        {
            std::cout << current->_data << std::endl;
        }
    }

    //
    // Internal consistency check
    //
public:
    virtual bool check() const
    {
        bool sizeConsistent = isSizeConsistent();
        bool headTailConsistent = isEndConsistent();

        if (!sizeConsistent) std::cerr << "Size inconsistent" << std::endl;
        if (!headTailConsistent) std::cerr << "Head / Tail inconsistent" << std::endl;

        return sizeConsistent && headTailConsistent;
    }

    //
    // Stated size is accurate to the entire list
    //
    bool isSizeConsistent() const
    {
        int count = 0;
        for (Node* current = _head->_next; current != _tail; current = current->_next)
        {
            count++;
        }

        return size() == count;
    }

    //
    // Checks that the head and tail are defaulted properly and the
    // respective next pointers are appropriate.
    //
    bool isEndConsistent() const
    {
        if (_head->_data != T{}) return false;

        if (_tail->_data != T{}) return false;

        if (_head->_next == nullptr) return false;

        if (_tail->_next != nullptr) return false;

        if (isEmpty() && _head->_next != _tail) return false;

        if (!isEmpty() && _head->_next == _tail) return false;

        return true;
    }
};

#endif

And finally, here is my main. The top portion is to test the functionality for LinkedList. The bottom portion is what I was working with to test queue.

#include "Queue.hpp"
#include "LinkedList.hpp"
#include <string>
#include <iostream>

int main()
{
    LinkedList<int> list;
    LinkedList<int> listEmpty;
    Queue<int> list2;

    list.push(1);
    list.push(2);
    list.push(3);
    list.push(4);
    list.push(5);

    list.remove(1);

    std::cout << "List contains 4? " << list.contains(4) << std::endl;
    std::cout << "List empty? " << list.isEmpty() << std::endl;
    std::cout << "List size: " << list.size() << std::endl;
    std::cout << "Last in list? " << list.last() << std::endl;
    std::cout << "What is in position 4? " << list[4] << std::endl;
    std::cout << "Search " << list.search(10) << std::endl;
    //std::cout << "3 is in position " << list.search() << std::endl;
    std::cout << " " << std::endl;

    list.toString();
    list.clear();
    std::cout << "///////////////////////////////////////////////////////////////////////////////" << std::endl;
    list.push(4);

    list.toString();
    std::cout << "///////////////////////////////////////////////////////////////////////////////" << std::endl;
    std::cout << "QUEUE STUFF" << std::endl;
    std::cout << "///////////////////////////////////////////////////////////////////////////////" << std::endl;

    list2.push(1);
    list2.push(2);
    list2.push(6);
    list2.push(3);
    list2.push(4);
    list2.push(5);

    std::cout << "Queue empty? " << list2.empty() << std::endl;
    std::cout << "Queue size: " << list2.size() << std::endl;

    std::cout << "First in Queue? " << list2.peek() << std::endl;
    std::cout << "What position is 6 in? : " << list2.search(6) << std::endl;

    list2.toString();

    std::cout << " " << std::endl;

    system("pause");

I guess my question is this, what steps can I take to go about fixing this particular function?

Thanks in advance!

Body:
The problem with your code is that peek, as you said, should not modify the Queue and neither take any parameter because it merely looks at the top of the structure and returns either true or false.

So a solution is to remove the parameter in peak as follows and everything compiles and runs.

bool peek() const
{
    std::cout << _list.last() << std::endl;
    return true;

}

Specifically, the error you get is because you cannot assign to a non-const lvalue reference an rvalue reference.
This is exactly what you are doing in T& val = T{}. T{} is an rvalue and clearly, val is a non-const reference to T.

You can try using bool peek(const T& val = T{}) const and see by yourself that everything compiles fine.


问:
Query Excel where Rows and Columns are reversed
How can I query an Excel file where the rows and columns are reversed / rotated 90 degrees?

Can it be done with a SELECT query, or do I need to recurse the cells programmatically?

It's for a .NET app, so linq or other suggestions are welcome.

答:
Transpose a Datatable with a code like this:</p>

```<code>private DataTable GenerateTransposedTable(DataTable inputTable)
    {
        DataTable outputTable = new DataTable(inputTable.TableName);
        outputTable.Columns.Add(inputTable.Columns[0].ColumnName);

        foreach (DataRow inRow in inputTable.Rows)
        {
            string newColName = inRow[0].ToString();
            outputTable.Columns.Add(newColName);
        }

        for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
        {
            DataRow newRow = outputTable.NewRow();

            newRow[0] = inputTable.Columns[rCount].ColumnName;
            for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
            {
                string colValue = inputTable.Rows[cCount][rCount].ToString();
                newRow[cCount + 1] = colValue;
            }
            outputTable.Rows.Add(newRow);
        }

        return outputTable;
    }
</code>```

Body:
Transpose a Datatable with a code like this:

private DataTable GenerateTransposedTable(DataTable inputTable)
    {
        DataTable outputTable = new DataTable(inputTable.TableName);
        outputTable.Columns.Add(inputTable.Columns[0].ColumnName);

        foreach (DataRow inRow in inputTable.Rows)
        {
            string newColName = inRow[0].ToString();
            outputTable.Columns.Add(newColName);
        }

        for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
        {
            DataRow newRow = outputTable.NewRow();

            newRow[0] = inputTable.Columns[rCount].ColumnName;
            for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
            {
                string colValue = inputTable.Rows[cCount][rCount].ToString();
                newRow[cCount + 1] = colValue;
            }
            outputTable.Rows.Add(newRow);
        }

        return outputTable;
    }


问:
ruby - rails - Dealing with a Boolean False- It outputs nothing
I have record in my db that is a boolean field (true/false).

The field is archived. When archived is true all these work great to output true:

```<code>  Rails.logger.info @commentable.archived
  Rails.logger.info @commentable.archived?
  Rails.logger.info !!@commentable.archived?
</code>```

BUT when the archived is false, it outputs nothing for either of the above. How can I get an output of false when the field is FALSE?

Thanks

答:
Try .to_s on the field?

```<code>irb(main):001:0> false.to_s
=> "false"
irb(main):002:0> true.to_s
=> "true"
irb(main):003:0>
</code>```

Body:
I have record in my db that is a boolean field (true/false).

The field is archived. When archived is true all these work great to output true:

  Rails.logger.info @commentable.archived
  Rails.logger.info @commentable.archived?
  Rails.logger.info !!@commentable.archived?

BUT when the archived is false, it outputs nothing for either of the above. How can I get an output of false when the field is FALSE?

Thanks

Body:
Try .to_s on the field?

irb(main):001:0> false.to_s
=> "false"
irb(main):002:0> true.to_s
=> "true"
irb(main):003:0>


答:
You can use Array#map to iterate the players, and create the array you want:

var obj1 = {
  score: [10, 22, 30, 55, 70, 90],
  lettersOfMyName: ["a", "m", "r"],
  avgScore: null,
  favoritePlayers: [{
      name: "messi",
      club: "barcelona"
    },

    {
      name: "totti",
      club: "roma"
    }
  ],

  getPlaysIn() {
    return this.favoritePlayers.map(function(player) {
      return player.name + ' plays in ' + player.club;
    });
  }
};

console.log(obj1.getPlaysIn());```

Title: how to iterate throught an array of objects and concate the contents


问:
Laravel 5.3 - TokenMismatchException in VerifyCsrfToken.php line 68:
When I log in to my app, and immediately go back when I enter it, and then try to log out, I get the error from the title, how can I fix that?</p>

答:
Out of the box, Laravel comes with web and api middleware groups that contains common middleware you may want to apply to your web UI and API routes

If you check your app/Providers/RouteServiceProvider.php, you will find that by default, a web middleware group is applied to all your routes in routes/web.php.

```<code>protected function mapWebRoutes()
{
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
    ], function ($router) {
        require base_path('routes/web.php');
    });
}
</code>```

Now, if you go check your app/Http/Kernel.php and take a look at the $middlewareGroups property, you will find a new EncryptCookies middleware. You can read about it, but if you remove this middleware from the web middleware group, your app might not give the TokenMismatchException which you are getting currently.

Body:
Out of the box, Laravel comes with web and api middleware groups that contains common middleware you may want to apply to your web UI and API routes

If you check your app/Providers/RouteServiceProvider.php, you will find that by default, a web middleware group is applied to all your routes in routes/web.php.

protected function mapWebRoutes()
{
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
    ], function ($router) {
        require base_path('routes/web.php');
    });
}

Now, if you go check your app/Http/Kernel.php and take a look at the $middlewareGroups property, you will find a new EncryptCookies middleware. You can read about it, but if you remove this middleware from the web middleware group, your app might not give the TokenMismatchException which you are getting currently.


问:
angular4 local variable issue for *ngFor
I have a requirement where I have load multiple items using item list. Whenever you upload a file, upload file input has to hide and details of that file has to show like filename and other button.

I implemented the scenario by using a localvariable, it works fine with one item, but when we have multiple items, its not working.
Assume if I have 3 itemList, if we click on 1st item fileupload button and upload a file, it loads filename and validate button, but if we do same process for 2nd item (after 1st process), after fileupload, 1st filename will be modified.

View:

```<code><div id="userItemList" *ngFor="let item of itemList; let i=index">
    <div>
        <span>{{item.Id}}</span>
        <span>{{item.Name}}</span>
        <span>{{item.Count}}</span>
    </div>
    <div>
        <input type="file" name="UploadFile" id="fileInput" #fileInput (change)="txtUploadFile($event,i)">
        <div class="validate-file-div" #validateContent style="display:none">
            <div class="file-name" #fileName></div>
            <span id="validate-csv-button" data-program-id="0" class="button">Validate</span>
        </div>
    </div>
</div>
</code>```

My component look like:

```<code>import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-programs-manager',
  templateUrl: './ProgramsManager.component.html',
  styleUrls: ['./ProgramsManager.component.css'],
})

export class ProgramsManagerComponent implements OnInit {

    itemList = [{"Id":1,"Name":"Item1","Count":2},{"Id":2,"Name":"Item2","Count":2},{"Id":3,"Name":"Item3","Count":3}];
    @ViewChild("fileInput") fileInput;
    @ViewChild("validateContent") validateContent;
    @ViewChild("fileName") fileName;

    constructor() { }

    ngOnInit() {
    }

    txtUploadFile(event,index) {
        this.fileInput.nativeElement.style.display = "none";
        this.validateContent.nativeElement.style.display = "block";
        this.fileInput.nativeElement.innerHTML = event.target.files[0].name;
    }
}
</code>```

I feel local variable is giving problem,but don't know how to fix it. can anyone help me.
Thanks in advance

答:
Eliseo is right you should get index value instead of 0. That's why. To show and hide a div, you must create a class variable like showInfo = null by default and set it with the file array value.

Change the value when the use click on the download button using <button (click)="showInfo=item[index]"/>
 Then in your HTML use

```<code><a [class.hidden]="!showInfo">Download {{item.name}} </a>
</code>```

which display the info if existing

Body:
I have a requirement where I have load multiple items using item list. Whenever you upload a file, upload file input has to hide and details of that file has to show like filename and other button.

I implemented the scenario by using a localvariable, it works fine with one item, but when we have multiple items, its not working.
Assume if I have 3 itemList, if we click on 1st item fileupload button and upload a file, it loads filename and validate button, but if we do same process for 2nd item (after 1st process), after fileupload, 1st filename will be modified.

View:

        {{item.Id}}
        {{item.Name}}
        {{item.Count}}

        <input type="file" name="UploadFile" id="fileInput" #fileInput (change)="txtUploadFile($event,i)">

            Validate

My component look like:

import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-programs-manager',
  templateUrl: './ProgramsManager.component.html',
  styleUrls: ['./ProgramsManager.component.css'],
})

export class ProgramsManagerComponent implements OnInit {

    itemList = [{"Id":1,"Name":"Item1","Count":2},{"Id":2,"Name":"Item2","Count":2},{"Id":3,"Name":"Item3","Count":3}];
    @ViewChild("fileInput") fileInput;
    @ViewChild("validateContent") validateContent;
    @ViewChild("fileName") fileName;

    constructor() { }

    ngOnInit() {
    }

    txtUploadFile(event,index) {
        this.fileInput.nativeElement.style.display = "none";
        this.validateContent.nativeElement.style.display = "block";
        this.fileInput.nativeElement.innerHTML = event.target.files[0].name;
    }
}

I feel local variable is giving problem,but don't know how to fix it. can anyone help me.
Thanks in advance

Body:
Eliseo is right you should get index value instead of 0. That's why. To show and hide a div, you must create a class variable like showInfo = null by default and set it with the file array value.

Change the value when the use click on the download button using <button (click)="showInfo=item[index]"/>
 Then in your HTML use

<a [class.hidden]="!showInfo">Download {{item.name}} </a>

which display the info if existing


问:
Check variable equality against a list of values
I'm checking a variable, say foo, for equality to a number of values. For example,

```<code>if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}
</code>```

The point is that it is rather much code for such a trivial task. I came up with the following:

```<code>if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}
</code>```

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

答:
You could use an array and indexOf:

```<code>if ([1,3,12].indexOf(foo) > -1)
</code>```

Body:
I'm checking a variable, say foo, for equality to a number of values. For example,

if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}

The point is that it is rather much code for such a trivial task. I came up with the following:

if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

Body:
You could use an array and indexOf:

if ([1,3,12].indexOf(foo) > -1)


问:
TensorBoard Embedding Example?
I'm looking for a tensorboard embedding example, with iris data for example like the embedding projector http://projector.tensorflow.org/

But unfortunately i couldn't find one. Just a little bit information about how to do it in https://www.tensorflow.org/how_tos/embedding_viz/

Does someone knows a basic tutorial for this functionality?

Basics:

1) Setup a 2D tensor variable(s) that holds your embedding(s).

```<code>embedding_var = tf.Variable(....)
</code>```

2) Periodically save your embeddings in a LOG_DIR.

3) Associate metadata with your embedding.

答:
The accepted answer was very helpful to understand the general sequence:

Create metadata for each vector (sample)

Associate images (sprites) with each vector

Load the data into TensorFlow and save the embeddings using checkpoint and summary writer (mind that the paths are consistent throughout the process).

For me, the MNIST-based example still relied too much on pre-trained data and pre-generated sprite & metadata files. To fill this gap I created such an example myself and decided to share it here for anyone interested - the code is on GitHub.

Title: TensorBoard Embedding Example?

Body:
I'm looking for a tensorboard embedding example, with iris data for example like the embedding projector http://projector.tensorflow.org/

But unfortunately i couldn't find one. Just a little bit information about how to do it in https://www.tensorflow.org/how_tos/embedding_viz/

Does someone knows a basic tutorial for this functionality?

Basics:

1) Setup a 2D tensor variable(s) that holds your embedding(s).

embedding_var = tf.Variable(....)

2) Periodically save your embeddings in a LOG_DIR.

3) Associate metadata with your embedding.


问:
Find element which contains text
Could someone please assist me in following issue:
i have to pickup from dropdown elements which have - Open as a part of title (as per on screenshot below)

Since that value will be change during time period, it is useless to use that, and have to pickup ones with 'Open' status (not showed, but rest of statuses are: Frozen & Closed)
So, here is xpath which I tried:

```<code>//*[@id="period"]/contains(@text, '')
</code>```

For above i got result from test  is true. (It does exist text as I understand that)
But when add wanted text

```<code>//*[@id="period"]/contains(@text, 'Open')
</code>```

I got as a result false and can not find elements.
Also, when searched with:

```<code>//*[@id="period"]
</code>```

I got result (all periods are shown).

```<code> 01. Oct 2018 - 31. Oct 2018 - Open01. Sep 2018 - 30. Sep 2018 - Open01. Aug 2018 and so on ...
</code>```

HTML is as follows:

```<code><main class="main row">
<div class="content clearfix column medium-8">
<div class="row">
<article class="column medium-12">
<div class="t-box">
 <p></p><div class="compete">
 <a class="button primary" href="« Back to overview</a>
 <div class="promotion">
  <h2 class="promotion-header"><img src="/assets/images/system/stats/language/EN.png.pagespeed.ce.nTcGwJ7dzC.png">Top of the month</h2>
</code>```

```<code> <form class="row" method="GET" action="/compete">
 <input type="hidden" name="id" value="3">
 <div class="column large-2">
  <label for="period"><strong> <br>Period:</strong></label>
   </div>
   <div class="column large-8">
   <select id="period" name="period">
   <option value="39">01. Oct 2018 - 31. Oct 2018 - Open</option><option    value="38">01. Sep 2018 - 30. Sep 2018 - Open</option><option value="37">01. Aug 2018 - 31. Aug 2018 - Open</option><option value="36">01. Jul 2018 - 31. Jul 2018 - Open</option><option value="35">01. Jun 2018 - 30. Jun 2018 - Open</option><option value="34">01. May 2018 - 31. May 2018 - Open</option><option value="33">01.
</code>```

What I am doing wrong, please assist.

答:
To print all the months which have Open as a part of title you can use the following code block :

```<code>Select months = new Select(driver.findElement(By.id("period")));
List<WebElement> monthList = months.getOptions();
for(WebElement month:monthList)
    if(month.getAttribute("innerHTML").contains("Open"))
        System.out.println(month.getAttribute("innerHTML"));
</code>```

Title: Find element which contains text

Body:
Could someone please assist me in following issue:
i have to pickup from dropdown elements which have - Open as a part of title (as per on screenshot below)

Since that value will be change during time period, it is useless to use that, and have to pickup ones with 'Open' status (not showed, but rest of statuses are: Frozen & Closed)
So, here is xpath which I tried:

//*[@id="period"]/contains(@text, '')

For above i got result from test  is true. (It does exist text as I understand that)
But when add wanted text

//*[@id="period"]/contains(@text, 'Open')

I got as a result false and can not find elements.
Also, when searched with:

//*[@id="period"]

I got result (all periods are shown).

 01. Oct 2018 - 31. Oct 2018 - Open01. Sep 2018 - 30. Sep 2018 - Open01. Aug 2018 and so on ...

HTML is as follows:

 <a class="button primary" href="« Back to overview

Top of the month

 <form class="row" method="GET" action="/compete">
 <input type="hidden" name="id" value="3">

Period:

   <select id="period" name="period">
   <option value="39">01. Oct 2018 - 31. Oct 2018 - Open</option><option    value="38">01. Sep 2018 - 30. Sep 2018 - Open</option><option value="37">01. Aug 2018 - 31. Aug 2018 - Open</option><option value="36">01. Jul 2018 - 31. Jul 2018 - Open</option><option value="35">01. Jun 2018 - 30. Jun 2018 - Open</option><option value="34">01. May 2018 - 31. May 2018 - Open</option><option value="33">01.

What I am doing wrong, please assist.

Body:
To print all the months which have Open as a part of title you can use the following code block :

Select months = new Select(driver.findElement(By.id("period")));
List<WebElement> monthList = months.getOptions();
for(WebElement month:monthList)
    if(month.getAttribute("innerHTML").contains("Open"))
        System.out.println(month.getAttribute("innerHTML"));


问:
Google App Invites: Tracking Invites
I'm trying to understand this part of the guide (https://developers.google.com/app-invites/android/guides/app):

Tracking Invitations

After your app has received an invitation and taken the intended
  actions, it should call the updateInvitationOnAppInstalled method to
  mark the invitation as successful:

```<code>private void updateInvitationStatus(Intent intent) {
    String invitationId = AppInviteReferral.getInvitationId(intent);

    // Note: these  calls return PendingResult(s), so one could also wait to see
    // if this succeeds instead of using fire-and-forget, as is shown here
    if (AppInviteReferral.isOpenedFromPlayStore(intent)) {
        AppInvite.AppInviteApi.updateInvitationOnInstall(mGoogleApiClient,invitationId);

    }

    // If your invitation contains deep link information such as a coupon code, you may
    // want to wait to call `convertInvitation` until the time when the user actually
    // uses the deep link data, rather than immediately upon receipt
    AppInvite.AppInviteApi.convertInvitation(mGoogleApiClient, invitationId);
}
</code>```

The code above requires a connected GoogleApiClient with AppInvite.API
  enabled.

I see you can track app invites with AppInvite.API but I don't see a way in which one can view the stats after tracking it.

The AppInviteApi just says the following:

The main entry point for interacting with AppInvite invitations. This
  class provides a method to update invitation status after receiving an
  invitation id after app installation.

Link to AppInviteApi docs

How can I view what I'm tracking?
I opened a Google Analytics account but it will only display data in 1-2 days and I doubt it will even be displayed there as from my understanding, Google Analytics is optional when using Google App Invites.

答:
Use Firebase Invites to drive app referrals and sharing through email or SMS

By combining the power of word of mouth with a frictionless and personalized onboarding flow, Firebase Invites help drive installs by enabling your users to share an app or their favorite in-app content with people they know. Firebase Invites help you optimize an important means of app discovery — according to a Google and Ipsos MediaCT survey, 52% of people say they discover apps through word of mouth.

Firebase Link

Referral link

Title: Google App Invites: Tracking Invites

Body:
I'm trying to understand this part of the guide (https://developers.google.com/app-invites/android/guides/app):

Tracking Invitations

After your app has received an invitation and taken the intended
  actions, it should call the updateInvitationOnAppInstalled method to
  mark the invitation as successful:

private void updateInvitationStatus(Intent intent) {
    String invitationId = AppInviteReferral.getInvitationId(intent);

    // Note: these  calls return PendingResult(s), so one could also wait to see
    // if this succeeds instead of using fire-and-forget, as is shown here
    if (AppInviteReferral.isOpenedFromPlayStore(intent)) {
        AppInvite.AppInviteApi.updateInvitationOnInstall(mGoogleApiClient,invitationId);

    }

    // If your invitation contains deep link information such as a coupon code, you may
    // want to wait to call `convertInvitation` until the time when the user actually
    // uses the deep link data, rather than immediately upon receipt
    AppInvite.AppInviteApi.convertInvitation(mGoogleApiClient, invitationId);
}

The code above requires a connected GoogleApiClient with AppInvite.API
  enabled.

I see you can track app invites with AppInvite.API but I don't see a way in which one can view the stats after tracking it.

The AppInviteApi just says the following:

The main entry point for interacting with AppInvite invitations. This
  class provides a method to update invitation status after receiving an
  invitation id after app installation.

Link to AppInviteApi docs

How can I view what I'm tracking?
I opened a Google Analytics account but it will only display data in 1-2 days and I doubt it will even be displayed there as from my understanding, Google Analytics is optional when using Google App Invites.


问:
DocuSign - Getting a user ID for a user whose organization admins has pre-authorized the application
Any route requires you to be authenticated as a DocuSign user to use it. With the standard service integration flow, you direct the user through docusign's /oauth/auth flow, use the returned code to get an access token via /oauth/token, then  use that token on /oauth/userinfo to get the user's ID which you can then sign and use in a JWT.

Instead of directing users through the oauth UI to get their consent, DocuSign allows organization admins to pre-authorize an application for everyone in the application. No need to send organization members through the oauth flow. Great.

However, once this action has been taken, it's not clear how my application could make requests on behalf of any user, since the /oauth/userinfo route that gives you the user id requires an oauth code that you get by passing the user through DocuSign's oauth browser UI.

More specifically: if the admin of foo.com's DocuSign organization authorizes my app, and bob@foo.com starts using my application, how do I get bob@foo.com's user ID to create a JWT with?

答:
When you say "bob@foo.com starts using my application" what, exactly, does that mean?

Case 1: Bob is interacting with your application. In that case, you should be using a User Application OAuth flow such as Authorization Code Grant to enable him to login.

If your app needs to later act on behalf of Bob when he's not around, then store Bob's user id for later use with the JWT grant.

Case 2: Your app is running in the background (no human interaction). At some point your app needs to starting doing things for Bob by impersonating him. All you have is his email address.

If this time arrives and your app has had no interaction with Bob, then yes, you need prior access as an admin (in Bob's account) so you can look up Bob's user_id from his email.

This second account would be the "admin user account" for your app. The account would need admin privileges to lookup the user's information. Your app would get access to this admin account when your app is installed.

Use the Users:list API call. Remember to encode the email address.

Example:

```<code>GET call: /v2/accounts/{accountId}/users?email=larry%2Buser%40foo.com
</code>```

Re: user_id lifetime I'm reasonably sure that the user_id guid doesn't change for a given accounted user (someone who is a member of an account on DocuSign). I will check to make sure.

Body:
When you say "bob@foo.com starts using my application" what, exactly, does that mean?

Case 1: Bob is interacting with your application. In that case, you should be using a User Application OAuth flow such as Authorization Code Grant to enable him to login.

If your app needs to later act on behalf of Bob when he's not around, then store Bob's user id for later use with the JWT grant.

Case 2: Your app is running in the background (no human interaction). At some point your app needs to starting doing things for Bob by impersonating him. All you have is his email address.

If this time arrives and your app has had no interaction with Bob, then yes, you need prior access as an admin (in Bob's account) so you can look up Bob's user_id from his email.

This second account would be the "admin user account" for your app. The account would need admin privileges to lookup the user's information. Your app would get access to this admin account when your app is installed.

Use the Users:list API call. Remember to encode the email address.

Example:

GET call: /v2/accounts/{accountId}/users?email=larry%2Buser%40foo.com

Re: user_id lifetime I'm reasonably sure that the user_id guid doesn't change for a given accounted user (someone who is a member of an account on DocuSign). I will check to make sure.


问:
What is difference between spark.jars and spark.driver.extraClassPath
I'm trying to run spark program using spark-submit in yarn-client mode and getting classNotFound Exception. So my question is in which parameter should I pass my jar(--jars or --driver-class-path).

Spark =2.0.0
HDP 2.5
Hadoop= 2.7.3

答: Use --jars if you want to make these jars available to both driver and executor class-paths. If the required jar is only to be used by driver code, use option --driver-class-path


问:
How to represent boolean-type fields in Web API results
I am designing a REST Web API, and I am unsure of how to model certain parts of the response.

I think an example of the output will be most illustrative, so here it is.

This:

```<code><packages>
  <package>
    <name>My Package, Yay!</name>
    <description>This is my package, Yay!</description>
    <features>
      <text_overlays />
      <localizable />
      <!-- Only features that are true for this package are listed -->
    </features>
  </package>
</packages>
</code>```

Or this:

```<code><packages>
  <package>
    <name>My Package, Yay!</name>
    <description>This is my package, Yay!</description>
    <features>
      <text_overlays>True</text_overlays>
      <localizable>True</localizable>
      <audio>False</audio>
      <another_feature>False</another_feature>
      <this_aint_your_fathers_feature>False</this_aint_your_fathers_feature>
      <every_other_feature_that_exists_listed_here_too>False</every_other_feature_that_exists_listed_here_too>
    </features>
  </package>
</packages>
</code>```

Basically, I have boolean fields, and it seems overly verbose to specify them all if many are false.

I am thinking about using the presence of an element as indicating whether it is true or false, but in the same thought I worry this would be a bad practice.  It certainly seems less discoverable, but I'm not sure there's much value in discoverability here.

Is there a consensus on this sort of issue?

From a consuming client's perspective, I don't see too much difference.  Testing for the presence of the element shouldn't be any more complicated than checking the value of the element.

Also, I expect there may be up to a dozen or possibly two dozen of these type of parameters, so it's not like there would be hundreds or thousands of them.

Lastly, we intend for our API to be used with XML and JSON.  The JSON equivalent would be omitting the properties, and again from a consuming client perspective I see little difference between the two.

We have the opportunity to do this correctly from the beginning, and that is our goal.

What advice is there?

答: If the decision comes down to being explicit or implicit, I'd default to explicit to remove any possible confusion. The entity being represented has those attributes regardless of whether you send them or not, but you should include a complete representation.</p>

Body:
I am designing a REST Web API, and I am unsure of how to model certain parts of the response.

I think an example of the output will be most illustrative, so here it is.

This:

<packages>
  <package>
    <name>My Package, Yay!</name>
    <description>This is my package, Yay!</description>
    <features>
      <text_overlays />
      <localizable />

    </features>
  </package>
</packages>

Or this:

<packages>
  <package>
    <name>My Package, Yay!</name>
    <description>This is my package, Yay!</description>
    <features>
      <text_overlays>True</text_overlays>
      <localizable>True</localizable>
      <audio>False</audio>
      <another_feature>False</another_feature>
      <this_aint_your_fathers_feature>False</this_aint_your_fathers_feature>
      <every_other_feature_that_exists_listed_here_too>False</every_other_feature_that_exists_listed_here_too>
    </features>
  </package>
</packages>

Basically, I have boolean fields, and it seems overly verbose to specify them all if many are false.

I am thinking about using the presence of an element as indicating whether it is true or false, but in the same thought I worry this would be a bad practice.  It certainly seems less discoverable, but I'm not sure there's much value in discoverability here.

Is there a consensus on this sort of issue?

From a consuming client's perspective, I don't see too much difference.  Testing for the presence of the element shouldn't be any more complicated than checking the value of the element.

Also, I expect there may be up to a dozen or possibly two dozen of these type of parameters, so it's not like there would be hundreds or thousands of them.

Lastly, we intend for our API to be used with XML and JSON.  The JSON equivalent would be omitting the properties, and again from a consuming client perspective I see little difference between the two.

We have the opportunity to do this correctly from the beginning, and that is our goal.

What advice is there?


问:
Date.parse() results in NaN
```<code>Date.parse();
</code>```

My jsFiddle works fine, but run it in my ide (both Aptana and WebStorm) shows NaN in the console.log() output.

Really confused about this... Has someone had such experience before?

答:
The date should be in the IETF date syntax (RFC2822 Section 3.3) format, e.g. "Mon, 25 Dec 1995 13:30:00 GMT", or "Mon, 25 Dec 1995 13:30:00 GMT+0430".

Read more: Date.parse()

Surprisingly this should be done also for the current (2017) versions of IE (11.x) and FF (56.x) for the Date.parse to work correctly.

Title: Date.parse() results in NaN

Body:
Date.parse();

My jsFiddle works fine, but run it in my ide (both Aptana and WebStorm) shows NaN in the console.log() output.

Really confused about this... Has someone had such experience before?


问:
Sorting each row and select the top three values from a dataframe
I have a dataframe which looks something like :

```<code>device_id   s2  s41 s47 s14
30          0   0   0   0.003
125         0   0   0   0
32          0   0   0   0
45          0   0   0   0
</code>```

The objective is to get the 3 highest s's from each row and if there is a match then select the maximum index. For example, for the first row, there is a match between s2, s41 and s47 so s47 will be selected along with s41. So the selection from row 1 would be s14, s47 and s41. There are more than 2 million records and more than 250 s's and hence I need an efficient way of doing this. I have tried with iterrows and then sorting each row but it is slow and takes more than an hour for all the data.

The end objective would be to search for the s's ( s14, s47 , s41) in a dictionary where these values are the keys and getting the appropriate values from there.

Can someone please help me in doing this efficiently.
Thanks

答:
I don't know pandas, but I understand it is numpy-based, so here is a numpy solution. It uses argpartition to efficiently get the indices of the largest 4 in each row. Unfortunately, the algorithm used by numpy is not stable, so if the smallest two of those four are equal we must do a full sort, sort giving us the option of choosing a stable algorithm.

Code (Couldn't check with 2m rows b/c memory on my rig, but 0.5m takes 2 sec or so):

```<code>import numpy as np

def stable_high_3(data):
    n, m = data.shape
    high_4 = np.argpartition(data, np.arange(m-4, m), axis=-1)[:, -4:]
    must_check = np.where(data[np.arange(n), high_4[:, 0]]
                          == data[np.arange(n), high_4[:, 1]])[0]
    high_4[must_check, -3:] = np.argsort(data[must_check], axis=-1,
                                         kind='mergesort')[:, -3:]
    return high_4[:, -3:]

data = np.reshape(np.arange(30)%5, (-1, 6))
print(data)
print(stable_high_3(data))

data = np.reshape(np.arange(256*2**18)%50, (-1, 256))
stable_high_3(data)
</code>```

Prints

```<code>[[0 1 2 3 4 0]
 [1 2 3 4 0 1]
 [2 3 4 0 1 2]
 [3 4 0 1 2 3]
 [4 0 1 2 3 4]]
[[2 3 4]
 [1 2 3]
 [5 1 2]
 [0 5 1]
 [4 0 5]]
</code>```

Body:
I have a dataframe which looks something like :

device_id   s2  s41 s47 s14
30          0   0   0   0.003
125         0   0   0   0
32          0   0   0   0
45          0   0   0   0

The objective is to get the 3 highest s's from each row and if there is a match then select the maximum index. For example, for the first row, there is a match between s2, s41 and s47 so s47 will be selected along with s41. So the selection from row 1 would be s14, s47 and s41. There are more than 2 million records and more than 250 s's and hence I need an efficient way of doing this. I have tried with iterrows and then sorting each row but it is slow and takes more than an hour for all the data.

The end objective would be to search for the s's ( s14, s47 , s41) in a dictionary where these values are the keys and getting the appropriate values from there.

Can someone please help me in doing this efficiently.
Thanks

Body:
I don't know pandas, but I understand it is numpy-based, so here is a numpy solution. It uses argpartition to efficiently get the indices of the largest 4 in each row. Unfortunately, the algorithm used by numpy is not stable, so if the smallest two of those four are equal we must do a full sort, sort giving us the option of choosing a stable algorithm.

Code (Couldn't check with 2m rows b/c memory on my rig, but 0.5m takes 2 sec or so):

import numpy as np

def stable_high_3(data):
    n, m = data.shape
    high_4 = np.argpartition(data, np.arange(m-4, m), axis=-1)[:, -4:]
    must_check = np.where(data[np.arange(n), high_4[:, 0]]
                          == data[np.arange(n), high_4[:, 1]])[0]
    high_4[must_check, -3:] = np.argsort(data[must_check], axis=-1,
                                         kind='mergesort')[:, -3:]
    return high_4[:, -3:]

data = np.reshape(np.arange(30)%5, (-1, 6))
print(data)
print(stable_high_3(data))

data = np.reshape(np.arange(256*2**18)%50, (-1, 256))
stable_high_3(data)

Prints

[[0 1 2 3 4 0]
 [1 2 3 4 0 1]
 [2 3 4 0 1 2]
 [3 4 0 1 2 3]
 [4 0 1 2 3 4]]
[[2 3 4]
 [1 2 3]
 [5 1 2]
 [0 5 1]
 [4 0 5]]