text:
Q: Loop through keys of an array, in order is that easily possible?
I have the next code:
for each_key in "${!myArray[@]}"
    do
        echo $each_key" : "${myArray[$each_key]}
    done

sure it works flawesly, but items do not show in order
I try with
IFS=$'\n' orderedMyArray=($(sort <<< "${myArray[@]}"))
declare -p orderedMyArray

but is giving me values and not keys

A:
it works flawesly, but items do not show in order

Sure and ordering them on keys is trivial - just actually sort on the keys.
for each_key in "${!myArray[@]}"; do
    echo "$each_key : ${myArray[$each_key]}" # remember to quote variable expansions!
done | sort

You could sort keys before passing them to for:
for each_key in "$(printf "%s\n" "${!myArray[@]}" | sort)"; do
# or funnier:
for each_key in $(IFS=$'\n'; sort <<<"${!myArray[*]}"); do
# or I think I would do a while read:
keys=$(IFS=$'\n'; sort <<<"${!myArray[*]}")
while IFS= read -r each_key; do ...; done <<<"$keys"

A: If you mean something other than sorting the keys themselves in alphabetic order, you could try a parallel array.
$: order=( peach pear lemon lime ) # declare the order you want
$: declare -A data=( [peach]=pickled [pear]=salad [lemon]=drop [lime]=twist )
$: for k in "${order[@]}"; do echo "$k: ${data[$k]}"; done
peach: pickled
pear: salad
lemon: drop
lime: twist


text:
Q: Why is my WPF window loading slowly? I am trying to design what is a pretty simple interface that shows a number of images and then rating buttons.  Here is the XAML.
   <Window x:Class="ASU_Evaluation2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local ="clr-namespace:ASU_Evaluation2"
        Title="MainWindow" Height="686" Width="1154" Loaded="Window_Loaded" Closing="Window_Closing">

    <Grid Name="ReviewData" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200*"/>
            <ColumnDefinition Width="205"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="474*" />
            <RowDefinition Height="25*" />
        </Grid.RowDefinitions>

        <StackPanel Grid.Column="1" Grid.RowSpan="2">

            <ToggleButton Content="Cell is good" Name="tbGoodCell" Height="30" Margin="1,1" IsChecked="{Binding Cell_Good}"  Width="200"/>
            <ToggleButton Content="Recon is good" Name="tbReconGood" Height="30" Margin="1,1" IsChecked="{Binding Recon_Good}"  Width="200"/>
            <ToggleButton Content="Stain is good" Name="tbStainCell"  Height="30" Margin="1,1" IsChecked="{Binding GoodStain}"  Width="200"/>
            <ToggleButton Content="Recon Clipped" Name="tbReconClipped"  Height="30" Margin="1,1" IsChecked="{Binding Clipping}"  Width="200"/>
            <ToggleButton Content="Interesting" Name="tbInteresting"  Height="30" Margin="1,1" IsChecked="{Binding Interesting}"   Width="200"/>
            <ToggleButton Content="Background Noise" Name="tbNoisy"  Height="30" Margin="1,1" IsChecked="{Binding Noisy}"  Width="200"/>
            <ToggleButton Content="Has Rings" Name="tbRings"  Height="30" Margin="1,1" IsChecked="{Binding Rings}"  Width="200"/>
            <Label Content="Interfering Object" Margin="1,10,1,1"></Label>

            <ListBox Name="tbInterferingObject"  Height="70" SelectedIndex="{Binding InterferingObject}"  Width="200">
            <ListBoxItem>None          </ListBoxItem>
                <ListBoxItem>Close         </ListBoxItem>
                <ListBoxItem>Far           </ListBoxItem>
                <ListBoxItem>Side    </ListBoxItem>
            </ListBox>

            <Label Content="Comments"/>
            <TextBox Margin="1,5" Height="400" Name="Comments" Text="{Binding Comments}" Width="200"/>

        </StackPanel>

        <ComboBox Grid.Row="2" Grid.Column="0" x:Name="themes" Width="150" Height="20" SelectionChanged="themes_SelectionChanged" SelectedIndex="0" />
        <TabControl Grid.Column="0"  Name="tabControl1" >
            <TabItem Header="Recon View" Name="tabItem1">
                <Grid Height="612" Width="934">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="225" />
                        <ColumnDefinition Width="225" />
                        <ColumnDefinition Width="225" />
                        <ColumnDefinition Width="225*" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="291" />
                        <RowDefinition Height="291" />
                    </Grid.RowDefinitions>
                    <Image Grid.Column="0" Grid.Row="0"   Margin="2,2" Name="MIP_Image" Height="210" Width="210"/>
                    <Image Grid.Column="1" Grid.Row="0"   Margin="2,2" Name="Axial_Image" Source="{Binding Axial_Image}" Height="210" Width="210"/>
                    <Image Grid.Column="0" Grid.Row="1"   Margin="2,2" Name="Sag_Image" Source="{Binding Sag_Image}" Height="210" Width="210"/>
                    <Image Grid.Column="1" Grid.Row="1"   Margin="2,2" Name="Z_Image" Source="{Binding Z_Image}" Height="210" Width="210"/>
                    <Image Grid.Column="2" Grid.Row="0"   Margin="2,2" Name="Fly_Through"  Height="210" Width="210"/>
                    <Image Grid.Column="2" Grid.Row="1" Grid.ColumnSpan="2" Margin="2,2" Name="Background"  Source="{Binding Background}" Height="250" Width="450"/>
                </Grid>
            </TabItem>
            <TabItem Header="Alignment View" Name="tabItem2">
                <Grid >
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="460" />
                        <ColumnDefinition Width="460" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="190" />
                        <RowDefinition Height="190" />
                        <RowDefinition Height="190" />
                    </Grid.RowDefinitions>
                    <Image Grid.Column="0" Grid.Row="0"   Margin="2,2" Name="PP1"   Source="{Binding PP1}" Width="460" Height="190" />
                    <Image Grid.Column="0" Grid.Row="1"   Margin="2,2" Name="PP2"   Source="{Binding PP2}" Width="460" Height="190" />
                    <Image Grid.Column="0" Grid.Row="2"   Margin="2,2" Name="PP3"   Source="{Binding PP3}" Width="460" Height="190" />
                    <Image Grid.Column="1" Grid.Row="0" Grid.RowSpan="3"   Margin="2,2" Name="Centering" HorizontalAlignment="Center" VerticalAlignment="Center" Width="400" MinHeight="400"  Source="{Binding Centering}"/>

                </Grid>
            </TabItem>
            <TabItem Header="Stack View" Name="tabItem3" GotFocus="tabItem3_GotFocus">
                <Grid >
                    <Grid.RowDefinitions>
                        <RowDefinition Height="418*" />
                        <RowDefinition Height="24*" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="581*" />
                        <ColumnDefinition Width="207*" />
                    </Grid.ColumnDefinitions>
                    <Image Name="Stack_Image" VerticalAlignment="Center" HorizontalAlignment="Center" MinHeight="100" MinWidth="100"   Height="400" Margin="98,26,82,15" Width="400" />
                    <ScrollBar Grid.Column="1" Height="353" HorizontalAlignment="Left" Margin="36,50,0,0" Name="StackZPosition" VerticalAlignment="Top" Width="17" ValueChanged="StackZPosition_ValueChanged" />
                    <Label Content="Z Position" Grid.Column="1" Height="27" HorizontalAlignment="Left" Margin="13,17,0,0" Name="label1" VerticalAlignment="Top" Width="79" />
                    <ProgressBar Grid.Row="1" Height="14" HorizontalAlignment="Left" Margin="95,4,0,0" Name="StackProgress" VerticalAlignment="Top" Width="404" />
                </Grid>
            </TabItem>
            <TabItem Header="Othogonal View" Name="tabItem4">
                <Grid >
                    <Grid.RowDefinitions>
                        <RowDefinition Height="418*" />
                        <RowDefinition Height="24*" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="581*" />
                        <ColumnDefinition Width="207*" />
                    </Grid.ColumnDefinitions>

                </Grid>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

the class that is bound looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Threading.Tasks;
using System.Drawing;

namespace ASU_Evaluation2
{
class DatasetExample
{
      public string Date { get { return "3/3/3"; } }
    public ImageSource ExampleImage
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\CrossSections_X___TIK.jpg";

            if (File.Exists(exampleImage))
                return BitmapFrame.Create(new Uri(exampleImage, UriKind.Absolute), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            else
                return null;
        }
    }
    public bool Recon_Succeeded { get { return true; } }
    public bool Cell_Good
    {
        get;
        set;
    }
    public bool Recon_Good
    {
        get;
        set;
    }
    public string DatasetName { get; private set; }
    public string TopDirectory { get; private set; }

    string VGFolder;
    string StorageFolder;
    string DehydrateFolder;
    string BackupFolder;
    string StackFolder;
    string StackReportFilePath;

    private void BuildPaths()
    {
        string dirName = Path.GetFileNameWithoutExtension(TopDirectory);
        //return dirName;
        string[] parts = dirName.Split('_');
        string Prefix = parts[0];
        string Year = parts[1].Substring(0, 4);
        string month = parts[1].Substring(4, 2);
        string day = parts[1].Substring(6, 2);

        VGFolder = Path.Combine(@"y:\", Prefix + "\\" + Year + month + "\\" + day + "\\" + dirName);
        StorageFolder = Path.Combine(@"z:\", Prefix + "\\" + Year + month + "\\" + day + "\\" + dirName);
        DehydrateFolder = Path.Combine(@"e:\", Prefix + "\\" + Year + month + "\\" + day + "\\" + dirName);
        BackupFolder = Path.Combine(@"V:\BackupCompleted\", Prefix + "\\" + Year + month + "\\" + day + "\\" + dirName);

        if (Prefix.ToLower() == "cct001")
        {
            StackFolder = Path.Combine(@"V:\Raw PP\cct001\Absorption\", Year + month + "\\" + day + "\\" + dirName + "\\STACK\\000");
        }
        else
            StackFolder = Path.Combine(@"V:\Raw PP\", Prefix + "\\" + Year + month + "\\" + day + "\\" + dirName + "\\STACK\\000");

        StackReportFilePath = VGFolder + "\\FixedStackReport.xml";
    }

    public DatasetExample(string name, string path)
    {
        DatasetName = name;
        TopDirectory = path;
        GoodStain = true;
        Clipping = false;
        Interesting = false;
        Noisy = false;
        Rings = false;
        InterferingObject = 0;
        Comments = "  ";
        Evaluator = "Brian";
        Cell_Good = true;
        CellType = " ";
        Recon_Good = true;

    }

    public string Evaluator { get; set; }
    public string CellType { get; set; }
    public bool GoodStain { get; set; }
    public bool Clipping { get; set; }
    public bool Interesting { get; set; }
    public bool Noisy { get; set; }
    public bool Rings { get; set; }
    public int  InterferingObject { get; set; }
    public string Comments { get; set; }

    public ImageSource Axial_Image
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\CrossSections_X___TIK.jpg";

            if (File.Exists(exampleImage))
                return BitmapFrame.Create(new Uri(exampleImage, UriKind.Absolute), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            else
                return null;
        }
    }
    public ImageSource Sag_Image
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\CrossSections_Y___TIK.jpg";

            if (File.Exists(exampleImage))
                return BitmapFrame.Create(new Uri(exampleImage, UriKind.Absolute), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            else
                return null;
        }
    }
    public ImageSource Z_Image
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\CrossSections_Z___TIK.jpg";

            if (File.Exists(exampleImage))
                return BitmapFrame.Create(new Uri(exampleImage, UriKind.Absolute), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            else
                return null;
        }
    }

    public void ClearMemory()
    {

    }

    public ImageSource Background
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\background.tif";

            if (File.Exists(exampleImage))
                return BitmapFrame.Create(new Uri(exampleImage, UriKind.Absolute), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            else
                return null;
        }
    }
    public ImageSource PP1
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\projection1.jpg";

            if (File.Exists(exampleImage))
                return BitmapFrame.Create(new Uri(exampleImage, UriKind.Absolute), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            else
                return null;
        }
    }
    public ImageSource PP2
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\projection2.jpg";

            if (File.Exists(exampleImage))
                return BitmapFrame.Create(new Uri(exampleImage, UriKind.Absolute), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            else
                return null;
        }
    }
    public ImageSource PP3
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\projection3.jpg";

            if (File.Exists(exampleImage))
                return BitmapFrame.Create(new Uri(exampleImage, UriKind.Absolute), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            else
                return null;
        }
    }
    public string Centering
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\centering.avi";

            if (File.Exists(exampleImage))
                return exampleImage;
            else
                return "";
        }
    }

    public ImageSource Stack_Image
    {
        get
        {
            string exampleImage = TopDirectory + @"\data\CrossSections_Y___TIK.jpg";

            if (File.Exists(exampleImage))
                return BitmapFrame.Create(new Uri(exampleImage, UriKind.Absolute), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            else
                return null;
        }
    }

}

}
It takes 15-20 seconds to load the interface on a high end computer.  I have tried to run the performance monitor tool with the windows SDK and it just crashes.  What am I doing wrong?  This is a embarrassingly simple task in winforms.

A: First of all, your properties are returning a NEW instance of ImageSource every time they're called. you Should avoid this.

*

*Fix 1:
private ImageSource sag_Image;
public ImageSource Sag_Image
{
    get
    {
        if (sag_Image != null)
            return sag_Image;

        //... Etc your code

        sag_Image = //Assign the backing field to use it later.
    }
}

You should Freeze your Freezables (such as ImageSource).

*

*Fix 2:
public ImageSource Sag_Image
{
    get
    {
        if (sag_Image != null)
            return sag_Image;

        //... Etc your code

        sag_Image = //Assign the backing field to use it later.

        sag_Image.Freeze(); //Notice the Freeze() method.
    }
}

*Fix 3:
Async. All operations that take more than 10 ms to complete SHOULD be async.
Third, your XAML looks like it was obtained from the Visual Studio designer, and also has some suspicious things such as the ScrollBar.ValueChanged event. What is that doing? Post the relevant code, and probably a screenshot of what you need. I'm sure there is a right way to do it WPF which does not involve horrible code-behind winforms type of hacks, and does not show these performance issues you described here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read the head section of a web page? On my web page, when the user types in a URL in the text field, I wan to get some information about that page, like title or link information.
Is there way to do it? On the client (JavaScript) or on the server (PHP)? And how?

A: You can't do it through Javascript, unless the page is in your domain. This is because cross-server scripting is restricted.
But you can use PHP (check file_get_contents() function), parse the content of the <head>  tag with simpledom and then pass it to an ajax request.

A: On the server:
need simpledom
    include("simpledom.php");
    $html = file_get_html('http://www.google.com/');
    echo $html->find('head')->outertext; // returns <head>...</head>

A: In php you can open URLs like files, i.e.
$f = fopen ("http://www.site/page.htm", r);

If you want to actually use a real DOM then use simpledom or another module.
Edit: You can probably ignore the fopen() suggestion above, for some reason I was thinking you were asking only about reading sites that you had full control of.

A: So, you page have an input text box, and when your user types in a link you want to retrieve information about it?
This might be useful:
http://www.bin-co.com/php/scripts/load/
According to that page that would return something like this:
Array
(
    [headers] => Array
        (
            [Date] => Mon, 18 Jun 2007 13:56:22 GMT
            [Server] => Apache/2.0.54 (Unix) PHP/4.4.7 mod_ssl/2.0.54 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2 SVN/1.4.2
            [X-Powered-By] => PHP/5.2.2
            [Expires] => Thu, 19 Nov 1981 08:52:00 GMT
            [Cache-Control] => no-store, no-cache, must-revalidate, post-check=0, pre-check=0
            [Pragma] => no-cache
            [Set-Cookie] => PHPSESSID=85g9n1i320ao08kp5tmmneohm1; path=/
            [Last-Modified] => Tue, 30 Nov 1999 00:00:00 GMT
            [Vary] => Accept-Encoding
            [Transfer-Encoding] => chunked
            [Content-Type] => text/xml
        )
    [body] => ... Contents of the Page ...
    [info] => Array
        (
            [url] => http://www.bin-co.com/rss.xml.php?section=2
            [content_type] => text/xml
            [http_code] => 200
            [header_size] => 501
            [request_size] => 146
            [filetime] => -1
            [ssl_verify_result] => 0
            [redirect_count] => 0
            [total_time] => 1.113792
            [namelookup_time] => 0.180019
            [connect_time] => 0.467973
            [pretransfer_time] => 0.468035
            [size_upload] => 0
            [size_download] => 2274
            [speed_download] => 2041
            [speed_upload] => 0
            [download_content_length] => 0
            [upload_content_length] => 0
            [starttransfer_time] => 0.826031
            [redirect_time] => 0
        )

)


text:
Q: How To Send FormData object?
*

*get Form with id

*create formdata with Form ID

*send Data with $.ajax

My code:
<form id="company">
    <input type="text" name="name" />
    <input type="tel" name="tel" />
    <input type="button" id="send" name="send" value="send" />
</form>

 <script>
        ##get Form id an create form data##
        var testForm = document.getElementById('send');
        testForm.onclick = function(event) {
            var formData = new FormData(document.getElementById('company'));
        ##this is Ajax Method##
                $.ajax({
                    url : './json/company.php',
                    method : 'POST',
                    data : formData,
                    timeout : 10,
                    dataType :'json',
                    success: function(data)
                    {
                        alert("Success");
                    }
                });
        }
    </script>

Error : TypeError: Argument 1 of FormData.constructor is not an object

A: Try this
data : JSON.stringify(formData)

A: Since your form doesn't have a input type file you should use the serialize function instead
$(testForm).click(function(event) {
                event.preventDefault();//don't forget to prevent the default click event from redirecting you from the page
                $.ajax({
                    url : './json/company.php',
                    method : 'POST',
                    data : $('#company').serialize(),
                    timeout : 10,
                    dataType :'json',
                    success: function(data)
                    {
                        alert("Success");
                    }
                });
        });

A: You're missing crucial options, and jQuery is trying to process the formData, which it can't.
You have to add the processData: false option, and you should avoid sending a contentType as well
var testForm = document.getElementById('send');
testForm.onclick = function(event) {
    var formData = new FormData(document.getElementById('company'));
    $.ajax({
        url: './json/company.php',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        timeout: 10,
        dataType: 'json',
        success: function(data) {
            alert("Success");
        }
    });
}

A: In order to use formdata with jquery you have to set the correct options
var testForm = document.getElementById('send');
testForm.onclick = function(event) {
    var formData = new FormData(document.getElementById('company'));
    $.ajax({
        url : './json/company.php',
        type: "POST",
        data : formData,
        processData: false,
        contentType: false,
        success: function(data)
        {
          alert("Success");
        },
        error: function(jqXHR, textStatus, errorThrown){
            //if fails
        }
    });
}


text:
Q: Unable to insert data into mysql but no error message shown Was trying to make a student register page but the data won't insert into database and there was no error message shown so i'm not sure where the problem is. Any help is appreciated!
Here's the code:
    <form onsubmit="return Add_Validate()" class="form-horizontal"  action="AddStudent.php" method="POST">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

 Add Student

            Student Name
            :

                  <input type="text" class="form-control" id="Add_Student_Name" placeholder="Student Name" name="Student_Name1" autocomplete="off" required>

            Gender
            :

                  <select class="form-control" id="Add_Student_Gender" name="Student_Gender1" required>
                    <option value="">~~SELECT~~</option>
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                  </select>

            Address
            :

                  <input type="text" class="form-control" id="Add_Student_Address" placeholder="Address" name="Student_Address1" autocomplete="off" required>

            Contact Number
            :

                  <input type="text" class="form-control" id="Add_Contact_Number" placeholder="Contact Number" name="Contact_Number1" autocomplete="off" required>

            Email
            :

                  <input type="text" class="form-control" id="Add_Student_Email" placeholder="Email" name="Student_Email1" autocomplete="off" required>

            Faculty
            :

                <select class="form-control" name="Add_Faculty1" id="FacultyName" required>
                    <option value="">~~SELECT~~</option>
                    <?php $query_faculty="SELECT FacultyName FROM `faculty`";
                    $result_faculty = mysqli_query($connect, $query_faculty) or die(mysqli_error($connect));
                    while($row_faculty=mysqli_fetch_array($result_faculty)) { ?>
                    <option value="<?php echo $row_faculty['FacultyName'] ?>"><?php echo $row_faculty['FacultyName'] ?></option>
                <?php } ?></select>

            Username
            :

                    <input type="text" class="form-control" id="Add_Student_Username" placeholder="Username" name="Student_Username1" autocomplete="off" required>

            Password
            :

                  <input type="password" class="form-control" id="Add_Password" placeholder="Password" name="Student_Password1" autocomplete="off" required>

And SQL command:
<?php require 'php_action/db_connect.php';

if($_POST) {

$Student_Name= $_POST['Student_Name1'];
$Student_Gender= $_POST['Student_Gender1'];
$Student_Address= $_POST['Student_Address1'];
$Contact_Number= $_POST['Contact_Number1'];
$Student_Email= $_POST['Student_Email1'];
$FacultyName= $_POST['Add_Faculty1'];
$Student_Username= $_POST['Student_Username1'];
$Password= $_POST['Student_Password1'];

$sql = "INSERT INTO student (Student_Name,Student_Gender,Student_Address,Contact_Number,Student_Email,FacultyName,Student_Username,Password) VALUES ('$Student_Name', '$Student_Gender','$Student_Address','$Contact_Number','$Student_Email','$FacultyName','$Student_Username','$Password')";

if($connect->query($sql) === TRUE) {
    echo "";
}
else {
    echo "";
}

}
$connect->close();
 ?>

A: You're not getting an error message because you never get the error message from MySQL and show it in your alert. $connect->error will contain the error message, and you can add that to your alert like this:
else {
    echo "";
}

A: Found the error, seems to be wrong column name, sorry the all the trouble.....
Admin please close my question.


text:
Q: Error: Syntax Error: Token ',' is an unexpected token I have this strange error that i'm not sure how to solve. I keep getting Error: Syntax Error: Token ',' is an unexpected token at column 6 of expression [Cough, splutter, slobber  Who are you? What do you want?] which has been loaded from a JSON file. It has been working for weeks but now it's not
This is the line of code calling the String

And this is the factory loading the data which seems to load correctly
  .factory('Stories', ['$http', function($http) {

            var factory = {};
            var stories = null;

            stories = $http.get('./json/stories.json')
                    .success(function(data) {
                        stories = data;

                    })
                    .error(function(data, status) {
                        alert(data);
                        alert(status);
                    });
            factory.getStories = function() {
                return stories;
            };
            factory.getStory = function(id) {
                return stories[id];
            };
            factory.getPage = function(id, page) {
                return stories[id].pages[page];
            };
            return factory;
        }])

finally this line loads the data from the JSON file into the scope to be exectuted on the partial
 $scope.page = Stories.getPage($scope.param.id - 1, $scope.param.pageNo - 1);

As far as i can tell there is nothing obvious that stands out to be wrong
The JSON being loaded is
"PageNo": 1,
"text": "Cough, splutter, slobber
 Who are you? What do you want?",
"image": "img/story-1/jpg/1.jpg",
"sound_background": "sound/story-1-sound/Story1A.aif",
"sound_voiceover": "sound/story-1-voiceover/Story1-01.mp3"

Can anyone see something im not

A: You can use {{}} with ng-bind-html and ng-bind-html-unsafe.
Just wrap the curly brackets in single quotes as such:

You can even combine it with filters

A: Ok so i figured it out apparently you can't use the {{}} if the value of ng-bind-html-unsafe is a string. My guess is that angular tries to evaluate it as a function or something causing problems
So

should be


text:
Q: Trying to understand Monads. The >> Operator I'm new to haskell and I'm learning through LearnYouAHaskell. I just can't understand the reason behind the (>>) operator.
The default implementation is:
(>>) :: (Monad m) => m a -> m b -> m b
m >> n = m >>= \_ -> n

Which is (as far as I understand) ignores the first value and returns the second one. However, from the example in LearnYouAHaskell this happens:

ghci> Nothing >> Just 3
  Nothing
  ghci> Just 3 >> Nothing
  Nothing

So it doesn't ignores the first value. Yet, from a little research I found this quote from here

The >> function binding operator ignores the value of its first action
  and returns as an overall result the result of its second action only.

So I'm puzzled about the usage of this operator and I want to ask 2 things:

*

*What does it actually do?

*When is it useful?

A: It ignores the value of the first action, not the action itself.
Just 3 >> Just 5

The value of the action Just 3 is 3. It is being ignored in the \_ -> n part. The overall result is Just 5.
Just 3 >> Nothing

The value of the action Just 3 is 3. It is being ignored in the \_ -> n part. The overall result is Nothing.
Nothing >> Just 3

The action Nothing does not produce any value at all. What does it pass to the right operand of >>= (or >>) then? It doesn't! >>= for the Maybe monad is built such that if the left action is Nothing, the right action is not executed at all, and the overall result is Nothing.

A: To complete Sibi answer >> can be seen as the ; in other languages like C or C++..
When you do in C (or equivalent in other language)
printf("foo");
   printf("bar");
You obviously print foobar (the side effect) but those calls to printf also have a return value, which in our case is the length being printed ie 3 3. Have you ever wonder what happen to those numbers ?
They get ditched, because in C, expr 1; exp 2, means

*

*evaluate expr1

*ditch its result

*evaluate expr2
(At that point, you could ask yoursef why should the compiler bother evaluating expr1 if it's to discard its result ? Because of the side effect. In the case of printf the side effect is to print something. You are rarely interested in the returned value itself.)
So ; can be seen as an operator taking 2 expression and returning a new one. This is exactly the same as what the >> operator do.
When you write
 print "foo" >> print "bar"

it's exactly equivalent to printf("foo");printf("bar") except (and that's a major difference) >> is not something magic like ; in C. >> it's a user defined operator and can be redefined for each type of Monad.
This is why Haskell programmers love Monad so much : In short, it allows you to redefine your own the behavior of ;.
As we seen, in C ; just evaluate an expression and discard it's value. In fact, it's bit more complicated because it doesn't if it's a break or a return. The Nothing in the Maybe monad could be seen as a break or a return. >> evaluates the first expression, and stop if it's Nothing. Otherwise it discards it's value and carry on.
You first example can be seen in C (I think it's valid C)
3; return

and
return; 3

The first example, compute 3, discard its value and returns.
The second, returns straight away.
To answer you question when is it usefull ? Pretty much all the time when you are using IO, even though you rarely see it.
Instead of writing
 print "foo" >> print "bar"

Haskell provides a syntaxic sugar which transforms (pretty much) newlines to >> via the do-notation,
so you'll write
do
  print "foo"
  print "bar"

which is strictly equivalent to the former version (It fact the do notation version is transformed to the previous one by the compiler).
It is even also equivalent to (even though rarely used)
do print "foo"; print "bar"

To summarize, >> can be seen as an equivalent to ; or newline is other languages with the difference that it's exact meaning depends on the context (which Monad is acting on).
>> in a Maybe monad is different from >> in a IO Monad.

A: First of all let's clear your confusion on Maybe monad. Consider the following
instance Monad Maybe where
  return = Just
  (Just x) >>= g = g x
  Nothing  >>= _ = Nothing

As you can see by definition, Nothing >>= _ is Nothing. Since >> is just a special case of >>= where the parameter is ignored, the result is the same.
This is because  Maybes are usually used to represent computation that might fail. This is to tell us that "Once you fail, you are always fail".
Now to answer your questions.

*

*The quote you mentioned already answer it.

*It is useful in some situations where the result of the action is just not needed. For instance, the result of putStrLn is (), which is neither interesting nor can be useful in any way.

A: The >> function only ignores the result of the first value but it doesn't ignore the side effect of the first value. To understand your example, see how Maybe Monad is defined:
instance Monad Maybe where
  return = Just
  (Just x) >>= f = f x
  Nothing >>= _ = Nothing

And >> function is defined like this:
m >> k      = m >>= \_ -> k

Nothing >> _ will produce Nothing according to the definition of Maybe monad. In your second example Just 3 >> Nothing gets expanded to Just 3 >>= \_ -> Nothing and produces Nothing. To give you an example of how it only ignores the value of the first action but doesn't ignore the side effect, consider the following example:
λ> print 3 >> print 4
3
4

You can see in the above example, that although it ignores the result of print 3 which is () but it doesn't ignore the side effect of it which is to display 3 to the screen.
>> function becomes useful once you start using other Haskell libraries. Two places where I use them occasionally is when dealing with Parsers (parsec, attoparsec) and Pipes library.

A: The reason is simple: simple words there are two operations needed for monad implementation:

*

*>>=

*>>
The first executes action and pass it's result of action to another action. For example:
Prelude> :t getLine
getLine :: IO String
Prelude> :t putStrLn
putStrLn :: String -> IO ()

Two functions: first getLine just return String wrapped with IO, it reads string from stdin and wrapped it to IO. Second putStrLn gets String and prints it. Bind has following type:
:t (>>=)
(>>=) :: Monad m => m a -> (a -> m b) -> m b

It can be represented as IO String -> (String -> IO String) -> IO String, so you can combine this two or more functions with (>>=) by executing getLine and pass result String to the putStrLn:
getLine >>= putStrLn

So you can combine this two or more functions in one action.
The second >> produces almost the same, but it no need in result of previous action.
:t (>>)
(>>) :: Monad m => m a -> m b -> m b

It just executes, first action, and than second, and second action is no need in result of first action:
putStrLn "Hello" >> putStrLn "World"


text:
Q: In registered model display list of all User(Foreign key) In image you can see i have only few user that i added from add button but i want to display all user
class Notification_user (models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    assign_jobs_notification = models.ManyToManyField(AppJob)

In admin section when i register joblist then it shows only user that are add by add Job List. But i want to display all users.
here is my admin.py
class NotificationAdminForm(forms.ModelForm):
    assign_jobs_notification = forms.ModelMultipleChoiceField(
      queryset=AppJob.objects.all(),
      required=False,
      widget=FilteredSelectMultiple(
        verbose_name=_('Jobs_Notifications'),
        is_stacked=False
      )

    )

    class Meta:
      model = User
      exclude =[]

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

      if self.instance and self.instance.pk:
        self.fields['assign_jobs_notification'].initial = self.instance.assign_jobs_notification.all()

    def save(self, commit=True):
      appjob = super(NotificationAdminForm, self).save(commit=False)

      if commit:
        appjob.save()

      if appjob.pk:
        appjob.assign_jobs_notification = self.cleaned_data['assign_jobs_notification']
        self.save_m2m()

      return appjob

class NotificationAdmin(admin.ModelAdmin):
    form = NotificationAdminForm
admin.site.register(Notification_user,NotificationAdmin)

A: That's the default behaviour of a OneToOneField. As the name implies and as the docs says, this is for a 1:1 relationship. You can see an example here which basically says a restaurant (physically) can be at one address. In your case, that means that a user will be assigned to a job listing instance. What I think you should use is a ForeignKey for that.
class JobList(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ...


text:
Q: Laravel: is it possible to store objects in a database field? If so, how? Suppose I have an User, and a Transaction model on Laravel. It doesn't matter the properties, they only have in common an uuid and a name field
Now I want to create an Audit model which will take more or less the following fields:
id       - The regular autoincrement id
ts       - The timestamp when the action is performed
actor    - The one who performs an action, its a reference to a user's id
verb     - Which action is performing over a certain object
object   - The object to which the action is performed
comment  - whatever

So if an admin creates o updates a new user will produce an audit records like
1, 1/1/2021 00:00:01, 1, 'create', User, 'bla bla bla'
2, 1/1/2021 00:00:02, 1, 'update', User, 'reset password'

But that will also apply to other kind of records like the Transaction I mentioned before
Currently I'm storing the object's id, and based on the "verb" (or action), I know the kind of Object they were acting upon, and it works, but I'm experimenting if there are some other ways. My databases aren't huge, so performance is not an issue.

A: The best way to store an object like that in a database is in a normal form.
I'd suggest creating a new migration and model for your audit, and storing all the relevant information there.
However, you can serialize your object as a string if you don't have any performance concerns, or if the data structure is likely to change. A popular way of doing this is to use json_encode($your_obj).


text:
Q: Difference between position of argument in running shell script from cygwin prompt I have been running shell script through cygwin terminal.
I could not figure out what's the difference between :
sh script1.sh argument="john"

 argument="john" sh script.sh

A: CygWin, by default, uses the bash shell so this is really a bash question. You can see the difference by using the following script1.sh:
echo "env[argument] = '$argument'"
echo "parameter     = '$1'"

and examining the following transcript:
pax > sh script1.sh argument="john"
env[argument] = ''
parameter     = 'argument=john'

pax> argument="john" sh script1.sh
env[argument] = 'john'
parameter     = ''

The first variant simply passes the string (dequoted) as a parameter to the script.
The second sets an environment variable for the duration of the script then runs it with no parameters. This particular case is covered in the bash documentation (slightly paraphrased):

The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments of the form name=value. These assignment statements affect only the environment seen by that command.


text:
Q: PHP Parse XML file for all .mp3 links I am trying to write a PHP script that parses an XML file for all .mp3's on https://feeds.transistor.fm/the-good-news-podcast and then echos them. I have started with PHP's simplexml_load_file(). The mp3's are located like so:
<enclosure url="https://media.transistor.fm/025fe5da.mp3" length="3636030" type="audio/mpeg"/>

How would I target all of the enclosure tag urls? Here is what I have so far but it is not working:
<?php
    $mysongs = simplexml_load_file('https://feeds.transistor.fm/the-good-news-podcast');
    foreach ($mysongs as $songinfo):
        $title=$songinfo->enclosure(url);
        echo $title;
    endforeach;
?>

also tried this but no luck:
<?php
$html= simplexml_load_file('https://feeds.transistor.fm/the-good-news-podcast');
$dom = new DOMDocument;
$dom->loadXML($html);
foreach ($dom->getElementsByTagName('enclosure') as $tag) {
        if(strpos($tag->getAttribute('url'),'.mp3')!==false)
        {
            echo $tag->getAttribute('url')."
";
        }

}
?>

A: Just figured it out thanks to Get enclosure img url from rss feed:
<?php
$rss=simplexml_load_file('https://feeds.transistor.fm/the-good-news-podcast');
foreach ($rss->channel->item as $item) {
    if (isset($item->enclosure)) {
        echo $item->enclosure['url'].'
';
    }
}
?>

A: You can try something simple if that is where it is applied.
$html= simplexml_load_file('https://feeds.transistor.fm/the-good-news-podcast');
preg_match_all("/h.*mp3/", $html, $mp3s);
foreach ($mp3s as $mp3){
echo $mp3.'
';
}

this will output
array(1
0   =>  array(9
0   =>  https://media.transistor.fm/0cf8f8b1.mp3
1   =>  https://media.transistor.fm/f45a0d7d.mp3
2   =>  https://media.transistor.fm/2ba746c9.mp3
3   =>  https://media.transistor.fm/025fe5da.mp3
4   =>  https://media.transistor.fm/58cf9a08.mp3
5   =>  https://media.transistor.fm/65a6df2b.mp3
6   =>  https://media.transistor.fm/33e65d6c.mp3
7   =>  https://media.transistor.fm/e29ea8d3.mp3
8   =>  https://media.transistor.fm/3422d3aa.mp3
)
)


text:
Q: Calculating the average grade in Python? I am trying to get the average of two passing grades. The output should be:

*

*0.0 if neither of the grades is a passing grade both <50

*The passing grade, if only one of the grades is a passing grade (if
one is >50)

*The average of the two grades, if both are passing grades (if both
are greater than 50)

Here is my code so far:
def passing_grade(grade1,grade2):
    '''(number, number)--> number
    This function definition prints the average of all passing grade(s)
    '''
    # Function 1 - If both numbers are outside the grading range (0-100)
    if 0.0 < grade1 > 100.0 and 0 < grade2 > 100.0:
           print ('Not available grading')

    elif 0.0 >= grade1 <= 50.0 and 0.0 >= grade2 <= 50.0:
            print (0.0)

    #Function 2 - If one of the grades is passing then, print passing grade
    elif 0.0 >= grade1 <= 50.0 and 0.0 >= grade2 >= 50.0:
        print (grade2)
    elif 0.0 >= grade1 >= 50.0 and 0.0 >= grade2 <= 50.0:
        print (grade1)

    #Function 3 - If both grades are passing >50 then print the average
    elif 50.0 > grade1 <= 100.0 and 50.0> grade2 <= 100.0:
        print ((grade1+grade2)/2)

A: I'm just guessing about your problem here, since you haven't specified, but it looks like you bad logic in the second part of "Function #2":
elif 0.0 >= grade1 <= 50.0 and 0.0 >= grade2 >= 50.0:
    print (grade2)
elif 0.0 >= grade1 >= 50.0 and 0.0 >= grade2 <= 50.0:
    print (grade1)

Should be:
elif grade1 <= 50.0 and grade2 >= 50.0:
    print (grade2)
elif grade1 >= 50.0 and grade2 <= 50.0:
    print (grade1)

If you look at your original conditions, you keep checking 0.0 >= gradeN, which means is only true if the grade is a negative number. There are similar problems in some of your other sections.

A: Your comparisons are screwed up. They don't say what you mean, and many evaluate to False always. There can be no grade1 such that 0.0 >= grade1 >= 50.0, as there are no nonpositive numbers greater-equal 50. I suggest you write out your multiple comparisons "the long way" until you're clear about what you mean to say, rather than using this keystroke-saving feature of Python. a < b < c in Python means a < b and b < c not a < b or b < c which is the form of what you want to say in your first 'if' statement.
Finally, when writing multiple comparisons in one expression, don't mix directions of the comparisons, it's needlessly confusing (for you, to start with).
A more concise way of writing (the calculation part of) your function:
def avg_passing_grade(grade1, grade2):
    passing_grades = [g for g in (grade1, grade2) if 50 <= g <= 100]
    return sum(passing_grades)/max(1, len(passing_grades))

This makes a list passing_grades containing only the grades supplied to the function that are passing. The function returns their average, taking care not to divide by 0 in case no grades are passing.
Although the following may be overkill, it's within such easy reach that I have to mention it: the function above generalizes easily to one that takes an arbitrary number of grades:
def average_passing_grade(* grades):
    '''Return the average of the passing grades among grades.'''
    passing_grades = [g for g in grades if 50 <= g <= 100]
    return sum(passing_grades)/max(1, len(passing_grades))

which you can use like this:
>>> average_passing_grade()
0.0
>>> average_passing_grade(35.3)
0.0
>>> average_passing_grade(75.5)
75.5
>>> average_passing_grade(35.3, 88)
88.0
>>> average_passing_grade(88, 20)
88.0
>>> average_passing_grade(50, 100)
75.0
>>> average_passing_grade(40, 50, 60, 70, 80, 90)
70.0

A: Besides the bad logic pointed out in the other answers, you could use max and min to do a single logical check for certain cases.
if grade1 >= 50.0 and grade2 >= 50.0:

can be
if min (grade1, grade2) >= 50.0: # Both are >= 50.0

similarly
if  max(grade1, grade2) < 50.0 # both are less than 50.0

Once those two have been shown false, the the else means that one is on each side of the limit.
Similarly, to test for the invalid values you can use
if max(grade1, grade2) > 100.0 or min(grade1, grade2) < 0:

means that at least one grade is invalid
if min(grade1, grade2) > 100 or max(grade1, grade2) <0:

means that both grades are invalid in the same way.

A: I am no expert in Python. However, I'm pretty sure your error is because of your if conditions.
    if 0.0 < grade1 > 100.0 and 0 < grade2 > 100.0:

Should be something like
    if (grade1 < 0 or grade1 > 100) and (grade2 < 0 or grade2 > 100):


text:
Q: Deploying php messaging app on heroku and using twilio to send messages I am trying to deploy a sms application which is written in PHP and I am deploying it on Heroku and using Twilio to send messages. When someone sends a message on my Twilio number, this app will send an appropriate reply to that message. I am facing a problem with switch statement in this app. I am new to coding in PHP and I am unable to get this to work. I am pasting my code below. Please help me  fix it. Thank you in advance.
<?php
    session_start();
    header("content-type: text/xml");
    switch ($answer) {
        case 'headache' : {
            print('OTC Crocin may help!');
            break;
        case 'stomachache' : {
            print('OTC Tylenol may help!');
            break;
        case 'cough' : {
            print('OTC Robitussin Cough may help!');
            break;
        case 'cold' : {
            print('OTC Aspirin may help!');
            break;
        case 'vomiting' : {
            print('OTC Pepto-Bismol may help!');
            break;
        case 'headache doctor' : {
            print('Dr. Lorem Ipsum - Here is the address! Call at +1 xxx xxx xxxx');
            break;
        case 'stomachache doctor' : {
            print('Dr. Lorem Ipsum - Here is the address! Call at +1 xxx xxx xxxx');
            break;
        case 'cough doctor' : {
            print('Dr. Lorem Ipsum - Here is the address! Call at +1 xxx xxx xxxx');
            break;
        case 'cold doctor' : {
            print('Dr. Lorem Ipsum - Here is the address! Call at +1 xxx xxx xxxx');
            break;
        case 'vomiting doctor' : {
            print('Dr. Lorem Ipsum - Here is the address! Call at +1 xxx xxx xxxx');
            break;
    }

    $from   = $_POST['From'];
    $answer = $_POST['Body'];
    $reply  = array();

    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>

<Response>
    <Sms>
            <?php
                if(is_array($reply)){
                    foreach($reply as $key => $value){
                        echo $value;
                    }
                }
                else{
                    echo $reply;
                }
            ?>
    </Sms>
</Response>

A: Twilio developer evangelist here.
You're responding to an incoming SMS message, however you are using the <Sms> TwiML verb. <Sms> is only used for sending an SMS message during a voice call.
Instead, you want to use the <Message> TwiML verb which is for replying to SMS messages. So, the last part of your code should look like:
<Response>
    <Message>
            <?php
                if(is_array($reply)){
                    foreach($reply as $key => $value){
                        echo $value;
                    }
                }
                else{
                    echo $reply;
                }
            ?>
    </Message>
</Response>


text:
Q: How to change keycode? I made a mistake changing the C keystroke into the numbersign, so every time I type C in keyboard, the display show numbersign instead. How can I change it back?

A: You said that you changed it with xmodmap -e "keycode 54 shift = numbersign asciitilde".
To change this back, you can run
xmodmap -e "keycode 54 shift = c C"

Since you can't type "c" and "C", you can either copy-paste the command from here, or press Ctrl+Shift+U, then either "63" for lowercase "c", or "43" for uppercase "C", and finally Enter.


text:
Q: Meteor reading csv file Papa Parse guys I am new to Meteor. For my present application I am using openlayer so for openlayer I call Template.map.onRendered event which will load a map which has a overlay which shows marker on map and when we click on this marker an event is generated and a popup is called. Now the data to be shown in popup is hardcoded at present but I want to read it from a .csv file stored on server.
I checked online coders suggested to use Papa Parse with this code.
Papa.parse("http://example.com/file.csv", {
    download: true,
    complete: function(results) {
        console.log(results);
    }
});

My problems are:

*

*But, I don't understand the code and how to use it to solve my
problem.

*And also doing like this is safe or not in terms of browser
compatibility?

*And in which folder I should save this .csv file. On internet it says private folder.

Sorry, I can't share the code using Jsfiddle as it is a private code and I am not allowed to share it.

A: PapaParse is mainly for client-side usage. It also has a Meteor wrapper, harrison:papa-parse, so you can try installing that as well:
meteor add harrison:papa-parse
Parse file via URL:
To parse CSV file on the server side via URL, you can try using the Parse Remote File option:
Papa.parse(url, {
    download: true,
    // rest of config ...
})

Parse file via CSV String:
Else you can store the file in /private folder, as it is a good option in Meteor to keep the file secure.
You can then access the file /private/file.csv using Assets.getText() method that will return a UTF-8 encoded string.
You can include the PapaParse string function in the Assets.getText() callback. After that, you can wrap the resulting function in a Meteor method, which you can call from the client using Meteor.call():
Meteor.methods({
    'parseFile'() {
        // read private asset as text
        Assets.getText('/private/file.csv', (error, result) => {
          if(error) {
            return console.log(error);
          }
          // 'result' should be a UTF-8 string,
          // parse it using PapaParse string function
          return Papa.parse(result)
        });
    }
});

See if that works, read the documentation for more details.
If it doesn't work, check to see if you can read the source file at all on server-side. Often, it turns out to be a relative path error.
Alternative: BabyParse
You can also try to use the PapaParse Node.js fork called BabyParse, available on NPM. However, it cannot read files, only strings. So you will first have to read the CSV file via Assets.getText() and convert it into a CSV string. You can then feed the CSV string into BabyParse to get your result.


text:
Q: Java JSON ignore null values when child objects are null but not the parent object I would like to create json file from below Object graph. Json file should exclude NUll and Empty value.
We do not want to print the name of the parent class when all of its property objects are null.
please the code below.Any solution to remove/ignore writing these values?

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class A {
    @JsonProperty("classA.empName")
    public  B empName = new B();
    @JsonProperty("classA.emp_name")
    public  int age = 25;

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class B {
    @JsonProperty("classB.dept")
    public C dept = new C();
    @JsonProperty("classB.salary")
    public  Integer salary=5445455;
}

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class C {
    @JsonProperty("x")
    public  Integer x = null;
    @JsonProperty("y")
    public  Y y = null;
    @JsonProperty("z")
    public   Z z = null;

}
public class ToJSON {

    ObjectMapper mapper = new ObjectMapper();
    public static void main(String Args[]) throws IOException {
        A a = new A() ;
        System.out.println(mapper.writeValueAsString(sourceObj));
    }

    }
output  : {"classA.empName":{"classB.dept":{},"classB.salary":5445455},"classA.emp_name":25}
expected: {"classA.empName":{"classB.salary":5445455},"classA.emp_name":25}


text:
Q: Selenium Python Firefox vs PhantomJS I am writing a webscraper using selenium on python. I wrote the script to pull information from one site, then go to another and pull different information (emails).
When I run the script with browser = webdriver.Firefox(), the script behaves perfectly. However, for speed purposes I decided to switch to browser = webdriver.PhantomJS().
When I do this, (I tested both scenarios), the driver doesnt seem to go change to the second website and instead pull the second round of information (searching for an email) from the first site.
Why would the script behave differently with phantomJS when all other things are exactly the same?

A: I found the answer. With PhantomJS, you need to specify browser.get('http://www.' + website), which is not required for Firefox.


text:
Q: Rescale logarithmic dB value scale I'm currently working on implementing a peak meter and need to rescale the logarithmic dB-values.
Searching for existing functions I found this: How do I calculate logrithmic labels for a VU meter scale?
It does almost what I need.
I don't get the mathematical background of those functions.
I hope somebody can explain.
function sigLog(n) {
    return Math.log(Math.abs(n) + 1) / Math.log(10) * sig(n);
}

function sig(n) {
    return n == 0 ? 0 : Math.abs(n) / n;
}

function sigExp(n) {
    return (Math.pow(10, Math.abs(n)) - 1) * sig(n);
}

A: First, logarithmic scale is just one of the possible numeric scales, linear is just another. Like, for example, celsius or fahrenheit temperature scales. You may know nothing about "Celsius" or "Fahrenheit", but you can simply use the formulas:
[°C] = ([°F] - 32) × 5/9
[°F] = [°C] × 9/5 + 32

... And do not think about anything (because these scales are strictly defined).
As for logarithmic & linear scales, you should think a little, because you should know which kind of scale you're currently using: for example, you have some "logarithmic" value, but what are the limits of your target linear scale? from 0 to 32768, or may be from 0 to 1 ? Also, The standard used logarithm base is 10, but possible to be another.
What I use to convert logarithmic sound volume parameter to a liner ratio coefficient (from "log" to [0, 1] linear scale), in c++:
float db_to_linear_ratio(float db_val)
{
    return pow(10.0, db_val/10.0);
}

See: Why is a logarithmic scale used to measure sound?
Edit. As for a peak meter, I have never seen it in a real linear scale. In sound editors peak meters just display logarithmic values (-72, -30, -1, 0, ...) on an uniform scale:

Therefore, I see a solution for you not to convert dB-values to a linear scale, but just display them on a uniform scale.


text:
Q: Python can't infer static type of subclass when using a handler factory I would like to use a general HandlerFactory class like the one described here (see Solution 2: Metaprogramming).
Let me use an example:
Suppose we have the following classes:
class Person:
    name: str

@PersonHandlerFactory.register
class Mark(Person):
    name = "Mark"
    job = "scientist"

@PersonHandlerFactory.register
class Charles(Person):
    name = "Charles"
    hobby = "football"

You may have noticed that the subclasses contain a decorator. This decorator is used to register these classes into the following PersonHandlerFactory class, which returns a specific class given the person name:
from typing import Dict, Type

class PersonHandlerFactory:
    handlers: Dict[str, Type[Person]] = {}

    @classmethod
    def register(cls, handler_cls: Type[Person]):
        cls.handlers[handler_cls.name] = handler_cls
        return handler_cls

    @classmethod
    def get(cls, name: str):
        return cls.handlers[name]

As you can see, I used the type Type[Person], because I want this method to be used for any subclass of Person.
But somehow Python interprets the static type of an instance of any subclass as the class Parent:
mark = Mark()  # Static type of 'mark' is 'Person' :S
print(mark.job)  # Python can't find the type of 'job'

I don't want to change Type[Person] for Mark | Charles because the class PersonHandlerFactory should not know about the subclasses of Person.

A: Use a bound TypeVar, this allows the correct subclass to be inferred.
from typing import Dict, Type, TypeVar

class Person:
    name: str

T = TypeVar("T", bound=Person)

class PersonHandlerFactory:
    handlers: Dict[str, Type[Person]] = {}

    @classmethod
    def register(cls, handler_cls: Type[T]) -> Type[T]:
        cls.handlers[handler_cls.name] = handler_cls
        return handler_cls

    @classmethod
    def get(cls, name: str):
        return cls.handlers[name]

@PersonHandlerFactory.register
class Mark(Person):
    name = "Mark"
    job = "scientist"

mark = Mark()  # Static type of 'mark' is 'Mark' :)

The class returned by PersonHandlerFactory.get will however always be inferred as Type[Person]


text:
Q: Google TV emulator without chrome browser? Is it normal not to have the Google Chrome browser on a google TV emulator in a Linux machine with KVM enabled?
When launching an Intent from my application that hits a web page,
I get the error message "No activity found to handle intent {act=android.intent.action.VIEW, dat=http://...}" and I have tried several web addresses.
The code from My Activity is this and it works fine in other android platforms:
Intent myIntent= new Intent(Intent.ACTION_VIEW,
                           Uri.parse( "http://www.test.com");
startActivity(myIntent);

Am I missing some step to install the Google Chrome browser? On the other hand I can not find the Google Market application neither.

A: Sadly it is normal not to have the Chrome browser installed with the emulator. This does make it a bit of a pain to do things like you are trying currently. I'm not sure if there are plans for adding Chrome to the emulator in the future, but in the meantime, it is possible to install Browser.apk (the Android browser) to the emulator (via adb install Browser.apk, which you can either build from AOSP or possibly pull from a device or standard Android emulator via adb pull /system/app/Browser.apk - I think this is the default Browser location on devices).
Once Browser.apk is installed you should be able to test these things as you would expect.
So the steps are:

*

*Start an emulator with Android 3.1 running

*adb -s device_id pull /system/app/Browser.apk

*adb -s device_id install Browser.apk

A: In the Android smart TV emulator, I've tried the simplest method to download the Chrome browser.
Drag and drop the APK onto the emulator after downloading it from the provided link. After you will allow from to Settings > Device Preferences > Security & Restrictions > Unknown sources
Chrome APK Download URL
Second
Alternate you can follow the article link


text:
Q: C Name Mangling - Where are the technical documents? The C standard does not specify how compilers should generate the name of a C function inside an object file. It seems that GCC compatible front-ends simply prepend the name of the C function by an underscore. Microsoft compilers use a different strategy.
However, a lot of languages are able to call C functions (Rust, Go, etc).
I assume that the developers had access to some document explaining how the C symbols are translated by the different compilers on the different operating systems.
Is there some publicly available website/document/RFC documenting this point for the different compilers (GCC, Visual C++, etc) or operating systems?
EDIT: On this page http://www.iecc.com/linker/linker05.html in the Name Mangling section, a brief history is given. On this post: What is the reason function names are prefixed with an underscore by the compiler?, we talk about a simple convention. Has this rule been ever written somwhere in some of the compilers' documentation?


text:
Q: Capturing the previous one and next one word from a sentence based on searched word and start position I want to retrieve the previous one and next one word of the searched word based on the searched word and his start position(character index of the searched word in the string and starting from 0) from a string in java.
For example, if I have a string as follows:
I am a teacher and a father.

If given a searched word is : a
and his start position: 4
the output should be:
am a teacher

If given a searched word is : a
and his start position:18
the output should be:
and a father

Any ideas?
EDIT: Keep in mind I need to use the start position as there may be duplicate words in the string.

A: public String searchedWordContext(String sentence, String searchedWord) {
    if (sentence == null || searchedWord == null) throw new IllegalArgumentException("May not be null");
    String[] words = sentence.split(" ");
    int searchedIndex = -1;
    for (int i=0; i<words.length; i++) {
        if (words[i].equals(searchedWord)) searchedIndex = i;
        // first occurence - abort
        if (searchedIndex!=-1) break;
    }
    if (searchedIndex == -1) throw new IllegalArgumentException("Searched word: " + searchedWord + " not found in sentence: " + sentence);
    if (words.length < 2) return searchedWord;
    if (searchedIndex == 0) return words[searchedIndex] + " "+ words[serchedIndex+1];
    if (searchedIndex == words.length) return words[searchedIndex-1] + " "+ words[searchedIndex];
    return words[searchedIndex-1] + " " + words[searchedIndex] + " " + words[searchedIndex+1];
}

A: public String queryExamples(String sentence,int selectedPosition) {
    StringBuffer queries = new StringBuffer();
    if (selectedPosition > sentence.length()) {
    throw new IllegalArgumentException("The selected position must be less than sentence length.");
        }
        String[] afterWords = sentence.substring(selectedPosition).split(" ");
        String afterWord = "";
        String beforeWord = "";
        if (afterWords.length == 1) {
            afterWord = "";
        } else {
            afterWord = afterWords[1];
        }

        if(selectedPosition==0){
            beforeWord = "";
        } else {
            String[] WordList = sentence.substring(0, selectedPosition).split(" ");
            if (WordList.length > 0) {
                beforeWord = WordList[WordList.length - 1];
            }
        }
        queries.append(beforeWord).append(" ").append(afterWord);

    }

    return queries;
}


text:
Q: PHP/AJAX Live logins log Basically, when the user logins, I need a separate web page automatically updating each log in, for example:
12:30 User1 have logged in.
12:35 User5 have logged in.
etc. etc.
I want the page to update itself all the time.
How can I achieve this simply?
@Edit
Yes, I know about Ajax, but I mean generally how to do it.
When the user logins, shall I write into HTML each log line by line and then use Ajax to keep reloading it?

A: When a user logs in, you append a string to a file using PHP.
Now create a PHP file called ajaxCalls.php and from there you have to open the file and echo out every row.(be sure to encode this output as json, it becomes easier to work with in javascript).
Now call ajaxCalls.php(using AJAX) and fetch the result as a a json object from the page you want the strings below to be shown on.
12:30 User1 have logged in.
12:35 User5 have logged in.

login.php
<?php
    $username = "foo";
    $password = "bar";
    if(userCanLogin($username, $password))
    {
        saveToFile($username);
    }

    function saveToFile($username)
    {
        $fileHandle = fopen("userLogins.txt", "a");
        fwrite(date("H:i") . " " . $username . " has logged in.", $fileHandle);
        fclose($fileHandle);
    }
?>

index.php The page you want the to update automaticly

ajax.php This file is should only be called asynchronous
<?php
    $lines = file("userLogins.txt");
    echo json_encode($lines);
?>

All of the code above is untested!
If you want instant updates, you have to setup a service that "pushes" the data to you, instead of "pulling".
When pushing is performed, the client acts like a receiver which is sent from a server. The then have to use some sort of sockets, like WebSockets to handle the data. You can either use a "push" provider like http://beaconpush.com/ or create your own push server(NodeJS is recommended).


text:
Q: ASP.NET files necessary for development I am just getting started in ASP.NET and have some existing projects to maintain.
I have read that ASP.NET projects include a folder called app_data, a code behind DLL, .sln project files, .proj files etc
Which of these files are necessary for the continued development of a ASP.NET website?
Also, are there others which are key to building ASP.NET applications?

A: Unfortunately, there are two kinds of ASP.NET application: Web Sites and Web Application Projects. If you have files with a .csproj type or .vbproj, then you're in luck - you have a Web Application Project. You'll want to open the .csproj file as a project in Visual Studio. All the files that are listed are necessary.
In fact, if it's in the site's folder or subfolders, you should assume it's necessary.


text:
Q: Demystify Windbd memory usage labels: "Private Working Set" is large while memory is marked as RegionUsageFree After a run, i see that my application takes 3.5Gb in TaskMgr

What I see in Windbg is a little bit confusing:
0:022> !address -summary
 ProcessParametrs 0000000001b7ed70 in range 0000000001b7e000 0000000001b80000
 Environment 0000000001c0c970 in range 0000000001c0c000 0000000001c0e000

-------------------- Usage SUMMARY --------------------------
    TotSize (      KB)   Pct(Tots) Pct(Busy)   Usage
   1037fe000 ( 4251640) : 00.05%    87.22%    : RegionUsageIsVAD
   7fed67a5000 (8585059988) : 99.94%    00.00%    : RegionUsageFree
    7dd6000 (  128856) : 00.00%    02.64%    : RegionUsageImage
    1900000 (   25600) : 00.00%    00.53%    : RegionUsageStack
      32000 (     200) : 00.00%    00.00%    : RegionUsageTeb
     950000 (    9536) : 00.00%    00.20%    : RegionUsageHeap
   1bff4000 (  458704) : 00.01%    09.41%    : RegionUsagePageHeap
       1000 (       4) : 00.00%    00.00%    : RegionUsagePeb
          0 (       0) : 00.00%    00.00%    : RegionUsageProcessParametrs
          0 (       0) : 00.00%    00.00%    : RegionUsageEnvironmentBlock
       Tot: 7ffffff0000 (8589934528 KB) Busy: 000000012984b000 (4874540 KB)

-------------------- Type SUMMARY --------------------------
    TotSize (      KB)   Pct(Tots)  Usage
   7fed67b5000 (8585060052) : 99.94%   : <free>
    7dd7000 (  128860) : 00.00%   : MEM_IMAGE
    2e76000 (   47576) : 00.00%   : MEM_MAPPED
   11ebee000 ( 4698040) : 00.05%   : MEM_PRIVATE

-------------------- State SUMMARY --------------------------
    TotSize (      KB)   Pct(Tots)  Usage
   df283000 ( 3656204) : 00.04%   : MEM_COMMIT
   7fed67b5000 (8585060052) : 99.94%   : MEM_FREE
   4a5b8000 ( 1218272) : 00.01%   : MEM_RESERVE

So, 99.94% of memory is RegionUsageFree ?
Can someone demystify the terms above ? RegionUsageFree means memory was free'd and can be used ? What is Private Working Set means ?
If free, why is shown in Private Working Set ? Should I worry about this ? That memory can be (re)used ? I'm on 64 bit, OOM is not an issue here, on 32 it might be ? How  can I reduce this Private Working Set ?
PS: The heap look good:
0:022> !heap -s
LFH Key                   : 0x0000005b29625009
Termination on corruption : ENABLED
          Heap     Flags   Reserv  Commit  Virt   Free  List   UCR  Virt  Lock  Fast
                            (k)     (k)    (k)     (k) length      blocks cont. heap
-------------------------------------------------------------------------------------
00000000000e0000 00000002    1024      8   1024      3     1     1    0      0
0000000003c20000 00001002     512      8    512      3     1     1    0      0
0000000004d40000 00001002     512      8    512      3     1     1    0      0
00000000001e0000 00008000      64      8     64      5     1     1    0      0
00000000070e0000 00001002      64      8     64      3     1     1    0      0
0000000004d30000 00001002      64      8     64      3     1     1    0      0
0000000007010000 00001002     512      8    512      3     1     1    0      0
0000000004d00000 00001002      64      8     64      3     1     1    0      0
000000000c8b0000 00001002     512      8    512      3     1     1    0      0
00000000070b0000 00001002      64      8     64      3     1     1    0      0
000000000ef00000 00001002      64     32     64     27     1     1    0      0
0000000012180000 00001002     512      8    512      3     1     1    0      0
000000000f630000 00001002     512      8    512      3     1     1    0      0
0000000010490000 00001002      64      8     64      3     1     1    0      0
00000000105b0000 00001002     512      8    512      3     1     1    0      0
0000000012170000 00001002      64      8     64      3     1     1    0      0
0000000039860000 00001002     512      8    512      3     1     1    0      0
00000000397e0000 00001003     512      8    512      5     1     1    0    bad
000000003ca30000 00001003     512      8    512      5     1     1    0    bad
000000003dbc0000 00001003     512      8    512      5     1     1    0    bad
0000000010900000 00001003     512      8    512      5     1     1    0    bad
0000000012090000 00001003     512      8    512      5     1     1    0    bad
0000000039730000 00001003     512      8    512      5     1     1    0    bad
0000000010aa0000 00001003     512      8    512      5     1     1    0    bad
00000000136b0000 00001002      64      8     64      3     1     1    0      0
000000000eff0000 00001002      64      8     64      3     1     1    0      0
0000000013590000 00001002      64      8     64      3     1     1    0      0
0000000013850000 00001002      64      8     64      3     1     1    0      0
000000000fd70000 00001002      64      8     64      3     1     1    0      0
-------------------------------------------------------------------------------------

A: TaskMgr and WinDbg both display right data. Look more about Private Working Set at How to interpret Windows Task Manager?  99.94% of memory is RegionUsageFree because x64 has 8TB size virtual address space in user mode and almost all of it is free and can be used. You do not must reduce working set. Windows trims working sets for you. (Although you can use VMMap Empty Working Set feature in the View menu) For more information see M. Russinovich blog Pushing the Limits of Windows: Virtual Memory.


text:
Q: Python slicing and negative stride - why are these examples apparently contradictory? I've read a bunch of answers here about combining slicing with negative strides, but the following issue still confuses me. In several places, I've seen the diagram below used to illustrate how slice notation works (referring to gaps, rather than entries):
 +---+---+---+---+
 | T | e | s | t |
 +---+---+---+---+
 0   1   2   3   4
-4  -3  -2  -1

These examples are consistent with the diagram above:
>>> "Test"[2:]
'st'

>>> "Test"[-2:]
'st'

But
>>> "Test"[-2::-1]
'seT'

does not seem consistent - if starting at the -2 divider, and counting backwards, why is the s also included in the returned string?

A: The mental model you have is thus only useful to positive stride values, but it doesn't help when using negative strides. Use the following picture instead:
  +---+---+---+---+
  | T | e | s | t |
  +---+---+---+---+
    0   1   2   3   4
-5 -4  -3  -2  -1

where you label the indices, not the boundaries.
The boundary model is nice, but only for making it easier to forget about the fact that the end index is not included in the resulting value. By just numbering the indices instead and omitting the end index, you can see how both positive and negative strides work.
For the nitty gritty details, take a look at the official documentation for the way Python calculates slices; from the sequence type notes (note 5):

s[i:j:k]
  The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become "end" values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

So, for your negative stride, the values become:
i = len(s) - 2 = 2
j = None = -1 (end for negative strides, *not* len(s) - 1)
k = -1

where j is the 'end', here -1 as that is the point where you ran out of string in a negative step. Then the indices become:
x0 = i + 0*k = 2
x1 = i + 1*k = 1
x2 = i + 2*k = 0

giving you 3 indices.

A: If "Test"[-2:] includes s, then by the same logic, it'll include s in "Test"[-2::-1] as the range includes the first position but excludes the second position.


text:
Q: Why accesing DataFrame from UDF results in NullPointerException? I have a problem executing a Spark application.
Source code:
// Read table From HDFS
val productInformation = spark.table("temp.temp_table1")
val dict = spark.table("temp.temp_table2")

// Custom UDF
val countPositiveSimilarity = udf[Long, Seq[String], Seq[String]]((a, b) =>
    dict.filter(
        (($"first".isin(a: _*) && $"second".isin(b: _*)) || ($"first".isin(b: _*) && $"second".isin(a: _*))) && $"similarity" > 0.7
    ).count
)

val result = productInformation.withColumn("positive_count", countPositiveSimilarity($"title", $"internal_category"))

// Error occurs!
result.show

Error message:
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 54.0 failed 4 times, most recent failure: Lost task 0.3 in stage 54.0 (TID 5887, ip-10-211-220-33.ap-northeast-2.compute.internal, executor 150): org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1: (array<string>, array<string>) => bigint)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at $anonfun$1.apply(<console>:45)
    at $anonfun$1.apply(<console>:43)
    ... 16 more

Driver stacktrace:
  at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
  at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
  at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
  at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
  at scala.Option.foreach(Option.scala:257)
  at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
  at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
  at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
  at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
  at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
  at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)
  at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:333)
  at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
  at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2371)
  at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
  at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2765)
  at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2370)
  at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2377)
  at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2113)
  at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2112)
  at org.apache.spark.sql.Dataset.withTypedCallback(Dataset.scala:2795)
  at org.apache.spark.sql.Dataset.head(Dataset.scala:2112)
  at org.apache.spark.sql.Dataset.take(Dataset.scala:2327)
  at org.apache.spark.sql.Dataset.showString(Dataset.scala:248)
  at org.apache.spark.sql.Dataset.show(Dataset.scala:636)
  at org.apache.spark.sql.Dataset.show(Dataset.scala:595)
  at org.apache.spark.sql.Dataset.show(Dataset.scala:604)
  ... 48 elided
Caused by: org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1: (array<string>, array<string>) => bigint)
  at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
  at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
  at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
  at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
  at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
  at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
  at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
  at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
  at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
  at org.apache.spark.scheduler.Task.run(Task.scala:99)
  at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
  ... 3 more
Caused by: java.lang.NullPointerException
  at $anonfun$1.apply(<console>:45)
  at $anonfun$1.apply(<console>:43)
  ... 16 more

I have checked whether productInformation and dict have null value in Columns. But there are no null values.
Can anyone help me?
I attached example code to let you know more details:
case class Target(wordListOne: Seq[String], WordListTwo: Seq[String])
val targetData = Seq(Target(Seq("Spark", "Wrong", "Something"), Seq("Java", "Grape", "Banana")),
                     Target(Seq("Java", "Scala"), Seq("Scala", "Banana")),
                     Target(Seq(""), Seq("Grape", "Banana")),
                     Target(Seq(""), Seq("")))
val targets = spark.createDataset(targetData)

case class WordSimilarity(first: String, second: String, similarity: Double)
val similarityData = Seq(WordSimilarity("Spark", "Java", 0.8),
                     WordSimilarity("Scala", "Spark", 0.9),
                     WordSimilarity("Java", "Scala", 0.9),
                     WordSimilarity("Apple", "Grape", 0.66),
                     WordSimilarity("Scala", "Apple", -0.1),
                     WordSimilarity("Gine", "Spark", 0.1))
val dict = spark.createDataset(similarityData)

val countPositiveSimilarity = udf[Long, Seq[String], Seq[String]]((a, b) =>
    dict.filter(
        (($"first".isin(a: _*) && $"second".isin(b: _*)) || ($"first".isin(b: _*) && $"second".isin(a: _*))) && $"similarity" > 0.7
    ).count
)

val countDF = targets.withColumn("positive_count", countPositiveSimilarity($"wordListOne", $"wordListTwo"))

This is an example code and is similar to my original code.
Example code operates well. Which point should I check in original code and data?

A: You can not use a Dataframe inside of an udf. You will need to join productInformation and dict, and do the udf logic after the join.

A: Very interesting question. I have to do some search, and here is my though. Hope this will help you a little bit.
When you create Dataset via createDataset, spark will assign this dataset with LocalRelation logical query plan.
def createDataset[T : Encoder](data: Seq[T]): Dataset[T] = {
    val enc = encoderFor[T]
    val attributes = enc.schema.toAttributes
    val encoded = data.map(d => enc.toRow(d).copy())
    val plan = new LocalRelation(attributes, encoded)
    Dataset[T](self, plan)
  }

Follow this link:
LocalRelation is a leaf logical plan that allow functions like collect or take to be executed locally, i.e. without using Spark executors.
And, it's true as isLocal method point out
 /**
   * Returns true if the `collect` and `take` methods can be run locally
   * (without any Spark executors).
   *
   * @group basic
   * @since 1.6.0
   */
  def isLocal: Boolean = logicalPlan.isInstanceOf[LocalRelation]

Obviously, You can check out your 2 datasets is local.
And, the show method actually call take internally.
private[sql] def showString(_numRows: Int, truncate: Int = 20): String = {
    val numRows = _numRows.max(0)
    val takeResult = toDF().take(numRows + 1)
    val hasMoreData = takeResult.length > numRows
    val data = takeResult.take(numRows)

So, with those envidences, I think the call countDF.show is executed, it will behave simliar as when you call count on dict dataset from driver, number of call times is number of records of targets. And, the dict dataset of course doesn't need to be local for the show on countDF work.
You can try to save countDF, it will give you exception same as first case
org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1: (array<string>, array<string>) => bigint)


text:
Q: Error en php y sql por medio de conexion odbc Tengo el siguiente código. Al momento que ejecuto en el navegador me indica el único error:

odbc_exec() expects parameter 1 to be resource, string given in C:\AppServ\www\centrales\index.php on line 64

la linea 64 es la siguiente:
$result = odbc_exec($sql,$cid);

codigo php
<?php include("templates/header.php"); ?>

Centrales vs Mediacion

Listado de Centrales

Selecciona la central <form action="index.php" method="post"><select name="filtro"><option value="todos"></option><option value="Nimajuyu">Nimajuyu</option><option value="El Carmen 2">El Carmen 2</option><option value="Monte Verde 5">Monte Verde 5</option><option value="Lourdes EIN">Lourdes EIN</option><option value="Guarda Transito">Guarda Transito</option><option value="Guarda Viejo 5">Guarda Viejo 5</option><option value="Centro Transito EIN">Centro Transito EIN</option><option value="Tivoli">Tivoli</option><option value="Villa de Guadalupe 3">Villa de Guadalupe 3</option><option value="Aristos">Aristos</option><option value="Chimaltenango">Chimaltenango</option><option value="Retalhuleu">Retalhuleu</option><option value="Zacapa">Zacapa</option></select> <button type="submit">Filtrar</button></form>

    <?php
        $result = odbc_exec($sql,$cid);
        echo '

                central
                centrales_nombre
                fecha_dcms
                archivo_dcms
                correlativo_dcms
                bytes_dcms
                archivo_ivr
                correlativo_ivr
                fecha_ivr
                bytes_ivr
                ivr_num_eventos
                dif_bytes

';
if(($registro)>0)
{
    while($registro2 = odbc_fetch_array($registro)){
        echo '

                '.$registro2['central'].'
                '.$registro2['centrales_nombre'].'
                '.$registro2['fecha_dcms'].'
                '.$registro2['archivo_dcms'].'
                '.$registro2['correlativo_dcms'].'
                '.$registro2['bytes_dcms'].'
                '.$registro2['archivo_ivr'].'
                '.$registro2['correlativo_ivr'].'
                '.$registro2['fecha_ivr'].'
                '.$registro2['bytes_ivr'].'
                '.$registro2['ivr_num_eventos'].'
                '.$registro2['dif_bytes'].'

';
    }
}else{
    echo '

                No se encontraron resultados

';
}
echo '
';

?>

Donde las variables han sido definidas previamente asi
$sql = "select * from tarificado.rep_con where extract(week from fecha_dcms) in(19) AND central in (208) order by central,correlativo_dcms, archivo_dcms;";

A: El problema es que tienes los parametros al revez.  Primero va la conexion y despues el query asi:
$result = odbc_exec($cid, $sql);


text:
Q: $|\det (A+B)|\ge |\det B|$ for all $B$ such that $AB=BA$ iff $A^2=O$
Let $A\in M_2(\mathbb{C})$. $Z(A)$ is the set of all $B\in M_2(\mathbb{C})$ such that $AB=BA$. Prove that $|\det(A+B)|\ge |\det B|$ for all $B\in Z(A)$ if and only if $A^2=O$.

If $A^2=O$ and $A\neq O$, suppose $\lambda$ is an eigenvalue of $A+B$. Then $(A+B)x=\lambda x$, then $A(A+B)x=\lambda(Ax)$, or $ABx=\lambda (Ax)$, or $B(Ax)=\lambda(Ax)$. Then $\lambda$ is also an eigenvalue of $B$. Thus $\det (A+B)=\det B$.
The problem is I don't know how to deal with the converse, that is if $|\det (A+B)|\ge |\det B|$ for all $B\in Z(A)$, then $A^2=O$.
Thanks in advance.

A: Claim: Both eigenvalues of $A$ are zero.
Proof: If $A$ has a non-zero eigenvalue $\lambda \neq 0,$ then take $B=-\lambda I$ resulting $0= |\det(A - \lambda I)| \geq |\det(-\lambda I)|=|\lambda|^2,$ thus, $\lambda =0 $ also implying $\text{tr}(A)=\det(A)=0$
Now, by Cayley-Hamilton (for $2$ by $2$ matrices), we have $A^2 - \text{tr}(A)A + \det(A)=0 \to A^2=0$


text:
Q: React.JS: Quill starts infinite loop using dangerouslyPasteHTML I'm trying to build a spell checker editor using React.JS and Quill.JS module: https://www.npmjs.com/package/react-quilljs.
At this moment, I can paint my misspelling words using the formatText method and display some suggested words to correct (this will appear as a button).
However, when clicking the button it sends, via props, the wrong words and the corrected one to replace them in my Editor.JS component. I have already used the quillRef.current.firstChild.innerHTMLand it works for the first time but when I continue writing the editor can not painting the wrong words correctly (although it continues to display them in the interface) and the quill cursor goes to the beginning.
Another solution that I made was quill.setText(corrected_phrase); but it works inside a settimeout function and delete all the style format (ex: bold, italic, etc.).
However, I found that with dangerouslyPasteHTML I can keep the formatting applied, but the editor goes into an infinite loop, replicating the words endlessly.
 var [palavrasCorrigirImediaBODY] = useGlobalState("palavraErradaCorrigir")

var [palavrasACORRIGIRImediaBODY] = useGlobalState("palavraSugerida")

if (palavrasACORRIGIRImediaBODY != "" && palavrasCorrigirImediaBODY != "") {
    corrigirPalavrasBodyText(palavrasACORRIGIRImediaBODY, palavrasCorrigirImediaBODY);
}

function corrigirPalavrasBodyText(palavrasACORRIGIRImediaBODY, palavrasCorrigirImediaBODY) {

    let uniqueChars = [...new Set(indexes_arrays_mal)];

    console.log(uniqueChars);
    let novaFrase;
    var count = 0;
    uniqueChars.map((resposta, indexes) => {

        console.log(indexes);
        console.log(quillRef.current.firstChild.innerHTML);
        if (resposta[2] == palavrasCorrigirImediaBODY) {

            novaFrase = quillRef.current.firstChild.innerHTML.replaceAll(palavrasCorrigirImediaBODY, palavrasACORRIGIRImediaBODY);
            count = 1;
            //quillRef.current.firstChild.innerHTML.replaceAll(palavrasCorrigirImediaBODY, palavrasACORRIGIRImediaBODY);

        }
    });

    if (count == 1) {

        var timer3 = setTimeout(() => {

            let frase_escrita = novaFrase;

            var content = quill.container.innerHTML;

            quill.clipboard.dangerouslyPasteHTML(0, novaFrase)

            // quill.setText(novaFrase);
        }, 1000);
    }

Thank you for your attention.


text:
Q: Is it possible to set private property via reflection? Can I set a private property via reflection?
public abstract class Entity
{
    private int _id;
    private DateTime? _createdOn;
    public virtual T Id
    {
        get { return _id; }
        private set { ChangePropertyAndNotify(ref _id, value, x => Id); }
    }
    public virtual DateTime? CreatedOn
    {
        get { return _createdOn; }
        private set { ChangePropertyAndNotify(ref _createdOn, value, x => CreatedOn); }
    }
}

I've tried the following and it does not work, where t represents a type of Entity:
var t = typeof(Entity);
var mi = t.GetMethod("set_CreatedOn", BindingFlags.Instance | BindingFlags.NonPublic);

I guess I can do this but I can't work it out.

A: None of these worked for me, and my property name was unique, so I just used this:
public static void SetPrivatePropertyValue<T>(T obj, string propertyName, object newValue)
{
    // add a check here that the object obj and propertyName string are not null
    foreach (FieldInfo fi in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
    {
        if (fi.Name.ToLower().Contains(propertyName.ToLower()))
        {
            fi.SetValue(obj, newValue);
            break;
        }
    }
}

A: Yes, it is:
/// <summary>
/// Returns a _private_ Property Value from a given Object. Uses Reflection.
/// Throws a ArgumentOutOfRangeException if the Property is not found.
/// </summary>
/// <typeparam name="T">Type of the Property</typeparam>
/// <param name="obj">Object from where the Property Value is returned</param>
/// <param name="propName">Propertyname as string.</param>
/// <returns>PropertyValue</returns>
public static T GetPrivatePropertyValue<T>(this object obj, string propName)
{
    if (obj == null) throw new ArgumentNullException("obj");
    PropertyInfo pi = obj.GetType().GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    if (pi == null) throw new ArgumentOutOfRangeException("propName", string.Format("Property {0} was not found in Type {1}", propName, obj.GetType().FullName));
    return (T)pi.GetValue(obj, null);
}

/// <summary>
/// Returns a private Property Value from a given Object. Uses Reflection.
/// Throws a ArgumentOutOfRangeException if the Property is not found.
/// </summary>
/// <typeparam name="T">Type of the Property</typeparam>
/// <param name="obj">Object from where the Property Value is returned</param>
/// <param name="propName">Propertyname as string.</param>
/// <returns>PropertyValue</returns>
public static T GetPrivateFieldValue<T>(this object obj, string propName)
{
    if (obj == null) throw new ArgumentNullException("obj");
    Type t = obj.GetType();
    FieldInfo fi = null;
    while (fi == null && t != null)
    {
        fi = t.GetField(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        t = t.BaseType;
    }
    if (fi == null) throw new ArgumentOutOfRangeException("propName", string.Format("Field {0} was not found in Type {1}", propName, obj.GetType().FullName));
    return (T)fi.GetValue(obj);
}

/// <summary>
/// Sets a _private_ Property Value from a given Object. Uses Reflection.
/// Throws a ArgumentOutOfRangeException if the Property is not found.
/// </summary>
/// <typeparam name="T">Type of the Property</typeparam>
/// <param name="obj">Object from where the Property Value is set</param>
/// <param name="propName">Propertyname as string.</param>
/// <param name="val">Value to set.</param>
/// <returns>PropertyValue</returns>
public static void SetPrivatePropertyValue<T>(this object obj, string propName, T val)
{
    Type t = obj.GetType();
    if (t.GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) == null)
        throw new ArgumentOutOfRangeException("propName", string.Format("Property {0} was not found in Type {1}", propName, obj.GetType().FullName));
    t.InvokeMember(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, obj, new object[] { val });
}

/// <summary>
/// Set a private Property Value on a given Object. Uses Reflection.
/// </summary>
/// <typeparam name="T">Type of the Property</typeparam>
/// <param name="obj">Object from where the Property Value is returned</param>
/// <param name="propName">Propertyname as string.</param>
/// <param name="val">the value to set</param>
/// <exception cref="ArgumentOutOfRangeException">if the Property is not found</exception>
public static void SetPrivateFieldValue<T>(this object obj, string propName, T val)
{
    if (obj == null) throw new ArgumentNullException("obj");
    Type t = obj.GetType();
    FieldInfo fi = null;
    while (fi == null && t != null)
    {
        fi = t.GetField(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        t = t.BaseType;
    }
    if (fi == null) throw new ArgumentOutOfRangeException("propName", string.Format("Field {0} was not found in Type {1}", propName, obj.GetType().FullName));
    fi.SetValue(obj, val);
}

A: You can access private setter from derived type via code
public static void SetProperty(object instance, string propertyName, object newValue)
{
    Type type = instance.GetType();

    PropertyInfo prop = type.BaseType.GetProperty(propertyName);

    prop.SetValue(instance, newValue, null);
}

A: t.GetProperty("CreatedOn")
    .SetValue(obj, new DateTime(2009, 10, 14), null);

EDIT: Since the property itself is public, you apparently don't need to use BindingFlags.NonPublic to find it.  Calling SetValue despite the the setter having less accessibility still does what you expect.

A:     //mock class
    public class Person{
        public string Name{get; internal set;}
    }

    // works for all types, update private field through reflection
    public static T ReviveType<T>(T t, string propertyName, object newValue){
        // add a check here that the object t and propertyName string are not null
        PropertyInfo pi = t.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
         pi.SetValue(t, newValue, null);
        return t;
    }

    // check the required function
    void Main()
    {
        var p = new Person(){Name="John"};
        Console.WriteLine("Name: {0}",p.Name);

        //box the person to object, just to see that the method never care about what type you pass it
        object o = p;
        var updatedPerson = ReviveType<Object>(o, "Name", "Webber") as Person;

         //check if it updated person instance
        Console.WriteLine("Name: {0}",updatedPerson.Name);
    }

// Console Result: -------------------
Name: John
Name: Webber

A: Use
            UtilTest.SetProperty(data.Process, "CurrentStepId", (int)WorkFlowStep.HappyClaimsIsContract);

Definition
public class UtilTest
{
public static void SetProperty( object instance, string propertyName, object newValue)
    {
        try
        {
            Type type = instance.GetType();

            PropertyInfo prop = type.GetProperty(propertyName);
            if (prop.PropertyType == typeof(decimal))
            {
                prop.SetValue(instance, Convert.ToDecimal(newValue), null);

            }
            else
            {
                prop.SetValue(instance, newValue, null);
            }
        }
        catch
        {
        }

    }

}