text:
Q: DataTables warning - Request unknown parameter '0' for row 0, column 0 I'm using a jQuery DataTable to display data taken from a database using a stored procedure and web service. I can run the SP or service using Fiddler just fine, but when it comes to populating the DataTable I get the error documented here. In my specific case the message is:
"DataTables warning: table id=tblCashRecord - Requested unknown parameter '0' for row 0, column 0"
What happens then is that my DataTable shows the correct number of rows, but all of the cells are empty.
I'm pretty sure the number of columns in the HTML table are the same as the number of columns I'm pushing to using aoColumns (it's four), but I could be wrong. I know there are plenty of the same question being asked, but this is the only one I found useful that might be relevant, and I've also tried this without success.
My HTML table:

            Kiosk Name
            Service Type
            Transaction Timestamp
            Amount (RM)

            Total:

My Javascript:
$.ajax({
                        type: "POST",
                        url: "../Services/Report.svc/GetCashPaymentRecord/?s=" + session + "&r=" + reference,
                        data: "{\"kioskID\":" + JSON.stringify(kioskID) + "," + "\"startDate\": " + JSON.stringify(startDate) + "," + "\"endDate\":" + JSON.stringify(endDate) + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            if (response.success == true) {
                                if (response.cashPayment != null && response.cashPayment.length > 0) {
                                    cashList = response.cashPayment;
                                    var data = { "aaData": [] };

                                    $('#tblCashRecord').dataTable().fnClearTable();
                                    $('#tblCashRecord').dataTable().fnDestroy();

                                    $.each(response.cashPayment, function (item) {
                                        data.aaData.push({
                                            "id": item.id,
                                            "kioskName": item.kioskName,
                                            "total": item.total,
                                            "transactionTimestamp": moment.utc(item.transactionTimestamp).format("DD-MM-YY HH:mm:ss"),
                                            "serviceType": item.serviceType,
                                            "paymentType": item.paymentType, //remove later in SP
                                            "paymentRecordID": item.paymentRecordID
                                        });
                                    });

                                    table = $('#tblCashRecord').DataTable({
                                        "paging": false,
                                        "ordering": false,
                                        "bAutoWidth": false,
                                        "bSortable": false,
                                        "bFilter": false,
                                        "bInfo": false,
                                        dom: 'Blfrtip',
                                        "aaData": data.aaData,
                                        "aaColumns": [
                                            { "mData": "kioskName" },
                                            { "mData": "serviceType" },
                                            { "mData": "transactionTimestamp" },
                                            { "mData": "total" }
                                        ]
                                    });

                                    $('#tblCashRecord tbody tr').each(function () {
                                        var col = $(this).find('td:eq(3)').html();
                                        total += parseFloat(col);
                                    });

                                    $('#totalAmount').html(total.toFixed(2));
                                    $('.sorting_asc').removeClass('sorting_asc');
                                }
                                else {
                                    $('#tblCashRecord').dataTable().fnClearTable();
                                    $('#tblCashRecord').dataTable().fnDestroy();

                                    $('#tblCashRecord').dataTable({
                                        "paging": false,
                                        "ordering": false,
                                        "bAutoWidth": false,
                                        "bSortable": false,
                                        "bFilter": false,
                                        "bInfo": false,
                                        "oLanguage": {
                                            "sEmptyTable": "No Record Found."
                                        }
                                    });
                                    $('#totalAmount').html("");
                                    $('.sorting_asc').removeClass('sorting_asc');
                                }
                            }
                            else {
                                $('#tblCashRecord').dataTable().fnClearTable();
                                $('#tblCashRecord').dataTable().fnDestroy();

                                $('#tblCashRecord').dataTable({
                                    "paging": false,
                                    "ordering": false,
                                    "bAutoWidth": false,
                                    "bSortable": false,
                                    "bFilter": false,
                                    "bInfo": false,
                                    "oLanguage": {
                                        "sEmptyTable": "Error: Could not load data."
                                    }
                                });
                                $('#totalAmount').html("");
                                $('.sorting_asc').removeClass('sorting_asc');
                            }
                        }
                    });

My web service:
cashPaymentResponse IReport.GetCashPaymentRecord(string session, string reference, cashPaymentRequest request)
        {
            Guid sessionID, referenceID, kioskID;
            Guid.TryParse(session, out sessionID);
            Guid.TryParse(reference, out referenceID);
            Guid.TryParse(request.kioskID, out kioskID);

            if (sessionID == Guid.Empty)
            {
                return new cashPaymentResponse("Invalid Session.");
            }

            DateTime startDate, endDate;

            try
            {
                startDate = new DateTime(Convert.ToInt32(request.startDate.Substring(6, 4)), Convert.ToInt32(request.startDate.Substring(3, 2)), Convert.ToInt32(request.startDate.Substring(0, 2)), 0, 0, 0);

                endDate = new DateTime(Convert.ToInt32(request.endDate.Substring(6, 4)), Convert.ToInt32(request.endDate.Substring(3, 2)), Convert.ToInt32(request.endDate.Substring(0, 2)), 23, 59, 59);
            }
            catch (Exception ex)
            {
                return new cashPaymentResponse("No Date Selected.");
            }

            List<ReportCashPaymentRecord_Result> result;
            try
            {
                using (MyDBEntities context = new MyDBEntities())
                {
                    result = context.ReportCashPaymentRecord(sessionID, kioskID, startDate, endDate).ToList();
                }
            }
            catch (Exception ex)
            {
                if (isDebug() == false)
                {
                    return new cashPaymentResponse("Database connection failed.");
                }
                else
                {
                    return new cashPaymentResponse(ex.Message);
                }
            }

            if (result.Count > 0)
            {
                cashPaymentResponse response = new cashPaymentResponse();
                cashPaymentItem item;
                response.cashPayment = new List<cashPaymentItem>();

                for (int i = 0; i < result.Count; i++)
                {
                    item = new cashPaymentItem();

                    if (result[i].kioskName == "session")
                    {
                        return new cashPaymentResponse("Invalid Session.");
                    }
                    else
                    {
                        item.id = (Guid)result[i].cashID;
                        item.paymentRecordID = (Guid)result[i].paymentRecordID;
                        item.total = (decimal)result[i].total;
                        item.transactionTimestamp = JsonConvert.SerializeObject(new DateTime(result[i].transactiontimestamp.Value.Year, result[i].transactiontimestamp.Value.Month, result[i].transactiontimestamp.Value.Day, result[i].transactiontimestamp.Value.Hour, result[i].transactiontimestamp.Value.Minute, result[i].transactiontimestamp.Value.Second, 0, DateTimeKind.Utc)).Replace("\"", "");
                        item.kioskName = result[i].kioskName;
                        item.serviceType = (result[i].serviceType.ToString() == "0") ? "Assessment" : (result[i].serviceType.ToString() == "1") ? "Water Bill" : (result[i].serviceType.ToString() == "2") ? "Rental" : (result[i].serviceType.ToString() == "3") ? "Compound" : "None";
                        item.paymentType = (result[i].paymentType.ToString() == "1") ? "Cash" : (result[i].paymentType.ToString() == "3") ? "Credit Card" : (result[i].paymentType.ToString() == "2") ? "Cheque" : "None";

                        response.cashPayment.Add(item);
                    }
                }
                return response;
            }
            else
            {
                return new cashPaymentResponse();
            }
        }

My JSON Response (there are actually 8 entries, but I included only the first one to reduce clutter):
{
    "success": true,
    "cashPayment": [
        {
            "id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
            "kioskName": "00001",
            "paymentRecordID": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy",
            "paymentType": "Cash",
            "serviceType": "Water Bill",
            "total": 100,
            "transactionTimestamp": "2016-01-21T10:15:21Z"
        }
    ]
}

EDIT: I have edited the GUIDs in the response above to remove sensitive information.

A: Classic hungarian notation typo. aaColumns should be aoColumns - for array object. Then I am sure it will work. aoColumns is BTW from 1.10.x now called columns (but both names is still supported).
In general, use the new 1.10.x camelcase naming convention and please skip all that qouting around literal names :
table = $('#tblCashRecord').DataTable({
  paging: false,
  ordering: false,
  autoWidth: false,
  sortable: false,
  filter: false,
  info: false,
  dom: 'Blfrtip',
  data: data.aaData,
  columns: [
    { data: "kioskName" },
    { data: "serviceType" },
    { data: "transactionTimestamp" },
    { data: "total" }
  ]
});

Update per comment. The reason for empty cells, after you have corrected "aaColumn", is that you are using $.each the wrong way :
$.each(response.cashPayment, function (item) {

should be
$.each(response.cashPayment, function (index, item) { //<----
    data.aaData.push({
      "id": item.id,

You are accidently trying to take the attributes out of the index, not the object.


text:
Q: What is the best practice with regards to handling HTTPS? I've been learning more about hosting my own web server and specifically one with HTTPS, and was wondering what the best practice is.
Should you handle the HTTPS in the application itself or should you make a separate proxy application to put between it that handles all the HTTPS stuff so your application doesn't have to?
My personal example in case my question isn't clear:
I now have 2 separate Node applications running on my server, and I wanted to have them accessible using the same domain name but separate paths.
So App1 uses /app1/ and App2 uses /app2/
I then found http-proxy-middleware which is able to do this. But then I discovered that it was also possible to handle the HTTPS stuff this way.
This meant that I was able to strip out all the things about handling HTTPS from my applications, and just let the proxy do it.
I image using the proxy is the preferred way, but I have no idea whether there are some hidden downsides or something.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it OK to create an object inside a function I work on a class in VBA, that encapsulates downloading stuff with MSXML2.XmlHttp.
There are three possibilities for the return value: Text, XML and Stream.
Should I create a function for each:
 aText=myDownloader.TextSynchronous(URL,formData,dlPost,....)
 aXml.load myDownloader.XmlSynchronous(URL,formData,dlPost,....)

Or can I just return the XmlHttpObject I created inside the class and then have
 aText=myDownloader.Synchronous(URL,formData,dlPost,.....).ResponseText
 aXML=myDownloader.Synchronous(URL,formData,dlPost,.....).ResponseXML

In the former case I can set the obj to nothing in the class but have to write several functions that are more or less the same.
In the latter case, I relay on the "garbage collector" but have a leaner class.
Both should work, but which one is better coding style?

A: In my opinion, the first way is better because you don't expose low level details to a high level of the abstraction.
I did something similar with a web crawler in Java, so I have a class only to manipulate the URL connection getting all the needed data (low level) and a high level class using the low level class that return an object called Page.
You can have a third method that only execute myDownloader.Synchronous(URL,formData,dlPost,.....) and stores the returned object in a private variable and the others method only manipulate this object. This form, you will only open the connection one time.

A: After much seeking around in the web (triggered by the comment by EmmadKareem) I found this:
First of all, Dont do localObject=Nothing at the end of a method - the variable goes out of scope anyway and is discarded. see this older but enlightening post on msdn
VBA uses reference counting and apart from some older bugs on ADO this seems to work woute well and (as I understand) immediately discards ressources that are not used anymore. So from a performance/memory usage point of view this seems not to be a problem.
As to the coding style: I think the uncomfortable fdeeling I had when I designed this could go away by simply renaming the function to myDownloader.getSyncDLObj(...) or some such.
There seem to be two camps on codestyle. One promotes clean code, which is easy to read, but uses five lines everytime you use it. Its most important prerogative is "every function should do one thing and one thing only. Their approach would probably look something like
myDownloader.URL="..."
myDownloader.method=dlSync
myDownloader.download
aText=myDownloader.getXmlHttpObj.ResponseText
myDownloader.freeResources

and one is OK with the more cluttered, but less lineconsuming
aText=myDownloader.getSyncObj(...).ResponseText

both have their merits both none is wrong, dangerous or frowned upon. As this is a helper class and I use it to remove the inner workings of the xmlhttp from the main code I am more comfortable with the second approach here. (One line for one goal ;)
I would be very interested on anyones take on that matter


text:
Q: Not able to assign view variable in spree I have the custom method in my ProductsController of my spree app.
module Spree
  module Api
    class ProductsController < Spree::Api::BaseController

      def custom_view
        @test = "This is test variable"
      end

    end
  end
end

in my view custom_view.html.erb i have the following

Custom View Title

test : <%= @test %>

The rendering gives the following output:
Custom View Title
test :
Obviously the variable is not being transmitted from the controller.
I have tried to add before_filer methods and added puts "debug" custom view in the method but neither the before_filter seem to be executing nor the puts output is showing in the log.
Am i doing something wrong ? How can i pass view variables in that case ?
Thanks!
EDIT:
I have tried to replace
module Spree
  module Api
    class ProductsController < Spree::Api::BaseController

by
Spree::Api::ProductsController.class_eval do

Only to end-up with the same results...


text:
Q: UICollection ContentInsetAdjustment behavior modifying 'ghost' reusable view instead of my header I am having difficulty getting UICollectionView Content Insets Adjustment Behavior setting to work. It appears to be modifying the location of 'ghost' ReusableView instead of my header view. In this screenshot the ghost view is selected, the header view I'm trying to control is green (its bg color).
I have tried using both the story board and programatic options, both are moving the position of the ghost view instead of my visible view. I cannot find where these ghost views are being generated nor can I see them in storyboard.
screenshot of ghost views
Here is my reusable view function:
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    if(kind == "UICollectionElementKindSectionHeader"){
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "questionHeader", for: indexPath) as! QuestionheaderCollectionReusableView
        if(self.mode == .Test){
            view.scoreRing.alpha = 0.5
            view.scoreRing.style = .ontop
        }else{
            view.updateScore(session: QKSession.default)
        }
        if((activeQuestion) != nil){
            view.questionLabel.text = activeQuestion?.question
            view.updateProgress(session: QKSession.default, question: activeQuestion!)
        }else{
            view.questionLabel.text = "Please select a MQF"
        }

        return view
    }else{
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "questionFooter", for: indexPath) as! QuestionFooterCollectionReusableView
        return view
    }
}

Has anyone else seen anything like this?


text:
Q: XSLT - wrapping xsl:template output up in a tag I need to take in 1 .XML file, and output N files that are a sub-set of the input file.  This sub-set is based on a predicate check of 2 nodes.  My plan is to run the input file over a  XSLT template N times to output each file.
My input looks like this:
<employee_data>
<employees>
    <employee id="1">
    <first_name>2sk8d</first_name>
    <agency_code>38</agency_code>
    <offices_administered>
        <office_administered office_identifier="ALLPOIs" agency_code="HL" />
    </offices_administered>
    </employee>
    <employee id="2">
        <first_name>2sk8d</first_name>
        <agency_code>24</agency_code>
        <offices_administered>
            <office_administered office_identifier="ALLPOIs" agency_code="22" />
        </offices_administered>
    </employee>
    <employee id="3">
        <first_name>2sk8d</first_name>
        <agency_code>22</agency_code>
        <offices_administered>
            <office_administered office_identifier="ALLPOIs" agency_code="HL" />
        </offices_administered>
    </employee>
</employees>

My XSLT looks like this
<?xml version="1.0" encoding="utf-8"?>

<xsl:output method="xml" indent="yes"  encoding="utf-16"/>

<xsl:template match="/employee_data/employees/employee[agency_code='22' or offices_administered/office_administered/@agency_code='22']">
    <xsl:copy>
        <xsl:copy-of select="."/>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="@* | node()">
    <xsl:message terminate="no">
        Catch 1 <xsl:value-of select="name()"/>
    </xsl:message>
</xsl:template>

My problem is that my output does not contain the EmployeeData or Employees root/parent nodes.
If I change my xslt to put  in the first xsl:template-match, then those tags are repeated multiple times/
If I change my match predicate to /employee_data/employees[employee/agency_code='22' or employee/offices_administered/office_administered/@agency_code='22'] then I get all employees.
It's almost like I want some magic to wrap my whole output of the match up in my two parent tags.

A: From what I understand from this question, you want something like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
   <employee_data>
        <employees>

          <xsl:apply-templates select=
          "/*/employees/employee
                [agency_code='22'
                or offices_administered/office_administered/@agency_code='22']"/>
        </employees>
  </employee_data>
 </xsl:template>

  <xsl:template match="employee">
   <xsl:copy-of select="."/>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:message terminate="no">
        Catch 1 <xsl:value-of select="name()"/>
    </xsl:message>
  </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:
<employee_data>
    <employees>
        <employee id="1">
            <first_name>2sk8d</first_name>
            <agency_code>38</agency_code>
            <offices_administered>
                <office_administered office_identifier="ALLPOIs" agency_code="HL" />
            </offices_administered>
        </employee>
        <employee id="2">
            <first_name>2sk8d</first_name>
            <agency_code>24</agency_code>
            <offices_administered>
                <office_administered office_identifier="ALLPOIs" agency_code="22" />
            </offices_administered>
        </employee>
        <employee id="3">
            <first_name>2sk8d</first_name>
            <agency_code>22</agency_code>
            <offices_administered>
                <office_administered office_identifier="ALLPOIs" agency_code="HL" />
            </offices_administered>
        </employee>
    </employees>
</employee_data>

the wanted, correct result is produced:
<employee_data>
   <employees>
      <employee id="2">
         <first_name>2sk8d</first_name>
         <agency_code>24</agency_code>
         <offices_administered>
            <office_administered office_identifier="ALLPOIs" agency_code="22"/>
         </offices_administered>
      </employee>
      <employee id="3">
         <first_name>2sk8d</first_name>
         <agency_code>22</agency_code>
         <offices_administered>
            <office_administered office_identifier="ALLPOIs" agency_code="HL"/>
         </offices_administered>
      </employee>
   </employees>
</employee_data>

II. XSLT 2.0 solution
Using XSLT 2.0 it is possible to create all N documents with a single run of the transformation:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pCodes" as="xs:string+" select="'22', '38'"/>
 <xsl:variable name="vDoc" select="/"/>

 <xsl:template match="/">
   <xsl:for-each select="$pCodes">
    <xsl:variable name="vCode" select="."/>
    <xsl:result-document href="'Agency'{.}.xml">
       <employee_data>
             <employees>

              <xsl:apply-templates select=
              "$vDoc/*/employees/employee
                    [agency_code=$vCode
                    or offices_administered/office_administered
                                              /@agency_code=$vCode]"/>
             </employees>
       </employee_data>
      </xsl:result-document>
  </xsl:for-each>
 </xsl:template>

  <xsl:template match="employee">
   <xsl:copy-of select="."/>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:message terminate="no">
        Catch 1 <xsl:value-of select="name()"/>
    </xsl:message>
  </xsl:template>
</xsl:stylesheet>

When we run this transformation on the same provided (above) XML document, two files are created:
Saxon 9.1.0.5J from Saxonica
Java version 1.6.0_31
Stylesheet compilation time: 610 milliseconds
Processing file:/C:/Program%20Files/Java/jre6/bin/marrowtr.xml
Building tree for file:/C:/Program%20Files/Java/jre6/bin/marrowtr.xml using class net.sf.saxon.tinytree.TinyBuilder
Tree built in 0 milliseconds
Tree size: 25 nodes, 21 characters, 9 attributes
Loading net.sf.saxon.event.MessageEmitter

Writing to file:/C:/Program%20Files/Java/jre6/bin/'Agency'22.xml
Writing to file:/C:/Program%20Files/Java/jre6/bin/'Agency'38.xml

Execution time: 94 milliseconds
Memory used: 11464160
NamePool contents: 26 entries in 26 chains. 6 prefixes, 7 URIs


text:
Q: Movie/Animation having an immortal man trying to revive his brother after 3000 years I'm trying to recall the title of an animated movie I watched as a kid long ago. I'm not even sure it was a movie (though if it was it's probably an animated one), but I remember I watched it on TV. The plot is sort of as below, where (xyz?) denotes parts that I'm not sure and could be something similar.
There was a legend of two close brothers in ancient times, (who were strong warriors?). Something happened and one of them (died?), then no one heard of the other. It was believed that (either the two were immortal, or the surviving one turned immortal in that event?).
Some 3000 years later, a group including the protagonist is trying to solve some (mystery?). Investigation relates it to the two brothers' legend, then one in the group figures the survived brother should still be alive and probably has accumulated a lot of wealth. It turns out that brother did become very rich and currently the owner of a huge/very powerful corporation.
He has been preparing for an upcoming significant event, which hasn't happened for at least 3000 years (and also is the chance to revive his brother?). The group (tries to stop him?) for some reason.

A: As pointed out by the comments, it seems that this is a partial recollection (along with other stories, especially for the "brother" part) of the 2007 Teenage Mutant Ninja Turtles movie. It was CGI, which would fit the "animation" OP was remembering.

It was believed that (either the two were immortal, or the surviving one turned immortal in that event.
From the intro:

An evil born 3000 years ago. It was in that time that a warrior king named Yoatl led a brotherhood that fought side by side with one purpose: to conquer all the kingdoms of the world. Nothing could stand in their way as they left a trail of destruction behind them.  In his quest, the warrior learned of a constellation known as the Stars of Kikan. Every 3000 years, the stars would align, opening a portal to a world of unknown power. He became immortal, but at a price.

The guy doesn't have a brother per se (at least not that we know of), but his companions are referred to as his "brotherhood", who were turned to stone.
Some 3000 years later, a group including the protagonist is trying to solve some (mystery?). Investigation relates it to the two brothers' legend, then one in the group figures the survived brother should still be alive and probably has accumulated a lot of wealth.
The events take place 3000 years after the intro. The turtles have split up, but are later bourght back together and investigate April's boss, a rich guy named Max Winters. Winter turns out to be Yoatl.
It turns out that brother did become very rich and currently the owner of a huge/very powerful corporation.
Winters is the boss, and presumed founder, of Winterscorp:

"You've never heard of Winterscorp?"
"That's what I'm telling you."
"They're into everything: Real estate, technology, pharmaceuticals, hair gel."

He has been preparing for an upcoming significant event, which hasn't happened for at least 3000 years (and also is the chance to revive his brother?).
Winters/Yaotl replicates the event from 3000 years ago. Upon this, his generals are indeed "revived" of sorts.


text:
Q: Can creatures follow me through a portal? Can creatures from both the Nether and the Overworld follow me through a portal? Is it safe to build a portal in the open, or should it be surrounded in a cobblestone hut to prevent unwanted travellers?
Can regular creatures use the portal to enter the Nether, or can I use it to evade them?

A: As of Minecraft dev version 1.4.2, mobs have the ability to travel through portals.  Taken from the wiki:

*

*Added new Full-screen toggle to the Video settings.

*Added new use Vsync toggle in the Video settings.

*Improved maps

*Maps now align to a grid, making it easier to create adjacent maps.

*A compass and paper do now create an empty map

*An empty map has no data on it until you right click on it. The point on your world - - - where you right clicked it is the map's
  center

*A map (with data) can be cloned. Cloned maps are stackable

*Maps can be zoomed out (but not zoomed in)

*Stairs now auto-arrange into corners. This is a test and may change based on feedback.

*Mobs (and all other entities) can travel through portals.

*Fire charges shot from a dispenser or a Blaze create the "fireball" sound effect. Leather armor can be dyed.

Thus to answer your questions above:

Can creatures from the Nether come through a portal?

Yes, they can. This now applies to all mob entities, including the Wither and Enderdragon bosses.

Is it safe to build a portal in the open, or should it be surrounded in a cobblestone hut to prevent unwanted travelers?

Depends on how you are playing your game (ie game difficulty)

Can regular creatures use the portal to enter the Nether, or can I use it to evade them?

You will not be able to travel through the portal instantaneously, but mobs can. Also, the player now can go through the nether quicker, as of 12w38a.  As for mob behavior, they do not chase you into the portals.  They may wander into the portals, but not by following the player.

A: Note: This answer applies to Minecraft 1.4.1 and earlier. For newer versions see the other answers.
Mobs can not follow you through a portal. "Follow" meaning continuing a pursuit by entering the portal after you do and chasing you again once you're on the other side.
Currently, the only danger coming from the existence of a portal is the possibility of a Ghast spawning by it in the "Earth", "Overworld" or whatever we now call the main area of the game. The space they need to spawn there is at least 4x4x4 and, according to Notch, their appearance near the portal is "extremely uncommon".

A: I built a monster trap close to the Overworld side of my Nether gate and spent many nights there.  When I went back into the Nether, I found that numerous skeletons and regular zombies had been going into the gate.  Apparently they could not move once they got there, so the small cobblestone structure housing the Nether side of the gate was jam-packed with skeletons and zombies.  They rapidly pushed me out of the building and killed me....
So Nether gates should probably be protected from monsters by structures on both sides.  I don't think this will stop the occasional appearance of zombie pigmen on the Overworld side, but at least it will stop the Nether side from becoming a skeleton ranch.

A: I don't now about all or about following, but as of today I was just sitting in my house (portal inside my house) and a zombie pig-man came out of nowhere and attacked me. So I guess any monster standing still long enough could pass through the portal without following you as well, for I had not went though the portal all day, yet here came this zombie after my brains.

A: Yes mobs can go through portals but you can't push/force them through easiliy. You can try but it takes a very long time. Unless you are riding the mob.


text:
Q: pandas.read_csv duplicate issue Solution: removing the print statement shows the data once. But I do not understand the logic behind this?
This seems like a very straightforward issue but I am having a great deal of trouble finding a solution or anyone else that has replicated this issue.
I am simply trying to read some data from a csv using pandas. The csv is fairly large and I thought was the cause of the issue but I created a new test case csv by hand which is simply a 3x3 grid:
 A  b  c
 1  2  3
 4  5  6

This also caused the issue that I have not seen before. Essentially when I interact with the dataframe it is replicated twice.
import json #(for later use)
import pandas as pd
import numpy as np

data = pd.read_csv("Workbook1.csv")

print (data)

output:
   A  b  c
0  1  2  3
1  4  5  6
   A  b  c
0  1  2  3
1  4  5  6

print (type(data))

output:
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>

It's not the case that I can drop the first few rows to delete one half either:
data.drop(data.index[0], axis =0, inplace = True)
print (data)

output:
   A  b  c
1  4  5  6
   A  b  c
1  4  5  6

It seems like the strangest problem that I have not seen before from using pandas and reading files multiple times with no such similar issue.
Edit
Further to this, when I remove the 'import json' at the top, the script fails all together stating that 'module' object has no attribute 'read_csv'
  import pandas as pd
  import numpy as np

  data = pd.read_csv('Workbook1.csv')
  data

Results in AttributeError: 'module' object has no attribute 'read_csv'

A: It appears that the strange behaviour of my script is due to the fact that a compiled version of the script had been created with extension .pyc
I had read an answer to a similar problem that suggested changing the name of the script (my script was named json.py so thought this could cause issues). Upon changing the name of the script I now had test.py but with json.pyc in the same directory. When I run the script, somehow the compiled version was continuing to be referenced therefore I continued to see the same issues. Removing the .pyc extension file solved my issue.


text:
Q: How can I duplicate the add to cart button on the single product page, but redirect to another page? We're building a webshop with a lot of custom code added and hooked on WooCommerce.
On the single product page, we have ofcourse the add-to-cart button, which automatically redirects to the cart page.
Underneath the add-to-cart button, we've added a button to add the product to a 'quotation'. I general, this button has to exactly copy the Add-to-cart button functions, but in stead of redirecting to the Cart page, it has to redirect to a custom page.
There is this code to change the redirect url when adding a product in your cart, but that's not enough.
function my_custom_add_to_cart_redirect( $url ) {
    $url = get_permalink( 1 ); // URL to redirect to (1 is the page ID here)
    return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );

When clicking on the add to cart button -> Cart page
When clicking on the add to quote button -> Custom page
Is there any possibility to 'copy' the functionalities from the Add-to-cart button, but change the redirect that's happening afterwards?
NOTE: We hooked on a few WooCommerce functions like adding Cart Item Data, so all of these have to be 'copied' as well.

A: I have divided my answer into 3 parts. The intention is to add a copy of the existing add to cart button with 1 difference, and we will use that difference for the redirect.
Step 1) Adding the (copy) of the add to cart button can be done by adjusting/overwriting the template file, however it can also be done by using the available hooks in the template file, for example the woocommerce_after_add_to_cart_button hook
// Add new/extra button
function action_woocommerce_after_add_to_cart_button() {
    global $product;

    // Button text
    $button_text = __( 'My new text', 'woocommerce' );

    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Simple products
        if ( $product->is_type( 'simple' ) ) {
            echo '<button type="submit" name="add-to-cart" value="'. esc_attr( $product->get_id() ) . '" class="single_add_to_cart_button button alt custom_redirect_button">' . $button_text . '</button>';
        // Variable products
        } elseif( $product->is_type( 'variable' ) ) {
            echo '<button type="submit" class="single_add_to_cart_button button alt custom_redirect_button">' . $button_text . '</button>';
        }
    }
}
add_action( 'woocommerce_after_add_to_cart_button', 'action_woocommerce_after_add_to_cart_button', 10 );

This adds a copy of the existing add to cart button for simple and variable products but with 1 difference. Namely: when the button is clicked, a hidden input field is added via jQuery (step 2).

Step 2) This is the code to add the hidden input field with a certain value. I added the jQuery via an action hook but this can just as well be included in an external js file.
// Add jQuery to footer
function action_wp_footer() {
    // Only on single product page
    if ( is_product() ) {
        ?>
        <script type="text/javascript">
        jQuery( function($) {
            // Add to cart button or custom button is clicked
            $( document ).on( 'click', '.custom_redirect_button', function () {
                // NOT disabled
                if ( ! $( this ).hasClass( 'disabled' ) ) {
                    // Add hidden input field after
                    $( this ).after( '<input type="hidden" name="custom-redirect" value="my-value" />' );
                }
            });
        });
        </script>
        <?php
    }
}
add_action( 'wp_footer', 'action_wp_footer', 10 );

Step 3) Get the value from the hidden input field and when it matches, then it is our custom button and we apply our own url.
// Redirect
function filter_woocommerce_add_to_cart_redirect( $redirect_url, $product ) {
    // If value isset
    if ( isset( $_REQUEST['custom-redirect'] ) ) {
        // If equal to
        if ( $_REQUEST['custom-redirect'] == 'my-value' ) {
            // URL to redirect to (1 is the page ID here)
            $redirect_url = get_permalink( 1 );
        }
    }

    return $redirect_url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'filter_woocommerce_add_to_cart_redirect', 10, 2 );


text:
Q: OpenJFX packaging with application I am trying to work with JavaFX/OpenJFX. I see that it has dependencies with platform classifier, e.g., javafx-graphics, for common platforms (Windows, Linux, etc.). I am looking ahead and I am curious

*

*if I can just package all the platform .jar files or extracted .class files into resulting distribution ZIP or JAR and it will magically pick up the right one, or

*if I will have to create separate distributions for each of the supported platforms?


text:
Q: Python Multiprocessing Pool Class won't work I am trying to use multiprocessing on a different problem but I can't get it to work. To make sure I'm using the Pool class correctly, I made the following simpler problem but even that won't work. What am I doing wrong here?
from multiprocessing import Pool

def square(x):
    sq = x**2
    return sq

def main():
    x1 = [1,2,3,4]
    pool = Pool()
    result = pool.map( square, x1 )
    print(result)

if __name__ == '__main__': main()

The computer just seems to run forever and I need to close and restart the IPython shell before I can do anything.

A: I figured out what was wrong. I named the script "multiprocessing.py" which is the name of the module that was being imported. This resulted in the script attempting to import itself instead of the actual module.


text:
Q: Tab Background change on selection I need to set different Images as tab background on different states. I have set one image as background for default but how to switch to other one when tab is selected. Below is my code.
public class HelloTabWidget extends  TabActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost();  // The activity TabHost
        TabHost.TabSpec spec;  // Resusable TabSpec for each tab
        Intent intent;  // Reusable Intent for each tab
        TabWidget tw = getTabWidget();

        for (int i = 0; i < tw.getChildCount(); i++) {
                    View v = tw.getChildAt(i);
                    v.setBackgroundDrawable(getResources().getDrawable
        (R.drawable.tab_artist));
                  }

        //First tab
        intent = new Intent().setClass(this, FirstActivity.class);    // Initialize a TabSpec for each tab and add it to the TabHost
        spec = tabHost.newTabSpec("First").setIndicator("First")
        .setContent(intent);
        tabHost.addTab(spec);
        getTabHost().getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.tabselected);

         //Second tab
         intent = new Intent().setClass(this, SecondActivity.class);    // Initialize a TabSpec for each tab and add it to the TabHost
            spec = tabHost.newTabSpec("Second").setIndicator("Second")
            .setContent(intent);
            tabHost.addTab(spec);
             getTabHost().getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.tabselected);

             //third
             intent = new Intent().setClass(this, ThirdActivity.class);    // Initialize a TabSpec for each tab and add it to the TabHost
                spec = tabHost.newTabSpec("Third").setIndicator("Third")
                .setContent(intent);
                tabHost.addTab(spec);
                getTabHost().getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.tabselected);

    }
}

/*tab_artist.xml*/
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:background="@drawable/tabselected"  android:state_selected="true" />
<!-- When not selected, use white-->
<item android:background="@drawable/tabunselected" />
</selector>

A: Implement onTabChangeListener() and there modify their backgrounds. Cheers
http://developer.android.com/reference/android/widget/TabHost.OnTabChangeListener.html
Edit:
Use the tabHost to implement the method. You can implemented where ever you want. Let's say do it after you set all the TabWidgets. Its good practice to use ids of the tab like you've set them "First", "Second" etc etc.
 tabHost.setOnTabChangedListener(new OnTabChangeListener(){
          @Override
            public void onTabChanged(String tabId) {
                        if(tabId.equals("First"){
                                //do something
                        }else if(tabId.equals("Second"))
                        {
                            //do something
                        }// etc etc etc

                        }});

A: public class HelloTabWidget extends  TabActivity implements OnTabChangeListener{
.....

mTabHost. setOnTabChangedListener(this);

@Override
    public void onTabChanged(String tabId) {

              // Here in tabId you will get the name of the Tab from that you can check and set the background
                // of the requirement tab according to need.
    }
}

A: this may help you
Tabhost.setOnTabChangedListener(new OnTabChangeListener(){
@Override
        public void onTabChanged(String tabId) {

            for(int i=0;i<tb.getTabWidget().getChildCount();i++)
            {
                   tb.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.tabunselected); //unselected
            }
            tb.getTabWidget().getChildAt(tb.getCurrentTab()).setBackgroundResource(R.drawable.tabselected);
}});


text:
Q: Boolean Algebra, Simplification: Sum of products
Possible Duplicate:
Boolean Algebra, Simplification: Don't know the method used

Based on a previous question, the answer I got for the "sum of products" method was:
RC' + RCG' + RCGM'

Just for completeness, can someone help walk me through to how this was arrived at?  Thanks again in advance!


text:
Q: How does MySQL's ORDER BY RAND() work? I've been doing some research and testing on how to do fast random selection in MySQL. In the process I've faced some unexpected results and now I am not fully sure I know how ORDER BY RAND() really works.
I always thought that when you do ORDER BY RAND() on the table, MySQL adds a new column to the table which is filled with random values, then it sorts data by that column and then e.g. you take the above value which got there randomly. I've done lots of googling and testing and finally found that the query Jay offers in his blog is indeed the fastest solution:
SELECT * FROM Table T JOIN (SELECT CEIL(MAX(ID)*RAND()) AS ID FROM Table) AS x ON T.ID >= x.ID LIMIT 1;

While common ORDER BY RAND() takes 30-40 seconds on my test table, his query does the work in 0.1 seconds. He explains how this functions in the blog so I'll just skip this and finally move to the odd thing.
My table is a common table with a PRIMARY KEY id and other non-indexed stuff like username, age, etc. Here's the thing I am struggling to explain
SELECT * FROM table ORDER BY RAND() LIMIT 1; /*30-40 seconds*/
SELECT id FROM table ORDER BY RAND() LIMIT 1; /*0.25 seconds*/
SELECT id, username FROM table ORDER BY RAND() LIMIT 1; /*90 seconds*/

I was sort of expecting to see approximately the same time for all three queries since I am always sorting on a single column. But for some reason this didn't happen. Please let me know if you any ideas about this. I have a project where I need to do fast ORDER BY RAND() and personally I would prefer to use
SELECT id FROM table ORDER BY RAND() LIMIT 1;
SELECT * FROM table WHERE id=ID_FROM_PREVIOUS_QUERY LIMIT 1;

which, yes, is slower than Jay's method, however it is smaller and easier to understand. My queries are rather big ones with several JOINs and with WHERE clause and while Jay's method still works, the query grows really big and complex because I need to use all the JOINs and WHERE in the JOINed (called x in his query) sub request.
Thanks for your time!

A:
It may have to do with indexing. id is
  indexed and quick to access, whereas
  adding username to the result, means
  it needs to read that from each row
  and put it in the memory table. With
  the * it also has to read everything
  into memory, but it doesn't need to
  jump around the data file, meaning
  there's no time lost seeking. This
  makes a difference only if there are
  variable length columns, which means
  it has to check the length, then skip
  that length, as opposed to just
  skipping a set length (or 0) between
  each row

Practice is better that all theories! Why not just to check plans? :)
mysql> explain select name from avatar order by RAND() limit 1;
+----+-------------+--------+-------+---------------+-----------------+---------+------+-------+----------------------------------------------+
| id | select_type | table  | type  | possible_keys | key             | key_len | ref  | rows  | Extra                                        |
+----+-------------+--------+-------+---------------+-----------------+---------+------+-------+----------------------------------------------+
|  1 | SIMPLE      | avatar | index | NULL          | IDX_AVATAR_NAME | 302     | NULL | 30062 | Using index; Using temporary; Using filesort |
+----+-------------+--------+-------+---------------+-----------------+---------+------+-------+----------------------------------------------+
1 row in set (0.00 sec)

mysql> explain select * from avatar order by RAND() limit 1;
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows  | Extra                           |
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
|  1 | SIMPLE      | avatar | ALL  | NULL          | NULL | NULL    | NULL | 30062 | Using temporary; Using filesort |
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
1 row in set (0.00 sec)

 mysql> explain select name, experience from avatar order by RAND() limit 1;
+----+-------------+--------+------+--------------+------+---------+------+-------+---------------------------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows  | Extra                           |
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
|  1 | SIMPLE      | avatar | ALL  | NULL          | NULL | NULL    | NULL | 30064 | Using temporary; Using filesort |
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+

A: While there's no such thing as a "fast order by rand()", there is a workaround for your specific task.
For getting any single random row, you can do like this german blogger does: http://web.archive.org/web/20200211210404/http://www.roberthartung.de/mysql-order-by-rand-a-case-study-of-alternatives/ (I couldn't see a hotlink url. If anyone sees one, feel free to edit the link.)
The text is in german, but the SQL code is a bit down the page and in big white boxes, so it's not hard to see.
Basically what he does is make a procedure that does the job of getting a valid row. That generates a random number between 0 and max_id, try fetching a row, and if it doesn't exist, keep going until you hit one that does. He allows for fetching x number of random rows by storing them in a temp table, so you can probably rewrite the procedure to be a bit faster fetching only one row.
The downside of this is that if you delete A LOT of rows, and there are huge gaps, the chances are big that it will miss tons of times, making it ineffective.
Update: Different execution times

SELECT * FROM table ORDER BY RAND() LIMIT 1; /30-40 seconds/
SELECT id FROM table ORDER BY RAND() LIMIT 1; /0.25 seconds/
SELECT id, username FROM table ORDER BY RAND() LIMIT 1; /90 seconds/
I was sort of expecting to see approximately the same time for all three queries since I am always sorting on a single column. But for some reason this didn't happen. Please let me know if you any ideas about this.

It may have to do with indexing. id is indexed and quick to access, whereas adding username to the result, means it needs to read that from each row and put it in the memory table. With the * it also has to read everything into memory, but it doesn't need to jump around the data file, meaning there's no time lost seeking.
This makes a difference only if there are variable length columns (varchar/text), which means it has to check the length, then skip that length, as opposed to just skipping a set length (or 0) between each row.

A: I can tell you why the SELECT id FROM ... is much slower than the other two, but I am not sure, why SELECT id, username is 2-3 times faster than SELECT *.
When you have an index (the primary key in your case) and the result includes only the columns from the index, MySQL optimizer is able to use the data from the index only, does not even look into the table itself. The more expensive is each row, the more effect you will observe, since you substitute the filesystem IO operations with pure in-memory operations. If you will have an additional index on (id, username), you will have a similar performance in the third case as well.

A: Why don't you add an index id, username on the table see if that forces mysql to use the index rather than just a filesort and temp table.

A: PrimaryKey's are indexed.  So those are "found" faster.
If you want a random (entire row) but the speed of using the PrimaryKey with the Random function..you can try this (below code):
You use the derived-table to "find" the primary-key of a single random row.  Then you join on it..to get the entire-row.
   Select * from my_thing mainTable
   JOIN
   (
      Select my_thing_key from my_thing order by RAND() LIMIT 1
    ) derived1
    on mainTable.my_thing_key = derived1.my_thing_key;

A: Using RAND() is slower. And * is slower, too.
What I cannot explain is why id, username is slower than *.
This is a strange phenomenon that I cannot replicate.
The fastest method would be to get MAX(id) and store it in memory. Then, using your software pull a random number with it as the ceiling and then in SQL
SELECT id, username FROM table WHERE id > ? LIMIT 1;

and if no row, fall back to
SELECT id, username FROM table LIMIT 1;

If your MySQL installation is not buggy, you should do
SELECT id, username FROM table ORDER BY RAND() LIMIT 1;

with a small-medium data set. Doing two selects cannot be faster. But software is buggy.


text:
Q: How to set a  tag text value from Google Apps Script with JavaScript? How are the elements foo and bar set to the values for their corresponding variables?
html:
<!DOCTYPE html>

  <base target="_top">

  foo is:<input type="text" id="foo" />
  <input type="button" value="sendFoo" onclick="sendFoo()" />

    bar is:
Change only me
but not me

code:
const SPREADSHEET_ID = "1L3Sd-J780mQtb7JYsmJzInI1kMdrQA8GbLspQJ5eVW4";
const SPREADSHEET_NAME = "data";

function setFoo(foo) {
  // Logger.log("setFoo..");
  // Logger.log(foo);
}

function getBar() {
  //  Logger.log("getBar..");
  return "baz";
}

function getUrl() {
  // Logger.log("getUrl..");

  var url = ScriptApp.getService().getUrl();
  return url;
}

function doGet(e) {
  // Logger.log("doGet..");
  var htmlOutput = HtmlService.createTemplateFromFile('FooBarBaz');
  htmlOutput.url = getUrl();
  return htmlOutput.evaluate();
}

Server side logs show foo and bar values when uncommented.  However, there seems no output from console.log("some text"); from within the function defined on the HTML page.

A: If you are trying to get the response of the google script function, then you will have to call that with success handler.
google.script.run.getBar() should be updated as:
var bar = '';
google.script.run.withSuccessHandler((response)=>{
  bar = response;
  console.log(response); // prints 'baz' on console.
}).getBar();

You can use this value to assign to the div or perform some other operations.

A: function sendFoo()
    {
      var foo = document.getElementById("foo").value;
      google.script.run.setFoo(foo);
      google.script.run
      .withSuccessHandler((s) => {
        document.getElementById("bar").innerHTML = s;
      })
      .getBar();
      document.getElementById("foo").value = '';
      document.getElementById("bar").childNodes[0].textContent = "put variable here..";
    }

A: Just including this as a more full answer:
<!DOCTYPE html>

  <base target="_top">

  foo is:<input type="text" id="foo" />
  <input type="button" value="sendFoo" onclick="sendFoo()" />

    foo entered:

    bar is:

does a bit more logging, shows the foo entered, and bar value from server side.
Ideally, would switch to the # query selector notation rather than using id.


text:
Q: Dynamically setting the state is not working in react I am trying to set an array dynamically and render it using useState hook. But it seems the array is not setting. below is my code:
import React, { useState, useEffect } from "react";

export default ({ item }) => {
    const [attachments, setAttachments] = useState([]);
    const setAttachmentValues = function(response){
        setAttachments(response.data);

    }
    const fetchMedia = async ()=> {
        setAttachments([]);
        await apiCall().then((response) => {
            setAttachmentValues(response);
        });
    }

    useEffect(() => {
        fetchMedia();
    }, []);
    return (
        <>

                {(attachments.map((ele) => {

{ele}

                )}
        </>
    )
}

apiCall() will return an array of objects.
setState in this way is working well in some cases. What is the actual issue here?

A: This way you can render data
import React, { useState, useEffect } from 'react';

export default ({ item }) => {
  const [attachments, setAttachments] = useState([]);

  useEffect(() => {

    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((response) => {
        setAttachments(response);
        console.log(response);
      });
  }, []);
  return (
    <>

        {attachments.map(item =>
 {item.username}
 )}

    </>
  );
};


text:
Q: С начала суток часовая стрелка повернулась на угол в α градусов. Определите на какой угол повернулась минутная стрелка с начала последнего часа Подскажите, пожалуйста, алгоритм решения данной задачи:

С начала суток часовая стрелка повернулась на угол в α градусов.
  Определите на какой угол повернулась минутная стрелка с начала
  последнего часа. Входные и выходные данные — действительные числа.

Задача отсюда: тут.
Написал 2 варианта решения, но работает не верно. Вот один из:
a = float(input())
m=int(a*2)%60
print(m*6)

A: Минутная стрелка движется в 12 раз быстрее часовой.
Один час - это поворот часовой стрелки на 30 градусов.

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
  <input type=number ng-model=angle ng-init="angle=0">
  <output>{{angle % 30 * 12}}</output>
</div>

A: За час минутная стрелка совершает полный оборот (1 круг == 360°), а часовая стрелка передвигается на один час (1/12 круга == 30°). Поэтому полный угол поворота минутной стрелки в 12 раз больше, чем угол поворота часовой стрелки.
Угол поворота часовой стрелки с начала последнего часа это остаток от деления на 30:
α = float(input('Угол поворота часовой стрелки: '))
print((α % 30) * 12)  # угол поворота минутной стрелки за последний час

Может быть проще запомнить формулу, если сперва преобразовать угол поворота часовой стрелки в угол поворота минутной стрелки (α * 12), а затем найти угол поворота минутной стрелки, который относится только к последнему часу — последнему обороту (% 360 — один оборот это 360°) как предложил @StateItPrimitive в комментарии:
α = float(input('Угол поворота часовой стрелки: '))
print((α * 12) % 360)  # угол поворота минутной стрелки за последний час

Игнорируя ошибки, относящиеся к вычислениям, использующим числа с плавающей точкой, результат обоих формул одинаковый.

A: *

*За сутки часовая стрелка поворачивается на 720 градусов, то есть за час на 30.

*За час минутная стрелка поворачивается на 360 градусов

*Получаем пропорцию (на C# - pithon не знаю)
int dHH = alpha%30;

double degMM = dHH/30. * 360;

A: А можно подойти так: узнать разность между всем углом, который прошла минутная стрелка (в 12 раз быстрее, т.е. a*12) и углом, до начала ближайшего часа (a*12//360)*360. Небольшая ремарка: будьте внимательны, оператор // возвращает целое от деления, поэтому сокращать ничего не нужно.

A: h = float(input('hour gradus: '))

min = ((h%30)*6)*2

print(min)


text:
Q: Direct link to sample data? Is there a direct link to the sample data for CE 1.9.1/1.9.2?
I'm trying to download it directly to the servers using wget but the links on http://devdocs.magento.com/guides/m1x/ce18-ee113/ht_magento-ce-sample.data.html are broken and the normal download page has a user interface that hides the link.
My local internet connection is slow enough for the download to take about 20 minutes and the upload will probably take well over an hour.

A: Both 1.9.1 and 1.9.2 use the same sample data package.
http://sourceforge.net/projects/mageloads/files/assets/1.9.1.0/magento-sample-data-1.9.1.0.tar.gz

A: There is also this project which contains highly optimised (compressed) sample data https://github.com/Vinai/compressed-magento-sample-data


text:
Q: p2 repository only with feature content and no dependencies I need to create p2 repositories to add extra software in my application.
for instance I want to externalize all i18n bundle, so I have a set of features with only i18n fragments.
The way I do that is from a complete p2 repository that was build by pde and containt the product and the i18n plugins and features.
I try to use the p2.mirror ant task to create a p2 repository with only the i18n fragments but the problem is that it always embbed the host bundles that those i18n bundle depend on. This makes my p2 repo huge because it has most of my application along with the i18n.
<p2.mirror source="file://${build.repo.path}" destination="file://${i18n.repo.path}">
    <iu id="org.talend.i18n.all-feature.feature.group" version="" />
</p2.mirror>

Is there a way to create a p2 repository including only the bundle that are referenced in a given feature and not the ones that host them ?

A: You need to add so-called "slicing options" and specify that you only want strict version range dependencies:
<p2.mirror ...>
    <slicingoptions followStrict="true" />
</p2.mirror>

The inclusion relationship between features and plug-ins is encoded in p2 as strict version range dependency, so with this option you should only get the feature and its included plug-ins.
Note that p2 relies on the publishers to correctly translate the information from the feature.xml. If you use a non-standard publisher or influence the publishing via a p2.inf, the strict version range dependencies may not correspons 1:1 to the inclusions. In this case, it is not possible to achieve what you want. p2 mirroring will only operate on p2 metadata – there is no option to make it look at the feature.xml again.


text:
Q: Cannot persist many-to-many relationship correctly Article and Image have many-to-many relationship and their intermediate table is ArticleImage. I expect I'll see 1 rows in Article table, 3 rows in Image table, and 3 rows in ArticleImage table. Article and ArticleImage part are working as expected, however, there is 0 row in Image table and the foreigh-key column 'image_id' in ArticleImage table of that 3 newly-added rows are 'NULL'. What am I missing to persist rows in Image table correctly?
(there is no error printed)
My code:
db_session = some_function()  # get connection to database here
try:
    article = Article()
    db_session.add(article)
    article.name = 'new post #1'
    article.author = 'pojan'
    article.images.append(Image('img1.jpg'))
    article.images.append(Image('img2.jpg'))
    article.images.append(Image('img3.jpg'))
    db_session.merge(article)
    db_session.commit()

    print db_session.query(Article).count()       # 1
    print db_session.query(ArticleImage).count()  # 3
    print db_session.query(Image).count()         # 0 <- error here, images are not added

except Exception as e:
    print e

I have also tried the following code, now the Image would be added to database, but the image_id column in ArticleImage still remain as NULL:
    article = Article()
    db_session.add(article)
    article.name = 'new post #1'
    article.author = 'pojan'

    image1 = Image('img1.jpg')
    image2 = Image('img2.jpg')
    image3 = Image('img3.jpg')
    db_session.add(image1)
    db_session.add(image2)
    db_session.add(image3)

    article.images.append(image1)
    article.images.append(image2)
    article.images.append(image3)
    db_session.merge(article)
    db_session.commit()

My model:
class Image(EntityClass):
    attributes = ['id', 'name', 'path']

    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)
    path = Column(String(255), nullable=False, unique=True)

    def __init__(self, name):
        self.name = name
        self.path = '/root/' + name

class ArticleImage(EntityClass):

    article_id = Column(Integer, ForeignKey('article.id'))
    image_id = Column(Integer, ForeignKey('image.id'))
    image = relationship(Image)
    position = Column(Integer)

class Article(EntityClass):

    attributes = ['id','name','author']

    id = Column(Integer, primary_key=True)

    _images = relationship(ArticleImage,
             order_by=[ArticleImage.position],
             collection_class=ordering_list('position'))
    images = association_proxy('_images', 'image')

    name = Column(String(255), nullable=False)
    author = Column(String(255), nullable=False)

(the design is base on an article I found on internet, and I made some minor changes)

A: According to the article you refer to, you should also add a constructor in ArticleImage to associate ArticleImage with Image when an ArticleImage oject is created, otherwise ArticleImage would never know which image row it should refer to.
class ArticleImage(EntityClass):

    article_id = Column(Integer, ForeignKey('article.id'))
    image_id = Column(Integer, ForeignKey('image.id'))
    image = relationship(Image)
    position = Column(Integer)

    def __init__(self, image=None):
        self.image = image

A: You missed primary key in ArticleImage compared to the example you give.
I would get

sqlalchemy.exc.ArgumentError: Mapper Mapper|ArticleImage|article_image could not assemble any primary key columns for mapped table 'article_image'

with your ArticleImage code.


text:
Q: How to convert an image to Base64 encoding How can I convert an image from a URL to Base64 encoding?

A: I think that it should be:
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

A: Also use this way to represent an image in Base64-encoded format...
Find the PHP function file_get_content and next use the function base64_encode.
And get the result to prepare str as data:" . file_mime_type . " base64_encoded string. Use it in the img src attribute. The following code ma be helpful:
// A few settings
$img_file = 'raju.jpg';

// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;

// Echo out a sample image
echo '';

A: Here is the code for uploading to encode and save it to a MySQL database:
if (!isset($_GET["getfile"])) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Error: " . $_FILES["file"]["error"] . "
";
    } else {
        move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);

        $bin_string = file_get_contents($_FILES["file"]["name"]);
        $hex_string = base64_encode($bin_string);
        $mysqli = mysqli_init();

        if (!$mysqli->real_connect('localhost', 'root', '', 'arihant')) {
            die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
        }

        $mysqli->query("INSERT INTO upload(image) VALUES ('" . $hex_string . "')");
    }
}

For showing the image, use this:
echo "";

A: Just in case you are (for whatever reason) unable to use curl nor file_get_contents, you can work around:
$img = imagecreatefrompng('...');
ob_start();
imagepng($img);
$bin = ob_get_clean();
$b64 = base64_encode($bin);

A: You can also do this via cURL. You just need a path to an image file and pass it to the function given below...
public static function getImageDataFromUrl($url)
{
    $urlParts = pathinfo($url);
    $extension = $urlParts['extension'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $base64 = 'data:image/' . $extension . ';base64,' . base64_encode($response);
    return $base64;
}

A: Easy:
$imagedata = file_get_contents("/path/to/image.jpg");
             // alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

Bear in mind that this will enlarge the data by 33%,
and you'll have problems with files whose size exceed your memory_limit.

A: <img src="data:image/png;base64,<?php echo base64_encode(file_get_contents("IMAGE URL HERE")) ?>">

I was trying to use this resource, but I kept getting an error. I found the code above worked perfectly.
I just replaced "IMAGE URL HERE" with the URL of your image - http://www.website.com/image.jpg

A: Very simple and to be commonly used:
function getDataURI($imagePath) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $type = $finfo->file($imagePath);
    return 'data:' . $type . ';base64,' . base64_encode(file_get_contents($imagePath));
}

// Use the above function like below:
echo '';
echo '';

Note: The MIME type of the file will be added automatically (taking help from this PHP documentation).

A: Here is an example using a cURL call... This is better than the file_get_contents() function. Of course, use base64_encode().
<?php
    $url = "http://example.com";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
?>

<img src="data:image/png;base64,<?php echo base64_encode($output);?>">


text:
Q: Can't access nestjs app deployed on AWS Amplify I've "successfully" deployed my nestjs app to AWS Amplify, but I can't access the endpoints.  It's only returning 404 (as seen on the access log)

Do I need to make any changes to the source code or package.json for this?
You can see the deployed code here


text:
Q: Finite dimensional representation of infinite group cannot be unitary: example with $\mathbb R$ Consider the representation of the group of real numbers $\mathbb R$ given by
$$ \rho (x) = \begin{pmatrix} 1 & x \\ 0 & 1 \end{pmatrix} $$
for $x \in \mathbb R$.
How can we see that this representation cannot be equivalent to a unitary representation?

A: Every unitary matrix is diagonalizable, but $\rho(x)$ is not diagonalizable unless $x=0$ (its only eigenvector (up to scaling) is $(1,0)$).


text:
Q: Observing Array Properties in Aurelia I have a property on my class:
class Control {
    @bindable households;

    get people() {
        return households
            .map(household => househould.people)
            .reduce((g1, g2) => g1.concat(g2), []);
    }
}

Which I use to compute a collection of all people[] within all households which is then rendered here:

        ${person.firstName} ${person.lastName} - ${person.phone}

I need the list to update whenever people are added to a household, OR if any of the rendered properties, firstName, lastName, phone, for any element in the computed collection is updated. How can I do this in Aurelia? If I use @computedFrom() it will not detect changes to elements of the array, and since the list of people in all households is dynamic, I cannot just create an observer for each element without creating a system for managing when observers should be subscribed / unsubscribed.

A: Right as I was about to give up on being able to Google for a solution, Aurelia Signaling came to the rescue. This code ended up working for me:

        ${renderPersonInfo(person) & signal: 'example-signal'}

And the class:
import {BindingSignaler} from 'aurelia-templating-resources';

@inject(BindingSignaler)
class Control {
    @bindable households;

    constructor(bindingSignaler) {
        this.bindingSignaler = bindingSignaler;
        //Obviously, you can have this trigger off any event
        setInterval(() => this.bindingSignaler.signal('example-signal'), 1000);
    }

    get people() {
        return households
            .map(household => househould.people)
            .reduce((g1, g2) => g1.concat(g2), []);
    }
}

A: Use Dirty Checking
Leave off @computedFrom() and you'll achieve the desired behavior.
export class App {
  @bindable households;
  get people() {
    const households = this.households || []; // Make sure househoulds is defined.
    return households.reduce((people, household) => people.concat(household.people), []);
  }
}

https://gist.run/?id=040775f06aba5e955afd362ee60863aa

A: You must avoid dirty-checking as far as possible, signals are the perfect option for your scenario. Just bear in mind that if you want to use computedFrom on an array you can do so by watching its length property for instance rather than  dirtyChecking, sth like the following @computedFrom("myArray.length")


text:
Q: Deploying dynamic Nextjs + Nodejs application inside docker using caddy server I am currently developing a simple portfolio app and my app structure is like this.
Nextjs/client,
Nodejs/server,
Mongodb/db
Nextjs is hosted locally on port 3001, Nodejs app on 5000. Whenever nextjs needs to fetch any api it calls nodejs application. All the things are configured inside docker. I am very new to deploying nextjs application and have recently used caddy server which has automatic https.
I am able to deploy the nextjs application statically using commands
next build
next export

The statically exported file called index.html inside out directory of nextjs application is pointed to caddy server on port 80 and 443. Statically exported app doesn't support api routes which I recently came to know. I tried next build and next start command to generate a dynamic production build inside .next directory. The main problem is How do I point my dynamically generated nextjs application in caddy configuration inside docker container. My present caddy configuration looks like
www.example.com:443 {
 tls xyz@email.com
 root * /srv
 route {
   reverse_proxy /api* api-server:5000
   try_files {path} {path}/ /index.html
   file_server
   }
}

I am looking for hints especially related to proxy server.
Thank you in advance

A: I'm assuming the api url in your frontend looks like this http://localhost:5000 (based on your youtube comment here) which won't work if you're accessing your dockerized app from a remote computer (in this case your computer, since I'm assuming your app is hosted). Try changing it to https://www.example.com:5000 and rebuild your image.


text:
Q: 'Given a choice' vs.'If I had to choose' Can the phrases given a choice and if I had to choose be used interchangeably?
I made a statement like "Given a choice, I would do this," my original intention being to select that over the other option. But it was misinterpreted as "I did not want to do the other option," and I was told that I should have used "If I had to choose between the two."
Some inputs would be highly appreciated

A: "Given a choice" considers the situation where you have the freedom of choosing as a hypothetical. It therefore suggests that you would very strongly favour the option you then describe.
Consider what it implies in the negative; that the only reason you would ever go for the other possibility is that you had no choice (you either had to do both, or had the decision made for you by factors outside your control).
"If I had to choose" considers an almost opposite hypothetical situation; you are forced to choose between the two, and the option of doing both or doing neither is not allowed. It therefore suggests you would very much prefer to do both or very much prefer to do neither (just which may or may not be clear from context).


text:
Q: how to bind value to hyperlink in gridview in c# code behind I have a custom grid on which i have binded data in my c# code behind. I have given a hyperlink field to one of my column. If i click the hyperlink value, it should navigate to the details page of that hyperlink value. The code is given below,
  protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink myLink = new HyperLink();
            myLink.Text = e.Row.Cells[2].Text;
            e.Row.Cells[2].Controls.Add(myLink);
            myLink.NavigateUrl = "Estimation.aspx?EstimateID=" + EstimateID + "&VersionNo=" + VersionNo;
        }
    }

If i click the link, the page is getting navigated, but i am not getting the details which are already pre-loaded in that page. Please give me suggestions on how to incorporate this.
Thanks

A: You can use this to redirect, read this
<asp:HyperLink ID="HyperLink1"
               runat="server"
               NavigateUrl="Default2.aspx">
                 HyperLink
</asp:HyperLink>

to add attribute with link just add
HyperLink1.Attributes.Add ("");

A: You need to do a small change in the RowDataBound event
myLink.Attributes.Add("href"," your url");

A: You need to fetch the values for EstimateID and VersionNo from the grid row data. Take a look at the documentation for GridViewRowEventArgs and you'll see there's a .Row property.
So your code needs to be something like:
myLink.NavigateUrl = "Estimation.aspx?EstimateID=" + e.Row.Cells[4].Text + "&VersionNo=" + e.Row.Cells[5].Text;

Or, maybe you need to get to the data item associated with the grid row, in which case take a look at e.Row.DataItem, the GridViewRow.DataItem property. This DataItem will need to be cast to the type of data you've bound to the grid in order to fetch the data from it, which might be something like:
((MyCustomDataRow)e.Row.DataItem).EstimateID

A: Try below solution :
Page-1 that is your list page :
ASPX code :
<asp:GridView ID="GridView1" runat="server"
        onrowdatabound="GridView1_RowDataBound">
    <Columns>
    <asp:TemplateField>
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink>
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>

Code Behind :
protected void Page_Load(object sender, EventArgs e)
    {
        List<Data> lstData = new List<Data>();
        for (int index = 0; index < 10; index++)
        {
            Data objData = new Data();
            objData.EstimateID = index;
            objData.VersionNo = "VersionNo" + index;
            lstData.Add(objData);
        }

        GridView1.DataSource = lstData;
        GridView1.DataBind();
    }

    public class Data
    {
        public int EstimateID { get; set; }
        public string VersionNo { get; set; }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink HyperLink1 = e.Row.FindControl("HyperLink1") as HyperLink;
            HyperLink1.NavigateUrl = "Details.aspx?EstimateID=" + e.Row.Cells[1].Text + "&VersionNo=" + e.Row.Cells[2].Text;
        }
    }

Page-2 that is your details page :
Code behind :
protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Request.QueryString["EstimateID"].ToString());
        Response.Write(Request.QueryString["VersionNo"].ToString());
    }


text:
Q: Apply two regex rules in match() var url = document.referrer;
var a=document.createElement('a');
a.href=url;
var path = a.pathname;

Let's say path is this:
/cat-dog-fish/

I want to remove leading and trailing slashes, if they exist, else do nothing.
I can do this (removes trailing slash):
a.pathname.replace(/\/$/,'')

Or this (removes leading slash)
a.pathname.replace(/^\//,'')

But how do I remove both at once, in a oner, if they exist?

A: A regex literal like /^\/|\/$/g can be used to replace with empty string, or you may use /^\/([^]*)\// (match /, then any 0+ chars up to the last / capturing what is in-between the slashes) to replace with $1:

var s = "/cat-dog-fish/";
console.log(s.replace(/^\/|\/$/g, ''));
console.log(s.replace(/^\/([^]*)\/$/, '$1'));

Note:

*

*^\/ - matches the start of string and a / right there

*| - means OR

*\/$ - matches a / at the end of string

*([^]*) - is a capturing group (...) that captures 0 or more (*) any characters as [^] means not nothing.

A:

var a="/cat-dog-fish/";

var d = a.replace(new RegExp("(^\/|\/$)",'g'),'');

console.log(d);

    a.pathname.replace(new RegExp("(^\/|\/$)",'g'),'');


text:
Q: Programmatically insert a List as a webpart in a webpart page in WSS 3.0 I tried searching on the net to programmatically insert a List as a webpart in a webpart page but was not lucky enough.
Any thoughts or ideas how i could Programmatically insert a List as a webpart in a webpart page
Many Thanks!

A: First add these using statements.
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

Then in your code
// First get the list
SPSite site = new SPSite("http://myserver");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["MyCustomlist"];

// Create a webpart
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Top";   // Replace this ith the correct zone on your page.
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();

// Get the web part collection
SPWebPartCollection coll =
    web.GetWebPartCollection("default.aspx",    // replace this with the correct page.
    Storage.Shared);

// Add the web part
coll.Add(wp);

If you want to use a custom view, try playing with this:
SPView view = list.GetUncustomizedViewByBaseViewId(0);
wp.ListViewXml = view.HtmlSchemaXml;

Hope it helps,
W0ut

A: You need to perform two steps to add a web part to a page. First you have to create the list you want to show on the page. Therefore you can use the Add() method of the web site's list collection (SPListCollection).
To show the list on the web part page you have to add a ListViewWebPart to the web part page using the SPLimitedWebPartManager of the page.

A: To make this more re-usable as part of a feature receiver, you could pass in the splist and spview as part of a method:
static public void AddEventsListViewWebPart(PublishingPage page, string webPartZoneId, int zoneIndex, string webPartTitle, PartChromeType webPartChromeType, string listName, string viewname)
{
     using (SPLimitedWebPartManager wpManager = page.ListItem.File.GetLimitedWebPartManager(PersonalizationScope.Shared))
     {
         SPWeb web = page.PublishingWeb.Web;
         SPList myList = web.Lists.TryGetList(listName);
         using (XsltListViewWebPart lvwp = new XsltListViewWebPart())
         {
             lvwp.ListName = myList.ID.ToString("B").ToUpperInvariant();
             lvwp.Title = webPartTitle;
             // Specify the view
             SPView view = myList.Views[viewname];
             lvwp.ViewGuid = view.ID.ToString("B").ToUpperInvariant();
             lvwp.TitleUrl = view.Url;
             lvwp.Toolbar = "None";
             lvwp.ChromeType = webPartChromeType;
             wpManager.AddWebPart(lvwp, webPartZoneId, zoneIndex);
         }
     }
}

And then call it during feature activation:
AddEventsListViewWebPart(welcomePage, "Right", 1, "Events", PartChromeType.TitleOnly, "Events", "Calendar");


text:
Q: VLC from Python reciving a stream   #!/usr/bin/python3
  import vlc
  p = vlc.MediaPlayer('https://stream.dxbh.net/AWR360Iloilo')
  p.play()

This is my python program. It does nothing. No error message. I am told the website is a shoutcast server. If I put the url in the browser, it works fine.
I am using Linux mint 20.3
I did  pip install python-vlc
Any ideas what I am doing wrong?
It's not complicated. I got the code from SO.  But there are no errors showing.

A: The program quits right after you start playing. It won't wait for your media to complete. You need to add something to wait. A minimal solution would be:
import time

while True:
    time.sleep(1)


text:
Q: use existing function in arcmap use VBA in Arcobjects I have a UI tool button, I would like to get and use the existing function (select elements tool) in Arcmap when I activate this button, does anybody know that how to call the existing function using Vb arcobjects ??

A: You can use the ArcMap Commands, eg.
  Dim pUID As New UID
  Dim pCmdItem As ICommandItem
  ' Use the GUID of the Save command
  pUID.Value = "{161496AD-AC99-11D2-87F8-0000F8751720}"
  ' or you can use the ProgID
  ' pUID.Value = "esriArcMapUI.EditSelectAllCommand"
  pUID.SubType = 3
  Set pCmdItem = Application.Document.CommandBars.Find(pUID)
  pCmdItem.Execute

Or, check out this forum post to grab elements on mouse up event.
http://forums.esri.com/Thread.asp?c=93&f=993&t=158293

A: Not sure if I understand you correctly, but would it not make sense to explicitly GET the tool you want...just in case the user has not selected it?  It's OK to set it if it's already set.
Dim pCmdBar As ICommandBar
Dim pCmdItem As ICommandItem
Dim pUID As New UID

Set pCmdItem = Document.Parent.Document.CommandBars.Find(ArcID.PageLayout_SelectTool)
Set ThisDocument.Parent.CurrentTool = pCmdItem

Note that ArcID.PageLayout_SelectTool is for ArcGIS 10, in 9.3 it was Select_Elements I think.
Hope this helped.


text:
Q: Jquery Plugin to Generate Tree based on Level priority I want to develop a tree based on Level priority. Please look at the below image. How to generate this with all lines(relations) using jquery.

Please suggest me any plugins which are nearest functioning to it.
Thank You

A: use this plug in. This is using html5 canvas and jquery


text:
Q: How are Aluminium objects made in the first Mistborn Trilogy? In the third mistborn book the main characters get their hands on some Aluminium from a set of cutlery from a noble's house.

It is stated that is is incredibly rare and valuable, much more so than gold. I don't recall how it compared the Atium (did they make a comparison?)
This makes sense - Aluminium is really hard to refine.
To my surprise, Native Aluminium can be found naturally occuring, so that explains where it comes from.
(Is that the explaination given in the book?)
Indeed I suspect Native Aluminum nuggets would be of a reasonable size for burning.
But how is it shaped into cutlery?
You can't heat it, or it will ignite. (That the reason we use MIG welding today),
So how was it shaped?  (I honestly can't remember if the book went in to this.
Did they have to find large pieces and cold forge it? It seems like Aliminum would be too brittle for that.)
So my three questions:
In the original Mistborn trilogy, (Misborn - the Final Empire)

*

*How was the raw Aluminum produced? (native nuggets?)

*How was Aluminium shaped into objects

*How does the value of Aluminum compare to Atium?

A: I haven't read the books, so in-universe this is all speculation.
However, it is certainly possible to melt and cast aluminum with primitive technology: http://www.backyardmetalcasting.com/
Also, the first historic production of aluminum was done by chemical means (without electricity), although of course this was very expensive and inefficient.
I'm not sure why you think aluminum would ignite. Perhaps you are thinking of magnesium?

A: There was no in-universe explanation for how aluminum was worked or how it was found in the wild that I recall.  It's possible it is a metal that occurs naturally at a higher frequency in that world than in our own (even while being rare).  The wikipedia article for Allomancy notes that it is a "pure metal", which I take to mean occurs naturally since metals there are noted as either being pure, or alloy.
I also do not recall a comparison to Atium.  It's in universe worth is surely less than Atium.  For one, you don't see anyone sporting atium cookware/figurines/etc.  Atium is simply too powerful and too jealously horded to be used like that.  Breaking out the Atium-ware for a big dinner party wouldn't look like showing off.  It would look stupid and reckless.  While Aluminum had an allomatic (I wonder if I'm saying that right) purpose (or tactical use, anyway), it as limited.  Atium's importance, generally, is far greater.  I would estimate the value of atium to be much, much higher than the value of aluminum as a result

A: Aluminum was found naturally in volcanoes according to the newest Mistborn book, Bands of Mourning.

"(...) the metal is now common. Bauxite refining, modern chemical processes, these have given us access to metals on a level that was never before possible. Why, the Last Obligator's autobiography explains that early aluminum was harvested from the inside of the Ashmounts!"

A: Atium was invaluable.  There's no amount of aluminium that a noble would have traded for a single bead of atium.


text:
Q: Is UMS (User-Mode Scheduling) officially documented outside of docs.microsoft.com? I've been struggling for weeks to understand UMS, but there's almost no info on it.
The only solid thing I could find was a short page on msdn (https://learn.microsoft.com/en-us/windows/win32/procthread/user-mode-scheduling), a few throwaway mentions in Windows Internals and Windows 10 System Programming, and a video on channel9 (reuploaded to Youtube https://www.youtube.com/watch?v=PYlP8MXRCZc).
Are there any first party (or even third party) sources that explain User Mode Scheduling in detail?
If not, why is MS so quiet about this?


text:
Q: Where are the time dilatational effects of orbital motion and gravitational acceleration equal? Nearly four years ago, upon hearing of the observation of time dilation in two optical atomic clocks at an elevation one metre apart, due to acceleration towards earths centre of gravity by Chou, C. W.; Hume, D. B.; Rosenband, T.; Wineland, D. J. I wondered where the point would be, at which time dilation caused by acceleration toward the earth gives way to time dilation caused by acceleration around the earth, via orbital velocity. (I mean the point at which the two effects are at equilibrium with each other.)
I asked a friend who is a physicist, he got back to me almost immediately, fascinated by his back of an envelope calculations that this point is the Clarke orbit, or the geosynchronous orbit.
If for instance the rotation velocity of earth were a slightly different speed, the result would be different, and no relationship apparent. I think there may be a very interesting relationship waiting to be revealed.
Is there a physical or mathematical relationship? And if so, what is it? Not being a mathematician (I'm an artist) I'm not capable of doing the math, but this has fascinated me ever since.

A: Let $\Delta_S$ and $\Delta_G$ be the time dilation effects due to General Relativity (gravity) and Special Relativity (motion) respectively (i.e. the clock rate on the satellite due to SR and GR is $1 - \Delta_S + \Delta_G$, signs chosen for simplicity). If these are small, they can be approximated as :
\begin{eqnarray}
\Delta_S &=& 1 - \sqrt{1 - \frac{v^2}{c^2}} &\approx& \frac{v^2}{2c^2} \\
\Delta_G &=& \sqrt{1 - \frac{2GM}{R c^2}} - \sqrt{1 - \frac{2GM}{r c^2}} &\approx& \frac{G M}{R c^2} - \frac{G M}{r c^2}
\end{eqnarray}
Where $v$ is the orbital velocity, $r$ the orbital radius, $R$ the radius of the earth, and $M$ its mass. Note that $\Delta_S$ and $\Delta_G$ act in opposite directions. Setting the 2 equal, and recalling that for a circular orbit we have $v^2 = \frac{GM}{r}$, we obtain :
\begin{eqnarray}
\frac{G M}{R c^2} - \frac{G M}{r c^2} &=& \frac{GM}{2 r c^2} \\
r &=& \frac{3 R}{2}
\end{eqnarray}
This is about $3,000$ km higher than the earth's surface, well below the $35,000$ km of geostationary orbits. By then, the GR effect largely dominates over the SR one.
tl;dr There is such an orbit but it is actually much lower than the Clarke orbits you suggested.


text:
Q: ModuleNotFoundError: No module named 'PySide2.QtWebKitWidgets' I have installed Anaconda environment on CentOS and Windows.
And have installed PySide2 using conda.
The problem is my project run well in CentOS, but in Windows, it shows "ModuleNotFoundError: No module named 'PySide2.QtWebKitWidgets'" when run server.
Conda, pyhon, pip, PySide2 and PyQt5 's version are same in Both OS.
I don't know what's wrong?

A: I experienced the same problem when creating a sample app using pyside2 where the error message was as follows:
Traceback (most recent call last):
File "browse.py", line 7, in
File "/usr/local/lib/python3.7/dist-packages/shiboken2/files.dir/shibokensupport/feature.py", line 146, in _import
File "/home/pjm/prj/eis3/gui/browser.py", line 15, in
File "/usr/local/lib/python3.7/dist-packages/shiboken2/files.dir/shibokensupport/feature.py", line 146, in _import
ModuleNotFoundError: No module named 'PySide2.QtWebKitWidgets'
So the issue is that the version of designer or pyside2-uic is using the old QtWebKitWidgets rather than what I believe is the more modern QtWebEngineView.
I actually think it is my version of designer which produces the following extract:
  <customwidget>
   <class>QWebView</class>
   <extends>QWidget</extends>
   <header>QtWebKitWidgets/QWebView</header>
  </customwidget>

In any event I "fixed" this by means of a sed script in a makefile as follows:
browser.py: browser.ui makefile
    pyside2-uic  $< --output temp.txt
    cat temp.txt | sed s/QtWebKitWidgets/QtWebEngineWidgets/g | sed s/QWebView/QWebEngineView/g > $@

My version of designer was 5.11.3 which is installed on debian which may explain this.  In short I think the problem may be the version of designer that was used to create the ui file.

A: QtWebkit is deprecated, you can try to build PySide2 from scratch enabling the module in the CMakeLists.txt file.


text:
Q: Ping linux c++ сокеты Есть реализация пингования (для проверки наличия соединения между клиентом и сервером), прочёл несколько статей, видел разные реализации, остановился на этой. В общем если пинг норм, возвращается 0, а если нет, то 1.
У меня возвращается всегда 0, я пробовал разные хосты, реальные по типу google.com и локальный 127.0.0.1.
Проверял при наличии соединения с сервером и без, результат один и тот же...Не понимаю, что я делаю не так..Если что, всё запускается корректно с правами root, так что не нужно удивляться, почему необработанный (сырой) сокет создаётся.
    #include <arpa/inet.h>
    #include <sys/types.h>
    #include <sys/param.h>
    #include <sys/socket.h>
    #include <sys/file.h>
    #include <sys/time.h>
    #include <netinet/in_systm.h>
    #include <netinet/in.h>
    #include <netinet/ip.h>
    #include <netinet/ip_icmp.h>
    #include <netdb.h>
    #include <unistd.h>
    #include <sys/ioctl.h>
    #include <iostream>
    #define PACKETSIZE  64
    struct packet
    {
        struct icmphdr hdr;
        char msg[PACKETSIZE-sizeof(struct icmphdr)];
    };

    int pid=-1;
    struct protoent *proto=NULL;
    int cnt=1;

    /*--------------------------------------------------------------------*/
    /*--- checksum - standard 1s complement checksum                   ---*/
    /*--------------------------------------------------------------------*/
    unsigned short checksum(void *b, int len)
    {
        unsigned short *buf = (unsigned short*)b;
        unsigned int sum=0;
        unsigned short result;

        for ( sum = 0; len > 1; len -= 2 )
            sum += *buf++;
        if ( len == 1 )
            sum += *(unsigned char*)buf;
        sum = (sum >> 16) + (sum & 0xFFFF);
        sum += (sum >> 16);
        result = ~sum;
        return result;
    }

    /*--------------------------------------------------------------------*/
    /*--- ping - Create message and send it.                           ---*/
    /*    return 0 is ping Ok, return 1 is ping not OK.                ---*/
    /*--------------------------------------------------------------------*/
    int ping(const char *adress)
    {
        const int val=255;
        int i, sd;
        struct packet pckt;
        struct sockaddr_in r_addr;
        int loop;
        struct hostent *hname;
        struct sockaddr_in addr_ping,*addr;

        pid = getpid();
        proto = getprotobyname("ICMP");
        hname = gethostbyname(adress);
        bzero(&addr_ping, sizeof(addr_ping));
        addr_ping.sin_family = hname->h_addrtype;
        addr_ping.sin_port = 0;
        addr_ping.sin_addr.s_addr = *(long*)hname->h_addr;

        addr = &addr_ping;

        sd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); // пробовал с PF_INET, результат тот же
        if ( sd < 0 )
        {
            perror("socket");
            return 1;
        }
        if ( setsockopt(sd, SOL_IP, IP_TTL, &val, sizeof(val)) != 0)
        {
            perror("Set TTL option");
            return 1;
        }
        if ( fcntl(sd, F_SETFL, O_NONBLOCK) != 0 )
        {
            perror("Request nonblocking I/O");
            return 1;
        }

        for (loop=0;loop < 10; loop++)
        {

            socklen_t len=sizeof(r_addr);

            if ( recvfrom(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&r_addr, &len) > 0 )
            {
                return 0;
            }

            bzero(&pckt, sizeof(pckt));
            pckt.hdr.type = ICMP_ECHO;
            pckt.hdr.un.echo.id = pid;
            for ( i = 0; i < sizeof(pckt.msg)-1; i++ )
                pckt.msg[i] = i+'0';
            pckt.msg[i] = 0;
            pckt.hdr.un.echo.sequence = cnt++;
            pckt.hdr.checksum = checksum(&pckt, sizeof(pckt));
            if ( sendto(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)addr, sizeof(*addr)) <= 0 )
                perror("sendto");

            usleep(300000);

        }

        return 1;
    }
int main() {
  std::cout << ping("127.0.0.1") << std::endl;
  getchar();
  return 0;
}

Я проверил поле msg в пакете при чтении функцией recvfrom, оно не совпадает со значением при отправке..Но так всегда, что есть подключение к серверу, что нет...


text:
Q: Strange behaviour of Spring Cacheable returning null after the first call I encouter a strange problem with one method.. no idea why this one, because it is the same as the other one..
I'm using Redis for the cache, but redis doesn't return me the cached response after the first call..
Springboot parent version : 2.6.3
    @GetMapping(value = "/groups", produces = APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.OK)
    @Cacheable(value = "groups")
    public GroupsDTO getAllGroups() {
        return iGroupsAndUsersService.getAllGroups();
    }

    @GetMapping(value = "/users", produces = APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.OK)
    @Cacheable(value = "users")
    public UsersDTO getAllUsers() {
        System.out.println("here"); // is displayed the first call
        return iGroupsAndUsersService.getAllUsers();
    }

For my first call to /users i get my list of users within 1.5 seconds so OK.
The second call and other one i get null like this (http 200) :
{
    "items": null
}

I can see that my method as been called only one time, but unlike other methods, the cache is not returning me the cached response..
The endpoint /groups is working without any problem.. these methods do the same job...
public interface IGroupsAndUsersService {

        GroupsDTO getAllGroups();

        UsersDTO getAllUsers();

}

Users
@Data
public class Users {
  List<Item> items;

  @Data
  public static class Item {
    public Metadata metadata;
    public String fullName;
  }

  @Data
  public static class Metadata {
    public String name;
  }

}

public class UsersDTO extends Users implements Serializable{

}