text:
Q: Not getting expected results from complex view This is a somewhat involved question as the data I am working with is a little large.
I have the following document structure: https://gist.github.com/gaigepr/5b28a7c67ced0cd71e4e
and the following map function: https://gist.github.com/gaigepr/a721bcc8ef6f681f3807
A little description, this function goes through the example document to collect a list of all combinations of characters from 1 to 5 and supplies them with a 1 or 0 to indicate a win or a loss for that particular combo of characters. This is accomplished by getting the powerset of the team and ignoring the empty set when emitting the array key and integer to indicate a win or loss.
The problem I am having is with reducing the data. My goal is to get the win rate of a particular group of characters in the game this data is from. the view takes a key formatted as such: [1] and should output the win rate and games played by that pair of characters.
so my reduce function should be something like this:

However when I do this, I do not actually get all the games played by that pair in the reduction. in my test database, I have 96 games played by the above pair [1, 18] but when I run map and reduce on the with that key, I get that there were only 2 games played and null for the win rate.
A note: This seems to only happen inconsistently. With my data, when I query with the key [1, 18] I get accurate results.

I am a little bit at a loss for what to do to debug this and would appreciate some help. I am happy to add more details, gists, even pictures of the futon output if that would be helpful.
I do not have a lot of reason for this yet, or confirmation, but it seems that the data passed to the reduce function is not formatted how I expect it to be but I am not sure why that is.


text:
Q: merge 3 files with awk in linux following problem: (similar to one last question)
I tried `
 awk 'FNR==NR {a[NR]=$0;next} {print a[1]","c[1]", "$0}' file1 file2 file3

but does not work
FILE1:
line1
line2
line3

and FILE2:
date1

and FILE3:
TITEL1

Result should be date1 merged to each line of file1.
So result:
line1, date1, TITEL1
line2, date1, TITEL1
line3, date1, TITEL1

Thanks

A: Input
[akshay@localhost tmp]$ cat f1
line1
line2
line3

[akshay@localhost tmp]$ cat f2
date1

[akshay@localhost tmp]$ cat f3
TITEL1

Output
[akshay@localhost tmp]$ awk 'FNR==1{i++}i<3{A[i,1]=$0;next}{print $0,A[1,1],A[2,1]}' OFS=', ' f2 f3 f1
line1, date1, TITEL1
line2, date1, TITEL1
line3, date1, TITEL1

redpajama_set_name: RedPajamaStackExchange


text:
Q: php mysql for loop in my query i want only from id 1-3 to appear in the result, not 4-6.  is there any other way to do it?
beautician database table:
id_beautician   name
1               a
2               b
3               c
4               d
5               e
6               f

i tried to put the code below in mysql query
for($i=4; $i<=6; $i++) :
    $q.$i = $db->query("SELECT * FROM beautician WHERE id_beautician='$i'");
    $r.$i = $q.$i->fetch_assoc();
    //echo $i;
endfor;

but it gives me an error:

Object of class mysqli_result could
  not be converted to string

A: Instead of doing n queries, modify SQL query to match only data you need - for example:
$query = $db->query("SELECT * FROM beautician WHERE id_beautician <= 3");
while ( $row = $query->fetch_assoc() ) {
    echo $row['id'] . ' = ' . $row['name'] . '
';
}

A: If ids are not in sequence, you can also use as below.
$query = $db->query("SELECT * FROM beautician WHERE id_beautician in (1,2,3)");
while ( $row = $query->fetch_assoc() )
{
    echo $row['id'] . ' = ' . $row['name'] . '
';
}

using IN in query sometimes slow down the execution, but can be used efficiently for small-size database.


text:
Q: Wix navigation library module does not add to my project with running npm install --save react-native-navigation I am trying to add Wix navigation library to my project according to  https://wix.github.io/react-native-navigation/#/docs/Installing but when i run the npm install --save react-native-navigation command in terminal and then i open my android project in android studio, i don't see any library module for navigation in my project. But the name of react-native-navigation will appear in package.json file.
here is my package.json file:
      {
  "name": "PleaseAnswer",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.6.3",
    "react-native": "0.57.8",
    "react-native-navigation": "^2.5.0"
  },
  "devDependencies": {
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.51.1",
    "react-test-renderer": "16.6.3"
  },
  "jest": {
    "preset": "react-native"
  }
}

A: *

*Android:
if you're using V2 version than react-native link won't automatically link your package to android. I would recommend you to follow docs https://wix.github.io/react-native-navigation/#/docs/Installing

*iOS: I recommend you to use cocoapods for iOS configuration Add pod 'ReactNativeNavigation', :path => '../node_modules/react-native-navigation' in your podfile and run pod install


text:
Q: Collection contains object but cannot remove it I have a class that holds several collections and I'm having problems removing some of the objects from one of the collections.  If I call collection.contains(object) it returns true then on the next line I call collection.remove(object) and the object doesn't get removed.
This is the original code that didn't work.  All of the collections are SortedSets.  What confused me here was that the male collection is populated directly from the people collection, but when you try to remove the male objects from the people collections not all of them will be removed.
    for(Person person : peopleBin.getPeople())
    {
        if(person.isMale())
        {
            peopleBin.getMen().add(person);
        }
    }
    peopleBin.getPeople().removeAll(peopleBin.getMen());

Person has an equals method like this
public boolean equals( Object obj )
{
    if ( obj == null )
        return false;
    if ( !(obj instanceof Person) )
        return false;
    Person that = (Person)obj;
    return
        that.age == age &&
        that.id == id &&
        that.someCount == someCount ;
}

Now when I replaced the first snippet's removeAll line with this I get strange behavior.
    for(Person person: personBin.getMen())
    {
        if(personBin.getPeople().contains(person))
            personBin.getPeople().remove(person);
    }

if(personBin.getPeople().contains(person))  always returns true, but personBin.getPeople().remove(person) does not always remove.  Sometimes it does and sometimes it doesn't.
I have changed all of the class names and field names to be generic to post in a public forum.
Any help would be greatly appreciated!
edit: here is the compareTo impl
    public int compareTo (Object o)
{
    if ( ! ( o instanceof Person) )
    {
        throw new ClassCastException();
    }

    Person that = (Person)o;

    int comparison = 0;

    return
        ( (comparison = this.age () - that.age ()) != 0 ? comparison :
        ( (comparison = this.id - that.id) != 0 ? comparison :
        ( (comparison = this.someCount - that.someCount ))));
}

edit: here is the hashCode impl
public int hashCode() {
    int result = 31;
    result = 61*result + age;
    result = 61*result + id;
    result = 61*result + someCount;
    return result;
}

A: To remove an item from a colelction , the best way is to use an Iterator to avoid any problem :
replace you loop by this, and try again :
for(Iterator<Person> iterator =  personBin.getMen().iterator();iterator.hasNext();){
            Person person = iterator.next();
            if(personBin.getPeople().contains(person)){
                iterator.remove();
            }
        }


text:
Q: Increment form value I have several images with the class "red".
When the user clicks on any of them, a form field with the Id of "red" should be incremented.
I'm trying to write this in a way that is easy to re-use.
I can't figure out if there is a way of incrementing the form field value without using a global variable. Simply writing
    $(#red).val(++);
doesn't do anything.
If I first declare a global variable like
var redAmount;
$(#red).val(redAmount++);

it works, but I don't like the idea of having to type the color + Amount each time I re-use this for other colors.
Which made me try to form the variable name dynamically like
var redAmount;
var currentColor = $(obj).attr("class"); //getting the class of the clicked element
$('#' + currentColor).val(currentColor+'Amount'++); //trying to form the variable name dynamically but failing

Sorry for the long explanation. What I'm trying to ask is this:

*

*Can I increment the form value without a global variable

*If not, how do I form the variable name dynamically based on the class of the clicked element

A: You can do this with the increment operator in plain-old JavaScript:
document.getElementById("red").value++;

jsFiddle

A: Code revised with tested sample.
http://jsfiddle.net/webwarrior/CrjY9/25/
Are you not trying to increment the value of item you are clicking on?
jQuery("img").click(function () {
    jQuery("#" + jQuery(this).attr("class"))[0].value++;
});

Hope this helps.
This is the true JQuery way, but I guess the JavaScript value++ way is just as good, in some browsers.


text:
Q: Boxes overlap each other so I got a while loop display the names and some css and jquery to make it so when you hover over one of the boxes made in the while loop it will have a little description telling about that result scroll up. But the problem is all the description boxes are overlapping each other. What am I doing wrong?
Css
  .App_display {
        border: 2px solid black;
    padding:30px;
    background:white;
    border-radius:25px;
    float:left;
    width:190px;
    height:100px;
    margin:10px;
 }

.boxTop { position:absolute; z-index:9; top:0; left:0; height:inherit; width:inherit;
          overflow:hidden;}
.description { position:absolute; bottom:-50px; height:40px; width:459px; background-color:#000; opacity:.7; font-size:16px; color:#fff; padding:10px; }

Jquery

Html(This code is generated in a while loop)

<?php echo $name; ?>

  .App_display {
        border: 2px solid black;
    padding:30px;
    background:white;
    border-radius:25px;
    float:left;
    width:190px;
    height:100px;
    margin:10px;
 }

.boxTop { position:absolute; z-index:9; top:0; left:0; height:inherit; width:inherit;
          overflow:hidden;}
.description { position:absolute; bottom:-50px; height:40px; width:459px; background-color:#000; opacity:.7; font-size:16px; color:#fff; padding:10px; }

Item1

Item2

A: in css when you use position absolute it will set the position of the element relative to the first non static ancestor element, in your case probably the window.
so you need to set the next ancestor to a non static position then it will fix your issue
add to your App_display class this line:
 .App_display {
        position:relative;
 }


text:
Q: Extract correct counter value of a reference Somewhere in my document there is a theorem labelled theoremA that has the number 2.21. Later, I want to set another counter to that specific number 21.
First, I tried \setcounterref{newcounter}{reference} which does not work as I expected it to: theoremA has the counter value 2.21 and \setcounterref sets newcounter to 2 instead of 21.
To fix this, I tried \setcounter{theorem}{\StrBehind{\getrefnumber{orbitcomeagre}}{.}} which yields the error Missing number, treated as zeroeven though \StrBehind{\getrefnumber{orbitcomeagre}}{.}has the correct value of 21.
Does anyone have any suggestions how I can fix this?

A: Maybe I'm missing an important complication, but I think all you need to do is (a) define a "scratch" counter variable named, say, scratchcounter, in the preamble and (b) use an instruction such as
\setcounter{scratchcounter}{\value{theorem}}

immediately after the theorem in question to store the number of the theorem (minus the "prefix") in the counter named scratchcounter. Its value may be accessed elsewhere in the document via \thescratchcounter.

\documentclass{article}
\usepackage{amsthm} % or: "\usepackage{ntheorem}"
\newtheorem{theorem}{Theorem}[section]

\newcounter{scratchcounter} % define the scratch counter

\begin{document}
\setcounter{section}{2}   % just for this example
\setcounter{theorem}{20}

\begin{theorem}[Pythagoras] \label{thm:pyth}
$a^2+b^2=c^2$.
\end{theorem}
\setcounter{scratchcounter}{\value{theorem}} % Store value of 'theorem' counter

\bigskip\noindent
Later on \dots\ the value of the ``scratch'' counter is \thescratchcounter.
\end{document}

A: The idea of \StrBehind is good, but you have to use it in a different way.
\StrBehind{\getrefnumber{orbitcomeagre}}{.}[\orbitcomeagrenumber]
\setcounter{theorem}{0\orbitcomeagrenumber}

The 0 is for avoiding issues when the reference is not yet defined and \StrBehind would output nothing.
\documentclass{article}

\usepackage{xstring,refcount}

\newtheorem{theorem}{Theorem}[section]
\newcounter{mycount}

\begin{document}

\setcounter{section}{1}
\section{A section}

\setcounter{theorem}{20}

\begin{theorem}\label{orbitcomeagre}
A theorem.
\end{theorem}

See Theorem~\ref{orbitcomeagre}.

\StrBehind{\getrefnumber{orbitcomeagre}}{.}[\orbitcomeagrenumber]
\setcounter{mycount}{0\orbitcomeagrenumber}

See Theorem~\themycount.

\end{document}

An "abstract" version:
\documentclass{article}

\usepackage{xstring,refcount}

\newtheorem{theorem}{Theorem}[section]

\newcounter{mycount}

\newcommand{\setcountertoref}[2]{%
  \begingroup
  \StrBehind{\getrefnumber{#2}}{.}[\setcountertoreftemp]%
  \setcounter{#1}{0\setcountertoreftemp}%
  \endgroup
}

\begin{document}

\setcounter{section}{1}
\section{A section}

\setcounter{theorem}{20}

\begin{theorem}\label{orbitcomeagre}
A theorem.
\end{theorem}

See Theorem~\ref{orbitcomeagre}.

\setcountertoref{mycount}{orbitcomeagre}

See Theorem~\themycount.

\end{document}

A: The following solution implements \extractthmnum{<cnt>}{<ref>} in a similar way to refcount's \setcounterref:

\documentclass{article}

\newtheorem{theorem}{Theorem}[section]
\newcounter{mycount}

\makeatletter
\def\@extractthmnum#1.#2{#2}
\newcommand{\extractthmnum}[2]{% \extractthmnum{<cnt>}{<ref>}
  \setcounter{#1}{0}% Default
  \ifcsname r@#2\endcsname
    \edef\@tempa{\csname r@#2\endcsname}% Extract complete reference
    \edef\@tempa{\expandafter\@firstoftwo\@tempa}% Extract number
    \setcounter{#1}{\expandafter\@extractthmnum\@tempa}% Strip number
  \fi
}
\makeatother

\begin{document}

\setcounter{section}{1}
\section{A section}

\setcounter{theorem}{20}
\begin{theorem}\label{thm:theorem}
A theorem.
\end{theorem}

See Theorem~\ref{thm:theorem}.

\extractthmnum{mycount}{thm:theorem}%
See Theorem~\themycount.

\end{document}


text:
Q: HeaderText vs Design Name of Column in DataGrid I have the following code which works fine, but it gets the design name (DataGridViewTextBoxColumn11) of my column instead of the header text. How can I alter my code to get the header text on my column instead of the design name?
For Each row As DataGridViewRow In grdTransaction.Rows
            If grdTransaction.Item("DataGridViewTextBoxColumn11", row.Index).Value IsNot Nothing Then
                If grdTransaction("DataGridViewTextBoxColumn11", row.Index).Value.Equals(DBNull.Value) Then
                    row.DefaultCellStyle.BackColor = Color.Red
                End If
            End If
        Next

A: My convention for this kind of thing is to name the item as the database column name prefixed by dgc (DataGridColumn).  Thus the heading is 'Customer Name' and the columnname is 'dgcCustomerName'.  If you have more than one datagrid on the form or user control, and you have (for instance) CustomerId in columns in both grids, naming them the same creates a conflict.  dgcCustomerId is an object in the container namespace, allowing you to get property settings from it without having to specify the grid membership first.  That being the case, in the second grid you might have to call the column 'dgcInvoiceCustomerId' or 'dgcLineItemCustomerId'.

A: Create a function to return the column index from the DGV from supplied column header text:
Private Function getColID(ByVal colHeaderText As String) As Integer
    Dim result As Integer = -1
    For Each col As DataGridViewColumn In grdTransaction.Columns
        If col.HeaderText = colHeaderText Then
            result = col.Index
            Exit For
        End If
    Next
    return result
End Function

then in your code:
For Each row As DataGridViewRow In grdTransaction.Rows
            If grdTransaction.Item(getColID("header text"), row.Index).Value IsNot Nothing Then
                If grdTransaction(getColID("header text"), row.Index).Value.Equals(DBNull.Value) Then
                    row.DefaultCellStyle.BackColor = Color.Red
                End If
            End If
        Next

or this little change:
For Each row As DataGridViewRow In grdTransaction.Rows
            If row.cells(getColID("header text")).Value IsNot Nothing Then
                If row.cells(getColID("header text")).Value.Equals(DBNull.Value) Then
                    row.DefaultCellStyle.BackColor = Color.Red
                End If
            End If
        Next

A: I think this is simple ..
For Each row As DataGridViewRow In grdTransaction.Rows

    If Not IsDBNull(row.cells("column_name").Value) Then

        row.DefaultCellStyle.BackColor = Color.Red

    End If

 Next


text:
Q: How to Install Azure Artifacts Packages dependencies in Vs Code? How to Install the Azure Artifacts Packages in VS Code, I tried to check the Connect to feed option and found there are multiple Nuget options like Dotnet, Nuget.exe, and Visual Studio, etc.
But when I am trying for VS Code then it's not working.
What I did so far in the VS Code?
1 Approach) I install the NuGet package manager and when I am trying to do search my package then it's not showing in the list. but using this command "Get-PackageSource" I am able to see the package in the console.
2 Approach) I created one nuget.config file and mentioned below the package details
'<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="test@Release" value="https://xxxxxxx.pkgs.visualstudio.com/_packaging/test/nuget/v3/index.json" />
  </packageSources>
</configuration>'

after that running NuGet restore command and below giving the output but I didn't see any dependencies in the project and the same thing working fine using Visual Studio 2017
NuGet Config files used:
 C:\Users\sudhir\source\repos\testPrivateNugetFeed\NuGet.Config
    C:\Users\sudhir\AppData\Roaming\NuGet\NuGet.Config
    C:\Program Files (x86)\NuGet\Config\Microsoft.VisualStudio.Offline.config
    C:\Program Files (x86)\NuGet\Config\Xamarin.Offline.config

Feeds used:
`https://XXXXX.pkgs.visualstudio.com/_packaging/test/nuget/v3/index.json'
All projects are up-to-date for restore.
I have also followed this thread
Add custom package source to Visual Studio Code
Please give me some solution.

A:
How to Install Azure Artifacts Packages dependencies in Vs Code?

I could reproduce this issue on my side, it seems to be a limitation of the NuGet package manager extension or Visual Studio Code.
No matter how I set up my Nuget.config file, I could not see the custom nuget package from the Azure devops feed in the NuGet package manager extension. I also test any other extension like NuGet Gallery, but not success.
To resolve this issue, I add following nuget.config file in my project, which next to my .sln file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="AzureDevOpsFeed" value="https://pkgs.dev.azure.com/<MyORGName>/_packaging/<MyFeedName>/nuget/v3/index.json" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>

  <config>

</config>

  <packageSourceCredentials>
    <AzureDevOpsFeed>
      <add key="Username" value="LeoTest" />
      <add key="ClearTextPassword" value="My PAT Here" />
    </AzureDevOpsFeed>
  </packageSourceCredentials>

</configuration>

And add following in my packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="LibA" version="1.0.0" targetFramework="net461" />
</packages>

The LibA is a custom package in my Azure decops feed:

Then I use nuget.exe to restore the package for my project:

If nuget restore not work for you, please share the log for that command.


text:
Q: Fetch row from tableview on Button click in same row JavaFX I have created a TableView in JavaFX it contains two columns :

*

*First Row (Roll): It contains roll no. of student

*Second Row (Details): It contains a Button which when clicked prints "Roll" of corresponding row.

My Approach is:
    static ObservableList<Student> list= FXCollections.observableArrayList();
    static ObservableList<Student> getStudentList() throws SQLException {
        con = ConnectionUtil.getDataBaseConnection();

        String SQL = "Select * from student;";
            ResultSet rs = con.createStatement().executeQuery(SQL);
            while(rs.next()){
              //Student cm = new Student(rs.getInt("rno"), rs.getString("name"),false);
                Student cm = new Student();
                cm.setFullName(rs.getString("name"));
                cm.setRoll(rs.getString("rno"));
                cm.setSingle(false);
              list.add(cm);
            }
      return list;
    }

    static TableColumn<Student, String> rollCol = new TableColumn<Student, String>("Roll");

    static TableColumn<Student, Void> viewCol = new TableColumn<Student, Void>("Details");

      static TableColumn<Student, Void>  addButtonToTable() {
        //TableColumn<Student, Void> viewCol = new TableColumn("Button Column");

        Callback<TableColumn<Student, Void>, TableCell<Student, Void>> cellFactory = new Callback<TableColumn<Student, Void>, TableCell<Student, Void>>() {
            @Override
            public TableCell<Student, Void> call(final TableColumn<Student, Void> param) {
                final TableCell<Student, Void> cell = new TableCell<Student, Void>() {

                    private final Button btn = new Button("View");

                    {

                        btn.setOnAction((ActionEvent event) -> {

                            /////////////////WORK START FROM HERE
                            static Student stu=tables.getItems();

                            String res = (stu.getRollNo().toString());

                            System.out.println(res);
                        });
                    }

                    @Override
                    public void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(btn);
                        }
                    }
                };
                return cell;
            }
        };

        viewCol.setCellFactory(cellFactory);

        return viewCol;
    }
    public String getRollNo() {
        return rollNo;
    }
    public void setRoll(String rollNo) {
        this.rollNo = rollNo;
    }

Problem with me:

*

*My Table shows both columns well

*But it doesn't prints the "Roll" in the output.

Please tell me how can I do this...
Thanks in advance

A: static is not allowed for declarations of local variables and TableView.getItems returns a ObservableList, not Student. Access the Student instance via the TableRow. (If you display all the buttons in a row, not in a column, the required logic would be very different.)
private final Button btn = new Button("View");

{

    btn.setOnAction((ActionEvent event) -> {
        Student stu = getTableRow().getItem();
        String res = stu.getRollNo().toString();
        System.out.println(res);
    });
}

@Override
public void updateItem(Void item, boolean empty) {
    super.updateItem(item, empty);
    setGraphic(empty ? null : btn);
}


text:
Q: remove geolocation radius from google maps api v3 can anyone help me remove the radius on the geolocation marker? The code im using
  var map, GeoMarker;

  function initialize() {
    var mapOptions = {
      zoom: 17,
      center: new google.maps.LatLng(-34.397, 150.644),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
        mapOptions);

    GeoMarker = new GeolocationMarker();
    GeoMarker.setCircleOptions({fillColor: '#808080'});

    google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
      map.setCenter(this.getPosition());
      map.fitBounds(this.getBounds());
    });

    google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
      alert('There was an error obtaining your position. Message: ' + e.message);
    });

    GeoMarker.setMap(map);

I tried removing         GeoMarker.setCircleOptions({fillColor: '#808080'}); but it makes the circle much darker as a  default.
Thanks for any help. (this is using https://www.npmjs.com/package/geolocation-marker plugin for geolocation)

A: If you don't want the circle, you should instead be using a google.maps.Marker instead. here is the link to the Google Maps Javascript API's relevant section on how to do so.

A: If you don't want circle visible, set it's opacity to 0 (and strokeWeight as well)
GeoMarker.setCircleOptions({
  fillOpacity: 0,
  strokeWeight: 0
});

proof of concept fiddle


text:
Q: "Page not found" HTML title when I click the next link of wordpredd blog pagination I have implemented a pagination links at the end of my wordpress blog page. In a one page I have 3 posts and when I click the next link of my pagination links it take me to the next page which contains the next 3 posts.
I retrieve posts from only one category. But when I go to the next page the html title of that page is "Page not found"
My code is like below:
  $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
  $args = array('cat'=> 4, 'posts_per_page' => 3, 'paged' => $paged );
   query_posts($args);
        if(have_posts()) :
         print ('
');
     while (have_posts()) : the_post();
       $excerpt = get_the_excerpt();
              //My post contents
         endwhile;
              if (function_exists("pagination")) {
       pagination();
     }
        print ('
');
       endif;
  }

My pagination function is:
   function pagination() {
  /*
  post: retun the pagination post cout and next previous buttons
  */
       global $paged;
          if(empty($paged)) $paged = 1;
       if($pages == '') {
          global $wp_query;
              $pages = $wp_query->max_num_pages;
              if(!$pages) {
               $pages = 1;
           }
       }
       if(1 != $pages) {
        print('
');
     if ($paged < $pages)
                 echo "NEXT";
       if($paged <= $pages && $paged > 1)
         echo "BACK";
             echo "
Page ".$paged." of ".$pages."
";
              echo "
";
          }
  }

Please help me for this

A: Try this insteatd
<?php
$big = 999999999; // need an unlikely integer

echo paginate_links( array(
    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format' => '?paged=%#%',
    'current' => max( 1, get_query_var('paged') ),
    'total' => $the_query->max_num_pages
) );
?>

A: Try to add this
paginate_links(array(
              'base' => get_pagenum_link(1) . '%_%',
              'format' => 'page/%#%',
              'current' => $current_page,
              'total' => $total_pages,
              'cat' => 4,
            ));

You missed category ID (cat=>4)
also change:
ADMIN PANEL -> SETTING -> READING -> Blog pages show at most : 3
as per $args = array('cat'=> 4, 'posts_per_page' => 3, 'paged' => $paged );


text:
Q: Google Dataproc Presto: how to run queries using Python I have set up a Google Dataproc cluster running Presto by going through the steps in this link.
It works fine and I am able to run queries through gcloud command-line tool as shown on the link like this.
gcloud dataproc jobs submit hive \
    --cluster presto-cluster \
    --region=${REGION} \
    --execute "SELECT COUNT(*) FROM chicago_taxi_trips_parquet;"

In the end, the tutorial shows how to run queries on Presto through a java application. I am trying to find a similar solution with Python. Is there a way I can run queries on the Dataproc cluster through my Python application?
I know there are Python clients for Presto but I was not able to find resources on how to connect it with the Presto running on the Dataproc cluster.
Similarly, there is a Python library to submit jobs to Dataproc, but there are no resources as to how can I submit Presto query jobs to the Dataproc cluster.
Can someone tell me how can we connect to a Presto on Google Dataproc and run queries on it remotely using a Python application?

A: You can find examples how to use Dataproc Jobs API to submit supported jobs (including Presto) in official Dataproc Python client library documentation: https://cloud.google.com/dataproc/docs/tutorials/python-library-example#submit_a_job_to_a_cluster


text:
Q: match the image src with new one if match replace the whole img tag I have tried the above code... but it not working. i just want to change the whole <img> tag with new src and class.. but i down know
what attribute added into the <img> tag... my validation are only
if img src is matched then replace the whole <img> tag with new one...
$match="abc.jpg";
$url ="<img class='descimg' src='111'>";

preg_replace('/<img[^>]*?src=\"'.preg_quote($match).'"',$url,$html);

pls help me
thank you

A: Further to me comment the following preg_replace line should work better. I can't actually tell from your description exactly what you are trying to do. If you included your expected output I will improve my answer as required to fit.
preg_replace('/<img[ ]+src=\"'.preg_quote($match).'"',$url,$html);

I also note that $match does not appear in the your original string and so it is odd that it is part of the regular expression?


text:
Q: Null Sets $\{\{\emptyset\}\} \subset\{\emptyset, \{\emptyset\}\}$ Regarding null sets, I'm wondering if anyone can explain this $\{\{\emptyset\}\} \subset \{\emptyset, \{\emptyset\}\}$ I don't understand how the left set is a proper set of the right set.
In particular, I'm wondering what the extra brace on the left means and how it is different from say just plain $\{\emptyset\}$. It seems if I disregard the outer brace in the left hand set, my answer matches that of the answer key (namely, true).
I'm posting this again because it was in the wrong stackexchange.
Thanks!

A: The only element of $\{\{\varnothing\}\}$ is $\{\varnothing\}$ which is in $\{\varnothing, \{\varnothing\}\}$.
Thus it is a subset...

A: a general rule:
$$
a \in S \Rightarrow \{a\} \subset  S
$$
since, in your example
$$
\{\emptyset\} \in \{\emptyset,\{\emptyset\}\}
$$
the result follows

A: $\{\{\emptyset\}\}$ is a set that has a set containing the empty set as a member.
$\{\emptyset\}$ is a set that has the empty set as a member.
$\{\emptyset,\{\emptyset\}\}$ is a set that has the empty set and a set containing the empty set as members.
Now $\{\{\emptyset\}\}\subset\{\emptyset,\{\emptyset\}\}$ because all the members of $\{\{\emptyset\}\}$, namely $\{\emptyset\}$, are in $\{\emptyset,\{\emptyset\}\}$.
But it is also true that $\{\emptyset\}\subset\{\emptyset,\{\emptyset\}\}$ since $\emptyset$ is also a member of $\{\emptyset,\{\emptyset\}\}$.

A: $\{\emptyset\}$ is a set containing the null set.
$\{\{\emptyset\}\}$ is a set containing a set which in turn contains the null set.
So we can write, for example, $\{\emptyset\} \in \{\{\emptyset\}\}$.
$\{\emptyset, \{\emptyset\}\}$ is a set with two elements: one element is the null set, and the other element is a set containing the null set.
So it's true that $\{\{\emptyset\}\} \subset \{\emptyset,\{\emptyset\}\}$: the only element of the left side ($\{\emptyset\}$) is also an element of the right side, but the right side also contains a different second element ($\emptyset$).

A: More generally, try proving that $\lbrace A \rbrace \subset \lbrace B,A \rbrace$.

A: When you see curly braces around something, that means you have a set with that something as an element. For example, $\{ S \}$ is a set, and its only element is $S$.  Similary, $\{1 \}$ is a set, and its only element is $1$.  $\{Hi, Bye \}$ is a set, and it has two elements: Hi and Bye.
Similarly, when you have $\{ \{ \emptyset \} \}$, this is a set, and its only element is $\{ \emptyset \}$.  It just so happens that the element of our set is a set itself, but there is nothing wrong with that.
Now, why is $\{ \{ \emptyset \} \} \subset \{ \emptyset, \{ \emptyset \} \}$?  Well, to show a set $A$ is a subset of a set $B$, you need to show every element of $A$ is an element of $B$... But $\{ \{ \emptyset \} \}$ has only one element: $\{ \emptyset \}$.  And is this element in the set $\{ \emptyset, \{ \emptyset \} \}$?  Of course, it is the second element of that set.
So, every element of $\{ \{ \emptyset \} \}$ is an element of $\{ \emptyset, \{ \emptyset \} \}$.
Now the last question is: why is this containment proper?  Well, to show a set $A$ is properly contained in a set $B$, you need to show that every element of $A$ is in $B$ (this shows $A$ is contained in $B$), and also that there is some element in $B$ that is not in $A$ (this shows $A$ and $B$ are not equal, i.e., $A$ is properly contained in $B$).  Well, our $A$ is $\{ \{ \emptyset \} \}$ and our $B$ is $\{ \emptyset, \{ \emptyset \} \}$.  Is there an element of our $B$ that is not in our $A$?  Our $B$ has two elements and our $A$ only has one element.  So there has to be an element in $B$ that is not in $A$, and actually, it is exactly the element $\emptyset$.
So, this explains why $\{ \{ \emptyset \} \} \subset \{ \emptyset, \{ \emptyset \} \}$.

A: Here, {$a,b,c,d,e,....z$} means a set with elements $a,b,c...z$. Now whenever a set is written , everything inside {} are called elements( they can be numbers, alphabets, sets, elephants....) so in your case, on Left hand side, {{$\phi$}} means the set {$\phi$} is an element in the set {{$\phi$}} and as {$\phi$} is an element on R.H.S, {{$\phi$}} $\subset${$\phi,${$\phi$}}

A: maybe, you can think of a set as a bag containing somethings. while $\emptyset $ is a empty bag, $\{\emptyset\}$ is a bag containing a empty one,and so on.
{{ϕ}} ⊂ {ϕ, {ϕ}} is right,because every element in $\{\{\emptyset\}\}$ ,namely $\{\emptyset\}$, is a element in {ϕ, {ϕ}}. it is proper because $\emptyset \in \{\emptyset,\{\emptyset\}\}$


text:
Q: how to use $_POST to change some contents forever I am trying to populate data from a website to another wensite:
a.html:
<form action="b.php" method="post">
<textarea id="myProjects" name="mp"></textarea>
<input id="submit" type="submit" value="Submit" />
</form>

in b.php:
<?php $content=$_POST['mp'];
echo "you entered ".$content;
?>

This works in a very strange way, when I click submit button, I am directed to the b.php page, and I can see what I entered. But if I reload this page, not refresh, my contents disappear, and throwWarning: Undefined array key "mp"  It looks like data received from $_POST is "temporarily" stored. I am new to PHP, so I am not sure how can I figure it out.

A: You can use the PHP SESSION feature to keep the data persistent:
in b.php:
<?php
   // Start the session
   session_start();

   // save the input var as a SESSION property
   if (isset($_POST['mp'])) {
      $_SESSION['content'] = $_POST['mp'];
   }

   // display the property
   echo "you entered " . $_SESSION['content'];

A: Generally speaking, what you want to do is to store the value of $_POST['mp'] into the $_SESSION variable so that it persists from one page request to the next.
However doing it by manipulating these variables directly is generally bad practice. Unless you sanitize the user input you are open to a myriad of scripting attacks. Although there is some learning involved, you are much better off using an established PHP framework (for example Laravel), which has a full set of validation functions, and manages the process of starting the session for you. A good framework will also help you in many other ways.


text:
Q: One AngularJS IIS Web Site on a server connects to the WebAPI but an identical site doesn't I have an AngularJS website on C:\inetpub\wwwroot\CoolWebSite and it connects to my C# based WebAPI successfully. I can tell the WebAPI is succesfully connected because on the main page there is a dropdown which is populated with data returned from WebAPI.
When I make an exact copy of the website on C:\inetpub\wwwroot\CoolWebSite2 (files are copypasta'd) the WebAPI does not get successfully connected. The dropdown is empty. No console errors either.
What would be some reasons this second identical site doesn't work?
Suggestion 1: Site Bindings:

I probably don't have enough info here but I don't know what I don't know. Feel free to suggest more info and I'll nab it.


text:
Q: JDialog.setAlwaysOnTop(true) brings all dialogs to the front under Windows I create two dialogs:
DialogA: setVisible(true) called only once.
DialogB: setVisible(true) and setAlwaysOnTop(true) called every 1,5 sec
Windows: Each call to dialogB.setAlwaysOnTop(true) brings dialogA AND dialogB to the front.
OSX: Each call to dialogB.setAlwaysOnTop(true) brings only dialogB to the front. (Expected Behaviour)
Test Case (Windows):

1 I start the application from my IDE.
2 I see DialogA.
3 I click in the IDE and DialogA disappears.
4 After one second DialogA and DialogB will show up.
5 I click in the IDE and DialogA and DialogB disappears. GOTO 4
Expected Behaviour(OSX):
4. After one second DialogB will show up.
5. I click in the IDE and DialogB disappears. GOTO 4
Question:
How do I get the expected behaviour under Windows?
import javax.swing.JDialog;
import javax.swing.JLabel;
public class JDialogSetAlwaysonTopTEST
{
public static void main(String[] p_Strings)
{
    final JDialog dialogA = new JDialog();
    dialogA.setLocation(0, 0);
    dialogA.add(new JLabel("DialogA: Click on the overlapped   window"));
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            dialogA.pack();
            dialogA.setVisible(true);
        }
    });

    try {Thread.sleep(3000);} catch (InterruptedException e){}

    final JDialog dialogB = new JDialog();
    dialogB.setLocation(70, 70);
    dialogB.add(new JLabel("DialogB:  Do you see DialogA?"));

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            dialogB.pack();
            dialogB.setVisible(true);
        }
    });

    while(true)
    {
        java.awt.EventQueue.invokeLater(new Runnable()  {
            public void run() {
                dialogB.setAlwaysOnTop(true);  //prerequisite
                dialogB.setVisible(true);
                dialogB.setAlwaysOnTop(false); //prerequisite
            }
        });
        try {Thread.sleep(1500);} catch (InterruptedException e){}
    }
}
}

A: I found a "dirty" solution to my problem.
final JDialog dialogA = new JDialog(new JFrame());
...
final JDialog dialogB = new JDialog(new JFrame());

If each dialog has an independent owner dialogB.setAlwaysOnTop(true), dialogB.setVisible(true) does not effect dialogA


text:
Q: Cursor Loader observer already registered error I have an AutoCompleteTextView in my application, and I am loading the data with CursorLoader. Apparently there is some problem with the loading of data using this approach, because from time to time I keep getting this error:
07-01 11:17:49.209: E/AndroidRuntime(20758): java.lang.IllegalStateException: Observer
android.widget.CursorAdapter$ChangeObserver@422dd8b8 is already registered.

Did anyone have this kind of problem?

A: I seem to have solved the problem. I had this kind of crash (error) only when I performed on item clicks from the autocomplete list from the AutoCompleteTextView. The error was obviously internal, and it had something to do with the inner observer of the CursorAdapter that I had been using as an Adapter for my AutoCompleteTextView. So now, on every item click, I do the following:
    txtAutocomplete.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // ... your code here ...
                autocompleteContactsAdapter.changeCursor(null);
            }
        }
    });

Now my application does not crash.


text:
Q: Delete records from table where a = b and b = a I have a table with two fields, a and b. Some records are duplicated in the sense that a = b and b = a. I want to delete on of these records.
Consider this:
declare @temp table (a int, b int)

insert into @temp values (1, 2)
insert into @temp values (3, 4)
insert into @temp values (4, 3)
insert into @temp values (5, 6)

--delete 3, 4 or 4, 3

select * from @temp

/*
a | b
--|--
1 | 2
3 | 4
5 | 6

or (I don't care which one)

a | b
--|--
1 | 2
4 | 3
5 | 6
*/

How can I accomplish this? It needs to support Microsoft SQL Server 2000 and up.

A: DELETE  x
FROM    TableName x
        INNER JOIN
        (
          SELECT  a.A, a.B
          FROM    tableName a
                  INNER JOIN tableName b
                      ON ((a.A = b.A AND a.b = b.b) OR
                          (a.A = b.B AND a.b = b.A)) AND
                         a.a > b.a
        ) y ON x.A = y.A AND x.B = y.B

*

*SQLFiddle Demo

A: Here is a solution for newer version of SQL Server
declare @temp table (a int, b int)

insert into @temp values (1, 2)
insert into @temp values (3, 4)
insert into @temp values (4, 3)
insert into @temp values (5, 6)
insert into @temp values (6, 5)
--delete 3, 4 or 4, 3

delete t3
--select *
from
(select t1.a, t1.b,rank() over (partition by t2.a +t2.b order by t1.a) as row_number from @temp t1
join @temp t2 on t2.a = t1.b and t2.b = t1.a)c
join @temp t3 on c.a =t3.a and c.b = t3.b
where c.row_number <>1

select * from @temp

Posting just to show the newer syntax for anyone else who is searching for the same thing.


text:
Q: ScalaCheck Arbitrary case class with random data generation (Magnolia) Using a basic example I'm attempting to randomly generate a bunch of Person (case class Person(name: String, age: Int) instances using this library for random data generation.
The problem I'm running into is when creating an Arbitrary that has bound limits for the age parameter as shown below.
  val arbPersonUnder18: Arbitrary[Person] = Arbitrary(
    for {
      name <- Gen.alphaStr
      age <- Gen.chooseNum(Int.MinValue, 17)
    } yield Person(name, age)
  )

  "validatePersonForAlcohol" should {
    "ensure people with age less than 18 cannot buy alcohol" in {
      implicit val _: Arbitrary[Person] = arbPersonUnder18
      forAll { person: Person =>
        ...
      }
    }
  }

Which results in could not find implicit value for parameter arbA: org.scalacheck.Arbitrary[pbtexample.Person]
I can't see why it's not able to find the arbitrary it needs, any advice would be great.

A: Even though an implicit value is seldom, if ever, referenced by name, it still needs one, what the language spec calls a "stable identifier."
Using _ as the variable name tells the compiler that it can forget about this value after it's been created.


text:
Q: Populate NULL from existing value from another record I'm using ArcGIS Pro on the table below (ACCT_ID field is sorted). The goal is to calculate/populate the "Asset" field where if rows have the same "ACCT_ID" and at least one of these rows has "Asset" is not null, calculate the null Asset field(s) with the same Asset that has a matching ACCT_ID.
For example, for the four ACCT_IDs of 1976550000, calculate Asset to be 00070925 for the three remaining nulls.
Or for the two ACCT_IDs of 3988856629, calculate Asset 00146135 for the null record
Or for the two ACCT_IDs 366804000, leave Asset null.
I assume this is best done using field calculator but not sure how to go about it.

A: The field calculator loops over records in order, so there's no way to know what the first <Null> should be for a given ID if a valid value hasn't been seen yet.  It would take two loops over the data, once to determine the mapping and then another to fill the nulls.  So this would be better suited to python cursors than the field calculator.
Here's a snippet as an example.  Has not been tested, so back up your data if necessary:
fc = r'C:\example.gdb\the_feature_class'
fields = ['ACCT_ID', 'Asset']
lookup = {}

with arcpy.da.SearchCursor(fc, fields) as cursor:
    for acct_id, asset in cursor:
        if asset:
            lookup[acct_id] = asset

with arcpy.da.UpdateCursor(fc, fields) as cursor:
    for acct_id, asset in cursor:
        if not asset:
            try:
                asset = lookup[acct_id]
            except KeyError:
                print('No asset for "{}"'.format(acct_id))
            else:
                cursor.updateRow([acct_id, asset])

This assumes one unique asset per acct_id.

A: There are a couple alternative approaches to what has already been put forward.
One approach is to loop through the table twice with a cursor, similar to @mikewatt's earlier answer, but to use the same cursor instead of two separate cursors.  Although an update cursor can update a table, it doesn't have to update a table, and resetting an existing cursor is both less code and can be more efficient than instantiating multiple cursors in certain situations.
# modifying mikewatt code for demonstration

fc = # path to feature class or table
fields = ['ACCT_ID', 'Asset']
lookup = {}

with arcpy.da.UpdateCursor(fc, fields) as cursor:
    for acct_id, asset in cursor:
        if asset:
            lookup[acct_id] = asset

    cursor.reset()
    for acct_id, asset in cursor:
        if not asset:
            try:
                asset = lookup[acct_id]
            except KeyError:
                print('No asset for "{}"'.format(acct_id))
            else:
                cursor.updateRow([acct_id, asset])

A second approach that doesn't involve looping over the table twice with a cursor is to use the DBMS engine to pre-sort the data when the cursor is instantiated, thus allowing a single pass over the table to make updates.
fc = # path to feature class or table

with arcpy.da.UpdateCursor(
    fc,
    ["ACCT_ID", "Asset"],
    sql_clause=(None, "ORDER BY ACCT_ID, Asset DESC")
) as cursor:
    prev_id, prev_asset = next(cursor)
    for cur_id, cur_asset in cursor:
        if cur_id == prev_id:
            cursor.updateRow([prev_id, prev_asset])
        else:
            prev_id, prev_asset = cur_id, cur_asset


text:
Q: Error showing info in Flot chart line tooltip I have a chart line with tooltip using Flot plugin getting data from mysql database via AJAX.
I get chart lines established over a period of time, but the problem is when, for example, I select a certain date from January 2014 (01/2014) to December 2014 (12/2014), chart is showing me correct values but incorrect dates in tooltip (12/2013) like this:

I checked timestamps, for example, this is the timestamp of January 1th 2014: 1388534400000 (it's already multiplied by 1000).
So I show info like this:
$("#graph").bind("plothover", function (event, pos, item) {

    if (item) {
        var x = item.datapoint[0],
        y = item.datapoint[1];

        var date = new Date(x); //1388534400000 = 2014-01-01
        var amount = $.number(y,2);

        $("#tooltip").html(""+item.series.label+""+"
Fecha: " + ('0' + (date.getMonth()+1)).slice(-2) + '/'+ date.getFullYear()+ " | Amount: S/ "+amount).css({top: item.pageY+5, left: item.pageX+5}).fadeIn(200);
        } else {
            $("#tooltip").hide();
        }

    });

But it's still showing from one month ago:

And sequence is continuing one month ago but months in xaxis are correct.
How can I fix it? I'd like some help.

A: This is likely because of the javascript Date object using your local timezone. Remember that 1388534400000 is December in any timezones < the UTC default.
I usually dislike recommending libraries as a valid answer, but timezones with the default JS Date object really suck. https://momentjs.com/ is a good alternative if you're looking for universal times.
EDIT: Actually, you can call getUTCMonth() + 1 to return the correct month


text:
Q: jquery-ui auto-complete issue I'm using the jQuery auto-complete, but I notice a strange issue that is happening in my input. For example, in the example below:
    $(function() {

var data = var data = [
  {
    "label": "12 12 North",
    "value": "12 North",
    "country_code": "IN",
    "name": "12 North",
    "code_airline": 12
  },
  ...];

          $('#sample-01').autocomplete({
            maxShowItems: 5,
              minLength:2,
            source: data
          });

        });

I'm getting an array of objects that gives me some information regarding, in my case, airline companies. If I start to search for the first characters of the airline company it gives me the correct label.
But then when I try to replace the data variable with the URL source, to be like:
$('#sample-01').autocomplete({
            maxShowItems: 5,
              minLength:2,
            source: "http://www.json-generator.com/api/json/get/cqycMlSXci?indent=2"
          });

It is not giving me the correct label/company name, as if the autocomplete stops filtering the correct data. What is wrong with my code?

A: From jqueryui:

String: When a string is used (...) The Autocomplete plugin does not filter the results....

Try loading json data first, then populate autocomplete plugin. For example:
$(function(){
    var json = $.getJSON("http://www.json-generator.com/api/json/get/cqycMlSXci?indent=2");
    json.done(function(data){
        $('#sample-01').autocomplete({
            maxShowItems: 5,
            minLength:2,
            source: data
        });
    });
});


text:
Q: Width of 3d touch QuickAction menu same on iPhone 6s and iPhone 6s plus? I integrated 3d touch QuickActions for my iOS app made with Xcode and Swift. Since I only have an iPhone 6s plus, I'm not able to test it on an iPhone 6s. The title is long and fills the line without overflow. But how is it on iPhone 6s? Will the text cutted there? Or does the menu have the same size as on iPhone 6s plus?

A: It looks like, from the images I've seen, the 3D Touch menu is the same width (3 App Icons) between the 6s and the 6s plus, but it looks like they are scaled so it is likely that the text won't be truncated(cut).
If you have Xcode 7.3, you can also check for yourself in the iOS Simulator with a third party library (or maybe a force touch enabled trackpad?): Simulate force touch / 3D touch on iPhone 6S or iPhone 6S Plus simulators


text:
Q: How do add generic types in nested structs in Rust? I know that there is a similar question here, but I've not been able to make it fit my use case.
I have a Model struct that's nested into other structs. The model can have two different types of Config objects, a ModelConfig or a SeedConfig. They are nearly identical save for a few fields. As it stands now, I need two concrete implementations of Model (SeedModel and ModelModel) in order to change the config field, resulting in duplication of all the methods and trait implementations.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct MetaModel {
   pub model: Model
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Model {
    pub name: String,
    pub config: Option<ModelConfig>
}

What I've tried:

*

*Using Generics: This pushes the generic type up the chain and results in very complex definitions and areas where I don't have the context to create the parent struct (i.e. the MetaModel definition has no access to the Model definition at creation).

This eventually results in a the type parameter C is not constrained by the impl trait, self type, or predicates unconstrained type parameter error
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct MetaModel<C> {
   pub model: Model<C>
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Model<C> {
    pub name: String,
    pub config: Option<C>
}

*

*Trait Objects: This doesn't work because serde cannot serialize trait objects

pub trait Config {}

pub struct ModelConfig;
impl Config for ModelConfig {}
pub struct SeedConfig;
impl Config for SeedConfig {}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Model {
    pub name: String,
    pub config: Option<Box<dyn Config>
}

What I'd like to do:
impl OtherTrait for Model {
    type Value = Model;
    fn build_model(&self, m: DerivedMeta) -> Result<Self::Value, &'static str> {
        Ok(Model {
           // Either a SeedConfig or a ModelConfig
        })
    }
}

A: What I would do is use a combination of #[serde(flatten)] and #[serde(untagged)]:
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
struct Config {
    members: i32,
    shared_by: String,
    both: i64,

    #[serde(flatten)]
    specific: SpecificConfig,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(untagged)]
enum SpecificConfig {
    SeedConfig {
        some_members: i16,
        unique_to: String,
        seed_config: u64,
    },
    ModelConfig {
        other_members: i8,
        not_shared_with_above: u32,
    },
}

Serde explanation of flatten:

Flatten the contents of this field into the container it is defined in.
This removes one level of structure between the serialized representation and the Rust data structure representation.

Serde explanation of untagged:

There is no explicit tag identifying which variant the data contains. Serde will try to match the data against each variant in order and the first one that deserializes successfully is the one returned.

By combining these two, we get the following behavior:

*

*flatten allows all shared fields and specific fields to be on the same level in the config

*untagged allows us to avoid adding an explicit tag in the config

*all shared properties are directly accessible

*only specific properties require matching the specific enum


text:
Q: Add a datagridview column from another form I have two forms and a datagridview which is in the form1.Im trying to add a new column by clicking in a button from form2.Like that:
 Form2

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 form1 = new Form1();

        form1.dataGridView1.Columns.Add("test" , "test");

    }

How can I do that?

A: Form1 form1 = new Form1();

This will not work as your real form1 is already there, I pressume. Instead create a reference to it in form2 and load it in form2's constructor!
Here are the steps:

*

*the local reference to form1 in form2's variables:  Form1 form1

*When opening form2 pass a reference to form1 in the constructor:
form2 = new Form2(this);

*Store it in the local refence in the constructor on form2:
public Form2(Form1 form1_)
{
    InitializeComponent();
    form1 = form1_;
}

Now you are all set to use Form1 and its public properties and controls. To use form1.dataGridView1 you must make it public first, though. (Or create a public reference to it..)


text:
Q: Why can I not take the positive or negative square root while solving a quadratic equation in this instance? I have the problem $4x^2 -36x = -81$, and I am asked to solve it by factoring. I move the $81$ to the left side of the equation, then divide by $4$, giving me $x^2 +9x + \frac {81}4 = 0$. Since I know that $\frac {81}4$ is the perfect square of $\frac 92$, I can factor this equation into $(x - \frac 92)^2 = 0$. I then take the square root, and the equation becomes $\pm$$(x-\frac 92) = 0$. I turn the equation into 2 different ones:
$(x - \frac 92) = 0$
$-1(x - \frac 92) = 0$
So, that means that $x = \frac 92$.
But, $-1(x - \frac 92) = (\frac 92 - x) = 0$,
so this means that x also equals $-\frac 92$. I put this through a python program I wrote, and it gave me $4.5$ or $4.5$. Where did the negative come from?

A: Your mistake is where you say that $-(x-\frac 92)=0 \Rightarrow x=-\frac 92$.
In fact $-(x-\frac 92)=0 \Rightarrow -x+\frac 92=0 \Rightarrow x=\frac 92$
This is an example of a 'repeated root.'

A: Notice there is an issue in your final deduction:
From $y^2 = 0$, you cannot have $y = -y$ in general (and that's what you did)
Instead, if $y^2 = 0$, you could only get $y = 0$
But of course, when you get $y=0$, $y=-y$ will hold, becase $0 = -0$
So you see the sequence of the logic?

A: I would say you began to go off track when you said

I then take the square root, and the equation becomes $±(x−\frac{9}{2})=0$.

When you have $(x-\frac{9}{2})^2=0$, instead of taking the square root, you should expand the binomial:
$$(x-\frac{9}{2})(x-\frac{9}{2})=0$$
So $x=\frac{9}{2}$. This is sometimes called a double root.
By mistakenly taking the square root, you introduced the negative term, which was never there in the first place.
You might have been able to see your mistake by graphing the equation. This is a parabola that opens up with the vertex at $(\frac{9}{2},0)$. (A parabola with a vertex on the $x$-axis always has a double root.) The parabola does not cross the $x$-axis at $x=-\frac{9}{2}$. So the graph would have told you the negative answer was incorrect.

A: $4x^2-36x=-81$
You added 81 to both sides:
$4x^2-36x+81 = 0$
You divided both sides by 4:
$x^2-9x+\frac{81}{4} = 0$
You factored the LHS:
$(x-\frac{9}{2})^2 = 0$
The next thing you did was incorrect. The result after taking squares roots is $x-\frac{9}{2} = ±0$, not $±(x-\frac{9}{2}) = 0$.
$x-\frac{9}{2} = ±0$
$x = \frac{9}{2} ± 0$
$x_1 = \frac{9}{2} + 0$ and $x_2 = \frac{9}{2} - 0$
$x_1 = x_2 = \frac{9}{2}$
The root is repeated.
By the way, $\frac{9}{2}$ is the solution of $\frac{9}{2} - x = 0$. Where did you get $-\frac{9}{2}$?


text:
Q: How to extract heat transfer model parameters from empirical data? I have made a simple model of heat transfer between ambient and a silicon chip (module) from which I can read its internal temperature $T_m$. I do not need fancy equations and an approximate model will do just fine.
I have modelled the system using electrical equivalent model (RC), but determining parameters requires equilibrium point data.
Using the heat transfer slope I could potentially determine the model parameters, only that the data is noisy and even using Rick Chartrand, "Numerical differentiation of noisy, nonsmooth data" algorithm I still couldn't get a good estimate for the actual derivatives.
My solution now is to fit data and extract parameters from empirical data.
After I heat the module I let it cool down, but to measure the internal temp I need some part of the module to run, which should account for a residual power $P$.
The model is $\frac{\delta T_m}{\delta t} = c (T_a -T_m(t)) + P$
I can easily assume that the room will not change temperature because of a very small chip running, such that $T_a$ is constant.
I can determine estimates of $c$ from halftime and $P$ from solving $\frac{\delta T_m}{\delta t} = 0$.
A linear sweep of values around this estimates will give probably sufficiently good estimates.
My problem comes from the fact that if I solve the diferential equation I end up with this solution
$T_m(t) = T_m(0) e^{-ct} + (cT_a+P)t$
which makes no physical sense since it simply states temperature will rise infinetly.
What is the right solution for this diferential equation of heat transfer?

A: The correct solution to your differential equation is:
$$ T_m(t)=(T_m(0)-\frac{P}{c}-T_a)e^{-ct} + (T_a+\frac{P}{c}) $$
or more succinctly,
$$ T_m(t)=(T_m(0)-T_m(\infty))e^{-ct}+T_m(\infty) $$
where $T_m(\infty)=T_a+\frac{P}{c}$.


text:
Q: logstash-forwarder json invalid character At some point my logstash forwarder used to work properly but at some point fail to start with this error message

Failed unmarshalling json: invalid character ']' looking for beginning of value logstash

This message appears only if i run forwarder with this command:
$ /opt/logstash-forwarder/bin/logstash-forwarder -config="/etc/logstash-forwarder"

If i run it as a service it fails without any error message, if i restart the service getting this

Restarting log shipper logstash-forwarder
  start-stop-daemon: warning: failed to kill PID: No such process
  ...done.

The first time stopped forwarder working i found in syslog this message:

connection from UDP: [54.194.184.218]:63707->[10.38.143.181] Nov 21
  12:41:38 logstash-forwarder[PID]: 2014/11/21 12:41:38.692517 Read
  error looking for ack: EOF Nov 21 12:41:38 logstash-forwarder[PID]:
  2014/11/21 12:41:38.692592 Setting trusted CA from file:
  /etc/pki/tls/certs/logstash-forwarder.crt Nov 21 12:41:38
  logstash-forwarder[PID]: 2014/11/21 12:41:38.692827 Connecting to
  X.X.X.X:5000 (X.X.X.X) Nov 21 12:41:38 logstash-forwarder[PID]:
  2014/11/21 12:41:38.694128 Failure connecting to X.X.X.X: dial tcp
  X.X.X.X:5000: connection refused

At server side logstash and ES cluster seems to work fine..
I found many similar problems with mine but not any solution.


text:
Q: TDD & BDD? Which, Why and How? TDD & BDD? Which, Why and How?
Can anyone give a good explanation to justify "Which", "Why" and "How" on both?
Thanks in advance.

A: TDD is used more for unit testing e.g. testing a method on a class. BDD is used for testing the behaviour of a system e.g. Creating a user, or Sending out new product emails.
So for TDD you might see something like.
public void Test()
{
    // Arrange.
    var sut = new ClassToTest();

    // Act.
    int result = sut.SoSomething();

    // Assert.
    Assert.Equal(result, 23);
}

With BDD (depending on the tools you're using) you tend to see something like this:
Feature: Add a user
    As a system admin
    In order to give a user access to the site
    I want to create a user account

Scenario: Creating a basic user
    Given I have the user's name
    When I create a new user account
    Then that user can log onto the site

As you can, BDD is testing the behaviour of a system rather then single unit. Here is a very good intro to BDD by Dan North - http://dannorth.net/introducing-bdd/
I would recommend using TDD when you are building your classes/code and want to testing little bits of it at a time. Use BDD when you want to test more then one of those classes in a test i.e. integration test.
EDIT:
With the how side of things, for BDD I would recommend using SpecFlow. This is a popular BDD tool which adds a lot of functionality to Visual Studio for creating feature files (The Feature: stuff I mentioned above) and running and debugging the tests.
Under the hood SpecFlow can use NUnit or MSTest to generate the tests. Other BDD tools include:

*

*MSpec

*NSpec

*SpecsFor

*StoryQ
and many others I've forgotten about right now :) I would suggest you try them out and see which one you prefer.
For TDD you have many options including:

*

*NUNit

*xUnit

*MSTest

A lot of the above tools can installed via NuGet in Visual Studio, which is handy.


text:
Q: how to customize hello dolly plugin? I am trying to play with the Hello Dolly plugin. I want that plugin to work on the front end. Is it possible to bring Hello Dolly to the front end? Or will that affect my existing website?

A: In your theme, add a custom action in a template where you want to show the output:
do_action( 'show_lyrics' );

This does nothing for itself. Now you can add the function hello_dolly as a  callback for that action in your functions.php:
if ( function_exists( 'hello_dolly' ) ) {
    add_action( 'show_lyrics', 'hello_dolly' );
}


text:
Q: Ordenação específica de uma lista sem plugin Estou enfrentando um problema bem específico em um projeto.
Estou criando slide, onde eu preciso ordernar a lista de acordo o que é clicado na paginação. Ela deve ficar da seguinte forma:
Seguinte forma:
Quando clico na paginação no item 3, a lista deve ficar da seguinte forma:

Lista original:       Lista MO
0                            2
1                           *3*
2                            4
3                            0
4                            1

----------

Quando clico na paginação no item 2, a lista deve ficar da seguinte forma:

Lista original:        Lista MO
0                            1
1                           *2*
2                            3
3                            4
4                            0

----------

Quando clico na paginação no item 0, a lista deve ficar da seguinte forma:

Lista original:        Lista MO
0                            4
1                           *0*
2                            1
3                            2
4                            3

Sempre será visível apenas o item da lista na posição 1. Como mostra na imagem a baixo:

Quem puder ajudar, segue o jsfiddle, com uma base para testes, tanto pode ser feito em JS puro ou jQuery.

A: Com a ajuda do pessoal do grupo Jquery Brasil, consegui resolver o problema. Para quem tiver interesse em ver o resultado:

0

1

2

3

4

    0
    1
    2
    3
    4

$(function(){
    var list = $(".list li");
    var newList = new Array();

    $(".pagination a").bind("click", function(){
        var pageSelected = $(this);
        var afterPage = list.slice(pageSelected.data("position") - 1,list.length);
        var beforePage = list.slice(0, pageSelected.data("position") - 1);

        afterPage.each(function(a,b){
            newList.push(b);
        });

        beforePage.each(function(a,b){
            newList.push(b);
        });

        $(".list").append(newList);
    });
});

jsfiddle

A: Baseando no seu JsFiddle, criei essa solução para seu problema.
Exemplo:
$(function(){

    $('.pagination').find('a').click(function(e){

        e.preventDefault();

        var pos = $(this).data('position');

        var $list = $('.list').find('li');

        $list
         .filter('[data-position='+pos+']')
         .insertAfter($list.first());

    })

});

Por não ser tão comum o uso deles no jQuery, aqui vai uma breve explicação:
insertAfter = Insere um determinado valor depois o elemento especificado
filter = Da lista dos elementos atuais, pega os elementos que casam com os valores passados no parâmetro. No caso acima, estamos especificando que o elemento tem que ter o data-position igual ao data-position do link clicado.
Estamos basicamente dizendo para o jQuery: "procure o elemento que tenha o data-position igual ao position do link clicado atual e insira ele depois do primeiro elemento da lista"
Código atualizado no jsFiddle


text:
Q: Question regarding kernels in Hilbert-Schmidt operators I'm studying some Hilbert-Schmidt integral operator theory. I read that a Hilbert-Schmidt integral operator is uniquely determined by its kernel, and I wonder how exactly that is. I guess what I'm looking for are hints/suggestions on how to show that Hilbert-Schmidt integral operators are uniquely determined by their kernels.
Here are the definitions I'm going by:
$\textit{Let k be a function of two variables }(x,y)\in I \times I=I^2$ $\textit{ where }I\textit{ is a finite or infinite real interval. We define a linear integral operator K with kernel }$
$k(x,y)\textit{ as }$
$$Ku(x)=\int_{I}k(x,y)u(y)\ dy,\ \ x\in I$$
$\textit{whenever this integral makes sense. The domain D(K) will have to be specified in order to accomplish this.}$
$\textit{An integral operator on }L^2(I)\textit{ is called a Hilbert-Schmidt operator if the kernel }k\textit{ is in }L^2(I\times I),\textit{that is if}$
$$||k||_{L^{2}}^2=\int_{I}\int_{I}|k(x,y)|^2\ dxdy<\infty$$
The book I'm using now says it's possible to show that a Hilbert-Schmidt operator is uniquely determined by its kernel, that is, if
$$\int_{I}k(x,y)u(y)\ dy=\int_{I}h(x,y)u(y)\ dy$$
for all $u\in L^2(I)$, then $k=h$ in $L^2(I\times I)$.
This is where I'm unsure of how to show this.
Thanks in advance!

A: Let $T_k$ be the operator $T_ku(x)=\int_{I}k(x,y)u(y)\,dy$.  If $T_k=T_h$, then $T_{k-h}=T_k-T_h=0$.  So, it suffices to show that if $T_k=0$, then $k=0$.
To prove this, suppose $T_k=0$ and let $k_x(y)=\overline{k(x,y)}$.  Note that $k_x\in L^2(I)$ for almost every $x\in I$, and that $T_ku(x)=\langle u, k_x\rangle$.  Now pick an orthonormal basis $\{e_n\}$ for $L^2(I)$ (or really just any countable subset whose span is dense).  For each $n$, $T_ke_n=0$, meaning that for almost all $x$, $k_x$ is orthogonal to $e_n$.  Since a countable union of null sets is null, this means that for almost all $x$, $k_x$ is orthogonal to $e_n$ for all $n$.  But since the span of $\{e_n\}$ is dense in $L^2(I)$, this means $k_x=0$ almost everywhere.  So $k_x=0$ almost everywhere for almost all $x$, which means $k=0$ almost everywhere.


text:
Q: Negation of the Lipschitz condition We know that a function $f: X \to Y$, where $X$ and $Y$ are metric spaces with metrics $d_1$ and $d_2$ respectively, is a Lipschitz function if there exists a real number $K>0$ such that for every $x,y$ that belong to $X$,
$$ d_2( f(x), f(y)) \le K d_1(x, y).$$
Therefore, the negation should look as follows:
A function $f: X \to Y$ is not a Lipschitz function if for every real number $K>0$ there exists some $x,y$ that belong to $X$ such that
$$ d_2( f(x), f(y)) > K d_1(x, y).$$
But now I want to write an equivalent negation using sequences, how can I do that?

A: $f$ is not Lipschitz if and only if for every positive integer $n$ there exist $x_n,y_n$ such that
$$d_2(f(x_n,f(y_n)) >n d_1(x_n,y_n).$$


text:
Q: An scala collection container with next and previous methods I am looking for a class in scala collections which allows me to traverse to next and previous element of a list of items.
For example:
val container = SomeClassFromScala(Int,Double,classOf[String],7)

container.getPreviousItem(Double) => Option[Int]
container.getNextItem(7) => None

Is there any class in Scala collections with this api and constant time for getNext/getPrevious.
I can write the code but I wanted to see if there is anything I can use right away.

A: If you want to have an immutable collection with your requirements, you can have a look at Zipper in scalaz:

Provides a pointed stream, which is a non-empty zipper-like stream structure that tracks an index (focus)
  position in a stream. Focus can be moved forward and backwards through the stream, elements can be inserted
  before or after the focused position, and the focused item can be deleted.

All operations are constant time. Though the constant is larger as one would expect from something that wraps an array (and doesn't allow insertion/deletion of elements), as it involves object creation.
Implementation is basically by having two lists (Streams, whatever), where one holds the previous, reversed elements. Moving is done by swapping over the head element from one list to the other.

A: Have a look at DoubleLinkedList.  It adds a prev that gives you a list with the previous item as its head.
import collection.mutable.DoubleLinkedList
val a = DoubleLinkedList(1,2,3,4)
val b = a.next.next                 // DoubleLinkedList(3, 4)
val c = b.prev                      // DoubleLinkedList(2, 3, 4)

Downsides: It's not constant time, and it's mutable.


text:
Q: AWS EMR with Glue catalog, specify catalogId explicitly is there a way to specify a Glue catalogId explicitly in EMR configuration?
https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-hive-metastore-glue.html
This shows how to specify to use Glue in EMR for Hive metastore, but does not document any parameter to specify the catalogId that would be passed to Glue API calls (presumably, defaults to the account ID).
Later on the doc does mention "... if the cluster is in a different AWS account" which seems to imply there is a way to point the EMR cluster at a Glue catalog in a different account.

A: It looks like this was recently added.  The relevant property is hive.metastore.glue.catalogid, within hive-site
https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-hive-metastore-glue.html
"In addition, with Amazon EMR 5.16.0 and later, you can use the configuration classification to specify a Data Catalog in a different AWS account."
"To specify a Data Catalog in a different AWS account, add the hive.metastore.glue.catalogid property as shown in the following example"


text:
Q: Django Styling a UserCreationForm with css I a trying to add some style to the UserCreationForm, I cannot user Bootstrap for this project so need to modify its html and css directly. I have not been able to find anything in its documentation the allows me to do this.
I added a email field to my UserCreationForm field by adding this snippet of code to models.py
class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

and I pass the form as context to my template in views.py
def register(request):
    if request.method == 'GET':
        if request.user.is_authenticated:
            return redirect('news')
        else:
            form = CreateUserForm()
            context = {'form': form}
            return render(request, 'base1.html', context)

    if request.method =='POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            user = form.cleaned_data.get('username')
            messages.success(request, 'Account was created for ' + user)
            return redirect('login')

    return render(request, 'registration.html', context)

this is how I have manage to display it inside my HTML5 template
       <form action="" method="post">
            {% csrf_token %}

 Register

{{form.username.label}}

            {{form.username}}

            {{form.email.label}}{{form.email}}
            {{form.password1.label}}{{form.password1}}
            {{form.password2.label}}{{form.password2}}
            <input type="submit" name="Create User">
        </form>

More over I have looked at several tutorials and did not find what I was looking for as well as an Stackoverflow where this answers seem to help but since they are years old the links are no longer valid and I have no way of looking at the documentation.
Django - Styling a UserCreationForm with css
 from 5 years ago
How do I style my user registration form using Bootstrap in DJango? from 5 years ago and please no bootstrap.
So how do I modify the style of the fields in UserCreationForm and ad my own css and/or html?
And where can I find the documentation for this? (I have looked at the documentation site many times but it is huge and I can't seem to find anything about this.)

A: You can use layouts at Django crispy form.
class SendFeedbackForm(forms.Form):
title = forms.CharField(label="Title",widget=forms.TextInput(attrs={'class': 'custom-feedback-class', 'onkeyup':'feedback_form_control()'}))
message = forms.CharField(label="Your Message", widget=forms.Textarea(attrs={'class': 'custom-feedback-class', 'onkeyup':'feedback_form_control()'}) )

def __init__(self, *args, **kwargs):
    super(SendFeedbackForm, self).__init__(*args, **kwargs)

    self.helper = FormHelper()
    self.helper.form_method = 'POST'
    self.helper.layout = Layout(
    'title',
    'message',
    Submit('submit','Send', css_id="id_feedback_submit", css_class='feedback-disabled-button '),
    )

I can give a example I use. While creating this form, my main goal is to get 2 input fields. When these fields are empty, do not activate the "send" button. When both of these fields are full, let the "send" button work. So I need to add both css and js rules.
index.html

    <form method = "post">
       {% csrf_token %}
       {% crispy form_sendfeedback %}
    </form>

  .
  .
  .


text:
Q: jar-size too big. How to decrease jar-size in maven-project? When I build my maven Project I get a big jar of 300mb. It has to be under
75mb. Is there a way to not compile unused maven libraries/dependencies?
Or is there a way to find out which libraries/dependencies my project doesnt need?

A: https://maven.apache.org/plugins/maven-dependency-plugin/analyze-mojo.html is the plugin you are looking for. It will find used+undeclared (=transitive) dependencies and unused+declared dependencies.
Just be aware that it cannot detect reflection.

A: Sounds like you need to include Skinny WAR option. Could you try the following POM in your project and let us know if that helped to reduce from 300MB to?
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>${war-plugin-version}</version>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <classpathPrefix>lib/</classpathPrefix>
            </manifest>
        </archive>
        <webResources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/webapp</directory>
                <includes>
                    <include>**/web.xml</include>
                </includes>
            </resource>
        </webResources>
    </configuration>
</plugin>


text:
Q: Add a button to a layout and program crashes. Why? This app displays movies and each movie poster can be clicked to see details about the movie. However, when I try to add a button to the detail view layout the app crashes with these errors. When I remove the button from the layout the app works as it should. This crash seems odd to me.
04-19 20:05:53.479 28975-28975/com.jcaseydev.popularmovies E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jcaseydev.popularmovies, PID: 28975
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jcaseydev.popularmovies/com.jcaseydev.popularmovies.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.jcaseydev.popularmovies.MovieListFragment.onCreateView(MovieListFragment.java:72)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:339)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:602)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
at android.app.Activity.performStart(Activity.java:6268)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Here is my detail activity code.
package com.jcaseydev.popularmovies;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

public class DetailFragment extends Fragment{
public DetailFragment(){}
Movie movie;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.detail_fragment, container, false);

    //get intent
    Intent intent = getActivity().getIntent();

    //key for the intent extra
    String MOVIE_INFO = "movie_info";

    //test if intent is null and if it has the correct extra
    if(intent != null && intent.hasExtra(MOVIE_INFO)){
        //fill movie with the details of the clicked item
        movie = intent.getParcelableExtra(MOVIE_INFO);

        //update view with all of the details
        updateView(rootView);
    }

    return rootView;
}
private void updateView(View view){
    //set up the views
    TextView title = (TextView) view.findViewById(R.id.movieTitle);
    TextView overview = (TextView)view.findViewById(R.id.movieOverview);
    TextView releaseDate = (TextView)view.findViewById(R.id.movieReleaseDate);
    ImageView moviePoster = (ImageView)view.findViewById(R.id.moviePoster);
    TextView movieVoteAvg = (TextView)view.findViewById(R.id.movieVote);

    //set the text on the views
    title.setText(movie.getMovieTitle());
    overview.setText(movie.getMovieOverview());
    releaseDate.setText(movie.getMovieReleaseDate());
    Picasso.with(getActivity()).load(movie.getMoviePoster()).into(moviePoster);
    movieVoteAvg.setText(Double.toString(movie.getMovieVoteAverage()));
}

}
Here is the layout file associated with the detailview class
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/moviePoster"
    android:contentDescription="@string/movie_poster" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/movieReleaseDate" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/movieVote"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/movieTitle" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/movieOverview" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"/>

Here is the movie list class
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MovieListFragment extends Fragment {

private ArrayList<Movie> movieArrayList = new ArrayList<>();
private ArrayList<String> listOfMoviePosters = new ArrayList<>();
private String MOVIE_KEY = "movie_info";
private ImageAdapter imageAdapter;
private String BASE_URL = "http://api.themoviedb.org/3/movie/now_playing";
int toggle = 0;

public MovieListFragment(){
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

private void updateMovies() {
    //clear out both lists
    movieArrayList.clear();
    listOfMoviePosters.clear();

    //create a new async task and execute
    FetchMovieData fmd = new FetchMovieData();
    fmd.execute();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.movie_list_fragment, container, false);

    imageAdapter = new ImageAdapter(getActivity(), listOfMoviePosters);

    GridView mGridView = (GridView) rootview.findViewById(R.id.movie_list_grid_view);
    mGridView.setAdapter(imageAdapter);

    mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Movie details = movieArrayList.get(position);
            Intent intent = new Intent(getActivity(), DetailActivity.class)
                    .putExtra(MOVIE_KEY, details);
            startActivity(intent);
        }
    });

    return rootview;
}

@Override
public void onStart() {
    super.onStart();
    updateMovies();
}

public class FetchMovieData extends AsyncTask<Void, Void, List<Movie>> {

    private List<Movie> getDataFromJSon(String json)throws JSONException{

        //items that need to be got
        final String ARRAY_OF_MOVIES = "results";
        final String TITLE = "title";
        final String POSTER_PATH = "poster_path";
        final String OVERVIEW = "overview";
        final String RELEASE_DATE = "release_date";
        final String VOTE_AVERAGE = "vote_average";
        final String MOVIE_ID = "id";

        //store the json in a json object
        JSONObject jsonObject = new JSONObject(json);

        //get the actual movie results
        JSONArray jsonArray = jsonObject.getJSONArray(ARRAY_OF_MOVIES);

        //get the length of the array for looping
        int limit = jsonArray.length();

        //creat a list of movies
        List<Movie> movies = new ArrayList<>();

        //loop through all of the movies in the array
        for(int i = 0; i < limit; i++){
            //get the current movie object
            JSONObject movieObject = jsonArray.getJSONObject(i);

            //get the various details about the movie
            String title = movieObject.getString(TITLE);
            String poster = "http://image.tmdb.org/t/p/w342/" + movieObject.getString(POSTER_PATH);
            String overview = movieObject.getString(OVERVIEW);
            String releasedate = movieObject.getString(RELEASE_DATE);
            Double voteAvg = movieObject.getDouble(VOTE_AVERAGE);
            int movieId = movieObject.getInt(MOVIE_ID);

            //add the movie object to the movie list
            movies.add(new Movie(title, poster, overview, releasedate, voteAvg, movieId));
        }

        return movies;
    }

    @Override
    protected List<Movie> doInBackground(Void... params) {

        try {

            final String QUERY_API = "api_key";

            //Build URL to get data from
            Uri builtUri = Uri.parse(BASE_URL).buildUpon()
                    .appendQueryParameter(QUERY_API, BuildConfig.TMDB_API_KEY)
                    .build();

            Log.d("URL", builtUri.toString());
            //Using OkHttp to make network request
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(builtUri.toString())
                    .build();

            //creating a response object
            Response response = null;

            try {
                //attempt to execute request
                response = client.newCall(request).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //Storing results of request in a string
            String jsonData = response.body().string();

            try {
                //attempt to call method that will extract data
                return getDataFromJSon(jsonData); //call to extract data
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<Movie> result) {
        if (result != null){
            //add all of the movie objects that have be gathered
            //into the movieArrayList
            movieArrayList.addAll(result);
            //Call updatePoster to get movie posters
            updatePoster();

            //notify the image adapter that there is data now
            imageAdapter.notifyDataSetChanged();

        }
    }
    public void updatePoster(){
        //for every movie in movieArraylist add to
        //listOfMoviePosters
        for (Movie movie : movieArrayList){
            listOfMoviePosters.add(movie.getMoviePoster());
        }
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.movie_list_fragment_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    //simple way to toggle the sort order
    if(id == R.id.sort_action) {
        if (toggle == 0) {
            BASE_URL = "http://api.themoviedb.org/3/movie/top_rated";
            movieArrayList.clear();
            listOfMoviePosters.clear();
            updateMovies();
            toggle = 1;
        } else if(toggle == 1){
            BASE_URL = "http://api.themoviedb.org/3/movie/now_playing";
            movieArrayList.clear();
            listOfMoviePosters.clear();
            updateMovies();
            toggle = 0;
        }
    }
        return super.onOptionsItemSelected(item);

}

}
Im not sure what could be causing this. Thanks in advance for the help!

A: The stack trace tells you:

Attempt to invoke virtual method 'void
  android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a
  null object reference

Where did you call setAdapter in the code?
mGridView.setAdapter(imageAdapter);

What did you try to call it on?
mGridView

How did you get the reference to that?
GridView mGridView =(GridView)rootview.findViewById(R.id.movie_list_grid_view);

...Which is clearly returning null. So now just figure out why it can't find the view.
I don't see the id movie_list_grid_view anywhere in your code.

A: Can you show the content of this file movie_list_fragment.xml? I think the problem is from there. Maybe you the GridView has a different ID as compare to movie_list_grid_view.


text:
Q: How do you test inquirer CLIS? I would like to write units tests for a CLI I made in inquirer. I want to verify that the prompts are displayed correctly, simulate choices in the command line, and verify that the resonses are correct.

A: After trying a bunch of packages, reading SO, and making mocks, I found the answer!
First you need to make a testInquirer.js
import { writeFileSync, unlinkSync } from "fs";
import * as child_process from "child_process";

const TEMP_FILE_PATH = "/tmp/";

export default async (
  command,
  inputs,
  { output, error },
  { timeout, nodeScript, nodeCommand } = {
    timeout: 100,
    nodeScript: false,
    nodeCommand: "node"
  }
) =>
  new Promise(async resolve => {
    let proc;
    let tmpFile = `${TEMP_FILE_PATH}${Math.random()}.js`;

    if (nodeScript) {
      writeFileSync(tmpFile, command);
      proc = child_process.exec(`${nodeCommand} ${tmpFile}`);
    } else {
      proc = child_process.exec(command);
    }

    proc.stdout.on("data", data => {
      output(data);
    });

    proc.stderr.on("data", data => {
      error(data);
    });

    const sendKeys = async inputs => {
      await inputs.reduce(
        (previousPromise, input) =>
          new Promise(async resolve => {
            if (previousPromise) {
              await previousPromise;
            }

            setTimeout(() => {
              proc.stdin.write(input);
              resolve();
            }, timeout);
          }),
        null
      );

      proc.stdin.end();
    };

    await sendKeys(inputs);
    proc.on("exit", code => {
      if (nodeScript) {
        unlinkSync(tmpFile);
      }
      resolve(code);
    });
  });

// https://www.tldp.org/LDP/abs/html/escapingsection.html
export const DOWN = "\x1B\x5B\x42";
export const UP = "\x1B\x5B\x41";
export const ENTER = "\x0D";
export const SPACE = "\x20";

Then you can test your CLI as so.
The api for testInquirer is:

*

*command: the command you use to run the CLI ('usually something like CDing into the right dir and running node . or yarn start)

*inputs: array of inputs in order to send to stdin. You can use the exported helpers (ENTER, DOWN, etc) or enter input

*output: pass a jest.fn() which will listen to all stdout output

*opts:

*

*timeout: timeout in between commands

test:
import run, { UP, DOWN, ENTER, SPACE } from '../testInquirer';

describe('cli', () => {
  it('runs', async () => {
    const outputMock = jest.fn();

    await run('yarn start', [
      // Choose "Babel Config Generator"
      SPACE,
      DOWN,

      // Choose "CodeFresh Config Generator"
      SPACE,

      // Next Question
      ENTER,

    ], outputMock);

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/Which Generators do you want to use/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/❯◯ Babel Config Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/❯◯ CodeFresh Config Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/RUNNING GENERATOR: Babel Config Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/RUNNING GENERATOR: CodeFresh Config Generator/)
    );
  })
})

If you want to test a file that accepts inputs into a function, it would look something like this:
describe(runGenerator, () => {
  let outputMock;
  let errorMock;

  beforeEach(() => {
    outputMock = jest.fn();
    errorMock = jest.fn();
  });

  it.only('runs a generator', async () => {
    const runGeneratorPath = `${__dirname.replace(/(\s+)/g, '\\$1')}/../runGenerator.ts`;
    const code = await testInquirer(`
      const runGenerator = require("${runGeneratorPath}").default;
      console.error(runGenerator)
      runGenerator(${JSON.stringify(MOCK_GENERATOR)});
    `, [], { output: outputMock, error: errorMock }, {
      nodeScript: true,
      nodeCommand: 'ts-node'
    });

    expect(code).toBe(0);

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/RUNNING GENERATOR: Mock Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/Executing step:/)
    );
  })
})


text:
Q: Replace MySql database root image links with subdomain folders? Im trying to figure out a way to update some of my images in my database which are pointing to the wrong place. It was easy to do with the images which were in the wrong subfolder as I could just use a simple plugin to search for http://url.com/sub1/folder/ and change to http://url.com/sub2/folder/
But these are in root, so http://url.com/image.jpg and need to be http://url.com/sub2/folder/image.jpg
Can I use phpMyadmin to search for http://url.com/*.jpg and replace with http://url.com/sub2/folder/*jpg or another method?

A: Recent versions of phpMyAdmin have a find and replace feature which sounds like it might be what you're after.
This can be located by going to the table you wish to search and clicking the Search tab, then Find and Replace. Put your old URL in the "Find" field and new URL in the "Replace with" field, and click Go to preview the changes. It never hurts to have a backup of your data when making changes.


text:
Q: SSE connection got closed by browser after receiving first data I wrote a spring sse application but after receiving the first data from server, the sse emitter connection gets closed. I searched and analysed a lot and got to know it is the browser (in my case firefox) who closes the connection. Thats why I got this log in my application logs
org.eclipse.jetty.io.EofException
at org.eclipse.jetty.io.ChannelEndPoint.flush(ChannelEndPoint.java:292)
at org.eclipse.jetty.io.WriteFlusher.flush(WriteFlusher.java:429)
at org.eclipse.jetty.io.WriteFlusher.write(WriteFlusher.java:322)
at org.eclipse.jetty.io.AbstractEndPoint.write(AbstractEndPoint.java:372)
at org.eclipse.jetty.server.HttpConnection$SendCallback.process(HttpConnection.java:750)
at org.eclipse.jetty.util.IteratingCallback.processing(IteratingCallback.java:241)
at org.eclipse.jetty.util.IteratingCallback.iterate(IteratingCallback.java:224)

Caused by: java.io.IOException: An established connection was aborted by the software in your host machine
at sun.nio.ch.SocketDispatcher.writev0(Native Method)
at sun.nio.ch.SocketDispatcher.writev(SocketDispatcher.java:55)
at sun.nio.ch.IOUtil.write(IOUtil.java:148)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:503)
at org.eclipse.jetty.io.ChannelEndPoint.flush(ChannelEndPoint.java:272)
... 29 more

and this occurred at line E1.send(value,MediaType.APPLICATION_JSON);
I understand that since E1 is closed, hence that line threw that exception, by I could not understand why the browser behaves like this i.e. closing the exisitng connection after getting the first data. I searched a lot in internet for this issue but could not find any solution.
Please help. I am getting stuck with this issue for two weeks. Thanks.

A: I just placed the html page (that contain the javascript code) inside WEB-INF and it worked successfully. Previously I ran it outside of the war file and got the above error. Now it works perfectly.


text:
Q: Laravel Vite CSS and JS giving 404 files in production I've been trying to fix this for a couple of days now, on and off, and hope to finally find a fix.
The compiled files of Vite give a 404 when trying to access them in production while they work fine in development. I'm 100% sure the files are there, other things load fine, just not the CSS and JS files. I've double checked if the APP_URL is correct, there is no hot file on production.
I copied the file name in /public/build/assets and went to the url website.com/build/assets/app-c0e92774.css but still getting a 404. File permissions have been set correctly and should be visible to the outside. But I'm sure it's pointed to correctly use the /public folder as the robots.txt loads fine for example.