text:
Q: Using a string to reference a variable in C++ Is it even possible to use a string to reference a variable in c++? Note that this is a wrapper around a c project.
I have an incoming message that looks like with data populated in all 3 variables:
struct {
  char[20] var_a;
  char[20] var_b;
  char[20] var_c;
} data_type;

Additionally, I have another incoming message that can either be a string of "var_a", "var_b", or "var_c"
Is there anyway I can extract the data based on my incoming message.
For example
char new[20] = str2var("var_a")

Where str2var is just there to represent what I am trying to do. The size of the message and the data are already defined, I just need the ability to select which data to pull out based on another function.
Any other ideas to accomplish this goal are welcomed.

A: From what you described, you should be able to index the last character, and just use a case statement.
char[20] m2;  // second message

switch (m2[4]) {

  case 'a':
    // use var_a
    break;

  case 'b':
    // use var_b
    break;

  case 'c':
    // use var_c
    break;

  default:
    // error
    break;
}


text:
Q: Can't select Multiple Dropdown with Selenium webdriver (not class Select) I'm having a problem with my tests with Selenium webdriver. I'm using Java. Can't select from a multiple drop-down that is not class Select. This is how the drop-down looks like:
Drop-Down picture
And that's the code:

       Categories
      <select placeholder="" multiple="multiple" id="CurrentCategoriesNomIds" name="CurrentCategoriesNomIds" tabindex="-1" class="selectized" style="display: none;">
          <option value="325" selected="selected">Education</option>
      </select>

       Education
       ×

    <input type="text" autocomplete="off" tabindex="" id="CurrentCategoriesNomIds-selectized" style="width: 4px; opacity: 1; position: relative; left: 0px;">

Agriculture

Culture

Employment

Environment

Other

Political

Transport

This is how it looks like when 2 options are selected. I was wondering if I can try with KEYS but the page doesn't work like that. Haven't seen that kind of field before, and not sure how to proceed?

A: You can click on dropdown using this code :
   public static  void selectOption(WebDriver driver, String optionName) {
        List<WebElement> options = driver.findElements(By.xpath("//div[@class='selectize-dropdoun-content']//div[@class='option']"));
        options.forEach(option -> {
            if (option.getAttribute("innerText").equals(optionName)) {
                Actions actions = new Actions(driver);
                actions.moveToElement(option).click().build().perform();
            }
        });
    }

and then use like this:
String option = "Education";
selectOption(driver,option);

Hope that helps you:)
Adding screenshot for what I have tried on website : https://semantic-ui.com/modules/dropdown.html

A: I don't much use Java, so I'll be writing some pseudo code for this that should give you an outline on how to achieve it (but may not run as written).
public static void selectOptionFromSelectizeDropdown(String optionText, String dropdown){
   boolean completed = false;
   int numberOfOptions = driver.findElements(By.css(dropdown + " .option")).length
   for(int i = 0; i < numberOfOptions && completed === false; i++){
       // Check if it's displayed, if it is, HUZZAH! Click the option
       if(driver.findElement(By.xpath('//*/*[contains(@class, "option") and contains(text(), "'+optionText+'")])')).isDisplayed()){
           driver.findElement(By.xpath('//*/*[contains(@class, "option") and contains(text(), "'+optionText+'")])')).click();
           completed === true;
           break;
       } else {
           // In case there are many options, and you have to scroll through them.
           int x = 0;
           while(x <= 6){
              driver.findElement(By.css(dropdown)).sendKeys(Keys.DOWN);
              i++;
           }
       }
       if(i===numberOfOptions - 1){
          throw new Error("Option Not Found");
       }
   }
}

selectOptionFromSelectizeDropdown("Education", ".selectize-dropdown-content");

If this doesn't work, I'd recommend changing the click() to a sendKeys(Key.ENTER) to see if that would work.
Explanation
Will loop through, seeing if the option is displayed on the page. If not, will scroll down x times, and check again, until the option is found.
If it reaches the number of options inside the box, it will throw an error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How is the EMQ Web Dashboard user/password changed? I do not see any configuration or documentation on how to change the username/password for the emqtt.io Web Dashboard.  Does anyone know how to change this?

A: *

*Login to the emq broker web dashboard using default username as
admin and password as public The web dashboard is running on the port 18083 by default so your url will be like http://localhost:18083

*Click on Users on the bottom left of the web dashboard page.

*Click on edit button on the right of the username for which you want
change password for.

*A popup will be shown having an option to change
user password.  Click on save and the password will be changed.

Hope this helps ! Thanks.


text:
Q: Dynamically Populating Drop down list from selection of another drop down value My requirement is that for a selection in a 'meal' drop down list, a second drop down list 'category' should get dynamically populated with values related to the selection in first drop down list. Then depending on what is selected in the meal dropdown, the list should change in category. I have written the following Javascript function but the output I'm getting is not freshly populating the 2nd dropdown. On change of a selection, the new list is just getting appended to the old list.
function changecat() {
    var selectHTML = "";

    var A = ["Soup", "Juice", "Tea", "Others"];
    var B = ["Soup", "Juice", "Water", "Others"];
    var C = ["Soup", "Juice", "Coffee", "Tea", "Others"];

    if (document.getElementById("meal").value == "A") {
        var select = document.getElementById('category').options.length;

        for (var i = 0; i < select; i++) {
            document.getElementById('category').options.remove(i);
        }

        for (var i = 0; i < A.length; i++) {
            var newSelect = document.createElement('option');
            selectHTML = "<option value='" + A[i] + "'>" + A[i] + "</option>";
            newSelect.innerHTML = selectHTML;
            document.getElementById('category').add(newSelect);
        }
    }

    else if (document.getElementById("meal").value == "B") {
        var select = document.getElementById('category').options.length;

        for (var i = 0; i < select; i++) {
            document.getElementById('category').options.remove(i);
        }

        for (var i = 0; i < B.length; i++) {
            var newSelect = document.createElement('option');
            selectHTML = "<option value='" + B[i] + "'>" + B[i] + "</option>";
            newSelect.innerHTML = selectHTML;
            document.getElementById('category').add(newSelect);
        }
    }

    else if (document.getElementById("project").value == "C") {
        var select = document.getElementById('category').options.length;

        for (var i = 0; i < select; i++) {
            document.getElementById('category').options.remove(i);
        }

        for (var i = 0; i < C.length; i++) {
            var newSelect = document.createElement('option');
            selectHTML = "<option value='" + C[i] + "'>" + C[i] + "</option>";
            newSelect.innerHTML = selectHTML;
            document.getElementById('category').add(newSelect);
        }
    }
}

HTML-
<select name="meal" id="meal" onchange="changecat();">
    <option value="">Select</option>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>

<select name="category" id="category">
    <option value="">Select</option>
</select>

A: Hope this might help you.
JSFiddle : DEMO
HTML
<select name="meal" id="meal" onChange="changecat(this.value);">
    <option value="" disabled selected>Select</option>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>
<select name="category" id="category">
    <option value="" disabled selected>Select</option>
</select>

JS
var mealsByCategory = {
    A: ["Soup", "Juice", "Tea", "Others"],
    B: ["Soup", "Juice", "Water", "Others"],
    C: ["Soup", "Juice", "Coffee", "Tea", "Others"]
}

    function changecat(value) {
        if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
        else {
            var catOptions = "";
            for (categoryId in mealsByCategory[value]) {
                catOptions += "<option>" + mealsByCategory[value][categoryId] + "</option>";
            }
            document.getElementById("category").innerHTML = catOptions;
        }
    }

There is a loop (for...in loop) in JavaScript, which would help you in this case

A for...in loop only iterates over enumerable properties. Objects
created from built–in constructors like Array and Object have
inherited non–enumerable properties from Object.prototype and
String.prototype, such as String's indexOf() method or Object's
toString() method. The loop will iterate over all enumerable
properties of the object itself and those the object inherits from its
constructor's prototype (properties closer to the object in the
prototype chain override prototypes' properties).

In each iteration one property from object is assigned to variable-name and this loop continues till all the properties of the object are exhausted.
For more Link

A: You can use onchange event and use a switch statement with the selected value from the first dropdown and according to it append the options to the second list:

    var A= ["Soup", "Juice", "Tea","Others"];
    var B= ["Soup","Juice","Water", "Others"];
    var C= ["Soup","Juice","Coffee", "Tea","Others"];

var changeCat = function changeCat(firstList) {
    var newSel = document.getElementById("category");
    //if you want to remove this default option use newSel.innerHTML=""
    newSel.innerHTML="<option value=\"\">Select</option>"; // to reset the second list everytime
    var opt;

      //test according to the selected value
      switch (firstList.options[firstList.selectedIndex].value) {
          case "A":
              for (var i=0; len=A.length, i<len; i++) {
                    opt = document.createElement("option");
                    opt.value = A[i];
                    opt.text = A[i];
                    newSel.appendChild(opt);
              }
              break;
          case "B":
              for (var i=0; len=B.length, i<len; i++) {
                    opt = document.createElement("option");
                    opt.value = B[i];
                    opt.text = B[i];
                    newSel.appendChild(opt);
              }
              break;
          case "C":
              for (var i=0; len=C.length, i<len; i++) {
                    opt = document.createElement("option");
                    opt.value = C[i];
                    opt.text = C[i];
                    newSel.appendChild(opt);
              }
              break;
      }

}
<select name="meal" id="meal" onchange="changeCat(this);">
     <option value="">Select</option>
     <option value="A">A</option>
     <option value="B">B</option>
     <option value="C">C</option>
</select>

<select name="category" id="category" size="5">
     <option value="">Select</option>
</select>

I used size="5" with the second dropdown to see the live result changes for each selection.

A: The reason why your code gets appended is because in the for loop for clearing the second drop down list, the update expression is not required as the list is itself being reduced in size and so in every iteration the length of the list decreases, and so you are unable to clear the whole list. Also the removal function should be outside the if conditions to avoid redundancy.`function changecat() {
    var selectHTML = "";
var A = ["Soup", "Juice", "Tea", "Others"];
var B = ["Soup", "Juice", "Water", "Others"];
var C = ["Soup", "Juice", "Coffee", "Tea", "Others"];
var select = document.getElementById('category').options.length;

    for (var i = 0; i < select; ) {
        document.getElementById('category').options.remove(i);
    }

if (document.getElementById("meal").value == "A") {

    for (var i = 0; i < A.length; i++) {
        var newSelect = document.createElement('option');
        selectHTML = "<option value='" + A[i] + "'>" + A[i] + "</option>";
        newSelect.innerHTML = selectHTML;
        document.getElementById('category').add(newSelect);
    }
}

else if (document.getElementById("meal").value == "B") {

    for (var i = 0; i < B.length; i++) {
        var newSelect = document.createElement('option');
        selectHTML = "<option value='" + B[i] + "'>" + B[i] + "</option>";
        newSelect.innerHTML = selectHTML;
        document.getElementById('category').add(newSelect);
    }
}

else if (document.getElementById("project").value == "C") {

    for (var i = 0; i < C.length; i++) {
        var newSelect = document.createElement('option');
        selectHTML = "<option value='" + C[i] + "'>" + C[i] + "</option>";
        newSelect.innerHTML = selectHTML;
        document.getElementById('category').add(newSelect);
    }
}

}


text:
Q: Create csv file with Hashmap in Kotlin I am fairly new to kotlin, and have wanted to change the way to save my CSV file. Currently my Hashmap is :
private var Sdata:MutableMap<String, MutableList<String>> = mutableMapOf<String, MutableList<String>>()
and my data looks like this :
{a1 = [1:2:3:4, 1:2:3:4, ....], b2 = [1:2:3:4, 1:2:3:4,....]}
and my csv saving function:
binding.btnSave.setOnClickListener() {
        Sdata = viewModel.savehash
        Log.d(TAG, "CSV VIEW: ${Sdata.keys}")
        Log.d(TAG, "CSV VIEW: ${Sdata.values.size}")
        if(Sdata.keys.size != 0) {
            val csv = File(this.filesDir, "test1.csv") // Internal App storage

            val valuesSeparator = ","
            val lineTerminator = "\r\n"
            //write header, overwrite file if it has existed
            csv.writeText(
                Sdata.keys.joinToString(
                    separator = valuesSeparator,
                    postfix = lineTerminator
                )
            )
            val nRows = Sdata.values.maxOf { it?.size }    // size of list ar not all equal
            for (i in 0 until nRows) {
                val row = Sdata.values
                    .map { it.getOrElse(i) { "" }.trim() }
                    .joinToString(separator = valuesSeparator, postfix = lineTerminator)
                csv.appendText(row)
            }

            Toast.makeText(this, "Data Saved to Documents", Toast.LENGTH_SHORT).show()
        }
        else{
            Toast.makeText(this, "No Logged Data", Toast.LENGTH_SHORT).show()
        }
    }

converts my files to look like this :

I want to reiterate column values where column a1 has --> a1W, a1X, a1Y, a1Z and the values underneath are separated by the ":" delimters so that each single column is separated into 4 columns. Will this be difficult in Kotlin?
Any help would be greatly appreciated thankyou!!

A: The following for loop instead of yours should do the trick (thanks @Joffrey for the hint):
for (i in 0 until nRows) {
    val row = Sdata.flatMap { it.getOrElse(1) { "" }.trim().split(":") }
        .joinToString(separator = valuesSeparator, postfix = lineTerminator)
    csv.appendText(row)
}

Basically, you split your 1:2:3:4 values into a list containing the four numbers. And then your code should do the rest.

A: To do that, you just need to slightly modify the way you create the headers row and the data rows.
For the header row, change the Sdata.keys.joinToString(...) into:
Sdata.keys
    .flatMap { listOf("${it}W", "${it}X", "${it}Y", "${it}Z") }
    .joinToString(separator = valuesSeparator, postfix = lineTerminator)

The flatMap call allows you to create a new list by converting each element (like a1) into a list of 4 elements (a1W, a1X...) and joining all those lists together into a big one.
For the data row, change the .map { it.getOrElse(i) { "" }.trim() } into:
.flatMap { it.getOrElse(i) { "" }.trim().split(":") }


text:
Q: Compare two arrays and merging in PHP I have two arrays:
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");

Here $array1 has keys and values. Now I want to take the first value from $array1(as 1) and I want to check if this is repeated in this array .
Here 1 is repeated two times so I want to take the two keys 1,10 and display the corresponding values of these keys from $array2. If the value in $array1 is not repeated  then I want to just display the value of this key from $array2.
I want to get the output as follows:
Hello Test
check
error

That means in $array1 1,10 keys have the same value so the value of 1 and the value of 10 from $array2 is merged then displayed.
Like 12 has 0 this is not repeated so simply take value of 12 from $array2.
Like 13.
How can I do this?

A: <?php

$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
$groupedKeys = array();
foreach($array1 as $key=>$arr){
   $groupedKeys[$arr][] = $key;
}
foreach($groupedKeys as $key => $groupedKeyArr){
    foreach($groupedKeyArr as $groupedKey){
        echo $array2[$groupedKey];
    }
    echo "
 ";
}

?>

http://codepad.org/9R9s5lTM

A: There is a built in function that returns an array with the number of times a value is repeated http://php.net/manual/en/function.array-count-values.php

A: This is really rough, but a simple way of doing it could be:
<?

$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");

$prev = $array1[1];

foreach($array1 as $key => $val)
{
    if($val != $prev && $key != 1)
    {
        echo '
';
    }

    echo $array2[$key].' ';

    $prev = $val;
}

?>

Example: http://codepad.org/OpLdtStp
This assumes that you're first key is always going to be 1 by the way.

A: I am providing you a function returns an array with the number of times a value is repeated in an array(as values) and values as the keys. Further task is not difficult.
function check_number_of_times_elements_occur_in_array($a)//returns values of array as keys, associating values being their total occurences in the array
{
$r=array();
foreach($a as $v)
    ++$r[$v];
return $r;
}

A: I think this will do for you..
function test($array1,$array2) {
$repeated_values = array_count_values($array1);
foreach($repeated_values as $key => $value){
    if($value > 1) {
        foreach($array1 as $key1 => $value1){
            if($key == $value1){
                $repeated_values_keys[] = $key1;
            }
        }
    }
}
$str_top = "";
foreach($repeated_values_keys as $k){
    $str_top .= $array2[$k]." ";
}
echo $str_top.'
';
foreach($array2 as $key2 => $value){
    if(!in_array($key2,$repeated_values_keys)){
        echo $value.'
';
    }
}

}


text:
Q: Validación de input date con javascript necesito hacer la validación de un input de tipo date, para que garantice que no sea una fecha incorrecta, según leí se puede hacer con una regex, por lo que implementé una, sin embargo, todas las fechas que ejecute salen como "incorrectas". Les dejo mi código
    let fechaUs= document.getElementById("fecha");
    let regex=/^(?:(?:(0?[1-9]|1\d|2[0-8])[/](0?[1-9]|1[0-2])|(29|30)[/](0?[13-9]|1[0-2])|(31)[/](0?[13578]|1[02]))[/](0{2,3}[1-9]|0{1,2}[1-9]\d|0?[1-9]\d{2}|[1-9]\d{3})|(29)[/](0?2)[/](\d{1,2}(?:0[48]|[2468][048]|[13579][26])|(?:0?[48]|[13579][26]|[2468][048])00))$/;
    if(fechaUs.value!="")
    {
        if (regex.test(fechaUs.value)) {
            alert("Fecha correcta");
            return true;
        }else{
            alert("Fecha incorrecta");
            return false;
        }
    }else{
        alert("Debe seleccionar una fecha de nacimiento");
        return false;
    }
}```


text:
Q: how to create postgresql database using linux commandline I have tried to create a postgresql database from linux(CentOS) command line by executing the following,
psql -U admin -p55432 postgres -c "CREATE DATABASE TEST_DB"

Created database name appeared as "test_db". I need to create database in upper case.

A: In PostgreSQL unquoted names are case-insensitive. So I do not see special reason to need of Upper case database name. But you can try something like:
psql -U admin -p55432 postgres -c "CREATE DATABASE \"TEST_DB\""

A: You can use the createdb(1) command, installed with Postgres, to create a database with an uppercase name without having to use quoting:
createdb -U admin -p55432 TEST_DB

Unless you want the database to be owned by admin, you should probably also set an owner using the -O flag.
Note: There's also an accompanying dropdb(1) command.
You can read more about the Postgres command-line tools in the official documentation.


text:
Q: How can I add platform-specific dynamic libraries to Python wheel, with independent binaries for Windows and Linux? I really want to use blender compiled as a python package in my project. I was thinking about attaching already compiled blender binaries to the wheel on PyPI, as compilation is already complicated on its own and requires a huge amount of dependencies. However, I'm new to wheels and I'm not sure how to configure setup.py to make it use different binaries depending on the target platform (How to make two wheels, independent for each platform) and whether the PyPI endpoint will accept them.
I will be very grateful for the answers and/or links to some documentation that describes such usage of wheels because I was not able to correctly formulate the questions to Google on my own.
I'd also like to add that I have already found a method to attach binaries at all here and a way to create platform-specific wheels here but those do not solve my problem, or I'm not aware they do.


text:
Q: Hot to commit changes for a TreeView while editing a node (C#)? I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid.
Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.

A: The node label editing is performed with a text box and when that text box loses focus the change in name will be committed as the new label for the node. So if the 'Save' button you are clicking on takes the focus then it will cause the update automatically because the text box will lose focus.
If the 'Save' button does not take focus then need to handle a click event for the 'Save' button and ask the tree to end any current label editing. If does not have a method/property you can call to request label editing finish so you have two choices. If the tree view has the focus then put the focus somewhere else. Alternatively turn off/on again label editing...
treeView.LabelEdit = false;
treeView.LabelEdit = true;

A: I'll accept the answer even though it's not really documented: does it or does it not have such a method? You actually didn't answer to this, just passed the question back to me.
Meanwhile found the same hack-ish solution with forcing the focus to some other control (not very elegant but works), even though it's a bit harder for me since I use a TreeView as part of a UserControl.

A: Do you really need a save button?
you could listen for the end of the node edit - for instance by listening for the "return" key in the KeyDown event of the TreeView. if you're editing something (find out with SelectedNode.IsEditing) then you know you have a commit. You can then commit this to your dataupdate stuff. If you want to be able to edit many different nodes and save them all at the end, then you need to add each edited node to a collection of some sort, and then when you click your save button iterate through this collection.


text:
Q: How can i share a NSString between classes Is there anyway that i can define an NSString. Inside of one class then access its value inside of another class?

A: As an example...
In global.h
extern NSString *const VERSION;

in global.mm
#import "Global.h"
NSString *const VERSION = @"1.0.1";

any other source file can #import global.h to access the value.


text:
Q: How to get all elements of mobile in Katalon Studio..? I am automating Android App on Android emulator.
I am not able to get all elements of mobile but instead I am getting text of element rather than getting the element.
How can I solve this?

A: import com.kms.katalon.core.mobile.keyword.internal.MobileDriverFactory
import io.appium.java_client.AppiumDriver as AppiumDriver

AppiumDriver<MobileElement> driver = MobileDriverFactory.getDriver()
List <MobileElement> elements = driver.findElementsById("element-id")

Pls try this way, I'm using this way, hope they're what you need.


text:
Q: Am I Calculating Quartiles Correctly? Here is my data set: 5, 8, 12, 42, 43
I am trying to work out the first quartile. When using R (the programming language) it shows the 1st quartile as 8, but when I work it out manually, it shows it as 6.5.
Here's how I am working it out:
First I work out the 25%
25/100 * (5 + 1)

Which is:
1.5

There is no value at 1.5, so I do the following to get the average:
(5 + 8) / 2

Which equals:
6.5

Where am I going wrong?

A: There are 9 methods defined for computing quantiles, see the help page for quantile in R for the details. You can choose between them using the type argument, the default is 7.
Your method corresponds to type 6 (and is that used by Minitab and SPSS):
x <- c(5, 8, 12, 42, 43)
sapply(1:9, function(y) quantile(x,type=y))["25%",,drop=FALSE]
    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]   [,9]
25%    8    8    5 5.75 7.25  6.5    8    7 7.0625

Each method uses a different weighted average of consecutive order statistics. The methods are defined in Hyndman, R. J. and Fan, Y. (1996) Sample quantiles in statistical packages, American Statistician, 50, 361–365.


text:
Q: A value of type 'Widget' can't be assigned to a variable of type 'PreferredSizeWidget'

THERE ARE 2 ERRORS IN THIS PROGRAM WHICH HAVE BEEN SHOWN IN THE IMAGES ABOVE

Main.dart file
void main() {

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Personal Expenses ',
      theme: ThemeData(
        primarySwatch: Colors.green,
        accentColor: Colors.amber,
        //errorColor: Colors.red[700],
        fontFamily: 'Quicksand',
        textTheme: ThemeData.light().textTheme.copyWith(
            title: TextStyle(
              fontFamily: 'OpenSans',
              fontWeight: FontWeight.bold,
              fontSize: 18,
            ),
            button: TextStyle(color: Colors.amber)),
        appBarTheme: AppBarTheme(
          textTheme: ThemeData.light().textTheme.copyWith(
                title: TextStyle(
                  fontFamily: 'OpenSans',
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
        ),
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<Transaction> _userTransactions = [

  ];
  bool _showChart = false;
  List<Transaction> get _recentTransactions {
    return _userTransactions.where((tx) {
      return tx.date.isAfter(
        DateTime.now().subtract(
          Duration(days: 7),
        ),
      );
    }).toList();
  }

  void _addNewTransaction(
      String txTitle, double txAmount, DateTime chosenDate) {
    final newTx = Transaction(
      title: txTitle,
      amount: txAmount,
      date: chosenDate,
      id: DateTime.now().toString(),
    );

    setState(() {
      _userTransactions.add(newTx);
    });
  }

  void _startAddNewTransaction(BuildContext ctx) {
    showModalBottomSheet(
      context: ctx,
      builder: (_) {
        return GestureDetector(
          onTap: () {},
          child: NewTransaction(_addNewTransaction),
          behavior: HitTestBehavior.opaque,
        );
      },
    );
  }

  void _deleteTransaction(String id) {
    setState(() {
      _userTransactions.removeWhere((tx) => tx.id == id);
    });
  }

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final isLandscape = mediaQuery.orientation == Orientation.landscape;
    final PreferredSizeWidget appbar = Platform.isIOS

A value of type 'Widget' can't be assigned to a variable of type 'PreferredSizeWidget'.

        ? CupertinoNavigationBar(
            middle: Text(
              'Personal Expenses ',
            ),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                GestureDetector(
                  child: Icon(CupertinoIcons.add),
                  onTap: () => _startAddNewTransaction(context),
                )
              ],
            ),
          )
        : AppBar(
            title: Text(
              'Personal Expenses ',
              style: TextStyle(fontFamily: 'OpenSans'),
            ),
            actions: <Widget>[
              IconButton(
                icon: Icon(Icons.add),
                onPressed: () => _startAddNewTransaction(context),
              ),
            ],
          );
    final txListWidget = Container(
      height: (mediaQuery.size.height -
              appbar.preferredSize.height -
              mediaQuery.padding.top) *
          0.7,
      child: TransactionList(
        _userTransactions,
        _deleteTransaction,
      ),
    );
    final pageBody = SingleChildScrollView(
      child: Column(

        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          if (isLandscape)
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Show Chart'),
                Switch.adaptive(
                  activeColor: Theme.of(context).accentColor,
                  value: _showChart,
                  onChanged: (val) {
                    setState(() {
                      _showChart = val;
                    });
                  },
                ),
              ],
            ),

        ],
      ),
    );

return Platform.isIOS
? CupertinoPageScaffold(
child: pageBody,
navigationBar: appbar,

The argument type 'PreferredSizeWidget' can't be assigned to the parameter type 'ObstructingPreferredSizeWidget?'.

          )
        : Scaffold(
            .........,
                  ),
          );
  }
}

A: I faced the same issue, this is due to the null safety feature of Dart
Solution
final dynamic appBar = Platform.isIOS
    ? CupertinoNavigationBar() : AppBar()

Or you can use
final PreferredSizedWidget appBar = Platform.isIOS
        ? CupertinoNavigationBar() as ObstructingPreferredSizedWidget : AppBar()

A: Your code works in non-null safe versions of Flutter. I do not know why the null safe version now objects to:
final PreferredSizeWidget appbar = Platform.isIOS ...

If you omit the type:
final appbar = Platform.isIOS ...

Then appbar is interpreted as a Widget and gives an error on appbar.preferredSize.
You can force the type to be examined at runtime:
final dynamic appbar = Platform.isIOS ...

This works for me testing with my Android device. However, I have not tested with an Apple device.
I created this flutter issue for the change in behaviour with the null-safe version of flutter. You can subscribe to the issue to get update notifications.
Edit:
The Flutter team raised a Dart issue which explains the new bahaviour and suggests using:
final PreferredSizeWidget appbar = (Platform.isIOS ? CupertinoNavigationBar() : AppBar())
                                   as PreferredSizeWidget;

A: the issue is , appBar accept widget that implements PreferredSize
and CupertinoPageScaffold accept widget the implements  ObstructingPreferredSizeWidget
so don't determine the datatype of the appbar
and let it be determine at the runtime
simply  make it like this
final appBar = Platform.IOS ?  CupertinoNavigationBar() : AppBar()
and add the CupertinoNavigationBar in CupertinoPageScaffold
and add the AppBar in Scaffold


text:
Q: Why can't cabal haddock find lens? I've got a project where I'm trying out the lens library.  I'm trying to generate haddock docs so I can see the functions produced by the makeClassy TemplateHaskell function. cabal build works fine, but cabal haddock fails with
$ cabal haddock
Running Haddock for myproject-0.0.1...
Warning: The documentation for the following packages are not installed. No
links will be generated to these packages: rts-1.0
Preprocessing library myproject-0.0.1...
<command line>: cannot satisfy -package-id lens-3.7.1-a40583cdc124338f52ab40ebbf747e8f
    (use -v for more information)

What am I missing?


text:
Q: set image as a background of a sibling element my goal is to let the user to choose the background, but my js doesn;t work.

The images div is dynamic and should always change the image of the .step just before.
here is my buggy js:
$(document).on('click', '#images img', function(){
  var src = $(this).data('src');
  $(this).before().find('.step').css("background" , "url("+src+")");
});

A: I think what you are selecting is wrong and before() appends elements.
$(this).parent().prev('.step').css("background" , "url("+src+")");

basic explanation
$(this)  //the image
    .parent()  // the div #images
        .prev('.step')  //get the previous sibling with the class step
            .css("background" , "url("+src+")");

If you want all of the .step elements, you would use .siblings(".step") instead of .prev(".step")

A: I think you want prev(), not before()

A: The .before() method inserts content, it doesn't find an earlier element. You want the .prev() method, noting that it finds the previous sibling so you need to traverse via the .parent():
$(this).parent().prev().css("background" , "url("+src+")");

Demo: http://jsfiddle.net/DBRkS/
Note that .prev() doesn't search backwards until it finds a matching element, it selects the immediately preceding sibling if it matches the selector you supply, otherwise it returns nothing. So for the html you've shown it would work the same with or without the ".step" selector.

A: $(this).parent() will give you the div which holds the images & .prev('.step') gives you the previous element with class step. before() is only used to insert before each element in the set of matched elements.
$(this).parent().prev('.step').css("background" , "url("+src+")");


text:
Q: Using Django validators with admin - TypeError: "object of type 'int' has no len()" so I have an eCommerce customer-facing app with a Django Admin interface. I want employees who will be using the admin to be able to create users. The problem is the custom regex validation I built in applies to the customer-facing side only, and when an employee wants to create a new user using the admin, my use of Django Validators throws an error when attempting to create the user.
I was wondering if (1) there was a way to reuse my UserManager class (inherited from models.Manager) which handles the customer-side validation, with Django admin also. If not, then (2) if I was to rely on Django Validators how could I clean up the code as to not throw errors like:
TypeError: "object of type 'int' has no len()

I've done a little homework trying to figure this out and found this thread: TypeError: object of type 'int' has no len() error assistance needed
This basically explains the error being thrown for this example is because it's trying to call len() on an int instead of a list. What I don't get is why don't I get this same error on the customer-facing side when a user signs himself up?
At any rate, I can't figure out how to implement the solution given how I set up my UserManager. I'm not using Django Forms and have tried fooling around with some of the clean methods, but am also trying not to repeat myself by reusing the validation I already wrote in the UserManager.
Here is my code, thanks for any help!
models.py
class UserManager(models.Manager):
    def validation(self, postData, error_validation):
    errors = {}
    if error_validation == 'register':
        if not NAME_REGEX.match(postData['first_name']):
            errors['first_name'] = "First name can only contain letters."
        if not NAME_REGEX.match(postData['last_name']):
            errors['last_name'] = "Last name can only contain letters."
        elif User.objects.filter(email=postData['email']):
            errors['email'] = "Email already being used."
        elif len(postData['password']) < 8:
            errors['password'] = "Password must contain 8 or more characters."
        elif not postData['password'] == postData['confirm_password']:
            errors['password'] = "Both passwords must match!"
    if error_validation == 'login':
        user = User.objects.filter(email=postData['email'])
        if not user or not bcrypt.checkpw(postData['password'].encode(), user[0].password.encode()):
            errors['user_login'] = "Invalid credentials."
    return errors

class User(models.Model):
    first_name      = models.CharField(max_length=50)
    last_name       = models.CharField(max_length=50)
    dob             = models.DateField()
    address         = models.CharField(max_length=100)
    city            = models.CharField(max_length=35)
    state           = models.CharField(max_length=2)
    zipcode         = models.IntegerField(validators=[MinLengthValidator(5), MaxLengthValidator(10)])
    phone           = models.IntegerField(validators=[MinLengthValidator(10), MaxLengthValidator(10)])
    email           = models.CharField(max_length=65)
    password        = models.CharField(max_length=255)
    created_at      = models.DateField(auto_now_add=True)
    updated_at      = models.DateField(auto_now=True)
    objects         = UserManager()
    def __str__(self):
        return self.email

A: You are using MinLengthValidator and MaxLengthValidator on the IntegerFields, which will try to apply len() function on the integers. That's why you got this kind of error. You can change your zipcode and phone attributes to CharField, or just remove the validators.

A: One thing to note is that CharField doesn't have a min_length attribute.
So just as an ill-advised alternative, instead of using Min/MaxLengthValidator, you can use Min/MaxValueValidator Min/MaxValueValidator. What's cool is you can subclass the validators to handle custom error messaging:
models.py
from django.core.validators import MinValueValidator, MaxValueValidator

class ZipcodeMaxValueValidator(MaxValueValidator):
    message = ("AWWW YEA ERROR!!")

class User(models.Model):
    zipcode = models.IntegerField(validators=[MinValueValidator(99999), ZipcodeMaxValueValidator(99999)]


text:
Q: Cannot instantiate cyclic dependency after adding a Error Handler in Angular 5 A JavaScript error while trying to create a custom Error Handler for Angular 5 in order to handle the error received from Java.
For that I followed this tutorial :
https://itnext.io/how-to-handle-your-run-time-errors-in-your-angular-application-8d72fefbf8a4
However I receive this error :
Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule App.module in ./AppModule@-1:-1

Here is app.module.ts :
   import {ErrorHandler, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {FooterComponent, LayoutModule, MainComponent, NavbarComponent} from './layout/index';
import {HomeModule} from './home/home.module';
import {HttpClient, HttpClientModule} from '@angular/common/http';
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {KblEventManager} from './service/event-manager.service';
import {
  AddActionModule,
  KBL_BASEURL,
  KblHttpInterceptorModule,
  KblSpinnerComponent,
  KblSpinnerModule
} from '@kbl/components';
import {SlideinModule} from './slidein/slidein.module';
import {RouterModule} from '@angular/router';
import {APP_ROUTES} from './app.route';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {SharedModule} from './shared/shared.module';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {environment} from '../environments/environment';
import {HttpSpinnerComponent} from './layout/spinner/http-spinner.component';
import {AuthenticationService} from './model/authenticationService';
import {LoginService} from './login.service';
import {AppErrorHandlerService} from './app-error-handler.service';
import {RecommendationTableModule} from './recommendation-table/recommendation-table.module';
import {ReportingModule} from './reporting/reporting.module';
import {ReportModule} from './add-recommendation/report.module';
import {FollowUpModule} from './update-recommendation-dialog/follow-up.module';
import {MatSharedModule} from './shared/mat-shared.module';

const APP_BASE_URL

  = {provide: KBL_BASEURL, multi: true, useValue: environment.BASE_URL};

const APP_ERROR_HANDLER

  = {provide: ErrorHandler, useClass: AppErrorHandlerService};

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

/*export function bootstrap(authentificationService: AuthenticationService): () => Promise<any> {
  return (): Promise<any> => {
    return authentificationService.initApp().toPromise();
  };
}*/

@NgModule({
  imports: [
    BrowserModule,
    LayoutModule,
    FormsModule,
    BrowserAnimationsModule,
    HomeModule,
    ReportingModule,
    ReportModule,
    FollowUpModule,
    RecommendationTableModule,
    RouterModule.forRoot(APP_ROUTES, {useHash: true}),
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      }
    }),
    AddActionModule,
    SlideinModule,
    HttpClientModule,
    SharedModule,
    MatSharedModule,
    NgbModule,
    KblHttpInterceptorModule.forRoot(),
  ],

  declarations: [
    MainComponent,
    FooterComponent,
    NavbarComponent,
    // ManualAuthenticationDialogComponent,
    HttpSpinnerComponent,
  ],
  entryComponents: [
    KblSpinnerComponent,
  ],
  providers: [
    APP_ERROR_HANDLER,
    KblEventManager,
    APP_BASE_URL,
    AuthenticationService,
    LoginService],
  bootstrap: [MainComponent]
})
export class AppModule {
}

I received this error only after adding the ErrorHandler class and if I remove that from the provider it works fine but without exception handler.
Here is my error stack :
[Error] Error: Provider parse errors:
Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
    parse (compiler.js:19771)
    compile (compiler.js:20360)
    _compileModule (compiler.js:34658)
    compileModuleAsync (compiler.js:34481)
    bootstrapModule (core.js:5783)
    Codice Eval
    eval
    ../../../../../src/main/webapp/app/main.ts (main.bundle.js:281)
    __webpack_require__ (inline.bundle.js:55)
    (funzione anonima) (main.bundle.js:549)
    __webpack_require__ (inline.bundle.js:55)
    webpackJsonpCallback (inline.bundle.js:26)
    Codice globale (main.bundle.js:1)

Here is the AppErrorHandler.ts :
    import {ErrorHandler, Injectable} from '@angular/core';
import {BAD_REQUEST, FORBIDDEN, UNAUTHORIZED} from 'http-status-codes';
import {Router} from '@angular/router';
import {Toast, ToastsManager} from 'ng2-toastr';

@Injectable()
export class AppErrorHandlerService implements ErrorHandler {

  static readonly REFRESH_PAGE_ON_TOAST_CLICK_MESSAGE: string = 'An error occurred: Please click this message to refresh';
  static readonly DEFAULT_ERROR_TITLE: string = 'Something went wrong';

  constructor(private router: Router, private toastManager: ToastsManager) { }

  public handleError(error: any) {
    console.error(error);
    let httpErrorCode = error.httpErrorCode;
    switch (httpErrorCode) {
      case UNAUTHORIZED:
        this.router.navigateByUrl('/login');
        break;
      case FORBIDDEN:
        this.router.navigateByUrl('/unauthorized');
        break;
      case BAD_REQUEST:
        this.showError(error.message);
        break;
      default:
        this.showError(AppErrorHandlerService.REFRESH_PAGE_ON_TOAST_CLICK_MESSAGE);
    }
  }

  private showError(message: string) {
    this.toastManager.error(message, AppErrorHandlerService.DEFAULT_ERROR_TITLE, { dismiss: 'controlled'}).then((toast: Toast) => {
      let currentToastId: number = toast.id;
      this.toastManager.onClickToast().subscribe(clickedToast => {
        if (clickedToast.id === currentToastId) {
          this.toastManager.dismissToast(toast);
          window.location.reload();
        }
      });
    });
  }

}


text:
Q: .net: When i update the assembly version, it said: Could not load file or assembly. A strongly-named assembly is required I have a assembly with C# code. And the version of this assembly is 1.0.0.0. This Assembly's information is serialized when i serialize the data of this assembly into binary. And then i update this assembly version into 4.0.0.0, **

and i remove the signature

**. When i de-serialize the data of assembly, an exception occur, which is "Could not load file or assembly '[AssemblyName], Version=1.0.0.0, Culture=neutral, PublicKeyToken=[TokenKey]' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)".
How can i redirect my old version assembly to a new version assembly?
Does configuration assembly binding work?

A: In your config, add the following block ,
    <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="yourAssembly" publicKeyToken="PKTokenOfYourAssembly"/>
    <bindingRedirect oldVersion="1.0.0.0" newVersion="4.0.0.0"/>
  </dependentAssembly>
</assemblyBinding>


text:
Q: Get ID value from ListView in another class I am a novice programmer, I wrote some code. I want get wallet_id in another class, but when I try this variable always have value = 0. In class ChooseWallet wallet_id sets value wallet_id well. But I don't know how get wallet_id in another class. Any idea?
public class ChooseWallet extends AppCompatActivity {
public int wallet_id;
DatabaseDEO db = new DatabaseDEO(this);
ListView choose;
private SimpleCursorAdapter adapter;
final String[] from = new String[] {Wallets.COLUMNS.name,Wallets.COLUMNS.surname};
final int[] to = new int[] {R.id.name, R.id.surname };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_choose_wallet);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    choose = (ListView)findViewById(R.id.listselement);
    choose.setEmptyView(findViewById(R.id.null));
    Cursor cursor = db.fetch();
    adapter = new SimpleCursorAdapter(this, R.layout.activity_see_record, cursor, from, to, 0);
    adapter.notifyDataSetChanged();

    choose.setAdapter(adapter);

        choose.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        walllet_id = position+1;
    }
});

}}

A: In my opinion this is impossible. Spinner was better solutions than ListView.

A: maybe you can try to use setOnItemClickListener .
like this:
    choose.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            walllet_id = position+1;
        }
    });


text:
Q: Null pointer exception failure. Expects bitmap if not should load default pic I'm trying to learn Android, and I decided to try a simple game with andengine.  The idea is that in the main menu you can take a pic, load a pic from external, or just use the default.  I can load the game just fine when it recieves a bitmap.  But the way I'm checking to see if the pic is present so it can decide to load the default pic must be wrong.  Looking to you guys for some help.  Thanks in advance.  Here is the chunk of code that sends the intent.
         Intent launchIntent = new Intent(GameActivity.this, Game.class);
     startActivity(launchIntent);

Here is the code that gets the intent
public class Game extends SimpleBaseGameActivity {
private static int CAMERA_WIDTH = 800;
private static int CAMERA_HEIGHT = 480;
private ITextureRegion mBackgroundTextureRegion, mTowerTextureRegion, mRing1, mRing2, mRing3;
private Sprite mTower1, mTower2, mTower3;
private Stack mStack1, mStack2, mStack3;

@Override
public EngineOptions onCreateEngineOptions() {
    final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
    return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
}

@Override
protected void onCreateResources() {
    try {
        // 1 - Set up bitmap textures
        ITexture backgroundTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
            Bitmap bitmap = (Bitmap)getIntent().getParcelableExtra("BitmapImage");
            @Override
            public InputStream open() throws IOException {
                if (bitmap != null) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(CompressFormat.PNG, 100, stream);
                    InputStream is = new ByteArrayInputStream(stream.toByteArray());
                    return is;
                }
                else {
                    return getAssets().open("gfx/tower.png");
                }
            }
        });

I'm fairly certain the problem is here somewhere in OnCreateResources.  Thanks again!
Also, if it makes a difference (I seriously doubt it).  The intent are launched via onClick= in the manifest
logcat:
08-01 02:25:41.933: E/AndroidRuntime(825): FATAL EXCEPTION: main
08-01 02:25:41.933: E/AndroidRuntime(825): java.lang.NullPointerException
08-01 02:25:41.933: E/AndroidRuntime(825):  at org.andengine.ui.activity.BaseGameActivity.onResumeGame(BaseGameActivity.java:222)
08-01 02:25:41.933: E/AndroidRuntime(825):  at org.andengine.ui.activity.BaseGameActivity$4.run(BaseGameActivity.java:373)
08-01 02:25:41.933: E/AndroidRuntime(825):  at android.os.Handler.handleCallback(Handler.java:725)
08-01 02:25:41.933: E/AndroidRuntime(825):  at android.os.Handler.dispatchMessage(Handler.java:92)
08-01 02:25:41.933: E/AndroidRuntime(825):  at android.os.Looper.loop(Looper.java:137)
08-01 02:25:41.933: E/AndroidRuntime(825):  at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 02:25:41.933: E/AndroidRuntime(825):  at java.lang.reflect.Method.invokeNative(Native Method)
08-01 02:25:41.933: E/AndroidRuntime(825):  at java.lang.reflect.Method.invoke(Method.java:511)
08-01 02:25:41.933: E/AndroidRuntime(825):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 02:25:41.933: E/AndroidRuntime(825):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 02:25:41.933: E/AndroidRuntime(825):  at dalvik.system.NativeStart.main(Native Method)


text:
Q: Is there a way to force the client to match me with people from North America? I am temporarily visiting a South American country. When I play Overwatch, I keep getting matched with, well, people from South America, which makes sense.
... Unfortunately I can't understand whatever they're saying, so that makes teamwork a bit difficult and I'm essentially muting everybody every time I play.
Is there a way to force the client to match me with people from North America? The Blizzard launcher generalizes it too much to just "Americas".

A: In the upcoming social features update, the "Looking for Group" feature is being added, which let's you create a group based on certain criteria. With this, you can specify that you're looking to play with people with voicechat who also speak English.


text:
Q: Format JSON with Google protobuf With this code:
var button = Value.ForStruct(new Struct{
    Fields={
        ["type"] = Value.ForString("postback"),
        ["title"] = Value.ForString("Call Representative"),
        ["payload"] =  Value.ForString("+15105551234"),
    }
});

var inPayload = Value.ForStruct(new Struct{
    Fields ={
        ["buttons"] = Value.ForList(button),
        ["text"] = Value.ForString("try the postback"),
        ["template_type"] = Value.ForString("button"),
    }
});

var attachment = Value.ForStruct(new Struct{
    Fields ={
        ["payload"] = inPayload,
        ["type"] = Value.ForString("template"),
    }
});

var msg = Value.ForStruct(new Struct{
    Fields ={
        ["attachment"] = attachment,
    });

Payload = new Struct{
    Fields ={
        ["facebook"] = msg
    }

I was able to create the following json:
"payload":    {
      "facebook": {"attachment":       {
         "payload":          {
            "buttons": [            {
               "type": "postback",
               "title": "Call Representative",
               "payload": "+15105551234"
            }],
            "text": "try the postback",
            "template_type": "button"
         },
         "type": "template"
      }}

Now I need to create the following other format but I dont find how to do it:
"payload":    {
         "message": "Yes I did it"
         "platform": "kommunicate",
         "attachment":       {
             "payload":          {
                "buttons": [            {
                   "type": "postback",
                   "title": "Call Representative",
                   "payload": "+15105551234"
                }],
                "text": "try the postback",
                "template_type": "button"
             },
             "type": "template"
          }

I really dont find how to eliminate the first "facebook": { element and leave only:
  {
    "message": "Yes I did it",
    "platform": "kommunicate",
    "attachment":

And include message and platform at the same level.  Here is the complete json I will like to generate:
"payload":    {
   "platform": "kommunicate",
   "message": "Yes I did it",
   "attachment":       {
         "payload":          {
            "buttons": [            {
               "type": "postback",
               "title": "Call Representative",
               "payload": "+15105551234"
            }],
            "text": "try the postbackggggggg",
            "template_type": "button"
         },
         "type": "template"
      }

A: If you want to take an object and convert it to json I would recommend taking a look at Newtonsoft Json.Net library. They have plenty of examples that might help you. There is also protobuf.net library for serializing to protobuf instead of json.
Both libraries are used in similar ways, you create a class with appropriate properties and set the values you want. You will need multiple classes for nested types as in your example. Protobuf requires you to annotate the properties with attributes, while this is optional for json.net. You then send the object to the serialization library and get a string or binary data representing your object. This kind of object is often called a Data Transfer Object (DTO), since the only purpose it has is to aid in serialization or/and transfering the data to another system.


text:
Q: For $\sqrt[3]{-1+i}$, is $r$ (when put in polar form) $\sqrt[6]{2}$? And when you put that into the nth root form... It becomes $2^{1/18}\cos\theta + 2^{1/18}\sin\theta$?
$n$th root form given is: $\sqrt[n]r\cdot\cos(\theta+2\pi k)n$

A: Think of $-1 + i = r e^{i \theta}$ geometrically as the point $(-1,1)$ so it has length $r = \sqrt{2}$.
So the cube root of it has length $\sqrt[3]{r} = \sqrt[3]{\sqrt{2}} = \sqrt[6]{2}$.

A: $(1+i)^\frac{1}{3} = (|1+i| e^{i \arg (1+i)})^\frac{1}{3} = (\sqrt{2} e^{i \frac{\pi}{4}})^\frac{1}{3}$
The $3$rd roots are given by $(\sqrt{2} e^{i (\frac{\pi}{4}+2 \pi k)})^\frac{1}{3} = 2^{\frac{1}{6} }e^{i (\frac{\pi}{12}+ \frac{2\pi k}{3})} = 2^{\frac{1}{6} }(\cos (\frac{\pi(1+8k)}{12}) + i \sin \frac{\pi(1+8k)}{12})$, for $k=0,1,2$.

A: The easiest if you know the exponential function: $e^{x+iy}=e^x(\cos y+i\sin y)$.
Then, if you drawn in coordinate system, you will find the angle $\vartheta$ of $-1+i$. Then,
$$-1+i= \sqrt2\cdot e^{\theta i} $$
this makes easier the power to $1/3$. Don't forget that you will have 3 solutions, as $e^{4\pi i}=e^{2\pi i}=1$ but their thirds are different.

A: You have $\theta = \frac{3\pi}{4}$ and $r=\sqrt{2}$, and using the fact that $e^{i2k\pi}=1$, then
$$ z^3 = (-1+i) = \sqrt{2}\,e^{i\frac{3\pi}{4}}= \sqrt{2}\,e^{i\frac{3\pi}{4}}e^{i2k\pi}=\sqrt{2}e^{i\frac{3\pi}{4}+i2k\pi} $$
$$ \implies z = 2^{1/6}\,e^{\frac{i\pi}{4}+\frac{i2k\pi}{3}} \,. $$
Now, taking $k=0,1,2$ gives the three roots. Note that, if you take $k>2$ you will get the same roots.


text:
Q: Is the word "Shinobi" an accepted English word? I've been wondering if the word "Shinobi" is an accepted English word. As far as I know, its synonym "Ninja" is an accepted English word where "Spy" is the nearest common English.

A: Depends on the audience. For a general audience, it seems shinobi would not be understood.
Wikipedia has a list of English words of Japanese origin, and shinobi is not on that list, not that educated native speakers would be expected to know all those words, however.
http://en.wikipedia.org/wiki/List_of_English_words_of_Japanese_origin
Some native speakers of English who are pretty fluent in Japanese (such as myself) don't even know the word shinobi. Just don't read much about ninjas, I guess.
However, in the context of ninjas, shinobi does seems to be understood. Here is a book title at Amazon that uses the term:
The Secret Traditions of the Shinobi: Hattori Hanzo's Shinobi Hiden and Other Ninja Scrolls


text:
Q: What is wrong with this bash scripting syntax for adding an element to an array? A simple shell script used for creating some system reporting contains the code
ARRAY=$(awk -F ':' '$3>=1000 && $3<60000 {print $1}' /etc/passwd)
ARRAY+=('root')

The array's declaration in the first line doesn't produce any error output, but for the second line I get an error message saying: Syntax error: word unexpected (expecting ")")
What is wrong with this code?

A: The problem, from your screenshot, is that you are not running it as a bash script.  You're doing sh testscript which executes it with the sh shell, which is not bash.  Make the changes that @Cyrus recommended and either make the script executable so you use the shebang line and do ./testscript or use bash to run it bash testscript
Also, set +x turns off tracing/debugging so when you're hitting unexpected problems you'd be better using set -x to turn it on for the block in question.
I demonstrated the problem for myself as follows:
$ cat testscript
ARRAY=$(awk -F ':' '$3>=1000 && $3<60000 {print $1}' /etc/passwd)
ARRAY+=('root')
$ sh testscript
testscript: 2: testscript: Syntax error: word unexpected (expecting ")"
$ bash testscript
$


text:
Q: Express angular position of the Earth as a function of time Say I have for example the Earth orbiting the Sun (in circular orbit) and I want to express angular position (in radians) as a function of time.
Would I be correct in thinking that $2\pi/t$ does the trick?

A: The usual representation is
$$\theta = \frac{2 \pi t}{T}$$ where $T$ is the period (one year).

A: I would think you need to throw in the period.  Like $\frac{2\pi\times t}{365 \text{ days}}$ where t is in days.

A: In circular motion constant angular velocity
$$ \omega = \dfrac{d \theta}{d t} $$
If it is constant, integrate to obtain $\theta = \omega \,t $ for given time less than one period.
For a full rotation around Sun
$$\theta_{max} = \omega \,T $$ where $T$ is for one full time period, 1 year in this case.


text:
Q: Modify vertices in a THREE.BufferGeometry object I need to selectively show/hide 1000+ lines of different sizes, positions and colors.
My first attempt made a THREE.Geometry with a name for each. To hide/show I iterate over scene and hide/show on each based on name and my heuristic. That seemed very slow - around 50Hz for ~1000 lines.
I made a test using a similar approach but using only a single THREE.Geometry to hold all of the lines. That was much faster but of course but I can only apply one material to all the lines which is no good. I was able to set the right flags and update the positions of the lines while the app was running though.
The best approach seems to be to use THREE.BufferGeometry. I made a test which was very fast and worked as expected for the initial set up but I was unable to change the position/visibility and color of each line afterwards. I made a JS fiddle that illustrates it - http://jsfiddle.net/SSnKk/ - but calling buffer_geometry.dynamic = true; and buffer_geometry.verticesNeedUpdate = true; didn't appear to help.

A: If you update the contents of the attribute buffers, you need to set the needsUpdate flag. For example:
buffer_geometry.attributes.position.needsUpdate = true;

buffer_geometry.attributes.color.needsUpdate = true;

three.js r.143


text:
Q: Optimizing business-day check (R) My goal is to take a startdate observation from a data frame, compare it against a calendar, and if the date is not a business date (holiday or weekend), move push it back until it becomes a valid business day. I will do the same for enddate, but pushing it forward.
As an example, this is what my data looks like:
  tickers  startDate    endDate
1   GOOGL 2016-01-31 2016-02-02
2   GOOGL 2015-10-21 2015-10-23
3   GOOGL 2015-07-15 2015-07-17
4   GOOGL 2015-04-22 2015-04-24
5   GOOGL 2015-01-28 2015-01-30
6   GOOGL 2014-10-15 2014-10-17

And my calendar information:
        Date   Weekday Business         Event
1 2001-01-01    Monday    FALSE New Years Day
2 2001-01-02   Tuesday     TRUE          <NA>
3 2001-01-03 Wednesday     TRUE          <NA>
4 2001-01-04  Thursday     TRUE          <NA>
5 2001-01-05    Friday     TRUE          <NA>
6 2001-01-06  Saturday    FALSE          <NA>

So I'm achieving this the following way, with dplyr:
for(i in 1:10){
stocks1 <- stocks1 %>%
  mutate(startDate = as.Date(ifelse(startDate %in% dates[dates$Business==F,]$Date, startDate - 1, startDate))) %>%
  mutate(endDate = as.Date(ifelse(endDate %in% dates[dates$Business==F,]$Date, endDate + 1, endDate)))
}

I guess there must be a more elegant way to do this... Any ideas? Ideally with dplyr since I'm trying to master this package :)
Thanks!

A: The chron package has some delightful functions called is.weekend and is.holiday which are very helpful here. As for optimization, this actually seems like the rare case where a while loop actually seems merited in R. You'll still need two, unless you want to do it very programmatically.
One caveat: is.holiday requires a list of holidays (by default it uses six American ones from 1992). We can just use the dates from the second data.frame where Business == FALSE, which may include weekends, but that's fine. Really, with this approach you could skip is.weekend entirely, if your weekend data is already good. In this case, the dates for the two don't align, so it's not terribly useful. Regardless, the approach will work with the right data. All together, where df1 and df2 are your first and second data.frames, respectively:
library(chron)
# make a vector of holidays in chron's dates form for is.holiday
holidays <- chron(dates. = as.character(df2$Date), format = 'y-m-d')
while(sum(is.weekend(df1$startDate) | is.holiday(df1$startDate, holidays)) > 0){
  indices <- is.weekend(df1$startDate) | is.holiday(df1$startDate, holidays)
  df1$startDate[indices] <- df1$startDate[indices] - 1
}
while(sum(is.weekend(df1$endDate) | is.holiday(df1$endDate, holidays)) > 0){
  indices <- is.weekend(df1$endDate) | is.holiday(df1$endDate, holidays)
  df1$endDate[indices] <- df1$endDate[indices] + 1
}

Alternately, you could build your own function with or without chron. base has a weekday function that does half the work, anyway. Wrapped in a function, you can easily chuck a function inside of dplyr's mutate/transmute, so it will fit neatly into your chains.

Data:
df1 <- structure(list(tickers = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "GOOGL", class = "factor"),
    startDate = structure(c(16831, 16729, 16631, 16547, 16463,
    16358), class = "Date"), endDate = structure(c(16833, 16731,
    16633, 16549, 16465, 16360), class = "Date")), .Names = c("tickers",
    "startDate", "endDate"), row.names = c(NA, -6L), class = "data.frame")

df2 <- structure(list(Date = structure(c(11323, 11324, 11325, 11326,
    11327, 11328), class = "Date"), Weekday = structure(c(2L, 5L,
    6L, 4L, 1L, 3L), .Label = c("Friday", "Monday", "Saturday", "Thursday",
    "Tuesday", "Wednesday"), class = "factor"), Business = c(FALSE,
    TRUE, TRUE, TRUE, TRUE, FALSE), Event = structure(c(2L, 1L, 1L,
    1L, 1L, 1L), .Label = c("<NA>", "New_Years_Day"), class = "factor")), .Names = c("Date",
    "Weekday", "Business", "Event"), row.names = c(NA, -6L), class = "data.frame")


text:
Q: Jersey+grizzly2 standalone server JSON parse error Code what i have now in my little project:
Main class:
package main;

import com.sun.jersey.api.container.grizzly2.GrizzlyWebContainerFactory;
import org.glassfish.grizzly.http.server.HttpServer;
import utils.text.Messages;
import utils.text.Props;

import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class Main {

    public static URI BASE_URI;

    private static void getBaseURI(int port) {
        BASE_URI = UriBuilder.fromUri(Props.BASE_URL).port(getPort(port)).build();
    }

    private static int getPort(int defaultPort) {
        String port = System.getProperty(Props.JERSEY_TEST_PORT);
        if (null != port) {
            try {
                return Integer.parseInt(port);
            } catch (NumberFormatException e) {
            }
        }
        return defaultPort;
    }

    protected static HttpServer startServer() throws IOException {
        final Map<String, String> initParams = new HashMap<String, String>();
        initParams.put("com.sun.jersey.config.property.packages", "rest");
        initParams.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
        return GrizzlyWebContainerFactory.create(BASE_URI, initParams);
    }

    public static void main(String[] args) throws IOException, java.text.ParseException {

                getBaseURI(11111);
                final HttpServer httpServer = startServer();
                System.out.println(Messages.STARTING_GRIZZLY + BASE_URI);
                System.in.read();
                httpServer.stop();
    }
}

pom.xml:
 <dependencies>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-grizzly2</artifactId>
        <version>1.9.1</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.9.1</version>
    </dependency>

</dependencies>

Resource class:
import utils.text.RestResources;
import utils.text.RestResponse;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path(RestResources.MAIN_REST_PATH)
public class ClientDisconnectRest {

    @POST
    @Path("/client_disconnect")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createTrackInJSON(LoginData cld) {
        try {
            return Response.status(200).entity(RestResponse.OK).build();
        } catch (Exception e) {
            return Response.status(400).entity(RestResponse.ERROR).build();
        }

    }
}

LoginData entity class:
import javax.ws.rs.QueryParam;

public final  class LoginData {

    private  String login;
    private  String password;

    public LoginData(
            @QueryParam("login") final String login,
            @QueryParam("password") final String password) {

       // require(login != null, "login", login);
       // require(password != null, "password", password);

        this.login = login;
        this.password = password;
    }

    public String getLogin() {
        return login;
    }

    public String getPassword() {
        return password;
    }

Then Im starting server and trying to send POST request via PostaMan, please see this link
Exception log: at pastebin
Amigos can you please help me? or maybe someone has any ideas? Thank you.

A: I have send incorrect JSON, so I change it and all works


text:
Q: Moving div under another when navigation changes on screen resize I want my main-content div to move under my navigation bar which reforms into a horizontal navigation bar on screen resize.
I assumed something simple like this would work:
@media screen and (max-width: 540px) {
    #main-content{
    display:block;
    width:100%;
    }
}

But both divs are displayed side by side. How can I get my main-content to shift under my navigation bar as soon as it becomes a horizontal bar?
Here is my current approach demonstrating the issue:

.site-wrapper {
  height: 100%;
  min-height: 100%;
  display: flex;
}

/* NAVIGATION */

.nav-container {
  border-right: 1px solid #E4E2E2;
  height: 100%;
  width: 200px;
  background-color: #f4f3f3;
}

.logo-holder {
  text-align: center;
}

.nav {
  text-align: justify;
}

.nav-link {
  display: block;
  text-align: left;
  color: #333;
  text-decoration: none;
  margin-left: 0px;
  padding-left: 15px;
}

.nav-link:hover {
  background-color: #333;
  color: #f4f3f3;
}

.nav ul {
  width: 100%;
  padding: 0px;
}

.nav ul li {
  margin-left: 5px;
  list-style-type: none;
  height: 25px;
}

.nav ul li a {
  text-align: left;
  padding: 5px;
  color: #333;
  text-decoration: none;
  margin-left: 15px;
}

.nav li:hover a {
  color: #f4f3f3;
}

/* MAIN CONTENT */

#main-content {
  float: left;
  margin: 10px;
  border: 1px solid black;
  width: 80%;
  height: 500px;
}

@media screen and (max-width: 540px) {
  #main-content {
    display: block;
    width: 100%;
  }
}

.reg-div {
  border: 1px solid red;
  width: 80%;
}

.reg-div ul li {
  list-style: none;
  text-decoration: none;
  color: #333;
}

/* MEDIA QUERIES */

@media screen and (max-width: 540px) {
  .nav-container {
    width: 100%;
    height: 100px;
    background-color: #f4f3f3;
    border-bottom: 0.5px solid #f4f3f3;
  }
  .nav-link {
    padding: 10px;
  }
  .logo-holder {
    overflow: hidden;
    display: block;
    width: 40%;
  }
  .nav-container nav ul {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
  }
  .logo-holder {
    text-align: left;
  }
  #navigation-div {
    background-color: #f4f3f3;
    margin-top: 0;
  }
}

test 1

test 2

test 3

Login | Sign Up

JS fiddle: https://jsfiddle.net/gtLhje4z/

A: Since you have set up your .site-wrapper to be a flexbox, add a media query for the wrapper as well to be flex-direction: column at max-width: 540px. By default, flexbox is set to be in a row.
Also, you don't need to float your '#main-content' since flexbox does all the work for you.

.site-wrapper {
  height: 100%;
  min-height: 100%;
  display: flex;
}

@media screen and (max-width: 540px) {
    .site-wrapper {
        flex-direction: column;
    }
}

/* NAVIGATION */

.nav-container {
  border-right: 1px solid #E4E2E2;
  height: 100%;
  width: 200px;
  background-color: #f4f3f3;
}

.logo-holder {
  text-align: center;
}

.nav {
  text-align: justify;
}

.nav-link {
  display: block;
  text-align: left;
  color: #333;
  text-decoration: none;
  margin-left: 0px;
  padding-left: 15px;
}

.nav-link:hover {
  background-color: #333;
  color: #f4f3f3;
}

.nav ul {
  width: 100%;
  padding: 0px;
}

.nav ul li {
  margin-left: 5px;
  list-style-type: none;
  height: 25px;
}

.nav ul li a {
  text-align: left;
  padding: 5px;
  color: #333;
  text-decoration: none;
  margin-left: 15px;
}

.nav li:hover a {
  color: #f4f3f3;
}

/* MAIN CONTENT */

#main-content {

  margin: 10px;
  border: 1px solid black;
  width: 80%;
  height: 500px;
}

@media screen and (max-width: 540px) {
  #main-content {
    display: block;
    width: 100%;
  }
}

.reg-div {
  border: 1px solid red;
  width: 80%;
}

.reg-div ul li {
  list-style: none;
  text-decoration: none;
  color: #333;
}

/* MEDIA QUERIES */

@media screen and (max-width: 540px) {
  .nav-container {
    width: 100%;
    height: 100px;
    background-color: #f4f3f3;
    border-bottom: 0.5px solid #f4f3f3;
  }
  .nav-link {
    padding: 10px;
  }
  .logo-holder {
    overflow: hidden;
    display: block;
    width: 40%;
  }
  .nav-container nav ul {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
  }
  .logo-holder {
    text-align: left;
  }
  #navigation-div {
    background-color: #f4f3f3;
    margin-top: 0;
  }
}

test 1

test 2

test 3

Login | Sign Up


text:
Q: Nullspace of a linear mapping from higher to lower dimension It is a well-known fact that a linear mapping $A: \mathbb{R}^n \to \mathbb{R}^m$ , where $m < n$, has a non-trivial null space. This follows from the "rank-nullity" theorem of linear algebra.
This result somewhat seems to intuitively true - something that "flattens" out the the space should send some elements to zero.
My first question is can this fact be proved (using analytical methods, for example) without introducing the notion of a basis and its dimension?
More generally, can this result be extended to "appropriate" non-linear mappings $f: \mathbb{R}^n \to \mathbb{R}^m$, where $m < n$ (of course, the term "null-space" would not make sense; we just ask for the existence of non-trivial zeros)?

A: *

*Sure. You write a matrix $M$ for the transformation (which arguably uses the notion of basis**, but...) and do row reduction to produce a matrix $M'$. Row-reduction doesn't change the kernel. But in the row-reduced matrix, pick column that does not contain the leading "1" in a row, say column $i$. (There has to be such a column because $m < n$). Then it's easy to construct a vector $v$ with a "1" in slot $i$ and perhaps some nonzero entries in other slots such that $M' v = 0$, showing the kernel's nontrivial. (The nonzero entries in $v$ are the negatives of the entries in column $i$ of $M'$, placed in the slots corresponding to columns of $M'$ that contain a leading $1$.)
** Well...not really. The columns of the matrix $M$ are just $T(e_i)$, where the $e_i$ are the vectors that are all 0 except for a 1 in slot $i$.

*For differentiable mappings, the inverse/implicit function theorems capture the behavior you're talking about, I believe.

A: Regarding your first question, there are certainly theorems ruling out the existence of such $f$ assuming $f$ is continuous or smooth or algebraic or whatever. (I'm thinking of proofs using (co)homological methods.) But I would expect that these proofs ultimately make use of linear mappings as a base case somewhere (especially when $f$ is assumed differentiable -- we then consider (linear) maps of tangent spaces).
Regarding your last question, rather than 'kernel' or 'nullspace' (set of elements $x$ such that $f(x) = 0$), one can consider, for general functions $f : X \to Y$, the fiber product
$$X \times_f X = \{(x_1,x_2) : f(x_1) = f(x_2)\} \subset X \times X.$$
If $f$ is injective, $X \times_f X \cong \Delta(X) \cong X$. Otherwise the fibers of $X \times_f X$ over $Y$ (by specifying $f(\_) = y$) describe the noninjectivity of $f$ piece-by-piece.
Anyway, the point is that you can still ask about (non-)injectivity, if your function is nonlinear. Of course, it's a theorem of topology that there is no continuous injection $f: \mathbb{R}^n \hookrightarrow \mathbb{R}^m$ with $n > m$, so $\mathbb{R}^n \times_f \mathbb{R}^n$ will have interesting fibers.


text:
Q: Call a method from another class in another application with FOSTRestBundle in Symfony I have the class file ex: Stats.php when i want to give an array with information from another method in another application and class file ex: Information.php.
File Stats.php
public function getStats()
{
 $myInformations = // here i want to get information from Information.php
 .
 .
 .
 return $myInformations;
}

In different application.
File Informations.php
/**
* Get all locales
* @FOS\View()
* @FOS\Get("/locales")
* @param ParamFetcherInterface $paramFetcher
* @return mixed
*/
public function getLocales(ParamFetcherInterface $paramFetcher)
{
  .
  .
  .
  return $locales;
}

How I call function getLocales from url: http://myhost.com/api/locales in function getStatus()?

A: When you are using the GuzzleBundle as mentioned in your comment. You can just inject a client into the class containing getStats() or by making it ContainerAware and retrieving the guzzle-client by its service id from the container. If you don't have to set default options for your client, i.e. you just want to access a url you assume is always available for all environments from all places you could just create a new client with default values:
$guzzleClient = new GuzzleHttp\Client();

Making a request with the client is described in the guzzle docs in the Quickstart in section Sending Requests:
$response = $guzzleClient->get('http://myhost.com/api/locales')

When the request was successful you can retrieve the locales by calling:
$content = $response->getBody()->getContent();

Either casting getBody() to string or using getContent() is important here. Again refer to Guzzle's documentation particularly the section on using responses.
For example if you send a json-encoded string you can do something like:
$encodedLocales = $response->getBody()->getContent();
$decodedLocales = json_decode($encodedLocales, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new \Exception(json_last_error_msg());
}

There are many things that should be said about this approach such as it's fragile because it relies on a working network connection possibly to a different server, it's not easily testable, transfer exceptions are not handled gracefully, etc. pp. but for a simple proof of concept or asa starting point this should suffice.


text:
Q: Using mplcursors.cursor().connect() display bar name
This is my data frame

df = pd.DataFrame((['Sep-2015',  'Adam',3,10 ],
['Sep-2015',  'David',3,9],
['Sep-2015',  'Adam',4,8],
['Sep-2015',  'Adam' ,3,7],
['Sep-2015',  'David',6,6],
['Sep-2015' , 'Hardik',1,5],
['Sep-2015' , 'David' ,3,4],['Aug-2015' , 'David' ,3,4],['Aug-2015' , 'Ada' ,3,4]),columns=
['Date','Name','Count','alarm'])

Using this data frame I have plotted a stacked bar graph

df.sort_values('Date')
df = df.drop_duplicates(['Date', 'Name'], keep='last')
df2 = pd.DataFrame()
df2['Date'] = df['Date']
df2['Name'] = df['Name']
df2['Count'] = df['alarm']
df2
#pivot table
df2 = pd.pivot_table(data = df, values = 'alarm', columns = 'Name', index = 'Date').reset_index()
df2 = df2.set_index('Date')
plot = df2.plot(kind = 'bar',stacked = True,figsize=(15, 5))

I got output as following

Here, I tried to display the bar name when clicked on a bar. I tried

mplcursors.cursor(plot).connect(
                    "add", lambda sel: sel.annotation.set_text(['Ada','Adam','David','Hardik'][sel.target.index]))

But when I try this it only displays the first element (Ada) for all bars.
How could I display the bar name?

A: This works:
mplcursors.cursor(plot).connect("add",
                                lambda sel: sel.annotation.set_text(sel.artist.get_label()))


text:
Q: checksum validation fro rsa encryption in openssl? Does rsa encryption method in OpenSSL provide some sort of checksum validation ?
Thank you,

A: I think your question might be better posted in crypto.stackexchange.com.
That said, the answer is...  sorta.  OpenSSL is PKCS#1 compliant and PKCS#1 padding doesn't utilize a checksum, persay, but the checksum does need to conform to certain criteria, which I'd say has the effect of a simple parity-bit style checksum.
OAEP padding actually uses cryptographic hashes within it that provide for more elaborate validation.


text:
Q: Do the linear transformation is the only transformation that invariant under change of basis? From https://en.wikipedia.org/wiki/Transformation_(function), there are linear transformation, affine transformation and so on.
It also mentions about translation, reflection, rotation, etc. I know which transformation is a linear or affine transformation. I think that the affine transformation is more general, I am not sure that the linear transformation is a specific case of the affine transformation (Kabo already answered this).
I just learn about the linear transformation as (1,1)tensor.
I understand that -form (one-form, bilinear and so on) can be viewed as linear transformation $V\times V\times...\rightarrow R$.
In conclusion, I know that linear transformation is invariant under change of basis and affine may or may not but I don't know that is there any other type of transformation that invariant under change of basis.
The other question is about the affine transformation.
Is the linear transformation is a subset of the affine transformation?


text:
Q: Link Navigation View Controller cell to a Web View I have a navigation controller with multiple cells. I want to link each of the cells to a webpage in a web view. However, I don't want to create another view controller for each cell. Is it possible to create 1 view controller and link all cells to the same view controller but make a different webpage show up in the web view for each cell? For example, there is cell 1 and cell 2. They both link to one view controller with a web view in the view controller. When you click cell 1, it brings you to the view controller and in the web view it brings you to http://example.com. When you click cell 2, it brings you to the same view controller as cell 1 but in the web view, it brings you to http://example.com/1. How can I do that?

A: Just declare a property in your viewcontroller which holds the URL you want to request.
@property (strong,nonatomic) NSString *url;

When you click on a cell assign the URL of the cell accordingly to the property of your viewcontroller
Your viewcontroller should look something like this.
Header
#import <UIKit/UIKit.h>

@interface RSViewController : UIViewController

@property (weak, nonatomic) NSString *url;

@end

Implementation
#import "RSViewController.h"

@interface RSViewController ()<UIWebViewDelegate>

@property (strong,nonatomic) IBOutlet UIWebView *webview;

@end

@implementation RSViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.webview.delegate = self;

    NSURLRequest *urlRequest = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:self.url]];
    [self.webview loadRequest:urlRequest];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"Did start loading");
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"Did finish loading");
}

@end

Now you just need a reference to your viewcontroller in your tableviewcontrollerand set the urlproperty on cell click.


text:
Q: Stream stateful computation: cumulative sums Assuming I have a Java IntStream, is it possible to convert it to an IntStream with cumulative sums? For example, a stream starting with [4, 2, 6, ...] should be converted to [4, 6, 12, ...].
More generally, how should one go about implementing stateful stream operations? It feels like this should be possible:
myIntStream.map(new Function<Integer, Integer> {
    int sum = 0;
    Integer apply(Integer value){
        return sum += value;
    }
);

With the obvious restriction that this works only on sequential streams. However, Stream.map explicitely requires a stateless map function. Am I right in missing a Stream.statefulMap or Stream.cumulative operation or is that missing the point of Java streams?
Compare for example to Haskell, where the scanl1 function solves exactly this example:
scanl1 (+) [1 2 3 4] = [1 3 6 10]

A: It's possible to do with a collector that then creates a new stream:
class Accumulator {
    public static void accept(List<Integer> list, Integer value) {
        list.add(value + (list.isEmpty() ? 0 : list.get(list.size() - 1)));
    }

    public static List<Integer> combine(List<Integer> list1, List<Integer> list2) {
        int total = list1.get(list1.size() - 1);
        list2.stream().map(n -> n + total).forEach(list1::add);
        return list1;
    }
}

This is used as:
myIntStream.parallel()
    .collect(ArrayList<Integer>::new, Accumulator::accept, Accumulator::combine)
    .stream();

Hopefully you can see that the important attribute of this collector is that even if the stream is parallel as the Accumulator instances are combined it adjusts the totals.
This is obviously not as efficient as a map operation because it collects the whole stream and then produces a new stream. But that's not just an implementation detail: it's a necessary function of the fact that streams are intended to be potentially concurrently processed.
I have tested it with IntStream.range(0, 10000).parallel() and it functions correctly.

A: You can do this with an atomic number. For example:
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

public class Accumulator {
    public static LongStream toCumulativeSumStream(IntStream ints){
        AtomicLong sum = new AtomicLong(0);
        return ints.sequential().mapToLong(sum::addAndGet);
    }

    public static void main(String[] args){
        LongStream sums = Accumulator.toCumulativeSumStream(IntStream.range(1, 5));
        sums.forEachOrdered(System.out::println);
    }
}

This outputs:
1
3
6
10

I've used a Long to store the sums, because it's entirely possible that two ints add up to well over Integer.MAX_VALUE, and a long has less of a chance of overflow.


text:
Q: How to get pixel color of an image without BufferedImage? I am making a maze game where your mouse can't touch a certain color. The problem I am having is getting the pixel color without using a BufferedImage. Are there any alternatives?

A: Not tested. Try to use Robot and PointerInfo declared as:
PointerInfo pointer = MouseInfo.getPointerInfo();
Point coord = pointer.getLocation();
Robot robot = new Robot();

And then to get a Color upon a Point:
Color color = robot.getPixelColor((int)coord.getX(), (int)coord.getY());


text:
Q: Задать CornerRadius как Attached Property для ComboBox Я смог сделать CornerRadius как Attached property для Button и TextBox с помощью класса
public class CornerRadiusSetter
{
    public static CornerRadius GetCornerRadius(DependencyObject obj) => (CornerRadius)obj.GetValue(CornerRadiusProperty);

    public static void SetCornerRadius(DependencyObject obj, CornerRadius value) => obj.SetValue(CornerRadiusProperty, value);

    public static readonly DependencyProperty CornerRadiusProperty =
        DependencyProperty.RegisterAttached(nameof(Border.CornerRadius), typeof(CornerRadius),
            typeof(CornerRadiusSetter), new UIPropertyMetadata(new CornerRadius(), CornerRadiusChangedCallback));

    public static void CornerRadiusChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
    {
        Control control = sender as Control;

        if (control == null) return;

        control.Loaded += Control_Loaded;
    }

    private static void Control_Loaded(object sender, EventArgs e)
    {
        Control control = sender as Control;

        if (control == null || control.Template == null) return;

        control.ApplyTemplate();

        Border border = control.Template.FindName("border", control) as Border;

        if (border == null) return;

        border.CornerRadius = GetCornerRadius(control);
    }
}

Это позволяет задать произвольный CornerRadius в XAML:
<TextBox local:CornerRadiusSetter.CornerRadius="5" />

<Button local:CornerRadiusSetter.CornerRadius="15">Button</Button>

Как сделать чтобы этот класс срабатывал ещё и для ComboBox?
После control.ApplyTemplate() добавлял такой код
Control toggleButton = control.Template.FindName("toggleButton", control) as Control;

if (toggleButton != null)
    SetCornerRadius(toggleButton, GetCornerRadius(control));

Border dropDownBorder = control.Template.FindName("DropDownBorder", control) as Border;

if (dropDownBorder != null)
    dropDownBorder.CornerRadius = GetCornerRadius(control);

Но ничего не менялось.

A: У меня на Windows 10 для ComboBox сработало следующее:
var toggleButton = control.Template.FindName("toggleButton", control) as ToggleButton;
var border = toggleButton.Template.FindName("templateRoot", toggleButton) as Border;
border.CornerRadius = GetCornerRadius(control);

т.е. вы просто ошиблись с именем элемента в шаблоне (запутались в стилях?)

A: Для ComboBox надо немноого добавить существующий метод обработки загрузки и добавить различные улучшения для стилей самого выпадающего списка, чтобы у него не было торчащих углов.
public static class CornerRadiusSetter
{
    public static CornerRadius GetCornerRadius(DependencyObject obj) => (CornerRadius)obj.GetValue(CornerRadiusProperty);

    public static void SetCornerRadius(DependencyObject obj, CornerRadius value) => obj.SetValue(CornerRadiusProperty, value);

    public static readonly DependencyProperty CornerRadiusProperty =
        DependencyProperty.RegisterAttached(nameof(Border.CornerRadius), typeof(CornerRadius),
            typeof(CornerRadiusSetter), new UIPropertyMetadata(new CornerRadius(), CornerRadiusChangedCallback));

    public static void CornerRadiusChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
    {
        Control control = sender as Control;

        if (control == null) return;

        control.Loaded -= Control_Loaded;
        control.Loaded += Control_Loaded;
    }

    private static void Control_Loaded(object sender, EventArgs e)
    {
        Control control = sender as Control;

        if (control == null || control.Template == null) return;

        control.ApplyTemplate();

        CornerRadius cornerRadius = GetCornerRadius(control);

        if (control is ComboBox)
            StyleComboBox(control, cornerRadius);
        else
        {
            // setting borders for non-combobox controls
            Border border = control.Template.FindName("border", control) as Border;

            if (border == null) return;

            border.CornerRadius = cornerRadius;
        }
    }

    private static void StyleComboBox(Control control, CornerRadius cornerRadius)
    {
        Control toggleButton = control.Template.FindName("toggleButton", control) as Control;

        if (toggleButton == null) return;

        toggleButton.ApplyTemplate();

        // Set border radius for border radius border
        Border toggleButtonBorder = toggleButton.Template.FindName("templateRoot", toggleButton) as Border;
        toggleButtonBorder.CornerRadius = cornerRadius;

        // Decrease width of dropdown and center it to avoid showing "sticking" dropdown corners
        Popup popup = control.Template.FindName("PART_Popup", control) as Popup;

        if (popup != null)
            popup.HorizontalOffset = cornerRadius.BottomLeft;

        Decorator shadowChrome = control.Template.FindName("shadow", control) as Decorator;

        if (shadowChrome != null)
        {
            double minWidth = control.ActualWidth - cornerRadius.BottomLeft - cornerRadius.BottomRight;
            if (minWidth > 0)
            {
                shadowChrome.MinWidth = minWidth;
                shadowChrome.Width = minWidth;
            }
        }
    }
}


text:
Q: Can't get heroku procfile I'm trying to build up a deep-learning-based facebook chatbot (using Python). I'm trying to deploy it on Heroku firstly, but as I'm using the command web: gunicorn echoserver:app the terminal says web: command not found. Howevere, I've installed gunicorn already.

A: This is because you are typing web:, which is not a command line interface (CLI) command.
If you've installed gunicorn, then the command (from the CLI) is gunicorn.  Something like, for instance
gunicorn echoserver:app

I suppose it's also possible that you have a Windows machine.  gunicorn does not work on Windows, so you would need to use something like waitress.  With waitress, you would type web: on a Windows machine, so that it would be something like
web: waitress-serve echoserver:app

A: Note that the procfile is literally a file you place in your repository. The contents of the procfile should contain the command you want Heroku to run to start your server.
So in the root directory of your repo, you should have a Procfile (named exactly that with no file extension) with the following contents:
web: gunicorn echoserver:app

The first part (web:) is just used to tell Heroku which dyno to run the second part (the command) on. So Heroku will only run the command on web dynos and not on background dynos.
More info here: https://devcenter.heroku.com/articles/procfile


text:
Q: View Print preview scaling through shorcut key/code in Firefox Is there any shorcut key to view print preview in firefox automatically? I want to view all this  content through shorcut key or through coding Link. The main reason I want to view this because I want to adjust scale when print .Currently when I click button in my html it goes like this image, this should not be the output before I print I want to view the print preview to adjust my scaling, so I need to click this window image but it is so hassle to click this buttons, I came up from this question, is there any shorcut key? or code to view print preview automatically? like this image. in Firefox browser, This is all I got below.

function printData()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();
   newWin.close();
}

$('button').on('click',function(){
printData();
})

    First Name
    Last Name
    Points

    Jill
    Smith
    50

    Eve
    Jackson
    94

    John
    Doe
    80

    Adam
    Johnson
    67

<button>Print me</button>


text:
Q: Algolia aroundLatLonViaIP not returning results further away I have a large databases of objects where I'd like to show objects that are nearer to the user searching first so I'm using aroundLatLngViaIP.
This works well for objects that are near by, however, if there aren't any nearby it doesn't show any further away even if there is an exact text match.
Is it possible to use aroundLatLngViaIP to promote results nearby but not exclude those that are far away?

A: To achieve this, you need to use aroundRadius: all as an additional query parameter. Quoting from the doc:

The special value all causes the geo distance to be computed and taken into account for ranking, but without filtering; this option is faster than specifying a high integer value.

https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/


text:
Q: JSON.net Add new Property with the same name I want to merge this two Json's in only one, a mean, Level B with several Applications items:
Json 1:
 {
   "Level A": {
                "Level B": {
                    "Application": [
                        {
                            "id": "1"
                        }
                    ]
                }
            }
        }

Json 2:
  {
        "Level A": {
            "Level B": {
                "Application": [
                    {
                        "id": "2"
                    }
                ]
            }
        }
    }

This is my code:
_jsonMaster = JObject.Parse(jsonMaster);
_jsonApplication = JObject.Parse(jsonApplication);

JProperty newApplication = _jsonApplication["Level A"]["LevelB"].First as JProperty;

_jsonMaster["Level A]["Level B"].AddAfterSelf(newApplication);

This is my error:
An error ocurred while executing the JoinNewApplication: Newtonsoft.Json.Linq.JProperty cannot have multiple values.
If not possible have two Properties with the same name?


text:
Q: Summation involving Bernoulli numbers How would I go about proving (or disproving) that $$\sum_{j=1}^{k}C(2k+2,2j)\,B_{2j}\,B_{2k+2-2j}=-(2k+3)\,B_{2k+2}, \qquad k=1,2,\ldots.$$
(I have checked the validity of the "identity" for a few values of $k$ using Mathematica.)
Note: While solving a nonlinear ODE using the Frobenius method I found out that the coefficients given by a recursion relation were in fact algebraic expressions of Bernoulli numbers. After some manipulations I got the identity given above.
Edit: This identity is usually called Euler's identity (for example: here) or sometimes known as the Euler-Ramanujan identity.

A: We have
$$ \sum_{k\geq 1}\frac{B_{2k}}{(2k)!} x^{2k} = -1+\frac{x}{2}\coth\left(\frac{x}{2}\right) \tag{1}$$
so the given identity just follows from
$$ \frac{d}{d\theta}\coth(\theta) = 1-\coth^2(\theta)\tag{2} $$
since OP's LHS is $(2k+2)!$ times the coefficient of $x^{2k+2}$ in the square of $(1)$, while the RHS is related with a coefficient in the derivative of $(1)$.