问:
How to get string and byte to compare?
I'm new to Arduino and c++ coding, I have been working on this project all day and I'm getting nowhere. I'm trying to compare the results from the RFID reader to the results coming from the database but I keep getting an error.

I have tried many different ways of fixing this but the firebase libary doesn't  have the getbyte function.

```<code>int UID1 = 2;
int UID2 = 2;
int UID3 = 2;
int UID4 = 2;
int UID5 = 2;
int UID6 = 2;

byte nuidPICC[4];

constexpr uint8_t RST_PIN = 5; // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 4;  // Configurable, see typical pin layout above

MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
MFRC522::MIFARE_Key key;

// Init array that will store new NUID

void setup() {
  Serial.begin(115200);
  SPI.begin();     // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }
  delay(2000);
  Serial.println('\n');

  wifiConnect();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

  delay(10);
}

void loop() {

  // Look for new cards
  if (!rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if (!rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
      piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
      piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("Your tag is not of type MIFARE Classic."));
    return;
  }

  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
      rfid.uid.uidByte[1] != nuidPICC[1] ||
      rfid.uid.uidByte[2] != nuidPICC[2] ||
      rfid.uid.uidByte[3] != nuidPICC[3]) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    Serial.print(F("UID: "));
    printDec(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  } else {
    Serial.println(F("Card read previously."));
  }
  // Halt PICC
  rfid.PICC_HaltA();
  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();

  Serial.print(Firebase.getString("UID1") + "\n");
  Serial.print(Firebase.getString("UID2") + "\n");
  Serial.print(Firebase.getString("UID3") + "\n");
  Serial.print(Firebase.getString("UID4") + "\n");
  Serial.print(Firebase.getString("UID5") + "\n");
  Serial.print(Firebase.getString("UID6") + "\n");

  analogWrite(UID1, Firebase.getString("UID1").toInt());
  analogWrite(UID2, Firebase.getString("UID2").toInt());
  analogWrite(UID3, Firebase.getString("UID3").toInt());
  analogWrite(UID4, Firebase.getString("UID4").toInt());
  analogWrite(UID5, Firebase.getString("UID5").toInt());
  analogWrite(UID6, Firebase.getString("UID6").toInt());
  delay(3000);

  if (WiFi.status() != WL_CONNECTED) {
    wifiConnect();
  }
  delay(10);

  if (Firebase.getString("UID1") = rfid.uid.uidByte()) {
    Serial.print("Match")
  }
}
</code>```

Here is my error:

fireabse-alpha1:118:22: error: incompatible types in assignment of
    'String' to 'byte [10] {aka unsigned char [10]}'

if (rfid.uid.uidByte = Firebase.getString("UID1")) {

                         ^

     fireabse-alpha1:120:1: error: expected ';' before '}' token

}

      ^

答:
Serial.println('\n'); is not needed. Because the ln in the name means that it wil print a newline.

rfid.uid.uidByte is a array of 10 bytes.

Firebase.getString("UID1") returns a arduino String

You can't compare an array to a String. But you can compare the elements of a String to the elements of an array.

```<code>String handle = Firebase.getString("UID1");
uint8_t lengthToCompare = rfid.uid.size;
if(handle.length() != lengthToCompare){ // this only works if you compare the whole string
    // not equal
}

bool equal = true;
for(int i=0;i<lengthToCompare;++i) {
    equal &= handle.c_str()[i] == rfid.uid.uidByte[i]; // compare if equal and variable
                                                       // equal remains true if so
}
// equal now holds if the sequences where equal
</code>```

As said before rfid.uid.uidByte = Firebase.getString("UID1") is not a comparison but a assignment, and a bad one at that because a String is being assigned to a array of bytes. The comparison operator is ==.

Also when posting on StackOverflow (or working with your code): clang-format.exe -i <filename> is your friend. (assuming you are using windows of course, I wouldn't want to presume your OS preferences)

Title: How to get string and byte to compare?

Body:
I'm new to Arduino and c++ coding, I have been working on this project all day and I'm getting nowhere. I'm trying to compare the results from the RFID reader to the results coming from the database but I keep getting an error.

I have tried many different ways of fixing this but the firebase libary doesn't  have the getbyte function.

int UID1 = 2;
int UID2 = 2;
int UID3 = 2;
int UID4 = 2;
int UID5 = 2;
int UID6 = 2;

byte nuidPICC[4];

constexpr uint8_t RST_PIN = 5; // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 4;  // Configurable, see typical pin layout above

MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
MFRC522::MIFARE_Key key;

// Init array that will store new NUID

void setup() {
  Serial.begin(115200);
  SPI.begin();     // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }
  delay(2000);
  Serial.println('\n');

  wifiConnect();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

  delay(10);
}

void loop() {

  // Look for new cards
  if (!rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if (!rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
      piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
      piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("Your tag is not of type MIFARE Classic."));
    return;
  }

  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
      rfid.uid.uidByte[1] != nuidPICC[1] ||
      rfid.uid.uidByte[2] != nuidPICC[2] ||
      rfid.uid.uidByte[3] != nuidPICC[3]) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    Serial.print(F("UID: "));
    printDec(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  } else {
    Serial.println(F("Card read previously."));
  }
  // Halt PICC
  rfid.PICC_HaltA();
  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();

  Serial.print(Firebase.getString("UID1") + "\n");
  Serial.print(Firebase.getString("UID2") + "\n");
  Serial.print(Firebase.getString("UID3") + "\n");
  Serial.print(Firebase.getString("UID4") + "\n");
  Serial.print(Firebase.getString("UID5") + "\n");
  Serial.print(Firebase.getString("UID6") + "\n");

  analogWrite(UID1, Firebase.getString("UID1").toInt());
  analogWrite(UID2, Firebase.getString("UID2").toInt());
  analogWrite(UID3, Firebase.getString("UID3").toInt());
  analogWrite(UID4, Firebase.getString("UID4").toInt());
  analogWrite(UID5, Firebase.getString("UID5").toInt());
  analogWrite(UID6, Firebase.getString("UID6").toInt());
  delay(3000);

  if (WiFi.status() != WL_CONNECTED) {
    wifiConnect();
  }
  delay(10);

  if (Firebase.getString("UID1") = rfid.uid.uidByte()) {
    Serial.print("Match")
  }
}

Here is my error:

fireabse-alpha1:118:22: error: incompatible types in assignment of
    'String' to 'byte [10] {aka unsigned char [10]}'

if (rfid.uid.uidByte = Firebase.getString("UID1")) {

                         ^

     fireabse-alpha1:120:1: error: expected ';' before '}' token

}

      ^

Body:
Serial.println('\n'); is not needed. Because the ln in the name means that it wil print a newline.

rfid.uid.uidByte is a array of 10 bytes.

Firebase.getString("UID1") returns a arduino String

You can't compare an array to a String. But you can compare the elements of a String to the elements of an array.

String handle = Firebase.getString("UID1");
uint8_t lengthToCompare = rfid.uid.size;
if(handle.length() != lengthToCompare){ // this only works if you compare the whole string
    // not equal
}

bool equal = true;
for(int i=0;i<lengthToCompare;++i) {
    equal &= handle.c_str()[i] == rfid.uid.uidByte[i]; // compare if equal and variable
                                                       // equal remains true if so
}
// equal now holds if the sequences where equal

As said before rfid.uid.uidByte = Firebase.getString("UID1") is not a comparison but a assignment, and a bad one at that because a String is being assigned to a array of bytes. The comparison operator is ==.

Also when posting on StackOverflow (or working with your code): clang-format.exe -i <filename> is your friend. (assuming you are using windows of course, I wouldn't want to presume your OS preferences)


来源: stackexchange

问:
Is there any way i can achieve this step bar?
I am trying to make this type of step bar as in the picture but i am unable to do it.Please Suggest some way to achieve it.

I have tried various libraries like https://github.com/shuhart/StepView but i cannot get the desired results.

答:
Use something like StateProgressBar it is an Android library to realize the various states and transitions in a ProgressBar as per your requirement

https://github.com/kofigyan/StateProgressBar

Add Dependancy

dependencies {
     implementation 'com.kofigyan.stateprogressbar:stateprogressbar:1.0.0'
}```
</div>
</div>
</p>

<p>Add XML</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><com.kofigyan.stateprogressbar.StateProgressBar
    android:id="@+id/your_state_progress_bar_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:spb_currentStateNumber="three"
    app:spb_maxStateNumber="four"
    app:spb_stateBackgroundColor="#BDBDBD"
    app:spb_stateForegroundColor="#009688"
    app:spb_stateNumberBackgroundColor="#808080"
    app:spb_stateNumberForegroundColor="#eeeeee"
    app:spb_currentStateDescriptionColor="#009688"
    app:spb_stateDescriptionColor="#808080"
    app:spb_animateToCurrentProgressState="true"
    app:spb_checkStateCompleted="true"/></code>```

Add in your Activity

String[] descriptionData = {"Details", "Status", "Photo", "Confirm"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

    StateProgressBar stateProgressBar = (StateProgressBar) findViewById(R.id.your_state_progress_bar_id);
    stateProgressBar.setStateDescriptionData(descriptionData);

}```

Attribute code referred to from https://github.com/kofigyan/StateProgressBar

ContentLicense: CC BY-SA 4.0

Body:
Use something like StateProgressBar it is an Android library to realize the various states and transitions in a ProgressBar as per your requirement

https://github.com/kofigyan/StateProgressBar

Add Dependancy

dependencies {
     implementation 'com.kofigyan.stateprogressbar:stateprogressbar:1.0.0'
}

Add XML

<com.kofigyan.stateprogressbar.StateProgressBar
    android:id="@+id/your_state_progress_bar_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:spb_currentStateNumber="three"
    app:spb_maxStateNumber="four"
    app:spb_stateBackgroundColor="#BDBDBD"
    app:spb_stateForegroundColor="#009688"
    app:spb_stateNumberBackgroundColor="#808080"
    app:spb_stateNumberForegroundColor="#eeeeee"
    app:spb_currentStateDescriptionColor="#009688"
    app:spb_stateDescriptionColor="#808080"
    app:spb_animateToCurrentProgressState="true"
    app:spb_checkStateCompleted="true"/>

Add in your Activity

String[] descriptionData = {"Details", "Status", "Photo", "Confirm"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

    StateProgressBar stateProgressBar = (StateProgressBar) findViewById(R.id.your_state_progress_bar_id);
    stateProgressBar.setStateDescriptionData(descriptionData);

}

Attribute code referred to from https://github.com/kofigyan/StateProgressBar


问:
Are there any alternatives to recaptcha.net, for stopping spam?
A member of my company in greater ranking than myself refuses to use recaptcha.net on his website to thwart spam off of a public form.  He thinks it would be difficult for anyone coming to our site to enter their information since the Turing Tests are "so darn hard to read".

Is there an alternative to using this method?  That doesn't contain these sorts of difficult to read images?

(Okay stupid question...if it were up to me we'd use recaptcha because everyone else on earth does...but I just figured I'd check anyway.)

Also, is using a hidden field that is set by Javascript and later checked on the server really a good way to thawart spam?

I myself don't really buy that it is...since there are all sorts of Javascript engines that don't run in a browser yet can run Javascript (Rhino etc...), that could easily be used to thawart a JS/Serverside anti-spam method.

答:
I used to think CAPTCHAs were good and used reCAPTCHA on public forms.  I noticed that spam submissions were gone but I also noticed that real submissions were cut drastically as well.

Now I don't believe in CAPTCHAs.  They work but I feel they can do more harm than good.  After having to enter in hard to read CAPTCHAs on other sites I understand why I don't get as many real submissions.  Any input that a user must act on that is not related to their main goal is a deterrent.

I usually use several methods to prevent spam and it depends on what type of content I'm expecting in forms.  I created server methods that scan comments and mark them as spam based on content.  It works ok, but I'm no spam expert so it doesn't work great.  I wish someone would make a web service that did this.

I think the links from Evan are pretty interesting!

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: cletus

OwnerDisplayName: webdtc


问:
 is not showing icon properly
import '../node_modules/font-awesome/css/font-awesome.min.css';
above the module imported in both index.js and in my component file. How to display icons properly?

答:
your file is a css file not a js one so you'll need to import it with the following line

```<code><link href="../node_modules/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
</code>```

in the  of your html (not sure about react but AFAIK you have a index.html)

if this doesn't work looking at Linking to css files from react index may help you

Title: <i className='fab fa-instagram'></i> is not showing icon properly

Body:
your file is a css file not a js one so you'll need to import it with the following line

<link href="../node_modules/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

in the <head> of your html (not sure about react but AFAIK you have a index.html)

if this doesn't work looking at Linking to css files from react index may help you


问:
lcov code coverage --remove command with input variable does not work

Problem Description

I am trying to filter directories that we don't want to ignore for the test coverage. For this purpose we are using Lcov.

When I try to put the directories that are to be ignore in a variable __ignoreinput the command #${__lcov} ${__gcovopts} --remove MYCODE.info "${__ignoreinput}" -o MYCODE_filtered.info > /dev/null 2> /dev/null doesn't work, it doesn't filter anything. Whereas when I use the command without the __ignoreinput as in

```<code> ${__lcov} ${__gcovopts} --remove MYCODE.info '/opt/*' '/usr/include/*' '*3rdParty/*' '*Input_API/*' '*Grammars/*' -o MYCODE_filtered.info > /dev/null 2> /dev/null
if [[ ${?} -ne 0 ]] ;then echo "Error *** lcov filtrering failed" && exit 1 ;fi
</code>```

The filter works ok. What am I doing wrong. I don't understand.

Script

```<code>#!/bin/bash
__orc=/home/anybody/workspace/project
__buildtype="local"
__output=/home/anybody/workspace/lcov

#doe not work
#__ignoreinput="'/opt/*' '/usr/include/*' '*3rdParty/*' '*Input_API/*' '*Grammars/*'"
#__ignoreinput="/opt/* /usr/include/* *3rdParty/* *Input_API/* *Grammars/* "
#__ignoreinput="\"/opt/*\" \"/usr/include/*\" \"*3rdParty/*\" \"*Input_API/*\" \"*Grammars/*\""

__gcovopts=--gcov-tool=/opt/1A/x86_64-2.6.32-v2/bin/gcov
__lcov=lcov
if [[ "${__buildtype}" == "docker" ]] ;then
  __build=MYCODE/build_x86_64-2.6.32-v2_Gcov
else
  __build=MYCODE/cmake-build-coverage
fi

echo "Filter lcov tracefile"
cd ${__orc}/${__build}
#does not work
#${__lcov} ${__gcovopts} --remove MYCODE.info "${__ignoreinput}" -o MYCODE_filtered.info > /dev/null 2> /dev/null

#works
${__lcov} ${__gcovopts} --remove MYCODE.info '/opt/*' '/usr/include/*' '*3rdParty/*' '*Input_API/*' '*Grammars/*' -o MYCODE_filtered.info > /dev/null 2> /dev/null
if [[ ${?} -ne 0 ]] ;then echo "Error *** lcov filtrering failed" && exit 1 ;fi

echo "Generate HTML reports"
cd ${__orc}/${__build}
genhtml --ignore-errors source -o ${__output}/lcov_"$(git rev-list HEAD -n 1)" MYCODE_filtered.info > /dev/null 2> /dev/null
if [[ ${?} -ne 0 ]] ;then echo "Error *** lcov reports failed" && exit 1 ;fi
</code>```

答:
One simple way to pass the __ignoreinput would be to store the glob expressions in the array under single quote expand them while passing to the lcov command. Write your ignore input as

```<code>__ignoreinput=( '/opt/*' '/usr/include/*' '*3rdParty/*' '*Input_API/*' '*Grammars/*' )
</code>```

and doing below should work as expected.

```<code>"${__lcov}" "${__gcovopts}" --remove MYCODE.info "${__ignoreinput[@]}" -o MYCODE_filtered.info 2>&1 > /dev/null
</code>```

For all the failure cases in your description __ignoreinput is set as one whole-string under ".." but the command expects words split up one expression for each. The array expansion "${__ignoreinput[@]}" though puts each word defined in the array as a separate word as expected by the command.

Also carefully single/double quote the words in the array during the definition, because with lack of quotes * could undergo path-name expansion and could expand to the list of filenames under each of those paths.

Also see how > /dev/null 2> /dev/null could be minimized to > /dev/null 2> /dev/null or simply &> /dev/null in bash.

 Also naming variable names prefixed with __ is a bad practice. Like most of the languages out there, the character can itself could be a valid variable identifier. As shown above enclosing the variable name completely around {..} is the recommended way.

Body:
Problem Description

I am trying to filter directories that we don't want to ignore for the test coverage. For this purpose we are using Lcov.

When I try to put the directories that are to be ignore in a variable __ignoreinput the command #${__lcov} ${__gcovopts} --remove MYCODE.info "${__ignoreinput}" -o MYCODE_filtered.info > /dev/null 2> /dev/null doesn't work, it doesn't filter anything. Whereas when I use the command without the __ignoreinput as in

 ${__lcov} ${__gcovopts} --remove MYCODE.info '/opt/*' '/usr/include/*' '*3rdParty/*' '*Input_API/*' '*Grammars/*' -o MYCODE_filtered.info > /dev/null 2> /dev/null
if [[ ${?} -ne 0 ]] ;then echo "Error *** lcov filtrering failed" && exit 1 ;fi

The filter works ok. What am I doing wrong. I don't understand.

Script

#!/bin/bash
__orc=/home/anybody/workspace/project
__buildtype="local"
__output=/home/anybody/workspace/lcov

#doe not work
#__ignoreinput="'/opt/*' '/usr/include/*' '*3rdParty/*' '*Input_API/*' '*Grammars/*'"
#__ignoreinput="/opt/* /usr/include/* *3rdParty/* *Input_API/* *Grammars/* "
#__ignoreinput="\"/opt/*\" \"/usr/include/*\" \"*3rdParty/*\" \"*Input_API/*\" \"*Grammars/*\""

__gcovopts=--gcov-tool=/opt/1A/x86_64-2.6.32-v2/bin/gcov
__lcov=lcov
if [[ "${__buildtype}" == "docker" ]] ;then
  __build=MYCODE/build_x86_64-2.6.32-v2_Gcov
else
  __build=MYCODE/cmake-build-coverage
fi

echo "Filter lcov tracefile"
cd ${__orc}/${__build}
#does not work
#${__lcov} ${__gcovopts} --remove MYCODE.info "${__ignoreinput}" -o MYCODE_filtered.info > /dev/null 2> /dev/null

#works
${__lcov} ${__gcovopts} --remove MYCODE.info '/opt/*' '/usr/include/*' '*3rdParty/*' '*Input_API/*' '*Grammars/*' -o MYCODE_filtered.info > /dev/null 2> /dev/null
if [[ ${?} -ne 0 ]] ;then echo "Error *** lcov filtrering failed" && exit 1 ;fi

echo "Generate HTML reports"
cd ${__orc}/${__build}
genhtml --ignore-errors source -o ${__output}/lcov_"$(git rev-list HEAD -n 1)" MYCODE_filtered.info > /dev/null 2> /dev/null
if [[ ${?} -ne 0 ]] ;then echo "Error *** lcov reports failed" && exit 1 ;fi

Body:
One simple way to pass the __ignoreinput would be to store the glob expressions in the array under single quote expand them while passing to the lcov command. Write your ignore input as

__ignoreinput=( '/opt/*' '/usr/include/*' '*3rdParty/*' '*Input_API/*' '*Grammars/*' )

and doing below should work as expected.

"${__lcov}" "${__gcovopts}" --remove MYCODE.info "${__ignoreinput[@]}" -o MYCODE_filtered.info 2>&1 > /dev/null

For all the failure cases in your description __ignoreinput is set as one whole-string under ".." but the command expects words split up one expression for each. The array expansion "${__ignoreinput[@]}" though puts each word defined in the array as a separate word as expected by the command.

Also carefully single/double quote the words in the array during the definition, because with lack of quotes * could undergo path-name expansion and could expand to the list of filenames under each of those paths.

Also see how > /dev/null 2> /dev/null could be minimized to > /dev/null 2> /dev/null or simply &> /dev/null in bash.

 Also naming variable names prefixed with __ is a bad practice. Like most of the languages out there, the character can itself could be a valid variable identifier. As shown above enclosing the variable name completely around {..} is the recommended way.


问:
How can I create and alter a new string[][] without altering the original?
I know this is an issue being caused by passing by reference rather than value, but I'm not sure what I need to do to fix it.

I have a field variable string[][] _cubeState which represents the state of a 2x2 Rubiks cube. This jagged array represents the state of the cube before any rotations take place and should be updated after every rotation, but only after my rotate method has returned and overwritten it.

What is actually happening is that when I get to the newCube[0][index] = _cubeState[0][index + 10]; line, this line updates both my newCube array and my original _cubeState array. Since the newCube is referencing cubeState it's also updating the original. How do I fix this so that the cubeState will only update after the method has returned?

```<code>private string[][] _cubeState;

public Rubiks () {
    _cubeState = new string[][] {
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
    };

    _cubeState = RotateAcw (0);
}

public string[][] RotateAcw (int index) {
    string[][] newCube = { _cubeState[0], _cubeState[1] };

    newCube[0][index] = _cubeState[0][index + 10];
    newCube[1][index] = _cubeState[1][index + 10];

    return newCube;
}
</code>```

答:
This is how to copy the jagged array:</p>

```<code>string[][] cubeState = new string[][] {
    new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
    new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
};

string[][] newCube = cubeState.Select(x => x.ToArray()).ToArray();
</code>```

Body:
I know this is an issue being caused by passing by reference rather than value, but I'm not sure what I need to do to fix it.

I have a field variable string[][] _cubeState which represents the state of a 2x2 Rubiks cube. This jagged array represents the state of the cube before any rotations take place and should be updated after every rotation, but only after my rotate method has returned and overwritten it.

What is actually happening is that when I get to the newCube[0][index] = _cubeState[0][index + 10]; line, this line updates both my newCube array and my original _cubeState array. Since the newCube is referencing cubeState it's also updating the original. How do I fix this so that the cubeState will only update after the method has returned?

private string[][] _cubeState;

public Rubiks () {
    _cubeState = new string[][] {
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
    };

    _cubeState = RotateAcw (0);
}

public string[][] RotateAcw (int index) {
    string[][] newCube = { _cubeState[0], _cubeState[1] };

    newCube[0][index] = _cubeState[0][index + 10];
    newCube[1][index] = _cubeState[1][index + 10];

    return newCube;
}

Body:
This is how to copy the jagged array:

string[][] cubeState = new string[][] {
    new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
    new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
};

string[][] newCube = cubeState.Select(x => x.ToArray()).ToArray();


问:
Bi-direction port connection with signal in SystemC
In module hierarchy, on connecting inout port with sc_signal it shows error, So is there any other type of signal I  need to connect with inout (bidirectional port) ?

Error: (E115) sc_signal cannot have more than one driver:
 signal Dha.signal_0' (sc_signal)
 first driverDha.Memory.port_4'  (sc_inout)
 second driver `Dha.Alloc.port_3' (sc_inout)

答:
You need to instantiate the sc_signal with a writer policy of SC_MANY_WRITERS to drive a signal from multiple ports/processes.

#include <systemc.h>
SC_MODULE(Foo) {
  sc_inout<bool> port;
  SC_CTOR(Foo)
    : port("port")
  {}
  // ...
};
SC_MODULE(Bar) {
  sc_inout<bool> port;
  SC_CTOR(Bar)
    : port("port")
  {}
  // ...
};
int sc_main(int, char*[])
{
  sc_signal<bool, SC_MANY_WRITERS> signal; // <-- policy here
  Foo foo("foo");
  Bar bar("bar");
  foo.port(signal);
  bar.port(signal);
  sc_start();
  return 0;
}
```


问:
Finding whether a date falls within the date range using XSLT
I have the following xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<divisions>
   <userProvidedEffDate>12/31/2002</userProvidedEffDate>
   <division>
      <GroupNumber>001</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/9999</GroupExpDt>
   </division>
   <division>
      <GroupNumber>002</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/2001</GroupExpDt>
   </division>
</divisions>
</code>```

Now I want to tranasform the above xml using XSLT 1.0 based on the value of <userProvidedEffDate>. If the <userProvidedEffDate> is in between the date range of the <division>'s <GroupEffDt> and <GroupExpDt>(inclusive), then we display that division. For example the above input xml should be transformed as below based on the <userProvidedEffDate> value 12/31/2002.

```<code><?xml version="1.0" encoding="UTF-8"?>
<divisions>
   <userProvidedEffDate>12/31/2002</userProvidedEffDate>
   <division>
      <GroupNumber>001</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/9999</GroupExpDt>
   </division>
</divisions>
</code>```

Any help is appreciated.

答:
As an example of why you switch to Saxon 9, if you had to do this in XSLT 1.0 (without any extension functions) you would have to convert the dates into a number of the form YYYYMMDD.

For example

```<code><xsl:variable name="userProvidedEffDate" select="number(concat(substring(userProvidedEffDate, 7, 4), substring(userProvidedEffDate, 1, 2), substring(userProvidedEffDate, 4, 2)))" />
</code>```

Try this XSLT

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes" />

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="divisions">
    <xsl:variable name="userProvidedEffDate" select="number(concat(substring(userProvidedEffDate, 7, 4), substring(userProvidedEffDate, 1, 2), substring(userProvidedEffDate, 4, 2)))" />
    <xsl:copy>
      <xsl:apply-templates select="@*|userProvidedEffDate" />
      <xsl:apply-templates select="division
                                     [number(concat(substring(GroupEffDt, 7, 4), substring(GroupEffDt, 1, 2), substring(GroupEffDt, 4, 2))) <= $userProvidedEffDate
                                      and number(concat(substring(GroupExpDt, 7, 4), substring(GroupExpDt, 1, 2), substring(GroupExpDt, 4, 2))) >= $userProvidedEffDate]" />
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

Of course, if you had control over the XML, an easy solution would be to have the dates in YYYYMMDD format in the XML in the first place

Body:
I have the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<divisions>
   <userProvidedEffDate>12/31/2002</userProvidedEffDate>
   <division>
      <GroupNumber>001</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/9999</GroupExpDt>
   </division>
   <division>
      <GroupNumber>002</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/2001</GroupExpDt>
   </division>
</divisions>

Now I want to tranasform the above xml using XSLT 1.0 based on the value of <userProvidedEffDate>. If the <userProvidedEffDate> is in between the date range of the <division>'s <GroupEffDt> and <GroupExpDt>(inclusive), then we display that division. For example the above input xml should be transformed as below based on the <userProvidedEffDate> value 12/31/2002.

<?xml version="1.0" encoding="UTF-8"?>
<divisions>
   <userProvidedEffDate>12/31/2002</userProvidedEffDate>
   <division>
      <GroupNumber>001</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/9999</GroupExpDt>
   </division>
</divisions>

Any help is appreciated.

Body:
As an example of why you switch to Saxon 9, if you had to do this in XSLT 1.0 (without any extension functions) you would have to convert the dates into a number of the form YYYYMMDD.

For example

<xsl:variable name="userProvidedEffDate" select="number(concat(substring(userProvidedEffDate, 7, 4), substring(userProvidedEffDate, 1, 2), substring(userProvidedEffDate, 4, 2)))" />

Try this XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes" />

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="divisions">
    <xsl:variable name="userProvidedEffDate" select="number(concat(substring(userProvidedEffDate, 7, 4), substring(userProvidedEffDate, 1, 2), substring(userProvidedEffDate, 4, 2)))" />
    <xsl:copy>
      <xsl:apply-templates select="@*|userProvidedEffDate" />
      <xsl:apply-templates select="division
                                     [number(concat(substring(GroupEffDt, 7, 4), substring(GroupEffDt, 1, 2), substring(GroupEffDt, 4, 2))) &lt;= $userProvidedEffDate
                                      and number(concat(substring(GroupExpDt, 7, 4), substring(GroupExpDt, 1, 2), substring(GroupExpDt, 4, 2))) &gt;= $userProvidedEffDate]" />
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Of course, if you had control over the XML, an easy solution would be to have the dates in YYYYMMDD format in the XML in the first place


问:
Javascript AJAX responseText problem in IE
I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:

(AJAX)

```<code>function getMessages(messengerid, repeat)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("messages").innerHTML=xmlhttp.responseText;
    document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
    }
  }
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
    setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}
</code>```

(PHP/MySql)

```<code><?php
$key = "abcIUETH85i236t246jerst3487Jh";

if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {

    include_once("../config.php");
    include_once("../class/system.class.php");

    $sys = new system($template_name);

    if(!$sys->connect($db)) {
        exit();
    }

    $messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
    $messenger    = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");

    $user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
    $user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");

    $displaynames[$user1[0]['id']] = $user1[0]['displayname'];
    $displaynames[$user2[0]['id']] = $user2[0]['displayname'];

    foreach($messages AS $key => $message) {

    if(is_numeric($key)) {
    ?>
    <div class="message">
        <b><?=$displaynames[$message['account_id']];?>  (<?=date("h:m:s", $message['timestamp']);?>) says:</b> <br />
        <?=nl2br($message['message_content']);?>
    </div>
    <?php
    }
    }

}

?>
</code>```

Any help would be much appreciated!
Thanks in advance.

Best Regards,
Skyfe.

答: Its a common problem with IE it caches the result.Add some dummy random parameter to your ajax call e.g current timestamp</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:

(AJAX)

function getMessages(messengerid, repeat)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("messages").innerHTML=xmlhttp.responseText;
    document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
    }
  }
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
    setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}

(PHP/MySql)

<?php
$key = "abcIUETH85i236t246jerst3487Jh";

if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {

    include_once("../config.php");
    include_once("../class/system.class.php");

    $sys = new system($template_name);

    if(!$sys->connect($db)) {
        exit();
    }

    $messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
    $messenger    = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");

    $user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
    $user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");

    $displaynames[$user1[0]['id']] = $user1[0]['displayname'];
    $displaynames[$user2[0]['id']] = $user2[0]['displayname'];

    foreach($messages AS $key => $message) {

    if(is_numeric($key)) {
    ?>

        <?=$displaynames[$message['account_id']];?>  (<?=date("h:m:s", $message['timestamp']);?>) says:

        <?=nl2br($message['message_content']);?>

    <?php
    }
    }

}

?>

Any help would be much appreciated!
Thanks in advance.

Best Regards,
Skyfe.


问:
Comparing nested list of list with a list
I am trying out to compare list of list values with another list and return if matched.I am looking it in scala however i am new into scala and it difficult to do if any suggestions please pass on

```<code>val l1 = List(List(1,12.34,76.456,12,List(1,2,3)),List(2,12.43,76.256,12,List(11,12,13)))

val l2 = List(1,2,3,12)
</code>```

so here trying to compare l1([1,2,3]) with l2 [1,2,3,12] and l1 [11,12,13] with l2 [1,2,3,12] and return if not matched any elements from l1 to l2.

here we are looking for of l1 any value matched with l2 then 0 else 1

Tricky but is it doable in scala?Any suggestions

答:
You need to flatten l1. to make it generic (because as I understand, l1 can be list of list of list..) you can create a generic method which flatten it:

```<code>def flatten[T](l: List[T]): List[T] = l match {
  case Nil => Nil
  case (x: List[T]) :: tail => flatten(x) ::: flatten(tail)
  case x :: tail => x :: flatten(tail)
}
</code>```

Then, you can get the result it by:

```<code>(l2.map(flatten(l1).contains)).map(_.compare(false)) // List(1,1,1,1)
</code>```

Here is the code to run and debug - https://scalafiddle.io/sf/3SStZZX/1

Body:
I am trying out to compare list of list values with another list and return if matched.I am looking it in scala however i am new into scala and it difficult to do if any suggestions please pass on

val l1 = List(List(1,12.34,76.456,12,List(1,2,3)),List(2,12.43,76.256,12,List(11,12,13)))

val l2 = List(1,2,3,12)

so here trying to compare l1([1,2,3]) with l2 [1,2,3,12] and l1 [11,12,13] with l2 [1,2,3,12] and return if not matched any elements from l1 to l2.

here we are looking for of l1 any value matched with l2 then 0 else 1

Tricky but is it doable in scala?Any suggestions

Body:
You need to flatten l1. to make it generic (because as I understand, l1 can be list of list of list..) you can create a generic method which flatten it:

def flatten[T](l: List[T]): List[T] = l match {
  case Nil => Nil
  case (x: List[T]) :: tail => flatten(x) ::: flatten(tail)
  case x :: tail => x :: flatten(tail)
}

Then, you can get the result it by:

(l2.map(flatten(l1).contains)).map(_.compare(false)) // List(1,1,1,1)

Here is the code to run and debug - https://scalafiddle.io/sf/3SStZZX/1


问:
How to combine two python files using third python file which can also add some code to the same file?
I have two python files I want to make a program that can merge those files and show me the new file.

File 1

def functiona(a):
    print("hi")
```

<p>File 2</p>

<pre class="lang-py prettyprint-override"><code>def functionb(a):
    print("hi")
</code>```

Combined file

def function(a):
    print("hi")

def functionb(a):
    print("hi")

if __name__ = "__main__":
    functiona(4)
    functionb(5)
```

答:
Updated:
Put this in a file and use it from the console to combine the functions and output them in one file.

```<code># arg 0: The path where the combined file will be created.
# args 1..inf: Paths to the files where your functions found.

import sys

with open(sys.argv[1], "w") as out_file:
    for i in range(2, len(sys.argv)):
        with open(sys.argv[i]) as in_file:
            for l in in_file.readlines():
                out_file.writelines(l)
            out_file.writelines("\n\n")

    # What ever you need to add at the end"
    additional_text = 'if __name__ = "__main__":\n\tfunctiona(4)\n\tfunctionb(5)'
    out_file.writelines(additional_text)
</code>```

Body:
I have two python files I want to make a program that can merge those files and show me the new file.

File 1

def functiona(a):
    print("hi")

File 2

def functionb(a):
    print("hi")

Combined file

def function(a):
    print("hi")

def functionb(a):
    print("hi")

if __name__ = "__main__":
    functiona(4)
    functionb(5)

Body:
Updated:
Put this in a file and use it from the console to combine the functions and output them in one file.

# arg 0: The path where the combined file will be created.
# args 1..inf: Paths to the files where your functions found.

import sys

with open(sys.argv[1], "w") as out_file:
    for i in range(2, len(sys.argv)):
        with open(sys.argv[i]) as in_file:
            for l in in_file.readlines():
                out_file.writelines(l)
            out_file.writelines("\n\n")

    # What ever you need to add at the end"
    additional_text = 'if __name__ = "__main__":\n\tfunctiona(4)\n\tfunctionb(5)'
    out_file.writelines(additional_text)


问:
pfuser with pointer not getting data back
I have subclassed PFuser and registered it. it works great.

In my database in the User table i made a pointer to another table that has some more information.

the app keeps crashing with this error:

```<code>2014-06-08 15:14:59.550 App[2333:60b] *** Terminating app due to uncaught exception
'NSInternalInconsistencyException',
reason: 'Key "place" has no data.  Call fetchIfNeeded
before getting its value.'
</code>```

While checking the debugger i can see it made the connection to another table but all fields are empty.

I think i need to put something like this: [query includeKey:@"company"];

for the pointer but I don't do a query for the User class...

do I need to override it somewhere ?

this is my custom user class:

-h file

```<code>#import "Company.h"

@interface PFCustomUser : PFUser<PFSubclassing>

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) UIImage *userPhoto;
@property (nonatomic, retain) Company *company;

+ (PFCustomUser *)currentUser;
</code>```

-m file

```<code>#import "PFCustomUser.h"

@implementation PFCustomUser

@dynamic name,userPhoto,company;

+ (PFCustomUser *)currentUser {
return (PFCustomUser *)[PFUser currentUser];
}
</code>```

In the appdelegate i do this

```<code>  [PFCustomUser registerSubclass];
</code>```

So technacly i would do this in a controller

```<code>PFCustomUser *currentUser = [PFCustomUser currentUser];
NSLog(@"%@",currentUser.company.place);
</code>```

company is nill so place is nill. hence the error..
In the debugger you can see it sees the objectId of company and the classname but the rest is nill

答:
The problem in your code is that you are not fetching the "Company" object when you are using it in currentUser.company.place

When u fetched currentUser, it only fetches the basic info like objectId,etc about its properties of Parse class Type ('Company' class in this case). That is why u are getting the objetId of company in debugger whereas currentUser.company.place is nil(because the actual object isn't fetched yet).

To solve this :

You have to fetch each property of Parse class type individually (however and wherever you want to implement it->ur choice) using 'fetchIfNeeded' method.

So ur code could look something like this :

```<code>PFCustomUser *currentUser = [PFCustomUser currentUser];
Company *company = currentUser.company;

[company fetchIfNeededInBackgroundWithBlock:^(PFObject * _Nullable object, NSError * _Nullable error) {
   //Handle error here
}

else
{
   //company.place can be fetched here
    NSLog(@"%@",company.place);
}

}];
</code>```

Hope this works. And hope it helps!

Body:
I have subclassed PFuser and registered it. it works great.

In my database in the User table i made a pointer to another table that has some more information.

the app keeps crashing with this error:

2014-06-08 15:14:59.550 App[2333:60b] *** Terminating app due to uncaught exception
'NSInternalInconsistencyException',
reason: 'Key "place" has no data.  Call fetchIfNeeded
before getting its value.'

While checking the debugger i can see it made the connection to another table but all fields are empty.

I think i need to put something like this: [query includeKey:@"company"];

for the pointer but I don't do a query for the User class...

do I need to override it somewhere ?

this is my custom user class:

-h file

#import "Company.h"

@interface PFCustomUser : PFUser<PFSubclassing>

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) UIImage *userPhoto;
@property (nonatomic, retain) Company *company;

+ (PFCustomUser *)currentUser;

-m file

#import "PFCustomUser.h"

@implementation PFCustomUser

@dynamic name,userPhoto,company;

+ (PFCustomUser *)currentUser {
return (PFCustomUser *)[PFUser currentUser];
}

In the appdelegate i do this

  [PFCustomUser registerSubclass];

So technacly i would do this in a controller

PFCustomUser *currentUser = [PFCustomUser currentUser];
NSLog(@"%@",currentUser.company.place);

company is nill so place is nill. hence the error..
In the debugger you can see it sees the objectId of company and the classname but the rest is nill

Body:
The problem in your code is that you are not fetching the "Company" object when you are using it in currentUser.company.place

When u fetched currentUser, it only fetches the basic info like objectId,etc about its properties of Parse class Type ('Company' class in this case). That is why u are getting the objetId of company in debugger whereas currentUser.company.place is nil(because the actual object isn't fetched yet).

To solve this :

You have to fetch each property of Parse class type individually (however and wherever you want to implement it->ur choice) using 'fetchIfNeeded' method.

So ur code could look something like this :

PFCustomUser *currentUser = [PFCustomUser currentUser];
Company *company = currentUser.company;

[company fetchIfNeededInBackgroundWithBlock:^(PFObject * _Nullable object, NSError * _Nullable error) {
   //Handle error here
}

else
{
   //company.place can be fetched here
    NSLog(@"%@",company.place);
}

}];

Hope this works. And hope it helps!


问:
alert box in asp.net web application
how can i use an alert box in asp.net web application without using javascript with Yes/NO option, much like messagebox in desktop (windows) application.

Thanks

答:
Write an ActiveX control?

(Please don't do that.)

Title: alert box in asp.net web application


问:
return insert id on none laravel db set up
I have a database that was not designed for Laravel. I am building a small api using Laravel. Thus I can not useLlaravel structured queries. The query is working but need to be able to retrieve the id number of an insert.

This is the insert I am using.

```<code>$results = DB::insert("
            SELECT * FROM insrdata.add_user(
                :assocID,
                :accountID,
                :firstName,
                :middleName,
                :lastName,
                :address1,
                :address2,
                :city,
                :state,
                :zipCode,
                :phone,
                :email,
                :birthDateMMDDYYYY,
                :gradeLevelID,
                :commentText
            )
        ",
        [
            'assocID' => $request->input('assocID'),
            'accountID' => $request->input('accountID'),
            'firstName' => $request->input('firstName'),
            'middleName' => $request->input('middleName'),
            'lastName' => $request->input('lastName'),
            'address1' => $request->input('address1'),
            'address2' => $request->input('address2'),
            'city' => $request->input('city'),
            'state' => $request->input('state'),
            'zipCode' => $request->input(''),
            'phone' => $request->input(''),
            'email' => $request->input('email'),
            'birthDateMMDDYYYY' => $request->input('birthDateMMDDYYYY'),
            'gradeLevelID' => $request->input('gradeLevelID'),
            'commentText' => $request->input('commentText')
        ]
    );

if($results) {
    $return_array = array(
        'p_contact_id' => "",
        'p_result' => "O.K."
    );
}
</code>```

I need to get the id of the insert.

答:
This is called "getting last inserted id". Here documentation in Laravel about it.

https://laravelcode.com/post/laravel-55-get-last-inserted-id-with-example

Body:
I have a database that was not designed for Laravel. I am building a small api using Laravel. Thus I can not useLlaravel structured queries. The query is working but need to be able to retrieve the id number of an insert.

This is the insert I am using.

$results = DB::insert("
            SELECT * FROM insrdata.add_user(
                :assocID,
                :accountID,
                :firstName,
                :middleName,
                :lastName,
                :address1,
                :address2,
                :city,
                :state,
                :zipCode,
                :phone,
                :email,
                :birthDateMMDDYYYY,
                :gradeLevelID,
                :commentText
            )
        ",
        [
            'assocID' => $request->input('assocID'),
            'accountID' => $request->input('accountID'),
            'firstName' => $request->input('firstName'),
            'middleName' => $request->input('middleName'),
            'lastName' => $request->input('lastName'),
            'address1' => $request->input('address1'),
            'address2' => $request->input('address2'),
            'city' => $request->input('city'),
            'state' => $request->input('state'),
            'zipCode' => $request->input(''),
            'phone' => $request->input(''),
            'email' => $request->input('email'),
            'birthDateMMDDYYYY' => $request->input('birthDateMMDDYYYY'),
            'gradeLevelID' => $request->input('gradeLevelID'),
            'commentText' => $request->input('commentText')
        ]
    );

if($results) {
    $return_array = array(
        'p_contact_id' => "",
        'p_result' => "O.K."
    );
}

I need to get the id of the insert.


问:
Working with ajax to change some items in mongoDB without refreshing the site
I have 'orders page' where orders should appear and could be changed with ajax without reloading the page. How do i make it to change specific boolean in mongoDB on a button click? Also i need to refresh page every time a new order comes up without reloading the page.

It works great with reloading the page with routing, but i need AJAX.

Script.js

```<code>  $('.confirm').click(function(){
    event.preventDefault();
    event.stopPropagation();
    $.ajax({
      url: 'order/' + $(this).attr('data-id') + '/confirm',
      type: 'POST',
      contentType: 'application/json',
      success: function(){
      }
  });
});
</code>```

index.ejs

```<code><form class="confirm" data-id="<%= order.id %>" method="POST">
  <button class="btn btn-success btn-lg" type="submit"><i class="fas fa-check"></i> Priimti</button>
</form>
</code>```

orders.js

```<code>router.post('/order/:id/confirm', isLoggedIn, function(req, res){
      Order.findOneAndUpdate({_id: (req.params.id)}, { $set: { isConfirmed: true, isDone: false } }, { returnOriginal: false }, (err, result) => {
        if (err){
          console.log(err);
        }
    });
  });
</code>```

So the site should be updating orders parameters such as 'isConfirmed' from false to true in mongoDB on a click of a button without reloading. Also ALL orders should appear on the site without reloading as well.

答:
You need to use the success: function(someVar) part of your ajax call.  This tells your code what it should do after the call is made, and any context you pass from your route will be accessible through someVar.  For example:

assuming your index.html looks like this, and that you are using jQuery:

```<code>  $.ajax({
  url: 'order/' + $(this).attr('data-id') + '/confirm',
  type: 'POST',
  contentType: 'application/json',
  success: function(data){
      //code to change the html of "someDiv"
      $('#someDiv').html(data['someData']);
  }
</code>```

On a side note, I would recommend always passing e in your functions, instead of calling event.preventDefault() because event by itself doesn't work on Firefox sometimes.  For example:

```<code>$('.confirm').click(function(e){
  e.preventDefault();
...
</code>```

Lastly, I don't think you need the event.stopPropagation.

Body:
I have 'orders page' where orders should appear and could be changed with ajax without reloading the page. How do i make it to change specific boolean in mongoDB on a button click? Also i need to refresh page every time a new order comes up without reloading the page.

It works great with reloading the page with routing, but i need AJAX.

Script.js

  $('.confirm').click(function(){
    event.preventDefault();
    event.stopPropagation();
    $.ajax({
      url: 'order/' + $(this).attr('data-id') + '/confirm',
      type: 'POST',
      contentType: 'application/json',
      success: function(){
      }
  });
});

index.ejs

<form class="confirm" data-id="<%= order.id %>" method="POST">
  <button class="btn btn-success btn-lg" type="submit"> Priimti</button>
</form>

orders.js

router.post('/order/:id/confirm', isLoggedIn, function(req, res){
      Order.findOneAndUpdate({_id: (req.params.id)}, { $set: { isConfirmed: true, isDone: false } }, { returnOriginal: false }, (err, result) => {
        if (err){
          console.log(err);
        }
    });
  });

So the site should be updating orders parameters such as 'isConfirmed' from false to true in mongoDB on a click of a button without reloading. Also ALL orders should appear on the site without reloading as well.

Body:
You need to use the success: function(someVar) part of your ajax call.  This tells your code what it should do after the call is made, and any context you pass from your route will be accessible through someVar.  For example:

assuming your index.html looks like this, and that you are using jQuery:

  $.ajax({
  url: 'order/' + $(this).attr('data-id') + '/confirm',
  type: 'POST',
  contentType: 'application/json',
  success: function(data){
      //code to change the html of "someDiv"
      $('#someDiv').html(data['someData']);
  }

On a side note, I would recommend always passing e in your functions, instead of calling event.preventDefault() because event by itself doesn't work on Firefox sometimes.  For example:

$('.confirm').click(function(e){
  e.preventDefault();
...

Lastly, I don't think you need the event.stopPropagation.


问:
Test class for setting same value to two diferents objects
Need help doing test class for this code part! how to do this in a test class

I tried creating the account and equals to the other object.

```<code>for (Account YieldU : AccountList){
           YieldU.Yield__c = a.Yield__c;
           YieldU.Yield2__c = a.Yield2__c;
          ...
</code>```

答:
As far as I understand in your code 'a' will also be one object so firstly insert a record for that object.</p>

```<code>abc__c ab= new abc__c();
ab.Yield__c = 10;
ab.Yield2__c = 20;
insert ab;

Account acct = new Account();
acct.Yield__c = ab.Yield__c;
acct.Yield2__c = ab.Yield2__c;
insert acct;
</code>```

Body:
Need help doing test class for this code part! how to do this in a test class

I tried creating the account and equals to the other object.

for (Account YieldU : AccountList){
           YieldU.Yield__c = a.Yield__c;
           YieldU.Yield2__c = a.Yield2__c;
          ...

Body:
As far as I understand in your code 'a' will also be one object so firstly insert a record for that object.

abc__c ab= new abc__c();
ab.Yield__c = 10;
ab.Yield2__c = 20;
insert ab;

Account acct = new Account();
acct.Yield__c = ab.Yield__c;
acct.Yield2__c = ab.Yield2__c;
insert acct;


问:
Moved my project folder to another location and now xcworkspace wont open with my main project
I just moved the folder where the entire project is located inside and after that when i try to launch my project with Xcode through the xcworkspace file, it just opens with the pod files ignoring my main project. Is there any way to reattach them?</p>

答:
With finder go the folder where your project is located. You can find it directly from Xcode if you click on the project file at the Navigator (left side of the screen) and the on the inspector (right) click on the arrow next to the file path and it will open the folder.

Then right click on the project file (somename.xcodeproj)and show package content. Then open project.pbxproj file with a text editor. Once opened you should find for lines with ** >>>>, ==== or <<<< ** symbols and remove the full lines. (I recommend you to make a copy of the file before touching anything). Save it, close everything and restart Xcode again. It should be ok.


问:
Cannot get ASP.Net to serve any pages under IIS6
I am trying to set up another instance of a live website for a customer to evalulate, however i am unable to get the server to serve up any ASP.NET pages at all.

I know this is normally a bit of a noob question, but i have set up these servers a hundred times and know all the usual gotchas, i have done all of the following to no avail, and for my example i have created a simple test page that writes out hello world, and i'm still unable to get anything to serve..

This is windows server 2003 R2 SPII

I have registered ASP.NET using aspnet_regiis.exe -i

I have enabled the web service extensions

I have created it as a virtual directory, and created the application

I have set the version of ASP.NET for my virtual directory to use

I have even created a new App Pool and given it administrator permissions.

I have run Auth Diag From Microsoft, i get and error from the authentication check, but it is blank

I have given full control to the everyone group for the folder

I have tried creating a new website with a different port, same problem

In fiddler i get the following repsonse when loading an asp.net page :

```<code>HTTP/1.1 504 Fiddler - Receive Failure
Content-Type: text/html
Connection: close
Timestamp: 09:43:01:0634

ReadResponse() failed: The server did not return a response for this request.
</code>```

Looking at the IIS logs, i dont see any entries for any of the ASP.NET requests unless i turn on windows authentication, then i see

```<code>2011-04-12 08:13:23 W3SVC1 10.4.3.16 GET /test/Test.aspx - 80 - 10.2.16.17 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+GTB6.6;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729;+InfoPath.2;+.NET4.0C;+.NET4.0E) - 401 2 2148074254

2011-04-12 08:13:26 W3SVC1 10.4.3.16 GET /test/Test.aspx - 80 - 10.2.16.17 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+GTB6.6;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729;+InfoPath.2;+.NET4.0C;+.NET4.0E) - 401 1 0
</code>```

HTML Pages serve up just fine, i'm stumped and about to get the server re-built as i have wasted long enough on this..

Any ideas :( ?

答: I ended up removing IIS and re-installign it, set the site back up and it worked fine...</p>

Body:
I am trying to set up another instance of a live website for a customer to evalulate, however i am unable to get the server to serve up any ASP.NET pages at all.

I know this is normally a bit of a noob question, but i have set up these servers a hundred times and know all the usual gotchas, i have done all of the following to no avail, and for my example i have created a simple test page that writes out hello world, and i'm still unable to get anything to serve..

This is windows server 2003 R2 SPII

I have registered ASP.NET using aspnet_regiis.exe -i

I have enabled the web service extensions

I have created it as a virtual directory, and created the application

I have set the version of ASP.NET for my virtual directory to use

I have even created a new App Pool and given it administrator permissions.

I have run Auth Diag From Microsoft, i get and error from the authentication check, but it is blank

I have given full control to the everyone group for the folder

I have tried creating a new website with a different port, same problem

In fiddler i get the following repsonse when loading an asp.net page :

HTTP/1.1 504 Fiddler - Receive Failure
Content-Type: text/html
Connection: close
Timestamp: 09:43:01:0634

ReadResponse() failed: The server did not return a response for this request.

Looking at the IIS logs, i dont see any entries for any of the ASP.NET requests unless i turn on windows authentication, then i see

2011-04-12 08:13:23 W3SVC1 10.4.3.16 GET /test/Test.aspx - 80 - 10.2.16.17 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+GTB6.6;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729;+InfoPath.2;+.NET4.0C;+.NET4.0E) - 401 2 2148074254

2011-04-12 08:13:26 W3SVC1 10.4.3.16 GET /test/Test.aspx - 80 - 10.2.16.17 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+GTB6.6;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729;+InfoPath.2;+.NET4.0C;+.NET4.0E) - 401 1 0

HTML Pages serve up just fine, i'm stumped and about to get the server re-built as i have wasted long enough on this..

Any ideas :( ?


问:
How to save DATE at the MySQL column
I am building simple REST with Spring Boot, MySQL, Hibernate.
Want to save current date (autogenerated) using Hibernate but everytime i test it in the PostMan i get Null

```<code>@Entity
@Table (name="purchase")
public class Purchase {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Temporal(TemporalType.DATE)
@Column(name="createat")
private Date created;}
CREATE TABLE `purchase`.`purchase` (
`id` INT NOT NULL             AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`createat` DATE,
PRIMARY KEY (`id`));
</code>```

I Need to save current date to my createat COLUMN

答:
Using Hibernate you can just use @CreationTimestamp to insert default date.

```<code>@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date")
private Date createDate;
</code>```

and @UpdateTimestamp to update the value if necessary

```<code>@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modify_date")
private Date modifyDate;
</code>```

Title: How to save DATE at the MySQL column

Body:
I am building simple REST with Spring Boot, MySQL, Hibernate.
Want to save current date (autogenerated) using Hibernate but everytime i test it in the PostMan i get Null

@Entity
@Table (name="purchase")
public class Purchase {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Temporal(TemporalType.DATE)
@Column(name="createat")
private Date created;}
CREATE TABLE `purchase`.`purchase` (
`id` INT NOT NULL             AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`createat` DATE,
PRIMARY KEY (`id`));

I Need to save current date to my createat COLUMN

Body:
Using Hibernate you can just use @CreationTimestamp to insert default date.

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date")
private Date createDate;

and @UpdateTimestamp to update the value if necessary

@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modify_date")
private Date modifyDate;


问:
How to fix Execution failed for task ':app:mergeDebugResources'
I updated to Android 3.4 and I'm Working on a TO-DO app and when I wanna run it but it is giving me this error:

```<code>Executing tasks: [:app:assembleDebug]

> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:compileDebugRenderscript NO-SOURCE
> Task :app:checkDebugManifest UP-TO-DATE
> Task :app:generateDebugBuildConfig UP-TO-DATE
> Task :app:prepareLintJar UP-TO-DATE
> Task :app:generateDebugSources UP-TO-DATE
> Task :app:javaPreCompileDebug UP-TO-DATE
> Task :app:mainApkListPersistenceDebug UP-TO-DATE
> Task :app:generateDebugResValues UP-TO-DATE
> Task :app:generateDebugResources UP-TO-DATE
> Task :app:mergeDebugResources FAILED

Execution failed for task ':app:mergeDebugResources'
>1 exception was raised by workers:
  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Users\CHARAN\Desktop\Android Development\BPTODO\app\src\main\res\drawable-v24\ic_launcher_foreground.xml:11: error: not well-formed (invalid token).
  C:\Users\CHARAN\Desktop\Android Development\BPTODO\app\src\main\res\drawable-v24\ic_launcher_foreground.xml: error: file failed to compile.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 35s
8 actionable tasks: 1 executed, 7 up-to-date

</code>```

I tried
1. clean and rebuild
2. invalidate caches and Restart
3. changing gradle dependencies
and this what android studio suggested
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
And even tried this

Gradle(project)

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```

Gradle(app)

```<code>
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.bptodo"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}
</code>```

Activity_main.xml

```<code><LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F4F4F4"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:background="#1eea40"
        android:layout_height="198dp">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_marginLeft="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/titlepage"
                    android:layout_marginTop="20dp"
                    android:textSize="32sp"
                    android:textColor="#FFF"
                    android:text="TO DO's"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

                <TextView
                    android:id="@+id/subtitlepage"
                    android:textSize="18sp"
                    android:textColor="#4A4E6A"
                    android:layout_marginTop="8dp"
                    android:text="Finish Them Quickly Today"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            </LinearLayout>

            <Button
                android:id="@+id/btnAddNew"
                android:layout_width="99dp"
                android:layout_height="52dp"
                android:layout_marginLeft="60dp"
                android:layout_marginTop="35dp"
                android:background="@drawable/bgbtnnew"
                android:text="+"
                android:textAlignment="center"
                android:textColor="#FFF"
                android:textSize="38sp" />

        </LinearLayout>

        <View
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:background="#131E69"
            android:layout_height="1dp" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/ourdoes"
        android:layout_width="match_parent"
        android:layout_marginTop="-60dp"
        android:layout_marginRight="16dp"
        android:layout_marginLeft="16dp"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

    <TextView
        android:id="@+id/endpage"
        android:textSize="16sp"
        android:textColor="#9A9A9A"
        android:layout_marginTop="20dp"
        android:text="No More Does"
        android:textAlignment="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

“I expect the output of smooth run, Please Help"
Thanks in advance

答:
Check the file: res\drawable-v24\ic_launcher_foreground.xml

Your error says it's not well formed. It means that there are some syntax error or typo or missing brackets or maybe no images.

Body:
I updated to Android 3.4 and I'm Working on a TO-DO app and when I wanna run it but it is giving me this error:

Executing tasks: [:app:assembleDebug]

> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:compileDebugRenderscript NO-SOURCE
> Task :app:checkDebugManifest UP-TO-DATE
> Task :app:generateDebugBuildConfig UP-TO-DATE
> Task :app:prepareLintJar UP-TO-DATE
> Task :app:generateDebugSources UP-TO-DATE
> Task :app:javaPreCompileDebug UP-TO-DATE
> Task :app:mainApkListPersistenceDebug UP-TO-DATE
> Task :app:generateDebugResValues UP-TO-DATE
> Task :app:generateDebugResources UP-TO-DATE
> Task :app:mergeDebugResources FAILED

Execution failed for task ':app:mergeDebugResources'
>1 exception was raised by workers:
  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Users\CHARAN\Desktop\Android Development\BPTODO\app\src\main\res\drawable-v24\ic_launcher_foreground.xml:11: error: not well-formed (invalid token).
  C:\Users\CHARAN\Desktop\Android Development\BPTODO\app\src\main\res\drawable-v24\ic_launcher_foreground.xml: error: file failed to compile.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 35s
8 actionable tasks: 1 executed, 7 up-to-date

I tried
1. clean and rebuild
2. invalidate caches and Restart
3. changing gradle dependencies
and this what android studio suggested
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
And even tried this

Gradle(project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Gradle(app)

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.bptodo"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

Activity_main.xml

<LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F4F4F4"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:background="#1eea40"
        android:layout_height="198dp">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_marginLeft="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/titlepage"
                    android:layout_marginTop="20dp"
                    android:textSize="32sp"
                    android:textColor="#FFF"
                    android:text="TO DO's"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

                <TextView
                    android:id="@+id/subtitlepage"
                    android:textSize="18sp"
                    android:textColor="#4A4E6A"
                    android:layout_marginTop="8dp"
                    android:text="Finish Them Quickly Today"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            </LinearLayout>

            <Button
                android:id="@+id/btnAddNew"
                android:layout_width="99dp"
                android:layout_height="52dp"
                android:layout_marginLeft="60dp"
                android:layout_marginTop="35dp"
                android:background="@drawable/bgbtnnew"
                android:text="+"
                android:textAlignment="center"
                android:textColor="#FFF"
                android:textSize="38sp" />

        </LinearLayout>

        <View
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:background="#131E69"
            android:layout_height="1dp" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/ourdoes"
        android:layout_width="match_parent"
        android:layout_marginTop="-60dp"
        android:layout_marginRight="16dp"
        android:layout_marginLeft="16dp"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

    <TextView
        android:id="@+id/endpage"
        android:textSize="16sp"
        android:textColor="#9A9A9A"
        android:layout_marginTop="20dp"
        android:text="No More Does"
        android:textAlignment="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

“I expect the output of smooth run, Please Help"
Thanks in advance


问:
Unable to setup multiple node kubernetes cluster using kubeadm (Vagrant)
I have been setting up multi node kubernetes cluster using kubeadm.Setup included 1 master and worker node each. I have created the VM using vagrant.

I followed the docs,
https://kubernetes.io/docs/setup/independent/install-kubeadm/
https://kubernetes.io/docs/setup/independent/create-cluster-kubeadm

Created 2 VM's using vagrant

IP: Master- 192.168.33.10 , Worker- 192.168.1.21 (Both host only network)

I have experienced 2 scenarios,

Case 1:

Ran kubeadm init --pod-network-cidr=10.244.0.0/16 successfully with all pods running.

Installed "Canal" pod network add on.

Followed all the instructions given at the end of the successfull kubeadm init command.

SSH into 2nd VM and ran kubeadm join .. command and I am struck at  "[preflight] Running pre-flight checks"

Case 2:

Did the same process with tag --apiserver-advertise-address=192.168.33.10

Successfully ran the command kubeadm init --apiserver-advertise-address=192.168.33.10

But when I ran the command kubectl get nodes it only showed the master node. (expected the worker node to show too).

Kindly help me understand how can I complete this setup. Thank you.

答: I have github repository which does exactly what you want. I am pretty sure that you will get idea from it. If anything is not clear, please update with comment or original post.</p>


问:
String Hex to Bool and String Hex to String ASCII conversion
Details about the application:

Developed under Visual Studio 2019 (Windows 10)

Designed on UWP platform with C# & XAML language

My application receive a frame from a remote server. After receiving the frame, I decode all received information, it's here that I have a problem.

Data received (hexa) : CA0000000100000030000000010000003137322E31362E3233392E343100000000000000000000000000000000000000

Code:

```<code>int _IndexLecture = 0;
bool _PRIORITE;
string _ABONNE;

_TraitementString = _Decode.Substring(_IndexLecture + 8, 2);
_VOIE = Convert.ToSByte(_TraitementString, 16);

_TraitementString = _Decode.Substring(_IndexLecture + 24, 2);
_PRIORITE = Convert.ToBoolean(_TraitementString);

_TraitementString = _Decode.Substring(_IndexLecture + 32, 64);
_ABONNE = Convert.ToString(_TraitementString);
</code>```

Obtained result :

```<code>_VOIE = 1
_PRIORITE =
_ABONNE =
</code>```

Exepected result :

```<code>_VOIE = 1
_PRIORITE = TRUE
_ABONNE = "172.16.239.41"
</code>```

How can I pass my hex string to bool and ASCII string to find the right values?

答:
String Hex to Bool and String Hex to String ASCII conversion

The reason why _PRIORITE is not correct, because _IndexLecture is string type. you could not pass such "01" string parameter to ToBoolean(sting value) method, you can only pass "true" or "false" string parameter. Please use the following method to replace.

```<code>_TraitementString = _Decode.Substring(_IndexLecture + 24, 2);
_PRIORITE = Convert.ToBoolean(int.Parse(_TraitementString, System.Globalization.NumberStyles.AllowHexSpecifier));
</code>```

How to pass hex string to IPAddress.

You could refer this case reply. And please note Internet Protocol version 4 (IPv4) defines an IP address as a 32-bit number. So, it can expressed in 8-bit hexadecimal numbers. Please check if _TraitementStringis correct.

```<code>var ip = new IPAddress(long.Parse("4a0e94cb", NumberStyles.AllowHexSpecifier));
</code>```

Body:
Details about the application:

Developed under Visual Studio 2019 (Windows 10)

Designed on UWP platform with C# & XAML language

My application receive a frame from a remote server. After receiving the frame, I decode all received information, it's here that I have a problem.

Data received (hexa) : CA0000000100000030000000010000003137322E31362E3233392E343100000000000000000000000000000000000000

Code:

int _IndexLecture = 0;
bool _PRIORITE;
string _ABONNE;

_TraitementString = _Decode.Substring(_IndexLecture + 8, 2);
_VOIE = Convert.ToSByte(_TraitementString, 16);

_TraitementString = _Decode.Substring(_IndexLecture + 24, 2);
_PRIORITE = Convert.ToBoolean(_TraitementString);

_TraitementString = _Decode.Substring(_IndexLecture + 32, 64);
_ABONNE = Convert.ToString(_TraitementString);

Obtained result :

_VOIE = 1
_PRIORITE =
_ABONNE =

Exepected result :

_VOIE = 1
_PRIORITE = TRUE
_ABONNE = "172.16.239.41"

How can I pass my hex string to bool and ASCII string to find the right values?

Body:
String Hex to Bool and String Hex to String ASCII conversion

The reason why _PRIORITE is not correct, because _IndexLecture is string type. you could not pass such "01" string parameter to ToBoolean(sting value) method, you can only pass "true" or "false" string parameter. Please use the following method to replace.

_TraitementString = _Decode.Substring(_IndexLecture + 24, 2);
_PRIORITE = Convert.ToBoolean(int.Parse(_TraitementString, System.Globalization.NumberStyles.AllowHexSpecifier));

How to pass hex string to IPAddress.

You could refer this case reply. And please note Internet Protocol version 4 (IPv4) defines an IP address as a 32-bit number. So, it can expressed in 8-bit hexadecimal numbers. Please check if _TraitementStringis correct.

var ip = new IPAddress(long.Parse("4a0e94cb", NumberStyles.AllowHexSpecifier));


问:
What am I doing wrong? It shows me that the list index is out of range
I have a given list and I want to add all elements of that list with an odd index to the new list. Here is my code :

```<code>def odd_indices(lst):
  new_lst = [ lst[i] for i in lst if (i + 2) % 2 != 0 ]
  return new_lst
</code>```

What am I doing wrong?

答:
You could slice the list as follows:

lst[1::2]
```

<p>The general syntax is:</p>

<pre class="lang-py prettyprint-override"><code>list[start:end:step]
</code>```

Body:
I have a given list and I want to add all elements of that list with an odd index to the new list. Here is my code :

def odd_indices(lst):
  new_lst = [ lst[i] for i in lst if (i + 2) % 2 != 0 ]
  return new_lst

What am I doing wrong?

Body:
You could slice the list as follows:

lst[1::2]

The general syntax is:

list[start:end:step]


问:
Finding missing numbers in a preset range
I am having a problem finding missing values within a preset range.  For example I have:

Column A: 3, 5, 7, 9, 10, 11
I want either VBA or a formula in excel to return
Column B: 1, 2, 4, 6, 8, 12, 13 --> 30

The final number in Column B will vary.  I want it to change based on user discretion.  For my problem I am working with days of the month.  So January, February, and March have different total days.  I've seen a lot of examples, but all are based on a array in the spreedsheet.  What if I want to change the array to 1-30, 1-31, or 1-28 (depending on which month I am looking at)?

答:
this is how VBA code would be:</p>

```<code>Option Explicit
Sub MissingNumbers()

    Dim C As Range
    Dim LastRow As Long
    Dim FirstNumber As Long
    Dim LastNumber As Long
    Dim i As Long
    Dim MyNumbers As New Scripting.Dictionary 'Need Microsoft Scripting Runtime library checked on references

    FirstNumber = 1 'here goes your first number to check
    LastNumber = 30 'here goes the last number to check

    'Assume you have a column A with all the values and column B will hold the missing ones
    With ThisWorkbook.Sheets("MySheet") 'Change MySheet for your working sheet name
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'Last Row on column A
        'Store your existing numbers in the dictionary
        For Each C In .Range("A2:A" & LastRow) 'I'm assuming you have headers on row 1
            MyNumbers.Add C.Value, 1
        Next C
        LastRow = 2 'starting on row 2 for column B
        'Loop through all the numbers you want to check
        For i = FirstNumber To LastNumber
            'If the number doesn't exist on the dictionary
            If Not MyNumbers.Exists(i) Then
                .Cells(LastRow, 2) = i 'write it on the next available row for columnB
                LastRow = LastRow + 1 'add 1 number to last row so we don't overwrite results
            End If
        Next i
    End With

End Sub
</code>```

Body:
this is how VBA code would be:

Option Explicit
Sub MissingNumbers()

    Dim C As Range
    Dim LastRow As Long
    Dim FirstNumber As Long
    Dim LastNumber As Long
    Dim i As Long
    Dim MyNumbers As New Scripting.Dictionary 'Need Microsoft Scripting Runtime library checked on references

    FirstNumber = 1 'here goes your first number to check
    LastNumber = 30 'here goes the last number to check

    'Assume you have a column A with all the values and column B will hold the missing ones
    With ThisWorkbook.Sheets("MySheet") 'Change MySheet for your working sheet name
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'Last Row on column A
        'Store your existing numbers in the dictionary
        For Each C In .Range("A2:A" & LastRow) 'I'm assuming you have headers on row 1
            MyNumbers.Add C.Value, 1
        Next C
        LastRow = 2 'starting on row 2 for column B
        'Loop through all the numbers you want to check
        For i = FirstNumber To LastNumber
            'If the number doesn't exist on the dictionary
            If Not MyNumbers.Exists(i) Then
                .Cells(LastRow, 2) = i 'write it on the next available row for columnB
                LastRow = LastRow + 1 'add 1 number to last row so we don't overwrite results
            End If
        Next i
    End With

End Sub


问:
Different behavior of MSVC and clang for if constexpr branches
Given this helper function:

```<code>template<typename Type>
std::string toString(Type const& value, bool encloseInQuotes = false) {
  if constexpr (std::is_same<bool, Type>::value) {
    auto s = value ? "true" : "false";
    return encloseInQuotes ? "\""s + s + "\"" : s;
  }

  if constexpr (std::is_arithmetic<Type>::value) {
    if (std::isnan(value)) {
      return encloseInQuotes ? "\"NaN\"" : "NaN";
    }
  }

  return "";
}
</code>```

which is supposed to convert basic types (and strings) to a string expression, I get a compilation error with MSVC when using it like this:

```<code>int main() {
  std::string temp = toString(true);
  return 0;
}
</code>```

With clang this compiles without any problem, with MSVC however I get this:

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): error C2668: 'fpclassify': ambiguous call to overloaded function

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(288): note: could be 'int fpclassify(long double) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(283): note: or       'int fpclassify(double) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(278): note: or       'int fpclassify(float) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): note: while trying to match the argument list '(_Ty)'

2>        with

2>        [

2>            _Ty=int

2>        ]

2>: note: see reference to function template instantiation 'bool isnan(_Ty) noexcept' being compiled

2>        with

2>        [

2>            Type=int,

2>            _Ty=int

2>        ]

Obviously the compiler considers the if constexpr (std::is_arithmetic<Type>::value) test as valid alternative too and generates the mentioned error. However, at runtime it correctly takes the path for bool (when I leave out the if constexpr (std::is_arithmetic<Type>::value) part or use a cast if (std::isnan(static_cast<double>(value)))).

How can I make this compile correctly on Windows as well?

答:
For bool at least two type traits return true:

```<code>std::is_same<bool, Type>::value
std::is_arithmetic<Type>::value
</code>```

and then you make a call std::isnan(true). Use else if:

```<code>if constexpr (std::is_same<bool, Type>::value) {
    auto s = value ? "true" : "false";
    return encloseInQuotes ? "\""s + s + "\"" : s;
}
else if constexpr (std::is_arithmetic<Type>::value) {
    if (std::isnan(value)) {
        return encloseInQuotes ? "\"NaN\"" : "NaN";
    }
    ...
}
else
    return "";
</code>```

Body:
Given this helper function:

template<typename Type>
std::string toString(Type const& value, bool encloseInQuotes = false) {
  if constexpr (std::is_same<bool, Type>::value) {
    auto s = value ? "true" : "false";
    return encloseInQuotes ? "\""s + s + "\"" : s;
  }

  if constexpr (std::is_arithmetic<Type>::value) {
    if (std::isnan(value)) {
      return encloseInQuotes ? "\"NaN\"" : "NaN";
    }
  }

  return "";
}

which is supposed to convert basic types (and strings) to a string expression, I get a compilation error with MSVC when using it like this:

int main() {
  std::string temp = toString(true);
  return 0;
}

With clang this compiles without any problem, with MSVC however I get this:

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): error C2668: 'fpclassify': ambiguous call to overloaded function

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(288): note: could be 'int fpclassify(long double) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(283): note: or       'int fpclassify(double) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(278): note: or       'int fpclassify(float) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): note: while trying to match the argument list '(_Ty)'

2>        with

2>        [

2>            _Ty=int

2>        ]

2>: note: see reference to function template instantiation 'bool isnan(_Ty) noexcept' being compiled

2>        with

2>        [

2>            Type=int,

2>            _Ty=int

2>        ]

Obviously the compiler considers the if constexpr (std::is_arithmetic<Type>::value) test as valid alternative too and generates the mentioned error. However, at runtime it correctly takes the path for bool (when I leave out the if constexpr (std::is_arithmetic<Type>::value) part or use a cast if (std::isnan(static_cast<double>(value)))).

How can I make this compile correctly on Windows as well?

Body:
For bool at least two type traits return true:

std::is_same<bool, Type>::value
std::is_arithmetic<Type>::value

and then you make a call std::isnan(true). Use else if:

if constexpr (std::is_same<bool, Type>::value) {
    auto s = value ? "true" : "false";
    return encloseInQuotes ? "\""s + s + "\"" : s;
}
else if constexpr (std::is_arithmetic<Type>::value) {
    if (std::isnan(value)) {
        return encloseInQuotes ? "\"NaN\"" : "NaN";
    }
    ...
}
else
    return "";


问:
IE Handling in Excel macros
I am new to Excel macros and I am trying to auto-fill the text box and select the option from Dropdown and click on Submit.

Using macros I have navigated to a page and from the page, I need to enter the text in the text box, and based on the Suggestion, I need to select the option.

Once the option is selected I need to click on continue using macros.

Here is the current code (I tried with the commented line but it's not working).

```<code>Sub Create_Change()
    Dim i As Long
    Dim URL As String
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object
    Dim HWNDSrc As Long
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    URL = "URL to Navigate"
    IE.Navigate URL
    Application.StatusBar = URL & " is loading. Please wait..."
    Do While IE.ReadyState = 4: DoEvents: Loop
    Do Until IE.ReadyState = 4: DoEvents: Loop
    Application.StatusBar = URL & " Loaded"
    ' IE.Document.All("Search for a template").Value = "text to search"
    Set IE = Nothing
    Set objElement = Nothing
    Set objCollection = Nothing
End Sub
</code>```

HTML CODE:

<input title="Search for a template"
       class="change-template__search-input ng-pristine ng-untouched ng-valid"
       role="combobox"
       aria-expanded="false"
       aria-owns="typeahead-258-8737"
       aria-autocomplete="list"
       type="text"
       placeholder="Search for a template"
       ng-enter="getRecommendedTemplates(template.search)"
       ng-model="template.search"
       typeahead="template as template for template in getTemplateList($viewValue)"
       typeahead-focus-first="false"
       typeahead-on-select="getRecommendedTemplates($item)"
       typeahead-min-length="3">
```

答:
You could try the following:

1) Focus and change

```<code>With ie.document.querySelector("[title='Search for a template']")
    .focus
    .value = "abcd"
End With
</code>```

2) Javascript set value

```<code>ie.document.parentWindow.execScript "document.querySelector('[title=\'Search for a template\']').value = 'abcd';"
</code>```

3) Attach event and fire

```<code>Dim evt As Object
Set evt = ie.document.createEvent("HTMLEvents")
evt.initEvent "change", True, False

With ie.document.querySelector("[title='Search for a template']")
    .Focus
    .Value = "abcd"
    .dispatchEvent evt
End With
</code>```

4) FireEvent

```<code>With ie.document.querySelector("[title='Search for a template']")
    .Focus
    .Value = "abcd"
    .FireEvent "onchange"
End With
</code>```

Title: IE Handling in Excel macros

Body:
I am new to Excel macros and I am trying to auto-fill the text box and select the option from Dropdown and click on Submit.

Using macros I have navigated to a page and from the page, I need to enter the text in the text box, and based on the Suggestion, I need to select the option.

Once the option is selected I need to click on continue using macros.

Here is the current code (I tried with the commented line but it's not working).

Sub Create_Change()
    Dim i As Long
    Dim URL As String
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object
    Dim HWNDSrc As Long
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    URL = "URL to Navigate"
    IE.Navigate URL
    Application.StatusBar = URL & " is loading. Please wait..."
    Do While IE.ReadyState = 4: DoEvents: Loop
    Do Until IE.ReadyState = 4: DoEvents: Loop
    Application.StatusBar = URL & " Loaded"
    ' IE.Document.All("Search for a template").Value = "text to search"
    Set IE = Nothing
    Set objElement = Nothing
    Set objCollection = Nothing
End Sub

HTML CODE:

<input title="Search for a template"
       class="change-template__search-input ng-pristine ng-untouched ng-valid"
       role="combobox"
       aria-expanded="false"
       aria-owns="typeahead-258-8737"
       aria-autocomplete="list"
       type="text"
       placeholder="Search for a template"
       ng-enter="getRecommendedTemplates(template.search)"
       ng-model="template.search"
       typeahead="template as template for template in getTemplateList($viewValue)"
       typeahead-focus-first="false"
       typeahead-on-select="getRecommendedTemplates($item)"
       typeahead-min-length="3">

Body:
You could try the following:

1) Focus and change

With ie.document.querySelector("[title='Search for a template']")
    .focus
    .value = "abcd"
End With

2) Javascript set value

ie.document.parentWindow.execScript "document.querySelector('[title=\'Search for a template\']').value = 'abcd';"

3) Attach event and fire

Dim evt As Object
Set evt = ie.document.createEvent("HTMLEvents")
evt.initEvent "change", True, False

With ie.document.querySelector("[title='Search for a template']")
    .Focus
    .Value = "abcd"
    .dispatchEvent evt
End With

4) FireEvent

With ie.document.querySelector("[title='Search for a template']")
    .Focus
    .Value = "abcd"
    .FireEvent "onchange"
End With