text:
Q: Appeal to reopen a question To share my recently gained knowledge I've created this question.
Initially it wasn't related to any programming language as this issue concerns color space algorithms in general. After some explanation given me by the moderator who put the question on hold, I've decided to put it in a specific programming context in which I've encountered this issue and vote for reopening.
According to this document this question was initially on-topic, and now is even more (although I feel that putting in the C# context made it loose generality unnecessarily), because:

*

*it is about "a software algorithm"

*it is "practical, answerable problems that are unique to software development"

I think that the first point doesn't need an explanation. The question is about an algorithm, and the answer is an algorithm. The second point: this question is practical because:
1) I've encountered it in a practical context, creating a color classifier :)
2) colour conversions and manipulations are practical concerns existing in large part of software related to graphics or pattern recognition.
Also, this problem is "unique to software development" as the fact that the number of colours is finite in this context is a direct consequence of developing a software on a computer.
What do you think about this?
If you agree, what can I do to have this question reopened?
If not, could you please explain why is it off-topic in the context of the on-topic definition from the Help Center I've referred to?
EDIT: this is another example of the fact, that relations between RGB and LAB spaces are not that uncommon in the programming context: https://stackoverflow.com/search?q=lab+rgb


text:
Q: Adding class to a table in ckeditor without using the advanced Tab dialog I want the associated table tag to be selected after the pop-up closes. but all that I receive is the 'p' tag using startElement. I need a way to get the associated table for which the dialog has opened up. This should be available both for table dialog as well as the tableProperties dialog
I have used the following code but I am unable to get the table element to which I want to add the class. Thanks in advance.
`CKEDITOR.on('dialogDefinition', function (e) {
 var dialogName = e.data.name;
 var dialogDefinition = e.data.definition;
 var dialogContents = dialogDefinition.getContents('info');
 if(dialogName == 'table' || dialogName == 'tableProperties'){
    var classElement =
        {
            type : 'select',
            id : 'class',
            label : 'Class',
            items: [ [ 'Blue' ], [ 'Pink' ], [ 'Green' ], [ 'Black' ] ],
            default: 'Blue'
        };
    dialogContents.add(classElement);
    dialogDefinition.onShow = function () {
       dialogContents.add(classElement);
     };
    dialogDefinition.onHide = function (evt) {
        var cls = this.getValueOf('info','class');
        var thisDialog = CKEDITOR.dialog.getCurrent();
        var startElement = thisDialog.getParentEditor().getSelection().getStartElement();
        var parentTable = jQuery(startElement.$.offsetParent);
        parentTable.addClass(cls);

     }
  }

});`

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to solve the traceback error, when it is not a code issue? So I downloaded this project (https://github.com/alectrocute/flasksaas) on my machine. Interesting is, that on my other computer everything works great, but not on this one.
I am stuck at the point, where I want to initialize the database with following command:
$python manage.py initdb

I reinstalled python, the modules etc., but it doesn't help.
I checked my system environment variables in the settings (OS: Windows), everything seems fine.
Error which occurs:
Traceback (most recent call last):
  File "manage.py", line 4, in <module>
__init__.py, line 6, in <module>
    app.config.from_object('app.config')
NameError: name 'config_dev' is not defined

Expected result:
"SQL database has been created."

A: After looking at the repo's Makefile, you'll find what each make target means:

*

*install : run $ pip install -r requirements.txt

*dev : copy (or link) the config_dev.py to config.py

*prod : copy (or link) the config_prod.py to config.py


text:
Q: Getting chromecast sample code to run I have found no joy in getting any of the sample programs for Chrome to connect to my Chromecasts.
The Chromecasts have been registered and I am able to browse to their IP address port 9222 successfully.
Both the Chrome browser and Beta extension are up to date.
I have tried the CastHelloVideo-Chrome, CastMedia-Chrome and Cast-Tictactoe-Chrome and all fail to connect.  The developer console shows a pair of errors:
GET chrome-extension://boadgeojelhgndaghljhdicfkmllpafd/cast_sender.js net::ERR_FAILED
and
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
When testing our own code we get an error when calling requestSession but the message returned  by Chrome.cast.Error is useless since the function and variable names have been obscured.

A: I also have a difficult time testing the examples for Chrome. I decided to use Chrome to test because debugging JavaScript is so much quicker than going directly to Android. I spent hours trying to figure out why I keep getting the error message  GET chrome-extension://boadgeojelhgndaghljhdicfkmllpafd/cast_sender.js net::ERR_FAILED and Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null') if I run it from my PC but not when I run it from an example website at  http://www.videws.com/eureka/helloVideos/ provided by one of the Cast developers at Google. I keep reading/trying different combinations from  his readme note in the example until it dawned on me what he meant by "Put all files on your own server" instead of "computer".
I created a public weblink on my Google Drive, make the folder public and copied all the files there. When go to Google drive on the web, preview the example (index.html), the example runs beautifully. I tried tic-tac-toe. It also runs.
So the answer is you need to run it off a website -- not from a local file in your computer (ctrl-O in Chrome)
I hope this will help you going with Cast.
Danh

A: I was finally able to get connected, but from Android. Many steps will be the same though.
I tested this:  https://github.com/googlecast/CastHelloText-android  It let's you speak into the phone, and what you say appears on the TV/Chromecast.  I didn't install the formal sender app, but I was able to load the TicTac Toe from the receiver as well.  So i have seen them both on my CC.
I couldn't connect until I properly setup the RECEIVER APPLICATION.  You didn't mention it.
What I did from where I think you are at.. I just double checked my receiver app settings.

*

*File copy the receiver.hml file provided in the sample sender app. Place it in a public dropbox folder.  copy that public link to my clipboard.

*Go back to where you registered your Chromecast device(s). https://cast.google.com/publish -Add An Application.  I called mine :  ReceiverSimple

*Edit the app you just created, and for the URL field: paste in that public link. For you, set the platform to Chrome.   It did not seem to matter whether or not i included the package name, so try leaving it blank.

*Save It. Now COPY to clipboard the ApplicationID for the receiver you just created.

*Open the provided sender app source code, and find where it's using APP_ID (hopefully R.Strings or equivalent in chrome ) Paste that App ID in. That will tell your client to use your receiver app, (and therefore, load that receiver.html file into the chrome cast screen).

also try a chrome cast reboot as another means of sanity checking.
I think you're close.


text:
Q: Is there an efficient way to replace spaces with _ in filenames? (thousands of files) I have a directory "FolderName" with 10,000 new files every day. Almost a half of those files are named as follows:
filename_yyyy-mm-dd_hh:mm

while the other half are named:
filename_yyyy-mm-dd hh:mm

(with space instead of underscore)
The script I'd like to set up should do the following:
Rename only the files containing a space in their name, skipping files that need no processing.
I cannot find a way to make the script efficient, I need to really skip the good half, my script tries to mv any file, and it's quite long and inefficient. Any good idea for a better design?
Thanks everybody

A: Check out the rename utility, a Perl script designed just for this, it's powerful and fast.
rename -n ' ' _ *\ *

Or:
find /path/to/dir -type f -name '* *' -exec rename -n ' ' _ {} \;

The -n flag is for dry run, to print what works happen without actually renaming anything. If the output looks good, remove the flag and rerun.

A: with the legacy rename you can easily convert single space to underlines
$ rename ' ' '_' files

A: for f in "$(find . -name '* *')"; do mv $f $(echo $f | sed 's/\ /_/'); done will do it. There should be a better way using find's -exec option as well.
EDIT:
If the function is put in a script, then find can be used directly:
cat <<EOF > space_to_underscore
#!/usr/bin/env bash
mv "$1" "$(sed 's/\ /_/' <(echo "$1"))"
EOF
chmod +x space_to_underscore

find . -name '* *' -exec ./space_to_underscore {} \;

This will be faster than using a for loop.

A: Rename only the files containing a space in their name, skipping files that need no processing:
for file in *\ * ; do mv "$file" "${file// /_}" ; done

Move all the files older than one week to a "NewFolderName" folder:
find -mtime 7 -exec mv {} NewFolderName/ \;


text:
Q: Occasionally incorrect position of a DIV in Firefox I have an HTML page with the following layout:

The green square is a
 which holds a data grid in the real application. The

has an absolute position. Sometimes, Firefox displays the
 in a wrong place (it has a correct position but in a wrong container):

On other occasions, the
 appears in its proper place. I can reproduce this bug only in Firefox on both my Linux and Windows installations (no problem in Chrome, Opera and IE).
I also can only reproduce it when I access the page over the Internet (it cannot be reproduced when the application is deployed to the localhost web server).
The page is a JSP page and the problem appears most frequently when the server is busy and slow. When I save the page from the browser, and then open the file again, the green
 moves back into its normal place. I think the problem has something to do with the timing of the HTTP response.
The page does not use JavaScript. It has a linked CSS file. Here are the relevant parts of my code:
HTML

 ...

CSS
.b-panels {
    position: relative;
    width: 100%;
    display: table;
}

.b-left-panel {
    display: table-cell;
    width: 190px;
}

.b-center-panel {
    position: relative;
    display: table-cell;
    width: auto;
}

.b-right-panel {
    display: table-cell;
    width: 140px;
}

/* This is the green
! */
.b-center-panel .dataGrid {
    position: absolute;
    left: 20;
    top: 20;
}

How can I fix the problem?

A: Try this:
give the parent div of green div following css
style="position:relative"
by giving this style your green div will take position relative to the parent div.

A: UPDATE:
I found a better solution. Wrapping the green
 with one more
 solved the problem:

 ...

.wrapper {
    position: relative;
    width: 100%;
}

OLD SOLUTION:
I had to use JavaScript/jQuery to fix the problem. I used the following code:
$(document).ready(function() {

    // if the browser is Firefox
    if (!(window.mozInnerScreenX == null)) {

        // get the position of the parent
        var panelLeftPos = $("#dataGrid").parent().position().left;

        // set the position of the green tag
        $("#dataGrid").css({top: 20, left: panelLeftPos + 20, position:'absolute'});
    }
});


text:
Q: Can I use something like DebuggerTypeProxyAttribute on a type that I don't own? I've got an IClaimsPrincipal variable, and I'd like to see how many claims are in it. Navigating through the properties in the watch window is complicated, so I'd like to customize how this object is displayed.
I'm aware of the [DebuggerTypeProxy] attribute, which initially looked like it might do what I want. Unfortunately, it needs to be attached to the class, and I don't "own" the class. In this case it's a Microsoft.IdentityModel.Claims.ClaimsPrincipal.
I'd like to display the value of IClaimsPrincipal.Identities[0].Claims.Count.
Is there any way, using [DebuggerTypeProxy] or similar, to customize how the value of a type that I don't own is displayed in the watch window?

A: Example of DebuggerTypeProxyAttribute applied to KeyValuePair showing only the Value member:
using System.Collections.Generic;
using System.Diagnostics;

[assembly: DebuggerTypeProxy(typeof(ConsoleApp2.KeyValuePairDebuggerTypeProxy<,>), Target = typeof(KeyValuePair<,>))]
// alternative format [assembly: DebuggerTypeProxy(typeof(ConsoleApp2.KeyValuePairDebuggerTypeProxy<,>), TargetTypeName = "System.Collections.Generic.KeyValuePair`2")]

namespace ConsoleApp2
{
    class KeyValuePairDebuggerTypeProxy<TKey, TValue>
    {
        private KeyValuePair<TKey, TValue> _keyValuePair; // beeing non-public this member is hidden
        //public TKey Key => _keyValuePair.Key;
        public TValue Value => _keyValuePair.Value;

        public KeyValuePairDebuggerTypeProxy(KeyValuePair<TKey, TValue> keyValuePair)
        {
            _keyValuePair = keyValuePair;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<int, string>() { [1] = "one", [2] = "two" };
            Debugger.Break();
        }
    }
}

Tested on Visual Studio 2017

A: The best I've come up with so far is to call a method:
public static class DebuggerDisplays
{
    public static int ClaimsPrincipal(IClaimsPrincipal claimsPrincipal)
    {
        return claimsPrincipal.Identities[0].Claims.Count;
    }
}

...from the watch window:
DebuggerDisplays.ClaimsPrincipal(_thePrincipal),ac = 10

The ",ac" suppresses the "This expression causes side effects and will not be evaluated".
However, note that when this goes out of scope, Visual Studio will simply grey out the watch window entry, even with the ",ac". To avoid this, you'll need to ensure that everything is fully qualified, which means that you'll end up with extremely long expressions in the watch window.


text:
Q: Correctly labeling predicted classes when using the Java WEKA library I have a program that trains an algorithm with a 2-class categorical outcome, then runs and writes out predictions (probabilities of each of the 2 classes) for an unlabeled data set.
All data sets run against this program will have the same 2 classes as the outcome. With this in mind I ran the predictions and used a little post-hoc statistics to figure out which column of results described which outcome, and proceeded to hard code them:
public class runPredictions {
public static void runPredictions(ArrayList al2) throws IOException, Exception{
    // Retrieve objects
    Instances newTest = (Instances) al2.get(0);
    Classifier clf = (Classifier) al2.get(1);

    // Print status
    System.out.println("Generating predictions...");

    // create copy
    Instances labeled = new Instances(newTest);

    BufferedWriter outFile = new BufferedWriter(new FileWriter("silverbullet_rro_output.csv"));
    StringBuilder builder = new StringBuilder();

    builder.append("Prob_Retain"+","+"Prob_Attrite"+"\n");
    for (int i = 0; i < labeled.size(); i++)
    {
        double[] clsLabel = clf.distributionForInstance(newTest.instance(i));
        for(int j=0;j<2;j++){
           builder.append(clsLabel[j]+"");
           if(j < clsLabel.length - 1)
               builder.append(",");
        }
        builder.append("\n");
    }
    outFile.write(builder.toString());//save the string representation
    System.out.println("Output file written.");
    System.out.println("Completed successfully!");
    outFile.close();
}
}

The problem with this is that it turns out that which of the 2 columns describes which of the 2 outcome categories is not fixed. It seems to have to do with which category appears first in the training data set, which is entirely arbitrary. So when other data sets were used with this program the hard-coded labels were backwards.
So, I need a better way to label them, but looking at the documentation for Classifier and distributionForInstance and I'm not seeing anything useful.
Update:
I figured out how to print it to the screen (thanks to this), but still had trouble with writing it to csv:
for (int i = 0; i < labeled.size(); i++)
    {
        // Discreet prediction
        double predictionIndex =
            clf.classifyInstance(newTest.instance(i));

        // Get the predicted class label from the predictionIndex.
        String predictedClassLabel =
            newTest.classAttribute().value((int) predictionIndex);

        // Get the prediction probability distribution.
        double[] predictionDistribution =
            clf.distributionForInstance(newTest.instance(i));

        // Print out the true predicted label, and the distribution
        System.out.printf("%5d: predicted=%-10s, distribution=",
                          i, predictedClassLabel);

        // Loop over all the prediction labels in the distribution.
        for (int predictionDistributionIndex = 0;
             predictionDistributionIndex < predictionDistribution.length;
             predictionDistributionIndex++)
        {
            // Get this distribution index's class label.
            String predictionDistributionIndexAsClassLabel =
                newTest.classAttribute().value(
                    predictionDistributionIndex);

            // Get the probability.
            double predictionProbability =
                predictionDistribution[predictionDistributionIndex];

            System.out.printf("[%10s : %6.3f]",
                              predictionDistributionIndexAsClassLabel,
                              predictionProbability );

            // Attempt to write to CSV
            builder.append(i+","+predictedClassLabel+","+
                    predictionDistributionIndexAsClassLabel+","+predictionProbability);
                            //.charAt(0)+','+predictionProbability.charAt(0));

        }

        System.out.printf("\n");
        builder.append("\n");

A: I adapted the code below from this answer and this answer. Basically, you can query the test data for the class attribute, then obtain the specific value for each possible class.
for (int i = 0; i < labeled.size(); i++)
{
// Discreet prediction

double predictionIndex =
    clf.classifyInstance(newTest.instance(i));

// Get the predicted class label from the predictionIndex.
String predictedClassLabel =
    newTest.classAttribute().value((int) predictionIndex);

// Get the prediction probability distribution.
double[] predictionDistribution =
    clf.distributionForInstance(newTest.instance(i));

// Print out the true predicted label, and the distribution
System.out.printf("%5d: predicted=%-10s, distribution=",
                  i, predictedClassLabel);

// Loop over all the prediction labels in the distribution.
for (int predictionDistributionIndex = 0;
     predictionDistributionIndex < predictionDistribution.length;
     predictionDistributionIndex++)
{
    // Get this distribution index's class label.
    String predictionDistributionIndexAsClassLabel =
        newTest.classAttribute().value(
            predictionDistributionIndex);

    // Get the probability.
    double predictionProbability =
        predictionDistribution[predictionDistributionIndex];

    System.out.printf("[%10s : %6.3f]",
                      predictionDistributionIndexAsClassLabel,
                      predictionProbability );

    // Write to CSV
    builder.append(i+","+
            predictionDistributionIndexAsClassLabel+","+predictionProbability);

}

System.out.printf("\n");
builder.append("\n");

}

// Save results in .csv file
outFile.write(builder.toString());//save the string representation


text:
Q: Qt: Update widgets that are hidden before they are then shown? I have two QDialogs stacked on top of each other, with some data is shared between them shown in a QWidget in each dialog's layout (a widget showing a count graphically).
In the QDialog currently shown, the user can change that data. This change gets propagated to both widgets, and the correct count is displayed in the current QDialog. However, when the user closes that QDialog, and the one underneath becomes visible, the QWidget showing the count shows the old value for a split second before it then updates to the correct value.
I know that the QWidget underneath has the correct value before the other QDialog is shown, but I can't seem to get the Dialog to update before it's visible. I tried this while it was still hidden:
hiddenDialog->layout()->activate()
hiddenDialog->layout()->update()
But it still fails to actually update until after dialog is shown. My problem seems sort-of related to Qt: How to force a hidden widget to calculate its layout?, except I want to then show the QDialog after setting Qt::WA_DontShowOnScreen on. After turning on Qt::WA_DontShowOnScreen and updating the dialog, I tried setting:
dialog->setAttribute(Qt::WA_DontShowOnScreen, false);
dialog->show()
But the Dialog remains not shown on screen. Is there any way to make it visible again? Or is there some way to have the dialog and widgets update when they are hidden by the other dialog?

Here's some more details as requested:
There are two classes, Dialog1 and Dialog2, each extending the same base class, BaseDialog, which extends the QDialog class.
BaseDialog has a slot that gets called whenever the GlobalCount is changed. This slot updates a countWidget which draws a picture of the count.
void BaseDialog::updateCountWidget()
{
    _countWidget->updateCount(globalCount);
    _countWidget->update();
}

Dialog1 has a slot (connected from a QPushButton click()) that creates and shows a Dialog2:
void Dialog1::showDialog2()
{
    Dialog2* dialogTwo = new Dialog2();
    dialog2->show();
}

Dialog2 has two slots (connected to QPushButton signals), one subtract from the global count, the other closes the dialog. When the global count is subtracted, it emits a signal connected to the updateCountWidget() slot of both the Dialog1 and Dialog2.
void Dialog2::subtractCount()
{
    GlobalCount.subtractOne();
}

void Dialog2::userClosed()
{
    accept();
}

When I click the subtract button, I can see the _countWidget of Dialog2 update correctly. However, when I close Dialog2, and can once again see Dialog1, the _countWidget of Dialog1 shows the original count value for a split-second, then updates to the new value.
My goal is to prevent this momentary update, as it looks really funky to the user. This has gotten obscenely long, but I appreciate any insights!

A: call
hide()

on widget when you do
setAttribute(Qt::WA_DontShowOnScreen, true);

After that
setAttribute(Qt::WA_DontShowOnScreen, false);
show()

and it will work
I use Qt embedded on Linux

A: You could also try doing a hiddenDialog->layout()->update() before the ->activate(), that worked in a similar case for me, and no need to mess with WA_xxx attributes was required.


text:
Q: A collection and schematic is required during execution error when executing "ng generate environments" I'm using Angular 15 and Node version 18.12.1.
I created a new application in Visual Studio Code but learned that Angular no longer provides the environment files that were for test and production purposes.
I want these environment files back so I followed the instructions from Angular's site.
https://angular.io/guide/build
From PowerShell I entered "ng generate environments" but I get the following error message:
"Error: A collection and schematic is required during execution"
I need help figuring out how to get this working.
I followed the directions on Angular's site and that didn't work.
I also tried updating my version of Node just to be sure it was up-to-date.
None of these resolved my issue to create the environment files.

A: There was a Github issue for this:
https://github.com/angular/angular-cli/issues/24381
Also check this related post:
Angular 15 CLI does not create environments folder when creating an angular project via ng new
EDIT: Found another article about this, apparantly in Angular version 15.1 it should work again:
https://dev.to/this-is-angular/angular-15-what-happened-to-environmentts-koh
So check your current version:
ng version

Do update (if it's 15.0.X):
ng update

Then this should work again:
ng generate environments


text:
Q: How do I write this join in django? Look at this django code:
filtered = Question.objects.filter(children__marked=True).distinct()
return Question.objects.exclude(id__in=filtered)

It returns the list of all questions, except those that have an accepted (marked) answer. I'm trying to make it return questions with upvoted answers as well. See this SQL join:
SELECT * from forum_node AS questions

JOIN forum_node AS answers
ON
questions.node_type = 'question' AND
answers.node_type = 'answer' AND
answers.parent_id = questions.id

WHERE
answers.score > 0 or answers.marked

Now, how do I translate this join into Django?

A: answered = Question.objects.filter(children__marked=True).distinct()
unanswered = Question.objects.exclude(id__in=answered)
upvoted = Question.objects.filter(children__score__gt=0).distinct()
return unanswered | upvoted


text:
Q: Getting the values of argument and function from the contour plot There is an equation F(T,x)=0, which is not solved analytically in the T(x) form. I contour plotted T(x) dependence. How the values of x and T(x) can be constructed in {x_i,T(x_i)} table form? I need 100 points on the contour plotted graphic.

A: I myself would apply the FindRoot wrapped with Table to do this. However, you are right that the ContourPlot also can be used. Since you gave no example, I will take the one from the Help/WolframDocumentation/ContourPlot, that is, the equation
eq=Cos[x] + Cos[y] == 1/2;
plt = ContourPlot[Cos[x] + Cos[y] == 1/2, {x, 0, 4 Pi}, {y, 0, 4 Pi}]

This separates out the points forming the lines of the contour plot:
points = Cases[Normal@plt, Line[pts__] -> pts, Infinity];

Since we have here multiple lines, let us look at them such that we could select the one that we want to analyze:
    Manipulate[
 Graphics[{White, EdgeForm[{Black, Thin}],
   Rectangle[{0, 0}, {13, 13}], Blue, Map[Line, points], Red, Thick,
   Line[points[[n]]]}], {n, Range[9]}, ContentSize -> 250]

Here the value of n selects the part of the list points which contains the line in question. This line is highlighted by the red color. Let us take the central curve corresponding to n=9:
points[[9]]

Evaluate it. There are about 230 points. If you need only about 100 of them the following reduces their number:
lst = First /@ Partition[points[[9]], 2];
Length[lst]

(* 115  *)

The list lst, thus, contains 115 points you need. Done.
Have fun!


text:
Q: Can an ArrayList be null and have a size > 0? I was reviewing a Java project and saw the following code:
List<XYZ> xyzList = new ArrayList<>();

............................
do some things with the list
............................

if (xyzList != null && xyzList.size() > 0) doSomething();

Is there any case where a list can be null but have a size greater than 0? Or is this redundant and equivalent to if (xyzList.size() > 0)?
EDIT: xyzList can be modified from an outside class, so the null check is definitely needed. Thanks for responses, I've just had a long day and my mind was not functioning.

A: An object must exist before you can dereference anything on it.  This is what is being got at with the null-check:  we want to be sure that xyzList exists before we start doing anything on it.
That said, depending on where it was declared, this check may be frivolous.
If you see this on a field that is declared final, then the field could be considered eagerly initialized, and because it's final, you could guarantee that it will never get set back to null.
private final List<XYZ> xyzList = new ArrayList<>(); // guaranteed not null

If you see this in a method, and there are no mutations to the variable at all to set it to a null value, then the null check is pointless, as again - it is not going to change for the lifecycle of that method.
public void someMethod() {
    List<XYZ> xyzList = new ArrayList<>();
    // do other operations without reassigning xyzList
    // null check is useless since the variable is initialized to
    // a non-null value
    if(xyzList != null && !xyzList.empty()) {
        // operation with list
    }
}

This sort of pattern is done on variables which are not guaranteed to be initialized.  If you're eagerly initializing a variable or field, then there's no need to perform this check.

A: The code is ensuring that xyzList is not null before calling size() on it which would result in a crash/exception.
Because of short circuit evaluation, size() will not be called in the if clause when xyzList is null

A: If do some things with the list does not involve setting it to null, then the null check is redundant. A good IDE will spot this while you type and warn you of it.
Otherwise the null check ensures that the size check does not produce a NullPointerException.

A: I am not sure what
............................
do some things with the list
............................

is doing, but my guess is that "xyzList != null && xyzList.size() > 0" are called together because you don't want to end up calling  a method on a null reference. Hence, it is not redundant

A: An Array list can't be NULL & 0 at same time.
But it doesn't meant that a not null array list always have size > 0.
 Array list which is Not Null, can also have size 0.

*

*Always ensure that ArrayList is not null before calling arrayList.size(), to avoid null pointer exception.

example:
if (workImageArrayList != null) {
    Toast.makeText(this, "size : " + workImageArrayList.size(), Toast.LENGTH_SHORT).show();
    //can show ---> size : 0, but its not null.
} else {
    Log.e("WorkImageArrayList", "" + workImageArrayList);
    //arraylist is null.
}

A: This line construct a new empty ArrayList object with size = 0 and make the xyzList pointer points to that object.
List<XYZ> xyzList = new ArrayList<>();

xyzList pointer is null when it does not point to any object.
List<XYZ> xyzList;

Therefore, an ArrayList can either be null or have a size > 0, not both


text:
Q: Creating ext4 filesystem on 20TB Raid5 is still running - has it stalled or is this a very long process? I have a 20TB (4x5TB) RAID5 aray (please hold comments about RAID5, I know a lot of people don't like it) that I recently setup, through Webmin, on 18.04.3LTS ubuntu server.
I am not creating the filesystem (through Webmin) and it seems to be taking a very long time - it's been going (I think) for at least 24 hours now.
The command Webmin runs is
Executing command partprobe ; mkfs -t ext4 -c -q /dev/md0 ..

Since running, I am just getting the equivalent of the pinwheel - there is no progress bar to indicate if it's still actually working or has stalled.
In the 'Running Process' section of Webmin, the following two are at the top of the list
27638   root    12.7 %  [md0_raid5]
21798   root    10.4 %  badblocks -b 4096 -X /dev/md0 3662728703

I suspect maybe I ticked an option for it to check the array for badblocks, while creating filesystem, which might slow it down considerably? but I don't know what I don't know here.
Additionally, the activity LED on the drives are showing constant activity.
I am guessing this all means it's still progressing, but I was hoping there may be a command to run that may give me a progress indication? or may someone has completed a similar process and can give me an indication of how long I should wait before quitting and staring over?
UPDATE: this thread suggest it's badblocks and I'll probably be waiting 400+ hours...
If so, is there a way to kill the badblock process and have it just finish off the mkfs.ext4? Else, what commands should I run to start it again with just filesytem creation?

A: killed the badblock process (through the webmin process manager GUI). Didn't seem to cause an issue with the file-system as I was able to mount it (again, though the webmin raid manager GUI), so am assuming badblock and mkfs (filesystem creation) run independent of each other.


text:
Q: CSS Grid Elements Positioning on Window Resize
I have 4 divs, which on medium size windows look as bellow:

 ------------   ------------
| top-left    |  top right   |
 ------------   ------------
| bottom left |  bottom right|
 ------------   ------------

Given the code snippet attached, on small devices, the following
  positioning occurs:

 -------------
| top-left    |
 -------------
| bottom left |
 -------------
| top-right   |
 -------------
| bottom right|
 -------------

My desired positioning is:

 -------------
| top-left    |
 -------------
| top-right   |
 -------------
| bottom left |
 -------------
| bottom right|
 -------------

I would have expected that
  grid-template-areas:
      'top-left-container'
      'top-right-container'
      'bottom-left-container'
      'bottom-right-container';

would fulfill this, but it doesn't.
Any ideas why and how can this be achieved?

@media (min-width: 768px) {
  .container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: auto auto;
    grid-column-gap: 50px;
    grid-template-areas:
      'top-left-container top-right-container'
      'bottom-left-container bottom-right-container';
  }
}

@media (max-width: 768px) {
  .container {
    display: grid;
    grid-template-columns: auto;
    grid-template-rows: auto;
    grid-template-areas:
      'top-left-container'
      'top-right-container'
      'bottom-left-container'
      'bottom-right-container';
  }
}
.left {
  border: 3px solid gray;
}

.right {
  border: 3px solid gray;
}

.top-left {
  background: yellow;
  grid-area: top-left-container;
  height: 100px;
}

.top-right {
  background: yellow;
  grid-area: top-right-container;
  height: 100px;
}

.bottom-left {
  background: red;
  grid-area: bottom-left-container;
}

.bottom-right {
  background: red;
  grid-area: bottom-right-container;
  align-self: end;
}

      Top left

      Bottom left

      Top right

      Bottom right

A: So I'm not sure what to do with borders, but basically you have to have the structure flat for the grid to work and apply each border side individually however you want.

@media (min-width: 768px) {
  .container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: auto auto;
    grid-column-gap: 50px;
    grid-template-areas:
      'top-left-container top-right-container'
      'bottom-left-container bottom-right-container';
  }

  .top-left {
    border-top: 3px solid gray;
    border-left: 3px solid gray;
    border-right: 3px solid gray;
  }

  .top-right {
    border-top: 3px solid gray;
    border-left: 3px solid gray;
    border-right: 3px solid gray;
  }

  .bottom-left {
    border-bottom: 3px solid gray;
    border-left: 3px solid gray;
    border-right: 3px solid gray;
  }

  .bottom-right {
    border-bottom: 3px solid gray;
    border-left: 3px solid gray;
    border-right: 3px solid gray;
  }
}

@media (max-width: 768px) {
  .container {
    display: grid;
    grid-template-columns: auto;
    grid-template-rows: auto;
    grid-template-areas:
      'top-left-container'
      'top-right-container'
      'bottom-left-container'
      'bottom-right-container';
  }

  .top-left {
    border-top: 3px solid gray;
    border-left: 3px solid gray;
    border-right: 3px solid gray;
  }

  .top-right {
    border-bottom: 3px solid gray;
    border-left: 3px solid gray;
    border-right: 3px solid gray;
  }

  .bottom-left {
    border-top: 3px solid gray;
    border-left: 3px solid gray;
    border-right: 3px solid gray;
  }

  .bottom-right {
    border-bottom: 3px solid gray;
    border-left: 3px solid gray;
    border-right: 3px solid gray;
  }
}
.left {
  border: 3px solid gray;
}

.right {
  border: 3px solid gray;
}

.top-left {
  background: yellow;
  grid-area: top-left-container;
  height: 100px;
}

.top-right {
  background: yellow;
  grid-area: top-right-container;
  height: 100px;
}

.bottom-left {
  background: red;
  grid-area: bottom-left-container;
}

.bottom-right {
  background: red;
  grid-area: bottom-right-container;
  align-self: end;
}

      Top left

      Bottom left

      Top right

      Bottom right


text:
Q: AngularJS: function is not a function I have an AngularJS app, and on one of the pages, I have a number of widgets, each one displaying some information about the status of a part of the system.
I am currently working on adding the functionality to allow the user to 'hide' the heading of a given widget.
There is a 'Settings' button on the page where the widgets are displayed, which, when clicked, overlays a toolbar on top of each of the widgets. The toolbar has a number of buttons- one of which is another 'Settings' button, which opens up a dialog that allows the user to change the settings for that particular widget.
I have added a checkbox to the dialog, to enable the user to 'hide' the heading for that particular widget from view:

When the checkbox is selected on the dialog, and the user clicks 'Preview', I am expecting (eventually- I'm still working on the implementation of the feature) the heading for that particular widget to be hidden. However, currently, when the user clicks 'Preview', whether the checkbox is selected or not, I am getting an error in the console that says:

TypeError: $scope.widget.toggleWidgetHeading is not a function

This error is coming from the $scope.preview function in ctrl.js called when the 'Preview' button is clicked on the dialog:
}).controller('WidgetPickerCtrl', function($scope, $timeout, fxTag, gPresets, appWidget) {
    ...
    $scope.preview = function(e) {
        $scope.widget.toggleWidgetHeading();
        ...
    };
    ...
});

I don't understand why I'm getting this console error, since toggleWidgetHeading() clearly is a function...
If I right-click on the function call above in Sublime, and select 'Go to definition', I am taken to the directive.js file where the function is defined:
.directive('appWidget', function($timeout, fxTag, appColorFilter) {
    return {
        ...
        link: function($scope, $element){
            ...
            var toggleWidgetHeading = function(){
                ...
            }
            ...
        }
    }
})

Also, clicking the 'Preview' button on the dialog no longer closes the dialog...
Why is it that I'm being told that this function call is not a function when it is clearly defined as one? Is the issue here something to do with the scope (i.e. the fact that I'm calling the function from ctrl.js, even though it's defined in directive.js)?

A: The definition of your directive, where you added ..., is actually a really relevant part about directives scopes.
Directives can implement several kind of scopes. You can actually inherit and access the parent scope, or you can have an isolated scope for example.
You may read about that in the official documentation where is well explained:
https://docs.angularjs.org/guide/directive
However, whatever will be the scope you use, by default AngularJS implements the inheritance of scopes, as usually inheritance works: children can access parent methods, but parent cannot access children's methods.
Here it seems that from the parent scope (the controller) you are trying to access the directive's scope, which is actually no possible. (even if in the link function you define the toggleWidgetHeading as private variable, and not associated to the $scope itself - but it won't work either).
So you have few options in these cases:

*

*Define your "visible properties" inside a service and inject the service inside the directive and the controller. Then use the service in order to access and change these values, so that they will be sync between the controller and the directive

*Add a scope parameter to the directive as callback & and provide a function from the controller which returns the chosen visibility of the widget, so from the directive you can call that function and get back the value of widget's visibility

*Add a scope parameter as two way data binding = in the directive, which is bound to the widget's visibility of the controller, so that you have that always sync between your controller and your directive

*Use events in order to communicate between the controller and the directive, broadcasting an event from the controller when the visibility changes, and reading the event from the directive getting the widget's visibility value

I hope it makes sense


text:
Q: Sorting the documents by ignoring the case in Mongodb? We are using old version of Mongodb so collation does not work and we not using indexes.
Documents are saved in MongoDB collection:
{ "_id" : ObjectId("5223850fa89de4a9f691dacf"), "name" : "B" }
{ "_id" : ObjectId("52238511a89de4a9f691dad0"), "name" : "c" }
{ "_id" : ObjectId("52238515a89de4a9f691dad1"), "name" : "A" }
{ "_id" : ObjectId("52238522a89de4a9f691dad2"), "name" : "z" }
{ "_id" : ObjectId("5223852ea89de4a9f691dad3"), "name" : "X" }

I am querying, sorting by name:
db.collection.find().sort({name:1});

and the result is:
{ "_id" : ObjectId("52238515a89de4a9f691dad1"), "name" : "A" }
{ "_id" : ObjectId("5223850fa89de4a9f691dacf"), "name" : "B" }
{ "_id" : ObjectId("5223852ea89de4a9f691dad3"), "name" : "X" }
{ "_id" : ObjectId("52238511a89de4a9f691dad0"), "name" : "c" }
{ "_id" : ObjectId("52238522a89de4a9f691dad2"), "name" : "z" }

Thank you for your help in advance.

A: Demo - https://mongoplayground.net/p/OkphOyxTMo2
Use $toLower to convert name to the lower case in caseInsensitiveName and perform $sort on it.

Converts a string to lowercase, returning the result.

you can use $toUpper as well.
db.collection.aggregate([
  {
    $project: {
      name: 1,
      caseInsensitiveName: {
        $toLower: "$name"
      }
    }
  },
  {
    $sort: {
      caseInsensitiveName: 1
    }
  }
])

A: I think you can do it with Collation:
db.collection.find({}).collation({strength: 1}).sort({ name: 1 })


text:
Q: How to resolve Error = 1001 "No Fill" using Facebook Audience Network in android I have an Android version of my app and integrated FAN into my Application.
It worked for some months but now it's displaying "NO FILL"
Error Domain=com.facebook.ads.sdk Code=**1001 "No fill"**
UserInfo={NSLocalizedDescription=**No fill**,
FBAdErrorDetailKey={ msg = "**No fill**"}}

And no FAN ad is shown. If I put a testing ID then it's displaying, but only on my device, not for another device.
How to resolve this problem "No Fill"?
compile 'com.facebook.android:audience-network-sdk:4.+'

Mentioned in build.gradle
I've seen many questions regarding this but unable to find an answer.
I've already seen below links:

*

*Facebook AudienceNetwork loaded failure: No fill, Error Message "No fill", what is the reason about FaceBook android Advertise?

*facebook audience network testing on test flight No Fill

*Audience Network iOS Ads Suddenly Become "No Fill"

*Facebook Audience Network returns "No fill"

*Testing Audience Network Implementation

A: Try this.It solves my problem .
you have to follow this steps for solve this problem In this all screenshot and steps are given .
May this help you. Because of the update in facebook developer console in audience Network tab ad-spaces group that is newly created from placements. You have to follow this steps. Might it helps others.
I have also posted screenshot along with steps details.
here Click on up-grouped for appName and then follow steps.

*

*Tick check-mark box for any one ad then make placements button will be enable.

*Enter name and description related to where ad will display in your app and then click on Move Button

*After move one ad you can also select other ad from un-grouped ad and move it to ad-spaces , here it will shoe you choice for move to existing or create new one ad-space.

*If you want to create new one then select radio button for new one . and click move after enter name and description.

A: You need add the test device to test it before your app approved by Facebook. Here is how you can get the device hash.
NSLog(@"the test device hash is %@",[FBAdSettings testDeviceHash]);

Run the app and copy the testDeviceHash from logs then add it to FBAdSettings.
[FBAdSettings addTestDevice:@"YOUR_TEST_DEVICE_HASH_CODE_HERE"];

You need to do it before you init the FBAdView

A: I got same error when I want testing ad.
Error: No Fill error code [1001] No fill. We are not able to serve ads to this person.
I didn't register for AD because my app is not live at that moment. So, I don't have advertise Id . I'm using test id "YOUR_PLACEMENT_ID" for demo propose when I got that error. So only test id is not enough for get testing ads in Facebook Ad.
I found solution for that as below.
When You're initialize AudienceNetworkAds then just enable testmode that's it.

AdSettings.setTestMode(true)

class AudienceNetworkInitializeHelper : AudienceNetworkAds.InitListener {

        override fun onInitialized(result: AudienceNetworkAds.InitResult) {
            Log.d(AudienceNetworkAds.TAG, result.message)
        }

        companion object {

            internal fun initialize(context: Context) {
                if (!AudienceNetworkAds.isInitialized(context)) {
                    if (DEBUG) {
                        AdSettings.turnOnSDKDebugger(context)
                        AdSettings.setTestMode(true)// for get test ad in your device
                    }

                    AudienceNetworkAds
                            .buildInitSettings(context)
                            .withInitListener(AudienceNetworkInitializeHelper())
                            .initialize()
                }
            }
        }
}

My audience-network-sdk is implementation 'com.facebook.android:audience-network-sdk:5.4.0'
  and It's work also in 5.6.0 .

A: I managed to resolve this issue. My steps:
1. Make sure to set the test device hash in your code

*

*Start by testing from the xCode simulator and not your device to make sure it works well.

*Add this log somewhere (e.g. viewDidLoad) to display your xCode simulator device hash:

NSLog(@"%@",[FBAdSettings testDeviceHash]);

*

*Then set it in your code:

[FBAdSettings addTestDevice:@"YOUR_TEST_DEVICE_HASH"];

2. Make sure you're using the correct placementID

*

*Go to Monetization Manager home page

*Expand Integration on the left menu

*Click on Properties

*Copy the ID of your properties and paste it in your code:

- (void)loadNativeAd{
    FBNativeAd *nativeAd = [[FBNativeAd alloc] initWithPlacementID:@"YOUR_PLACEMENT_ID"];
    nativeAd.delegate = self;
    NSLog(@"%@",[FBAdSettings testDeviceHash]);
    [FBAdSettings addTestDevice:@"YOUR_TEST_DEVICE_HASH"];
    [nativeAd loadAd];
}

It worked for me.

A: Try this version,and check that it's working or not
implementation 'com.facebook.android:audience-network-sdk:5.1.0'

A: My problem was solved, until I logged in with my admin account into facebook app and download again my application from google play.
A few suggestions for you problem:
"No Fill" with error code 1001 -  is a common error, FAN not returning ads to your ad.
Ensure the following things:
 - Ad Status with Placement ID (Audience Network> Ad Space> Placement) must be "Enabled and received ad request recently" (1)
- Your Ad Status must be reviewed and approved by facebook. (2)
If (1), you can try to disable and enable again.
If (2), you must download the facebook app from google play + login with administrator account / or developer / testers (added in Roles tab)), I recommend login with admin account; and download your app directly from google play.
You said your application has been active for some time, and the above things is right, the last is send a message to the Audience Network Team and they will reply in 3-5 business days.


text:
Q: Include check_command with nagios/icinga alerts Is there a way to include the check_command that is being used when being alerted via Nagios or Icinga.
Example:
define command {
        command_name    check-x-dc6.x-icmp
        command_line    $USER1$/check_ping -H IP -w 100.0,20% -c 500.0,60%
}
Basically what im looking for is the command_line of this command to be included in the alerting system for nagios/icinga?

A: Include the $HOSTCHECKCOMMAND$ macro in your notification command. (Or $SERVICECHECKCOMMAND$ for service checks).
See the list of macros that you can use for more information.


text:
Q: How to shuffle an array of objects in javascript? The code below works for a normal array but not with an array with object does anybody knows how to do this?

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    let temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

const result = shuffle(array);

console.log(JSON.stringify(result));

A: Try sorting like this snippet:

console.log( [
    { some: 1 },
    { some: 2 },
    { some: 3 },
    { some: 4 },
    { some: 5 },
    { some: 6 },
    { some: 7 },
  ]
  .sort( () => Math.random() - 0.5) );

In reponse to Martin Omanders comment: here's a shuffle method according to the Fisher-Yates algorithm

const result = document.querySelector("pre");
for (let i=0; i<20; i+=1) {
  result.textContent +=
    JSON.stringify(shuffleFisherYates([0,1,2,3,4,5,6,7,8,9])) + '\n';
}

function shuffleFisherYates(array) {
  let i = array.length;
  while (i--) {
    const ri = Math.floor(Math.random() * i);
    [array[i], array[ri]] = [array[ri], array[i]];
  }
  return array;
}

Which may be condensed to a one liner (note: this one liner will not compile in the Google Closure Compiler with level advanced):

const shuffle = array =>
  [...Array(array.length)]
    .map((el, i) => Math.floor(Math.random() * i))
    .reduce( (a, rv, i) => ([a[i], a[rv]] = [a[rv], a[i]]) && a, array);
const result = document.querySelector("pre");
for (let i=0; i<100; i+=1)
  result.textContent +=
   JSON.stringify(shuffle([0,1,2,3,4,5,6,7,8,9])) + '\n';

A: Here is one more example based on lodash _.shuffle.

const array = [
    { some: 1 },
    { some: 2 },
    { some: 3 },
    { some: 4 },
    { some: 5 },
    { some: 6 },
    { some: 7 },
  ];
console.log(_.shuffle(array));

A: If you need to shuffle a collection of element nodes (in the DOM), convert it to an array first:
var wrapper = document.getElementById('someid');
var array = Array.prototype.slice.call(wrapper.children);

Shuffling a HTMLCollection object (as returned by children) directly doesn't work even if you can iterate the collection with a for loop. This stumbled me for a while.


text:
Q: Get selected Value in ListView c# I just want to get the selected item in my ListView.
This the XAML:
<TabItem Header="Musique" Background="#1874CD" BorderBrush="#68838B">
    <ListView x:Name="ListM" Width="Auto" Background="#D1EEEE" ItemsSource="{Binding Path=MediaCollection}" Margin="-8,-0.877,-1,-2.925" SelectionChanged="ListM_SelectionChanged">
        <ListView.View>
            <GridView AllowsColumnReorder="True" >
                <GridViewColumn Header="" Width="Auto" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Image Name="IconImage" Source="{Binding IconUri}" Panel.ZIndex="2" Width="15" Height="15"></Image>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn DisplayMemberBinding="{Binding Title}" Header="Titre" Width="auto" />
                <GridViewColumn DisplayMemberBinding="{Binding Composer}" Header="Artiste" Width="70" />
                <GridViewColumn DisplayMemberBinding="{Binding Length}" Header="Durée" Width="50" />
                <GridViewColumn DisplayMemberBinding="{Binding Album}" Header="Album" Width="70" />
            </GridView>
        </ListView.View>
    </ListView>

I insert item with this piece of code :
ListM.Items.Add(new ListGrid() { IconUri = imagemp3.Source, Title = Ftitle, Length = duration, Album = Falbum, Composer = Fcomposer });

I need to get these details (Title, Length, ...) when I select an item on my list. I've tried but had many issues and it still doesn't work.

A: Just cast the SelectedItem to your type:
private void ListM_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  var listgrid = (ListGrid)ListM.SelectedItem;
}

But it seems you are mixing something. You are using DataBinding (ItemsSource) but you also manually add items.
Better you only use DataBinding by adding the items to MediaCollection in your ViewModel and bind the SelectedItem to another property in the ViewModel:
in XAML:
SelectedItem="{Binding SelectedItem}"

A: Using SelectedItems :
SelectedItems is the set of selected rows,
If you want to get only the Title:
string age = ListM.SelectedItems[0].SubItems[0].Text;

If you want to get all the details :
ListM.SelectedItems[0] returns an object. You first need to cast it to its specific type before you can access its members.
Create a Media class (Title, Composer...), then :
private void getSelectedIteminListView(object sender, MouseButtonEventArgs e)
{
    Media media = (Media)ListM.SelectedItems[0];
}

Don't forget to add the event :
ListM.DoubleClick += getSelectedIteminListView;

A: I finaly listen to @M.REJEB

    private void ListM_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListGrid media = (ListGrid)ListM.SelectedItems[0];
        string age = media.Title;
        MessageBox.Show("Selected : " + age);
    }

And it works with this class :

    class ListGrid
    {
        public string Path { get; set; }
        public string Title { get; set; }
        public System.TimeSpan Length { get; set; }
        public string Album { get; set; }
        public string Composer { get; set; }
        public System.Windows.Media.ImageSource IconUri { get; set; }
    }


text:
Q: Access and update PFObject from TableViewController I am new to iOS coding, and Parse, but have a question. I have created a table view which accesses the PFObjects and displays them correctly. My problem is that I have a button in each cell (a like button) and I want it to update the specific PFObject when pressed. How do I access it?
class chinTwoTimelineTableViewController: UITableViewController {

var timelineData:NSMutableArray = NSMutableArray()

func loadData() {
    timelineData.removeAllObjects()

    var findTimelineData:PFQuery = PFQuery(className: "ChinTwos")

    findTimelineData.findObjectsInBackgroundWithBlock{
        (objects:[AnyObject]?, error:NSError?)->Void in

        if let objects = findTimelineData.findObjects() as? [PFObject] {

            if error == nil{
                for object in objects{
                    let chinTwo:PFObject = object as PFObject
                    self.timelineData.addObject(chinTwo)
                }

                let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects
                self.timelineData = NSMutableArray(array: array)

                self.tableView.reloadData()

            }
        }
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:ChinTwoTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ChinTwoTableViewCell

    // Configure the cell...

    let chinTwo:PFObject = self.timelineData.objectAtIndex(indexPath.row) as! PFObject

    var myVar:Int = chinUp.objectForKey("likeCount") as! Int
    cell.countLabel.text = String(myVar)

    cell.nameLabel.text = chinUp.objectForKey("name") as? String
    cell.bodyText.text = chinUp.objectForKey("body") as! String

    cell.bodyText.font = UIFont(name: "HelveticaNeue-UltraLight", size: 18)
    cell.bodyText.textAlignment = .Center

    return cell
}

@IBAction func likeButtonTapped(sender: AnyObject) {
    // This is where I am lost.

}
If you need more information to help, let me know, I really appreciate it.

A: You can get the selected IndexPath using convertPoint then get the PFObject from the array.
@IBAction func likeButtonTapped(sender: AnyObject) {
    // This is where I am lost.
        var senderPoint = sender.convertPoint(sender.bounds.origin, toView: self?.tableView)
       var indexPath = self?.tableView.indexPathForRowAtPoint(senderPoint)
       let chinTwo:PFObject = self.timelineData.objectAtIndex(indexPath.row) as! PFObject
}

Good luck


text:
Q: How to generate graphical sitemap of large website I would like to generate a graphical sitemap for my website. There are two stages, as far as I can tell:

*

*crawl the website and analyse the link relationship to extract the tree structure

*generate a visually pleasing render of the tree

Does anyone have advice or experience with achieving this, or know of existing work I can build on (ideally in Python)?
I came across some nice CSS for rendering the tree, but it only works for 3 levels.
Thanks

A: The only automatic way to create a sitemap is to know the structure of your site and write a program which builds on that knowledge. Just crawling the links won't usually work because links can be between any pages so you get a graph (i.e. connections between nodes). There is no way to convert a graph into a tree in the general case.
So you must identify the structure of your tree yourself and then crawl the relevant pages to get the titles of the pages.
As for "but it only works for 3 levels": Three levels is more than enough. If you try to create more levels, your sitemap will become unusable (too big, too wide). No one will want to download a 1MB sitemap and then scroll through 100'000 pages of links. If your site grows that big, then you must implement some kind of search.

A: Here is a python web crawler, which should make a good starting point. Your general strategy is this:

*

*you need to take care that outbound links are never followed, including links on the same domain but higher up than your starting point.

*as you spider, the site collect a hash of page urls mapped to a list of all the internal urls included in each page.

*take a pass over this list, assigning a token to each unique url.

*use your hash of {token => [tokens]} to generate a graphviz file that will lay out a graph for you

*convert the graphviz output into an imagemap where each node links to its corresponding webpage

The reason you need to do all this is, as leonm noted, that websites are graphs, not trees, and laying out graphs is a harder problem than you can do in a simple piece of javascript and css. Graphviz is good at what it does.

A: Please see http://aaron.oirt.rutgers.edu/myapp/docs/W1100_2200.TreeView
on how to format tree views.  You can also probably modify the example application
http://aaron.oirt.rutgers.edu/myapp/DirectoryTree/index to scrape your
pages if they are organized as directories of HTML files.


text:
Q: removing extensions in a column I have a file like this
ILMN_1343291    TGTGTTGAGAGCTTCTCAGACTATCCACCTTTGGGTCGCTTTGCTGTTCG  NM_001402.5
ILMN_1343295    CTTCAACAGCGACACCCACTCCTCCACCTTTGACGCTGGGGCTGGCATTG  NM_002046.3
ILMN_1651209    TCACGGCGTACGCCCTCATGGGGAAAATCTCCCCGGTGACTTTCAGGTCC  NM_182838.1

I want to remove the numeric extensions from the end in the 3rd column so that my output file looks like this
ILMN_1343291    TGTGTTGAGAGCTTCTCAGACTATCCACCTTTGGGTCGCTTTGCTGTTCG  NM_001402
ILMN_1343295    CTTCAACAGCGACACCCACTCCTCCACCTTTGACGCTGGGGCTGGCATTG  NM_002046
ILMN_1651209    TCACGGCGTACGCCCTCATGGGGAAAATCTCCCCGGTGACTTTCAGGTCC  NM_182838

How can I do it on command line preferably using awk? I can do this in perl but I am pretty sure there is a single command line to do it.

A: With awk:
awk -F'.' '{print $1}' file

-F option change default field separator(space) to dot(.).
$1 is index of field position(with . field separator).
{ILMN_1343291    TGTGTTGAGAGCTTCTCAGACTATCCACCTTTGGGTCGCTTTGCTGTTCG  NM_001402}.{5}
                  ^^ field index is $1                                          ^^$2

With rev and awk:
rev file | awk -F'.' '{print $2}'|rev # reverse characters of each lines,\
                                        print field number 2 with (.) separator \
                                        and reverse the result again

The rev utility copies the specified files to standard output, reversing the order of characters in every line. If no files are specified, standard input is read.
With sed:
sed 's/.[0-9]*$//' file

sed 's/.[^.]*$//' file

$ point to end of line. In first sed command search for char(.) which followed by zero or more occurrences of numbers and replace them with whitespace.
In second sed command remove everything that followed by (.) and also remove dot(.) itself.
With rev and sed:
rev file| sed 's/.*[.]//' |rev

Delete everything before dot(.) Also include and remove . itself.
With grep:
grep -oP '.*(?=\.[0-9])' file

    -o, --only-matching
          Print only the matched (non-empty) parts of a matching line,
          with each such part on a separate output line.
    -P, --perl-regexp
          Interpret PATTERN as a Perl compatible regular expression (PCRE)

(?=pattern): Positive Lookahead: The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign.
.*(?=\.[0-9]): (positive lookahead) matches everything(.*) followed by one dot(.) and any occurrences of numbers, without making the pattern(\.[0-9]) part of the match.
With rev and grep:
rev file |grep -oP '(?<=[0-9]\.).*' |rev

rev file |grep -oP '[0-9]\.\K.*' |rev

(?<=pattern): Positive Lookbehind. A pair of parentheses, with the opening parenthesis followed by a question mark, "less than" symbol, and an equals sign.
(?<=[0-9]\.).* (positive lookbehind) matches everything which followed by any occurrences of numbers and end with dot(.).
In second grep command, you can use the nifty \K in place of the lookbehind assertion.
With cut:
cut -f1 -d. file

cut -c 1-77 file # Print first 77 characters of each line.

cut - remove sections from each line of files

-d, --delimiter=DELIM
      use DELIM instead of TAB for field delimiter

-f, --fields=LIST
      select  only  these  fields;

-c, --characters=LIST
      select only these characters

With while loop:
while read line; do echo "${line::-2}";done <file

This will work if you have only number with length=1 at the end of each lines and they are fix length. above command remove last two character at the end of every lines in input file. alternative commands is ${line%??}.

A: Assuming the extensions are all-digit:
perl -pi -e 's/\.\d+$//' /path/to/file

-i does in-place editing (like in sed). \d means digits, and $ denotes the  end of the line.
With awk:
awk 'gsub(/\.[0-9]+$/,"")' /path/to/file

gawk has an in-place editing option in newer versions, but I am not sure how portable that is. gsub supports an optional parameter, specifying the target column:
awk 'gsub(/\.[0-9]+$/,"",$3)' /path/to/file

The last form has the undesired side-effect of separating each column by a single space in its output, as if you'd done print $1,..,$NF. I do not know why.

A: Using awk it is straightforward, just set your field separator as .:
awk -F. '{print $1}' file
Another approach, using the shell (in this case bash):
while IFS=.; read -r lines _; do  line+=("$lines"); done <file
printf "%s\n" "${line[@]}"
ILMN_1343291    TGTGTTGAGAGCTTCTCAGACTATCCACCTTTGGGTCGCTTTGCTGTTCG  NM_001402
ILMN_1343295    CTTCAACAGCGACACCCACTCCTCCACCTTTGACGCTGGGGCTGGCATTG  NM_002046
ILMN_1651209    TCACGGCGTACGCCCTCATGGGGAAAATCTCCCCGGTGACTTTCAGGTCC  NM_182838

A: With sed, you can do:
sed 's/\.[0-9][0-9]*$//' x.txt

Assuming the filename is x.txt. If you want to modify the file inline, use the -i switch of sed as below:
sed -i 's/\.[0-9][0-9]*$//' x.txt

If you want to preserve the contents of original file, use redirection as below:
sed 's/\.[0-9][0-9]*$//' x.txt > newfile.txt

A: This removes everything starting with the dot:
sed 's/\..*//'


text:
Q: Firebase Hosting from freenom (dot.tk) I would like to host my webapp on Firebase, since I'm using their services and functionalities since a long time (before Firebase was inside Google and since its static hosting service was named Divshot... ).
But I've got a demo domain from Freenom (.tk domain) and I was wondering how to connect this with firebase:
I can set only this paramater relative to TXT record:
dns management
so where should I define the parameters needed
google-site-verification=...
?
Thank You to all!
PS: I've already seen
Firebase hosting custom domain error
and related
firebase-talk Dqmz9Iuio54
and
and the question: how-can-i-verify-my-custom-domain-using-domains-google-com/39020649#39020649
but none of them seems to respond to my problem...
PS: I've come here from firebase support page where StackOverflow is the first choice.
Thank you!

A: Leave the "Name" field blank and fill "Target" with the google-site-verification=... value. Once you've done so, things should go through. One way to check is to run:
dig yourdomain.tk TXT

If you've done it correctly, you should receive back the google-site-verification=... value. It may take some time to propagate before it starts showing up.

A: *

*DNS registrar / records host: delete TXT records pointing to
firebase.

*firebase console: delete the custom domain.

*firebase console: add custom domain.

*copy the two TXT records from firebase to DNS host

*DNS record host should include two entries with one yourdomain.tk and www.yourdomain.tk

*Once the yourdomain.tk is added it'll  show as empty and other entry will be shown as www.

*The copy the two given A records to Freenom DNS records.

*There will be 4 A records two for yourdomain.tk and two for www.yourdomain.tk.

*Wait 24-48 hours to see if the changes work.

*If it doesn't work, contact firebase support from the console; be sure to take screen shots of the DNS records and the firebase console. These will help the firebase support team to troubleshoot the problem.
Mean while you can check for the dns propagation by using below tutorial

The Firebase Hosting servers run what is essentially this command for verifying the TXT records for your domain:
dig -t txt +noall +answer yourdomain.tk

If you immediately run this command right now, you might not get results. If the Firebase servers are seeing the same in their DNS query, they will not be able to continue.
That means that either you didn't save/apply your changes yet, or they haven't propagated everywhere yet. The longer it takes for the changes to show up, the more likely it becomes that you still need to take some action at your DNS provider


text:
Q: wordpress ajax form submission is not working? Here is the code..I think action i ajax not working and getting 403 error! using Wamp and running Wordpress on it
js code
    jQuery('#InsertionForm').submit(
function (){
var x = jQuery('#nm').val();
var y = jQuery('#em').val();

jQuery.ajax({
type:"POST",

url: "<?php echo admin_url('admin-ajax.php'); ?>",

data: {
        action: 'get_my_option',
        namo: x,
        emao: y
    },

success:function(){
    alert("working");
}
});

return false;

});

main plugin code ..please can anyone tell me ...the given bellow code is in right sequence or not?
    <?php

/*

Plugin Name: lucky

*/

//adding script files in HTML

wp_enqueue_script('myscript', plugins_url('myscript.js', __FILE__),

array('jquery'), '', true);

wp_localize_script( 'myscript', 'my_ajax_object',

            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

function get_my_option()

{

    //do something

   alert("this is a function action: in ajax");

}

add_action("wp_ajax_nopriv_get_my_option", "get_my_option");

add_action("wp_ajax_get_my_option", "get_my_option");

    #Shortcode function.........................................

function html_form_code() {

    global $wpdb;

    # Input form fields.....

    echo '<form method="post" id="InsertionForm">';

    echo '
Insertion Form
';

    echo '
Your Name (required)
';

    echo '<input id="nm" type="text" name="namel" value="" size="40" />';

    echo '
';

    echo '
';

    echo 'Your Email (required)
';

    echo '<input id="em" type="email" name="emaill" value="" size="40" />';

    echo '
';

    echo '
<input type="submit" name="submitbtn" value="Send"> ';

    echo '</form>';
}

function my_ajax() {

    $nom = $_POST['namo'];

    $emo = $_POST['emao'];

    global $wpdb;

    $wpdb -> insert( 'lucky_wpdb', array('namel' => $nom, 'emaill' => $emo)

);

echo 'Submitted';

}

    //Shortcode working here....

add_shortcode( 'sitepoint_contact_form', 'html_form_code' );

?>

A: To make ajax action work you need to defined the separate actions for logged in and not-logged in users.
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );

where wp_ajax_nopriv_ means for not logged in user and wp_ajax_ means logged in user also my_action is your actual action. they can call to send action method or different depending on your requirements

A: Why is there alert in your action method get_my_option?
And to work with ajax in WP you should echo and them die;
try this
function get_my_option()

{
    //do something

   echo "this is a function action: in ajax";
   die();
}

A: Thanks to everyone for helping me...But I have solved the issue..
here is the code for answer seekers......It works....
Here is the main php file of plugin...I was created..
    <?php
/*
Plugin Name: lucky
Plugin URI:
Description:
Version:
Author:
Author URI:
License:
License URI:
*/

    #Ajax action function.......
function get_my_option() {

    $nom = $_POST['namo'];
    $emo = $_POST['emao'];

    global $wpdb;

    $wpdb -> insert( 'lucky_wpdb', array('namel' => $nom, 'emaill' => $emo) );
    echo 'Submitted';

}

    #Shortcode function.........................................
function html_form_code() {

    # Input form fields.....
    echo '<form method="post" id="InsertionForm">';

    echo '
Insertion Form
';

    echo '
Your Name (required)
';

    echo '<input id="nm" type="text" name="namel" value="" size="40" />';

    echo '
';

    echo '
';

    echo 'Your Email (required)
';

    echo '<input id="em" type="email" name="emaill" value="" size="40" />';

    echo '
';

    echo '
<input type="submit" name="submitbtn" value="Send"> ';

    echo '</form>';

}

//adding script files....

wp_enqueue_script('myscript', plugins_url('myscript.js', __FILE__), array('jquery'), '', true); // ajax script file...

wp_localize_script( 'myscript', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); //including admin-ajax.php in website html

    //Shortcode working here....
add_shortcode( 'sitepoint_contact_form', 'html_form_code' );

?>

myscript.js code...
// AJAX FORM SUBMITION CODE......

jQuery('#InsertionForm').submit(

function ajaxSubmit(){

var x = jQuery('#nm').val();
var y = jQuery('#em').val();

jQuery.ajax({
type:"POST",
url: ajax_object.ajax_url,
data: {
        'action': 'get_my_option', //action calling to insert data in wordpress db...
        'namo': x,
        'emao': y
    },
success:function($data){
    alert($data);

}
});

return false;

})

Put this code in functions.php of your selected theme...
add_action("wp_ajax_nopriv_get_my_option", "get_my_option");
add_action("wp_ajax_get_my_option", "get_my_option");


text:
Q: PHP MYSQL Carriage returns I have a script that is backing up a wordpress database, and it works great. However, I'm trying to restore it with php, and it always stops at the carriage returns, and errors out.
 Error:

\n\nThis is a text example, chang' at line 1
You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '\n\n

I've tried nl2br, htmlspecialchars,  mysql_real_escape_string, even preg-replacing them.
here's the code I'm using:
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());

// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename, FILE_IGNORE_NEW_LINES);
// Loop through each line
foreach ($lines as $line)
{
    // Skip it if it's a comment
    if (substr($line, 0, 2) == '--' || $line == '')
        continue;

    // Add this line to the current segment
    $templine .= $line;
    // If it has a semicolon at the end, it's the end of the query
    if (substr(trim($line), -1, 1) == ';')
    {
        // Perform the query
        mysql_query($templine) or print(mysql_error() . '

');
        // Reset temp variable to empty
        $templine = '';
       }
}

the $filename variable is an .sql file that is formatted correctly. In the database dump, I can see the \n's, and I'm pretty sure wordpress does some sort of nl2br, and replaces them with
's, so they can be removed or the spacing on the site gets removed completely.


text:
Q: Getting zero when extracting data from a PHP array in Laravel app Am working on some set of PHP array. Am trying to loop through each of them and check
the array whose name is equal to Josw Acade. Am using a for loop but I get zero
after extracting the data. I want to store the data in an array.
Array
array:6 [
  0 => array:4 [
    "id" => 1
    "name" => "Josw Acade"
    "value" => "Unlimited"
    "plan_type" => "Superior"
  ]
  1 => array:4 [
    "id" => 2
    "name" => "Verbal"
    "value" => "true"
    "plan_type" => "Superior"
  ]
  2 => array:4 [
    "id" => 12
    "name" => "Josw Acade"
    "value" => "$1,500,00"
    "plan_type" => "Classic"
  ]
  3 => array:4 [
    "id" => 13
    "name" => "Leon"
    "value" => "true"
    "plan_type" => "Classic"
  ]
  4 => array:4 [
    "id" => 14
    "name" => "One Time"
    "value" => "true"
    "plan_type" => "Classic"
  ]
  5 => array:4 [
    "id" => 15
    "name" => "Deat"
    "value" => "$25,000"
    "plan_type" => "Classic"
  ]
  6 => array:4 [
    "id" => 23
    "name" => "Josw Acade"
    "value" => "$100,000"
    "plan_type" => "Essential"
  ]
]

Logic
$Inst = [];
for($med = 0; $med < count($array); $med++){
    if($med['name'] == "Josw Acade"){
        $Inst = $med['value'];
    }
}

dd($Inst);

A: Your variables is not corretly set in the for loop, you are setting $med = 0 and acessing $med as an array.
Use filter, that runs a condition on each element and returns the items that satisfy that condition.
array_filter($array, function ($item) {
    return $item['name'] === 'Josw Acade';
});

In general you don't have to make old school arrays anymore, foreach does the same.
$results = [];

foreach($array as $item)
{
    if ($item['name'] === 'Josw Acade') {
        $results[] = $item['value'];
    }
}

A: You can use array_filter with callback
$filtered = array_filter($array, function($v){ return $v['name'] == 'Josw Acade'})
print_r($filtered);

A: You are looping through array; so on each iteration to get values; you need to pass index value and you are missing that. You are using $med as index.
Here is code.
$Inst = [];
for($med = 0; $med < count($array); $med++){
    if($array[$med]['name'] == "Josw Acade"){
        $Inst[] = $array[$med]['value'];
    }
}

A: there is many way to do this but according to me the best way to use array_filer()
array_filter($array, function ($item) {
    return $item['name'] === 'Josw Acade';
});


text:
Q: How to override RazorViewEngine when searching for EditorTemplate? It seems like that the default RazorViewEngine in the asp.net mvc 5 framework, only look for EditorTemplate in a folder named EditorTemplate inside the Shared folder. I am okay with that convention, the only thing I would like to add it search for EditorTemplate in the Shared/EditorTemplates and any folder inside if I place my EditorTemplate in ~/Views/Shared/EditorTemplates/SomeNewFolder it would still find it.
How can I extend the RazorViewEngine to tell razor to recursively look for any folder inside the EditorTemplates folder when searching for EditorTemplate?


text:
Q: Is symplectic reduction interesting from a physical point of view? Do you think that symplectic reduction (Marsden Weinstein reduction) is interesting from a physical point of view? If so, why? Does it give you some new physical insights?
There are some possible answers I often heard of, but I don't really understand it. Perhaps you could comment these points. Explain and illustrate why they are good reasons or if not, explain why they are nonsense:
1) Symplectic reduction is interesting because "it simplifies" the system under consideration because you exploit symmetries to eliminate some redundant degrees of freedom. I do not really understand what's the point here because in general reduction leads to a more complicated geometry. (Or even to singular spaces if you consider more general reduction settings).
2) It's interesting because it is a toy model for gauge theories.
3) It's interesting because if you want to "quantize" a system, from a conceptual point of view, one should start from the reduced system, from the "real" phase space. I don't see why one should do this for nonrelativistic quantum systems. Even for gauge theories I don't get the point, because the usual procedure is quantize the unreduced system (via gauge fixing), isn't it?
If there are points which make symplectic reduction interesting from a physical point of view, are there physical reasons why one should study reduction by stages?
Added; after reading José Figueroa-O'Farrill's answer I had some thoughts I should add:
I am still by far not an expert in gauge theories. But I think, that in gauge theories, one typically has redundant variables, which have no or at least not a direct physical interpretation. So I would agree that the "physical" dynamics takes place at the quotient in the case that the gauge theory itself has a physical meaning (in particular experimental evidence). Concerning quantization, however, if I am not mistaken, the only known quantum gauge theory which corresponding classical gauge theory which experimental support is quantum electrodynamics. For the other physical relevant quantum gauge theories, I think, the classical counterparts play just the role of auxiliary theories in some sense. In this case I would agree, that on the quantum side only the reduced space has physical meaning, but I think for the corresponding classical one, this seems to be a rather pointless question. So the question remains, why it is physically interesting to study on the classical side the reduced phase space in case of gauge theories. Moreover as José Figueroa-O'Farrill points out, the classical reduced space in most cases too complicated to quantize it directly, one would use some kind of extrinsic quantization as BRST instead. I don't know exactly how the situation for gravitation is. I think one can formulate ART as classical gauge theory. But makes it sense in this case to study the reduced classical phase space for quantization purposes? I guess not.

A:
Symplectic reduction is interesting
  because "it simplifies" the system
  under consideration because you
  exploit symmetries to eliminate some
  redundant degrees of freedom. I do not
  really understand what's the point
  here because in general reduction
  leads to a more complicated geometry.
  (Or even to singular spaces if you
  consider more general reduction
  settings).

Actually, the idea is to a find simpler dynamic "upstairs" in order to understand the complicated dynamic that occurs on the quotient space.
Let me give you an example with the so-called Calogero-Moser system.
Consider the cotangent space $T^*(\mathbb{C}^n_{reg})$ of the space $\mathbb{C}^n_{reg}$ consisting of $n$ pairwize dinstinct points in the complex plane. And try to study the dynamic associated to the Hamiltonian
$$
H(p_1,\dots,p_n,q_1,\dots,q_n):=\sum_ip_i^2-\sum_{i\neq j}\frac{1}{q_i-q_j}
$$
Are there enough conserved quantities ? What are the integral curves ? etc...
Actually you can see that everything is invariant under the symmetric group $S_n$ so I will actually try to study the same dynamic on $T^*(\mathbb{C}^n_{reg})/S_n$.
An a priori unrelated system
Consider the space of pairs $(X,Y)$ of $n\times n$ matrices. We actually have $M_n\times M_n=T^*(M_n)$ via the bilinear form $tr(XY)$. The Poisson bracket on coordinates is given by
$$
\{x_{ij},x_{kl}\}=0=\{y_{ij},y_{kl}\}\quad\{y_{ij},x_{kl}\}=\delta_{il}\delta{jk}
$$
Where $x_{ij}$ and $y_{kl}$ are the obvious coordinates on $M_n\times M_n$.
Consider the map to $\mathfrak{sl}_n$ defined by $\mu(X,Y)=[X,Y]$. It is a momentum map ( we again identify $\mathfrak{sl}_n$ with its dual as above), and take the reduction w.r.t the (co)adjoint orbit $\mathcal{O}$ of $diag(-1,\dots,-1,n-1)$. The reduced space $M_{red}$ is then the space of pairs $(X,Y)$ of matrices such that $[X,Y]-Id$ has rank $1$, modulo simultaneous conjugation.
Now observe that the functions $H_i=tr(Y^i)$, $i=1,\dots,n$, form an integrable system on $M_{red}$. Namely, they are independant Poisson commuting and conjugation invariant functions on $M_n\times M_n$ - therefore they descend to $M_{red}$ which has precisely dimension $n$.
The dynamic of $H_2$ is very easy. It is linear! Integral curves of $H_2$ are of the form
$$
(X(t),Y(t))=(X_0+2Y_0t,Y_0).
$$
How the hell is this related to what we had before?
The point is that we have an injective Poisson map from $T^*(\mathbb{C}^n_{reg})/S_n$ to $M_{red}$ that sends $(p_1,\dots,p_n,q_1,\dots,q_n)$ to the pair $(X,Y)$ with
$X=diag(q_1,\dots, q_m)$, $Y_{ii}=p_i$ and $Y_{ij}=\frac{1}{q_i-q_j}$. Moreover, th eimage of this map coincide with the dense open subset consisting of conjugation classes of pairs $(X,Y)$ such that $X$ is diagonalizable with pairwize distinct eigenvalues.
Now if you write $H_2$ in $(p,q)$ coordinates you find exactly the $H$ we started with.
So, in the end we found a way to write a complicated system as the reduction of a very simple one. This helps us to understand well the complicates one (e.g. in this example it helped to prove integrability).

The is not the only motivation for symplectic reduction. Studiing systems with constraints might be another one. But I found this example very enlighting about the potential useness of symplectic reduction.

reference: I think that the people who did this are Kazhdan, Kostant and Sternberg. You can find a very nice presentation of it (as well as many other interesting things) in the book "Lectures on Calogero-Moser systems" by Pavel Etingof.

A: Of course it is interesting, and the idea of factoring out symmetries goes back to Newton.
As for your point (1), yes it leads to more complicated geometry, and often some form of singular reduction is required (e.g. have a look at the blue book of Bates & Cushman for the case of integrable Hamiltonian systems with finitely many degrees of freedom), but from a dynamical point of view it makes much more sense.
For instance suppose you would like to study numerically a classical mechanical system (integrable or non-integrable all the same): working in reduced coordinates allows to easily distinguish between different Periodic Orbits (i.e. to count them only once), while in non-reduced dynamics the Periodic Orbits come in continuous families.
As for your comment, the topology of the reduced space is certainly a "new physical insight". Have a look at this recent paper by Yanguas, Palacian, Meyer & Dumas where they study periodic orbits of a non-integrable system as you ask, and where they discuss the issue of reduction and provide further references.
(Edited to correct an error; more links added in reply to comment.)

A: Here is a fancy example: Supersymmetry. Rigid N=1 supersymmetric theories in 4 dimension have a natural Kahler structure on the field space. The D-term is precisely a moment map. The moduli space of the theory is the symplectic quotient from this moment map.

A: Symplectic reduction arises naturally in constrained hamiltonian systems, e.g., gauge theories.  So it is not just a question of it being "interesting" as much as a fact of life.
The way to deal with coisotropic constraints -- those whose zero locus is a coisotropic submanifold -- is via symplectic reduction.  The real (read, physically meaningful) dynamics are taking place in the symplectic quotient, which is the standard quotient of the zero locus of the constraints by the (integrable) distribution defined by the hamiltonian vector fields associated to the constraints.
Now, as you point out, the symplectic quotient is usually much more complicated geometrically than the original symplectic manifold and this makes working there cumbersome.  For instance, quantising the symplectic quotient is usually difficult.  Luckily, one can go the other way: instead of performing the symplectic quotient and then quantising, one can first quantise the constrained system and then do a quantum version of the symplectic quotient.  One such procedure, which works in many gauge theories, is BRST quantisation.  This is a homological approach to the quantisation of constrained hamiltonian systems.  It has the virtue that it preserves the symmetries of the original system which "gauge fixing" typically destroys.

A: Inviscid fluid mechanics is one example of a physical system where symplectic reduction actually tells you a great deal, which would be very hard to obtain by other means.
The unreduced configuration space for a (inviscid, incompressible) fluid in a 3-dimensional container $M$ is the group $SDiff(M)$ of volume-preserving diffeomorphisms.  This group acts on itself from the right and this action leaves the fluid kinetic energy invariant.  Now, there are various kinds of reduction, and all of them give some insight into fluid dynamics:

*

*Working directly with the unreduced configuration space allows you to do fluid dynamics in Lagrangian variables, that is, you track every particle through its motion and record where it goes as time progresses;

*By factoring out the diffeomorphism group action, you end up from $T^\ast Q$ in the dual of the Lie algebra of $SDiff(M)$ and this will let you do fluid dynamics in the Eulerian picture.  Here you are fixed in space, and instead of tracking individual fluid particles you record what happens at a fixed position in space.  This is an instance of Poisson reduction, and will show you that the canonical Poisson structure on the dual of the Lie algebra of $SDiff(M)$ is the right one if you want to show that Euler's equations are Hamiltonian.  Not only does this process explicitly give you the Poisson structure, it also tells you that (e.g.) it satisfies Jacobi's identity (since it is obtained through reduction from the canonical Poisson structure on $T^\ast Q$), a fact which would otherwise be hard to obtain directly.

*Now fix an element $\mu$ in the dual of the Lie algebra of $SDiff(M)$ and do symplectic reduction at $\mu$.  V.I. Arnold has shown that the elements of the dual of the Lie algebra of $SDiff(M)$ can be interpreted as vorticity distributions of the fluid, so performing symplectic reduction is tantamount to fixing the vorticity distribution of the fluid, and only considering fluids with that amount of vorticity.  One important example shows up when you take $\mu$ to have support along a closed curve (knot or link).  In that case, the symplectic reduced space is nothing but the space of all knots/links that are diffeomorphic to the original curve, equipped with the natural symplectic form!  This is quite a simplification, and for instance tells you that the dynamics of vortex rings (a fundamental part of fluid dynamics) is Hamiltonian and has an incredibly nice geometric interpretation.   Moreover, by varying $\mu$ you get various other fluid-dynamical systems, such as the Kelvin, Lamb, Kirchoff-Lin, etc. equations, all in one fell swoop!
It's also important emphasize that symplectic reduction doesn't just give you "old" results in a new formulation, but also clears up much of the confusion that you would get when doing straightforward calculations.  For instance, people have been known to come up with various sequences of "conserved quantities" for the Euler equations, attempting to establish complete integrability this way.  However, having a clear picture of the geometry and how the coadjoint orbits sit inside the dual Lie algebra will quickly show you that these quantities are merely Casimirs and could hence never be used for integrability.

A: Suppose you have a kinematics that is parameterized by a; whose symmetries are given by the Lie Algebra [X,Y] = aZ, [Y,Z] = X, [Z,X] = Y. For instance, a could be a coefficient that distinguishes a "classical" from "non-classical" formulation; or a parameter that distinguishes a "bound" (a < 0) from a "free" (a > 0) system. What are the representations of this system? And in what sense is "representation" meant?
With symplectic reduction one can not only answer the question within a unified framework in a way that cuts across paradigm boundaries (both quantum and classical); but across the different cases of the parameter (a).
In contrast with Hilbert space representation theory, where the different cases of (a) have to be treated separately and one has to resort to the awkward "group contraction" mechanism to handle the different cases, it is possible to devise the Poisson-Lie manifold for each case of (a) and to then continuously connect them all into a single Poisson manifold, by simply treating (a) as an extra coordinate.
The symplectic reduction is then carried out on the unified manifold. Each of the symplectic leaves for values of (a > 0) corresponds to irreducible representations. The method however generally breaks down when passing over to limit values of the contraction parameter (here: where a = 0), where the boundary case may not only fail the Peter Weyl Theorem, but may not even have a tractible Hilbert space representation problem at all. (Some groups, like the Galilei group have what's known as a wild representation type, whose representation problems are generally unsolvable.)
In contrast, passing over from a > 0 to a = 0 and even a < 0 causes no problem with symplectic reduction. For this example, the reduction yields the cases:
{(0,0,0,a)}, for all values of a
((0,0,Z,0)}, for all non-zero values of Z
{(X,Y,Z,a): XX + YY + aZZ = RR }, for all values of a and R > 0
and you can see immediately which subsets are connected to which, as (a) varies (i.e. how the symplectic leaves morph as (a) crosses from a > 0 to a = 0 to a < 0); and which ones are connected to which for each given value of (a).
This construction transcends the linear representation theory of Hilbert spaces in the sense that the Poisson manifold is not the Poisson-Lie manifold of any Lie group or its Lie algebra, but is a manifold which encapsulates an entire family of such Lie groups and Lie algebras in a single unified setting.


text:
Q: React native EXPO installation (npm start) I created my app in react native using Expo but when i run the npm start command its showing me this:
running metro bundler on port 8081

and then
loading dependency graph, done

and never end. what to do?
Here is the complete console output.

A: Well, Nice question, First of all, I totally understand what's exactly your problem is, let me give you a solution in a very appropriate way.
Basically, there is two way to install and setup React Native Project on your mac and windows machines
1st React Native (native) Method: (That's basically you're using right know
Note: If you're using Apple product -  Like MacBook then you can do IOS and Android both platform by using this method, if you're using Windows or Linux you can only do this part for Android platforms
In this method, we have to follow these simple steps

*

*Download Nodejs from Offical website link here

*Installing the React Native Cli
npm install -g react-native-cli
If you get an error like Cannot find module 'npmlog', try installing npm directly: curl -0 -L https://npmjs.org/install.sh | sudo sh.
(Only for mac)

*Install the Xcode from Appstore (Only for Mac user/macos users)
otherwise

download and install the Android Studio (Stable version) from the official website of Android studio

*Setup Xcode (Simulator) or Setup Android Studio for Android devices use (emulator)
by learn and guide from this link here
Note: Basically in your scenario, I'm pretty sure you didn't set up your emulator for android and simulator for IOS that's why you didn't see anything after
2nd React Native with Expo Method: that's you're not using a loading dependency graph
Use
For Android
react-native run-android
For IOS
react-native run-ios
2nd React Native without Expo (that's not your case):
In this method, we have to follow these simple steps

*

*Download Nodejs from Offical website link here

*installing expo cli
npm install -g expo-cli
expo init yourprojectname
cd yourprojectname
npm start
Note: Simulators and emulators way same for both

A: First of all if you have a bundler like the one that you have used then it would suggest that you have used react-native init to create you application, instead of expo.
Expo bunders look like this:

If you have created a react-native init and as it suggests in your screenshot that you are building the app on a Windows machine, that means you will be developing on Android.
The instructions for using Android and running react-native are quite long and complicated, they can be found here. For the sake of brevity I am not going to repeat them here  asyou can just follow this link. Make sure to choose Building Projects with Native Code -> Development OS: Windows -> Target OS: Android to find the instructions that are pertinent to your situation.
https://facebook.github.io/react-native/docs/getting-started.html
If you are planning on developing on an emulator then you will need to make sure that you have one installed (the link above has all the info that you need). Also you need to make sure that you launch your emulator before running react-native run-android if you do that then it should load on to the emulator and you should be able to see what you are developing on.
If you want to run on your own Android device then you should follow the instructions on this page https://facebook.github.io/react-native/docs/running-on-device (again choosing the options for your situation).
Expo
If this feels like too much effort, you can always try Expo. It doesn't require you to be able to deal with native code. And depending on your use case can be a better option than creating a project with react-native init, plus you can always eject from the expo project and turn it in to a full fledged react-native app.
You install the expo-cli with
npm install -g expo-cli
Then download the expo app from the App Store or the Google Play Store (depending on the mobile that you are using).
Then you can use
expo init
to create your application
Check out the expo documentation for more information https://docs.expo.io/versions/v32.0.0/workflow/up-and-running