问:
Convert dictionary from wide to long form using pandas
I have a list of dictionaries in Python with different keys (Response Key is present in all ) and I want to convert it into a Panda Dataframe such that all key-values are shown as rows with Response Key value repeating as a Column. For instance, following list

[ {'Response': 1, 'work life': 5, 'life family': 2, 'family balance': 10},
{'Response': 2, 'encouragement management': 11, 'management career': 1, 'career aspirations': 4, 'aspirations develop': 8},{'Response': 3, 'encourage people': 15, 'people managers': 9, 'managers ask': 5, 'ask employees': 9} ]

should become 3-column dataframe as

```<code>Response | Attribute | Value
1, work life, 5
1, life family, 2
1, family balance, 10
2, encouragement management, 11
2, management career, 1
2, career aspirations, 4
2, aspirations develop, 8
3, encourage people, 15
3, people managers, 9
3, managers ask, 5
3, ask employees, 9
</code>```

答:
This might be what you're looking for. Use stack and then reset the index and column names.

```<code>df = pd.DataFrame(d).set_index('Response').stack().reset_index()
df.columns = ['Response', 'Attribute', 'Value']

df

    Response                 Attribute  Value
0          1            family balance   10.0
1          1               life family    2.0
2          1                 work life    5.0
3          2       aspirations develop    8.0
4          2        career aspirations    4.0
5          2  encouragement management   11.0
6          2         management career    1.0
7          3             ask employees    9.0
8          3          encourage people   15.0
9          3              managers ask    5.0
10         3           people managers    9.0
</code>```

d is your dictionary data. Keep in mind that dictionaries are not ordered, so it is unreasonable to always expect the same order as in your question.

Body:
I have a list of dictionaries in Python with different keys (Response Key is present in all ) and I want to convert it into a Panda Dataframe such that all key-values are shown as rows with Response Key value repeating as a Column. For instance, following list

[ {'Response': 1, 'work life': 5, 'life family': 2, 'family balance': 10},
{'Response': 2, 'encouragement management': 11, 'management career': 1, 'career aspirations': 4, 'aspirations develop': 8},{'Response': 3, 'encourage people': 15, 'people managers': 9, 'managers ask': 5, 'ask employees': 9} ]

should become 3-column dataframe as

Response | Attribute | Value
1, work life, 5
1, life family, 2
1, family balance, 10
2, encouragement management, 11
2, management career, 1
2, career aspirations, 4
2, aspirations develop, 8
3, encourage people, 15
3, people managers, 9
3, managers ask, 5
3, ask employees, 9

Body:
This might be what you're looking for. Use stack and then reset the index and column names.

df = pd.DataFrame(d).set_index('Response').stack().reset_index()
df.columns = ['Response', 'Attribute', 'Value']

df

    Response                 Attribute  Value
0          1            family balance   10.0
1          1               life family    2.0
2          1                 work life    5.0
3          2       aspirations develop    8.0
4          2        career aspirations    4.0
5          2  encouragement management   11.0
6          2         management career    1.0
7          3             ask employees    9.0
8          3          encourage people   15.0
9          3              managers ask    5.0
10         3           people managers    9.0

d is your dictionary data. Keep in mind that dictionaries are not ordered, so it is unreasonable to always expect the same order as in your question.


来源: stackexchange

问:
Getting asked twice to insert integer
I have some homework to do for the University, and since I'm a beginner I don't know how to code yet. So, there are 10 tests with the grade of each being between 0 and 10. I have to make sure that I don't get any negative number or a number greater than 10. while running the code I have to put 2 numbers in order to proceed to the next one, when, I clearly want just the one saved to A[i]. I hope you understand even though I can't even explain the problem. :)</p>

```<code>#include<stdio.h>

int main()
{
    int A[10];
    int i, j;
    for ( i = 1; i<11; i++)
    {
        printf("Enter %d grade \n", i);
        scanf("%d", &j);
        if (j<=10 && j>=0)
         A[i] = j;
        else
         printf("Enter a number between 0 and 10\n");
         scanf("%d", &j);
    }
}
</code>```

答:
Why 2 inputs?

What you wrote

```<code>     else
     printf("Enter a number between 0 and 10\n");
     scanf("%d", &j);
</code>```

which is same as

```<code>     else {
     printf("Enter a number between 0 and 10\n");
     }
     scanf("%d", &j);
</code>```

What you want is:-

```<code>    else {
     printf("Enter a number between 0 and 10\n");
     scanf("%d", &j);
    }
</code>```

This is what is told very early stage. It is clear this is why you need to enter 2 numbers even when you are giving correct input.

Undefined behavior:-

Also you have 10 location in A why write at A[10]. C arrays are 0-indexed. You are dealing with undefined behavior.

```<code>for ( i = 0; i<10; i++)
</code>```

Error in logic?

What happens when a user gives two times a wrong input? You need to use a while loop. ( You can't expect all user to be right the second time).

Scanf returns something ...

Check the return type of scanf to check if the scanf call is doing what you expect it to do.

Other bits that I will tell you will be use size_t in the looping variable.

ContentLicense: CC BY-SA 3.0

Title: Getting asked twice to insert integer

Body:
I have some homework to do for the University, and since I'm a beginner I don't know how to code yet. So, there are 10 tests with the grade of each being between 0 and 10. I have to make sure that I don't get any negative number or a number greater than 10. while running the code I have to put 2 numbers in order to proceed to the next one, when, I clearly want just the one saved to A[i]. I hope you understand even though I can't even explain the problem. :)

#include<stdio.h>

int main()
{
    int A[10];
    int i, j;
    for ( i = 1; i<11; i++)
    {
        printf("Enter %d grade \n", i);
        scanf("%d", &j);
        if (j<=10 && j>=0)
         A[i] = j;
        else
         printf("Enter a number between 0 and 10\n");
         scanf("%d", &j);
    }
}

Body:
Why 2 inputs?

What you wrote

     else
     printf("Enter a number between 0 and 10\n");
     scanf("%d", &j);

which is same as

     else {
     printf("Enter a number between 0 and 10\n");
     }
     scanf("%d", &j);

What you want is:-

    else {
     printf("Enter a number between 0 and 10\n");
     scanf("%d", &j);
    }

This is what is told very early stage. It is clear this is why you need to enter 2 numbers even when you are giving correct input.

Undefined behavior:-

Also you have 10 location in A why write at A[10]. C arrays are 0-indexed. You are dealing with undefined behavior.

for ( i = 0; i<10; i++)

Error in logic?

What happens when a user gives two times a wrong input? You need to use a while loop. ( You can't expect all user to be right the second time).

Scanf returns something ...

Check the return type of scanf to check if the scanf call is doing what you expect it to do.

Other bits that I will tell you will be use size_t in the looping variable.


问:
Solve a nonlinear equation system with constraints on the variables
Some hypothetical example solving a nonlinear equation system with fsolve:

```<code>from scipy.optimize import fsolve
import math

def equations(p):
    x, y = p
    return (x+y**2-4, math.exp(x) + x*y - 3)

x, y =  fsolve(equations, (1, 1))

print(equations((x, y)))
</code>```

Is it somehow possible to solve it using scipy.optimize.brentq with some interval, e.g. [-1,1]? How does the unpacking work in that case?

答:
As sascha suggested, constrained optimization is the easiest way to proceed. The least_squares method is convenient here: you can directly pass your equations to it, and it will minimize the sum of squares of its components.

```<code>from scipy.optimize import least_squares
res = least_squares(equations, (1, 1), bounds = ((-1, -1), (2, 2)))
</code>```

The structure of bounds is ((min_first_var, min_second_var), (max_first_var, max_second_var)), or similarly for more variables.

The resulting object has a bunch of fields, shown below. The most relevant ones are: res.cost is essentially zero, which means a root was found; and res.x says what the root is: [ 0.62034453,  1.83838393]

```<code> active_mask: array([0, 0])
        cost: 1.1745369255773682e-16
         fun: array([ -1.47918522e-08,   4.01353883e-09])
        grad: array([  5.00239352e-11,  -5.18964300e-08])
         jac: array([[ 1.        ,  3.67676787],
       [ 3.69795254,  0.62034452]])
     message: '`gtol` termination condition is satisfied.'
        nfev: 7
        njev: 7
  optimality: 8.3872972696740977e-09
      status: 1
     success: True
           x: array([ 0.62034453,  1.83838393])
</code>```

Body:
Some hypothetical example solving a nonlinear equation system with fsolve:

from scipy.optimize import fsolve
import math

def equations(p):
    x, y = p
    return (x+y**2-4, math.exp(x) + x*y - 3)

x, y =  fsolve(equations, (1, 1))

print(equations((x, y)))

Is it somehow possible to solve it using scipy.optimize.brentq with some interval, e.g. [-1,1]? How does the unpacking work in that case?

Body:
As sascha suggested, constrained optimization is the easiest way to proceed. The least_squares method is convenient here: you can directly pass your equations to it, and it will minimize the sum of squares of its components.

from scipy.optimize import least_squares
res = least_squares(equations, (1, 1), bounds = ((-1, -1), (2, 2)))

The structure of bounds is ((min_first_var, min_second_var), (max_first_var, max_second_var)), or similarly for more variables.

The resulting object has a bunch of fields, shown below. The most relevant ones are: res.cost is essentially zero, which means a root was found; and res.x says what the root is: [ 0.62034453,  1.83838393]

 active_mask: array([0, 0])
        cost: 1.1745369255773682e-16
         fun: array([ -1.47918522e-08,   4.01353883e-09])
        grad: array([  5.00239352e-11,  -5.18964300e-08])
         jac: array([[ 1.        ,  3.67676787],
       [ 3.69795254,  0.62034452]])
     message: '`gtol` termination condition is satisfied.'
        nfev: 7
        njev: 7
  optimality: 8.3872972696740977e-09
      status: 1
     success: True
           x: array([ 0.62034453,  1.83838393])


问:
2d array with parameter
I am trying to create a 2d array but I don't seem to be able to pass a value in the constructor.

For example

```<code>public class MyObj
{
    public string State {get; private set;}
    public MyObj(string s)
    {
         this.State = s;
    }
}
</code>```

And in another class

```<code>private MyObj[,] Obj;
private void Setup()
{
    this.Obj = new MyObj[5,5];
}
</code>```

When I review this.Obj the value of State is always null. I understand why but without looping over each item in the array (after it's created) and setting the State property (removing the private set) I'm not sure if I have other options?

Whilst I know the syntax is wrong, something like

```<code>this.Obj = new MyObj("default text for each item in array")[5,5,]
</code>```

答:
When you create an array of reference objects with new, each element is set to the default value of null. There is no syntax to pass the default element, so you need to fill the array manually using nested loops:

```<code>private void Setup() {
    this.Obj = new MyObj[5,5];
    int rows = codes.GetLength(0);
    int cols = codes.GetLength(1);
    for (var r = 0; r != rows ; r++) {
        for (var c = 0 ; c != cols ; c++) {
            Obj[r,c] = new MyObj("default text for each item in array");
        }
    }
}
</code>```

Title: 2d array with parameter

Body:
I am trying to create a 2d array but I don't seem to be able to pass a value in the constructor.

For example

public class MyObj
{
    public string State {get; private set;}
    public MyObj(string s)
    {
         this.State = s;
    }
}

And in another class

private MyObj[,] Obj;
private void Setup()
{
    this.Obj = new MyObj[5,5];
}

When I review this.Obj the value of State is always null. I understand why but without looping over each item in the array (after it's created) and setting the State property (removing the private set) I'm not sure if I have other options?

Whilst I know the syntax is wrong, something like

this.Obj = new MyObj("default text for each item in array")[5,5,]

Body:
When you create an array of reference objects with new, each element is set to the default value of null. There is no syntax to pass the default element, so you need to fill the array manually using nested loops:

private void Setup() {
    this.Obj = new MyObj[5,5];
    int rows = codes.GetLength(0);
    int cols = codes.GetLength(1);
    for (var r = 0; r != rows ; r++) {
        for (var c = 0 ; c != cols ; c++) {
            Obj[r,c] = new MyObj("default text for each item in array");
        }
    }
}


答:
Given that you're using this for a mask, you could simply add another axis to the underlying ndarray to allow for broadcasting. This should be somewhat faster, depending on the size of your DataFrame. </p>

```<code>(df[S].values < df.a.values[:,None]).any(1)
</code>```

Title: Boolean slicing by comparing one to many columns in pandas

Body:
How can i compare a column to all other columns and obtain a boolean series to slice the dataframe by using i loc?

import numpy as np
import pandas as pd
a = np.random.normal(1,10,(10,1))
b = np.random.normal(1,5,(10,1))
c = np.random.normal(1,5,(10,1))
d = np.random.normal(1,5,(10,1))

e = np.append(a,b, axis = 1)
e = np.append(e,c, axis = 1)
e = np.append(e,d, axis = 1)

df = pd.DataFrame(data = e, columns=['a','b','c','d'])

          a         b          c          d
0   4.043832 -1.672865  -0.401864   3.073481
1   4.828796 -0.830688   3.652347  -1.780346
2  13.055145  5.730707  -2.305093  -4.566279
3   6.589498 -0.525029  -1.077942  -3.850963
4   5.273932 -1.003112   0.393002  -0.415573
5  -7.872004 -2.506250   1.725281   6.676886
6  -4.797119  6.448990   0.254142  -7.374601
7   8.610763  8.075350  13.043584  12.768633
8 -10.871154  2.152322   2.093089  11.570059
9 -22.148239  1.493870   3.649696   2.455621

df.loc[df.a > df.b]

Will give the desired result, but only for a 1:1 comparison

        a         b          c          d
0   4.043832 -1.672865  -0.401864   3.073481
1   4.828796 -0.830688   3.652347  -1.780346
2  13.055145  5.730707  -2.305093  -4.566279
3   6.589498 -0.525029  -1.077942  -3.850963
4   5.273932 -1.003112   0.393002  -0.415573
7   8.610763  8.075350  13.043584  12.768633

My Approach was like this:

S = ['b','c','d']

(df.a > df[S]).any(axis = 1)

0    False
1    False
2    False
3    False
4    False
5    False
6    False
7    False
8    False
9    False
dtype: bool

But unfortunately, the series is somehow False for all rows. How can i solve this Problem?

Body:
Given that you're using this for a mask, you could simply add another axis to the underlying ndarray to allow for broadcasting. This should be somewhat faster, depending on the size of your DataFrame.

(df[S].values < df.a.values[:,None]).any(1)


问:
Replacing internal functions with testdouble.js?
Is it possible to td.replace an internal function in a node.js module when testing with testdouble.js?

The internal function consists of a DB call, so I do not want to test it.  I do however want to test that this function received the expected parameters.

For example, given a node.js module:

```<code>module.exports = { record: recordEvent }

recordEvent = (event) =>
    var dbModel = map(event);
    persist(dbModel);

var map = (event) =>
    // some code that transforms event to the db specific representation (testable)

var persist = (model) =>
    // some SQL insert/update code here (not testable)
</code>```

And the following test, that checks if persist gets the correct params:

```<code>recorder = require('event_recorder')
describe 'Event recorder module', ->
    it 'converts the event to a db model', ->

        var event = {...// mock event };
        var model = {...// mock model of the event };

        var persist = td.replace(recorder, 'persist')
        td.when(persist(model)).thenReturn(true)

        result = recorder.record(event)
        expected = true;

        result.should.be.equal(expected)
</code>```

However the test throws an error:

td.replace - No "persist" property was found

I understand why it has this error, its because the persist method is not public.  How else can I achieve this in testdouble?

答:
One option, as you insinuated, is to make the persist method public. Another option would be for persist to accept or make use of another function to perform the SQL query, and stub that function instead:

```<code>var executeQuery = td.function()

recorder.recordEvent(event, executeQuery)

td.verify(executeQuery('UPDATE ...'))
</code>```

Body:
Is it possible to td.replace an internal function in a node.js module when testing with testdouble.js?

The internal function consists of a DB call, so I do not want to test it.  I do however want to test that this function received the expected parameters.

For example, given a node.js module:

module.exports = { record: recordEvent }

recordEvent = (event) =>
    var dbModel = map(event);
    persist(dbModel);

var map = (event) =>
    // some code that transforms event to the db specific representation (testable)

var persist = (model) =>
    // some SQL insert/update code here (not testable)

And the following test, that checks if persist gets the correct params:

recorder = require('event_recorder')
describe 'Event recorder module', ->
    it 'converts the event to a db model', ->

        var event = {...// mock event };
        var model = {...// mock model of the event };

        var persist = td.replace(recorder, 'persist')
        td.when(persist(model)).thenReturn(true)

        result = recorder.record(event)
        expected = true;

        result.should.be.equal(expected)

However the test throws an error:

td.replace - No "persist" property was found

I understand why it has this error, its because the persist method is not public.  How else can I achieve this in testdouble?

Body:
One option, as you insinuated, is to make the persist method public. Another option would be for persist to accept or make use of another function to perform the SQL query, and stub that function instead:

var executeQuery = td.function()

recorder.recordEvent(event, executeQuery)

td.verify(executeQuery('UPDATE ...'))


问:
How to find all the paths in a undirected graph touching all the nodes of a given set
I have an undirected graph and i'd like to find all the possible paths in it connecting all the nodes of a given set.
Is it an NP problem? Is there an algorithm to doing it, or a good way to accomplish it?  I don't care about the order by which each paths touches the nodes in the set, i just need it to go through each of them.</p>

答:
It's called Hamiltonian Path Problem and it is NP-complete.

For detailed info: https://en.wikipedia.org/wiki/Hamiltonian_path_problem


问:
How to open a particular tab inside a modal
I have 2 buttons and each is responsible for opening a modal, however, this modal has 2 tabs for signup and sign in. I want that if a user clicks on signup button then after the modal opens the signup tab should be active and if a user clicks on sign in button then after the modal opens the sign in tab should be active

The code of the button is

```<code><button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg">SIGN UP</button>
<button type="button" class="btn btn-secondary" data-toggle="modal" data-target=".bd-example-modal-lg_two">SIGN IN</button>
</code>```

The code of modal is

```<code><div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <ul class="nav nav-tabs" >
                    <li class="nav-item col ">
                        <a class="nav-link active" href="#signup" data-toggle="tab" >Sign up</a>
                    </li>
                    <li class="nav-item col ">
                        <a class="nav-link" href="#signin" data-toggle="tab" >Sign in</a>
                    </li>
                </ul>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="container">
                    <div class="row">
                        <div class="col">
                            <div class="tab-content">
                                <div class="tab-pane active" id="signup">
                                    signup box
                                </div>
                                <div class="tab-pane" id="signin">
                                    signin box
                                </div>
                            </div>
                        </div>
                        <div class="col" id="social" >
                            Content
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
 </div>
</code>```

Can anyone please tell me how to do this

答:
You'll have to do it with Javascript.  Here's one way.  Working JSFiddle.

First, get rid of the data-toggle="modal" data-target=".bd-example-modal-lg" on both buttons.  You'll need to run your tab-targeting Javascript when you open the modal, and you can easily do that if you manually open the modal using the modal show method, rather than via the data attributes.

Next, in their place, add something to each button to identify which tab it targets - for eg a data attribute, with the id of your tabs:

```<code><button type="button" class="btn btn-primary" data-tab="signup">SIGN UP</button>
</code>```

Last, add some Javascript to do the work:

```<code>// Add an event handler to fire when our buttons are clicked
$('button').on('click', function() {
    // Find which button was clicked, so we know which tab to target
    var tabTarget = $(this).data('tab');

    // Manually show the modal, since we are not doing it via data-toggle now
    $('.bd-example-modal-lg').modal('show');

    // Now show the selected tab
    $('.nav-tabs a[href="#' + tabTarget + '"]').tab('show');
});
</code>```

Note that as the docs describe, you target the tab with the a link which opens it, not the div of the tab itself.

Body:
I have 2 buttons and each is responsible for opening a modal, however, this modal has 2 tabs for signup and sign in. I want that if a user clicks on signup button then after the modal opens the signup tab should be active and if a user clicks on sign in button then after the modal opens the sign in tab should be active

The code of the button is

<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg">SIGN UP</button>
<button type="button" class="btn btn-secondary" data-toggle="modal" data-target=".bd-example-modal-lg_two">SIGN IN</button>

The code of modal is

                        Sign up

                        Sign in

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                                    signup box

                                    signin box

                            Content

Can anyone please tell me how to do this

Body:
You'll have to do it with Javascript.  Here's one way.  Working JSFiddle.

First, get rid of the data-toggle="modal" data-target=".bd-example-modal-lg" on both buttons.  You'll need to run your tab-targeting Javascript when you open the modal, and you can easily do that if you manually open the modal using the modal show method, rather than via the data attributes.

Next, in their place, add something to each button to identify which tab it targets - for eg a data attribute, with the id of your tabs:

<button type="button" class="btn btn-primary" data-tab="signup">SIGN UP</button>

Last, add some Javascript to do the work:

// Add an event handler to fire when our buttons are clicked
$('button').on('click', function() {
    // Find which button was clicked, so we know which tab to target
    var tabTarget = $(this).data('tab');

    // Manually show the modal, since we are not doing it via data-toggle now
    $('.bd-example-modal-lg').modal('show');

    // Now show the selected tab
    $('.nav-tabs a[href="#' + tabTarget + '"]').tab('show');
});

Note that as the docs describe, you target the tab with the a link which opens it, not the div of the tab itself.


问:
How to run MSBuild from Powershell without spawning msbuild.exe process?
I am considering running MSBuild from a Powershell script by tapping directly to the MSBuild assemblies (as opposed to looking up MSBuild install path and starting msbuild.exe as a child process).

Has anyone done this? What would be the simplest, most straightforward way to run the build? Are there any pros/cons to either technique you'd like to point out? (I'm especially interested in any issues that might arise from running msbuild in the same process/appdomain as the rest of the script).

Currently my thinking is something along these lines:

```<code>[void][System.Reflection.Assembly]::Load('Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][Microsoft.Build.BuildEngine.Engine]::GlobalEngine.BuildProjectFile("path/main.proj")
</code>```

答:
I would very highly suggest looking at PSake.

Let me quote a portion of that page:

Remember that psake is syntactic sugar around PowerShell. So anything you can do in PowerShell, you can do in psake. That means that you can run MSBuild, NAnt, or other scripts. There is no need to completely replace your current build system. You can use psake to automate and extend it!

psake automatically adds the appropriate version of .NET Framework to its path. So you can access MSBuild, csc.exe, vbc.exe, or any other tools installed in $env:windir\Microsoft.NET\Framework\$version\ without the fully qualified path.

OwnerDisplayName: Milan Gardian

ContentLicense: CC BY-SA 2.5

Body:
I am considering running MSBuild from a Powershell script by tapping directly to the MSBuild assemblies (as opposed to looking up MSBuild install path and starting msbuild.exe as a child process).

Has anyone done this? What would be the simplest, most straightforward way to run the build? Are there any pros/cons to either technique you'd like to point out? (I'm especially interested in any issues that might arise from running msbuild in the same process/appdomain as the rest of the script).

Currently my thinking is something along these lines:

[void][System.Reflection.Assembly]::Load('Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][Microsoft.Build.BuildEngine.Engine]::GlobalEngine.BuildProjectFile("path/main.proj")

OwnerDisplayName: EBGreen

LastEditorDisplayName: EBGreen


问:
C# using HttpListener and Request.ServerVariables on Windows Forms or Console
Project Objectives:

Create a local Proxy Judge using a Console or Windows Form application for debugging and testing connections.

Project must request and receive proxy ServerVariables to display on client side.

Parse IPAddress and return Anonymity state.

Implement Basic Athentifcation Scheme.

Project must not use Scripts for functionality (e.g) PHP, Perl, Asp, etc.

Multi-platform Compatible (possibilty)

Questions:

Is it possible to use Request.ServerVariables on a local Windows or Console Application or is it ASP specific?

If this method is ASP specific is there another way to request the ServerVariables from a browser session?

If the method above is possible what is the proper approach for achieving this functionality?

What is a good example for verifing/Setting the Basic Authentification Scheme here? Like setting the password and user to be used and so on.

References used:

http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx
http://www.java2s.com/Code/CSharpAPI/System.Net/HttpListenerContextResponseStatusCode.htm
http://en.cship.org/wiki/ProxyJudge

Example Code:

```<code>using System.IO;
using System.Net;
using System.Web;
using System.Collections.Specialized;

namespace IPJudge
{
    public class IPJudgeClass : IHttpModule
    {
        public static void Main()
        {
            using (HttpListener listener = new HttpListener())
            {
                listener.AuthenticationSchemes = AuthenticationSchemes.None;
                listener.Prefixes.Add("http://localhost:8080/");
                //listener.Prefixes.Add("https://localhost/");
                listener.Start();

                HttpListenerContext ctx = listener.GetContext();
                ctx.Response.StatusCode = 200;
                string name = ctx.Request.QueryString["name"];

                StreamWriter writer = new StreamWriter(ctx.Response.OutputStream);
                writer.WriteLine("<P>Hello, {0}</P>", name);
                writer.WriteLine("<ul>");
                foreach (string header in ctx.Request.Headers.Keys)
                {
                    writer.WriteLine("<li><b>{0}:</b> {1}</li>", header, ctx.Request.Headers[header]);
                }
                writer.WriteLine("</ul>");

                writer.Close();
                ctx.Response.Close();
                listener.Stop();
            }
        }

        public void Init(HttpApplication app)
        {

            app.AcquireRequestState += new System.EventHandler(app_AcquireRequestState);
            app.PostAcquireRequestState += new System.EventHandler(app_PostAcquireRequestState);
        }

        public void app_AcquireRequestState(object o, System.EventArgs e)
        {
            HttpApplication httpApp = (HttpApplication)o;
            HttpContext ctx = HttpContext.Current;
            ctx.Response.Write(" Executing AcquireRequestState ");
            ctx.Response.Close();
        }

        public void Dispose()
        {
            // TODO:
            // Add code to clean up the
            // instance variables of a module.
        }

        public void app_PostAcquireRequestState(object o, System.EventArgs e)
        {
            HttpApplication httpApp = (HttpApplication)o;
            HttpContext ctx = HttpContext.Current;

            string remotehost  = ctx.Request.ServerVariables["REMOTE_ADDR"];
            string httpuseragent = ctx.Request.ServerVariables["HTTP_USER_AGENT"];
            string requstmethod = ctx.Request.ServerVariables["REQUEST_METHOD"];
            string httpreferer = ctx.Request.ServerVariables["HTTP_REFERER"];
            string HTTPXFORWARDEDFOR = ctx.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            string HTTPFORWARDEDFOR = ctx.Request.ServerVariables["HTTP_FORWARDED_FOR"];
            string HTTPXFORWARDED = ctx.Request.ServerVariables["HTTP_X_FORWARDED"];

            ctx.Response.Write("<P>REMOTE_ADDR: " + remotehost + "</P>");
            ctx.Response.Write("<P>HTTP_USER_AGENT: " + httpuseragent + "</P>");
            ctx.Response.Write("<P>REQUEST_METHOD: " + httpuseragent + "</P>");
            ctx.Response.Write("<P>HTTP_REFERER: " + httpreferer + "</P>");
            ctx.Response.Write("<P>HTTP_X_FORWARDED_FOR: " + httpreferer + "</P>");
            ctx.Response.Write("<P>HTTP_FORWARDED_FOR: " + httpreferer + "</P>");
            ctx.Response.Write("<P>HTTP_X_FORWARDED: " + httpreferer + "</P>");
            ctx.Response.Close();
        }
    }
}
</code>```

答:
Your code is merging ASP.NET logic and Application logic, which can't/shouldn't be done.

A IHttpModule is run by IIS in a ASP.NET WEB application

A Main method is run by a console application

Questions:

Request.ServerVariables can only be accessed on the web server

The method that you have (app_PostAcquireRequestState) where you are outputing the variables to the response stream, is how i do it. But not normally in a HttpModule or in that particular method. Try to output the variables towards the end of the ASP.NET pipeline.

You could turn on the tracing in web.config <trace>, that should output some of the variables you require.

http://msdn.microsoft.com/en-us/library/6915t83k.aspx

Not sure what you are talking about here, do you have some example code.

Body:
Project Objectives:

Create a local Proxy Judge using a Console or Windows Form application for debugging and testing connections.

Project must request and receive proxy ServerVariables to display on client side.

Parse IPAddress and return Anonymity state.

Implement Basic Athentifcation Scheme.

Project must not use Scripts for functionality (e.g) PHP, Perl, Asp, etc.

Multi-platform Compatible (possibilty)

Questions:

Is it possible to use Request.ServerVariables on a local Windows or Console Application or is it ASP specific?

If this method is ASP specific is there another way to request the ServerVariables from a browser session?

If the method above is possible what is the proper approach for achieving this functionality?

What is a good example for verifing/Setting the Basic Authentification Scheme here? Like setting the password and user to be used and so on.

References used:

http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx
http://www.java2s.com/Code/CSharpAPI/System.Net/HttpListenerContextResponseStatusCode.htm
http://en.cship.org/wiki/ProxyJudge

Example Code:

using System.IO;
using System.Net;
using System.Web;
using System.Collections.Specialized;

namespace IPJudge
{
    public class IPJudgeClass : IHttpModule
    {
        public static void Main()
        {
            using (HttpListener listener = new HttpListener())
            {
                listener.AuthenticationSchemes = AuthenticationSchemes.None;
                listener.Prefixes.Add("http://localhost:8080/");
                //listener.Prefixes.Add("https://localhost/");
                listener.Start();

                HttpListenerContext ctx = listener.GetContext();
                ctx.Response.StatusCode = 200;
                string name = ctx.Request.QueryString["name"];

                StreamWriter writer = new StreamWriter(ctx.Response.OutputStream);
                writer.WriteLine("
Hello, {0}
", name);
                writer.WriteLine("
");
                foreach (string header in ctx.Request.Headers.Keys)
                {
                    writer.WriteLine("
{0}: {1}
", header, ctx.Request.Headers[header]);
                }
                writer.WriteLine("
");

                writer.Close();
                ctx.Response.Close();
                listener.Stop();
            }
        }

        public void Init(HttpApplication app)
        {

            app.AcquireRequestState += new System.EventHandler(app_AcquireRequestState);
            app.PostAcquireRequestState += new System.EventHandler(app_PostAcquireRequestState);
        }

        public void app_AcquireRequestState(object o, System.EventArgs e)
        {
            HttpApplication httpApp = (HttpApplication)o;
            HttpContext ctx = HttpContext.Current;
            ctx.Response.Write(" Executing AcquireRequestState ");
            ctx.Response.Close();
        }

        public void Dispose()
        {
            // TODO:
            // Add code to clean up the
            // instance variables of a module.
        }

        public void app_PostAcquireRequestState(object o, System.EventArgs e)
        {
            HttpApplication httpApp = (HttpApplication)o;
            HttpContext ctx = HttpContext.Current;

            string remotehost  = ctx.Request.ServerVariables["REMOTE_ADDR"];
            string httpuseragent = ctx.Request.ServerVariables["HTTP_USER_AGENT"];
            string requstmethod = ctx.Request.ServerVariables["REQUEST_METHOD"];
            string httpreferer = ctx.Request.ServerVariables["HTTP_REFERER"];
            string HTTPXFORWARDEDFOR = ctx.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            string HTTPFORWARDEDFOR = ctx.Request.ServerVariables["HTTP_FORWARDED_FOR"];
            string HTTPXFORWARDED = ctx.Request.ServerVariables["HTTP_X_FORWARDED"];

            ctx.Response.Write("
REMOTE_ADDR: " + remotehost + "
");
            ctx.Response.Write("
HTTP_USER_AGENT: " + httpuseragent + "
");
            ctx.Response.Write("
REQUEST_METHOD: " + httpuseragent + "
");
            ctx.Response.Write("
HTTP_REFERER: " + httpreferer + "
");
            ctx.Response.Write("
HTTP_X_FORWARDED_FOR: " + httpreferer + "
");
            ctx.Response.Write("
HTTP_FORWARDED_FOR: " + httpreferer + "
");
            ctx.Response.Write("
HTTP_X_FORWARDED: " + httpreferer + "
");
            ctx.Response.Close();
        }
    }
}


问:
How to add auto increment column to csv Storage Engine type mysql table?
I have created a MySQL table which stored in CSV storage engine.
I want to create an auto increment column.But it isn't support for csv table.

Is there any way to create auto increment column using triggers?

答:
The CSV storage engine also does not support indexes, so it would cause incredibly bad performance if you wanted to write a trigger to calculate the next id by SELECT MAX(id)+1... because every row insert would cause a table-scan.

If you need an auto-increment column, you must convert the table to InnoDB while adding the auto-increment column.

```<code>ALTER TABLE MyTable
  ADD COLUMN id BIGINT AUTO_INCREMENT PRIMARY KEY FIRST,
  ENGINE=InnoDB;
</code>```

Body:
The CSV storage engine also does not support indexes, so it would cause incredibly bad performance if you wanted to write a trigger to calculate the next id by SELECT MAX(id)+1... because every row insert would cause a table-scan.

If you need an auto-increment column, you must convert the table to InnoDB while adding the auto-increment column.

ALTER TABLE MyTable
  ADD COLUMN id BIGINT AUTO_INCREMENT PRIMARY KEY FIRST,
  ENGINE=InnoDB;


问:
What is the best practice for implementing low cardinality searches in Cassandra
Assume that I have the following table CQL (well a fragment of the table): </p>

```<code>CREATE TABLE order (
  order_id UUID PRIMARY KEY,
  placed timestamp,
  status text,
)
</code>```

<p>Now if status could be one of PLACED, SHIPPED, or DELIVERED as an enum, I want to find all of the orders that are in PLACED status to process them. Given there are millions of orders and all orders are ultimately ending up in DELIVERED status a materialized view doesn't feel like the right solution to the problem. I am wondering what ideas there are to solve the problem of this low cardinality index without passing through the whole data set. Ideas? </p>

答:
I would recommend a table like

```<code>CREATE TABLE order_by_status (
  order_id UUID,
  placed timestamp,
  status text,
  PRIMARY KEY ((status), order_id)
)
</code>```

Then you can iterate through the query to SELECT * FROM order_by_status WHERE status = 'PLACED';. Millions shouldnt be too much of an issue but it would be good to prevent it from getting too large by partitioning by some date window.

```<code>CREATE TABLE order_by_status (
  order_id UUID,
  placed timestamp,
  bucket text,
  status text,
  PRIMARY KEY ((status, bucket), order_id)
)
</code>```

Where bucket is a string generated from timestamp like 2017-10 from the YYYY-MM. You might wanna stay away from MV's for a little bit yet, it has some bugs in current version. I would also recommend against secondary indexes for this model, using a 2nd table and issuing inserts to both is going to be your best solution.

Body:
Assume that I have the following table CQL (well a fragment of the table):

CREATE TABLE order (
  order_id UUID PRIMARY KEY,
  placed timestamp,
  status text,
)

Now if status could be one of PLACED, SHIPPED, or DELIVERED as an enum, I want to find all of the orders that are in PLACED status to process them. Given there are millions of orders and all orders are ultimately ending up in DELIVERED status a materialized view doesn't feel like the right solution to the problem. I am wondering what ideas there are to solve the problem of this low cardinality index without passing through the whole data set. Ideas?

Body:
I would recommend a table like

CREATE TABLE order_by_status (
  order_id UUID,
  placed timestamp,
  status text,
  PRIMARY KEY ((status), order_id)
)

Then you can iterate through the query to SELECT * FROM order_by_status WHERE status = 'PLACED';. Millions shouldnt be too much of an issue but it would be good to prevent it from getting too large by partitioning by some date window.

CREATE TABLE order_by_status (
  order_id UUID,
  placed timestamp,
  bucket text,
  status text,
  PRIMARY KEY ((status, bucket), order_id)
)

Where bucket is a string generated from timestamp like 2017-10 from the YYYY-MM. You might wanna stay away from MV's for a little bit yet, it has some bugs in current version. I would also recommend against secondary indexes for this model, using a 2nd table and issuing inserts to both is going to be your best solution.


问:
how to change devextreme data grid boolean filter labels
The status field (last row), we want the filter options to say Active and Inactive instead of true false. There's a coding method to do this but we're creating the table using the template. I feel like this would be super easy to do I just don't see it in the documentation.

```<code>      <dxi-column dataField="TruckNumber" caption="Truck #" alignment="left"></dxi-column>
      <dxi-column dataField="PlateNumber" caption="License Plate #" alignment="left"></dxi-column>
      <dxi-column dataField="Phone" dataType="string" alignment="left"></dxi-column>
      <dxi-column dataField="Status" alignment="center"></dxi-column>
</code>```

angular 4.4.6

答:
You can use trueText and falseText options:</p>

```<code><dxi-column dataField="Status" trueText="Active" falseText="Inactive" alignment="center"></dxi-column>
</code>```

Body:
The status field (last row), we want the filter options to say Active and Inactive instead of true false. There's a coding method to do this but we're creating the table using the template. I feel like this would be super easy to do I just don't see it in the documentation.

      <dxi-column dataField="TruckNumber" caption="Truck #" alignment="left"></dxi-column>
      <dxi-column dataField="PlateNumber" caption="License Plate #" alignment="left"></dxi-column>
      <dxi-column dataField="Phone" dataType="string" alignment="left"></dxi-column>
      <dxi-column dataField="Status" alignment="center"></dxi-column>

angular 4.4.6

Body:
You can use trueText and falseText options:

<dxi-column dataField="Status" trueText="Active" falseText="Inactive" alignment="center"></dxi-column>


问:
Angular 4 file upload in form post
Hi In a form I have several HTML controls and one file upload control. I’m filling all HTML controls with some text as well as one file for file upload.now I need to post all these data and file to my api.Can any one help me how to do this in angular 4</p>

答:
You can use ng2-file-upload on Angular side.
   In your angular component, add

```<code> this.uploadUrl = environment.baseApiUrl + '/api/file/Upload';
   this.uploader = new FileUploader({ url: this.uploadUrl });

   this.uploader.onBeforeUploadItem = (item) =>{

                var formData = [{‘your data’:’your data value’}];
                item.formData.push({ fileData: formData});

            };
</code>```

Then in web api, add a controller like below:

```<code>[RoutePrefix("api/file")]
    public class FileUploadController : ApiController    {
        [HttpPost]
        [Route("upload")]
        public async Task<HttpResponseMessage> FileUpload()
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "Media content error");
            }

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            if(provider!=null && provider.Contents.Count>1)
            {
                //Your form data;
                var fileDataBuffer = await provider.Contents[0].ReadAsByteArrayAsync();
                 String fileDataJson = System.Text.Encoding.Default.GetString(fileDataBuffer);

               //Your uploaded file
               var file = provider.Contents[1];
               var fileBuffer = await file.ReadAsByteArrayAsync();

            }
            else
            {

                return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "Invalid file");
            }

        }

    }
</code>```

Title: Angular 4 file upload in form post

Body:
You can use ng2-file-upload on Angular side.
   In your angular component, add

 this.uploadUrl = environment.baseApiUrl + '/api/file/Upload';
   this.uploader = new FileUploader({ url: this.uploadUrl });

   this.uploader.onBeforeUploadItem = (item) =>{

                var formData = [{‘your data’:’your data value’}];
                item.formData.push({ fileData: formData});

            };

Then in web api, add a controller like below:

[RoutePrefix("api/file")]
    public class FileUploadController : ApiController    {
        [HttpPost]
        [Route("upload")]
        public async Task<HttpResponseMessage> FileUpload()
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "Media content error");
            }

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            if(provider!=null && provider.Contents.Count>1)
            {
                //Your form data;
                var fileDataBuffer = await provider.Contents[0].ReadAsByteArrayAsync();
                 String fileDataJson = System.Text.Encoding.Default.GetString(fileDataBuffer);

               //Your uploaded file
               var file = provider.Contents[1];
               var fileBuffer = await file.ReadAsByteArrayAsync();

            }
            else
            {

                return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "Invalid file");
            }

        }

    }


答:
In this particular case, adding braces:

   //     V-- brace
     else {
           printf("Enter a number between 0 and 10\n");
         scanf("%d", &j);
     }
   //^-- brace

shoud solve the problem you described in your message.  Without the braces, only the first thing after the else is part of the conditional.  Therefore, scanf was always being executed, whether or not the number was between 0 and 10.

I also agree with the other answers --- zero-indexing and for-loop bounds are important.  Edit  Specifically, in C arrays the first element is 0.  Thus you are better off to number your tests 0..9 instead of 1..10.  You should also name your variables what they are, thus:

```<code>int which_test;
for (which_test = 0; which_test < 10; ++which_test)
</code>```

Title: Getting asked twice to insert integer

Body:
I have some homework to do for the University, and since I'm a beginner I don't know how to code yet. So, there are 10 tests with the grade of each being between 0 and 10. I have to make sure that I don't get any negative number or a number greater than 10. while running the code I have to put 2 numbers in order to proceed to the next one, when, I clearly want just the one saved to A[i]. I hope you understand even though I can't even explain the problem. :)

#include<stdio.h>

int main()
{
    int A[10];
    int i, j;
    for ( i = 1; i<11; i++)
    {
        printf("Enter %d grade \n", i);
        scanf("%d", &j);
        if (j<=10 && j>=0)
         A[i] = j;
        else
         printf("Enter a number between 0 and 10\n");
         scanf("%d", &j);
    }
}

Body:
In this particular case, adding braces:

   //     V-- brace
     else {
           printf("Enter a number between 0 and 10\n");
         scanf("%d", &j);
     }
   //^-- brace

shoud solve the problem you described in your message.  Without the braces, only the first thing after the else is part of the conditional.  Therefore, scanf was always being executed, whether or not the number was between 0 and 10.

I also agree with the other answers --- zero-indexing and for-loop bounds are important.  Edit  Specifically, in C arrays the first element is 0.  Thus you are better off to number your tests 0..9 instead of 1..10.  You should also name your variables what they are, thus:

int which_test;
for (which_test = 0; which_test < 10; ++which_test)


问:
Batch file command to select newest folder except if specific name
We have a batch file to create a variable from the folder name of the newest folder created in a specific location. As newer versions of this software is released the version number (folder name also) i.e. 10.0, 10.1, 10.2, 10.3 folder is created in this directory. Until now this has worked without hitch, however in the last update they decided to add a folder called Install in this same directory.

Is it possible to change the following script to ignore the Install folder and select the newest created folder name instead:

```<code>SET TABVER="C:\Program Files\Tableau\Tableau Server\"
FOR /F "delims=" %%i IN ('dir %TABVER% /b /ad-h /t:c /od') DO SET VERSION=%%i
SET TABCMD="C:\Program Files\Tableau\Tableau Server\%VERSION%\bin\tabcmd.exe"
</code>```

答:
This batch code could be used:

```<code>set "TABVER=C:\Program Files\Tableau\Tableau Server\"
for /F "delims=" %%I in ('dir "%TABVER%" /B /AD-H /T:C /O-D 2^>nul') do if /I not "%%I" == "Install" set "VERSION=%%I" & goto FoundVersion

echo Error: There is no version subfolder in probably not already existing folder:
echo/
echo        %TABVER%
echo/
pause
goto :EOF

:FoundVersion
set TABCMD="%TABVER%%VERSION%\bin\tabcmd.exe"
rem Other commands using TABCMD
</code>```

The DIR option /od is modified to /O-D to get the list of subdirectories in reverse order output by command DIR with newest directory first and oldest directory last.

The additional IF command compares case-insensitive the current directory name with the string Install. Only if the directory name is not Install the directory name is assigned to environment variable VERSION and the loop is exited without processing all other directory names with a jump to label FoundVersion.

I added an error output in case of C:\Program Files\Tableau\Tableau Server does not exist at all, contains no subdirectories or contains just Install and with halting batch file execution until user presses any key and then exiting the batch file processing.

Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.

See also How to set environment variables with spaces? In general it is better to use the command line set "variable=value" and reference the environment variable with "%variable%" instead of using set variable="value" and reference the environment variable with just %variable%. Look on %TABVER% references why it makes sense not having assigned a folder path with the double quotes to an environment variable.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

dir /?

for /?

goto /?

if /?

pause /?

rem /?

set /?

Read also single line with multiple commands using Windows batch file and Where does GOTO :EOF return to?

Body:
We have a batch file to create a variable from the folder name of the newest folder created in a specific location. As newer versions of this software is released the version number (folder name also) i.e. 10.0, 10.1, 10.2, 10.3 folder is created in this directory. Until now this has worked without hitch, however in the last update they decided to add a folder called Install in this same directory.

Is it possible to change the following script to ignore the Install folder and select the newest created folder name instead:

SET TABVER="C:\Program Files\Tableau\Tableau Server\"
FOR /F "delims=" %%i IN ('dir %TABVER% /b /ad-h /t:c /od') DO SET VERSION=%%i
SET TABCMD="C:\Program Files\Tableau\Tableau Server\%VERSION%\bin\tabcmd.exe"

Body:
This batch code could be used:

set "TABVER=C:\Program Files\Tableau\Tableau Server\"
for /F "delims=" %%I in ('dir "%TABVER%" /B /AD-H /T:C /O-D 2^>nul') do if /I not "%%I" == "Install" set "VERSION=%%I" & goto FoundVersion

echo Error: There is no version subfolder in probably not already existing folder:
echo/
echo        %TABVER%
echo/
pause
goto :EOF

:FoundVersion
set TABCMD="%TABVER%%VERSION%\bin\tabcmd.exe"
rem Other commands using TABCMD

The DIR option /od is modified to /O-D to get the list of subdirectories in reverse order output by command DIR with newest directory first and oldest directory last.

The additional IF command compares case-insensitive the current directory name with the string Install. Only if the directory name is not Install the directory name is assigned to environment variable VERSION and the loop is exited without processing all other directory names with a jump to label FoundVersion.

I added an error output in case of C:\Program Files\Tableau\Tableau Server does not exist at all, contains no subdirectories or contains just Install and with halting batch file execution until user presses any key and then exiting the batch file processing.

Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.

See also How to set environment variables with spaces? In general it is better to use the command line set "variable=value" and reference the environment variable with "%variable%" instead of using set variable="value" and reference the environment variable with just %variable%. Look on %TABVER% references why it makes sense not having assigned a folder path with the double quotes to an environment variable.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

dir /?

for /?

goto /?

if /?

pause /?

rem /?

set /?

Read also single line with multiple commands using Windows batch file and Where does GOTO :EOF return to?

ContentLicense: CC BY-SA 4.0


问:
Find largest sum of 3 numbers which is also divisable by 3
How to find largest sum of 3 numbers which is also divisable by 3?

Examples:

Input: [1, 15, 4, 7, 2]

Output: [15, 7, 2] (In that order)

Input: [1, 2, 4, 7]

Output: [1, 4, 7] (In that order)

I came up only with this:

```<code>function largestSum(arr) {
    let max = -1;
    let nums;

    for (let i = 0; i < arr.length; i++)
        for (let j = i + 1; j < arr.length; j++)
            for (let k = j + 1; k < arr.length; k++)
                if ((arr[i] + arr[j] + arr[k]) % 3 === 0 && arr[i] + arr[j] + arr[k] > max)
                    nums = [arr[i], arr[j], arr[k]], max = arr[i] + arr[j] + arr[k];

    return nums;
}
</code>```

But, isn't it better option here (with better efficiency)?

答:
If you sort the numbers first in descending order, then find the first solution which is divisible by three, this will be the largest value.

At it's worst, it's worse than your solution as it does everything yours does as well as sorting BUT at it's best it could be one sort and one test.

It's using the greedy algorithm.

Body:
How to find largest sum of 3 numbers which is also divisable by 3?

Examples:

Input: [1, 15, 4, 7, 2]

Output: [15, 7, 2] (In that order)

Input: [1, 2, 4, 7]

Output: [1, 4, 7] (In that order)

I came up only with this:

function largestSum(arr) {
    let max = -1;
    let nums;

    for (let i = 0; i < arr.length; i++)
        for (let j = i + 1; j < arr.length; j++)
            for (let k = j + 1; k < arr.length; k++)
                if ((arr[i] + arr[j] + arr[k]) % 3 === 0 && arr[i] + arr[j] + arr[k] > max)
                    nums = [arr[i], arr[j], arr[k]], max = arr[i] + arr[j] + arr[k];

    return nums;
}

But, isn't it better option here (with better efficiency)?


答:
A[i] = j; invoked undefined behaviour because C does not check array bound.

C11 J.2 Undefined behavior

Addition or subtraction of a pointer into, or just beyond, an array object and an integer type produces a result that points just beyond
  the array object and is used as the operand of a unary * operator that
  is evaluated (6.5.6).

In your code size of array A is 10*sizeof(int) bytes. So, you can store array elements 0 to 9.

Title: Getting asked twice to insert integer


问:
How to make a Ruby string safe for a filesystem?
I have user entries as filenames. Of course this is not a good idea, so I want to drop everything except [a-z], [A-Z], [0-9], _ and -.

For instance:

```<code>my§document$is°°   very&interesting___thisIs%nice445.doc.pdf
</code>```

should become

```<code>my_document_is_____very_interesting___thisIs_nice445_doc.pdf
</code>```

and then ideally

```<code>my_document_is_very_interesting_thisIs_nice445_doc.pdf
</code>```

Is there a nice and elegant way for doing this?

答:
For Rails I found myself wanting to keep any file extensions but using parameterize for the remainder of the characters:

```<code>filename = "my§doc$is°° very&itng___thsIs%nie445.doc.pdf"
cleaned = filename.split(".").map(&:parameterize).join(".")
</code>```

Implementation details and ideas see source: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/inflector/transliterate.rb

```<code>def parameterize(string, separator: "-", preserve_case: false)
  # Turn unwanted chars into the separator.
  parameterized_string.gsub!(/[^a-z0-9\-_]+/i, separator)
  #... some more stuff
end
</code>```

Body:
I have user entries as filenames. Of course this is not a good idea, so I want to drop everything except [a-z], [A-Z], [0-9], _ and -.

For instance:

my§document$is°°   very&interesting___thisIs%nice445.doc.pdf

should become

my_document_is_____very_interesting___thisIs_nice445_doc.pdf

and then ideally

my_document_is_very_interesting_thisIs_nice445_doc.pdf

Is there a nice and elegant way for doing this?

Body:
For Rails I found myself wanting to keep any file extensions but using parameterize for the remainder of the characters:

filename = "my§doc$is°° very&itng___thsIs%nie445.doc.pdf"
cleaned = filename.split(".").map(&:parameterize).join(".")

Implementation details and ideas see source: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/inflector/transliterate.rb

def parameterize(string, separator: "-", preserve_case: false)
  # Turn unwanted chars into the separator.
  parameterized_string.gsub!(/[^a-z0-9\-_]+/i, separator)
  #... some more stuff
end


问:
Java Error: NullPointerException due to missing Constructor(s)
I'm trying to access a method within another class, but I already have some constructors in said class which is throwing up an error when I try to create an instance in another class.

EDIT: I know I need to fill in a constructor, but I don't know what to put in it. Do I create another JFrame in the ArrayControl class or what?

This is the error I get when I run it:

```<code>Exception in thread "main" java.lang.NullPointerException
at Position.ArrayControl.updatePosition(ArrayControl.java:10)
at Display.Display.<init>(Display.java:39)
at Main.Game.<init>(Game.java:19)
at Main.Launch.main(Launch.java:6)
</code>```

This is where the error happens:

```<code>public class ArrayControl{
 Display display = new Display(); // Error here asking for a JFrame or String, int, int

public void updatePosition(String name, int x, int y){
    display.updateGrid(name, x, y, display.getGrid());
    }
}
</code>```

The "Display" class I'm trying to access:

```<code>public class Display {
public JPanel panel = new JPanel();
public ArrayControl arrayC = new ArrayControl();
public JFrame frame;
JLabel[][] grid= new JLabel[5][5];

public JFrame getFrame() {
    return frame;
}

public Display(JFrame frame){
    this.frame = frame;
}

private String title;
private int width, height;
Color sky = new Color(137, 182, 255);
Color enemyPortal = new Color(154, 91, 193);

//Creating a display function that takes in a title, the width (pixels) and height (pixels)
public Display(String title, int width, int height){
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
    arrayC.updatePosition("Test", 2, 3);
}
</code>```

I realise this may be a silly question and the answer is glaring me in the face, but all help is appreciated.
Thank you.

答:
As you identified, the error is here in your ArrayControl class:

```<code>Display display = new Display();
</code>```

The class Display does not have a parameterless constructor.

However, as ascertained from the comments, even fixing this will not fix your program.

Currently your ArrayControl class is constructing a new instance of Display (erroneously), and trying to update on the instance of Display stored in the field display in your ArrayControl class. This is not what you want to do, rather you want to update the instance of Display that instanstiated the ArrayControl object.

To achieve this you need to pass the current instance of Display to ArrayControl for it to use. For example (simplified):

```<code>public class Display {
    private ArrayControl arrayControl;

    public Display() {
        // Pass this instance of Display to ArrayControl to use
        arrayControl = new ArrayControl(this);
        arrayControl.updatePosition("Test", 2, 3);
    }

    public void updateGrid(String name, int x, int y) {
        // Do update grid stuff
    }

}

public class ArrayControl {

    private Display display;

    public ArrayControl(Display display) {
        this.display = display; // assign instance of Display to the field display
    }

    public void updatePosition(String name, int x, int y) {
        display.updateGrid(name, x, y);
        // I'm not sure why you want to pass the display back to the
        // Display class as in your example so I removed it
    }

}
</code>```

I'm not sure what your larger goal is, and why there is an ArrayControl class. I assume there is more to it, removed from the question.

Body:
I'm trying to access a method within another class, but I already have some constructors in said class which is throwing up an error when I try to create an instance in another class.

EDIT: I know I need to fill in a constructor, but I don't know what to put in it. Do I create another JFrame in the ArrayControl class or what?

This is the error I get when I run it:

Exception in thread "main" java.lang.NullPointerException
at Position.ArrayControl.updatePosition(ArrayControl.java:10)
at Display.Display.<init>(Display.java:39)
at Main.Game.<init>(Game.java:19)
at Main.Launch.main(Launch.java:6)

This is where the error happens:

public class ArrayControl{
 Display display = new Display(); // Error here asking for a JFrame or String, int, int

public void updatePosition(String name, int x, int y){
    display.updateGrid(name, x, y, display.getGrid());
    }
}

The "Display" class I'm trying to access:

public class Display {
public JPanel panel = new JPanel();
public ArrayControl arrayC = new ArrayControl();
public JFrame frame;
JLabel[][] grid= new JLabel[5][5];

public JFrame getFrame() {
    return frame;
}

public Display(JFrame frame){
    this.frame = frame;
}

private String title;
private int width, height;
Color sky = new Color(137, 182, 255);
Color enemyPortal = new Color(154, 91, 193);

//Creating a display function that takes in a title, the width (pixels) and height (pixels)
public Display(String title, int width, int height){
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
    arrayC.updatePosition("Test", 2, 3);
}

I realise this may be a silly question and the answer is glaring me in the face, but all help is appreciated.
Thank you.

Body:
As you identified, the error is here in your ArrayControl class:

Display display = new Display();

The class Display does not have a parameterless constructor.

However, as ascertained from the comments, even fixing this will not fix your program.

Currently your ArrayControl class is constructing a new instance of Display (erroneously), and trying to update on the instance of Display stored in the field display in your ArrayControl class. This is not what you want to do, rather you want to update the instance of Display that instanstiated the ArrayControl object.

To achieve this you need to pass the current instance of Display to ArrayControl for it to use. For example (simplified):

public class Display {
    private ArrayControl arrayControl;

    public Display() {
        // Pass this instance of Display to ArrayControl to use
        arrayControl = new ArrayControl(this);
        arrayControl.updatePosition("Test", 2, 3);
    }

    public void updateGrid(String name, int x, int y) {
        // Do update grid stuff
    }

}

public class ArrayControl {

    private Display display;

    public ArrayControl(Display display) {
        this.display = display; // assign instance of Display to the field display
    }

    public void updatePosition(String name, int x, int y) {
        display.updateGrid(name, x, y);
        // I'm not sure why you want to pass the display back to the
        // Display class as in your example so I removed it
    }

}

I'm not sure what your larger goal is, and why there is an ArrayControl class. I assume there is more to it, removed from the question.


问:
Domain specific htpasswd conditions
I am using a wildcard dns system that routes all subdomains through a single web app and sets a userid based on the first part of the URL (X.domain.com where X is the username).

I now want to edit my htaccess file to enable conditional httpauth using htpasswd for specific domains. e.g. if url = password.domain.com the enable httpauth.

I'm sure this is possible but have limited knowledge of htaccess.

答:
You can use SetEnvIf, here's a snippet from this post by Tom Schlick.

```<code>#allows a single uri through the .htaccess password protection
SetEnvIf Request_URI "/testing_uri$" test_uri

#allows everything if its on a certain host
SetEnvIf HOST "^testing.yoursite.com" testing_url
SetEnvIf HOST "^yoursite.com" live_url
Order Deny,Allow

AuthName "Restricted Area"
AuthType Basic
AuthUserFile /path/to/your/.htpasswd
AuthGroupFile /
Require valid-user

#Allow valid-user
Deny from all
Allow from env=test_uri
Allow from env=testing_url
Allow from env=live_url
Satisfy any
</code>```

Title: Domain specific htpasswd conditions

Body:
You can use SetEnvIf, here's a snippet from this post by Tom Schlick.

#allows a single uri through the .htaccess password protection
SetEnvIf Request_URI "/testing_uri$" test_uri

#allows everything if its on a certain host
SetEnvIf HOST "^testing.yoursite.com" testing_url
SetEnvIf HOST "^yoursite.com" live_url
Order Deny,Allow

AuthName "Restricted Area"
AuthType Basic
AuthUserFile /path/to/your/.htpasswd
AuthGroupFile /
Require valid-user

#Allow valid-user
Deny from all
Allow from env=test_uri
Allow from env=testing_url
Allow from env=live_url
Satisfy any


问:
Identifying whether an integer over a certain value appears before a non-numerical char does C++
I'm wanting to read through a file and identify if a letter character appears before an integer value which is above 10. The items in the file are separated by a space and at the end of the list is an "endl;".

So far, I tried getting an array of the integers in the file (just by reading in the arrays and checking if any are above 10) and equally, I've been reading characters in through the file and checking if any are not a digit, but I can't work out how to compare the positions of a non-digit character and too-large integer that I find? Any advice would be greatly appreciated!

```<code>// i.e. sample file may contain:
1 2 3 A 6 12 90 //(in which case the letter appears first).
// example two:
34A 20 4 5 6 7 //(large number here appears first).
</code>```

答:
You can use a regular expression. The following will find two or more digits followed by a letter

```<code>\d{2,}[a-zA-Z]
</code>```

This will work unless you have zero padded numericals (for example 01a)

Depending on the C++ standard you are targeting, you might be able to use <regex>. More info on that here

Here is an example how to return all matches.

Body:
I'm wanting to read through a file and identify if a letter character appears before an integer value which is above 10. The items in the file are separated by a space and at the end of the list is an "endl;".

So far, I tried getting an array of the integers in the file (just by reading in the arrays and checking if any are above 10) and equally, I've been reading characters in through the file and checking if any are not a digit, but I can't work out how to compare the positions of a non-digit character and too-large integer that I find? Any advice would be greatly appreciated!

// i.e. sample file may contain:
1 2 3 A 6 12 90 //(in which case the letter appears first).
// example two:
34A 20 4 5 6 7 //(large number here appears first).

Body:
You can use a regular expression. The following will find two or more digits followed by a letter

\d{2,}[a-zA-Z]

This will work unless you have zero padded numericals (for example 01a)

Depending on the C++ standard you are targeting, you might be able to use <regex>. More info on that here

Here is an example how to return all matches.


问:
dynamic script not parsing correctly
I basically trying to create a dynamic sql script that should do the following

```<code>IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('FinData2000_1') AND NAME = 'idx_FinData2000_1')
            drop  index idx_FinData2000_1 on FinData2000_1
</code>```

Following is the dynamic script that is not parsing

```<code>SET @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('
            + @tableName + '') AND NAME =  'idx_' + @tableName + '
            drop  index' + @tableName + '.idx_' + @tableName;
</code>```

答:
Your dynamic string is not correct, try:

```<code>SET @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('''
            + @tableName + ''') AND NAME =  ''idx_' + @tableName + '''
            drop  index idx_' + @tableName + ' ON ' + @tableName;
</code>```

Output: print(@SQL):

```<code>IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('FinData2000_1') AND NAME =  'idx_FinData2000_1'
            drop  index idx_FinData2000_1 ON FinData2000_1
</code>```

Title: dynamic script not parsing correctly

Body:
I basically trying to create a dynamic sql script that should do the following

IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('FinData2000_1') AND NAME = 'idx_FinData2000_1')
            drop  index idx_FinData2000_1 on FinData2000_1

Following is the dynamic script that is not parsing

SET @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('
            + @tableName + '') AND NAME =  'idx_' + @tableName + '
            drop  index' + @tableName + '.idx_' + @tableName;

Body:
Your dynamic string is not correct, try:

SET @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('''
            + @tableName + ''') AND NAME =  ''idx_' + @tableName + '''
            drop  index idx_' + @tableName + ' ON ' + @tableName;

Output: print(@SQL):

IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('FinData2000_1') AND NAME =  'idx_FinData2000_1'
            drop  index idx_FinData2000_1 ON FinData2000_1


问:
Batch File to Determine Modified Dates
Hey guys, I'm looking for a batch file to tell me if certain folders have been modified today (I'll run it every morning). I'm happy to specify each of the folders to be to be queried, I just haven't been able to find anything that meets my requirements yet. If anyone knows off the top of their head what the code for the .bat would be, that would be awesome :) Thanks in advance.</p>

答:
you can use a vbscript

```<code>Set objFS = CreateObject( "Scripting.FileSystemObject" )
strFolder = WScript.Arguments(0)
Set objFolder = objFS.GetFolder(strFolder)
If DateDiff("d", Now, objFolder.DateLastModified ) = 0 Then
    WScript.Echo "0"
End If
</code>```

in your batch file (or command line)

```<code>C:\test>cscript //nologo test.vbs myFolderName
</code>```

use a for loop to catch the output. (Or you can even do everything in vbscript )

Title: Batch File to Determine Modified Dates

Body:
you can use a vbscript

Set objFS = CreateObject( "Scripting.FileSystemObject" )
strFolder = WScript.Arguments(0)
Set objFolder = objFS.GetFolder(strFolder)
If DateDiff("d", Now, objFolder.DateLastModified ) = 0 Then
    WScript.Echo "0"
End If

in your batch file (or command line)

C:\test>cscript //nologo test.vbs myFolderName

use a for loop to catch the output. (Or you can even do everything in vbscript )


问:
Retrieve return values from multiple DIV's as one object in React
I have this component Home that calls Property component with two different types of data as shown given below.

```<code><Property
          location={this.props.fetchLocation}
          area={this.props.area}
        />
</code>```

Property component renders both of the data sets as nested lists and in different div's. I am using a third component to display elements in the form of checklist and I am calling it from Property component as:

```<code><div><ul>{this.props.location.map(item => {
        return(
        <div><Filter {...item} onChange={this.handleChange}/></div>);
      })}</ul></div>
</code>```

and a same div for the second data set.
I am able to get the checked list item in handleChange:

```<code>handleChange(name, checked) {
    console.log(`This ${name} is ${checked ? 'checked' : 'unchecked'}`)
  }
</code>```

I am wondering if it's possible to pack checked values from both div's i.e both lists into one object and send to Home component in order to filter the search results afterwards.

答:
The way you can do it is by maintaining a state in the Home component and then updating it from child whenever a value is checked or unChecked

Home

```<code>state: {
   selectedLocations: [],
   selectedAreas: []
}

updateCheckedValues = (key, value, isChecked) => {
   this.setState((prevState) => {
       if(isChecked) {
          return {[key]: prevState[key].concat(value)}
       } else {
          return { [key]: prevState[key].filter(obj => obj !== value)}
       }
   })
}

    <Property
          updateCheckedValues={(key, value, isChecked) => {this.updateCheckedValues(key, value, isChecked)}}
          location={this.props.fetchLocation}
          area={this.props.area}
        />
</code>```

Child:

```<code><div><ul>{this.props.location.map(item => {
    return(
    <div><Filter {...item} onChange={this.handleChange}/></div>);
  })}</ul></div>

handleChange = (key, name, checked) => {
   this.props.updateCheckedValues(key, name, checked);
}
</code>```

Body:
I have this component Home that calls Property component with two different types of data as shown given below.

<Property
          location={this.props.fetchLocation}
          area={this.props.area}
        />

Property component renders both of the data sets as nested lists and in different div's. I am using a third component to display elements in the form of checklist and I am calling it from Property component as:

{this.props.location.map(item => {
        return(

<Filter {...item} onChange={this.handleChange}/>
);
      })}

and a same div for the second data set.
I am able to get the checked list item in handleChange:

handleChange(name, checked) {
    console.log(`This ${name} is ${checked ? 'checked' : 'unchecked'}`)
  }

I am wondering if it's possible to pack checked values from both div's i.e both lists into one object and send to Home component in order to filter the search results afterwards.

Body:
The way you can do it is by maintaining a state in the Home component and then updating it from child whenever a value is checked or unChecked

Home

state: {
   selectedLocations: [],
   selectedAreas: []
}

updateCheckedValues = (key, value, isChecked) => {
   this.setState((prevState) => {
       if(isChecked) {
          return {[key]: prevState[key].concat(value)}
       } else {
          return { [key]: prevState[key].filter(obj => obj !== value)}
       }
   })
}

    <Property
          updateCheckedValues={(key, value, isChecked) => {this.updateCheckedValues(key, value, isChecked)}}
          location={this.props.fetchLocation}
          area={this.props.area}
        />

Child:

<div><ul>{this.props.location.map(item => {
    return(
    <div><Filter {...item} onChange={this.handleChange}/></div>);
  })}</ul></div>

handleChange = (key, name, checked) => {
   this.props.updateCheckedValues(key, name, checked);
}


问:
Java 8 collector for Guava Immutable Table
Use case:

Process list of string via method which returns ImmutableTable of type {R,C,V}. For instance ImmutableTable of {Integer,String,Boolean} process(String item){...}

Collect the result i.e, merge all results and return ImmutableTable. Is there a way to achieve it?

Current implementation (as suggested by Bohemian):

How about using parallel stream ? Is there any concurrency issues in the below code? With Parallel stream i an getting "NullPointerException at index 1800" on tableBuilder.build(), but works fine with stream.

```<code>ImmutableTable<Integer, String, Boolean> buildData() {

  // list of 4 AwsS3KeyName
listToProcess.parallelStream()

  //Create new instance via Guice dependency injection
.map(s3KeyName -> ProcessorInstanceProvider.get()
.fetchAndBuild(s3KeyName))
.forEach(tableBuilder::putAll);

 return tableBuilder.build(); }
</code>```

While below code worksgreat with stream as well as parallel stream. But ImmutableBuild is failing due to duplicate entry for row and col. What could be the best way to prevent duplicates while merging tables ?

```<code>public static <R, C, V> Collector<ImmutableTable<R, C, V>,
ImmutableTable.Builder<R, C, V>, ImmutableTable<R, C, V>>
toImmutableTable()
{
return Collector.of(ImmutableTable.Builder::new,
ImmutableTable.Builder::putAll, (builder1, builder2) ->
builder1.putAll(builder2.build()), ImmutableTable.Builder::build); }
</code>```

Edit :
If there is any duplicate entry in ImmutableTable.Builder while merging different tables then it fails,

Trying to avoid faluire by putting ImmutableTables in HashBasedTable

```<code>  ImmutableTable.copyOf(itemListToProcess.parallelStream()
            .map(itemString ->
           ProcessorInstanceProvider.get()
                    .buildImmutableTable(itemString))
                    .collect(
                            Collector.of(
                                    HashBasedTable::create,
                                    HashBasedTable::putAll,
                                    (a, b) -> {
                                        a.putAll(b);
                                        return a;
                                    }));
  )
</code>```

But i am getting runtime exception "Caused by: java.lang.IllegalAccessError: tried to access class com.google.common.collect.AbstractTable".

How can we use HashBasedTable as Accumulator to collect ImmutablesTables, as HashBasedTable overrides the existing entry with latest one and doesn't fail if we try to put duplicate entry , and return aggregated Immutable table.

答:
Since Guava 21 you can use ImmutableTable.toImmutableTable collector.

public ImmutableTable<Integer, String, Boolean> processList(List<String> strings) {
    return strings.stream()
            .map(this::processText)
            .flatMap(table -> table.cellSet().stream())
            .collect(ImmutableTable.toImmutableTable(
                    Table.Cell::getRowKey,
                    Table.Cell::getColumnKey,
                    Table.Cell::getValue,
                    (b1, b2) -> b1 && b2 // You can ommit merge function!
            ));
}

private ImmutableTable<Integer, String, Boolean> processText(String text) {
    return ImmutableTable.of(); // Whatever
}
```

Body:
Use case:

Process list of string via method which returns ImmutableTable of type {R,C,V}. For instance ImmutableTable of {Integer,String,Boolean} process(String item){...}

Collect the result i.e, merge all results and return ImmutableTable. Is there a way to achieve it?

Current implementation (as suggested by Bohemian):

How about using parallel stream ? Is there any concurrency issues in the below code? With Parallel stream i an getting "NullPointerException at index 1800" on tableBuilder.build(), but works fine with stream.

ImmutableTable<Integer, String, Boolean> buildData() {

  // list of 4 AwsS3KeyName
listToProcess.parallelStream()

  //Create new instance via Guice dependency injection
.map(s3KeyName -> ProcessorInstanceProvider.get()
.fetchAndBuild(s3KeyName))
.forEach(tableBuilder::putAll);

 return tableBuilder.build(); }

While below code worksgreat with stream as well as parallel stream. But ImmutableBuild is failing due to duplicate entry for row and col. What could be the best way to prevent duplicates while merging tables ?

public static <R, C, V> Collector<ImmutableTable<R, C, V>,
ImmutableTable.Builder<R, C, V>, ImmutableTable<R, C, V>>
toImmutableTable()
{
return Collector.of(ImmutableTable.Builder::new,
ImmutableTable.Builder::putAll, (builder1, builder2) ->
builder1.putAll(builder2.build()), ImmutableTable.Builder::build); }

Edit :
If there is any duplicate entry in ImmutableTable.Builder while merging different tables then it fails,

Trying to avoid faluire by putting ImmutableTables in HashBasedTable

  ImmutableTable.copyOf(itemListToProcess.parallelStream()
            .map(itemString ->
           ProcessorInstanceProvider.get()
                    .buildImmutableTable(itemString))
                    .collect(
                            Collector.of(
                                    HashBasedTable::create,
                                    HashBasedTable::putAll,
                                    (a, b) -> {
                                        a.putAll(b);
                                        return a;
                                    }));
  )

But i am getting runtime exception "Caused by: java.lang.IllegalAccessError: tried to access class com.google.common.collect.AbstractTable".

How can we use HashBasedTable as Accumulator to collect ImmutablesTables, as HashBasedTable overrides the existing entry with latest one and doesn't fail if we try to put duplicate entry , and return aggregated Immutable table.


问:
Scrollview does not work outside LinearLayout with Viewpager
My layout file:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

    <LinearLayout
        android:id="@+id/root_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <ImageView
            android:id="@+id/imageViewPage"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@drawable/zelenjavne_jedi"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TabLayout
                android:id="@+id/sliding_tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        </android.support.v4.view.ViewPager>

    </LinearLayout>

</ScrollView>
</code>```

No matter how I change height to fill_parents, wrap_content, match_parent etc, if I use other views such as Relative instead of Linear it still doesn't work.

答:
Solution found here

Have to set layout_height attribute to dp value such as this:

```<code><android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="500dp">
</code>```

Body:
My layout file:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

    <LinearLayout
        android:id="@+id/root_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <ImageView
            android:id="@+id/imageViewPage"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@drawable/zelenjavne_jedi"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TabLayout
                android:id="@+id/sliding_tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        </android.support.v4.view.ViewPager>

    </LinearLayout>

</ScrollView>

No matter how I change height to fill_parents, wrap_content, match_parent etc, if I use other views such as Relative instead of Linear it still doesn't work.

Body:
Solution found here

Have to set layout_height attribute to dp value such as this:

<android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="500dp">


问:
check value at database before importing data php
Is there a way to take a value supplied by a user on the front end and compare it with all values in the database without getting the data from the database and supplying it to the front end? For security purposes I do not want to supply the front end with the values unless there is a match in the database.

example:
user enters their "coupon code" on the front end
the code checks the value against the actual "coupon code" values in the database and only if there is a match does it return the data from the matching record and supply it to the front end

答:
Certainly.  You simply need to construct a query, and at that point you have a few options.  One way is to do a count() query and only proceed if the count is > 0.  The other is to issue the query, and use the client library feature to determine if there are results.

The specifics require a bit more information in regards to the database and client library you are utilizing in your code, not to mention the schema (table structure(s)) and the query(s) you are using.

For something as simple as finding a coupon row by some sort of id string, I would probably opt for the 2nd option, and run the query and check for a result.

Then your code checks that result set count with an if() and proceeds to fetch the row, or prints out your error/coupon not found message if not.

Just taking a wild guess that you might be using MySQL:

With mysqli
With PDO it is typically best to just query and fetch the data (as this should be either one row or none) and then check the result variable

```<code>$data = $pdo->query("SELECT * FROM table WHERE ...")->fetchAll();
if ($data) {
    // There's a coupon
} else {
    // There is no coupon
}
</code>```

It's actually more complicated than that, because you should be using prepare to bind the variable and execute, but the basic idea is the same.

Body:
Certainly.  You simply need to construct a query, and at that point you have a few options.  One way is to do a count() query and only proceed if the count is > 0.  The other is to issue the query, and use the client library feature to determine if there are results.

The specifics require a bit more information in regards to the database and client library you are utilizing in your code, not to mention the schema (table structure(s)) and the query(s) you are using.

For something as simple as finding a coupon row by some sort of id string, I would probably opt for the 2nd option, and run the query and check for a result.

Then your code checks that result set count with an if() and proceeds to fetch the row, or prints out your error/coupon not found message if not.

Just taking a wild guess that you might be using MySQL:

With mysqli
With PDO it is typically best to just query and fetch the data (as this should be either one row or none) and then check the result variable

$data = $pdo->query("SELECT * FROM table WHERE ...")->fetchAll();
if ($data) {
    // There's a coupon
} else {
    // There is no coupon
}

It's actually more complicated than that, because you should be using prepare to bind the variable and execute, but the basic idea is the same.


问:
C++ Enum equivalent in Kotlin
The problem I am trying to solve:

I have a list of elements. The list can be large and there can be many of them. I would like to access them by index. For those indexes I would like to use words instead of numbers. I would also like this words to be strongly typed, so I cannot mix numbers with them.

I believe Kotlin enum is not good for this, since every enumeration is an object instance itself. I can use Int constants, but then I lose the type safety.

In c++ this problem is solved by an Enum. Enumerations can be casted to their underlying type (in compile time) to be used as indexes. At the same type the Enum is a type and if a function takes it as a parameter, the compiler won't allow passing integers in. The enumerations themselves are not objects themselves, so you can have as many as you like without any performance hit.

C++ code example to show what I am looking for:

```<code>string someArray[] = {"element 0", "element 1"};

enum class Index
{
    first = 0,
    second = 1,
};

string getElement(Index i)
{
    return someArray[(int)i];
}

void foo()
{
    auto element0 = getElement(Index::first);
    auto element1 = getElement(1);  // compile time error - parameter type mismatch
}
</code>```

答: Thousands of objects is really very little, but you could just use normal Kotlin enums and then use Proguard to optimize them out. It does so by default but you may need to be careful configuring it and don't forget to test the application thoroughly afterwards.</p>

Title: C++ Enum equivalent in Kotlin

Body:
The problem I am trying to solve:

I have a list of elements. The list can be large and there can be many of them. I would like to access them by index. For those indexes I would like to use words instead of numbers. I would also like this words to be strongly typed, so I cannot mix numbers with them.

I believe Kotlin enum is not good for this, since every enumeration is an object instance itself. I can use Int constants, but then I lose the type safety.

In c++ this problem is solved by an Enum. Enumerations can be casted to their underlying type (in compile time) to be used as indexes. At the same type the Enum is a type and if a function takes it as a parameter, the compiler won't allow passing integers in. The enumerations themselves are not objects themselves, so you can have as many as you like without any performance hit.

C++ code example to show what I am looking for:

string someArray[] = {"element 0", "element 1"};

enum class Index
{
    first = 0,
    second = 1,
};

string getElement(Index i)
{
    return someArray[(int)i];
}

void foo()
{
    auto element0 = getElement(Index::first);
    auto element1 = getElement(1);  // compile time error - parameter type mismatch
}


问:
Haskell function use show and return Integer
I am troubleshooting with this a long time.

```<code>asInt_either2 ::  String -> Int
asInt_either2 str
    | null str = 0
    | (head str) == '-' = -1 * asInt_either2 (tail str)
    | isNumber (head str)  = foldl' nasob 0 str
    | otherwise  = error ("Not a Number: '" ++ [(head str)] ++ "'")
    where nasob x y = x*10 + (my_digit y)
        my_digit y
           | isNumber y = digitToInt y
           | otherwise = show ("Not a Number: '" ++ [y] ++ "'")
</code>```

This simply should convert String to Integer, but If it finds not Number character it will print "Not a Number : 'a' " (for example)

I try to get it work but I still get error.
I know, there exist better solutions for this,but this is exercise for me and I want to try it this way, if it is possible.

I am getting error:

```<code>• Couldn't match type ‘[Char]’ with ‘Int’
  Expected type: Int
    Actual type: String
• In the expression: show ("Not a Number: '" ++ [y] ++ "'")
  In an equation for ‘my_digit’:
      my_digit y
        | isNumber y = digitToInt y
        | otherwise = show ("Not a Number: '" ++ [y] ++ "'")
  In an equation for ‘asInt_either2’:
      asInt_either2 str
        | null str = 0
        | (head str) == '-' = - 1 * asInt_either2 (tail str)
        | isNumber (head str) = foldl' nasob 0 str
        | otherwise = error ("Not a Number: '" ++ [(head str)] ++ "'")
        where
            nasob x y = x * 10 + (my_digit y)
            my_digit y
              | isNumber y = digitToInt y
              | otherwise = show ("Not a Number: '" ++ [y] ++ "'")
</code>```

Update:

Rewrite show to error function solve the problems.

But I am trying to solve this exercise:
"The  function uses error , so its callers cannot handle errors. Rewrite
the function to fix this problem"

Thanks for help.

答:
show doesn't print anything.  It's just a function to convert something into a String

my_digit should be an Int but | otherwise = show ("Not a Number: '" ++ [y] ++ "'") returns a string.  Did you maybe mean to use error instead of show?

```<code>        my_digit y
          | isNumber y = digitToInt y
          | otherwise = error ("Not a Number: '" ++ [y] ++ "'")
</code>```

This will cause the program to fail and print your error message when it encounters a non-digit character.

Body:
I am troubleshooting with this a long time.

asInt_either2 ::  String -> Int
asInt_either2 str
    | null str = 0
    | (head str) == '-' = -1 * asInt_either2 (tail str)
    | isNumber (head str)  = foldl' nasob 0 str
    | otherwise  = error ("Not a Number: '" ++ [(head str)] ++ "'")
    where nasob x y = x*10 + (my_digit y)
        my_digit y
           | isNumber y = digitToInt y
           | otherwise = show ("Not a Number: '" ++ [y] ++ "'")

This simply should convert String to Integer, but If it finds not Number character it will print "Not a Number : 'a' " (for example)

I try to get it work but I still get error.
I know, there exist better solutions for this,but this is exercise for me and I want to try it this way, if it is possible.

I am getting error:

• Couldn't match type ‘[Char]’ with ‘Int’
  Expected type: Int
    Actual type: String
• In the expression: show ("Not a Number: '" ++ [y] ++ "'")
  In an equation for ‘my_digit’:
      my_digit y
        | isNumber y = digitToInt y
        | otherwise = show ("Not a Number: '" ++ [y] ++ "'")
  In an equation for ‘asInt_either2’:
      asInt_either2 str
        | null str = 0
        | (head str) == '-' = - 1 * asInt_either2 (tail str)
        | isNumber (head str) = foldl' nasob 0 str
        | otherwise = error ("Not a Number: '" ++ [(head str)] ++ "'")
        where
            nasob x y = x * 10 + (my_digit y)
            my_digit y
              | isNumber y = digitToInt y
              | otherwise = show ("Not a Number: '" ++ [y] ++ "'")

Update:

Rewrite show to error function solve the problems.

But I am trying to solve this exercise:
"The  function uses error , so its callers cannot handle errors. Rewrite
the function to fix this problem"

Thanks for help.

Body:
show doesn't print anything.  It's just a function to convert something into a String

my_digit should be an Int but | otherwise = show ("Not a Number: '" ++ [y] ++ "'") returns a string.  Did you maybe mean to use error instead of show?

        my_digit y
          | isNumber y = digitToInt y
          | otherwise = error ("Not a Number: '" ++ [y] ++ "'")

This will cause the program to fail and print your error message when it encounters a non-digit character.