text:
Q: rvest wikipedia scraping cells with links produce duplicates I am scraping an HTML table from wikipedia using rvest.
It appears that every time there is a cell that includes a link, I get the actual text, and then the name of the link in my R dataframe after running html_table().
Here is an example.
males_raw <- read_html("https://en.wikipedia.org/wiki/List_of_Academy_Award_Best_Actor_winners_by_age")

males <- males_raw %>%
html_nodes(xpath='//*[@id="mw-content-text"]/div/table') %>%
html_table()

males <- males[[1]]

Which produces a dataframe in which the names of the actors are repeated:
dplyr::glimpse(males)

Observations: 91
Variables: 9
$ `#`                         <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "1...
$ Actor                       <chr> "Jannings, EmilEmil Jannings", "Baxter, WarnerWarner Baxter...
$ Film                        <chr> "The Way of All Flesh and The Last CommandThe Last Command,...
$ `Date of birth`             <chr> "1884-07-23(1884-07-23)July 23, 1884", "1889-03-29(1889-03-...
$ `Date of award`             <chr> "May 16, 1929 (1929-05-16)", "April 3, 1930 (1930-04-03)", ...
$ `Age upon\nreceiving award` <chr> "44-2977004163670000000000♠44 years, 297 days", "41-0057004...
$ `Date of death`             <chr> "1950-01-02(1950-01-02)January 2, 1950", "1951-05-07(1951-0...
$ Lifespan                    <chr> "23,903 days (7004239030000000000♠65 years, 163 days)", "22...
$ Notes                       <chr> "Held record as oldest winner for 2 award ceremonies (from ...

I would prefer to just have the name, e.g., "Jannings, Emil" instead of "Jannings, EmilEmil Jannings"
Thanks!

A: The problem here is that the table cells contain span elements which are not displayed. html_table converts the contents into text and appends it to the text in the td elements. It happens for other columns too.

  Jannings, Emil
  Emil Jannings

One way around this is to remove the span nodes:
spans <- males_raw %>%
  html_nodes(xpath = "//*/tr/td/span")

xml_remove(spans)

males_raw %>%
  html_nodes(xpath='//*[@id="mw-content-text"]/div/table') %>%
  html_table() %>%
  .[[1]] %>%
  glimpse()

Observations: 91
Variables: 9
$ `#`                         <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"...
$ Actor                       <chr> "Emil Jannings", "Warner Baxter", "George Arliss", "Lionel Barrymor...
$ Film                        <chr> "The Last Command,The Way of All Flesh", "In Old Arizona", "Disrael...
$ `Date of birth`             <chr> "July 23, 1884", "March 29, 1889", "April 10, 1868", "April 28, 187...
$ `Date of award`             <chr> "May 16, 1929", "April 3, 1930", "November 5, 1930", "November 10, ...
$ `Age upon\nreceiving award` <chr> "44 years, 297 days", "41 years, 5 days", "62 years, 209 days", "53...
$ `Date of death`             <chr> "January 2, 1950", "May 7, 1951", "February 5, 1946", "November 15,...
$ Lifespan                    <chr> "23,903 days (65 years, 163 days)", "22,683 days (62 years, 39 days...
$ Notes                       <chr> "Held record as oldest winner for 2 award ceremonies (from the 1st ...


text:
Q: Bind property to a radio group value Lets say I have a group of radio buttons:

How do I bind this to a model property Foo so that its value is set to the value of the selected radio button? I tried binding it to the checked property and then applying transform, but ran into issues with overwriting model value when button is being unchecked.

It feels like this should be way simpler than this to begin with...

A: dojox/form/CheckMultiSelect widget provides the capabilities to get and set the selected radio button of a group easily.
If you take the example code in the tutorial for radio buttons and then experiment with setting and getting the value from the group, you will soon see that you can then start binding the value of a model state.
I had to read through the API docs for the widget to expand on the tutorial. To get and set the value of the selected radio in a group I used the standard get("attr")/set("attr", value) with the CheckMultiSelect widget...
// NOTE: make sure you have imported the dijit/registry module
// If my multi select widget has the id "multi".

// get selected value
var selectedValue = registry.byId("multi").get("value");

// set selected value
registry.byId("multi").set("value", newValue);

// getting a handle on all radio buttons
var options = registry.byId("multi").get("options");

The CheckedMultiSelect widget also extends _FormSelectWidget so you can do everything with stores as you'd expect from a select based widget, which may help you bind your model.

A: You can use "watch" to watch the value of a widget for changes. First argument is the value to watch and the second is a function that is called when that value changes.
radioButton.watch("checked", updateFoo);

Here is a fiddle showing it on the native dijit radio button.
http://jsfiddle.net/a2SEP/2/

A: You can use query('selector').on('event', callback) like so
query('.claro [type="radio"]').on('change', function(event) {
    textBox.set('value', event.target.id);
});

See http://jsfiddle.net/542uw/ for full example.
NB: basicaly you user name attribute to group radio buttons.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a Moq of a static extension method from LLBLGen i'm trying to use Moq to mock an extension method from the IDataAccessAdapter interface from LLBLGen. Here is FetchQueryAsync the extension method.
Doing so gave me the error that i can't Mock static extension methods. However there is no way i can change the code. So i tried creating a wrapper class, yet i had no success doing that either because i do not know how to apply it.
In the method Fetch, i want FetchQueryAsync to return an object i specified during the test and not actually execute the query.
public class QueryHandler
{
    private IDataAccessAdapterProvider dataAccessAdapterProvider;
    public QueryHandler(IDataAccessAdapterProvider provider)
    {
        this.dataAccessAdapterProvider = provider;
    }

    private async Task<T> Fetch(DynamicQuery<T> query)
    {
        using (IDataAccessAdapter adapter = dataAccessAdapterProvider.Provide()
        {
            result = await adapter.FetchQueryAsync(query)
        }
    }
}

public class DataAccessAdapterProvider : IDataAccessAdapterProvider
{
    public IDataAccessAdapter Provide()
    {
    var adapter = new DataAccessAdapter();
    return adapter;
    }
}

So in my Unit Test i have this:
List<int> il = new List<int>();

Mock<IDataAccessAdapterProvider> mock = new Mock<IDataAccessAdapterProvider>();

mock.Setup(m => m.Provide()
  .FetchQueryAsync<int>(It.IsAny<DynamicQuery<int>>()))
  .ReturnsAsync(il);

This won't work however because it's not supported.
So i tried wrapping the method as such.
interface IWrap
{
    Task<List<TElement>> FetchQueryAsync<TElement>(IDataAccessAdapter adapter, DynamicQuery<TElement> query);
}

public class Wrap : IWrap
{
    public async Task<List<TElement>> FetchQueryAsync<TElement>(IDataAccessAdapter adapter, DynamicQuery<TElement> query)
    {
        return await adapter.FetchQueryAsync(query);
    }
}

How do i apply this wrapper with Moq to mock the interface?

A: You started with an extension method and then you created your IWrap interface along with an implementation that uses the extension method. That's perfect.
Now all you need is to inject it into your class, just like IDataAccessAdapterProvider is already injected:
public class QueryHandler
{
    private readonly IDataAccessAdapterProvider _dataAccessAdapterProvider;
    private readonly IWrap _wrap; //I'm assuming you'll want a different name.

    public QueryHandler(IDataAccessAdapterProvider provider, IWrap wrap)
    {
        _dataAccessAdapterProvider = provider;
        _wrap = wrap;
    }

(I applied a common convention there. Prefixing the field names with an underscore - _wrap - means that the field and constructor arguments have different names, so you don't need to specify this.wrap. Plus when people see that underscore elsewhere they'll know it's a field.)
Now you can mock the interface:
var mock = new Mock<IWrap>();
var returnedFromMock = new List<int> { 1, 2, 3 };
mock.Setup(x => x.FetchQueryAsync<int>(It.IsAny<IDataAccessAdapter>(), It.IsAny<DynamicQuery<int>>()))
    .ReturnsAsync(returnedFromMock);

You mentioned that there is no way you can change the code. I'm not sure which part you can't change, but if you can't change QueryHandler to replace its concrete dependencies then this may just be a cautionary tale about static dependencies.
You have the source code, though. If you can't change the existing class, perhaps you can just create a new one from the existing source code. If someone asks why you duplicated an existing class, just say (tactfully) that you don't want to duplicate code - you'd rather fix the existing one so that it's testable.


text:
Q: Toggling font awesome Icon using React I want to toggle a fontAwesome icon class name on click. When clicked, the icon should change the color and also call a service which adds an object to a favorite list in the server (hence, why I use e.currentTarget: I need to remember which icon was clicked).  This code works on the first click, but fails to change the class back on the second click (doing an inspect, it says the FA´s classname equals "Object object"). Any idea how I could fix it?
    <FontAwesomeIcon onClick={this.ToggleClass} size={"sm"} icon={faHeart} />

    ToggleClass = (e) => {
      const heart = {
        color: "#E4002B",
      }

      const clicked = {
        color: "#E4002B",
        background: "red"
      }

      if (e.currentTarget.className.baseVal != heart && e.currentTarget.className.baseVal != clicked) {
        return e.currentTarget.className.baseVal === clicked;
#Callservicehere
      }
      else if (e.currentTarget.className.baseVal === clicked) {
        e.currentTarget.className.baseVal = heart;
#callservicehere
      }
    }

A: You're not thinking in React yet :)
Accessing the event target and imperatively manipulating the DOM bypasses React's rendering - you might as well just be using jQuery. Not that there's anything bad about that, but it's not the right way to go about things in React.
In React, if you need to change the DOM in response to user interaction you do it in the render method, i.e. output different JSX based on the component's current state or props.

A: A couple things that might help here:

*

*clicked and heart are both objects which means that you cannot compare them without using a deep comparison method.

var a = { id: 1 }
var b = { id: 1 }

console.log(a == b)    //false
console.log(a === b)   //false

*If you want to compare them, you can convert them both to strings using the toString() method

heart.toString() === clicked.toString()

*In your first if condition, it looks like you're returning a true/false value instead of assigning a desired classname to your target.

return e.currentTarget.className.baseVal === clicked // true/false

e.currentTarget.className.baseVal = clicked // assigned

*You could also take the approach of keeping your classnames as strings and adding your styled objects inside of css

class MysteryComponent extends React.Component {
  state = {
    className: 'heart'
  }

  toggleClass = (e) => {
    if (this.state.className === 'heart') {
      this.setState({ className: 'clicked' })
    } else if (this.state.className === 'clicked') {
      this.setState({ className: 'heart' })
    }
  }

  render() {
    return (
      <div className={this.state.className}>
        <FontAwesomeIcon onClick={this.toggleClass} size={"sm"} icon={faHeart} />
      </div>
    )
  }
}

// css
.heart {
  color: "#E4002B";
}

.clicked {
  color: "#E4002B";
  background: "red";
}

A: I see. You want to fill/unfill the color of the heart as the user clicks. The reason why the results are not meeting your expectations is because of the event.targets are especially funky with FontAwesome. You may think you're clicking on it, but it manipulates the DOM in a way that when you try extract the className, it's value is often inconsistent.
This is why everyone is recommending that you make use of React's state. The logic that determines how elements are styled is now more controlled by the component itself instead of the FontAwesome library. Consider the code below, we only care about whether the item was clicked, not what class it initially has.
class Example extends React.Component{
    state = {
        clicked: false
    }

    handleOnCLick = () => {
        this.setState({
            clicked: !this.state.clicked
        })
    }

    render(){

        var clicked = this.state.clicked

        return(
        <button onClick={this.handleOnClick}>
            <i
                class={ clicked ? "fas fa-heart" : "fas fa-circle"}
            </i>
        </button>

        )
    }
}


text:
Q: Single and double click on editor I have an editor (combobox) and I want to call different function on single click and double click.This is my editor
Ext.create('Ext.grid.CellEditor', {
field: Ext.widget('combo', {
    editable: false,
    allowBlank: false,
    width: 100,
    store: MyStore,
    displayField: 'name',
    valueField: 'id',
    listeners: {
        eventforSingleClick: function (){            },
        eventforDoubleClick: function (){            }
    }
})

});
Which event listeners I should implement for single and double click events?

A: Not sure if this is best solution, but you can do something like this:
    Ext.create('Ext.form.field.ComboBox', {
        editable: false,
        allowBlank: false,
        width: 100,
        listeners: {
            afterrender: function(combo) {
                combo.getEl().on('click', function() {
                    console.log('Clicked!');
                });
                combo.getEl().on('dblclick', function() {
                    console.log('Double clicked!');
                });
            }
        },
        renderTo: Ext.getBody()
    });

Working fiddle


text:
Q: What does it means this +1 in Permutation List with Python? This permutation comes from Udacity and is made with Python.
But i have problems to understand what does it means +1 in this line for j in range(0, len(p) + 1):. Someone could help me to understand it? I'm little bit confused.
Thanks to all!
import copy
def permute(l):

    perm = []
    if len(l) == 0:
        perm.append([])
    else:
        first_element = l[0]
        after_first = slice(1, None)
        sub_permutes = permute(l[after_first])
        for p in sub_permutes:
            for j in range(0, len(p) + 1):
                r = copy.deepcopy(p)
                r.insert(j, first_element)
                perm.append(r)
    return perm

A: The idea behind this loop is to create a lists each with first_element in different place.
To insert an element after the last index (mimic append behavior), you would write l.insert(len(l), element)). So when they are trying to insert the first element in each place of the list they want the range to be from 0 to len(p) and be inclusive, so they add +1 to the range.
In [1]: l = [1,2,3]
In [2]: for i in range(0, len(l)+1):
   ...:     new_l = list(l)
   ...:     new_l.insert(i, 4)
   ...:     print(new_l)
   ...:
[4, 1, 2, 3]
[1, 4, 2, 3]
[1, 2, 4, 3]
[1, 2, 3, 4] # without the +1 this line would not be created


text:
Q: Is it possible for pip to exclude folders to install? Is it possible for pip to exclude folders when installing from requirements.txt? For example I want pip to skip all static folders when installing on heroku (to keep the slug size down). I havent managed to find any info on it whatsoever.
I know I can push the directories without the folders myself and use https://devcenter.heroku.com/articles/python-pip#local-file-backed-distributions but this seems like a lot of work for something that could/should be easy!
Any other clever ways of achieving the same thing?
UPDATE:
I found that I can add in the packages setup.py exclude_package_data which is great but it means going through many different packages and adding a lookup for an ENV var or something similar like described here.
exclude_package_data = {'': ['.gitignore', 'artwork/*'],
                          'model': ['config.py']},


text:
Q: Queuing up blog posts from offline I have a Blogger blog and I will be going for long periods of time when I can only access the web via dial-up for short periods in the middle of the night (much like the so-called "flash sessions" that were common in the early days of AOL).
I'm looking for a system of creating blog posts while offline and queuing them up to be published during the night. If I can get this, I'll be happy, but there is one more thing I'm also looking for. I would like to set a delay for each post of about a week.
Anybody got a silver bullet for me?

A: Turns out Windows Live Writer lets me work offline and upload en masse as well as post-date my blog posts. Worked out great!

A: You could also blog by email

The Mail-to-Blogger feature turns any email account into a blog-posting application. In Settings | Email you can create a Mail-to-Blogger address which you will use to send posts via email to your blog:

have a look at this blogger help article for more details.


text:
Q: ORA-00942: Table or view does not exist I am passing a select query from java, it works for all table but one of the table gets an error "ora-00942 table or view does not exist". I checked grant and all, its same for all table. But for some reason it complains abtout this particular table. But if I run the same query in sql plus it works completely fine. Can someone tell me what may be the reason behind it. Thank you

A: I suspect you are using a different user from sqlplus than from your Java program, and then the error is caused by a missing synonym/schema name.


text:
Q: Switch doesn't in full view in match_parrent I have the following code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="horizontal">

    <Switch
        android:id="@+id/switch1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:checked="true" />
</LinearLayout>

But looks as following

Here I want the switch to in full view. I don't know what I am missing. Any help will be highly appreciable.


text:
Q: Am I on right path to simplifying php code block? Fairly new to php and following e commerce tutorials. When exploring a way to resolve a problem I had with a php code block, I came upon a post another person had with the same code block.
https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/
 The post suggested a way to simplify the code.
Original code block:
   <?php
if (isset($_POST ['pid'])) {
    $pid = $_POST ['pid'];
    $wasFound = false;
    $i = 0;
    if (!isset ($_SESSION["cart_array"]) || count($_SESSION ["cart_array"])<1){
        $_SESSION["cart_array"] = array (0=> array("item_id"=> $pid, "quantity" => 1));
    }  else {
        foreach ($_SESSION["cart_array"] as $each_item) {
            $i++;
            while(list($key,$value)=each($each_item)){
            if ($key== "item_id" && $value == $pid) {
                array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quantity"=> $each_item['quantity']+1)));
                $wasFound = true;
            }
        }
    }
    if($wasFound==false) {
        array_push ($_SESSION["cart_array"], array("item_id"=> $pid, "quantity" => 1));
        }
    }
    header("Location: cart.php");
    exit();
}
?>

This was the suggested simplified code block and an explanation of what to do after changing code. I am unsure how to implement the the part suggested after the code block.
if (isset($_POST['pid'])) {
    // add (+1) item to cart
    $pid = (int)$_POST['pid']; // cast as integer
    // valid pids are > 0
    if($pid > 0){
    if(!isset($_SESSION['cart_array'][$pid])){
    // item is not in the cart, add it with quantity = 1
    $_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it could also be simplified so that it is only the quantity, since the item_id is now the cart array index
    } else {
    // item is in the cart, increment quantity
    $_SESSION['cart_array'][$pid]['quantity']++;
    }
    }
    header("location: cart.php");
    exit();
    }

To get the details for the cart items, you need to run ONE query that gets all of them at the same time (putting a query inside of a loop is a resource killer.) For the definition of the cart that I have suggested, you can use array_keys to get all the item id's. You would then implode those into a comma separated list and put them into an IN() comparison in the WHERE clause in a query to get all the matching rows at once.
Edited by PFMaBiSmAd, 27 December 2012 - 02:05 PM.
This is what I am considering adding to the code block:
if  ($result = print_r(array_keys('cart_array',$pid))) {
$comma_seperated = implode("," $result);

// then use use $comma_seperated in query where needed later in annother code block?
}

Am I on the right path?

A: This was provided by Mike Brant in codereview.stackexchange. This is how I would extract the keys to be used in query.
$pidsInCart = array_keys($_SESSION['cart_array']);

A: Seems good to me - maybe you should add an check, if the session contains cart_array. And very important - indent your code! The one your provided isn't very readable..
if (isset($_POST['pid'])) {
    $pid = (int)$_POST['pid'];
    if($pid > 0){
        if (!isset($_SESSION['cart_array'])) {
            $_SESSION['cart_array'] = [];
        }

        if(!isset($_SESSION['cart_array'][$pid])){
            $_SESSION['cart_array'][$pid] = ["quantity" => 1];
        } else {
            $_SESSION['cart_array'][$pid]['quantity']++;
        }
    }
    header("location: cart.php");
    exit();
}


text:
Q: Record not updating on successful insert I have a row as shown in below image
Image
I am fetching id and name from db and other select options are to be updated in particular row.
My id and name fetching as shown below
$sql = "SELECT id, name,day,week,month,pickup,drop_location FROM crm LIMIT 10";
        $resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
        while( $emp = mysqli_fetch_assoc($resultset) ) {
        ?>

                <?php echo $emp["id"]; ?>

I am updating row but it is not working.
form.php
<form action="drop.php" name = "myForm" method="post">

                    <select style="width: 150px;" class="blue" id="pick" data-style="btn-info" name="pickup">
                        <option value="ward" id="ward1">Floor 1</option>
                        <option value="ward1" id="ward2">Floor 2</option>
                        <option value="ward2" id="ward3">Floor 3</option>
                    </select>

                    <select style="width: 150px;" class="blue" id="drop" data-style="btn-success" name="drop_location">
                        <option value="ward"  id="ward1">Floor 1</option>
                        <option value="ward1" id="ward2">Floor 2</option>
                        <option value="ward2" id="ward3">Floor 3</option>
                    </select>

                    <button class="btn btn-primary" type="submit" name="submit">submit</button>
                    <select style="width: 150px;" class="blue" id="stat" data-style="btn-warning" name="stat">

                        <option value="allocate">Allocated</option>
                        <option value="cancel">Cancelled</option>
                    </select>

                    <select style="width: 150px;" class="blue" id="status" data-style="btn-primary" name="status">
                        <option value="pending">pending</option>
                        <option value="Allocated">Allocated</option>
                        <option value="Engaged">Engaged</option>
                    </select>

            </form>

drop.php
 <?php
    /* Attempt MySQL server connection. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */
    $mysqli = new mysqli("localhost", "root", "", "redeem");

    // Check connection
    if($mysqli === false){
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }

    // Escape user inputs for security
    $pickup = $mysqli->real_escape_string($_POST['pickup']);
    $drop_location = $mysqli->real_escape_string($_POST['drop_location']);
    $stat = $mysqli->real_escape_string($_POST['stat']);
    $status = $mysqli->real_escape_string($_POST['status']);

    // attempt insert query execution
    $sql = "UPDATE crm SET pickup='$pickup',drop_location='$drop_location',stat='$stat', status='$status' WHERE id = 'id' ";

    if($mysqli->query($sql) === true){
        echo "Records inserted successfully.";
    } else{
        echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
    }

    // Close connection
    $mysqli->close();
    ?>

I have created id for the select like this
 $(document).ready(function() {
$("#pick, #drop, #stat, #status").on('change', function () {
    alert($(this).val());
});

I am not able to figure where the mistake is. Please, kindly help me out.
Thank you in Advance!!!

A: You are not taking which Id need to be updated. And In query you are using id = 'id' need to replace id with $id variable to update the value.
// Escape user inputs for security
    $pickup = $mysqli->real_escape_string($_POST['pickup']);
    $drop_location = $mysqli->real_escape_string($_POST['drop_location']);
    $stat = $mysqli->real_escape_string($_POST['stat']);
    $status = $mysqli->real_escape_string($_POST['status']);
    $id= $mysqli->real_escape_string($_POST['id']);   // Get id from post need to be updated

    // attempt insert query execution
    $sql = "UPDATE crm SET
            pickup='$pickup',drop_location='$drop_location',stat='$stat', status='$status'
            WHERE id = $id ";   // use $id variable

    if($mysqli->query($sql) === true){
        echo "Records inserted successfully.";
    } else{
        echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
    }

A: You are already fetching the records from database so what you need inside your form have a hidden field that will have a value of each record's id.
add this in your form :
<input type="hidden" name="id" value="<?=$emp['id']?>">

Then you can be able to update the record using that id, I also suggest that you use prepared statement to prevent sql injections.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "", "redeem");

// Check connection
if ($mysqli === false) {
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}

$pickup        = isset($_POST['pickup']) ? $_POST['pickup'] : null;
$drop_location = isset($_POST['drop_location']) ? $_POST['drop_location'] : null;
$stat          = isset($_POST['stat']) ? $_POST['stat'] : null;
$status        = isset($_POST['status']) ? $_POST['status'] : null;
$id            = isset($_POST['id']) ? intval($_POST['id']) : null;

// attempt insert query execution
$sql = "UPDATE crm SET pickup = ? ,drop_location= ? ,stat= ? , status= ?  WHERE id = ? ";

$stmt = $mysqli->prepare($sql); //prepare statement
$stmt->bind_param("ssssi", $pickup, $drop_location, $stat, $status, $id);

if ($mysqli->execute()) { //execute the query
    echo "Records inserted successfully.";
} else {
    echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}

// Close connection
$mysqli->close();
?>


text:
Q: Force flushing from inside bash script code to a stdout file I'm trying to flush to stdout the output of a bioinformatic software written on Python code (Ete-Toolkit software). I tried the command (stdbuf) detailed on Force flushing of output to a file while bash script is still running but does not work because I have seen that stdbuf command it's only possible to execute from shell and not from bash(How to use stdbuf on a bash function).
Moreover from Python I discovered the following function that maybe could be interesting:
import sys
sys.stdout.flush()

But I don't know how can I implement inside the next bash script attached below.
The purpose is that if I only use the options -o and -e in the bash script (as you can see) the output is printed to logs_40markers in a not continuos manner which does not permits me to see the error. I can do it working directly from shell but my internet connection is not stable and practically each night there are a power outage and I have to restart again the command that will takes minimun one week.
#!/bin/bash
#$ -N tree
#$ -o logs_40markers
#$ -e logs_40markers
#$ -q all.q@compute-0-3
#$ -l mf=100G

stdbuf -oL

module load apps/etetoolkit-3.1.2

export QT_QPA_PLATFORM='offscreen'

ete3 build -w mafft_default-none-none-none -m sptree_fasttree_all -o provaflush --cogs coglist_species_filtered.txt -a multifasta_speciesunique.fa  --clearall --cpu 40

&> logs_40markers

Thanks on advance if someone can give me some guide/advice,
Have a nice day,
Thank you,
Maggi

A: one informatician colleague of me solved the problem using the PYTHONUNBUFFERED command.
#!/bin/bash
#$ -N tree
#$ -o logs_40markers
#$ -e logs_40markers
#$ -q all.q@compute-0-3
#$ -l mf=100G
module load apps/etetoolkit-3.1.2

export QT_QPA_PLATFORM='offscreen'
export PYTHONUNBUFFERED="TRUE"

ete3 build -w mafft_default-none-none-none -m sptree_fasttree_all -o provaflush --cogs coglist_species_filtered.txt -a multifasta_speciesunique.fa  --clearall --cpu 40 --v 4

To check the current situation of the process,
type in the shell:
tail output.log file -f (means follow)
I hope that someone could find this solution helpful


text:
Q: Typescript Google API compilation errors I'm using Typescript, tslint and Google APIs but there's issues compiling in typescript to javascript and I'm not sure why and for some reason I can't find anything specific online about this problem.  Google searches don't render good results.  I can't find a good example of how your tsconfig should be setup with this library also.  So I'm coming here.
I'm running into lots of "Cannot find type definition file" and "Cannot find module" errors when I run tsc.
My file is literally just this line:
import {google} from 'googleapis'

That's it.
When I run tsc it gives me these errors:
$ tsc
node_modules/gaxios/build/src/common.d.ts:1:23 - error TS2688: Cannot find type definition file for 'node'.

1 /// <reference types="node" />
                        ~~~~

node_modules/gaxios/build/src/common.d.ts:3:23 - error TS2307: Cannot find module 'https'.

3 import { Agent } from 'https';
                        ~~~~~~~

node_modules/google-auth-library/build/src/auth/authclient.d.ts:16:23 - error TS2688: Cannot find type definition file for 'node'.

16 /// <reference types="node" />
                         ~~~~

node_modules/google-auth-library/build/src/auth/authclient.d.ts:17:30 - error TS2307: Cannot find module 'events'.

17 import { EventEmitter } from 'events';
                                ~~~~~~~~

node_modules/google-auth-library/build/src/auth/googleauth.d.ts:16:23 - error TS2688: Cannot find type definition file for 'node'.

16 /// <reference types="node" />
                         ~~~~

node_modules/google-auth-library/build/src/auth/googleauth.d.ts:17:21 - error TS2307: Cannot find module 'fs'.

17 import * as fs from 'fs';
                       ~~~~

node_modules/google-auth-library/build/src/auth/googleauth.d.ts:19:25 - error TS2307: Cannot find module 'stream'.

19 import * as stream from 'stream';
                           ~~~~~~~~

node_modules/google-auth-library/build/src/auth/googleauth.d.ts:182:20 - error TS2503: Cannot find namespace 'NodeJS'.

182     _osPlatform(): NodeJS.Platform;
                       ~~~~~~

node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts:16:23 - error TS2688: Cannot find type definition file for 'node'.

16 /// <reference types="node" />
                         ~~~~

node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts:17:25 - error TS2307: Cannot find module 'stream'.

17 import * as stream from 'stream';
                           ~~~~~~~~

node_modules/google-auth-library/build/src/auth/jwtclient.d.ts:16:23 - error TS2688: Cannot find type definition file for 'node'.

16 /// <reference types="node" />
                         ~~~~

node_modules/google-auth-library/build/src/auth/jwtclient.d.ts:18:25 - error TS2307: Cannot find module 'stream'.

18 import * as stream from 'stream';
                           ~~~~~~~~

node_modules/google-auth-library/build/src/auth/refreshclient.d.ts:16:23 - error TS2688: Cannot find type definition file for 'node'.

16 /// <reference types="node" />
                         ~~~~

node_modules/google-auth-library/build/src/auth/refreshclient.d.ts:17:25 - error TS2307: Cannot find module 'stream'.

17 import * as stream from 'stream';
                           ~~~~~~~~

node_modules/google-auth-library/build/src/crypto/crypto.d.ts:16:23 - error TS2688: Cannot find type definition file for 'node'.

16 /// <reference types="node" />
                         ~~~~

node_modules/google-auth-library/build/src/crypto/crypto.d.ts:32:60 - error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

32     verify(pubkey: string | JwkCertificate, data: string | Buffer, signature: string): Promise<boolean>;

My tsconfig file is:
    {
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "esModuleInterop": true,
    "noImplicitAny": false,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "app",
    "baseUrl": "./app",
    "paths": {
      "*": [
        "node_modules/*"
      ]
    }
  },
  "include": [
    "src/**/*"
  ]
}

My package dependencies are:
  "dependencies": {
    "googleapis": "^37.2.0",
    "mysql": "^2.16.0",
    "typescript": "^3.3.3333"
  },
  "devDependencies": {
    "nodemon": "^1.18.10",
    "tslint": "^5.12.1"
  }

I'm not using the tsc node module (which is deprecated), I'm using typescript v3.3.3
Help would be appreciated! :)

A: Type errors in 3rd party libraries typings can easily be avoided by either submitting a pull request OR turning on skipLibCheck: true in your tsconfig and wait for them to be fixed.
Hope this helps.


text:
Q: Haskell function that returns sublists of a list I'm writing a function in Haskell that, when given a list of numbers, will return a list containing all sublists (in order) of that original list. What I have so far is:
sublists [] = [[]]
sublists (x:xs) = [x:sublist | sublist <- sublists xs] ++ sublists xs

The above code, if given [1,2,3], returns [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]], which is not quite what I am looking for. Instead the function should return:
[[1],[1,2],[1,2,3]]

How do I modify the given code to get this result?

A: Why don't you take the first n elements from the list for n between 1 and the length of the input?
sublists :: [a] -> [[a]]
sublists xs = [ take n xs | n <- [1..length xs] ]

> sublists [1,2,3]
[[1],[1,2],[1,2,3]]

Alternatively using recursion and pattern matching
sublists' :: [a] -> [[a]]
sublists' xs = sublist [] xs where
    sublist a [b] = [ a ++ [b] ]
    sublist a (b:bs) = [ a ++ [b] ] ++ sublist (a ++ [b]) bs


text:
Q: GNUsetup objective-c undefined reference to `htmlReadMemory' linking with libxml2 i trying to link libxml2 with my simple objective-c in windows , i have the lib and the headers in place .
my GNUmakefile looks like this :
include $(GNUSTEP_MAKEFILES)/common.make
TOOL_NAME = sample_app
sample_app_CFLAGS = -Ic:/GNUstep/include/libxml2 -lxml2
sample_app_LDFLAGS =-Lc:/GNUstep/lib -lxml2
ADDITIONAL_FLAGS += -Ic:/GNUstep/include/libxml2 -lxml2
ADDITIONAL_LDFLAGS+=-Lc:/GNUstep/lib -lxml2

sample_app_HEADERS = HttpManager.h UT.h HtmlParser.h
sample_app_OBJC_FILES = main.m HttpManager.m UT.m HtmlParser.m
sample_app_RESOURCE_FILES =

include $(GNUSTEP_MAKEFILES)/tool.make

my implamentaion file that called HtmlParser in HtmlParser.m/h
looks like this :
#import <Foundation/Foundation.h>
#import <libxml/tree.h>
#import <libxml/parser.h>
#import <libxml/HTMLparser.h>
#import <libxml/xpath.h>
#import <libxml/xpathInternals.h>

@interface HtmlParser :NSObject
{
    NSString* encoding;
}

 -(void)ExtractInnerSiteLinks:(NSString*) PageHtml:(NSString*) url;

@end

#import "HtmlParser.h"
#import "UT.h"
@implementation HtmlParser

-(id) init
{
    self = [super init];
    if(self) {
        encoding = @"UTF-8";
    }

    return self;

}

-(void) ExtractInnerSiteLinks:(NSString*) PageHtml:(NSString*) url
{

    NSData* documentData = [PageHtml dataUsingEncoding:NSUTF8StringEncoding];
    NSData* urlData = [url dataUsingEncoding:NSUTF8StringEncoding];
    const char *cEncoding =[encoding UTF8String];
    xmlDocPtr doc;
    /*

    htmlReadMemory  (const char *buffer,
                     int size,
                     const char *URL,
                     const char *encoding,
                     int options);

    */
    doc = htmlReadMemory([documentData bytes],
                               [documentData length],
                               /*[urlData bytes]*/NULL,
                               /*cEncoding*/NULL,
                               HTML_PARSE_NOBLANKS | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING | HTML_PARSE_NONET);

}
 @end

when i run: make CC=clang
im getting :
$ make CC=clang
This is gnustep-make 2.6.2. Type 'make print-gnustep-make-help' for help.
Making all for tool sample_app...
 Compiling file main.m ...
clang: warning: -lxml2: 'linker' input unused when '-c' is present
 Compiling file HttpManager.m ...
clang: warning: -lxml2: 'linker' input unused when '-c' is present
 Compiling file UT.m ...
clang: warning: -lxml2: 'linker' input unused when '-c' is present
 Compiling file HtmlParser.m ...
clang: warning: -lxml2: 'linker' input unused when '-c' is present
HtmlParser.m:25:10: warning: unused variable 'urlData' [-Wunused-variable]
        NSData* urlData = [url dataUsingEncoding:NSUTF8StringEncoding];
                ^
HtmlParser.m:26:14: warning: unused variable 'cEncoding' [-Wunused-variable]
        const char *cEncoding =[encoding UTF8String];
                    ^
2 warnings generated.
 Linking tool sample_appscrapper ...
./obj/sample_appscrapper.obj/HtmlParser.m.o: In function `-[HtmlParser ExtractInnerSiteLinks::]':
d:/dev/objc/sample_appscrapper/HtmlParser.m:37: undefined reference to `htmlReadMemory'
collect2: ld returned 1 exit status
clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)
make[3]: *** [obj/sample_appscrapper.exe] Error 1
make[2]: *** [internal-tool-all_] Error 2
make[1]: *** [sample_appscrapper.all.tool.variables] Error 2
make: *** [internal-all] Error 2

make -n :
$ make -n CC=clang
This is gnustep-make 2.6.2. Type 'make print-gnustep-make-help' for help.
(make -f GNUmakefile --no-print-directory --no-keep-going \
        internal-master-tool-all \
        GNUSTEP_BUILD_DIR="." \
        _GNUSTEP_MAKE_PARALLEL=yes)
( \
instance=sample_app; \
operation=all; \
type=tool; \
abs_build_dir="."; \
if [ "" != "" ]; then \
  echo "Making $operation in subprojects of $type $instance..."; \
  for f in  __done; do \
    if [ $f != __done ]; then       \
      if [ "${abs_build_dir}" = "." ]; then \
        gsbuild="."; \
      else \
        gsbuild="${abs_build_dir}/$f"; \
      fi; \
      if [ "" = "" ]; then \
        if [ "$type" = "framework" ]; then \
          if [ "no" = "yes" ]; then \
            framework_version=""; \
            if [ "$framework_version" = "" ]; then \
              framework_version=""; \
              if [ "$framework_version" = "" ]; then \
                framework_version=""; \
                if [ "$framework_version" = "" ]; then \
                  framework_version="0"; \
                fi; \
              fi; \
            fi; \
            owning_project_header_dir="../${instance}.framework/Versions/${framework_version}/Headers"; \
          else \
            owning_project_header_dir="../${instance}.framework/Headers"; \
          fi; \
       else owning_project_header_dir=""; \
       fi; \
      else \
        owning_project_header_dir="../"; \
      fi; \
      if make -C $f -f GNUmakefile --no-print-directory --no-keep-going $operation \
          OWNING_PROJECT_HEADER_DIR_NAME="${owning_project_header_dir}" \
          DERIVED_SOURCES="../derived_src" \
          GNUSTEP_BUILD_DIR="$gsbuild" \
          _GNUSTEP_MAKE_PARALLEL=no \
        ; then \
        :; \
      else exit $?; \
      fi; \
    fi; \
  done; \
fi; \
echo "Making $operation for $type $instance..."; \
make -f GNUmakefile --no-print-directory --no-keep-going \
    internal-${type}-$operation \
    GNUSTEP_TYPE=$type \
    GNUSTEP_INSTANCE=$instance \
    GNUSTEP_OPERATION=$operation \
    GNUSTEP_BUILD_DIR="${abs_build_dir}" \
    _GNUSTEP_MAKE_PARALLEL=no)
Making all for tool sample_app...
(make -f GNUmakefile --no-print-directory --no-keep-going \
        internal-tool-compile \
        GNUSTEP_TYPE=tool \
        GNUSTEP_INSTANCE=sample_app \
        GNUSTEP_OPERATION=compile \
        GNUSTEP_BUILD_DIR="." \
        _GNUSTEP_MAKE_PARALLEL=yes)
(echo " Linking tool sample_app ...";clang  -Wl,--enable-auto-import -Lc:/GNUstep/lib -lxml2 -Lc:/GNUstep/lib -lxml2      -shared-libgcc -fexceptions -fgn
u-runtime -o obj/sample_app.exe \
                ./obj/sample_app.obj/main.m.o ./obj/sample_app.obj/HttpManager.m.o ./obj/sample_app.obj/UT.m.o ./obj/sample_app.obj/Html
Parser.m.o \
                     -L/home/meiry/GNUstep/Library/Libraries -L/GNUstep/Local/Library/Libraries -L/GNUstep/System/Library/Libraries     -lgnustep-base    -lobjc
   -lws2_32 -ladvapi32 -lcomctl32 -luser32 -lcomdlg32 -lmpr -lnetapi32 -lm -I. )


text:
Q: How to set the distance between ticks in plotly? I am using plotly to create dendrograms with different amounts of leaves. I aim to set the distance between the y-axis ticks to be exactly the same for all the different dendrograms. So far I have tried setting the height of the figure to depend on the number of leaves like this:
fig.update_layout(
    width=width,
    height=num_ticks * 50,
    margin={'l': 0, 'r': 0, 't': 0, 'b': 0}
)

While this ensures the same height ratio of the dendrograms, it seems like the distance in between the y-axis ticks gets smaller for plots with more leaves and, instead, more whitespace is added at the top of the graph. Ideally, I would like to set the distance in px, but I would also be happy to find a solution with a consistent distance between the different plots. Any help is appreciated!

A: This whitespace on the top could be added automatically by plotly to fit in the title or other elements of your dendrogram. I would try
fig.update_layout(
    width=width,
    height=num_ticks * 50,
    margin=dict(autoexpand = False, t = 0, b = 0, l = 0, r = 0)
)


text:
Q: How do i navigate through images stored in mysql rather than displaying all of them? This is my code but it displays all of the images saved in the database, i just want one to be displayed and the rest by using next and previous buttons. any help would be appreciated. Thanks!
<?php
    $sql = "SELECT * FROM images";
    $result = mysqli_query($conn, $sql) or die("bad request: $sql");
        $i = 0;
    while($row = mysqli_fetch_assoc($result)) {
        if($i%3 == 0)
        {
            echo "
";
        }
        echo"	";
        if($i%3 == 2) {
            echo"
";
        }
    }
 ?>

A: You should use LIMIT and OFFSET in your query. It would look like this:
$sql = "SELECT file_name FROM images LIMIT 0,1";

This will get you 1 record, starting at record 0. So from that query you can build your pagination script. Just keep adding one to the offset (the first number in the LIMIT clause). Remember to filter the page number (make sure it's an int).


text:
Q: Can I add feedback (notch) to a gesture on iOS using 3D Touch? With Force Touch on OS X applications can provide a feedback or a notch (haptics/taptics?) like Apple's example describes:

Map rotation: You'll feel a notch when you rotate the compass to north
  in Maps.

*

*https://support.apple.com/en-us/HT204352
Is the the same thing possible with 3D Touch beyond just the old audio API to vibrate the device (AudioServicesPlayAlertSound)?

A: Yes, using UIFeedbackGenerator in iOS 10+ on supported devices you could do something like this:
var feedbackGenerator: UISelectionFeedbackGenerator

func prepare() {
    // Instantiate a new generator.
    feedbackGenerator = UISelectionFeedbackGenerator()

    // Prepare the generator when the gesture begins.
    feedbackGenerator?.prepare()
}

func notch() {
    // Trigger selection feedback.
    feedbackGenerator?.selectionChanged()

    // Release the current generator.
    feedbackGenerator = nil
}


text:
Q: Tools to design good looking HTML forms Are there any free tools through which I can design beautiful HTML Forms?

A: I don't know of any tools, but there is a very nice basic article on A List Apart that might get you started.

A: http://wufoo.com/
Makes reasonably nice forms, will write all the HTML for you, make it easy to insert in your page, and even creates the validation js. If you just want to use it for the HTML code, its free - if you want to use them to host your forms and have any real amount of traffic its a paid service.
You get a certain amount of traffic even in the free version, I forget how much.

A: Hey guys, I found one simple tool. It works and is free.
http://www.phpform.org/

A: Here is a quite recent article that details some of the HTML5 form features, along with making a nice looking form. http://24ways.org/2009/have-a-field-day-with-html5-forms

A: If you work with Wordpress, you might also like to check out Gravity Forms. I've found them to strike a nice balance between simplicity and customisation. They have a solid user base, are reasonably priced and offer a good level of support in my experience:
http://www.gravityforms.com/


text:
Q: How to replace .Take() method in linq query? I have a linq query:
from cc in _db.CC
    from pn in _db.AlertDbEntities
        .Where(x => x.CompanyId == cc.Id)
        .DefaultIfEmpty()
        .Take(1)
join ns in _db.NS
     on cc.Id equals ns.CompanyId
...

'Take()' part of which is translated into the following SQL code:
ROW_NUMBER() OVER (PARTITION BY ...)

The problem is that this function appeared only in Mysql 8.0, and the server for which I am writing has a version of Mysql 5.7. A lot of workarounds of this problem either cannot be transferred to SQL

The LINQ expression 'ProjectionBindingExpression: 1' could not be
translated. Either rewrite the query in a form that can be translated,
or switch to client evaluation explicitly by inserting a call to
'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'

Maybe you had a similar problem? How can it be solved?
I tried also this code:
from cc in _db.CC
    from pn in _db.AlertDbEntities
        .Where(x => x.CompanyId == cc.Id)
        .OrderByDescending(n => n.CreatedAt)
        .AsEnumerable()
        .DefaultIfEmpty()
        .Take(1)
        .AsQueryable()
join ns in _db.NS
     on cc.Id equals ns.CompanyId
...
//------------------------------------------
from cc in _db.СС
                from pn in _db.AlertDbEntities
                    .Where(x => x.CompanyId == cc.Id)
                    .AsEnumerable()
                    .DefaultIfEmpty()
                    .OrderByDescending(n => n.CreatedAt)
                    .GroupBy(n => n.CompanyId)
                    .Select(g => g.FirstOrDefault())
join ns in _db.NS
     on cc.Id equals ns.CompanyId
...


text:
Q: Page(s) contain a ViewGroup with a LayoutTransition (or animateLayoutChanges="true"), which interferes with the scrolling animation I use fragments with ViewPager2, and I notice two relevant IllegalStateExceptions in production (I can't reproduce it myself) occurring in devices like Xiaomi, Yulong, asus, vivo running Android 8 or 9:
Fatal Exception: java.lang.IllegalStateException: Page can only be offset by a positive amount, not by -758
       at androidx.viewpager2.widget.ScrollEventAdapter.updateScrollEventValues(ScrollEventAdapter.java:280)
       at androidx.viewpager2.widget.ScrollEventAdapter.onScrolled(ScrollEventAdapter.java:178)
       at androidx.recyclerview.widget.RecyclerView.dispatchOnScrolled(RecyclerView.java:5173)
       at androidx.recyclerview.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:5338)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1029)
       at android.view.Choreographer.doCallbacks(Choreographer.java:834)
       at android.view.Choreographer.doFrame(Choreographer.java:760)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1015)
       at android.os.Handler.handleCallback(Handler.java:873)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:224)
       at android.app.ActivityThread.main(ActivityThread.java:7083)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)

and
Fatal Exception: java.lang.IllegalStateException: Page(s) contain a ViewGroup with a LayoutTransition (or animateLayoutChanges="true"), which interferes with the scrolling animation. Make sure to call getLayoutTransition().setAnimateParentHierarchy(false) on all ViewGroups with a LayoutTransition before an animation is started.
       at androidx.viewpager2.widget.ScrollEventAdapter.updateScrollEventValues(ScrollEventAdapter.java:272)
       at androidx.viewpager2.widget.ScrollEventAdapter.onScrolled(ScrollEventAdapter.java:178)
       at androidx.recyclerview.widget.RecyclerView.dispatchOnScrolled(RecyclerView.java:5173)
       at androidx.recyclerview.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:5338)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1029)
       at android.view.Choreographer.doCallbacks(Choreographer.java:841)
       at android.view.Choreographer.doFrame(Choreographer.java:769)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1015)
       at android.os.Handler.handleCallback(Handler.java:794)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:176)
       at android.app.ActivityThread.main(ActivityThread.java:6651)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)

While looking around, I passed by the following thread: https://issuetracker.google.com/issues/129530305, which as I understood correctly, seems to summarize to set animateLayoutChanges to false on any parent layout of viewPager2 and that's what I did. Unfortunately, that didn't solve my issue. Then I found another thread: java.lang.IllegalStateException: Page can only be offset by a positive amount, which seems to not help a lot. Any idea what else might cause the issue?

A: Another Problem I had was, that I did not got the above exception, but my viewpager2 started to flick / reload the page, when the transition started. I was a bit confused by these examples and how to add set setAnimateParentHiearchy to false, so I would like to add another example, how to fix this problem:
ViewPager Layout
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Toolbar -->
        <include
            android:id="@+id/headline"
            layout="@layout/registration_toolbar"
            app:isBold="@{false}"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:outsideToolbarTitle="@{@string/fragment_user_data_toolbar_title}" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tl_user_data"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/headline" />

        <!-- This Viewpager contains a fragment, which has android:animateLayoutChanges="true" -->
        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/vp_user_data"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tl_user_data" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Fragment Layout (which will be inside the viewpager)
   <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/outerContraintLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true" > <-- THIS WILL CAUSE PROBLEMS

       <!-- Deleted unnecessary parts -->

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

If you want to keep android:animateLayoutChanges, you have to call this inside your fragments onViewCreated()
class MyFragmentInsideViewPagerThatHasProblems : Fragment(R.layout.above_layout) {

     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val viewGroup = requireView().findViewById<ConstraintLayout>(R.id.outerContraintLayout) as ViewGroup
        viewGroup.layoutTransition.setAnimateParentHierarchy(false)
     }
}

A: I had the second error when used viewPager2.
As commented above, in my fragment layout I found viewGroup with animateLayoutChanges="true", then in fragment OnViewCreated I called
viewGroup.getLayoutTransition().setAnimateParentHierarchy(false);

That's fix my problem!

A: You need to perform this on each of your pages/Fragments
 View view = layoutInflater.inflate(R.layout.page, parent, false);
 ViewGroup viewGroup = view.findViewById(R.id.animated_viewgroup);
 viewGroup.getLayoutTransition().setAnimateParentHierarchy(false);

As looking at official documentation here
https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2
It states that

If your pages contain LayoutTransitions, then those LayoutTransitions
  must have animateParentHierarchy set to false. Note that if you have a
  ViewGroup with animateLayoutChanges="true" in your layout xml file, a
  LayoutTransition is added automatically to that ViewGroup. You will
  need to manually call
  getLayoutTransition().setAnimateParentHierarchy(false) on that
  ViewGroup after you inflated the xml layout.

same your error log talks about on very first line
Fatal Exception: java.lang.IllegalStateException: Page(s) contain a ViewGroup with a LayoutTransition (or animateLayoutChanges="true"), which interferes with the scrolling animation. Make sure to call getLayoutTransition().setAnimateParentHierarchy(false) on all ViewGroups with a LayoutTransition before an animation is started.


text:
Q: Returning tuple with variable number of elements I'm  experimenting writing a percentile utility in Scala. I was thinking  of writing a class that is initialized with a variable number of Int parameters. For example, a Percentile class initialized with 50,95 means it can compute the 50th percentile and the 95th percentile. The class would roughly look like this:
class PercentileUtil(num: Int*) {
    def collect(value: Int) {
        // Adds to a list
    }

    def compute = {
        // Returns the 50th and 95th percentiles as a tuple
    }
}

How should I define the function compute?

A: I'd return a Map if I were you:
class PercentileUtil(percentiles: Int*) {
  private def nthPercentile[T](n: Int, xs: Seq[T]): Seq[T] = ...
  def compute[T](xs: Seq[T]) = percentiles.map(p => p -> nthPercentile(p, xs)).toMap
}

A: If it has to be a Tuple you can declare the return value to be a Product.
def compute: Product = if(...) (1,2) else ("1", "2", "3")

compute match {
    case (a: Int, b: Int) =>
    case (a: String, b: String, c: String) =>
}

compute.productIterator.foreach(println)

A: You might consider using HLists instead from Miles Sabin's Shapeless library. They also support conversion to and from tuples.


text:
Q: Aligning unequal sized images in a Bootstrap grid I'm using 3 images with unequal dimensions inside a 3 x 4 columns Bootstrap grid:

Which are messing up my layout. What I would like to achieve is this:

What is the correct way to achieve this result via CSS?

Lorem Ipsum

              Autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae.

Dolor Sit Amet

                Autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae.

consetetur sadipscing

                Autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae.

A: you could add a top padding on the boxes with the smallest height while preserving the box-sizing by using the box-sizing property and set it to border-box.This way the inner contents would kind of shrink to the bottom without affecting the outer layour


text:
Q: Catastrophic error with ifort when allocating parametric declared type within a declared type Please consider following code
  module t_test
     implicit none

     type ttt(tsize)
        integer, len :: tsize
        real x(tsize)
     end type ttt

  type :: t_rndom_diameter(t_rsize,t_csize)
      integer, len :: t_rsize,t_csize
      real :: x(t_rsize,t_csize)
     type(ttt(tsize=:)), allocatable :: test_type
  end type t_rndom_diameter

  end module t_test

  program p_test
  USE t_test
  implicit none

  type(t_rndom_diameter(t_rsize=3,t_csize=3)) :: gdad

  allocate(gdad% ttt(tsize=10) ::  gdad % test_type)

  end program

it gives me a catastrophic error without mentioning what the error is:
catastrophic error: **Internal compiler error: segmentation violation signal raised** Please
report this error along with the circumstances in which it occurred in a Software Problem
Report.  Note: File and line given may not be explicit cause of this error.

However, I know what triggers this error, namely: allocate(gdad% ttt(tsize=10) :: gdad% test_type)
What does this mean?
I also tried without gdad, i.e. allocate(gdad% ttt(tsize=10) :: test_type)

A: As usual, an "internal compiler error" relates to a bug in the compiler.  This is something to report to the compiler vendor.
However, in this case it would be a low priority problem: the code you are attempting to compile is invalid.  As noted, the problematic line is
allocate(gdad% ttt(tsize=10) ::  gdad % test_type)

This is invalid because this form of the allocate statement requires a type specifier on the left-hand side.  gdad%ttt(10) is not such a thing.  The correct statement would be
allocate(ttt(tsize=10) ::  gdad % test_type)


text:
Q: windows and osx server behind 1 external ip I have a mac server and a windows server behind and sonicwall with one external ip address.  Currently, all http traffic points to the windows server. I've tried to figure out a way to redirect traffic from a subdomain to my apple server (apple.mysite.com), and even tried to do port changes mysite.com:1919.  I'm able to get to the server site os x server landing page
with the port change method.  Whenever I click a link or try to navigate to mysite.com:1919/mydevices I get a redirect error.
I've even tried this article from sonicwall: sonicwall article
Is there a accepted practice of trying to do this without getting another external ip address?  Can I redirect traffic with the windows server to a mac server?


text:
Q: Differences between "in-bag" and "out-of-bag" empirical risks in the R package "mboost" currently I am using the mboost R-package to estimate some additive models. When using the function gamboost(), you can control the hyper-parameters for boosting by using the option boost_control(). One argument of this option is related to the empirical risk, and there are three alternatives to compute it, "inbag", "oob" and "none". The following is the code I have used:
model <- gamboost(income,
                      data = datafit,
                      control = boost_control(mstop = 10000, nu = 0.1,
                                trace = TRUE),
                      weights = datafit$factor, # from survey design
                      family = QuantReg(tau = 0.05))
My questions are:
1.- I would like to know the differences between using "inbag", "oob" and/or "none" and when it is suggested to use each one.
2.- In the case of "oob", you have the option of introducing an extra vector in oobweights for the out-of-bag weights, how should this vector be? I have seen applications with only 0's and 1's but I have not seen a document about the proportion of 0's and 1's that the vector should have nor if I should also introduce here the weights from the sampling design (A priori, I have introduced this information in the option weights)

A: In-bag (IB) and out-of-bag (OOB) can be easily understood as follows: When we train a model we might choose to train our model using all the data we have available or segment our data such that we have a hold-out set that will not be used during training. Following the training of the learner we use, we now want to have an indication of its performance. If we trained our learner using all the available data, then the error we report is effectively the learner's fit on the training data - this is what we call in-bag. If during training we had a hold-out set, we using the unseen data of the hold-out set to estimate the performance of our learn - this is what we call out-of-bag error. Generally, in-bag error is considered an optimistic indicator of the performance of our learner, it is susceptible to over-fitting and generalises poorly. This is true for any model, boosting-based or not.
Particular to boosting, we train our model iteratively and thus we are prone to over-fitting. Because of this we may want to monitor the performance of our overall ensemble.  This is where the in/out-of-bag error comes into play. In addition, certain loss functions allow the inclusion of weights, i.e. a way to indicate that certain observations should be considered more relevant to our task than others. We should not use weights that equal to $0$, as this would effectively indicate that we fully exclude a particular sample point from any weighted calculations. The OOB weights allow for a different weighting to be used in the OOB sample than one used for the function gradient. Particular to mboost if we set value of the weight vector to $0$ and we do not specify an oobweights vector, then that point is used in the OOB error calculations.
As a general rule: avoid in-bag error measures, they are misleading. I would suggest using out-of-bag errors unless they are some specific reasons not to (e.g. the methodology followed explicitly says that it needs the in-bag error for some computation.) There is an excellent CV thread on: "How can I help ensure testing data does not leak into training data?", it is worth a read if one is interested more on this subject.


text:
Q: How to add multiple ternary operators in html code? Let us consider I am having following code :
It used to apply css class upto red4 , but I need to apply css classes upto red11 and myData is having size , I would like to have that size is dynamic manner.
For eg: Size would be having dynamic number range , 0 - 20 // 0 - 100 // 0 - 10000 etc. color range should depends upon the dynamic size range.
HTML :
<svg><path *ngFor="let item of myData" [attr.class]="item.myColor=='red1'?'red1':item.myColor=='red2'?'red2':item.myColor=='red3'?'red3':item.myColor=='red4'?'red4':null"></path>
</svg>

Here is my css classes :
svg path.red1 {
    cursor: pointer;
    fill: #ffcccc;
}
svg path.red2 {
    cursor: pointer;
    fill: #ffb3b3;
}
svg path.red3 {
    cursor: pointer;
    fill: #ff9999;
}
svg path.red4 {
    cursor: pointer;
    fill: #ff6666;
}
svg path.red5 {
    cursor: pointer;
    fill: #ff4d4d;
}
svg path.red6 {
    cursor: pointer;
    fill: #ff3333;
}
svg path.red7 {
    cursor: pointer;
    fill: #ff1a1a;
}
svg path.red8 {
    cursor: pointer;
    fill: #ff0000;
}
svg path.red9 {
    cursor: pointer;
    fill: #e60000;
}
svg path.red10 {
    cursor: pointer;
    fill: #cc0000;
}
svg path.red11 {
    cursor: pointer;
    fill: #b30000;
}

Here is a typescript code :
export interface DataInterface {
  id: string;
  title: string;
  size: number;
  myColor: string;
  myCheck: string;
  d: string;
  class?: string;
}
myList = [{ "id": "SG-05", "size": 30, }, { "id": "SG-04", "size": 9, }, { "id": "SG-01", "size": 20, }];

myData: DataInterface[] = [
  {
    "id": "SG-01", "size": 20, "myColor": "default", "myCheck": 'false'
  },
  {
    "id": "SG-02",  "size": 20, "myColor": "default", "myCheck": 'false',
  },
  {
    "id": "SG-03", "size": 20, "myColor": "default", "myCheck": 'false',
  },
  {
    "id": "SG-04",  "size": 40, "myColor": "default", "myCheck": 'false',
  },
  {
    "id": "SG-05",  "size": 70, "myColor": "default", "myCheck": 'false',
  },
]

fillColor() {
  for (let i = 0; i < this.myData.length; i++) {
    let myCountry = this.myData[i].id;
    for (let j = 0; j < this.myList.length; j++) {
      if (myCountry === this.myList[j].id) {
        this.myData[i].size = this.myList[j].size;
        if (myCountry === this.myList[j].id && this.myList[j].size <= 0) {
          this.myData[i].myColor = 'red1';
        }
        else if (myCountry === this.myList[j].id && this.myList[j].size <= 10) {
          this.myData[i].myColor = 'red2';
        }
        else if (myCountry === this.myList[j].id && this.myList[j].size <= 20) {
          this.myData[i].myColor = 'red3';
        }
        else if (myCountry === this.myList[j].id && this.myList[j].size <= 30) {
          this.myData[i].myColor = 'red4';
        }
      }
    }
    console.log('$$$$$$$$$$2', this.myData);
  }
}

Any help would be appreciated!
Thank you.

A: also
[ngClass]="item.myColor"

BTW, you can reemplace your function fillColor by
this.myData.forEach((x:any)=>{
  const country=this.myList.find(l=>l.id==x.id)
  if (country)
  {
       x.size=country.size;
       x.myColor='red'+(Math.floor(country.size/10)+1)
  }
})

using forEach and find array's methods

A: Since item.myColor returns color name you can just set
[attr.class] = "item.myColor ? item.myColor : null"


text:
Q: Need assistance with a for loop I'd like to know if there's a way I can have the below code increment the {{routemapnumber}} value by 5 each time it is listed. So the first {{routemapnumber}} value would be 5 then the other would be 10 etc.  I think  a for loop would work but Im having issues with syntax.
route-map RDS_FILTER permit {{routemapnumber}}
 match ip address {{item.aclnumber}}
 set ip next-hop verify-availability 10.4.21.157 1 track {{item.slanumber}}
 set ip next-hop 192.168.2.58
route-map RDS_FILTER permit {{routemapnumber}}
 match ip address 109
 set ip next-hop verify-availability 10.4.21.157 1 track 1
 set ip next-hop 192.168.2.58
route-map RDS_FILTER permit {{routemapnumber}}
 match ip address 108
route-map RDS_FILTER permit {{routemapnumber}}
match ip address 107
 set ip next-hop 192.168.0.2
route-map RDS_FILTER permit {{routemapnumber}

A: if there are not many lines, i would go with hardcoding the increments, for example:
route-map RDS_FILTER permit {{routemapnumber}}
 match ip address
 set ip next-hop verify-availability 10.4.21.157 1 track
 set ip next-hop 192.168.2.58
route-map RDS_FILTER permit {{routemapnumber + 10}}
 match ip address 109
 set ip next-hop verify-availability 10.4.21.157 1 track 1
 set ip next-hop 192.168.2.58
route-map RDS_FILTER permit {{routemapnumber + 15}}
 match ip address 108
route-map RDS_FILTER permit {{routemapnumber + 20}}
match ip address 107
 set ip next-hop 192.168.0.2
route-map RDS_FILTER permit {{routemapnumber + 25}}

if this is not a good option for you, you can add some math logic to the template, by using the set statement to increment the variable, right before you print it with:
{% set routemapnumber = routemapnumber + 5 %}
full example:
route-map RDS_FILTER permit {{routemapnumber}}
 match ip address
 set ip next-hop verify-availability 10.4.21.157 1 track
 set ip next-hop 192.168.2.58
route-map RDS_FILTER permit {% set routemapnumber = routemapnumber + 5 %}{{routemapnumber}}
 match ip address 109
 set ip next-hop verify-availability 10.4.21.157 1 track 1
 set ip next-hop 192.168.2.58
route-map RDS_FILTER permit {% set routemapnumber = routemapnumber + 5 %}{{routemapnumber}}
 match ip address 108
route-map RDS_FILTER permit {% set routemapnumber = routemapnumber + 5 %}{{routemapnumber}}
match ip address 107
 set ip next-hop 192.168.0.2
route-map RDS_FILTER permit {% set routemapnumber = routemapnumber + 5 %}{{routemapnumber}}


text:
Q: problem with nested observables and loading content in angular I'm starting to make my first app in angular using a weather api, in a first loading view I want to make 3 requests by subscribing to observables, all three of type get and each one depends on the following:
1 - Get the list of all states
2 - Get the list of the departments of each state
3 - Obtain the prediction of a department from each random state
The problem I want to face is that, when making different concatenated requests, I don't want to load the table with the data until all the load is finished, but this is making me very difficult since I have tried to put a loading variable at the beginning of the code and another at the end of the for that exists between point 2 and 3 but it does not work as desired.
My code is the following:
general.component.ts:
import { Component, OnInit } from '@angular/core';
import { eltiempoDataService } from 'src/app/services/eltiempo-data.service';
import { weatherGeneralModel } from 'src/app/models/weatherGeneral.model';

@Component({
  selector: 'app-general',
  templateUrl: './general.component.html',
  styleUrls: ['./general.component.css']
})
export class GeneralComponent implements OnInit {

  data_mun: weatherGeneralModel[] = [];
  loading_data: boolean;

  constructor(private eltiempoDataService: eltiempoDataService) {
    this.getRandomMunicipio()
    console.log('finish2')
  }

  ngOnInit() {
  }

  getRandomMunicipio() {
    let provs
    let prov_random: {}
    this.getProvincias().subscribe((data: any[]) => {
      this.loading_data = true;
      provs = data['provincias']
      this.processData(provs)
    })
  }

  processData(provs: any[]){
    for (let prop in provs) {
      this.getMunicipios(provs[prop]['CODPROV']).subscribe((data_municipios) => {
        let object_data_general: weatherGeneralModel = new weatherGeneralModel()
        let local_muni: any[] = data_municipios['municipios']
        var random = Math.floor(Math.random() * local_muni.length);
        let cod_ine_mun = local_muni[random]['CODIGOINE'].toString().substring(0, 5);
        this.getDataMunicipio(provs[prop]['CODPROV'], cod_ine_mun).subscribe((data_predict) => {
          object_data_general.comunidad = provs[prop]['COMUNIDAD_CIUDAD_AUTONOMA']
          object_data_general.provincia = provs[prop]['NOMBRE_PROVINCIA']
          object_data_general.municipio = data_predict['municipio']['NOMBRE']
          object_data_general.pronostico = data_predict['temperaturas']['max'] + '/' + data_predict['temperaturas']['min']
          object_data_general.cod_prov = provs[prop]['CODPROV']
          this.data_mun.push(object_data_general)
        })
      })
    }
    this.loading_data = false;
  }

  getProvincias() {
    return this.eltiempoDataService.getProvincias()
  }

  getMunicipios(cod_prov: string) {
    return this.eltiempoDataService.getMunicipios(cod_prov)
  }

  getDataMunicipio(cod_prov: string, id_muni: string) {
    return this.eltiempoDataService.getDataMunicipio(cod_prov, id_muni)
  }
}

eltiempo-dataService.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class eltiempoDataService {

  constructor(private http: HttpClient) {
    console.log('servicio ElTiempo.net listo')
  }

  getProvincias(){
    return this.http.get('https://www.el-tiempo.net/api/json/v2/provincias')
  }

  getMunicipios(cod_prov:string){
    return this.http.get(`https://www.el-tiempo.net/api/json/v2/provincias/${cod_prov}/municipios`)
  }

  getDataMunicipio(cod_prov:string, id_muni:string){
    return this.http.get(`https://www.el-tiempo.net/api/json/v2/provincias/${cod_prov}/municipios/${id_muni}`)
  }
}

general.component.html:

          #
          Comunidad
          Provincia
          Muicipio
          Prediccion

          {{data.CODPROV}}
          {{data.comunidad}}
          {{data.provincia}}
          {{data.municipio}}
          {{data.pronostico}}

I assume I am not following best practice and would appreciate any help, advice and guidance.
Thank you all

A: Here is StackBlitz Link:
https://stackblitz.com/edit/nested-api-calls-forkjoin?file=src/app/app.component.ts
First I suggest creating interfaces for all your endpoints because it's the power of typescript, you will get a lot of help from your IDE because it knows what kind of data you will be getting.
I exported some of your endpoints interfaces to see how it works:
export interface Municipios {
  breadcrumb: {
    name: string;
    title: string;
    url: string;
  }[];
  codprov: string;
  keywords: string;
  metadescripcion: string;
  municipios: Municipio[];
  provincia: string;
  title: string;
}

and in your service it will be like this.
  getMunicipios(cod_prov: string): Observable<Municipios> {
    return this.http.get<Municipios>(
      `https://www.el-tiempo.net/api/json/v2/provincias/${cod_prov}/municipios`
    );
  }

Second: Services, Interfaces and Classes Naming convention is PascalCase
so eltiempoDataService will be EltiempoDataService
third: since you need data from first array which is result of your first API requests then you can use forkJoin to simply send all requests all together and when they all are ready you can use the answer.
forkJoin: https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin
so here you can create an array which has province and observable of next data you need.
    this.loading_data = true;
    const provinciasGetMunicipiosObservables: {
      province: Province;
      getMunicipios: Observable<Municipios>;
    }[] = [];

    const getDataMunicipioObservables: { // This is for second wave of API Calls
      province: Province;
      municipios: Municipios;
      getDataMunicipio: Observable<DataMunicipio>;
    }[] = [];

    provincias.forEach(province => {
      /***************************
       **** Creating Array of province and  getMunicipios observable
       ***************************/
      provinciasGetMunicipiosObservables.push({
        province,
        getMunicipios: this.getMunicipios(province.CODPROV)
      });
    });

and when your array is ready you can pass it to forkJoin and when result of all of them is ready it will give the answer.
note: because I didn't create an absolute array of observables I needed to map the Observable only so It returns an array of Observables
And pipe inside observable is for mapping answer of that specific Observable and when It had access to province I mapped it inside Answer.
    forkJoin(
      provinciasGetMunicipiosObservables.map(x => {
        return x.getMunicipios.pipe(
          map(y => {
            return {
              province: x.province,
              getMunicipiosAnswer: y
            };
          })
        );
      })
    )
      .pipe(first())
      .subscribe(municipiosArray => {
// Time to send Second Wave of API requests

}

And simply you can repeat the process Just like before.
      .subscribe(municipiosArray => {
        municipiosArray.forEach(municipios => {
          /***************************
           **** Part two of data when we got getMunicipios
           ***************************/
          let local_muni: any[] = municipios.getMunicipiosAnswer.municipios;
          var random = Math.floor(Math.random() * local_muni.length);
          let cod_ine_mun = local_muni[random]["CODIGOINE"]
            .toString()
            .substring(0, 5);
          /***************************
           **** Creating second array for getting getDataMunicipio
           ***************************/
          getDataMunicipioObservables.push({
            municipios: municipios.getMunicipiosAnswer,
            province: municipios.province,
            getDataMunicipio: this.getDataMunicipio(
              municipios.province.CODPROV,
              cod_ine_mun
            )
          });
        });
          /***************************
           **** Send Requests with forkJoin
           ***************************/
        forkJoin(
          getDataMunicipioObservables.map(x => {
            return x.getDataMunicipio.pipe(
              map(y => {
                return {
                  province: x.province,
                  municipios: x.municipios,
                  getDataMunicipioAnswer: y
                };
              })
            );
          })
        ).subscribe(arrayOfFinalData => {
          // temproray array
          const finalData: WeatherGeneral[] = [];
          arrayOfFinalData.forEach(weatherData => {
            const max = weatherData.getDataMunicipioAnswer.temperaturas.max;
            const min = weatherData.getDataMunicipioAnswer.temperaturas.min;
            const pronostico = `${max}/${min}`;
            const weatherGeneral = new WeatherGeneral({
              cod_prov: weatherData.province.CODPROV,
              comunidad: weatherData.province.COMUNIDAD_CIUDAD_AUTONOMA,
              municipio: weatherData.getDataMunicipioAnswer.municipio.NOMBRE,
              pronostico,
              provincia: weatherData.province.NOMBRE_PROVINCIA
            });
            finalData.push(weatherGeneral);
          });
           this.loading_data = false;
          this.data_mun = [...finalData];
        });
      });

And feel free to ask if something was unclear.


text:
Q: java.io.FileNotFoundException I am trying to web scrape some data so that I can use it in my application.
The site I am trying to get data off is yahoo but I am getting a FileNotFoundException when it's trying to stream the data in.
I have also set the IP address and port explicitly.
Would be really thankful if someone can tell me where I am going wrong.
I have posted the sample code as well.
parentUrl = "http://www.yahoo.com";
pageUrl = new URL(parentUrl);
System.out.println(parentUrl);

try {
    in = new BufferedReader(new InputStreamReader(pageUrl.openStream()));
} catch(Exception ex2) {
    ex2.printStackTrace();
}

while ((inputLine = in.readLine()) != null) {
    out.write(inputLine);
    in.close();
}

out.close();

A: The problem is in the initialization of out. You haven't shown us that code, but it will be something like:
OutputStream out = new FileOutputStream("non/existent/path/somefilename");

It's probably due to you using a relative path, so to help you debug it, I recommend you change it to:
File file = new File("non/existent/path/somefilename");
System.out.println(file.getAbsolutePath()); // start with this simple debugging
OutputStream out = new FileOutputStream(file);

My guess is that the path of the file is not where you think it is.


text:
Q: Parse.com beforeDelete function failing with "success/error was not called" This is not going to be the best parse.com question out there, but it's the first time I write something in javascript and I can't figure out what's wrong.
In my db I have ParsePosts, ParseUsers and ParseComments. When I delete a post, I want the following to be done:

*

*Task 1: find the user who wrote the post, and decrement his "posts" counter;

*Task 2: delete all ParseComments that were related to the post to-be-deleted;

*Task 3: find user who "liked" the post, and decrement their "likes" counter.

I'm trying as follows (renaming some variables so there might be typos):
Parse.Cloud.beforeDelete("ParsePost", function(request,response) {
  var post = request.object;
  var user = post.get("author");
  user.increment("posts",-1);
  user.save().then(function(success) {

    var query = new Parse.Query("ParseComment");
    query.equalTo("post",post);
    return query.find();

  }).then(function(comments) {
    for (var i = 0; i < comments.length; i++) {
      var comment = comments[i];
      comment.destroy();
    }

    var query2 = new Parse.Query("ParseUser");
    query2.equalTo("postsLiked",post); //"postsLiked" is a relation field
    return query2.find();

  }).then(function(users) {
    for (var i = 0; i < users.length; i++) {
      var u = users[i];
      u.increment("postsLikedCount",-1);
      u.save();
    }
    response.success();
  });
});

However, deleting fails with the message: Result: success/error was not called. I have no idea why.
The way I dealt with promises, as far as I understood (not much), should call the next then() even if there's an error in one of the steps before. In other words, the three tasks are not really consequential - I'd like the function to:

*

*try to accomplish each task;

*call success() no matter the output of the tasks: I want the post to be deleted even if, say, comments.length == 0.

How should I accomplish that, and why my function is not reaching response.success()?
As a side note, I haven't even found a way to debug - I use parse deploy and then look at the logs section in parse.com, but I can't manage to write anything into it. Namely, console.log() gives no output.

A: One of your promises is throwing an error, and you do not have any .then()'s that catch that error.  .then() either takes 1 or 2 arguments, both of which are functions. If there is only 1, it takes the resolved value of a promise. If there are 2, the second one takes the rejected value of a promise.  One of your promises is being rejected, but the promise is never being caught. Add this to the end of your chain:
.then( function(){},
        function(error)
        {
             response.error("There was an error: " + error.message);
        }
    );

Rejected promises skip any link in the promise chain that does not contain an error handler, so having this one link at the end will catch any error from earlier links. Even if you call response.success() and don't return a promise, the success function of the next chain will be called. You just won't be passing anything in to the variable, so it'll be null/undefined
Edit - Looking at your code, I bet it's going to be an issue pretty early on. You never fetched the user, so it's just an empty object with nothing but an object id right now.
Edit2 - Also, query.find() only returns the first 1000 results. If you want to do something to every single object, you should be using query.each().


text:
Q: Group and count unique values in Python pandas dataframe I have a dataframe of over 33,000 rows which I'd like to simplify:
                   Crime type
GeographyCode
E01006687          Burglary
E01007229          Anti-social behaviour
E01007229          Anti-social behaviour
E01007229          Anti-social behaviour
E01007229          Burglary
E01007229          Other theft
E01007229          Other theft
E01007229          Shoplifting
E01007229          Theft from the person
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
...

There are 207 unique values of 'GeographyCode' and 12 unique values of 'Crime type'.
I'd like to make a new dataframe which has 207 rows and 12 columns plus the 'GeographyCode' index column, with each column representing a crime type, and containing a count of all occurances of that crime type within the GeographyCode.
Something like this:
                Burglary   Anti-social    Theft   Shoplifting   etc...
GeographyCode
E01006687       1          3              9       5             ...
E01007229       1          3              2       1             ...
E01007230       0          6              12      5             ...
...

I've tried a few things, but because there are no numeric values I'm finding it really difficult to get what I need.

A: You could use crosstab to compute this:
>>> pd.crosstab(df.index, df['Crime type'])
Crime type      Anti-social behaviour  Burglary  Other theft  Shoplifting  ...

E01006687                           0         1            0            0
E01007229                           3         1            2            1
E01007230                           6         0            0            0


text:
Q: X & Y coordinates of the main UIView are not 0,0 in interface builder
Possible Duplicate:
Storyboard weird controller view frame origins

in the following screenshot, the main view's X & Y coordinates are supposed to be 0,0 (because it's simply the main view that sticks by default to screen bounds) why do they appear as 160, 294 ?

A: See this Screenshot you can get the answer from this screenshot


text:
Q: finding the zeros of a polynomial that have irrational zeros $x^3-5x^2+x+8=0$
I know that the zeros are approx. $-1.07$, $1.72$, and $4.34$ by looking by using a graphing calculator, but how do I find the zeros without? Rational roots theorem does not work here!

A: Use the bisection-method or the newton-method.
Also possible is the regula falsi.
Idea of the bisection-method :
Let a and b be numbers, such that f(a) < 0 and f(b) > 0 or vice versa.
Then, take m := $\frac{a+b}{2}$.
If f(m)=0, you are done. Otherwise choose a or b, such that the signs differ
and continue the process.
The newton-method iterates as follows :
$$x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}\ ,$$
with some starting value $x_0$
Regula falsi is similar, but uses
$$\frac{f(b)-f(a)}{b-a}$$
instead of f '(x).
Here a,b are numbers with f(a) < 0 and f(b) > 0 or vice versa.
Regula falsi does not need the derivates, but converges slightly slower than
the newton-method.

A: As you note, there is no rational root. I'm afraid you have to either use a numerical approximation or use the general solution of cubic. There are many methods to find the general solution in closed form. Take a look at http://en.wikipedia.org/wiki/Cubic_function

A: To count the number of roots in a given interval, we can use the Sturm Sequence.
The Sturm Sequence for $f(x)=x^3-5x^2+x+8$ is the sequence of polynomals
$$
x^3-5x^2+x+8\\
3x^2-10x+1\\
\frac{44}{9}x-\frac{77}{9}\\
\frac{117}{16}
$$
If $N(x)$ is the number of sign changes in the Sturm Sequence at $x$, then for $a<b$, $N(a)-N(b)$ is the number of real roots of $f$ in $(a,b)$.
As $x\to-\infty$, the signs are "$-,+,-,+$"; that is, three sign changes: $N(-\infty)=3$.
At $x=0$, the signs are "$+,+,-,+$"; that is, two sign changes: $N(0)=2$.
As $x\to+\infty$, the signs are "$+,+,+,+$"; that is, no sign changes: $N(+\infty)=0$.
Thus, there are three real roots of $f$, one negatve and two positive.
We can use the Sturm Sequence to find intervals with a single root, then use bisection or Newton to find that root.


text:
Q: Remove repetition in jQuery? I have a few select menus on a page:I pass the selected value to a hidden input type with jQuery. In total I have 4 but is there a way I could just use on function which targets the select menu being used and passes the value accordingly. I've used the same 'format' for IDs and vars so I reckon it can be done. Thanks.
Below is just a chunk of what I using at the moment. It works as expected but surely there must be a way to use just one function?
jq('#stateSelect').change(function() {
    var myState = jq(this).val();
    jq('#stateChosen').val(myState);
    console.log(myState);
  });

  jq('#countySelect').change(function() {
    var myCounty = jq(this).val();
    jq('#countyChosen').val(myCounty);
    console.log(myCounty);
  });

  jq('#genderSelect').change(function() {
    var myGender = jq(this).val();
    jq('#genderChosen').val(myGender);
    console.log(myGender);
  });

  jq('#whoamiSelect').change(function() {
    var myWhoami = jq(this).val();
    jq('#whoamiChosen').val(myWhoami);
    console.log(myGender);
  });

A: Use .data()

*

*Apply a common class to select elements as commonSelect

*Apply different data-flag same as id of hidden inputs.

Code Example
$('.commonSelect').change(function() {
    var hiddenId = $(this).data('flag');
    $('#'+hiddenId).val($(this).val());
});

$('.commonSelect').change(function() {
    var hiddenId = $(this).data('flag');
    $('#'+hiddenId).val($(this).val());
});

<select data-flag="asdf" class="commonSelect">
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="asdf" />

<select data-flag="qwerty" class="commonSelect">
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="qwerty" />

A: You could build a general function, but you might need to also adapt your html.
Html sample:
<select class="jqSelect" id="state">...</select>
<input type="text" name="stateChosen" id="stateChosen" value="" />

And the script:
  jq('.jqSelect').change(function() {
    var myValue = jq(this).val();
    var myId = jq(this).attr('id');
    jq('#'+myId+'Chosen').val(myValue);
  });

A: To clarify, you want to use the same Jquery function to get data from a variety of select boxes, correct? If so, I would give all selectors a class ('You could also use input selectors)
So if you give all checkboxes a class of selector, and keep your ID so you know what is selected
You could do something like
 $('.selector).on('change, function(){
    active_selector = $(this).attr('id')
    value = $(this).val()

  });

A: You can use a for loop, data attributes, structure of the html, or countless other options.
For Loop  not the best solution, but works

["a","b"].forEach( function(val){
    $("#" + val + "Select").on("change", function() {
       $("#" + val + "Chosen").val($(this).val());
    }).trigger("change");
});

<select id="aSelect">
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="aChosen" />

<select id="bSelect">
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="bChosen" />

Data Attribute
A better solution since it uses a hard coded reference that will not change.

$("select[data-for]").on("change", function() {
    var sel = $(this);
    var txt = sel.data("for");
    $(txt).val(sel.val());
}).trigger("change");

<select data-for="#asdf">
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="asdf" />

<select data-for="#qwerty">
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="qwerty" />

HTML Structure
I have no idea what your structure is, but you could just use a relationship with selecting. This way is not great since it would break if your html structure changes.

$("select").on("change", function() {
    var sel = $(this);
    sel.next("input").val(sel.val());
}).trigger("change");

<select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="asdf" />

<select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="qwerty" />

Parse the id
You can easily strip the "Select" off the string and replace it with "Chosen" to build your selector to pick the textbox.

$("select[id$='Select']").on("change", function(){
   var sel = $(this);
   var prefix = this.id.replace(/Select$/,"");
   $("#" + prefix + "Chosen").val(sel.val());
}).trigger("change");

<select id="aSelect">
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="aChosen" />

<select id="bSelect">
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
</select>
<input id="bChosen" />

As I stated, there are a bunch of ways to do it and I am sure there are a bunch more.


text:
Q: (Select query) como deixar mais dinâmico? Tenho o seguinte método select na minha classe CRUD e utilizo ele em toda a aplicação, porem preciso deixar ele mais dinâmico, por exemplo preciso usar um ORDER BY, também utilizar outros campos diferente do $user_id, alguma dica?
//Select on database
public function select($where = null, $user_id, $fields = '*')
{
    if($where != null){
        $where = " WHERE ";
    }

    $query  = "SELECT {$fields} FROM `{$this->table}` {$where} `user_id`=:user_id ORDER BY id DESC";
    $stmt   = $this->db->prepare($query);
    $stmt->bindValue(":user_id", $user_id);
    $stmt->execute();
    return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}

A: Eu faço desta forma utilizando PDO:
/** @var PDO */
private static $connect = null;

/**
 * Conecta com o banco de dados com o pattern singleton
 * Retorna um objeto PDO!
 */
private static function Conectar(){

    try {

        Setup::checkLocal();

        if(self::$connect == null) {
            $dsn = 'mysql:host='.Setup::$host.';dbname='.Setup::$base;
            $options = [ PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8" ];
            self::$connect = new PDO($dsn, Setup::$user, Setup::$pass, $options);
        }

    } catch (PDOException $e) {
        echo 'PDOException: erro ao conectar ao banco de dados.';
        //PHPErro($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
        die;
    }

    self::$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //self::$connect->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);

    return self::$connect;
}

/** Retorna um objeto PDO Singleton Pattern */
public static function getConn(){
    return self::Conectar();
}

public static function prepareQuery($query, $params){

    $preparedQuery = self::getConn()->prepare($query);
    foreach ($params as $key => $value) {
        $preparedQuery->bindValue($key, $value);
    }

    $preparedQuery->execute();
    $result = $preparedQuery->fetchAll(PDO::FETCH_OBJ);

    self::$connect = null;

    return $result;
}

E costumo acessar desta forma:
$qrSelect = "SELECT campo1, campo2 FROM tabela WHERE campo1 = :campo1 ORDER BY campo1 ASC";

$params = [":campo1" => $valor];
$retorno = Conexao::prepareQuery($qrSelect, $params);

Eu sempre passo a query inteira. O que muda sempre são os parâmetros. Eu não vejo muito ganho em economizar as palavras select e from na hora de chamar o método select, se para compensar você terá q passar vários parâmetros e fazer outras validações.