问:
The value of the variable don't show in the other class
I make a program in Eclipse to Android and I have a problem. I have this class where I show the artists. Inside the onClick method I want to send the "value" of the clicked listitem.

```<code>...public class ArtistActivity extends ListActivity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview);

    String[] artists = getResources().getStringArray(R.array.artists_array);
    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, artists));

    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {
                StringActivity sA = new StringActivity();
                sA.setArtist(((TextView) v).getText().toString());
                String asd = sA.getArtist();
                //Toast.makeText(getApplicationContext(), asd/*((TextView) v).getText()*/, Toast.LENGTH_SHORT).show();
                Intent i = new Intent().setClass(getApplicationContext(), AlbumActivity.class);
                startActivity(i);
            }
    });
}}
</code>```

Inside onClick when I do it with Toast then it shows the picked item, but in the other class don't. Here are the code where I store the value:

```<code>public class StringActivity {
private String artist="";

public String getArtist() {
    return(artist);
}

public void setArtist(String artist) {
    this.artist=artist;
}

public String toString() {
    return(getArtist());
}}
</code>```

And here is the other class where it should show the value:

```<code>public class AlbumActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    StringActivity sA = new StringActivity();

    String asd = sA.getArtist();
    TextView textview = new TextView(this);
    textview.setText("Hello " + asd + " World!");
    setContentView(textview);
}}
</code>```

The hello world is there just because to see that there is nothing wrong with the textview. Maybe the problem is that it don't refresh (it's stay the same from the launch of the program - because when I give a value for the artist string in the StringActivity class then it shows, but when I click on an item it stay the same) or there is another problem?
Thanks!

答:
You are creating a new instance of StringActivity and then getting the value with getArtist(). It returns empty string because the instance is local and it has not been set to be anything else.

Unfortunately I have not done any Android development so I do not know how you should pass data around. Maybe it can be done with Bundle that is passed as parameter or maybe there is some other way. I guess it should be pretty easy to find if you search Android documentation and examples.

Body:
I make a program in Eclipse to Android and I have a problem. I have this class where I show the artists. Inside the onClick method I want to send the "value" of the clicked listitem.

...public class ArtistActivity extends ListActivity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview);

    String[] artists = getResources().getStringArray(R.array.artists_array);
    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, artists));

    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {
                StringActivity sA = new StringActivity();
                sA.setArtist(((TextView) v).getText().toString());
                String asd = sA.getArtist();
                //Toast.makeText(getApplicationContext(), asd/*((TextView) v).getText()*/, Toast.LENGTH_SHORT).show();
                Intent i = new Intent().setClass(getApplicationContext(), AlbumActivity.class);
                startActivity(i);
            }
    });
}}

Inside onClick when I do it with Toast then it shows the picked item, but in the other class don't. Here are the code where I store the value:

public class StringActivity {
private String artist="";

public String getArtist() {
    return(artist);
}

public void setArtist(String artist) {
    this.artist=artist;
}

public String toString() {
    return(getArtist());
}}

And here is the other class where it should show the value:

public class AlbumActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    StringActivity sA = new StringActivity();

    String asd = sA.getArtist();
    TextView textview = new TextView(this);
    textview.setText("Hello " + asd + " World!");
    setContentView(textview);
}}

The hello world is there just because to see that there is nothing wrong with the textview. Maybe the problem is that it don't refresh (it's stay the same from the launch of the program - because when I give a value for the artist string in the StringActivity class then it shows, but when I click on an item it stay the same) or there is another problem?
Thanks!


来源: stackexchange

问:
Counting Negative Values and Ranking Them
Trying to count the negative values and rank them from highest count to lowest

```<code>Banana  -1   2  -3   2   1
Orange   4  -3  -3  -1   2
Apple    1  -4   1   1   2
</code>```

I was going to use the worksheet function like this

```<code>Set CountRng = range("B1:F1")
CountBanana = Application.WorksheetFunction.CountIf(CountRng, "<0")
</code>```

But not sure how I can rank them. Maybe I need to use array here?

Result should rank Orange (3), Banana (2) and Apple (1)

Output in cell G1:G3

答:
use Evaluate with the formula I gave the first time you asked:

```<code>With Worksheets("Sheet3") 'change to your worksheet
    Dim lstRow As Long
    lstRow = .Cells(.Rows.Count, 1).End(xlUp).Row

    Dim i As Long
    For i = 1 To lstRow
        .Cells(i, 7).Value = .Evaluate("=SUMPRODUCT(--(COUNTIF(OFFSET($B$1,(ROW($1:$" & lstRow & ")-1),0,1,5),""<0"")<COUNTIF(B" & i & ":F" & i & ",""<0"")))+1")
    Next i
End With
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Trying to count the negative values and rank them from highest count to lowest

Banana  -1   2  -3   2   1
Orange   4  -3  -3  -1   2
Apple    1  -4   1   1   2

I was going to use the worksheet function like this

Set CountRng = range("B1:F1")
CountBanana = Application.WorksheetFunction.CountIf(CountRng, "<0")

But not sure how I can rank them. Maybe I need to use array here?

Result should rank Orange (3), Banana (2) and Apple (1)

Output in cell G1:G3

Body:
use Evaluate with the formula I gave the first time you asked:

With Worksheets("Sheet3") 'change to your worksheet
    Dim lstRow As Long
    lstRow = .Cells(.Rows.Count, 1).End(xlUp).Row

    Dim i As Long
    For i = 1 To lstRow
        .Cells(i, 7).Value = .Evaluate("=SUMPRODUCT(--(COUNTIF(OFFSET($B$1,(ROW($1:$" & lstRow & ")-1),0,1,5),""<0"")<COUNTIF(B" & i & ":F" & i & ",""<0"")))+1")
    Next i
End With


问:
returning the location of the first value at a dataframe location that meets a condition in pandas dataframe
I have this dataframe:

```<code>import pandas as pd
df = pd.DataFrame({'time': ['20:00', '23:00', '21:00', '21:00', '22:00', '22:00', '20:30'],
                   'traf': [100, 200, 25, 300, 100, 200, 100],
                   'num': [5, 3, 5, 6, 41, 34, 10]})
df = df.set_index(['time']).sort_index()
print(df)

        traf  num
time
20:00   100    5
20:30   100   10
21:00    25    5
21:00   300    6
22:00   100   41
22:00   200   34
23:00   200    3
</code>```

I am trying to write a function to aggregate my dataframe by values of column df['traf'] and then report the 1st value in column df['num'] that meets a condition.

here is example of what I am doing but I am not sure if this a right rough to go. Also, since I am dealing with a very large size dataframe, I am not sure if this way is efficient enough.

```<code>filter = df.groupby(["time"])['traf'].sum() >= 225
df.where(filter, inplace=True)
print(df)

         traf   num
time
20:00    NaN   NaN
20:30    NaN   NaN
21:00   25.0   5.0
21:00  300.0   6.0
22:00  100.0  41.0
22:00  200.0  34.0
23:00    NaN   NaN
</code>```

So from the above result, I want my output to be the first value in column num that is not NaN in this case 5.0.

答:
Using transform with sum then groupby again using first

```<code>s=df.groupby(["time"])['traf'].transform('sum').gt(255)
df[s].groupby('time').num.first()
Out[207]:
time
21:00     5
22:00    41
Name: num, dtype: int64
</code>```

Or

```<code>df.loc[s,'num'].iloc[0]
Out[211]: 5
</code>```

Body:
I have this dataframe:

import pandas as pd
df = pd.DataFrame({'time': ['20:00', '23:00', '21:00', '21:00', '22:00', '22:00', '20:30'],
                   'traf': [100, 200, 25, 300, 100, 200, 100],
                   'num': [5, 3, 5, 6, 41, 34, 10]})
df = df.set_index(['time']).sort_index()
print(df)

        traf  num
time
20:00   100    5
20:30   100   10
21:00    25    5
21:00   300    6
22:00   100   41
22:00   200   34
23:00   200    3

I am trying to write a function to aggregate my dataframe by values of column df['traf'] and then report the 1st value in column df['num'] that meets a condition.

here is example of what I am doing but I am not sure if this a right rough to go. Also, since I am dealing with a very large size dataframe, I am not sure if this way is efficient enough.

filter = df.groupby(["time"])['traf'].sum() >= 225
df.where(filter, inplace=True)
print(df)

         traf   num
time
20:00    NaN   NaN
20:30    NaN   NaN
21:00   25.0   5.0
21:00  300.0   6.0
22:00  100.0  41.0
22:00  200.0  34.0
23:00    NaN   NaN

So from the above result, I want my output to be the first value in column num that is not NaN in this case 5.0.

Body:
Using transform with sum then groupby again using first

s=df.groupby(["time"])['traf'].transform('sum').gt(255)
df[s].groupby('time').num.first()
Out[207]:
time
21:00     5
22:00    41
Name: num, dtype: int64

Or

df.loc[s,'num'].iloc[0]
Out[211]: 5


问:
Moving randomly svg objects using vanilla javascript
I want to move my svg objects randomly using vanilla javascript,
i make it to move element by adding value to cx by 10px but it likes it is jumping, is there any other way to move it smoothly, keyframes does not work. and javascript is used inside svg file, i need to achive effect like bouncing balls just with these elements
Effect like this one:
https://codepen.io/pintergabor/pen/DywHc

This should be used as background picture.

```<code><svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 500">
<defs>
    <style>
        .cls-1 {
            fill: url(#linear-gradient);
        }

        .cls-2 {
            fill: url(#linear-gradient-2);
        }

        .cls-3 {
            fill: url(#linear-gradient-3);
        }
        #circle{
            animate: circle 4s infinite linear;
        }
        @keyframes circle{
            to{
                transform: translate(55rem, 15px);
            }
        }
    </style>

    <linearGradient id="linear-gradient" x1="61.83" y1="217.56" x2="61.83" y2="256.64" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#9dcb3b" />
        <stop offset="1" stop-color="#aa2d23" />
    </linearGradient>
    <linearGradient id="linear-gradient-2" x1="316.43" y1="64.69" x2="316.43" y2="98.31" xlink:href="#linear-gradient" />
    <linearGradient id="linear-gradient-3" x1="321.31" y1="319.11" x2="321.31" y2="396.98" xlink:href="#linear-gradient" />
</defs>
<title>elements</title>
<circle id="circle" class="cls-1" cx="61.83" cy="237.1" r="19.54" />
<polygon id="triangle" class="cls-2" points="316.43 64.69 297.01 98.31 335.84 98.31 316.43 64.69" />
<path id="plus" class="cls-3" d="M323.9,397h-5.18V319.11h5.18Zm36.35-36.35v-5.17H282.37v5.17Z" />
</code>```

答:
You need to build a loop to do that using "vanilla" javascript.

A basic way to do that would be :

```<code>let fps = 60  // frames per second

function loop(){
   console.log('in loop')
}

window.setInterval(loop, 1000 / fps)
</code>```

Then in the loop function move your svg elements as you'd like.

Some libraries help a lot with this. A few coming to mind are SVG.js, two.js, velocity.js...

Body:
I want to move my svg objects randomly using vanilla javascript,
i make it to move element by adding value to cx by 10px but it likes it is jumping, is there any other way to move it smoothly, keyframes does not work. and javascript is used inside svg file, i need to achive effect like bouncing balls just with these elements
Effect like this one:
https://codepen.io/pintergabor/pen/DywHc

This should be used as background picture.

<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 500">
<defs>

    <linearGradient id="linear-gradient" x1="61.83" y1="217.56" x2="61.83" y2="256.64" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#9dcb3b" />
        <stop offset="1" stop-color="#aa2d23" />
    </linearGradient>
    <linearGradient id="linear-gradient-2" x1="316.43" y1="64.69" x2="316.43" y2="98.31" xlink:href="#linear-gradient" />
    <linearGradient id="linear-gradient-3" x1="321.31" y1="319.11" x2="321.31" y2="396.98" xlink:href="#linear-gradient" />
</defs>
<title>elements</title>
<circle id="circle" class="cls-1" cx="61.83" cy="237.1" r="19.54" />
<polygon id="triangle" class="cls-2" points="316.43 64.69 297.01 98.31 335.84 98.31 316.43 64.69" />
<path id="plus" class="cls-3" d="M323.9,397h-5.18V319.11h5.18Zm36.35-36.35v-5.17H282.37v5.17Z" />

Body:
You need to build a loop to do that using "vanilla" javascript.

A basic way to do that would be :

let fps = 60  // frames per second

function loop(){
   console.log('in loop')
}

window.setInterval(loop, 1000 / fps)

Then in the loop function move your svg elements as you'd like.

Some libraries help a lot with this. A few coming to mind are SVG.js, two.js, velocity.js...


问:
Three-dimensional array arrives in wrong order at serial port
For an university assignment I'm writing a java application that will run some game logic for an interactive LED table. The table itself is being controlled by either 2 Arduino Duemilanove or 1 Arduino Mega 2560.

To give the Arduino(s) information about which LEDs should be lit in which color I send the data over the serial port from a Raspberry Pi 3b+ to the Arduinos. As the table consists of 14 LED strips with 14 LEDs per LED strip and each LED has 3 color values (RGB) I store the data about the table in an int[14][14][3] array.

Before sending the array to the Arduino I create a JSON object of it (using the Jackson library) and then send the array as a String using jSerialComm. Depending on which Arduino setup I use I also either transfer the whole array to JSON or split it into two int[7][14][3] arrays before creating the JSON object.

As the data arrived in the wrong order at the serial port when I used 2 Arduinos and jSerialComm I now got a new Arduino Mega 2560 (as other SO questions suggested the wrong data order might occur due to an outdated PL2303 module) and tried it again with the same result. After some further research I now tried using JSSC instead of jSerialComm but still the same result shows up.

The java class that I use to send the data to the arduino looks like this (the outcommented code being the code where I used jSerialComm / 2 Arduinos):

```<code>package de.pimatrix.backend;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fazecast.jSerialComm.SerialPort;

import jssc.SerialPortException;

public class SerialThread implements Runnable {

    public static SerialPort arduino1, arduino2;
    private int[][][] matrix = new int[14][14][3];

    private int[][][] matrixLeft = new int[7][14][3];
    private int[][][] matrixRight = new int[7][14][3];

    private Socket localHost;
    private Matrix matrixData;
    private ObjectInputStream in;

    @Override
    public void run() {

        SerialJSONWriter writer = new SerialJSONWriter();

        ServerSocket ss = null;
        localHost = null;
        matrixData = new Matrix(matrix);
        try {
            ss = new ServerSocket(62000); // erstellen eines lokalen Sockets auf Port 62000, um die zu übertragende
                                            // Matrix vom ClientThread
        } catch (IOException e) {
        }

        while (true) {
            try {
                localHost = ss.accept();
            } catch (Exception e) {
                e.printStackTrace();
            }
            initializeInputStream();
            waitForMatrix();
            splitMatrix();

            try {
                writer.tryWrite(matrixRight, matrixLeft);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void splitMatrix() {
        for (int i = 0; i < 14; i++) {
            for (int j = 0; j < 14; j++) {
                if (i <= 6) {
                    matrixRight[i][j][0] = matrix[i][j][0];
                    matrixRight[i][j][1] = matrix[i][j][1];
                    matrixRight[i][j][2] = matrix[i][j][2];
                } else {
                    matrixLeft[i - 7][j][0] = matrix[i][j][0];
                    matrixLeft[i - 7][j][1] = matrix[i][j][1];
                    matrixLeft[i - 7][j][2] = matrix[i][j][2];
                }
            }
        }
    }

    private void initializeInputStream() {
        try {
            InputStream input = localHost.getInputStream();
            in = new ObjectInputStream(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void waitForMatrix() {
        System.out.println("Waiting for Matrix");
        try {
            matrixData = (Matrix) in.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        this.matrix = matrixData.matrix;
    }

    class SerialJSONWriter implements AutoCloseable {

        // Zuweisen der seriellen Ports
//      private final SerialPort /*arduino1, arduino2,*/ arduinoMega;
        private jssc.SerialPort arduinoMega;

        public SerialJSONWriter() {
//          arduino1 = SerialPort.getCommPort("COM5");
//          arduino2 = SerialPort.getCommPort("COM6");
//          arduinoMega = SerialPort.getCommPort("COM7");
            arduinoMega = new jssc.SerialPort("COM7");
            try {
                arduinoMega.openPort();
                arduinoMega.setParams(115200, 8, 1, jssc.SerialPort.PARITY_EVEN);
            } catch (SerialPortException e) {
                e.printStackTrace();
            }
//          arduinoMega.setBaudRate(115200);
//          arduinoMega.setNumDataBits(8);
//          arduinoMega.setNumStopBits(1);
//          arduinoMega.setParity(0);

            // setzen der Timeouts für die Kommunikation mit den Arduinos
//          arduino1.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
//          arduino2.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
//          arduinoMega.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
//          arduino1.setBaudRate(115200);
//          arduino2.setBaudRate(115200);
//          arduinoMega.setBaudRate(115200);
//          arduino1.openPort();
//          arduino2.openPort();
//          arduinoMega.openPort();
//          arduino1.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 0,
//                  0);
//          arduino2.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 0,
//                  0);

//          arduinoMega.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 0,
//                  0);
        }

        public void write() {

        }

        private void tryWrite(Object dataRight, Object dataLeft) throws IOException {
            String dataAsJSONRight = new ObjectMapper().writeValueAsString(dataRight) + "\n";
            String dataAsJSONLeft = new ObjectMapper().writeValueAsString(dataLeft) + "\n";
            try {
                arduinoMega.writeString(dataAsJSONRight);
            } catch (SerialPortException e) {
                e.printStackTrace();
            }
//          for (int i = 0; i < dataAsJSONRight.length(); i++) {
////                arduino1.getOutputStream().write(dataAsJSONRight.getBytes()[i]);
//              System.out.println(dataAsJSONRight);
//              arduinoMega.getOutputStream().write(dataAsJSONRight.getBytes()[i]);
//          }
//          for (int i = 0; i < dataAsJSONLeft.length(); i++) {
////                arduino2.getOutputStream().write(dataAsJSONLeft.getBytes()[i]);
//              arduinoMega.getOutputStream().write(dataAsJSONLeft.getBytes()[i]);
//          }
        }

        @Override
        public void close() throws Exception {
//          arduino1.closePort();
//          arduino2.closePort();
            arduinoMega.closePort();
        }
    }
}
</code>```

On the Arduino(s) the processing looks like this:

```<code>#include <ArduinoJson.h>
#include <Adafruit_NeoPixel.h>

#define PINROW0 2
#define PINROW1 3
#define PINROW2 4
#define PINROW3 5
#define PINROW4 6
#define PINROW5 7
#define PINROW6 8

#define NUMPIXELS 14 //Amount of pixels per row

Adafruit_NeoPixel row[] = { //Intitialize the array, that contains the addressable LED strips in the Adafruit format
  Adafruit_NeoPixel(NUMPIXELS, PINROW0, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW1, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW2, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW3, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW4, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW5, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW6, NEO_GRB + NEO_KHZ800)
};

#define DELAY 1000 //set refresh cycle to 10 milliseconds
#define NUMSTRIPS 7/*(sizeof(row)/sizeof(row[0]))*/ //Amount of connected LED strips

int values[7][14][3];
int c = 0;
String matrixAsString = "";

void setup() {

  /*Setup serial port on which the Pi connects to the Arduino*/
  Serial.begin(115200); //set baudrate to 115200 Bit per second
  Serial.setTimeout(1000);

  Serial.println(100);

  /*initialize NeoPixel Library*/
  for (int i = 0; i < NUMSTRIPS; i++) {
    row[i].begin();
    row[i].show();
  }
}

void process(String matrixAsString) {
  StaticJsonDocument<4372> doc;
  Serial.println(matrixAsString);
  deserializeJson(doc, matrixAsString);

  for (int i = 0; i < 7; i++) {
    for (int j = 0; i < 14; j++) {
      values[i][j][0] = values[i][j][1] = values[i][j][2] = (int) (doc[i][j][0]);
    }
  }
}

//infinite loop refreshing the matrix
void loop() {

  while (Serial.available()) {
    char c = Serial.read();
    Serial.println(matrixAsString);
    matrixAsString += c;
    if (c == '\n') {
      process(matrixAsString);
      matrixAsString = "";
    }

  }

}
</code>```

When sending the data for a half matrix (so an int[7][14][3]):

[[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[255,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]]

through the serial monitor in the Arduino IDE I get this output from the Arduino (as of the Serial.println() in void loop):

As one can see the first RGB values are transmitted correctly, however after even less than one complete LED strip the data arrives in the wrong order and (as you can see at the end of the picture) at some point completely stops showing up, which probably indicates no data is being read any more.

I've been trying a hell of things like changing the Arduino in case the PL2303 is outdated or defective as well as trying different libraries for serial communication however I cannot figure out what I'm doing wrong. I've spent over 30 hours trying different approaches to no avail so things are becoming really frustrating for me.

UPDATE

As suggested by B.Letz I got the setup of the data, stop and parity bits right (now being 8 data, 1 stop and no parity bits). By reading the arduino feedback I still got the same results but after some tweeking I recognized that the problem probably was that my Serial.print apparently led to a massive lag on the Arduino so it couldn't handle all the data correctly and in time. After removing the first Serial.print call before doing the processing I now see the first matrix that is being transmitted being printed correctly by the Arduino. However for some reason for all further transmitted data the Arduino prints null. I'll try extending the timeouts in case the null pointer occurs due to a timeout on the Arduino-side.

UPDATE 2

Opposed to my assumption reconfiguring the timeouts didn't solve the problem. I also figured out that after the first JSON Object is sent the Arduino prints null to the console and only sends me the first JSON object after receiving the second JSON object. However this is the only time I get any feedback from the Arduino except null. What I also noticed is that when I send the JSON String over the serial monitor the Arduino instantly prints the correct String BUT it also prints an empty new line and doesn't respond to any new data in any kind.

答:
The first step for a working solution was removing the unnecessary Serial.print() call everytime a new char was read. After removing this line I could confirm the data arrived properly.
The shifted feedback as mentioned in my second update to the post:

I also figured out that after the first JSON Object is sent the Arduino prints null to the console and only sends me the first JSON object after receiving the second JSON object. However this is the only time I get any feedback from the Arduino except null

occured due to the fact that I didn't wait long enough on the java application side for data to arrive before calling the read() function. After solving this I always received the correct string.

Trying out different configurations with either DynamicJsonDocument and StaticJsonDocument I now ended up using DynamicJsonDocument however also a StaticJsonDocument might have worked here.
A rather unpleasant issue was that in the inner for-loop in void process I accidently compared the counter variable to that of the outer for-loop, although I was able to retrieve the correct data at that point outside of the for-loop.

The problem asked in this questions is thereby solved, however a even bigger problem now occured as I'm not able to retrieve any data from the received JSON object as soon as I start implementing the code for controlling the LEDs and call row[i].setPixelColor(j, row[i].Color(values[i][j][0], values[i][j][1], values[i][j][2])); at any point in my code. So to sum things up this specific call is the actual reason that the code doesn't work properly.

I'll be opening a new question for that new problem as it doesn't belong to this question thematically, however I will add a reference to it here, once it's written.

UPDATE

The new question regarding addressing more than 7 LED strips using Adafruit's NeoPixel library can be found here.

Body:
For an university assignment I'm writing a java application that will run some game logic for an interactive LED table. The table itself is being controlled by either 2 Arduino Duemilanove or 1 Arduino Mega 2560.

To give the Arduino(s) information about which LEDs should be lit in which color I send the data over the serial port from a Raspberry Pi 3b+ to the Arduinos. As the table consists of 14 LED strips with 14 LEDs per LED strip and each LED has 3 color values (RGB) I store the data about the table in an int[14][14][3] array.

Before sending the array to the Arduino I create a JSON object of it (using the Jackson library) and then send the array as a String using jSerialComm. Depending on which Arduino setup I use I also either transfer the whole array to JSON or split it into two int[7][14][3] arrays before creating the JSON object.

As the data arrived in the wrong order at the serial port when I used 2 Arduinos and jSerialComm I now got a new Arduino Mega 2560 (as other SO questions suggested the wrong data order might occur due to an outdated PL2303 module) and tried it again with the same result. After some further research I now tried using JSSC instead of jSerialComm but still the same result shows up.

The java class that I use to send the data to the arduino looks like this (the outcommented code being the code where I used jSerialComm / 2 Arduinos):

package de.pimatrix.backend;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fazecast.jSerialComm.SerialPort;

import jssc.SerialPortException;

public class SerialThread implements Runnable {

    public static SerialPort arduino1, arduino2;
    private int[][][] matrix = new int[14][14][3];

    private int[][][] matrixLeft = new int[7][14][3];
    private int[][][] matrixRight = new int[7][14][3];

    private Socket localHost;
    private Matrix matrixData;
    private ObjectInputStream in;

    @Override
    public void run() {

        SerialJSONWriter writer = new SerialJSONWriter();

        ServerSocket ss = null;
        localHost = null;
        matrixData = new Matrix(matrix);
        try {
            ss = new ServerSocket(62000); // erstellen eines lokalen Sockets auf Port 62000, um die zu übertragende
                                            // Matrix vom ClientThread
        } catch (IOException e) {
        }

        while (true) {
            try {
                localHost = ss.accept();
            } catch (Exception e) {
                e.printStackTrace();
            }
            initializeInputStream();
            waitForMatrix();
            splitMatrix();

            try {
                writer.tryWrite(matrixRight, matrixLeft);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void splitMatrix() {
        for (int i = 0; i < 14; i++) {
            for (int j = 0; j < 14; j++) {
                if (i <= 6) {
                    matrixRight[i][j][0] = matrix[i][j][0];
                    matrixRight[i][j][1] = matrix[i][j][1];
                    matrixRight[i][j][2] = matrix[i][j][2];
                } else {
                    matrixLeft[i - 7][j][0] = matrix[i][j][0];
                    matrixLeft[i - 7][j][1] = matrix[i][j][1];
                    matrixLeft[i - 7][j][2] = matrix[i][j][2];
                }
            }
        }
    }

    private void initializeInputStream() {
        try {
            InputStream input = localHost.getInputStream();
            in = new ObjectInputStream(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void waitForMatrix() {
        System.out.println("Waiting for Matrix");
        try {
            matrixData = (Matrix) in.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        this.matrix = matrixData.matrix;
    }

    class SerialJSONWriter implements AutoCloseable {

        // Zuweisen der seriellen Ports
//      private final SerialPort /*arduino1, arduino2,*/ arduinoMega;
        private jssc.SerialPort arduinoMega;

        public SerialJSONWriter() {
//          arduino1 = SerialPort.getCommPort("COM5");
//          arduino2 = SerialPort.getCommPort("COM6");
//          arduinoMega = SerialPort.getCommPort("COM7");
            arduinoMega = new jssc.SerialPort("COM7");
            try {
                arduinoMega.openPort();
                arduinoMega.setParams(115200, 8, 1, jssc.SerialPort.PARITY_EVEN);
            } catch (SerialPortException e) {
                e.printStackTrace();
            }
//          arduinoMega.setBaudRate(115200);
//          arduinoMega.setNumDataBits(8);
//          arduinoMega.setNumStopBits(1);
//          arduinoMega.setParity(0);

            // setzen der Timeouts für die Kommunikation mit den Arduinos
//          arduino1.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
//          arduino2.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
//          arduinoMega.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
//          arduino1.setBaudRate(115200);
//          arduino2.setBaudRate(115200);
//          arduinoMega.setBaudRate(115200);
//          arduino1.openPort();
//          arduino2.openPort();
//          arduinoMega.openPort();
//          arduino1.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 0,
//                  0);
//          arduino2.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 0,
//                  0);

//          arduinoMega.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 0,
//                  0);
        }

        public void write() {

        }

        private void tryWrite(Object dataRight, Object dataLeft) throws IOException {
            String dataAsJSONRight = new ObjectMapper().writeValueAsString(dataRight) + "\n";
            String dataAsJSONLeft = new ObjectMapper().writeValueAsString(dataLeft) + "\n";
            try {
                arduinoMega.writeString(dataAsJSONRight);
            } catch (SerialPortException e) {
                e.printStackTrace();
            }
//          for (int i = 0; i < dataAsJSONRight.length(); i++) {
////                arduino1.getOutputStream().write(dataAsJSONRight.getBytes()[i]);
//              System.out.println(dataAsJSONRight);
//              arduinoMega.getOutputStream().write(dataAsJSONRight.getBytes()[i]);
//          }
//          for (int i = 0; i < dataAsJSONLeft.length(); i++) {
////                arduino2.getOutputStream().write(dataAsJSONLeft.getBytes()[i]);
//              arduinoMega.getOutputStream().write(dataAsJSONLeft.getBytes()[i]);
//          }
        }

        @Override
        public void close() throws Exception {
//          arduino1.closePort();
//          arduino2.closePort();
            arduinoMega.closePort();
        }
    }
}

On the Arduino(s) the processing looks like this:

#include <ArduinoJson.h>
#include <Adafruit_NeoPixel.h>

#define PINROW0 2
#define PINROW1 3
#define PINROW2 4
#define PINROW3 5
#define PINROW4 6
#define PINROW5 7
#define PINROW6 8

#define NUMPIXELS 14 //Amount of pixels per row

Adafruit_NeoPixel row[] = { //Intitialize the array, that contains the addressable LED strips in the Adafruit format
  Adafruit_NeoPixel(NUMPIXELS, PINROW0, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW1, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW2, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW3, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW4, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW5, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW6, NEO_GRB + NEO_KHZ800)
};

#define DELAY 1000 //set refresh cycle to 10 milliseconds
#define NUMSTRIPS 7/*(sizeof(row)/sizeof(row[0]))*/ //Amount of connected LED strips

int values[7][14][3];
int c = 0;
String matrixAsString = "";

void setup() {

  /*Setup serial port on which the Pi connects to the Arduino*/
  Serial.begin(115200); //set baudrate to 115200 Bit per second
  Serial.setTimeout(1000);

  Serial.println(100);

  /*initialize NeoPixel Library*/
  for (int i = 0; i < NUMSTRIPS; i++) {
    row[i].begin();
    row[i].show();
  }
}

void process(String matrixAsString) {
  StaticJsonDocument<4372> doc;
  Serial.println(matrixAsString);
  deserializeJson(doc, matrixAsString);

  for (int i = 0; i < 7; i++) {
    for (int j = 0; i < 14; j++) {
      values[i][j][0] = values[i][j][1] = values[i][j][2] = (int) (doc[i][j][0]);
    }
  }
}

//infinite loop refreshing the matrix
void loop() {

  while (Serial.available()) {
    char c = Serial.read();
    Serial.println(matrixAsString);
    matrixAsString += c;
    if (c == '\n') {
      process(matrixAsString);
      matrixAsString = "";
    }

  }

}

When sending the data for a half matrix (so an int[7][14][3]):

[[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[255,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]]

through the serial monitor in the Arduino IDE I get this output from the Arduino (as of the Serial.println() in void loop):

As one can see the first RGB values are transmitted correctly, however after even less than one complete LED strip the data arrives in the wrong order and (as you can see at the end of the picture) at some point completely stops showing up, which probably indicates no data is being read any more.

I've been trying a hell of things like changing the Arduino in case the PL2303 is outdated or defective as well as trying different libraries for serial communication however I cannot figure out what I'm doing wrong. I've spent over 30 hours trying different approaches to no avail so things are becoming really frustrating for me.

UPDATE

As suggested by B.Letz I got the setup of the data, stop and parity bits right (now being 8 data, 1 stop and no parity bits). By reading the arduino feedback I still got the same results but after some tweeking I recognized that the problem probably was that my Serial.print apparently led to a massive lag on the Arduino so it couldn't handle all the data correctly and in time. After removing the first Serial.print call before doing the processing I now see the first matrix that is being transmitted being printed correctly by the Arduino. However for some reason for all further transmitted data the Arduino prints null. I'll try extending the timeouts in case the null pointer occurs due to a timeout on the Arduino-side.

UPDATE 2

Opposed to my assumption reconfiguring the timeouts didn't solve the problem. I also figured out that after the first JSON Object is sent the Arduino prints null to the console and only sends me the first JSON object after receiving the second JSON object. However this is the only time I get any feedback from the Arduino except null. What I also noticed is that when I send the JSON String over the serial monitor the Arduino instantly prints the correct String BUT it also prints an empty new line and doesn't respond to any new data in any kind.


问:
ERR_SSL_PROTOCOL_ERROR not able to see https localhost pages in chrome browser
Not able to see the localhost https page properly in chrome . It says :

```<code>**This site can’t provide a secure connection**
localhost sent an invalid response.
Try running Windows Network Diagnostics.
ERR_SSL_PROTOCOL_ERROR
</code>```

I tried -deleting domain localhost from - chrome://net-internals/#hsts
But not helped.

答: Try clearing your website data and cache from chrome. Old htaccess files can cause problems on localhost.</p>

ContentLicense: CC BY-SA 3.0

Body:
Not able to see the localhost https page properly in chrome . It says :

**This site can’t provide a secure connection**
localhost sent an invalid response.
Try running Windows Network Diagnostics.
ERR_SSL_PROTOCOL_ERROR

I tried -deleting domain localhost from - chrome://net-internals/#hsts
But not helped.


问:
Replace capital letters in an entire string with lowercase letters and hyphens
I'm trying to replace the capital letters in an entire string with their lower case counter parts while adding hyphen after it (unless its the last letter). So that Sunny&Cloudy would be come sunny-&-cloudy

```<code>var name = 'Sunny&Cloudy';
name.replace(/([A-Z])(.*)/, '\L$1');
</code>```

I've tried this this myself but it only reaches the first capital letter adds a hyphen and stops. Leaving me with -S

答:
The following regex should do the trick:

```<code>const regex = /(.+?\b)+?/g;
const str = 'Sunny&Cloudy&rainy';
const subst = '$1-';
const result = str.replace(regex, subst);

//make string lowercase + remove last '-'
console.log('Substitution result: ', result.toLowerCase().substring(0, result.length - 1));
</code>```

By the way regex101.com can come in handy to perfect a regex. You can select the 'ECMAScript/JavaScript' regex option. I use that site whenever I need to create a regex.

Body:
I'm trying to replace the capital letters in an entire string with their lower case counter parts while adding hyphen after it (unless its the last letter). So that Sunny&Cloudy would be come sunny-&-cloudy

var name = 'Sunny&Cloudy';
name.replace(/([A-Z])(.*)/, '\L$1');

I've tried this this myself but it only reaches the first capital letter adds a hyphen and stops. Leaving me with -S

Body:
The following regex should do the trick:

const regex = /(.+?\b)+?/g;
const str = 'Sunny&Cloudy&rainy';
const subst = '$1-';
const result = str.replace(regex, subst);

//make string lowercase + remove last '-'
console.log('Substitution result: ', result.toLowerCase().substring(0, result.length - 1));

By the way regex101.com can come in handy to perfect a regex. You can select the 'ECMAScript/JavaScript' regex option. I use that site whenever I need to create a regex.


问:
Cannot ssh into EC2 instance from Windows using Putty
I was using a Mac to ssh into my ec2 instance, I am now using a Windows laptop and I cannot connect to the ec2 instance, any recommendations? I have followed the instructions using Putty but it still does not connect. I have even tried using MobaXterm to ssh into my a Ubuntu machine and then ssh from there and that still does not work either. I receive timeout errors in both cases. I have also checked the VPC and Subnets and everything in the route table is connected to each other how it should be. The Mac connection still works but I am just having trouble connecting through the Windows machine (using Putty).</p>

答:
The following is a helpful walk through guide: https://www2.linuxacademy.com/howtoguides/17385-use-putty-to-access-ec2-linux-instances-via-ssh-from-windows/

Ensure that you transform the .pem to a .ppk file using PuttyGen found here: https://www.ssh.com/ssh/putty/windows/puttygen#sec-PuTTYgen-download-and-install

Note: the user you login as by default one of the following:

•For an Amazon Linux AMI, the user name is ec2-user.

•For a RHEL AMI, the user name is ec2-user or root.

•For an Ubuntu AMI, the user name is ubuntu or root.

•For a Centos AMI, the user name is centos.

•For a Fedora AMI, the user name is ec2-user.

•For SUSE, the user name is ec2-user or root.

•Otherwise, if ec2-user and root don’t work, check with the AMI provider.

Open Putty and add your the username@xxx.xxx.xxx.xxx (replace with your ec2's IP) to the host section

use port 22

Click the 'Auth' section on the right panel and select your .ppk file

Go back to the 'Session' section and click 'open'


问:
How to compare BIGINT in Pig
In table commit_time is BIGINT and value store is like 20190508143744
when I try to compare with commit_time > 1000 it works without error
but when I try with commit_time > 20190508143743, it gives error as below

2019-05-29 17:35:38,390 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: For input string: "20190508143743"

Steps:

```<code>pig -useHCatalog

custProf = LOAD 'alisy3p.cust_change' using org.apache.hive.hcatalog.pig.HCatLoader();

// this step gives error
deviceChange= filter custProf by (commit_time > 20190508143743);
</code>```

Also Tried:

deviceChange= filter custProf by (commit_time > (bigint)20190508143743);

deviceChange= filter custProf by (commit_time > (long)20190508143743);

答:
According to the Pig documentation, you should be able to specific a biginteger constant by adding BI to the end of the number. Try this:

```<code>deviceChange = filter custProf by (commit_time > 20190508143743BI);
</code>```

Title: How to compare BIGINT in Pig

Body:
In table commit_time is BIGINT and value store is like 20190508143744
when I try to compare with commit_time > 1000 it works without error
but when I try with commit_time > 20190508143743, it gives error as below

2019-05-29 17:35:38,390 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: For input string: "20190508143743"

Steps:

pig -useHCatalog

custProf = LOAD 'alisy3p.cust_change' using org.apache.hive.hcatalog.pig.HCatLoader();

// this step gives error
deviceChange= filter custProf by (commit_time > 20190508143743);

Also Tried:

deviceChange= filter custProf by (commit_time > (bigint)20190508143743);

deviceChange= filter custProf by (commit_time > (long)20190508143743);

Body:
According to the Pig documentation, you should be able to specific a biginteger constant by adding BI to the end of the number. Try this:

deviceChange = filter custProf by (commit_time > 20190508143743BI);


问:
Update DLL used by a SSIS on server
I developed a dll used by a SSIS to be able to perform web api call.
This dll is registered with regasm and gacutil to be able to use it with the task script in the SSIS.
I updated the dll, I deployed it and register the new version with regasm and gacutil.
When I run the SSIS, the result still the same as the old version of the dll. So I presume that the dll still loaded in the memory.

In the server, I already stop/start the services SQL Server and SQL Server Agent but I still have the issue.

Any ideas ?

答:
When looking into my old deployment code I always removed old version from GAC using:

```<code>(path)\bin\gacutil.exe –u assembly_name
(path)\bin\gacutil.exe –i assembly_file_name
</code>```

If it is a custom component, I copied the dll to (SQLServerpath)\DTS\PipelineComponents

Title: Update DLL used by a SSIS on server

Body:
When looking into my old deployment code I always removed old version from GAC using:

(path)\bin\gacutil.exe –u assembly_name
(path)\bin\gacutil.exe –i assembly_file_name

If it is a custom component, I copied the dll to (SQLServerpath)\DTS\PipelineComponents


问:
ReferenceError when running javascript in a Laravel Blade
I am trying to run a simple javascript function from app.js in a blade but I am getting a ReferenceError that the function is not defined.

The "app.js" was compiled with "npm run dev".

The file "app.js" in binded and I can see my function there.

app.js

```<code>require('./bootstrap');

function myTest()
{
    alert(1);
}
</code>```

index.blade.php

```<code>@extends('layout')

@section('title', 'Some Title')

@section('content')
    Welcome
@endsection

@section('scripts')
    <script>myTest();</script>
@endsection
</code>```

Source code

```<code><html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="DeUaExASeRzE1Wl0OUAyVFhmHQ7DZNfbZR7kETJ7">
    <script src="http://127.0.0.1:8000/js/app.js"></script>
    <link rel="stylesheet" href="http://127.0.0.1:8000/css/app.css">
    <title>WOG</title>
</head>
<body>
    <!-- ######### NavBar ######### -->
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="container">
      <a class="navbar-brand" href="/">WOG</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavDropdown">
          <ul class="navbar-nav">
            <li class="nav-item">
              <a class="nav-link active" href="/">Home</a>
            </li>
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Module</a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                <a class="dropdown-item" href="/modules/alphanum">Alphanumerisch</a>
                <a class="dropdown-item" href="/modules/num">Numerisch</a>
              </div>
            </li>
          </ul>
        </div>
        </div>
      </nav>

    <!-- ######### Content ######### -->
    <div class="container">
            <h1>Willkommen</h1>
            <script>myTest();</script>
    </div>
  </body>
</html>
</code>```

I was expecting to get a simple alert, but instead i am getting a "ReferenceError: myTest is not defined".

What can i do?

Thanks in advance

答:
Compiling with Laravel Mix runs your code through webpack and puts it in a bundle. It won't add anything to the global scope. If you really want that function in the global scope, assign it directly to document or window:

In app.js:

```<code>require('./bootstrap');

window.myTest = function myTest() {
    alert(1);
}
</code>```

It's also recommended that you load your static assets with the helper function in blade

```<code><script src="{{asset('js/app.js')}}"></script>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</code>```

Body:
I am trying to run a simple javascript function from app.js in a blade but I am getting a ReferenceError that the function is not defined.

The "app.js" was compiled with "npm run dev".

The file "app.js" in binded and I can see my function there.

app.js

require('./bootstrap');

function myTest()
{
    alert(1);
}

index.blade.php

@extends('layout')

@section('title', 'Some Title')

@section('content')
    Welcome
@endsection

@section('scripts')

@endsection

Source code

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="DeUaExASeRzE1Wl0OUAyVFhmHQ7DZNfbZR7kETJ7">

    <link rel="stylesheet" href="http://127.0.0.1:8000/css/app.css">
    <title>WOG</title>

      WOG
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home

              Module

                Alphanumerisch
                Numerisch

Willkommen

I was expecting to get a simple alert, but instead i am getting a "ReferenceError: myTest is not defined".

What can i do?

Thanks in advance

Body:
Compiling with Laravel Mix runs your code through webpack and puts it in a bundle. It won't add anything to the global scope. If you really want that function in the global scope, assign it directly to document or window:

In app.js:

require('./bootstrap');

window.myTest = function myTest() {
    alert(1);
}

It's also recommended that you load your static assets with the helper function in blade

<script src="{{asset('js/app.js')}}"></script>
<link rel="stylesheet" href="{{asset('css/app.css')}}">


问:
S3Client::GetObject with SetRange returns wrong data?
I am attempting to read a segment of a large AWS S3 Object starting with the first 1048576 bytes.  I specify the range of bytes that I want to read but I do not receive those bytes.  The length returned is correct.

I am fairly new at this so I'm probably doing something wrong and being a C programmer instead of C++ has not helped a lot.

Here's a sample of my code:

```<code>int   start=0, rbytes=0;

Aws::S3::S3Client  s3_client;
Aws::S3::Model::GetObjectRequest read_object_request;
sprintf(range,"bytes=%lld-%lld",start,start+1048575);

read_object_request.SetBucket(container_name);
read_object_request.SetKey(object_name);
read_object_request.SetRange(range);
auto results = s3_client.GetObject(read_object_request);
if (results.IsSuccess())
{
   rbytes = results.GetResult().GetContentLength();
   std::cout << rbytes << " bytes read" << std::endl;
}
memcpy(bdata,results.GetResult().GetBody().rdbuf(),rbytes);
</code>```

I then dump the bdata buffer and it is not what I expected.  When I repeat the execution of the code, a new instance, it returns different data.

Though I don't show it the   bdata  buffer is pre-allocated 2 megabytes.

Any ideas that would point me in the right direction would be appreciated.

Thanks in advance.

答: rdbuf() is a stream and you are treating it as a memory pointer.

Body:
I am attempting to read a segment of a large AWS S3 Object starting with the first 1048576 bytes.  I specify the range of bytes that I want to read but I do not receive those bytes.  The length returned is correct.

I am fairly new at this so I'm probably doing something wrong and being a C programmer instead of C++ has not helped a lot.

Here's a sample of my code:

int   start=0, rbytes=0;

Aws::S3::S3Client  s3_client;
Aws::S3::Model::GetObjectRequest read_object_request;
sprintf(range,"bytes=%lld-%lld",start,start+1048575);

read_object_request.SetBucket(container_name);
read_object_request.SetKey(object_name);
read_object_request.SetRange(range);
auto results = s3_client.GetObject(read_object_request);
if (results.IsSuccess())
{
   rbytes = results.GetResult().GetContentLength();
   std::cout << rbytes << " bytes read" << std::endl;
}
memcpy(bdata,results.GetResult().GetBody().rdbuf(),rbytes);

I then dump the bdata buffer and it is not what I expected.  When I repeat the execution of the code, a new instance, it returns different data.

Though I don't show it the   bdata  buffer is pre-allocated 2 megabytes.

Any ideas that would point me in the right direction would be appreciated.

Thanks in advance.


问:
Allow playing mp3 files in the website but prevent download from a direct link
I'm having a codeigniter project for playing and downloading mp3 files. Users and admins can play mp3 files from the front-end and the back-end but users shouldn't be able to download these files except from the download controller using the download helper. That's what I did so far I added htaccess file in the sound directory to prevent direct download and it works but that prevents users from playing mp3 files at all.

```<code><FilesMatch "\.(mp3)$">
Order allow,deny
Deny from all
</FilesMatch>
</code>```

And the download controller works fine to allow specific users to download these files. How to edit it to allow playing mp3 files in that directory without direct access to full download path?

I want to access mp3 files from specific pages to play it and to download it and deny any other direct access to it.

Please not that the audio element in the project uses the absolute path to the mp3 file to play it. I even tried using relative path to it but didn't play too

答:
Here's an idea

Use a PHP file as the MP3...

I know this sounds weird but technically a PHP file can be interpreted as ANY file type

Your front end:

```<code><audio controls>
  <source src="music.php?token=as5df65s1df" type="audio/mpeg">
</audio>
</code>```

Let me explain this:
When the user visits the page, set a access token that can only be used once, set it on src and set it in session

```<code>$_SESSION['securePlay'] = 'as5df65s1df';
</code>```

```<code>if(!isset($_GET['token'])){
  //No token? They tried to view the file
  die('access denied');
}

if($_GET['token'] == $_SESSION['securePlay']){
// The one time token hasn't been used yet
// Go ahead and mimic an MP3 and play the music

  $file = 'realMusic.mp3';

  if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
  }

  //Here is where you'll want to invalidate the current token and get a new one

} else {
  //The tokens don't match meaning you got a new one and the old one cant be used anymore
  die('access denied');
}

</code>```

This does the following:
When a user visit page, hits play, it works because the token is used
When a user visits the audio src page, the get token isn't set, access denied
When a user visits the audio src page, the get was already loaded on initial load, so it's expired
If someone uses inspect to view the src file and they right-click and save the source, the token has already been used, access denied

This is NOT a bullet proof system but it's dang good for an average website

If it's a valid play, the php file will appear as an mp3 file
If it's not a valid play, it appears as a php file and access is denied

You'll also want to put the mp3 files outside of the public folder so only the php file reader can access them. The client will never see a .mp3 file and if you did decide to put the mp3 files in public view, they would have to guess the path to view it.

My recommendation is use the JS audio api and every time you want to play a song, create a new audio object and get a new token via AJAX

Note: while getting a new token, use POST or anything but get, we want to avoid the client from going to that route manually and getting a token

Body:
I'm having a codeigniter project for playing and downloading mp3 files. Users and admins can play mp3 files from the front-end and the back-end but users shouldn't be able to download these files except from the download controller using the download helper. That's what I did so far I added htaccess file in the sound directory to prevent direct download and it works but that prevents users from playing mp3 files at all.

<FilesMatch "\.(mp3)$">
Order allow,deny
Deny from all
</FilesMatch>

And the download controller works fine to allow specific users to download these files. How to edit it to allow playing mp3 files in that directory without direct access to full download path?

I want to access mp3 files from specific pages to play it and to download it and deny any other direct access to it.

Please not that the audio element in the project uses the absolute path to the mp3 file to play it. I even tried using relative path to it but didn't play too

Body:
Here's an idea

Use a PHP file as the MP3...

I know this sounds weird but technically a PHP file can be interpreted as ANY file type

Your front end:

<audio controls>
  <source src="music.php?token=as5df65s1df" type="audio/mpeg">
</audio>

Let me explain this:
When the user visits the page, set a access token that can only be used once, set it on src and set it in session

$_SESSION['securePlay'] = 'as5df65s1df';

if(!isset($_GET['token'])){
  //No token? They tried to view the file
  die('access denied');
}

if($_GET['token'] == $_SESSION['securePlay']){
// The one time token hasn't been used yet
// Go ahead and mimic an MP3 and play the music

  $file = 'realMusic.mp3';

  if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
  }

  //Here is where you'll want to invalidate the current token and get a new one

} else {
  //The tokens don't match meaning you got a new one and the old one cant be used anymore
  die('access denied');
}

This does the following:
When a user visit page, hits play, it works because the token is used
When a user visits the audio src page, the get token isn't set, access denied
When a user visits the audio src page, the get was already loaded on initial load, so it's expired
If someone uses inspect to view the src file and they right-click and save the source, the token has already been used, access denied

This is NOT a bullet proof system but it's dang good for an average website

If it's a valid play, the php file will appear as an mp3 file
If it's not a valid play, it appears as a php file and access is denied

You'll also want to put the mp3 files outside of the public folder so only the php file reader can access them. The client will never see a .mp3 file and if you did decide to put the mp3 files in public view, they would have to guess the path to view it.

My recommendation is use the JS audio api and every time you want to play a song, create a new audio object and get a new token via AJAX

Note: while getting a new token, use POST or anything but get, we want to avoid the client from going to that route manually and getting a token


问:
Empty variable due to asynchronous callback
There is some very simplified pseudo-ish code to understand the structure of my code.

What would be a simple approach to solve my asynchronous callback dilemma.

The token will be empty when it's used in requestOption. So the following usage of requestOption will not give any results due to the missing token.

```<code>var token = ''
var auth1 = someData
var auth2 = someFunc(auth1)
var auth3 = someOtherData
var auth4 = someOtherFunc(auth3)
var finalAuth = someFinalData
var finalAuth2 = finalAuth.someFinalFunc(auth4, cb)
  cb.onSuccess(result)
    token = result.getToken()

var requestOption = {
  someData: ...,
  'authToken': token,
  someMoreData: ...
}
req = request.post(requestOption)
</code>```

There are many solutions and most of them includes using functions to some extend.

Maybe it is useful to modularize the authentication and processing the the requests in another file.

But I would like to keep it simple and not be dependant on something like this

```<code>var empty = ''
var data = 'xyz'
auth(data, {
    onSuccess: function(res) {
        doSomething(res)
    }
})

function doSomething(var) {
 // do something
}
</code>```

What I found so far couldn't help me without overcomplicating my code.

答: You should include your request logic inside the success callback. In your case, your code with request and request options are executed before setting the value of the token, because auth function is asynchronous and the server need some time to respond.</p>

Body:
There is some very simplified pseudo-ish code to understand the structure of my code.

What would be a simple approach to solve my asynchronous callback dilemma.

The token will be empty when it's used in requestOption. So the following usage of requestOption will not give any results due to the missing token.

var token = ''
var auth1 = someData
var auth2 = someFunc(auth1)
var auth3 = someOtherData
var auth4 = someOtherFunc(auth3)
var finalAuth = someFinalData
var finalAuth2 = finalAuth.someFinalFunc(auth4, cb)
  cb.onSuccess(result)
    token = result.getToken()

var requestOption = {
  someData: ...,
  'authToken': token,
  someMoreData: ...
}
req = request.post(requestOption)

There are many solutions and most of them includes using functions to some extend.

Maybe it is useful to modularize the authentication and processing the the requests in another file.

But I would like to keep it simple and not be dependant on something like this

var empty = ''
var data = 'xyz'
auth(data, {
    onSuccess: function(res) {
        doSomething(res)
    }
})

function doSomething(var) {
 // do something
}

What I found so far couldn't help me without overcomplicating my code.


问:
How do I update a value in table A when creating a row in table B?
My platform has two tables UserInfo and PersonalInfo. When a user creates a profile the data is saved in UserInfo. The view for UserInfo has an @Html.EditorFor, which is auto populated from Active Directory(if the AD field  is null, a helper class adds N/A in its place). Depending on what application the user decides to use within the platform, more information will be needed so they will need to create a row in PersonalInfo. The view for PersonalInfo as a @Html.DropDownListFor that the user can choose from which will update that users department and cost center.

I would like to update the department for UserInfo when the row for PersonalInfo is created or updated.

Currently when I create a row it looks like this:

```<code>if (ModelState.IsValid)
{
var myUserInfo = new myUserInfo
{
    UserId = userNum.Id,
    Address = viewModel.Address,
    City = viewModel.City,
    State = viewModel.State,
    CellPhone = viewModel.CellPhone,
    Department = viewmodel.Department,
    CostCenter = viewmodel.CostCenter,
    ZipCode = viewModel.ZipCode
};
db.MyUserInfos.Add(myUserInfo);
db.SaveChanges();
}
</code>```

How do I update the Department field only in the  PersonalInfo table before db.SaveChanges() is called?

答:
add a row in tableB:-

```<code>var tableB = new TableB
{
    UserId = userNum.Id,
    Address = viewModel.Address,
    City = viewModel.City,
    State = viewModel.State,
    CellPhone = viewModel.CellPhone,
    Department = viewmodel.Department,
    CostCenter = viewmodel.CostCenter,
    ZipCode = viewModel.ZipCode
};
db.MyTableB.Add(tableB);
</code>```

update a row in tableA:-

```<code>var tableA = db.MyTableA.Find(tableAId);

tableA.Department = viewModel.Department;

db.MyTableA.Attach(tableA);
db.Entry(tableA).State = EntityState.Modified
</code>```

once you have made all the your required changes, call db.SaveChanges();

Body:
My platform has two tables UserInfo and PersonalInfo. When a user creates a profile the data is saved in UserInfo. The view for UserInfo has an @Html.EditorFor, which is auto populated from Active Directory(if the AD field  is null, a helper class adds N/A in its place). Depending on what application the user decides to use within the platform, more information will be needed so they will need to create a row in PersonalInfo. The view for PersonalInfo as a @Html.DropDownListFor that the user can choose from which will update that users department and cost center.

I would like to update the department for UserInfo when the row for PersonalInfo is created or updated.

Currently when I create a row it looks like this:

if (ModelState.IsValid)
{
var myUserInfo = new myUserInfo
{
    UserId = userNum.Id,
    Address = viewModel.Address,
    City = viewModel.City,
    State = viewModel.State,
    CellPhone = viewModel.CellPhone,
    Department = viewmodel.Department,
    CostCenter = viewmodel.CostCenter,
    ZipCode = viewModel.ZipCode
};
db.MyUserInfos.Add(myUserInfo);
db.SaveChanges();
}

How do I update the Department field only in the  PersonalInfo table before db.SaveChanges() is called?

Body:
add a row in tableB:-

var tableB = new TableB
{
    UserId = userNum.Id,
    Address = viewModel.Address,
    City = viewModel.City,
    State = viewModel.State,
    CellPhone = viewModel.CellPhone,
    Department = viewmodel.Department,
    CostCenter = viewmodel.CostCenter,
    ZipCode = viewModel.ZipCode
};
db.MyTableB.Add(tableB);

update a row in tableA:-

var tableA = db.MyTableA.Find(tableAId);

tableA.Department = viewModel.Department;

db.MyTableA.Attach(tableA);
db.Entry(tableA).State = EntityState.Modified

once you have made all the your required changes, call db.SaveChanges();


问:
Installing node-sass fails on Ubuntu 18.04
I have a simple next.js project, which I created following their tutorial. It builds and runs well on my Windows development machine.

I want to deploy it on Ubuntu 18.04.02 LTS but when I clone the git project and run npm install it fails to install node-sass with the following error message:

```<code>> node-sass@4.12.0 install /var/www/example.com/beta/node_modules/node-sass
> node scripts/install.js

internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module '/var/www/example.com/beta/node_modules/node-sass/scripts/install.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.12.0 install: `node scripts/install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.12.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: ...
</code>```

Here is a gist of the log file. See the last few lines for the error (I have included the whole file in case there is other information that is useful).

My NodeJS version is 10.15.3 and my NPM version is 6.4.1. I am not sure how to run next.js project on Ubuntu.

答:
Try installing it manually, prior to installing all of the other packages - there might be some package dependency issue.

npm install node-sass@4.12.0 && npm install

Body:
I have a simple next.js project, which I created following their tutorial. It builds and runs well on my Windows development machine.

I want to deploy it on Ubuntu 18.04.02 LTS but when I clone the git project and run npm install it fails to install node-sass with the following error message:

> node-sass@4.12.0 install /var/www/example.com/beta/node_modules/node-sass
> node scripts/install.js

internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module '/var/www/example.com/beta/node_modules/node-sass/scripts/install.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.12.0 install: `node scripts/install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.12.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: ...

Here is a gist of the log file. See the last few lines for the error (I have included the whole file in case there is other information that is useful).

My NodeJS version is 10.15.3 and my NPM version is 6.4.1. I am not sure how to run next.js project on Ubuntu.


问:
WSDL Import Issues with Delphi 7
I have a WSDL, I tried to import it in Delphi 7 but I got the next message

```<code>// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL     : http://201.155.181.40:59080/axis2/services/TimbradorIntegradores?wsdl
// Encoding : UTF-8
// Version  : 1.0
// (12/04/2011 08:57:28 a.m. - 1.33.2.5)
// ************************************************************************ //

unit TimbradorIntegradores;

interface

uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;

type

  // ************************************************************************ //
  // The following types, referred to in the WSDL document are not being represented
  // in this file. They are either aliases[@] of other types represented or were referred
  // to but never[!] declared in the document. The types from the latter category
  // typically map to predefined/known XML or Borland types; however, they could also
  // indicate incorrect WSDL documents that failed to declare or import a schema type.
  // ************************************************************************ //

implementation

initialization

end.
</code>```

I was reading something about it, a lot of people says that is for Delphi's version, I'm working with Delphi 7, they say that in Delphi 10 it's possible to do that, does somebody know something about it?

Thanks in advance,
Best regards

答:
Below is what Delphi XE makes of it.

I think it can compile in Delphi 7, let us know if it does.

```<code>// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL     : http://201.155.181.40:59080/axis2/services/TimbradorIntegradores?wsdl
//  >Import : http://201.155.181.40:59080/axis2/services/TimbradorIntegradores?wsdl>0
// Encoding : UTF-8
// Version  : 1.0
// (4/12/2011 4:32:56 PM - - $Rev: 34800 $)
// ************************************************************************ //

unit TimbradorIntegradores;

interface

uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;

const
  IS_OPTN = $0001;
  IS_NLBL = $0004;
  IS_REF  = $0080;

type

  // ************************************************************************ //
  // The following types, referred to in the WSDL document are not being represented
  // in this file. They are either aliases[@] of other types represented or were referred
  // to but never[!] declared in the document. The types from the latter category
  // typically map to predefined/known XML or Embarcadero types; however, they could also
  // indicate incorrect WSDL documents that failed to declare or import a schema type.
  // ************************************************************************ //
  // !:string          - "http://www.w3.org/2001/XMLSchema"[Gbl]
  // !:anyType         - "http://www.w3.org/2001/XMLSchema"[Gbl]

  Exception2           = class;                 { "http://integradores.cfdi.mx.konesh.com"[GblCplx] }
  Exception            = class;                 { "http://integradores.cfdi.mx.konesh.com"[Flt][GblElm] }

  // ************************************************************************ //
  // XML       : Exception, global, <complexType>
  // Namespace : http://integradores.cfdi.mx.konesh.com
  // ************************************************************************ //
  Exception2 = class(TRemotable)
  private
    FException: Variant;
    FException_Specified: boolean;
    procedure SetException(Index: Integer; const AVariant: Variant);
    function  Exception_Specified(Index: Integer): boolean;
  published
    property Exception: Variant  Index (IS_OPTN or IS_NLBL) read FException write SetException stored Exception_Specified;
  end;

  // ************************************************************************ //
  // XML       : Exception, global, <element>
  // Namespace : http://integradores.cfdi.mx.konesh.com
  // Info      : Fault
  // ************************************************************************ //
  Exception = class(ERemotableException)
  private
    FException: Exception2;
    FException_Specified: boolean;
    procedure SetException(Index: Integer; const AException2: Exception2);
    function  Exception_Specified(Index: Integer): boolean;
  public
    destructor Destroy; override;
  published
    property Exception: Exception2  Index (IS_OPTN or IS_NLBL) read FException write SetException stored Exception_Specified;
  end;

  // ************************************************************************ //
  // Namespace : http://integradores.cfdi.mx.konesh.com
  // soapAction: urn:get
  // transport : http://schemas.xmlsoap.org/soap/http
  // style     : document
  // use       : literal
  // binding   : TimbradorIntegradoresSoap12Binding
  // service   : TimbradorIntegradores
  // port      : TimbradorIntegradoresHttpSoap12Endpoint
  // URL       : http://201.155.181.40:59080/axis2/services/TimbradorIntegradores.TimbradorIntegradoresHttpSoap12Endpoint/
  // ************************************************************************ //
  TimbradorIntegradoresPortType = interface(IInvokable)
  ['{85D3323D-9BEE-180B-C748-39D139E150FE}']
    function  get(const cad: string; const tk: string; const user: string; const pass: string; const cuenta: string): string; stdcall;
  end;

function GetTimbradorIntegradoresPortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): TimbradorIntegradoresPortType;

implementation
  uses SysUtils;

function GetTimbradorIntegradoresPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): TimbradorIntegradoresPortType;
const
  defWSDL = 'http://201.155.181.40:59080/axis2/services/TimbradorIntegradores?wsdl';
  defURL  = 'http://201.155.181.40:59080/axis2/services/TimbradorIntegradores.TimbradorIntegradoresHttpSoap12Endpoint/';
  defSvc  = 'TimbradorIntegradores';
  defPrt  = 'TimbradorIntegradoresHttpSoap12Endpoint';
var
  RIO: THTTPRIO;
begin
  Result := nil;
  if (Addr = '') then
  begin
    if UseWSDL then
      Addr := defWSDL
    else
      Addr := defURL;
  end;
  if HTTPRIO = nil then
    RIO := THTTPRIO.Create(nil)
  else
    RIO := HTTPRIO;
  try
    Result := (RIO as TimbradorIntegradoresPortType);
    if UseWSDL then
    begin
      RIO.WSDLLocation := Addr;
      RIO.Service := defSvc;
      RIO.Port := defPrt;
    end else
      RIO.URL := Addr;
  finally
    if (Result = nil) and (HTTPRIO = nil) then
      RIO.Free;
  end;
end;

procedure Exception2.SetException(Index: Integer; const AVariant: Variant);
begin
  FException := AVariant;
  FException_Specified := True;
end;

function Exception2.Exception_Specified(Index: Integer): boolean;
begin
  Result := FException_Specified;
end;

destructor Exception.Destroy;
begin
  SysUtils.FreeAndNil(FException);
  inherited Destroy;
end;

procedure Exception.SetException(Index: Integer; const AException2: Exception2);
begin
  FException := AException2;
  FException_Specified := True;
end;

function Exception.Exception_Specified(Index: Integer): boolean;
begin
  Result := FException_Specified;
end;

initialization
  { TimbradorIntegradoresPortType }
  InvRegistry.RegisterInterface(TypeInfo(TimbradorIntegradoresPortType), 'http://integradores.cfdi.mx.konesh.com', 'UTF-8');
  InvRegistry.RegisterDefaultSOAPAction(TypeInfo(TimbradorIntegradoresPortType), 'urn:get');
  InvRegistry.RegisterInvokeOptions(TypeInfo(TimbradorIntegradoresPortType), ioDocument);
  InvRegistry.RegisterInvokeOptions(TypeInfo(TimbradorIntegradoresPortType), ioSOAP12);
  { TimbradorIntegradoresPortType.get }
  InvRegistry.RegisterMethodInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', '',
                                 '[ReturnName="return"]', IS_OPTN or IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'cad', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'tk', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'user', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'pass', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'cuenta', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'return', '',
                                '', IS_NLBL);
  RemClassRegistry.RegisterXSClass(Exception2, 'http://integradores.cfdi.mx.konesh.com', 'Exception2', 'Exception');
  RemClassRegistry.RegisterXSClass(Exception, 'http://integradores.cfdi.mx.konesh.com', 'Exception');

end.
</code>```

Title: WSDL Import Issues with Delphi 7

Body:
I have a WSDL, I tried to import it in Delphi 7 but I got the next message

// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL     : http://201.155.181.40:59080/axis2/services/TimbradorIntegradores?wsdl
// Encoding : UTF-8
// Version  : 1.0
// (12/04/2011 08:57:28 a.m. - 1.33.2.5)
// ************************************************************************ //

unit TimbradorIntegradores;

interface

uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;

type

  // ************************************************************************ //
  // The following types, referred to in the WSDL document are not being represented
  // in this file. They are either aliases[@] of other types represented or were referred
  // to but never[!] declared in the document. The types from the latter category
  // typically map to predefined/known XML or Borland types; however, they could also
  // indicate incorrect WSDL documents that failed to declare or import a schema type.
  // ************************************************************************ //

implementation

initialization

end.

I was reading something about it, a lot of people says that is for Delphi's version, I'm working with Delphi 7, they say that in Delphi 10 it's possible to do that, does somebody know something about it?

Thanks in advance,
Best regards

Body:
Below is what Delphi XE makes of it.

I think it can compile in Delphi 7, let us know if it does.

// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL     : http://201.155.181.40:59080/axis2/services/TimbradorIntegradores?wsdl
//  >Import : http://201.155.181.40:59080/axis2/services/TimbradorIntegradores?wsdl>0
// Encoding : UTF-8
// Version  : 1.0
// (4/12/2011 4:32:56 PM - - $Rev: 34800 $)
// ************************************************************************ //

unit TimbradorIntegradores;

interface

uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;

const
  IS_OPTN = $0001;
  IS_NLBL = $0004;
  IS_REF  = $0080;

type

  // ************************************************************************ //
  // The following types, referred to in the WSDL document are not being represented
  // in this file. They are either aliases[@] of other types represented or were referred
  // to but never[!] declared in the document. The types from the latter category
  // typically map to predefined/known XML or Embarcadero types; however, they could also
  // indicate incorrect WSDL documents that failed to declare or import a schema type.
  // ************************************************************************ //
  // !:string          - "http://www.w3.org/2001/XMLSchema"[Gbl]
  // !:anyType         - "http://www.w3.org/2001/XMLSchema"[Gbl]

  Exception2           = class;                 { "http://integradores.cfdi.mx.konesh.com"[GblCplx] }
  Exception            = class;                 { "http://integradores.cfdi.mx.konesh.com"[Flt][GblElm] }

  // ************************************************************************ //
  // XML       : Exception, global, <complexType>
  // Namespace : http://integradores.cfdi.mx.konesh.com
  // ************************************************************************ //
  Exception2 = class(TRemotable)
  private
    FException: Variant;
    FException_Specified: boolean;
    procedure SetException(Index: Integer; const AVariant: Variant);
    function  Exception_Specified(Index: Integer): boolean;
  published
    property Exception: Variant  Index (IS_OPTN or IS_NLBL) read FException write SetException stored Exception_Specified;
  end;

  // ************************************************************************ //
  // XML       : Exception, global, <element>
  // Namespace : http://integradores.cfdi.mx.konesh.com
  // Info      : Fault
  // ************************************************************************ //
  Exception = class(ERemotableException)
  private
    FException: Exception2;
    FException_Specified: boolean;
    procedure SetException(Index: Integer; const AException2: Exception2);
    function  Exception_Specified(Index: Integer): boolean;
  public
    destructor Destroy; override;
  published
    property Exception: Exception2  Index (IS_OPTN or IS_NLBL) read FException write SetException stored Exception_Specified;
  end;

  // ************************************************************************ //
  // Namespace : http://integradores.cfdi.mx.konesh.com
  // soapAction: urn:get
  // transport : http://schemas.xmlsoap.org/soap/http
  // style     : document
  // use       : literal
  // binding   : TimbradorIntegradoresSoap12Binding
  // service   : TimbradorIntegradores
  // port      : TimbradorIntegradoresHttpSoap12Endpoint
  // URL       : http://201.155.181.40:59080/axis2/services/TimbradorIntegradores.TimbradorIntegradoresHttpSoap12Endpoint/
  // ************************************************************************ //
  TimbradorIntegradoresPortType = interface(IInvokable)
  ['{85D3323D-9BEE-180B-C748-39D139E150FE}']
    function  get(const cad: string; const tk: string; const user: string; const pass: string; const cuenta: string): string; stdcall;
  end;

function GetTimbradorIntegradoresPortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): TimbradorIntegradoresPortType;

implementation
  uses SysUtils;

function GetTimbradorIntegradoresPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): TimbradorIntegradoresPortType;
const
  defWSDL = 'http://201.155.181.40:59080/axis2/services/TimbradorIntegradores?wsdl';
  defURL  = 'http://201.155.181.40:59080/axis2/services/TimbradorIntegradores.TimbradorIntegradoresHttpSoap12Endpoint/';
  defSvc  = 'TimbradorIntegradores';
  defPrt  = 'TimbradorIntegradoresHttpSoap12Endpoint';
var
  RIO: THTTPRIO;
begin
  Result := nil;
  if (Addr = '') then
  begin
    if UseWSDL then
      Addr := defWSDL
    else
      Addr := defURL;
  end;
  if HTTPRIO = nil then
    RIO := THTTPRIO.Create(nil)
  else
    RIO := HTTPRIO;
  try
    Result := (RIO as TimbradorIntegradoresPortType);
    if UseWSDL then
    begin
      RIO.WSDLLocation := Addr;
      RIO.Service := defSvc;
      RIO.Port := defPrt;
    end else
      RIO.URL := Addr;
  finally
    if (Result = nil) and (HTTPRIO = nil) then
      RIO.Free;
  end;
end;

procedure Exception2.SetException(Index: Integer; const AVariant: Variant);
begin
  FException := AVariant;
  FException_Specified := True;
end;

function Exception2.Exception_Specified(Index: Integer): boolean;
begin
  Result := FException_Specified;
end;

destructor Exception.Destroy;
begin
  SysUtils.FreeAndNil(FException);
  inherited Destroy;
end;

procedure Exception.SetException(Index: Integer; const AException2: Exception2);
begin
  FException := AException2;
  FException_Specified := True;
end;

function Exception.Exception_Specified(Index: Integer): boolean;
begin
  Result := FException_Specified;
end;

initialization
  { TimbradorIntegradoresPortType }
  InvRegistry.RegisterInterface(TypeInfo(TimbradorIntegradoresPortType), 'http://integradores.cfdi.mx.konesh.com', 'UTF-8');
  InvRegistry.RegisterDefaultSOAPAction(TypeInfo(TimbradorIntegradoresPortType), 'urn:get');
  InvRegistry.RegisterInvokeOptions(TypeInfo(TimbradorIntegradoresPortType), ioDocument);
  InvRegistry.RegisterInvokeOptions(TypeInfo(TimbradorIntegradoresPortType), ioSOAP12);
  { TimbradorIntegradoresPortType.get }
  InvRegistry.RegisterMethodInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', '',
                                 '[ReturnName="return"]', IS_OPTN or IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'cad', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'tk', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'user', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'pass', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'cuenta', '',
                                '', IS_NLBL);
  InvRegistry.RegisterParamInfo(TypeInfo(TimbradorIntegradoresPortType), 'get', 'return', '',
                                '', IS_NLBL);
  RemClassRegistry.RegisterXSClass(Exception2, 'http://integradores.cfdi.mx.konesh.com', 'Exception2', 'Exception');
  RemClassRegistry.RegisterXSClass(Exception, 'http://integradores.cfdi.mx.konesh.com', 'Exception');

end.


问:
Check if value is in undefined enum?
I am working on a file that runs on different processors, so the header files change based on the hardware. My program needs to receive an index and, if it is a valid index for a particular enum, use it, otherwise go to a default value.

I need to check if it is a valid index for this enum. HOWEVER, the enum is slightly different processor to processor. I have a header file for each chip, so I don't know how many indices are defined. Here is what it approximately looks like:

```<code>typedef enum
    {
    POWER_LEVEL_0
    POWER_LEVEL_1,
    POWER_LEVEL_2,
    POWER_LEVEL_3,
    POWER_LEVEL_4
    } power_type;
</code>```

and I need to be able to test if a received index is defined, like so:

```<code>int input;
...
if( exists_in_power_type(input) )
    //accept the value
else
    //use default value
</code>```

I know the number of indices will be in the range of about 4 to 7, and that may grow if I run this project on a new processor that may have 8 or more power options. In this case I want my program to be portable and only have to define an enum of the same name in a new header for that processor.

This problem may be a little easier because the enum values just start at 0 and increment by 1. Is there a way to get the length/max value of an enum without knowing its definition? Is there a similar work around that I could use here?

答:
There is no cross-platform way to determine the maximum legal enumerated value for a particular enum. However, you can get around this by introducing a dummy enumerated value that comes after all the others:

```<code>typedef enum
{
    POWER_LEVEL_0
    POWER_LEVEL_1,
    POWER_LEVEL_2,
    POWER_LEVEL_3,
    POWER_LEVEL_4,
    ILLEGAL_POWER_LEVEL // Not to be used directly; must be last
} power_type;
</code>```

Now, you can write your helper function as follows:

```<code>bool exists_in_power_type(power_type value) {
    return 0 <= value && value < ILLEGAL_POWER_LEVEL;
}
</code>```

As long as ILLEGAL_POWER_LEVEL is the last of the enumerated values, this approach will check whether you have something assigned to value that matches some enumeration.

Hope this helps!

Title: Check if value is in undefined enum?

Body:
I am working on a file that runs on different processors, so the header files change based on the hardware. My program needs to receive an index and, if it is a valid index for a particular enum, use it, otherwise go to a default value.

I need to check if it is a valid index for this enum. HOWEVER, the enum is slightly different processor to processor. I have a header file for each chip, so I don't know how many indices are defined. Here is what it approximately looks like:

typedef enum
    {
    POWER_LEVEL_0
    POWER_LEVEL_1,
    POWER_LEVEL_2,
    POWER_LEVEL_3,
    POWER_LEVEL_4
    } power_type;

and I need to be able to test if a received index is defined, like so:

int input;
...
if( exists_in_power_type(input) )
    //accept the value
else
    //use default value

I know the number of indices will be in the range of about 4 to 7, and that may grow if I run this project on a new processor that may have 8 or more power options. In this case I want my program to be portable and only have to define an enum of the same name in a new header for that processor.

This problem may be a little easier because the enum values just start at 0 and increment by 1. Is there a way to get the length/max value of an enum without knowing its definition? Is there a similar work around that I could use here?

Body:
There is no cross-platform way to determine the maximum legal enumerated value for a particular enum. However, you can get around this by introducing a dummy enumerated value that comes after all the others:

typedef enum
{
    POWER_LEVEL_0
    POWER_LEVEL_1,
    POWER_LEVEL_2,
    POWER_LEVEL_3,
    POWER_LEVEL_4,
    ILLEGAL_POWER_LEVEL // Not to be used directly; must be last
} power_type;

Now, you can write your helper function as follows:

bool exists_in_power_type(power_type value) {
    return 0 <= value && value < ILLEGAL_POWER_LEVEL;
}

As long as ILLEGAL_POWER_LEVEL is the last of the enumerated values, this approach will check whether you have something assigned to value that matches some enumeration.

Hope this helps!