text:
Q: How to return values from controls in popup and add them to the main page? The main page has a button for adding new items. When the user presses it, a popup window appears.

I used this code for popup.xaml:
<xct:Popup xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MReport.popup01"
             xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
             Size="300,400">

    <ScrollView>
        <StackLayout Orientation="Vertical" Spacing="10">
            <Label Text="From Time:" Padding="5,5,0,0" TextColor="Black"
                HorizontalTextAlignment="Start" />
            <TimePicker HorizontalOptions="Center" Time="00:00" />
            <Label Text="To Time" Padding="5,5,0,0" TextColor="Black"
                HorizontalTextAlignment="Start" />
            <TimePicker HorizontalOptions="Center"/>
            <Label Text="Your Activities:" Padding="5,5,0,0" TextColor="Black" />
            <Editor x:Name="editor_value" VerticalOptions="CenterAndExpand" HeightRequest="200" />
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Button Grid.Column="1" Text="Add" Clicked="Button_Clicked_1" />
                <Button Grid.Column="0" Text="Cancel" Clicked="Button_Clicked" />
            </Grid>
        </StackLayout>
    </ScrollView>

</xct:Popup>

For popup.xaml.cs:
using Xamarin.CommunityToolkit.UI.Views;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace MReport
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class popup01 : Popup
    {
        public popup01()
        {
            InitializeComponent();
        }
        private void Button_Clicked(object sender, EventArgs e)
        {
            Dismiss("Cancelled");
        }

        private void Button_Clicked_1(object sender, EventArgs e)
        {

        }
    }
}

For TabbedPage:
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MReport.TabbedMainPage">
  <!--Pages can be added as references or inline-->
    <ContentPage Title="New Report" IconImageSource="NewReport.png" BackgroundImageSource="blue_windows.jpg">
        <StackLayout>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <ScrollView>
                    <StackLayout>
                        <Label x:Name="lbl01" />
                    </StackLayout>
                </ScrollView>
                <Button Grid.Row="1" Text="Add New Item" Clicked="Button_Clicked"/>
            </Grid>
            <Button Grid.Row="1" Text="Send Report" />
        </StackLayout>
    </ContentPage>
    <ContentPage Title="Report History" IconImageSource="History.png" BackgroundImageSource="blue_windows.jpg" />
    <ContentPage Title="Messages" IconImageSource="Message.png" BackgroundImageSource="blue_windows.jpg"/>

</TabbedPage>

For TabbedPage.xaml.cs:
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
using Xamarin.Forms.Xaml;
using Xamarin.CommunityToolkit.Extensions;

namespace MReport
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TabbedMainPage : Xamarin.Forms.TabbedPage
    {
        public TabbedMainPage()
        {
            InitializeComponent();
            On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
            On<Android>().SetIsSmoothScrollEnabled(false);
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            Navigation.ShowPopup(new popup01());
        }
    }
}

I use CommunityToolKit for the popup.
The popup has two buttons. The ADD button will add the information entered in the popup to the main page.
I want the output to be like the image I've provided.
These frame boxes and their texts are added each time the user presses the add button in the popup. Those frame boxes are expanded based on the text volume inside them. What code should be written for the ADD button?
Please help me.

A: ShowPopupAsync can return a value to the caller
var result = await Navigation.ShowPopupAsync(popup);

whatever parameter is passed to Dismiss() will be returned to the caller


text:
Q: Paginate across two different tables I got two tables and wondering if it's possible to join them into one query.
the script gets a catID as GET, it should then list all the subCats(if any) and then list the photos that are in the mainCat cat = catID and subcat = 0
subCats table is:
id | parentCat | title | addedBy | date | active | defaultPhoto
photos table is: id | title | description | fileName | fileType | uploadedBy | time | cat | subCat
I got a pagination script that takes a count and generates a LIMIT to use. Wondering if I can combine this into one query for both tables some how to make pagination easier with what I got already. So one selects the count for both with the join, then another selects the results.
Any ideas? Really stuck on this.
This is my messy start but it seems like a bad design so far:
<?php
    if ($catInfoResult = $db->select("SELECT * FROM cats WHERE id = '%s' LIMIT 1", $catID))
    {
        if ($db->numRows > 0)
        {
            $pageTitle = h($catInfoResult[0]['title']) . ' - Photo Gallery';
            ?>

<?=h($catInfoResult[0]['title'])?> Photos

            <?php

            //get subCats
            $subCatCountResult = $db->count('subCats', '*', array('parentCat' => $catID));

            if (is_numeric($subCatCountResult))
            {
                $PerPage = 9; //how many locations you want to show per page

                $subCatLastPage = ceil($subCatCountResult/$PerPage);

                if ($subCatLastPage < 1)
                {
                    $subCatLastPage = 1;
                }

                $pageNum = (isset($_GET['pg'])) ? trim($_GET['pg']) : 1;
                $pageNum = preg_replace('#[^0-9]#', '', $pageNum);

                //////////////////////////////////////////////////

                $subCatLimit = 'LIMIT ' . ($pageNum - 1) * $PerPage . ',' . $PerPage;

                //////////////////////////////////////////////////

                $itemList = array(
                    'subCats' => array(),
                    'photos' => array()
                );

                if ($subCatListResult = $db->select("SELECT * FROM subCats WHERE parentCat = %s ORDER BY title $subCatLimit", $catID))
                {

                    if ($db->numRows > 0)
                    {
                        foreach ($subCatListResult as $row)
                        {

                            $photoID = 0;

                            if ($row['defaultPhoto'] == 0) //look up photo for
                            {

                                if ($firstPhotoResult = $db->select("SELECT id, time FROM photos WHERE subCat = '%s' ORDER BY time ASC LIMIT 1", $row['id']))
                                {
                                    if ($db->numRows > 0)
                                    {
                                        $photoID = $firstPhotoResult[0]['id'];
                                    }
                                    else
                                    {
                                        $photoID = -1;
                                    }

                                }

                            }
                            else
                            {
                                $photoID = $row['defaultPhoto'];
                            }

                            //add to $itemList
                            $itemList['subCats'][$row['id']] = array(
                                'title' => $row['title']
                            );

                            $itemList['subCats'][$row['id']]['defaultPhoto'] = $photoID;

                        }

                    }

                }
                else
                {
                    throwDBError();
                }

                function addPhotoToItemList($row)
                {
                    global $itemList;

                    $itemList['photos'][$row['id']] = array(
                        'title' => $row['title'],
                        'fileName' => $row['fileName'],
                        'fileType' => $row['fileType']
                    );

                    //

                }

                //get photos after subcats
                $photosOffset = 0;

                $grabPhotosCount = 9 - count($itemList['subCats']);

                if ($grabPhotosCount > 0)
                {

                    if ($result = $db->select("SELECT * FROM photos WHERE cat = %s and subCat = 0 ORDER BY title LIMIT 0, $grabPhotosCount", $catID))
                    {
                        if ($db->numRows > 0)
                        {
                            foreach ($result as $row)
                            {
                                $photosOffset++;
                                addPhotoToItemList($row);
                            }
                        }
                    }
                    else
                    {
                        throwDBError();
                    }

                }

                //get photos in maincat

                $photosCountResult = $db->count('photos', '*', array('cat' => $catID, 'subCat' => 0));

                if (is_numeric($photosCountResult))
                {

                }
                else
                {
                    throwDBError();
                }

                if ($pageNum < 1)
                {
                    $pageNum = 1;
                }
                else if ($pageNum > $subCatLastPage) //get photos
                {
                    if (count($itemList) < 9)
                    {
                        //load in photos for cat

                    }

                    //redirect('/gallery/?cat=' . $catID . '&pg=' . $lastPage);
                }

                //pagination
                $totalCounts = $grabPhotosCount + $subCatCountResult;

                $lastPage = ceil($totalCounts/$PerPage);

                if ($lastPage < 1)
                {
                    $lastPage = 1;
                }

                $pageNum = (isset($_GET['pg'])) ? trim($_GET['pg']) : 1;
                $pageNum = preg_replace('#[^0-9]#', '', $pageNum);

            }
            else
            {
                throwDBError();
            }

            echo '
';
            print_r($itemList);
            echo '
';

        }
        else
        {
            echo '
Category not found.
';
        }

    }
    else
    {
        throwDBError();
    }
?>

A: You could create a row number variable and then select from that derived table.  Taking a stab at what your table structure might be, something like this could work:
SELECT *
FROM (
  SELECT  p.id,
          p.title,
          sc.title as subcat_title,
          @curRow := @curRow + 1 AS row_number
  FROM    photos p
  INNER JOIN subCats sc on p.subcat = sc.id
  INNER JOIN (SELECT @curRow := 0) r
  ) AS tbl
WHERE row_number>3 AND row_number<=6

Set the start and end paging row counts in the WHERE clause.
Here is a fiddle for the above: http://sqlfiddle.com/#!2/107f7/9/0

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display a math formula in an Android app? My app is supposed to show some engineering formula.
How can I display a formula in my app?

A: Although there is no direct way to show math formula in android TextView,
But you can use MathJaxWebView and use the webview to show formula using it. Visit the link for more infomation on how to do it.

A: *You can use MathJax also but it is slightly heavy. So I propose you to use jqMath.
(jqMath is a JavaScript module that makes it easy to put formatted mathematical expressions in web pages.)
*Download this JavaScript Library here. http://mathscribe.com/author/jqmath.html
There`s a link to download that Library from link called "download jqMath"
*For more Info visit: https://inducesmile.com/android/how-to-display-math-formula-and-equation-in-android-application/
Good Luck!!


text:
Q: JavaScript: Comparing the current value to the previous value drawn from Json I was not sure how to write the question title or what is the correct way to ask for this question.
The goal is, I am currently drawing data from an external Json file that have about 700 or more data. What I want to do is, when looping through these data, for example, data 1, data 2, data 3...so on, I want the current value to be compared to the previous value and if it is greater, lesser, or equal to, then do something
right now, my code is written like this
function myJson() {

    $.getJSON('JsonData.json', function (response) {

        setInterval(function () {
            var TrialCount = response.length;
            updateTrack(X_Data);

            var counter = 0;
            var Info = response[counter];
            var X_Data = Info.X_Json;

            X_Data = X_Data.toFixed(2); // rounds to 2 decimal places

            document.getElementById("DisplayX").innerHTML = X_Data

            counter++;
        }, 500);
    });
};

function updateTrack(X_Data) {
    $('#X').html(X_Data);
        if (current X_Data < previous value){
            document.getElementById("X_Data_img").src = "first image";
        }
        else if (current X_Data > previous value) {
            document.getElementById("X_Data_img").src = "second image";
        }
        else {
            document.getElementById("X_Data_img").src = "third image";
        }
    };

How to put the current X_Data (current'th loop of Json data) to be compared from the previous X_data  (previous'th loop of Json data) ? |
Format of the Json data I have
var X_Json= {
  "data1" : "#",
  "data2" : "#",
  "data3" : "#",
   ..
},
{
  "data1" : "#",
  "data2" : "#",
  "data3" : "#",
   ..
},
{
  "data1" : "#",
  "data2" : "#",
  "data3" : "#",
   ..
},
{
  "data1" : "#",
  "data2" : "#",
  "data3" : "#",
   ..
}

A: Set a var previous_value outside the scope of updateTrack() and set the value of it at the end of updateTrack() with the current X_Data value.
var X_Data = [14,22,53,24,6,6,97];

var previous_value = null;

for (var i = 0; i < X_Data.length; i++) {
  var current_value = X_Data[i];
  if (i > 0) { // some sort of first item check
    if (current_value < previous_value) {
      // set first image
    } else if (current_value > previous_value) {
      // set second image
    } else {
      // set third image
    }
  }
  previous_value = current_value;
}

The loop is just to show you how it would work, imagine each iteration of the loop as a separate function call to updateTrack().
This a general pattern for handling in-array comparisons and hopefully will assist you in reaching your answer.
To help you in the right direction for your code, what you want to do is set counter outside the function and compare response[counter].X_Json to response[counter - 1].X_Json and set the image that way and skip it if the counter is 0. The way you set counter it is being reset each time the function is called.

A: I'm assuming that your JSON looks someething like this.
var myJson = {
  "data1" : "2",
  "data2" : "5",
  "data3" : "43",
   ..
}

If you want to loop through all the properties of an object as if it was an array, then put all the property names inside an array as strings.
var myProperties = Object.keys(myJson);

This will create an array of property names like this
["data1", "data2", "data3"....]

You can loop through myProperties and use the item names to identify properties in your myJson object.
for(var i = 1; i < myProperties.length ; i++) {
   if(myJson[myProperties[i]] < myJson[myProperties[i-1]]) {
       //Do something
   } else if(myJson[myProperties[i]] > myJson[myProperties[i-1]]){
      //Do another thing
   } else {
      //Do something else
   }
}

A: Depending your scene, comparing variables in js loops may be accomplished with html5 data attributes
Here a small example
...inside a loop
if ( $('#somehtmlelement').attr('data-value') !=  getValue() ) {
  console.log("not the same");
}

$('#somehtmlelement').data('value',getIndex()).attr('data-value',getValue());
... loop continues

A: maybe I am misunderstanding but are just trying to loop through your json data and compare the current to previous?
 $.getJSON('myurl', function (data) {

                $.each(data, function (i, item) {
                   if (i > 0 && item.myval < data[i - 1].myval){
                     // do whatever
                    }
                 });
            });


text:
Q: Unable to install juju-gui locally? I'm attempting to setup juju-gui in a VM running Ubuntu 13.10 x64 Server.
I intend to see if it's possible to deploy an openstack "all in one" node, using this method in that particular VM.
I've installed and bootstrapped juju in a local environment :
sudo apt-get install juju-core
sudo apt-get install juju-local
juju switch local
sudo juju bootstrap

Next I've executed the following :
juju deploy juju-gui
juju expose juju-gui
watch juju status

I was expecting to see juju-gui open up some ports and become available via a web-browser but nothing like that happened - why? how do I fix that? I believe I've managed to follow the deployment guides to the letter?
Are there any detailed walkthroughs regarding deploying openstack on 13.10, using juju?

A: The last thing you did "juju watch status" is a bit off.  It should call the "watch" command on "juju status", i.e
watch juju status

(That just runs juju status periodically and shows the results.)
After a while, the juju-gui portion of the status output will show the agent-state as "started" and display a public IP address.
At that point you can open your browser and go to the IP address.  You'll be prompted for a password, which is the 'admin-secret' found in your ~/.juju/environments.yaml under the "local" section.
Hope that helps!

A: Expose doesn't do anything in the local provider. There are no firewalls rules in place like other providers such as ec2. Once you deploy the juju-gui and it's started, you should be able to visit it via the ip address for the lxc machine that juju status shows you.
It is available on port 80 and 443.
If it did not come up to "started" state then please ssh to that machine and grab the log for the unit in /var/log/juju/unit-* and let us know.


text:
Q: git: the following untracked files would be overwritten by checkout I'm on my master branch, when trying to checkout I receive this error:

Currently all those folder and file names are in lower case, not upper case. But git used to ignore the casing until I changed its configuration and now this is some kind of left over. I can force checkout and it will work, but is there a way to "remove them" (these paths) although they don't exist in upper case but in lower case? In other words, how can I let git ignore those upper cased paths from now on?


text:
Q: Invalid < operator Hy! This is my first question on this site. Sorry for my English, if I will make mistakes:(
So, my problem is the following. I have simple class Date.
class Date
{
public:
    Date();
    Date(unsigned short day, unsigned short month, unsigned short year);
    Date(const Date &date);
    unsigned short getDay();
    unsigned short getMonth();
    unsigned short getYear();

    void setDay(unsigned short day);
    void setMonth(unsigned short month);
    void setYear(unsigned short year);

void printOnScreen()const;
friend
    std::ostream& operator<< (std::ostream& out, const Date& date) {
        out << date.day << "." << date.month << "." << date.year;
        return out;
    }

friend
    bool operator<(const Date& a, const Date& b) {
        if (a == b) {
            return false;
        }

        if (a.year < b.year) {
            return true;
        }
        if (a.month < b.month) {
            return true;
        }
        if (a.day < b.day) {
            return true;
        }

        return false;
}

friend
    Date& operator-(Date& a) {
        return a;
    }

friend
    Date operator-(const Date& a, const Date& b) {
        return Date(
            abs(a.day - b.day),
            abs(a.month - b.month),
            abs(a.year - b.year)
            );
    }

friend
    bool operator==(const Date& date1, const Date& date2) {

        return (
            date1.day == date2.day &&
            date1.month == date2.month &&
            date1.year == date2.year
            );
    }

    virtual ~Date();
private:
    friend KeyHasher;

    unsigned short day;
    unsigned short month;
    unsigned short year;
};

In my main function I call sort like in this example, and after it get the error.
auto dates = {
    Date(1, 5, 2016),
    Date(3, 2, 2015),
    Date(3, 3, 2000),
    Date(2, 1, 1991),
    Date(1, 8, 2200),
    Date(1, 8, 2200),
    Date(1, 8, 2020),
    Date(21, 9, 2016)
};

vector<Date> v1(dates);
sort(
    v1.begin(),
    v1.end(),
    less<Date>()
);

What is wrong, I don't understand. Thank you for help.

A: Your operator < is indeed incorrect, use std::tie:
auto as_tuple(const Date& d) {
    return std::tie(d.year, d.month, d.day);
}

bool operator<(const Date& lhs, const Date& rhs) {
    return as_tuple(lhs) < as_tuple(rhs);
}

bool operator == (const Date& lhs, const Date& rhs) {
    return as_tuple(lhs) == as_tuple(rhs);
}

A: Try to change your conditions like:
if (a.year < b.year)
    return true;
else if (a.year > b.year)
    return false;
else // a.year == b.year
{
    if (a.month < b.month)
         return true;
    else if (a.month > b.month)
         return false;
    else // a.month == b.month
    {
        if (a.day < b.day)
            return true;
        else
            return false;
    }
}


text:
Q: Truly modal window possible? Or would I have to do something like create a windows form and host the xaml inside it?  Trying to get as consistent a look and feel as I can.  If I can only do the latter, how do I achieve that?

A: This should be what you want:
var window = new MyWindow();
var helper = new WindowInteropHelper(window);
helper.Owner = this.Handle;
window.ShowDialog();

This is the key to ensuring correct behaviour upon minimise/restore. See this blog post for more information about the method.
(If this isn't quite what you need, perhaps you could define "truly modal".)

A: You can create custom dialog boxes, and they're modal. You can host a WPF Window within it and define buttons as modal closing buttons. That seems to be the best way to do a modal window, IMO.


text:
Q: Any issues with disabling local DNS Cache on Ubuntu Server 18.04 or 20.04 or 22.04 My Ubuntu 18.04 server is used to create websites and initiate SSL's via an Admin panel. The issue is that when I initiate the SSL I like to have the server check the DNS record, but since the client just changed the record on their Registrar the DNS hasn't propagated to my server yet. This is not a big deal as instead I now just ping 'https://dns.google.com/resolve' to get that info as it seems to not retain any cache as long.
However, another issue is that my server also checks the websites uptime, but since the client just changed the record on their Registrar the DNS hasn't propagated to my server yet. So then I can just ping the domain until it has propagated.
A manual solution is for me to just login and run sudo systemd-resolve --flush-caches but I obviously don't want to do that all the time.
So can I just run a cronjob to clear the dns cache every minute or 5 minutes?
Or maybe just disable DNS Cache all together?
What kind of issues will I run into doing either one of these?
What are the main disadvantages will I get with either one of these?
I am assuming my uptime checks, which are run every 5 minutes, will take slightly longer now, but I am assuming that is just milliseconds.
What type of issues will I have with apt, ntp, or other internal systems if I do one of these?
Thanks


text:
Q: Create thumbnail from asset - Azure Media Services Recently we have some problmes with news Media Services created. We have seen that "Azure Media Encoder" is depreciated and now we use "Media Encoder Standard". Thus, we can upload videos again, but we can´t create thumbnails. Do you can help us? How we can get a thumbnail from a asset?
This is error that show in administration page of Azure:
An error has occurred. Stage: ParsePreset. Code: System.InvalidOperationException.`

Microsoft.Cloud.Media.Encoding.PresetException: The XML is invalid or malformed. --->
System.InvalidOperationException: There is an error in XML document (1, 2). --->
System.InvalidOperationException: <Thumbnail xmlns=''> was not expected.">An error has occurred. Stage: ParsePreset. Code: System.InvalidOperationException.

Microsoft.Cloud.Media.Encoding.PresetException: The XML is invalid or malformed. --->
System.InvalidOperationException: There is an error in XML document (1, 2). --->
System.InvalidOperationException: <Thumbnail xmlns=''> was not expected.

Our code:
    public void CreateThumbnails(string idAssetVideo, int iSegundo, string sPath)
    {
        if (string.IsNullOrEmpty(idAssetVideo)) throw new Excepcion("El idAssetVideo no puede ser nulo. Póngase en contacto con soporte.");

        string sTime = Utilidades.GetDuracionLabelFromSegundos(iSegundo);

        IAsset asset = _context.Assets.Where(a => a.Id == idAssetVideo).SingleOrDefault();
        if (asset == null) throw new Excepcion("No existe ningún Asset con el Id indicado. Póngase en contacto con soporte.");

        // Declare a new job.
        IJob job = _context.Jobs.Create("My Thumbnail job");

        // Get a media processor reference, and pass to it the name of the
        // processor to use for the specific task.
        IMediaProcessor processor = UtilsAzure.GetLatestMediaProcessorByName("Media Encoder Standard", _context);

        //Configuración para generar el Thumbnail
        string configThumbnails = @"<Thumbnail Size='50%,*' Type='Jpeg' Filename='{OriginalFilename}_{Size}_{ThumbnailTime}_{ThumbnailIndex}_{Date}_{Time}.{DefaultExtension}'>
                                            <Time Value='0:0:0' Step='" + sTime + "'/></Thumbnail>";
        //string configThumbnails = "<?xml version='1.0' encoding='UTF-8'?><Thumbnail Size='200,*' Type='Jpeg' JpegQuality='90' Filename='" + sTime + ".jpeg'><Time Value='" + sTime + "'/></Thumbnail>";

        ITask task = job.Tasks.AddNew("My thumbnail task",
            processor,
            configThumbnails,
            TaskOptions.ProtectedConfiguration);

        // Specify the input asset to be encoded.
        task.InputAssets.Add(asset);
        // Add an output asset to contain the results of the job.
        task.OutputAssets.AddNew("Output asset",
            AssetCreationOptions.None);

        // Use the following event handler to check job progress.
        job.StateChanged += new
                EventHandler<JobStateChangedEventArgs>(UtilsAzure.StateChanged);

        // Launch the job.
        job.Submit();

        // Check job execution and wait for job to finish.
        Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);
        progressJobTask.Wait();

        // If job state is Error, the event handling
        // method for job progress should log errors.  Here we check
        // for error state and exit if needed.
        if (job.State == JobState.Error)
        {
            throw new Exception("Exiting method due to job error.");
        }

        List<IAssetFile> lAF = job.OutputMediaAssets[0].AssetFiles.ToList();

        //Valido
        if (lAF == null || !lAF.Any()) throw new Excepcion("El trabajo azure no devolvió resultados");
        if (lAF.Where(x => x.Name.EndsWith(".jpg")).FirstOrDefault() == null) throw new Excepcion("El trabajo azure no contiene ningún archivo con extensión JPG");
        if (!Directory.GetParent(sPath).Exists) throw new Excepcion("No existe la carpeta donde guardar el thumbnail de manera provisional");

        lAF.Where(x => x.Name.EndsWith(".jpg")).FirstOrDefault().Download(sPath);
    }

A: Looks to me like you are using the old deprecated Preset schema for Thumbnails.
Please review the new Presets for Media Encoder Standard features in this article:
https://learn.microsoft.com/en-us/azure/media-services/media-services-advanced-encoding-with-mes#a-idthumbnailsagenerate-thumbnails
Replace your configThumbnails with the newer JSON version of the Thumbnail preset.
Hope that helps!
-JD

A: Thanks! It´s works! Really, we need only create one image. Thus, we have simplified XML:
<?xml version='1.0' encoding='utf-16'?>
<Preset xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' Version='1.0' xmlns='http://www.windowsazure.com/media/encoding/Preset/2014/03'>
  <Encoding>
    <JpgImage Start='00:01:16' Step='00:00:01' Range='00:00:01'>
      <JpgLayers>
        <JpgLayer>
          <Width>640</Width>
          <Height>360</Height>
          <Quality>90</Quality>
        </JpgLayer>
      </JpgLayers>
    </JpgImage>
  </Encoding>
  <Outputs>
    <Output FileName='{Basename}_{Index}{Extension}'>
      <JpgFormat />
    </Output>
  </Outputs>
</Preset>


text:
Q: Create a Kubernetes Persistent Volume on GKE connected to an external NFS server on GCE I have a NFS server running on a VM in GCE. The NFS server /etc/exports file is already configured to allow mounting by the K8s cluster. I attempted to create a Persistent Volume (PV) and Persistent Volume Claim (PVC) and I added spec.containers.volumeMounts and spec.volumes entries. Basically, Google provisions a new disk instead of connecting to the NFS server.
In the deployments file I have added:
          volumeMounts:
            - name: nfs-pvc-data
              mountPath: "/mnt/nfs"
      volumes:
        - name: nfs-pvc-data
          persistentVolumeClaim:
            claimName: nfs-pvc

nfs-pv.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-pv
  namespace: comms
  labels:
    volume: nfs-pv
spec:
  capacity:
    storage: 10G
  #volumeMode: Filesystem
  accessModes:
    - ReadOnlyMany
  mountOptions:
    - hard
    - nfsvers=4.2
  nfs:
    path: /
    server: 10.xxx.xx.xx
    readOnly: false

nfs-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nfs-pvc
  namespace: comms
#spec: # The PVC is stuck on ready as long as spec.selector exists in the yaml
  #selector:
    #matchLabels:
      #volume: nfs-pv
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1G

A: I was able to mount the NFS server external to the Kubernetes cluster using the following PV and PVC YAML.
apiVersion: v1
kind: PersistentVolume
metadata:
  name: gce-nfs
  namespace: comms
spec:
  capacity:
    storage: 1Mi
  accessModes:
    - ReadWriteMany
  nfs:
    server: 10.xxx.xxx.xxx
    path: "/"

---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: gce-nfs
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: ""
  resources:
    requests:
      storage: 1Mi

Then in the deployment YAML I added the following to the containers section:
      volumeMounts:
        - name: nfs-pvc-data
          mountPath: "/mnt/nfs"
  volumes:
    - name: nfs-pvc-data
      persistentVolumeClaim:
        claimName: gce-nfs

The pod/container will boot connected to the external NFS server.


text:
Q: How to select a button using css select need help with css select syntax to select the button.
Please see screenshot.

A: One of the cssSelector patterns is:
tagName[attribute='value']...[attribute='value']

To select it's immediate child,  you could use '>' symbol (You might know this).
So, for your case one of the possible selectors is:
button[class='md-primary md-button ng-scope md-ink-ripple'] > span

There are several possible ways you can do this. You may go through the page for more:
http://www.guru99.com/locators-in-selenium-ide.html

A: You can use below cssSelector to locate Drug and Alcohol button :-
md-grid-list[md-cols='2'] button.md-primary.md-button[ng-click*='openCategory']

But I don't think this cssSelector could be unique, you can locate this button using their text which could be unique using xpath as below :-
.//button[normalize-space(.) = 'Drug and Alcohol']

Or
.//button[. = 'Drug and Alcohol]

Or
.//button[span[text() = 'Drug and Alcohol']]


text:
Q: What is the density of $(X,X)$ It might be stupid question, but:
Let $X$ be a RV with density $f(x)$. What is the "joint" density of random vector $(X,X)$?

A: So you know that $P(X\leq x) = \int_{-\infty}^x f(y)dy$, and you want to find $P(X\leq x_1,X\leq x_2)$.
But this probability is certainly dictated by whichever of $x_1$ and $x_2$ is the smallest, so
$$P(X\leq x_1,X\leq x_2) = P(X\leq \min(x_1,x_2))=\int_{-\infty}^{\min(x_1,x_2)}f(y)dy.$$
So you see that $(X,X)$ is a degenerate random vector in the sense that its distribution is not two-dimensional. This also means that there is no joint density of $(X,X)$ in the usual sense. The above gives you a rule for finding the distribution of $(X,X)$ by using the single density of the random variable $X$.


text:
Q: Using package-info.java for JAXB I am unable to build my application because of the syntax in the package-info.java file. The sample below is just a demo but any sample I try gives me the syntax errors I would expect since I'm placing code before the package and imports. How exactly are you suppose to get this to work if the syntax below is what is actually suppose to go into package-info.java?
Update: Another way to ask this question is, shouldn't the annotation go at the bottom? My compiler, IntelliJ, certainly things so...
@XmlSchema(
    elementFormDefault=XmlNsForm.QUALIFIED,
    namespace="http://www.example.com/FOO",
    xmlns={@XmlNs(prefix="bar",
                  namespaceURI="http://www.example.com/BAR")}
)
package blog.prefix;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

A: The problem was my IDE. For this to work in IntelliJ you must disable "Optimize Imports".

A: It's working fine in IntellIJ 2018 version :)


text:
Q: No 'Access-Control-Allow-Origin' header is present on the requested resource I'm having a struggle met CORS, after many attempts. I have tried the following; @CrossOrigin() in the controllers, added .cors() in filterchain, added a corsconfiurationsource in my securityconfig. Also if I dont write the whole url at the fetch function in React it goes to localhost:3000 instead of :8080 even though proxy is setup in package.json and works with other Get methods.
And now I am getting the following error when fetching a post method from React:
'Access to fetch at 'http://localhost:8080/like/liked' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.'
So this is how my code looks like right now(Spring as backend & React as frontend) :
SecurityConfig.java
@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authz) -> authz
                        .antMatchers("/**/*.{js,html,css}").permitAll()
                        .antMatchers("/", "/user", "/").permitAll()
                        .anyRequest().authenticated()

                )
                .csrf((csrf) -> csrf
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                )
                .cors()
                .and()
                .oauth2Login();
        return http.build();
    }

    @Bean
    public RequestCache refererRequestCache() {
        return new HttpSessionRequestCache() {
            @Override
            public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
                String referrer = request.getHeader("referer");
                if (referrer != null) {
                    request.getSession().setAttribute("SPRING_SECURITY_SAVED_REQUEST",
                            new SimpleSavedRequest(referrer));
                }
            }
        };
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
/*
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
*/
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        //the below three lines will add the relevant CORS response headers
            configuration.addAllowedOrigin("*");
            configuration.addAllowedHeader("*");
            configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

LikedController
@RestController
@RequestMapping("/like")
public class LikedController {
    @Autowired
    LikedService likedService = new LikedService();
    @Autowired
    NuserService nuserService = new NuserService();

    @PostMapping("/liked")
    public ResponseEntity<?> AddLikeToUser(@AuthenticationPrincipal OAuth2User ouser, @RequestBody Liked like)
    {
        if(like == null || ouser == null)
        {
            return ResponseEntity.ok().body("Something went wrong.");
        }
        else
        {
            Nuser user = nuserService.getuserbyemail(ouser.getAttribute("email"));
            like.setUser(user);
            like.setLiked_date(LocalDate.now());
            likedService.addLike(like);
            return ResponseEntity.ok().body("Person has been successfully liked");

        }
    }

Date.js where I fetch the post method.
const Date = () => {
    const globalcontext = useContext(AppContext);
    const [cookies] = useCookies(['XRSF-TOKEN']);
    const [loading, setloading] = useState(false);
    const [error, seterror] = useState(false);
    const [users, setusers] = useState([]);

    useEffect(() => {
        setloading(true);
        fetch("/user/allotherusers", {credentials: "include"})
            .then(response => response.text())
            .then(body => {
                if (body === "") {
                    return <Navigate to="/"/>
                } else {
                    setusers(JSON.parse(body));
                }
                setloading(false);
            });
    }, [])

    const userlist = users.map(user => {
        return (

 {user.firstname}

                <button onClick={() => like(user, false)}>Like</button>

        )
    });

    const like =  async (likeduser, superlike) => {
        const likemodel =
            {
                likeduser: likeduser,
                superlike: superlike

            }

         await fetch("http://localhost:8080/like/liked", {
            method: "POST",
            headers: {
                'X-XSRF-TOKEN': cookies['XRSF-TOKEN'],
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
             credentials: 'include',
             body: JSON.stringify(likemodel)

        });
    };

    return (

            {userlist}

    );

}
export default Date;

Package.json
"proxy": "http://localhost:8080",


text:
Q: Secure Communication Between Tomcat Servers Note: this question was sort of asked here, but not answered.
I need to communicate securely between two Tomcat servers running in two different environments. I have control of both servers.
I would like to do this through a simple REST call from Server-B to Server-A.
On the server I am communicating to, Server-A, I can easily set up HTTPS with a self-signed certificate. If I import this certificate into the Java Keystore on Server-B, I can make a trusted HTTPS Rest call from my Java code on Server-B.
Good instructions for doing this can be found here:
https://blog.10pines.com/2017/09/25/how-to-communicate-via-https-between-two-tomcat-servers-using-a-self-signed-certificate/
I would also like to add a confirmation that the Rest call to Server-A is certainly coming from Server-B and the message has integrity.
My plan is to generate a self-signed certificate on Server-B and  import this certificate into the Java Keystore on Server-A. Then for any REST call from Server-B I will first generate an SHA-512 hash of the message and sign the hash with the private key associated with the Server-B certificate. When Server-A receives the message, the SHA-512 hash will be recalculated and checked for accuracy of the hash (no message tampering). I will then check the signature of the Hash against the public key of the certificate from Server-B.
For a little bit of extra paranoia I may encrypt the REST message with the public key of the certificate from Server-A; for short messages this should be fine (no need for Symmetric encryption).
Does this seem like a good plan? Does Tomcat have a simpler mechanism for doing this?
The Java Messaging API seems a little "heavy" for this use case.


text:
Q: Jquery/Ajax not sending serialization data properly I am developing a online exam module in which user will create question quantity. after that it will submit the form .... so we are sending the form data using form.serialize but in controller it is showing only last question input boxes data i have mentioned the code so when user click on submit it showing only question 2 data in controller. please how to retrieve all question data and store in database

       <input type="text" name="ques" />
     Question 1

  <input type="text" name="opta" />
  Option A

    <input type="radio" name="radio" class="mt-5">

  <input type="text" name="optb" />
  Option B

    <input type="radio" name="radio" class="mt-5">

  <input type="text" name="optc" />
  Option C

    <input type="radio" name="radio" class="mt-5">

  <input type="text" name="optd" />
  Option D

    <input type="radio" name="radio" class="mt-5">

       <input type="text" name="ques" />
     Question 2

  <input type="text" name="opta" />
  Option A

    <input type="radio" name="radio" class="mt-5">

  <input type="text" name="optb" />
  Option B

    <input type="radio" name="radio" class="mt-5">

  <input type="text" name="optc" />
  Option C

    <input type="radio" name="radio" class="mt-5">

  <input type="text" name="optd" />
  Option D

    <input type="radio" name="radio" class="mt-5">

    <button class="btn btn-primary ad_qs" type="button">Submit</button>
   <button class="btn btn-secondary" type="reset">Cancel</button>

Jquery Code
       $(".ad_qs").click(function(){

                var qs=$("#eq_form").serialize();
                alert(qs);

                $.ajax({
               headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        url:'/add-ques',
                        type:'post',
                        data:qs,
                        success:function(data){

                            if(data.success){
                                //alert("done");
                                $(".scs_msg").fadeIn();
                                $(".eq_form").trigger('reset');
                            }

                        },
                        error: function (data) {
                        console.log('Error:', data);
                         }

                    });

Controller Code
           public function addQues(Request $request){

    print_r($request->all());
}

Response
       Array ( [_token] => ocEOwNjmhMEOLLPOuxuGUVLO8FItrqyAEYNDXSIA [ques] => question 2 data [opta] => ab [optb] => bc [optc] => cd [optd] => de )

A: Both of your questions input name is same. Both are using ques that's why 2nd question is overriding 1st one.
You must have different names and pass two data to the ajax.


text:
Q: Changing Coordinate axes type in Paraview How to change in Paraview, the co-ordinate axes from default to left-handed co-ordinates from This to This
I am reading in a vtk file written in legacy format for rectilinear grid
Thanks for the help

A: ParaView does not support left-handed coordinates. The best you can do is convert your left handed coordinates to right-handed coordinates to make them displayed correctly. The easiest way to do so is probably to use the Transform filter and scale by -1 along one axis.
Unfortunately, you cannot change the labels of the orientation axes (in the lower right corner) to be labeled as left-handed. However, if you are using the Axes Grid, you can changes the labels of that to indicate left-handed coordinates.


text:
Q: Repeated "checking for a bsd-compatible install ..." step running ./configure in docker container with debian jessie I am encountering problems running a ./configure script inside a debian:jesse docker container. The script works when I run it interactively on an ubuntu instance. However when I run it as part of a docker build script I just get the following
checking for a BSD-compatible install...
checking for a BSD-compatible install...
checking for a BSD-compatible install...
checking for a BSD-compatible install...
checking for a BSD-compatible install...

Repeating endlessly until the container runs out of space. Do you know what could be causing this?
Here is the docker file
FROM debian:jessie
MAINTAINER Michael Barton, mail@...
RUN apt-get update -y
RUN apt-get install -y wget
RUN wget --quiet http://hku-idba.googlecode.com/files/idba-1.1.1.tar.gz -O /tmp/idba-1.1.1.tar.gz

RUN apt-get install -y gcc build-essential make sed autoconf

ADD install /usr/local/bin/
RUN /usr/local/bin/install

ADD run /usr/local/bin/
ENTRYPOINT ["/usr/local/bin/run"]

Here is the install script
#!/bin/bash

set -o nounset

VERSION='1.1.1'
DIR="idba-${VERSION}"

TMP=$(mktemp -d)

cd ${TMP}
tar xzf "/tmp/${DIR}.tar.gz"
cd ${DIR}

# Required to allow for longer read lengths
sed --in-place 's/kMaxShortSequence = 128;/kMaxShortSequence = 1024;/' src/sequence/short_sequence.h

./configure
make

mv bin /usr/local/idba


text:
Q: String#replace won't work in my method As I get an HTML file containing some wild chars like ⋍ or 𖫻, I want to replace them with a bullet. So I wrote this method :
public String replaceAmps(String initial)
{
    // This list will contain all the &amps; to replace.
    ArrayList<String> amps = new ArrayList<String>();
    String res = initial;
    int index = initial.indexOf("&");
    // Get all the indexes of &amp.
    while (index >= 0)
    {
        StringBuilder stb = new StringBuilder("&");
        // Create a String until the next ";", for example &#1091;<- this one
        for(int i = index+5 ; initial.charAt(i) != ';' ; i++) stb.append(initial.charAt(i));
        stb.append(";");
        // Add the amp if needed in the list.
        if(!amps.contains(stb.toString())) amps.add(stb.toString());
        index = initial.indexOf("&", index + 1);
    }
    // Replace the Strings from the list with a bullet.
    for(String s : amps) res.replace(s, "•");
    return res;
}

I correctly get all the amps in my list, but the replacing doesn't work. Why? Thanks for your help.

A: Strings are immutable; the replace method returns a new String as the result of the replacement and does not modify res.  Try
for(String s : amps) res = res.replace(s, "•");


text:
Q: Wordpress - Show all button in categories list I have this following page: http://webserver-meetandengage-com.m11e.net/insights/  and I'm using this code to list the categories in the yellow bar at the top:

                <?php wp_list_categories( array(
                    'orderby'            => 'id',
                    'show_count'         => false,
                    'title_li' => false
                ) ); ?>

I would like to have an ALL button at the start of the list that will show all categories again.
Is there an array option I can add to it and set it to True? or is there more to it? Any help would be greatly appriciated :)

A: Ok this was simply fixed by me using the show_option_all argument in the array like so:

                <?php wp_list_categories( array(
                    'orderby'            => 'id',
                    'show_count'         => false,
                    'show_option_all'     => 'Show All',
                    'title_li' => false
                ) ); ?>

This created a button at the start of my list called: Show All.


text:
Q: AngularJS || Ignore ngBlur on element blur when executing other function that does blur While developing I have encountered an issue of firing blur two times, when i need to fire it only once.
Both ng-blur and ng-enter final actions are to make request to database, in our case 2 requests are done, when only 1 needed - or from ng-blur or from ng-enter. The problem is that ng-enter behaviour are causing to lose focus on element, which is connected to ng-blur.
Here are my two questions:

*

*Is there a way to prevent Angularjs to fire an ng-blur on todo div
when ng-enter is executed ?

*If there is no solution for first question, I really hope that there
is, then what options do I have ?
Below you can see parts of code that are responsible for my issue.
template.html

                        {{todo.title}}

controller.js
app.controller('homeController', function($scope, Todos, $state){

    $scope.editTodo = function($event) {
        var text = angular.element(angular.element(event.currentTarget).find('span')[0]);
        $event.preventDefault();
        text.attr("contenteditable", "true");
    }

    $scope.stopEditTodo = function($index, $event, todo) {
        angular.element(event.currentTarget).removeAttr('contenteditable');
    }
});

directive.js
app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

Thanks for your time!

A: Since ng-blur triggers an $evalAsync, there's not really anything you can do in ng-enter to stop it from happening.
On the other hand, you have a few options:
Option #1 - check if the content was still editable when stopEditTodo fired
var target = angular.element(event.target);
if (target.attr('contenteditable')) {
    target.removeAttr('contenteditable');
    // fire request
}

Note that all of this is better done via a completely custom directive to encapsulate the direct DOM manipulation.
See plunker for an example.
Option #2 - debounce
This is much more "hacky" but it usually does the trick - use a debounce function (i.e. Lodash) to make your handler fire only once per every X milliseconds. That is, something like this:
$scope.stopEditTodo = _.debounce(function($index, $event, todo) {
    angular.element(event.currentTarget).removeAttr('contenteditable');
    // fire request
}, 300);

This should do the trick for most usage scenarios.
Side note: it seems that you should be using event.target instead of event.currentTarget, as the latter will always refer to the parent div instead of the actual list item (which you want). Alternatively, you can move ng-enter to the list item instead of the parent.


text:
Q: Getting access to GDrive as app-specific user I am working with Google Drive from an application-specific account. It would be great to be able to get access to the GDrive UI logged with this account. Is this possible?

A: No, it is not possible to access the Google Drive web user interface of a service account.


text:
Q: Admob Ad only shows after resuming game I have a game where I'm using a surfaceView and no XML layout.
The code in my main activity:
RelativeLayout layout = new RelativeLayout(this);
    adView = new AdView(this);
    adView.setAdSize(AdSize.BANNER);
    // test ad ID
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); //test ad ID anyone can use
    AdRequest adRequest = new AdRequest.Builder().addTestDevice(
            "xxxxxx").build();
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    adView.setLayoutParams(lp);
    adView.loadAd(adRequest);
    layout.addView(renderView);
    layout.addView(adView);
    setContentView(layout);

What happens when I run the game is, I enter the main menu screen and there is no ad on display. However, if I press the android button to leave the app but then return to it, the ad appears and shows at the bottom of the main menu screen.
Any ideas what's going on? Been working on this for some hours no but to no avail, any help would be appreciated.

A: Try moving adView.loadAd(adRequest); until after setContentView(layout);


text:
Q: C# new object but instead of copying an object, but referencing? I have a class say ClassA with a string array inside class.
In my code I have ClassA as an object, then I want to create another new ClassA object, but it should copy the original object to the new class and do whatever it is supposed to do.
But strangely, when I declare that new object, whatever changed in the new object affects the original object.
Is there any reason why I am getting such behaviour?

A: I'm sure it is because you are just setting another reference to the one string array in the new object.  If you want a separate string array you need to create a constructor that creates a new string array and copies the strings over.

A: You can make a constructor overload that takes a new ClassA object and copies it's parameters.
public class ClassA
{
    public String SomeParam { get; set; }
    public ClassA(ClassA myoldobject)
    {
           //Logic for initializing new object.
           this.SomeParam = myoldobject.SomeParam;
    }
    public ClassA(String someparam)
    {
           this.SomeParam = someparam;
    }
}

This enables you to say
ClassA one = new ClassA("Test");
ClassA two = new ClassA(one);

A: It sounds like you're just doing this to copy it:
ClassA obj2 = obj1;

In this case then changes to obj2 would indeed be reflected in obj1 because the objects that you're using are just pointers to the same location in the memory heap.  You're not actually copying it, you're just making another reference to it.
Take a look at the ICloneable interface here.  You'd want something like this:
public class ClassA : ICloneable
{
    public string myString { get; set; }
    public object Clone()
    {
        var obj = new ClassA();
        obj.myString = myString;
        return myObj;
    }
}

Then you'd call it like this:
ClassA obj2 = (ClassA)obj1.Clone();

Keep in mind that this isn't very type-safe, however.  That cast is a bit messy (and, honestly, I haven't tried it, so it might even be problematic).  I don't think .NET has introduced a generic ICloneable yet.  But it shouldn't be too hard to write one.  Something like:
public interface ICloneable<T>
{
    public T Clone();
}
public class ClassA : ICloneable<ClassA>
{
    public string myString { get; set; }
    public ClassA Clone()
    {
        var obj = new ClassA();
        obj.myString = myString;
        return myObj;
    }
}

This should be callable like this:
ClassA obj2 = obj1.Clone<ClassA>();

or possibly even (at least with a little tweaking):
ClassA obj2 = obj1.Clone();

An additional benefit to making a generic interface like this is that any given class can be "cloneable" to other types, not just itself.  You can implement as many ICloneable<T> interfaces as you want on a single class.  So you could have something like:
SomeOtherClass obj3 = obj1.Clone<SomeOtherClass>();

This is all off the top of my head and I don't have a compiler handy to test it, but you get the idea.

A: This is because class - is a reference type and you are trying to get the behaviour of a value type. See deeper explanation here. Also it is greatly explained in CLR via C# book by J. Richter.
If you want to copy a reference type, you might need to implement an IClonable interface and call Clone for that.

A: It seems that you've assigned the first object to the second ..
To copy an existed object you have to assign all of its properties values to the new object, not to assign the whole object because this way you create another reference to the same object.
To create a copy of the first instance of ClassA, try the following:
ClassA = secondObject = new ClassA();
secondObject.Property1 = firstObject.Property1;
secondObject.Property2 = firstObject.Property2;
............


text:
Q: Any hardware/software routers that support Full Cone NAT? i'm trying to get Teredo to function on my machine.
Most routers, it seems, refuse to forward packets from any host other than the one i specifically connected to first. Teredo requires full Cone NAT in order to function.
Does any router, hardware or software, allow full cone NAT?
Is this an oversight by the designers of Teredo that nobody, in practice, can use it?

i've tried

*

*m0n0wall

*pfsense

*D-Link

*Linksys

*SMC

A: Some routers have a "gaming mode" that will turn on full cone NAT

A: I've never had Teredo fail behind any NAT, even dodgy old Checkpoint.
I don't have much more info then that as all the Linux NAT's I use now have 6to4 enabled and advertised giving native IPv6 to clients.

A: According to this post, in a 1-1 scenario maybe SNAT and DNAT will be sufficient in netfilter to make a full cone nat.

A: you can use Wive-NG firmware with supported router, or other - DD/Opeb-WRT. It's fully customized & supports NAT.

A: I had a similar problem with 3cx PBX it insisted on full cone NAT so I used a Draytek router. Worked a treat


text:
Q: Joint (close to uniform) distribution in finite fields This is perhaps a simple fact but I am struggling to prove it.
If A, B are distributed over some finite field $\mathbb{F}$, such that $aA + bB$ is $\epsilon$-close to uniform in $\mathbb{F}$ for every $a, b \in \mathbb{F}$ such that they are not both $0$. Then the random variable $(A,B)$ has joint distribution $\epsilon |\mathbb{F}|^2$-close to uniform in $\mathbb{F} \times \mathbb{F}$.
PS:  By $\epsilon$-close to uniform distribution, I mean the statistical distance from the uniform distribution is at most $\epsilon$.

A: I think the below is correct; it hasn't been very thoroughly checked.  One moral seems to be that this question is nicer in the $L^2$ distance than the $L^1$ distance (because the proof uses Fourier analysis); but I think I can deduce something like your $L^1$ result at the end.
Write $k$ for the cardinality of $\mathbb{F}$.  Let $F : \mathbb{F}^2 \rightarrow \mathbb{R}$ be the law of $(A, B)$, minus the uniform distribution; i.e. $F(x, y) = \mathbb{P}(A = x, B = y) - 1/k^2$.
For $a, b \in \mathbb{F}$ define $f_{a b}(r) = \sum_{x, y \in \mathbb{F}} F(x, y) 1\lbrace{a x + b y = r\rbrace}$.  Alternatively, this is equivalent to $f_{a b}(r) = \mathbb{P}(a A + b B = r) - 1/k$.
So, as I understand it your hypothesis is that $\|f_{a b}\|_1 \le \varepsilon$ for all $(a, b) \ne (0, 0)$, and you want to conclude a bound on $\|F\|_1$, where I use the counting measure on $\mathbb{F}$ and $\mathbb{F}^2$ to define the $L^1$ norm.
My approach is to apply Fourier analysis to $F$ and $f_{a b}$; so it will be convenient to immediately replace the $L^1$ estimate on $f_{a b}$ with the weaker estimate $\|f_{a b}\|_2 \le \varepsilon$ (as $\|\cdot\|_1 \ge \|\cdot\|_2$ wrt the counting measure).
Fix $\chi$ a non-trivial character of $\mathbb{F}$.  Then $\chi_r(x) = \chi(r x)$ ranges over all the characters of $\mathbb{F}$ as $r$ ranges over $\mathbb{F}$, and so the Fourier transform of $f_{a b}$ is
$$\widehat{f_{a b}}(r) = \sum_{s \in \mathbb{F}} f_{a b}(s) \chi_r(-s) = \sum_{x, y} F(x, y) \chi_r(-(a x + b y))$$
The characters on $\mathbb{F}^2$ are $\chi_{u, v}(x,y) = \chi(u x + v y)$, so we deduce
$$\widehat{f_{a b}}(r) = \sum_{x, y} F(x, y) \chi_{a r, b r}(-(x, y)) = \widehat{F}(a r, b r) $$
By Parseval's identity, we get that $\frac{1}{k} \sum_r |\widehat{f_{a b}}(r)|^2 \le \varepsilon^2$ for every $(a, b) \ne (0, 0)$.  We remark that $\widehat{F}(0, 0) = \sum_{x, y} F(x, y) = 0$.  Summing over all possible $a, b$ and double-counting, we get that
$$ \sum_{a, b} \sum_r |\widehat{F}(a r, b r)|^2 = (k - 1) \sum_{u, v} |\widehat{F}(u, v)|^2  \le k^3 \varepsilon^2$$
as each non-zero $(u, v)$ is counted once for each non-zero $r$, and we can ignore the zero terms.  By another application of Parseval,
$$ \sum_{x, y} |F(x, y)|^2 = \frac{1}{k^2} \sum_{u, v} |\widehat{F}(u, v)|^2 \le \frac{k \varepsilon^2}{k - 1} $$
So, $\|F\|_2 \le \varepsilon \sqrt{\frac{k}{k-1}}$ : this is the $L^2$ result.  Applying Cauchy-Schwarz we get something like
$$ \|F\|_1 \le k \|F\|_2 \le k \varepsilon \sqrt{\frac{k}{k - 1}} $$
which (even after Kevin Costello's correction below) means this result is stronger than you asked for by a factor $\sqrt{k (k - 1)}$, meaning I'm still slightly suspicious of the proof.


text:
Q: Append values of different variables I am trying to append values of different variable
Eg:
p1=100
j=1

and
echo $p1
100
echo $j
1

but I append both the value I need out put as
echo $p$j
100

that means instead of 1, I will give $j which has the same value, is there any other option?
Thanks

A: You can use ${!var} to refer to the value of the variable var:
$ var="p"$j
$ echo $var
p1
$ echo ${!var}
100


text:
Q: Ionic 3 - Ion-Item Clickable Ao utilizar a diretiva ION-ITEM dentro de ION-LIST, não é possível clicar em nenhum elemento que esteja dentro, ex.: um campo de text (input), quando testamos com o emulador iOS no Chrome.
<ion-list class="list-form">
  <ion-item tappable>
    <ion-label floating>
      <ion-icon name="mail" item-start class="text-white"></ion-icon>
      Email
    </ion-label>
    <ion-input type="email" formControlName="email"></ion-input>
  </ion-item>

  <ion-item>
    <ion-label floating>
      <ion-icon name="lock" item-start class="text-white"></ion-icon>
      Senha
    </ion-label>
    <ion-input type="password" formControlName="password"></ion-input>
  </ion-item>
</ion-list>

A: Tente usar ionFocus em vez de click.
<ion-input type="email" formControlName="email" (ionFocus)="doSomething()"></ion-input>

Tem várias issues abertas sobre esse problema, creio que possa ser resolvido em uma versão futura. O problema não é o item e sim o input dentro do mesmo.


text:
Q: overload for '\*=' that accepts CGFloat I'm studying Swift and trying to make some very simple application. I met a thing that I can't understand:
When I write
var point = CGPoint(x: 0.6, y: 0.6)
let size = CGSize(width: 15, height: 25)
point.x *= size.width
point.y *= size.height

compiler thinks that's all right.
But if I write the same in the extension
extension CGPoint {
    func scale(bySize size: CGSize) {
        self.x *= size.width
        self.y *= size.height
    }
}

I have an error Could not find an overload for '*=' that accepts the supplied arguments on each line in the function.
Could anybody explain what does it mean and what the difference?
point and size are the same in both cases, why in first case the *= operator exists but in the second one it does not?

A: mutating func scale(bySize size: CGSize) {
    self.x = self.x * size.width
    self.y *= size.height
}

you have to state that the function want to mutate the state of a "by value" struct.

"Structures and enumerations are value types. ...

if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. ..."
Auszug aus: Apple Inc. "The Swift Programming Language." iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329

A: You need to add the keyword mutating into your implementation:
extension CGPoint {
    mutating func scale(bySize size: CGSize) {
        self.x *= size.width
        self.y *= size.height
    }
}

You can find this in the docs here:

Instance methods added with an extension can also modify (or mutate)
  the instance itself. Structure and enumeration methods that modify
  self or its properties must mark the instance method as mutating, just
  like mutating methods from an original implementation.

Then they provide this example:
extension Int {
    mutating func square() {
        self = self * self
    }
}
var someInt = 3
someInt.square()
// someInt is now 9


text:
Q: Select query too slow even though I'm using an index I'm not sure if I'm doing something wrong here but I have a query running on a table with millions of rows.
The query is something like this:
select *
  from    dbo.table with (index (index_1), nolock)
          where   col1 = 15464
                  and col2 not in ('X', 'U')
                  and col3 is null
                  and col4 = 'E'

Index looks like this:
CREATE NONCLUSTERED INDEX [index_1] ON [dbo].[table] ([col1], [col2], [col3], [col4]) WITH (FILLFACTOR=90) ON [PRIMARY]
GO

This select still takes over a minute to run. What am I missing?

A: For this query:
select *
from table
where col1 = 15464 and
      col2 not in ('X', 'U') and
      col3 is null and
      col4 = 'E';

The best index is table(col1, col4, col3, col2).  The query should use the index automatically, without a hint.
When choosing an index based on a where clause, you should put the equality conditions in first -- followed by one column with an inequality.  For the purposes of indexing, in and not in are inequality conditions in general.
Also, if you mix data types, then sometimes indexes are not used.  So, this assumes that col1 is numeric.


text:
Q: In Java, when should I use an abstract method in an interface? I have the following interface in Java
public interface IFoo
{
    public abstract void foo();
    public void bar();
}

What is the difference between foo() and bar()?
When should I use abstract?
Both seem to accomplish what I want unless I'm missing something subtle?
Update Duplicate of Why would one declare a Java interface method as abstract?

A: You're not missing anything. From the Java Language Specification:

Every method declaration in the body
  of an interface is implicitly
  abstract, so its body is always
  represented by a semicolon, not a
  block.
Every method declaration in the body
  of an interface is implicitly public.

In other words, you can omit the public as well as the abstract on the interface methods.

A: It's redundant (there's no difference between the two declarations) and explicitly discouraged in section 9.4 of the Java Language specification:

For compatibility with older versions
  of the Java platform, it is permitted
  but discouraged, as a matter of style,
  to redundantly specify the abstract
  modifier for methods declared in
  interfaces.

And public is similarly unnecessary and discouraged:

It is permitted, but strongly discouraged as a matter of style, to redundantly specify the
  public modifier for interface methods.

I don't know why public is strongly discouraged but abstract is just discouraged...

A: Both accomplish the same, since all methods in an interface are abstract.

A: abstract in this scenario is unnecessary (as is marking methods in interfaces as public).
You would instead use this on a method in an abstract class in order to enforce its overriding by a subclass.

A: There no are difference between declarations. Conceptually, all methods in an interface are abstract.

A: It makes no difference. All the methods in a java interface are always abstract.
See the first note at this link :
http://java.sun.com/docs/books/tutorial/java/IandI/abstract.html

A: There isn't any functional difference. No implementation is ever provided in a java interface so all method declarations are implicitly abstract.
See [1]: http://java.sun.com/docs/books/tutorial/java/IandI/abstract.html
A direct quote form the above:

Note: All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods (it could be—it's just not necessary).

A: Interface methods are both public and abstract by default. There's no difference between foo() and bar() and you can safely remove all public and abstract keywords.

A: Both foo() and bar() are abstract as they are declared inside an interface. The abstract word you used here is of no significance - you better remove it.

A: Interfaces in java are equal "somehow" to a fully abstract classes, so adding the "abstract" keyword to a method declaration in an interface has nothing to do with the method!


text:
Q: how to Find derivative of a LHS expression with respect to a variable in the RHS of a Sympy Eq Suppose I have an eq1 such that
from sympy import symbols, solve, plot, Eq, diff
a, b, X, Y, U = symbols('a b X Y U')
eq1 = Eq(U, X**a*Y**b)

$U=(X^a)(Y^b)$
but When I run diff(eq1 , X)
the differential does not evaluate I merele just get the DU/DX symbol but not evaluated

I know I could defined the function as
U = X**a * Y**b
and easily compute diff(U)
but printing the U expression will not look nice.

A: I am surprised that you even get what you got. In general, algebraic operations on Eq are not supported.
>>> from sympy import Derivative
>>> ediff=lambda e, *x: e.func(Derivative(e.lhs,*x), e.rhs.diff(*x))
>>> ediff(eq1, X)
Eq(Derivative(U, X), X**a*Y**b*a/X)


text:
Q: WSO2 ESB - architecture for FIX I am a beginner in ESB subject, with no expieriance in that subject at all.
I am about to create an application for Prop trading using WSO2 ESB (I like the thing they have implemented FIX server in it). However, in our company we need to separate external connections and Intranet using DMZ. What kind of archtecture should I use:

*

*ESB installed both on Intranet and DMZ servers, connected between themselves using some kind of stream like online replication used in databases

*ESB installed both on Intranet and DMZ servers, using JMS or other type of messaging to communicate

*ESB installed only on the Intranet server and QuickFIX installed on the DMZ server

The architecture choosen should allow the Order Management System to be extremely quick, with no unnecessary latency.

A: So the DMZ is basically a firewall that allows certain IP addresses and ports to communicate together, right? You need to talk to the guys who implement that about the best way to allow external FIX sessions through the DMZ. They can open certain IP and port for FIX connections.


text:
Q: C# subscribe a function to System.Action that is subscribed to another System.Action: why does order matter? I have 3 classes, forming a tree. I'm using System.Actions to communicate events. But I'm confused why the order I subscribe matters. Check this pseudo code:
class Leaf
{
    public System.Action OnTrigger;
    public void Go()
    {
        if (OnTrigger != null)
            OnTrigger();
    }
}

class Chunk
{
    public System.Action OnTrigger;
    public Leaf leaf = null;
    public Chunk()
    {
        leaf = new Leaf();
    }
}

class Tree
{
    void Hello()
    {
        Debug.Log("Hello");
    }
    void World()
    {
        Debug.Log("World");
    }

    public Tree()
    {
        var chunk2 = new Chunk();
        chunk2.OnTrigger += Hello; // OK: will be called
        chunk2.leaf.OnTrigger += chunk2.OnTrigger;
        chunk2.OnTrigger += World; // NOT: not be called
        chunk2.leaf.Go();
    }
}

best regards,
Massa

A: This has nothing to do with the order per se.
It has everything to do with the assignments you've made.
    chunk2.OnTrigger += Hello; // this is **never** called
    chunk2.leaf.OnTrigger += chunk2.OnTrigger; // this is the only one called
    chunk2.OnTrigger += World; // this is **never** called

When you call chunk2.leaf.Go(); the only event that fires is chunk2.leaf.OnTrigger. The chunk2.OnTrigger is never called.

A: This is relatively apparent from examining how delegates work and the MSIL that is created when you compile this. First lets note that System.Action is a System.Delegate which has the ICloneable interface.
When you compile this program, here is pretty much what you get:

  IL_0015:  newobj     instance void [mscorlib]System.Action::.ctor(object,
                                                                    native int)
  IL_001a:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
                                                                                class [mscorlib]System.Delegate)
  IL_001f:  castclass  [mscorlib]System.Action
  IL_0024:  stfld      class [mscorlib]System.Action ConsoleTests.Program6/Chunk::OnTrigger
  IL_0029:  ldloc.0
  IL_002a:  ldfld      class ConsoleTests.Program6/Leaf ConsoleTests.Program6/Chunk::leaf
  IL_002f:  dup
  IL_0030:  ldfld      class [mscorlib]System.Action ConsoleTests.Program6/Leaf::OnTrigger
  IL_0035:  ldloc.0
  IL_0036:  ldfld      class [mscorlib]System.Action ConsoleTests.Program6/Chunk::OnTrigger
  IL_003b:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
                                                                                class [mscorlib]System.Delegate)
  IL_0040:  castclass  [mscorlib]System.Action
  IL_0045:  stfld      class [mscorlib]System.Action ConsoleTests.Program6/Leaf::OnTrigger
  IL_004a:  ldloc.0
  IL_004b:  dup
  IL_004c:  ldfld      class [mscorlib]System.Action ConsoleTests.Program6/Chunk::OnTrigger
  IL_0051:  ldnull
  IL_0052:  ldftn      void ConsoleTests.Program6::World()
  IL_0058:  newobj     instance void [mscorlib]System.Action::.ctor(object,
                                                                    native int)
  IL_005d:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
                                                                                class [mscorlib]System.Delegate)
  IL_0062:  castclass  [mscorlib]System.Action
  IL_0067:  stfld      class [mscorlib]System.Action ConsoleTests.Program6/Chunk::OnTrigger
  IL_006c:  ldloc.0
  IL_006d:  ldfld      class ConsoleTests.Program6/Leaf ConsoleTests.Program6/Chunk::leaf
  IL_0072:  callvirt   instance void ConsoleTests.Program6/Leaf::Go()

Notice that when you do a += on a delegate, the compiler converts that into a Combine call, which combines the current delegate with the passed in one. Now look at IL_004b, which is a dup call.

From the MSDN: "Copies the current topmost value on the evaluation stack, and then pushes the copy onto the evaluation stack."

This tells the runtime to duplicate the object on the stack, and since this is ICloneable, it creates a copy of the object. Now when you add another delegate to it, you are not adding it to both, just the one you are operating on, leaving the Leaf trigger as it was.
The almost equivalent code is this:
public Tree()
{
    var chunk2 = new Chunk();
    chunk2.OnTrigger += Hello; // OK: will be called
    chunk2.leaf.OnTrigger = (Action)chunk2.OnTrigger.Clone();
    chunk2.OnTrigger += World; // NOT: not be called
    chunk2.leaf.Go();
}

Which may make it a little clearer about what is going on here.


text:
Q: Laravel 5.4, changing login to work from header For my own project I am needing login/registering functions. But I don't to use the standard Laravel login pages and such. I want to use the Login form I have in my header. But I can't seem to figure out how to make the Controller use the login information from my header form and handle it in the desired way.
My login form is an include in my header and the code is as following:

            <form class="nk-sign-form-login active" action="{{ url('/') }}">
                {{ csrf_field() }}

Log In

                <input class="form-control " type="text" placeholder="Username" id="username"  name="username" value="{{ old('username') }}" required autofocus>

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

                        <input type="checkbox" class="form-check-input"> Remember Me

                <button class="nk-btn nk-btn-color-white text-dark-1 pull-right">Log In</button>

                    Register |
                    Lost Password?

            </form>

            <form class="nk-sign-form-lost" action="#">

Lost Password

                <input class="form-control" type="text" placeholder="Username or Email">

                <button class="nk-btn nk-btn-color-white text-dark-1 pull-right">Get New Password</button>

                Back to Log In
            </form>

            <form class="nk-sign-form-register" action="#">

Register

                <input class="form-control" type="text" placeholder="Username">

                <input class="form-control" type="email" placeholder="Email">

A password will be emailed to you.

                <button class="nk-btn nk-btn-color-white text-dark-1 pull-right">Register</button>

                Back to Log In
            </form>

My LoginController is as following:
    namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function username()
    {
        return 'username';
    }

    public function rules()
    {
        return [
            'login' => 'required',
            'password' => 'required'
        ];
    }

}

If someone could help me in the way of pointing me in the right direction it would be greatly appreciated. If I need to post some more code I'll be happy to. Thanks in advance
edit: I've uploaded the code to the domain: verenmanta.site, you can view the header and login form over there if that may help!


text:
Q: Removing rows from MySQL table where the timestamp is over one day old? I found the exact same question here.
But it isn't working for me. I've modified it a bit, manipulated it, and I can't figure it out. I'm trying to remove rows that are over a day old. Here is my code:
if (isset($_POST['prune'])) {

    $sql = "DELETE FROM logs WHERE time < date('now', '-1 days')";
    mysql_query($sql);

    echo 'Logs older than one day removed.';

    }

Fairly simple question I suppose, but its bugging the hell out of me. I would appreciate any help.
In case it makes a difference, the column is a TIMESTAMP type.
EDIT: Apparently I'm an idiot. The question I linked you to relates to SQLite3. So now my question is, how can I do this in MySQL?

A: That answer was IIRC for SQLite3. You're using MySQL which does not support this syntax.
You want to use DATE_ADD() function (example below not tested but should work):
DELETE FROM logs WHERE time < TIMESTAMPADD(DAY,-1,NOW());

A: You can subtract an interval:
DELETE FROM logs WHERE time < now() - interval 1 day

A: In my case, only the
timestampadd
in positive direction works when running through an asc ordered date calendar:
    if (urldecode ($aUrl['Select']) == '>')
        $this-> db-> where ('konzertdatum >', 'TIMESTAMPADD(DAY, 1, "'.  $id . '") ', false) ;
    else
        $this-> db-> where ('konzertdatum < ', 'TIMESTAMPADD(DAY, -1, "'.  $id . '") ', false) ;

In negative direction (-1), the timestamp goes back to the very first entry. I also tried not to use CodeIgniter, but the same consequence.
Summing up, +1 as parameter for timestampadd works, -1 works for the second lowest entry (then jumping back to the first one. But it fails when I step further away from the first date.


text:
Q: How to tell JAXB that, the element is a Child of the Root? I have some test data in XML format, that I want to map to POJO.
<Root>
   <Child1>
      <Data>
      </Data>
   </Child1>
   <Child2>
      <Data>
      </Data>
   </Child2>
</Root>

Child1 is the first Object and Child2 the second.
JAXBContext context = JAXBContext.newInstance(classesToLoad);
Unmarshaller um = context.createUnmarshaller();
Object obj = (Object) um.unmarshal(data);

Object in this case is just a placeholder
@Getter
@Setter
@XmlRootElement(name = "TestData")
public class Child1 {

    @XmlElement(name = "ID")
    private String ID;
}

.
This is the code I'm working with right now, but I get this exception:

javax.xml.bind.UnmarshalException: unexpected Element (URI:"",
  lokal:"TestData"). expectected elements are: Child1

A: Move the annotation
@XmlRootElement(name = "TestData")
To your Root class and change it to
@XmlRootElement(name = "Root")
And I believe you'll need
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Child1")

in the Child1 class.
And give it a go again.
What the exception tells you is it's expecting an element of name TestData with namespace "" (you can ignore namespace for now since it's blank, but take minute or two to have a look at this since it's something that can trip you up when working with XML for the first time), and it's because you define the root element as TestData.
Additionally, the data example you've provided does not seem to correspond to your designed class.
<Child1>
    <Data>
    </Data>
</Child1>

public class Child1 {

    @XmlElement(name = "ID")
    private String ID;
}

I don't know if you've replaced the enclosed data for brevity for the sake of a neater question, but your Java object would more closely resemble this XML.
<Child1>
   <ID>[String ID value]</ID>
</Child1>


text:
Q: How to rotate a node around a point outside of the object (i.e don't rotate around the center point of the object) What I have Right now, my game loads up on the simulator on Xcode as it should, but when I tap the screen, "basic Top" doesn't rotate. Basic top is one of four triangles that makes up a square.
What I want In order to make that square rotate I have to get all four triangles to rotate. Right now, basic top doesn't rotate even when I click on the screen. Once I get basic top to rotate, I can replicate the code for the other triangles in order to make a square that rotates. I need these four triangles all to rotate around a certain point.
Code
class GameScene: SKScene {
var brickSwitch: SKSpriteNode!
var basicTop = SKSpriteNode(imageNamed: "Top Side");
var basicBottom: SKSpriteNode!
var basicLeft: SKSpriteNode!
var basicRight: SKSpriteNode!
override func didMove(to view: SKView) {
layoutScene()
}

func turnBasicTop() {
  basicTop.isUserInteractionEnabled = true
  basicTop.run(SKAction.rotate(byAngle: .pi/2, duration: 0.25))
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    turnBasicTop()
}

func spawnBasicTop() {
let basicTop = SKSpriteNode(imageNamed: "basic top")
basicTop.size = CGSize(width: 400, height: 400)
basicTop.position = CGPoint(x: 230, y: 200)
basicTop.zPosition = 1

basicTop.physicsBody = SKPhysicsBody(rectangleOf: basicTop.size)
basicTop.physicsBody?.categoryBitMask = PhysicsCategories.basicTopCategory
basicTop.physicsBody?.isDynamic = false
basicTop.physicsBody?.allowsRotation = true

addChild(basicTop)
}

A: The basicTop defined in spawnBasicTop() refers to the local variable defined within the method as a local variable with the same name as another variable with a greater scope takes precedence in reference. Hence, when you attempt to run an animation on basicTop in the turnBasicTop() method, the action is run on a completely separate SKSpriteNode instance. I suppose you aren't seeing anything happen because either the node referenced by the scene's basicTop property is out of the view; has its isHidden property as true; or cannot be assigned to the image "Top Side" since it doesn't exist and therefore has zero size. Adding
self.basicTop = basicTop

to the spawnBasicTop() method will do the trick, although I recommend you learn more about Swift and how variables are declared, captured, etc.


text:
Q: Javafx MVC how to signal new threaded result from one controller to another I have a Javafx MVC Structure where Controller 1, 2, 3... are in charge of updating the UI elementes, and Super Controller executes whatever job is passed to it from them, and returns the result.
I have a Button Btn1 in Controller1 which when pressed will be disabled and show a processing symbol while the main job is done in other thread whose function is present in Super Controller. Once that thread completes its job, it'll notify the calling function that job is done, so that Btn1 will be enabled again, and processing symbol removed.
CONTROLLER1
@FXML
Button Btn1;

private ProgressIndicator loading;
private SUPERCONTROLLER con;

@Override
public void initialize(URL url, ResourceBundle rb){
    loading=new javafx.scene.control.ProgressIndicator();
    loading.setProgress(javafx.scene.control.ProgressIndicator.INDETERMINATE_PROGRESS);
}
@FXML
private void press(MouseEvent evt){
    Btn1.setDisable(true);
    Btn1.setGraphic(loading);
    Task<Integer>t=this.con.Action();
    new Thread(t).start();
    t.setOnSuceeded(e->{
        if(t.getValue()==0){
            System.out.println("Success");
        }else{
            System.out.println("falure");
        }
        Btn1.setDisable(false);
        Btn1.setGraphic(null);
    });
}
private void inject(SUPERCONTROLLER c){
    this.con=c;
}

SUPERCONTROLLER
@FXML
private VBox sidePane;
@Override
public void initialize(URL url,ResourceBundle rb){
    var fxml=new FXMLLoader(getClass().getResource("CONTROLLER1.fxml");
    Pane childPanel=fxml.load();
    sidePane.getChildren().add(childPanel);
    CONTROLLER1 childPanel.getController();
    CONTROLLER1.inject(this);
}
protected Task<Integer> Action(){
    Task<Integer>task=new Task<>(){
        @Override protected Integer call(){
            Thread.currentThread.wait(3000);    //Imitate long task
            return 0;
        }
    }
    return task;
}

However, I want the thread concept to stay in Super Controller itself. i.e., Instead of setting suceeded operation in Controller1, I want to move it to Super Controller and Controller1 should just re-enable the button when Super Controller tells it.


text:
Q: .Net Core project trying to conditionally reference 32/64 bit assembly but dotnet build always resolves 64bit I have a .net core library project and another Asp.net core project referencing this library project.
The library project references an assembly that has x64 and x86 versions and I want to reference the version according to the PlatformTarget property value.
I've seen this question and already used their solution except that I'm using PlatformTarget instead of creating a custom property, here is project file:
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <Configurations>Debug;Release</Configurations>
        <Platforms>AnyCPU</Platforms>
        <PlatformTarget>x86</PlatformTarget>
    </PropertyGroup>
    <ItemGroup>
      <Reference Include="STPadLibNet, Version=8.4.3.0, Culture=neutral, PublicKeyToken=a0c5b3c72d40bbc6">
        <HintPath>$(PlatformTarget)\STPadLibNet.dll</HintPath>
      </Reference>
    </ItemGroup>
</Project>

The assembly I'm trying to reference is called STPadLibNet, 64bit version is located in x64 folder in Project directory and 32bit version is located in x86 folder.
For some reason dotnet build always resolves to x64 folder even if the platform is set to x86 resulting in BadImageFormatException at application startup.
I've read about assembly probing and I now understand that when assembly resolver finds the assembly under Project directory or its subdirectories it ignores the HintPath, I tried using different file name for dll like STPadLibNetx64.dll for the 64-bit version and STPadLibNetx86.dll for the 32-bit version and reference the correct version like this:
<HintPath>STPadLibNet$(PlatformTarget).dll</HintPath>

For some reason the dll file is copied to my library project output directory but it's not copied to the asp.net core project output directory resulting in Assembly not found exception at startup, Also Rider(the IDE I use) shows that the assembly is not resolved by MSBuild.
So how to tell dotnet build to use HintPath ? or how to reference the correct version of the assembly according to PlatformTarget?
Notes:

*

*I'm using .Net core 3.1 and my IDE is Rider 2019.3, OS Is windows 10 x64 1909 and Programming language is C# 8.

*the assembly I'm referencing is a hardware SDK which I can't change for obvious reasons

*I don't want to create two projects and I prefer not to create some dummy project.

A: In The End, I moved x86 and x64 folders containing STPadLibNet.dll outside the Project Directory to the Solution Directory, this way HintPath is respected again.


text:
Q: Recursive Standard Deviation in Python I'm attempting to implement a recursive standard deviation function in Python. I believe this is the correct formula; however, I consistently get different answers compared to the built-in numpy std.
def standard_deviation(l):
    std = 0
    mean = 0

    for i in range(len(l)):
        mean = (i * mean + l[i]) / (i + 1)
        std = math.sqrt( ( (i * std ** 2) + (l[i] - mean) ** 2 )
        / (i + 1))

    return std

https://i.stack.imgur.com/YjYhf.png


text:
Q: Sample server & client for Rack hijack proxy questions I've got sample app for hijack proxy server
io_lambda = lambda{ |io|
      3.times do |i|
        puts i
        io.write "David\r\n"
      end
      io.close
    }

run lambda{ |req|
      [
        200,
        [ [ "rack.hijack", io_lambda ] ],
        [""]
      ]
    }

and starting it
rackup config.ru -p 3000

Now I trying to code client for it. First, just curl it:
curl http://localhost:3000 -vv

and get following client output:
* Rebuilt URL to: http://localhost:3000/
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 3000 (#0)
> GET / HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
<
David
David
* transfer closed with outstanding read data remaining
* stopped the pause stream!
* Closing connection 0
curl: (18) transfer closed with outstanding read data remaining

now, with httparty:
require 'rubygems'
require 'bundler/setup'
Bundler.require(:default)

response = HTTParty.get('http://localhost:3000')
puts response.body, response.code, response.message, response.headers.inspect

I get:
→ ruby httparty-client.rb
Traceback (most recent call last):
    19: from httparty-client.rb:5:in `<main>'
    18: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/httparty-0.17.1/lib/httparty.rb:627:in `get'
    17: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/httparty-0.17.1/lib/httparty.rb:508:in `get'
    16: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/httparty-0.17.1/lib/httparty.rb:594:in `perform_request'
    15: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/httparty-0.17.1/lib/httparty/request.rb:145:in `perform'
    14: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:1470:in `request'
    13: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:920:in `start'
    12: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:1472:in `block in request'
    11: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:1479:in `request'
    10: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:1517:in `transport_request'
     9: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:166:in `reading_body'
     8: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:229:in `body'
     7: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:204:in `read_body'
     6: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:283:in `read_body_0'
     5: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:278:in `inflater'
     4: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:285:in `block in read_body_0'
     3: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:324:in `read_chunked'
     2: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:324:in `ensure in read_chunked'
     1: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/protocol.rb:159:in `read'
/Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/protocol.rb:225:in `rbuf_fill': end of file reached (EOFError)

last try with net/http:
require 'net/http'

streamURL = 'http://localhost:3000'

uri = URI.parse(streamURL)

Net::HTTP.start(uri.host, uri.port) do |http|
  request = Net::HTTP::Get.new uri.request_uri

  http.request request do |response|
    response.read_body do |chunk|
       #We get the data here chunk-by-chunk
       puts chunk
    end
  end
end

I get:
→ ruby net-http-client.rb
David
David
David
David
Traceback (most recent call last):
    16: from net-http-client.rb:7:in `<main>'
    15: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:605:in `start'
    14: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:920:in `start'
    13: from net-http-client.rb:10:in `block in <main>'
    12: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:1479:in `request'
    11: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:1517:in `transport_request'
    10: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:165:in `reading_body'
     9: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http.rb:1518:in `block in transport_request'
     8: from net-http-client.rb:11:in `block (2 levels) in <main>'
     7: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:204:in `read_body'
     6: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:283:in `read_body_0'
     5: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:278:in `inflater'
     4: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:285:in `block in read_body_0'
     3: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:324:in `read_chunked'
     2: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/http/response.rb:324:in `ensure in read_chunked'
     1: from /Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/protocol.rb:159:in `read'
/Users/khataev/.rbenv/versions/2.6.1/lib/ruby/2.6.0/net/protocol.rb:225:in `rbuf_fill': end of file reached (EOFError)

Could someone explain me:
1) Why curl return David x2,  httparty - nothing and net/http - David x4, while server sent 5? Also I'm curious why httparty and net/http results differ, because one uses another under the hood.
2) Why in all cases we have an error (transfer closed with outstanding read data remaining and end of file reached (EOFError))?

A: Have figured it out. Headers do matter. This version makes it work for all clients
io_lambda = lambda{ |io|
      5.times do |i|
        puts i
        io.write "David\r\n"
        sleep 1
      end
      io.close
    }

app = lambda do |env|

  response_headers = {}
  response_headers['Transfer-Encoding'] = 'binary'
  response_headers["Content-Type"] = "text/plain"
  response_headers["rack.hijack"] = io_lambda
  [200, response_headers, nil]

end

run app


text:
Q: How to start the service after restarting the device on Android 11? I want to start the service after restarting or turning on the device. At the moment everything works fine on my Android 8.1 device. But the Android 11 device does not launch my service, I do not get any errors. Here is my code:
Manifest file:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<service
            android:name=".service.ServiceManager"
            android:exported="false" />

<receiver
            android:name=".receiver.AutoRebootReceiver"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
            <intent-filter android:priority="99999">
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.SCREEN_ON" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>