text:
Q: How can I use the native error icon and error sound in Windows using wxPython? This simple line:
wx.MessageBox('Foo', 'Bar', wx.OK | wx.ICON_ERROR)

Gives me a message box with an error icon and the Windows error noise (this is not the same noise as wx.Bell()). I would like to create a custom error dialog for uncaught exceptions, where the traceback is available in a text control and such, and I would like to include both the Windows error icon and the noise. I know that both differ between versions of Windows, and the error noise can even be customized.
Is there any straight-forward way of using these native Windows resources with wxPython? Bonus question; if the answer is no, what would be the most straight-forward way of doing what I'm trying to do?

Results after accepted answer:
I just wanted to show off the results after Anonymous Coward's excellent answer, as they far exceeded my expectations. This is the error dialog that now pops up on unhandled exceptions (on Windows 8):

It also packs the modern Windows "UNNK!" error sound. This is the code behind the dialog. I put it in a separate module that overrides sys.excepthook when it's imported:
"""This module, when imported, overrides the default unhandled exception hook
with one that displays a fancy wxPython error dialog."""

import sys
import textwrap
import traceback
import winsound

import wx

def custom_excepthook(exception_type, value, tb):
    dialog = ExceptionDialog(exception_type, value, tb)
    dialog.ShowModal()

# Override sys.excepthook
sys.excepthook = custom_excepthook

class ExceptionDialog(wx.Dialog):
    """This class displays an error dialog with details information about the
    input exception, including a traceback."""

    def __init__(self, exception_type, exception, tb):
        wx.Dialog.__init__(self, None, -1, title="Unhandled error",
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)

        self.SetSize((640, 480))
        self.SetMinSize((420, 200))

        self.exception = (exception_type, exception, tb)
        self.initialize_ui()

        winsound.MessageBeep(winsound.MB_ICONHAND)

    def initialize_ui(self):
        extype, exception, tb = self.exception

        panel = wx.Panel(self, -1)

        # Create the top row, containing the error icon and text message.
        top_row_sizer = wx.BoxSizer(wx.HORIZONTAL)

        error_bitmap = wx.ArtProvider.GetBitmap(
            wx.ART_ERROR, wx.ART_MESSAGE_BOX
        )
        error_bitmap_ctrl = wx.StaticBitmap(panel, -1)
        error_bitmap_ctrl.SetBitmap(error_bitmap)

        message_text = textwrap.dedent("""\
            I'm afraid there has been an unhandled error. Please send the
            contents of the text control below to the application's developer.\
        """)
        message_label = wx.StaticText(panel, -1, message_text)

        top_row_sizer.Add(error_bitmap_ctrl, flag=wx.ALL, border=10)
        top_row_sizer.Add(message_label, flag=wx.ALIGN_CENTER_VERTICAL)

        # Create the text control with the error information.
        exception_info_text = textwrap.dedent("""\
            Exception type: {}

            Exception: {}

            Traceback:
            {}\
        """)
        exception_info_text = exception_info_text.format(
            extype, exception, ''.join(traceback.format_tb(tb))
        )

        text_ctrl = wx.TextCtrl(panel, -1,
                                style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
        text_ctrl.SetValue(exception_info_text)

        # Create the OK button in the bottom row.
        ok_button = wx.Button(panel, -1, 'OK')
        self.Bind(wx.EVT_BUTTON, self.on_ok, source=ok_button)
        ok_button.SetFocus()
        ok_button.SetDefault()

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(top_row_sizer)
        # sizer.Add(message_label, flag=wx.ALL | wx.EXPAND, border=10)
        sizer.Add(text_ctrl, proportion=1, flag=wx.EXPAND)
        sizer.Add(ok_button, flag=wx.ALIGN_CENTER | wx.ALL, border=5)

        panel.SetSizer(sizer)

    def on_ok(self, event):
        self.Destroy()

The only improvement I could wish for is for the static text to flow and wrap automatically according to the width of the dialog, but I couldn't be bothered to make a custom control class just for that.

A: The wx.MessageBox calls the os-specific standard message/alert dialog box (on windows, that's MessageBox() from user32.dll). wxWidgets simply translates the flags you provide (like wx.OK and wx.ICON_INFORMATION) to the os-specific flags and options for the native message box.
You can obtain the os-specific icons through the wx.ArtProvider.
As far as sounds go, wx.Sound can only play sound files. However, if the application does not have to be portable, you can use the winsound module.
import wx
import winsound # windows only

class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,None,wx.ID_ANY)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add( wx.StaticBitmap(self,bitmap=wx.ArtProvider.GetBitmap(wx.ART_INFORMATION)) )
        sizer.Add( wx.StaticBitmap(self,bitmap=wx.ArtProvider.GetBitmap(wx.ART_QUESTION)) )
        sizer.Add( wx.StaticBitmap(self,bitmap=wx.ArtProvider.GetBitmap(wx.ART_WARNING)) )
        sizer.Add( wx.StaticBitmap(self,bitmap=wx.ArtProvider.GetBitmap(wx.ART_ERROR)) )
        self.SetSizerAndFit(sizer)
        self.Show()
        winsound.MessageBeep(winsound.MB_ICONASTERISK)
        winsound.PlaySound('SystemHand', winsound.SND_ASYNC | winsound.SND_ALIAS)

app = wx.PySimpleApp()
Frame()
app.MainLoop()


text:
Q: Filtering json data array with javascript I have a json data like below
 var data =  [
    {
      "type": "Feature",
      "id": 1,
      "properties":
       {
         "name": "William",
         "categorie": 107,
         "laporan":"Fire",
         "time":1,
         "type": "Firefighter",
         "phone_number": "0111111"
       }, "geometry":
        {
           "type": "Point",
           "coordinates": [ 106.814893, -6.219156]
        }
     }
    ,
    {
       "type": "Feature",
       "id": 7,
       "properties":
        {
          "name": "John",
          "categorie": 103,
          "laporan":"Thief",
          "time":3,
          "type": "Police",
          "phone_number": "0987654321"
     }, "geometry":
     {
        "type": "Point",
        "coordinates": [ 106.794107, -6.286935 ]
     }
   }
]

I want to filter the json data above to get properties and coordinates based on time, I have tried using code below, but it's not showing the data I want
  var data_filter=data.filter(function(item){
    return item.properties.time==1;
});
console.log(data_filter)

Do you know how I'm filtering the json data to get properties and coordinate data ?
Thank you

A: You could finally map the wanted properties.

var data = [{ type: "Feature", id: 1, properties: { name: "William", categorie: 107, laporan: "Fire", time: 1, type: "Firefighter", phone_number: "0111111" }, geometry: { type: "Point", coordinates: [106.814893, -6.219156] } }, { type: "Feature", id: 7, properties: { name: "John", categorie: 103, laporan: "Thief", time: 3, type: "Police", phone_number: "0987654321" }, geometry: { type: "Point", coordinates: [106.794107, -6.286935] } }],
    result = data
        .filter(item => item.properties.time == 1)
        .map(({ properties, geometry: { coordinates } }) => ({ properties, coordinates }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comparing two spreadsheets and add data from one if it meets both email address are correct I want to compare two spreadsheets against using email address and if the email address matches then take information from a cell and add it the the 2nd sheet.
Example Sheet columns:

*

*ID

*First name

*Last name

*Email address

*City

*State

Sheet 2:

*

*Account ID

*First Name

*Last name

*City

*State

I want to add Account ID to Sheet one where the emails match


text:
Q: Interpreting an exponential distribution for mathematical model. I am making a model on how robots choose between two shelter sites once they are evicted from their home. I will provide a brief description on the model.
Based on the model, there are three distinct phases on choosing the shelter where the robots finally settle in;
Phase 'Search' = Robots will search for potential shelter sites to move in this phase.
Phase 'Assessment' = Robots will assess if the potential shelter sites they  found is good or not.
Phase 'Recruitment' = Robots will take/convince other robot nest mates to come along with them to the newly found nest.
These are the three distinct stages in the decision making process. According to the model we assume that the robot have to choose a shelter, once the time since she is evicted from nest is greater than the threshold time to pick a shelter. The threshold time to pick a shelter is dependent on the quality of the shelter .Essentially a robot will take another robot to the shelter if the time passed since she is removed from her home is greater than a threshold time to pick a home. So if she finds a good shelter first, she will initiate recruitment to the good shelter faster.
Question:
From data, i calculated the Search duration, Assessment duration and Recruitment duration. From that i found that Search duration, Assessment duration and Recruitment duration to good shelter following  an exponential distribution. Can anyone suggest me the implication of these distributions to the model? Any help will be appreciated.


text:
Q: How to implement/upload my own html and css code to weebly? I made a custom website using html,css etc for a friend who is currently using a weebly platform template for their current website.
After agreeing to use my custom website, I have no clue on how to upload my pages to weebly and avoid using their templates. I've tried to clear the pages and then inputting my own html code and CSS, however, the CSS is not implemented and the html code itself is awkwardly placed. I have tried to google the problem, however, I cannot find any clear instructions or tutorials.
The only reason using I am weebly is because they are currently subscribed to it. So my question is how to use your own coded website with weebly?
Also if there are cheaper options of webhosting feel free to suggest them, since I'll need to use one for the future.
EDIT: I can run each page locally on my PC

A: Simple answer is, you can't. At least not the way you expect to be able to. Lots of platforms are like this.
That said, you can certainly convert what you've created to something that will work on the Weebly platform. Your Theme/Design, CSS and any custom JavaScript can be converted. The content itself is added using the Weebly editor.
I guess you should ask yourself; Who's going to be editing this website? And does the Weebly platform fit their needs. If it is your friend, and they already have a subscription, and the platform is sufficient for them, I would recommend converting it so it works with Weebly. ~And not create something that they can't manage later.


text:
Q: How to go through and display all data for this JSON file? I have a JSON file for example named data.json which look like this:
{
  "item1": {
    "details": [
      {
        "data": "2015-06-11 11:30:00",
        "link": "http:/link.com"
      },
      {
        "data": "2015-06-10 11:30:00",
        "link": "http:/link.com"
      },
      {
        "data": "2015-06-09 11:30:00",
        "link": "http:/link.com"
      }
    ]
  },
  "item2": {
    "details": [
      {
        "data": "2015-06-11 11:30:00",
        "link": "http:/link.com"
      },
      {
        "data": "2015-06-10 11:30:00",
        "link": "http:/link.com"
      },
      {
        "data": "2015-06-09 11:30:00",
        "link": "http:/link.com"
      }
    ]
  }
}

I have a structure in HTML where I want to append positions to the menu which will be created from "item1" and "item2" for example

item1

item2

Then after click on one of those appended link I want to trigger some function which will take "data" and "link" and append them to the links ID which should look like this for example:

Data: 2015-06-11 11:30:00http:/link.com

For now what I have is the script which load data form .json file and append links to the menu, but I don`t know how to append links to the page after click on menu item :/
$( document ).ready(function() {

    jQuery.ajax({
        url: "js/aa_dashboard.json",
        dataType:'json',
        success:function(response)
        {
            console.log(response);
            var menu_items = [];
            for(var key in response) {
                 console.log(key);
                 $('#menu_custom').append(
                    '
'+key+'
'
                 );
            }
        }
    });
});

A: Similarly as you have appended the list items in #menu_custom, you can keep a blank div on your page:-

Or if you don't have initial control on dom then you can append this to your body by :-
Then on click of every item you can set the html of the item content into the item-details div.
$("#item-details").html(itemDetailHtml);

where itemDetailHtml can be created in a similar way as you created the list items html.

A:

   data = {
      "item1": {
        "details": [
          {
            "data": "2015-06-11 11:30:00",
            "link": "http:/link.com"
          },
          {
            "data": "2015-06-10 11:30:00",
            "link": "http:/link.com"
          },
          {
            "data": "2015-06-09 11:30:00",
            "link": "http:/link.com"
          }
        ]
      },
      "item2": {
        "details": [
          {
            "data": "2015-06-11 11:30:00",
            "link": "http:/link.com"
          },
          {
            "data": "2015-06-10 11:30:00",
            "link": "http:/link.com"
          },
          {
            "data": "2015-06-09 11:30:00",
            "link": "http:/link.com"
          }
        ]
      }
    };

    $(function(){
      for(var key in data) {
        $('#menu_custom').append(
          '
'+key+'
'
        );
      }

    });

function loadItemlinks(clickedItem){
        var links = "ul";
        for(var i = 0; i < data[clickedItem].details.length; i++){
          var currentLinkDetail = data[clickedItem].details[i];
          links += '
' + currentLinkDetail.data + '
';
        }
        links += "
";
        $("#" + clickedItem).append(links);
      }


text:
Q: jQuery inserts nodeIndex property in HTML tags in Internet Explorer 8 We are using jQuery 1.5.1 on the site that I'm working on. I recently discovered a problem with my HTML in Internet Explorer 8
The problem is that 'nodeIndex' properties are inserted in the DOM, presumably by jQuery (see below for another StackOverflow question that mentions nodeIndex). The properties are not there in the page source -- only in the DOM then inspecting it with IE8's (awesome) developer tool.
The DOM in IE8:

  bold

  italics

  underline

The DOM in FF5 (and Chrome 12):

  bold

  italics

  underline

The problem is that the DIV is the text of a forum post. If the user wants to quote the forum post, the html of the post is to be converted into BBCode (because older forum posts use BBCode tags for markup), with the formatting markup maintained, and copied to a textarea in which the user writes the text for the new forum post (including the quoted text).
Using JavaScript/jQuery it would be simple to replace html tags with their corresponding BBCode tags, but the addition of the nodeIndex property makes it necessary to add a regular expression replacement of the nodeIndex property, which seems like an ugly hack.
Can anyone tell me why the nodeIndex properties are added in IE8 (and IE7), and is it jQuery that adds them -- and more importantly: Can I get rid of them in a better way than using a regular expression replacement?
The site I work on uses a bunch of different JavaScript/jQuery scripts so there might be a conflict or at least some unexpected behavior that is a result of the combination of scripts.
Edit: The properties are not there when JavaScript is disabled in IE.
Other StackOverflow question that mentions nodeIndex:
Is nodeIndex a valid DOM element property in IE?

A:
Can anyone tell me why the nodeIndex properties are added in IE8 (and IE7), and is it jQuery that adds them --

These properties are added by Sizzle (the jQuery selector engine, compare the definition of the Sizzle.selectors object in the jQuery source) , presumably to browsers that do not natively support the :nth-child CSS pseudo class.

and more importantly: Can I get rid of them in a better way than using a regular expression replacement?

The clean way would be to load the HTML snippet into a DOM and remove the attributes from it. You can do it on the server side or on the client side using jQuery itself.
var htmlText = '
Some text.

';
var $html = $("
" + htmlText + "
");
$html.find("*[nodeIndex]").removeAttr("nodeIndex");
console.log( $html.html() );
// logs "
Some text.

"


text:
Q: Apply regression equation to Landsat ETM+ image I have sample points in an Excel file with XY coordinates and canopy density. I also have a Landsat ETM+ image. All points are collected from the same area as in the image.

*

*I exported all sample points by first 'Display XY data' and then 'Export data', thus I got a shapefile.

*I used "Sample" extracted all points from ETM+ image, then I got a table and exported it to a DBF file. In the DBF file I have XY coordinates for all sample points and band values.

*Then I copied all band values from DBF to original sample points Excel file, then I calculated NDVI and did linear regression (canopy density as dependent variable and NDVI as independent variable) in Excel. Therefore I got a regression equation.

*After added the Excel to ArcGIS and joined it to sample points shapefile, I carried out OLS. However, I only got all sample points regressed.

What could be the problem and how should I apply regression equation to the image so I can produce a map?

A: you should apply your regression equation to your NDVI image using the raster calculator (map algebra tool)
"ndvi_raster" * slope + offset

where slope and offset are the numerical values of the parameters of your regression


text:
Q: Java websocket trigger event to javascript client I'm building an application with Spring 3, Spring MVC, Tomcat7.
I'm triying to refresh content in a jsp when something changes in server side.
For this purpose I followed this tutorial: https://netbeans.org/kb/docs/javaee/maven-websocketapi.html and this one http://self-learning-java-tutorial.blogspot.com.es/2014/08/annotated-server-endpoint.html.
Now I want to trigger one message to all clients (want to see the message in all oppened jsp pages) but I'm not sure how to do this. (For example when an entity is removed in server-side)
As far as I undesrstand, will I need to trigger somehow the method annotated with @OnMessage? and how would I do this? maybe injecting this @ServerEndpoint... class?
Thanks you all


text:
Q: jquery + fancybox issue, fancybox jquery event does not "see" html content which was just added to DOM tree I am using jQuery with Fancybox for generating images gallery this way: I show to user just one medium-sized image which he clicks (and after that click other images links being preloaded into hidden
) and gets nice images gallery.
I need to preload image links because it's not a static list, it depends on first image which user clicked and this way I can prevent fancybox to show duplicate images.
Here is my code (a bit messy, because I'm getting image urls from ruby):
javascript:
$(function() {

    $('#car_image').click(function(e) { // generating fancybox gallery containing only large images
    // here we should generate fancybox
 and place this div inside of

    var gallery_images_urls = [];
    var gallery_images_tagged = '';

    <% @car.photos.each do |car_photo| %>
        var current_image_url = '<%= car_photo.image.url(:large) %>';

        if(current_image_url != $('#changeme').attr('href')) gallery_images_tagged += '';
    <% end%>

        $('#car_image div#large_images_gallery_div').replaceWith('
' + gallery_images_tagged + '</div');

    });

  $("a.fancybox").fancybox();

});

html:

    <%= link_to @car.photos.first.image.url(:large), :class => "fancybox", :rel => "my_car_gallery", :id => "changeme" do %>
        <%= image_tag @car.photos.first.image.url(:medium) %>
    <% end%>

                <-- HERE ALL GALLERY IMAGES LINKS BEING PRELOADED -->

THE ISSUE: my list being loaded correctly, but fancybox shows me just first image and does not show others, which was added by jQuery's replaceWith() method
possible it can't "see" that DOM tree has been changed
BTW, sorry for my poor english
UPDATE
html before images links preloading:

html after images links preloading:

A: As I was told on #jquery @ freenode this question is about jQuery.delegate() so I got help with this method:
$('#car_image').delegate(
    ".fancybox",
    "click",
        function (ev) {
            ev.preventDefault();
            $.fancybox(
                (function () {
                    var gallery_images_urls = [];

                    gallery_images_urls.push(''); // pushing first image

                    <% @car.photos.each do |car_photo| %>
                        if($('a#changeme').attr('href') != '<%= car_photo.image.url(:large) %>') gallery_images_urls.push('<img src="<%= car_photo.image.url(:large) %>" />');
                    <% end %>

                    return gallery_images_urls;
                }).bind(this)(),
                    {
                        transitionIn : 'elastic',
                        transitionOut : 'elastic',
                        speedIn : 600,
                        speedOut : 200
                    }
            );
    }
);

which triggers delegate() for every click on #car_image, I solved to provide fancybox images objects directly to $.fancybox() method without any additional html preloading


text:
Q: A quantitative characterization of bounded approximation property Recall that a Banach space $X$ has the approximation property (AP for short ) if for every compact subset $K$ of $X$ and every $\varepsilon > 0$, there exists a finite rank operator $S$ on $X$ such that $\|Sx-x\|<\varepsilon$ for all $x\in K$. If, in addition, there exists $\lambda \geq 1$ such that we can always choose a finite rank operator $S$ on $X$ with $\|S\|\leq \lambda$, then we say that $X$ has the $\lambda$-bounded approximation property ($\lambda$-BAP). If a Banach space $X$ has the $\lambda$-BAP for some $\lambda$, we say that $X$ has the BAP.
Let $X,Y$ be Banach spaces. We denote by $\mathcal{L}_{w^{*}}(X^{*},Y),\mathcal{K}_{w^{*}}(X^{*},Y),\mathcal{F}_{w^{*}}(X^{*},Y)$ by the classes of all $w^{*}$-to-$w$ continuous operators, $w^{*}$-to-$w$ continuous compact operators and $w^{*}$-to-$w$ continuous finite rank operators from $X^{*}$ to $Y$, respectively. In 1955, A. Grothendieck proved that a Banach space $X$ has the AP if and only if $\mathcal{F}_{w^{*}}(X^{*},Y)$ is dense on $\mathcal{K}_{w^{*}}(X^{*},Y)$ in the operator norm topology for all Banach spaces $Y$.
I am thinking about a quantitative version of this well-known result. Let me fix some notations. If $A$ and $B$ are two nonempty subsets of a Banach space $X$, we set $$d(A,B)=\inf\{\|a-b\|:a\in A,b\in B\},$$$$\widehat{d}(A,B)=\sup\{d(a,B):a\in
A\}.$$ Let $A$ be a bounded subset of a Banach space $X$. The Hausdorff measure of non-compactness of $A$ is defined by $\chi(A)=\inf\{\widehat{d}(A,F):F\subseteq X$ finite subsets$\}$. Then $\chi(A)=0$ if and only if $A$ is relatively norm compact. For an operator $T: X\rightarrow Y$, $\chi(T)$ will denote $\chi(TB_{X})$. I have proved the following result:
Proposition. If a Banach space $X$ has the BAP, then there exists a constant $\mu>0$ such that $$d(T,\mathcal{F}_{w^{*}}(X^{*},Y))\leq \mu \chi(T^{*})$$ for all Banach spaces $Y$ and all $T\in \mathcal{L}_{w^{*}}(X^{*},Y)$.
Question. Is the converse of Proposition true?


text:
Q: Error getting document: clientDetails Error: Cannot modify a WriteBatch that has been committed What is the reason I am getting this error within a Firestore batch update? The promise is returned as a batch commit and the batches are created inside a loop. I could not get my head around this issue. Any advice?
export const updateUserDetailsTypeform = functions.firestore.
  document('responseClientDetails/{case}').onCreate((snap, context) => {

    const newValue = snap.data();
    const caseReference = snap.id;
    var batch = db.batch();

    var reg = "[^£]*£[^£]*";
    const uid = caseReference.match(reg);
    if (uid && newValue) {

      let document = db.collection("responseClientDetails").doc(caseReference);
      let refDoc = db.collection("clientDetails").doc(uid[0])
      batch.update(refDoc,{ has_seen_setup: "true" })

 document.get().then(function (doc: any) {
        if (doc.exists) {
          let refNo = db.collection("clientDetails").doc(uid[0])
          for (let [key, value] of Object.entries(doc.data())) {
            const keyValue = key;
            const valueValue = value;
            batch.update(refNo, { [keyValue]: valueValue })
           // promises.push(db.collection("clientDetails").doc(uid[0]).update({ [keyValue]: valueValue }))
          }

        }else{
          console.log("document does not exist")
        }
      }).catch(function (error: any) {
        console.log("Error getting document: clientDetails", error);
      });

return batch.commit().then(function () {
  console.log("updated clientDetails")
  return null

});

    }

  });

A: You will have to ensure that batch.commit() is called only after all the updates have been performed. What your code is doing now is committing before the second update is called.
The problem is that get() is asynchronous and is returning immediately before the query is complete. If you add some logging statements, you'll understand better what's going.  What you'll need to do instead is wait until the promise returned from get() is fully resolved before committing the batch.  This means that your call to batch.commit() should probably appear inside the then callback.

A: Your call to batch.update(refNo, { [keyValue]: valueValue }) runs asynchronously and is firing after your call to batch.commit
Let's clean up your code sample a little and add some comments to help illustrate what happens.
// 1 - This fires synchronously
batch.update(db.collection("clientDetails").doc(uid[0]), { has_seen_setup: "true" });

// 2 - This fires synchronously
db.collection("responseClientDetails").doc(caseReference).get().then(function (doc: any) {
  if (doc.exists) {
    let refNo = db.collection("clientDetails").doc(uid[0])
    for (let [key, value] of Object.entries(doc.data())) {
      const keyValue = key;
      const valueValue = value;
      // 4 - This fires asynchronously AFTER #3 runs, therefore the batch has been committed
      batch.update(refNo, { [keyValue]: valueValue })
    }
  } else {
    console.log("document does not exist")
  }
}).catch(function (error: any) {
  console.log("Error getting document: clientDetails", error);
});

// 3 - This fires synchronously
return batch.commit().then(function () {
  console.log("updated clientDetails")
  return null
});

So your fix is probably to move your batch.commit call into a then() call:
batch.update(db.collection("clientDetails").doc(uid[0]), { has_seen_setup: "true" });

db.collection("responseClientDetails").doc(caseReference).get().then(function (doc: any) {
  if (doc.exists) {
    let refNo = db.collection("clientDetails").doc(uid[0])
    for (let [key, value] of Object.entries(doc.data())) {
      const keyValue = key;
      const valueValue = value;
      batch.update(refNo, { [keyValue]: valueValue })
    }
  } else {
    console.log("document does not exist")
  }
})
.then(() => {
  return batch.commit().then(function () {
    console.log("updated clientDetails")
    return null
  });
})
.catch(function (error: any) {
  console.log("Error getting document: clientDetails", error);
});


text:
Q: With 3 points, how do I calculate the offset of the plane they form I have a triangle of 3 points A, B, and C.
I can find the normal of the triangle just fine by doing
|AB x AC|

In the below picture, it shows ABC that I know and |n1| which I can calculate. But how would I find P1?

If it helps, I need to use it to know if a Ray will collide with a Convex Mesh and it requires P1. Using A, B, or C, it seems to not work.

A: Vector P1 = (D*a1 + D*b1 + D*c1) should be perpendicular to vector (P1-C) (use any point from A,B,C), so dot product is zero
D * a1 * (D * a1 - cx) + D * b1 * (D * b1 - cy) + D * c1* (D * c1 - cz) = 0
or
D = (N.dot.C) / (a1^2 + b1^2 + c1^2)

If normal is unit (normalized), then expression for coefficient D becomes very simple
d = uN.dot.C

After that:
 P1 = D * N = d * uN

Quick check:
A = (2, 0, 0)
B = (2, 2, 0)
C = (2, 0, 2)
AB = (0, 2, 0)
AC = (0, 0, 2)
N = AB x AC = (4, 0, 0)
N.dot.N = 16
uN = (1, 0, 0)

N.dot.C = (4 * 2) = 8
D = N.dot.C / N.dot.N = 1/2
P1 = D * N  = (2, 0, 0)

d = uN.dot.C = (1 * 2) = 2
P1 = d * uN = (2, 0, 0)

A: The general equation for any plane is
Ax + By + Cz + D = 0

where (A, B, C) is a normal vector to the plane, that you have already calculated with three points.
To get D just substitute x,y,z with the coordinates of any point (x1,y1,z1) you know to be in the plane:
D = -(A*x1 + B*y1 + C*z1)

The good new is that if vector (A,B,C) is a unit vector, then |D| is the distance from the origin (perpendicular) to the plane.


text:
Q: Antd word-wrap in Menu.Item it is possible to apply word-wrap in a Menu.Item component ?
example not working: https://codepen.io/tiagowippel/pen/LYEKYbb?editable=true&editors=001
 <Menu.Item key="1">Option 1Option 1Option 1Option 1Option 1Option 1Option 1Option 1</Menu.Item>

A: The default CSS you're importing from Ant is set to truncate. You'll want to change the white-space property:
white-space: normal;
You may then notice that the wrapped text is overflowing in the y axis now. You can change your height to accommodate variable height content:
height: auto;

A: You can set some style to your Menu.Item :
<Menu.Item key="1" style={{whiteSpace: 'normal', height: 'auto'}}>Option 1Option 1Option 1Option 1Option 1Option 1Option 1Option 1</Menu.Item>


text:
Q: How to prevent initialization of properties which are not present in JSON string during Deserialization in C#? My given class is :
public class Myclass
    {
        public int id { get; set; }

        public string name{ get; set; }
    }

I am passing jsonString like this:
var jsonString = @"{ 'name': 'John'}".Replace("'", "\"");

When i try to deserialize above json string using following code :
var visitData = JsonConvert.DeserializeObject<Myclass>(jsonString, jsonSerialize);

I am getting following values in visitData :
id : 0
name : "john"

But i want to ignore the id property as it is not present in jsonString.
How should i implement this functionality in Console Application of .Net Core 3.1 in C#.

A: You can try to declare id as a nullable property
public class Myclass
{
    public int? id { get; set; } // a nullable property

    public string name{ get; set; }
}

A: Usually deserializer will look for the matching property from the json string, if not exist then the default value is assigned. In your case the default value of int is 0. Again if you make the int as nullable int then again the default value will be assigned i.e., null.
For Newtonsoft.Josn create a contract resolver and manage your serialization/deserialization. Please find the detail information here Should not deserialize a property


text:
Q: View binding with include layout not working I want to use view binding to bind the view in include layout. I had given the included layout with an id 'topBar' but still failed to access the views inside of it. And I try to use Android studio auto-fix to create a local variable to see its type. It shows type "android.widget . a"
I am using Android Studio4.0. Is this a bug in Android Studio?
My Activity
    private ActivityWalletBinding viewBinding;
    private ViewTitleBinding topBarBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding = ActivityWalletBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());
        viewBinding.topBar;
        android.widget . a = viewBinding.topBar; //Create local var using auto fix in android
studio
}

activity_wallet.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <include
        android:id="@+id/topBar"
        layout="@layout/view_title"/>

view_title.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="65dp"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/white"
    android:paddingTop="19dp"
    android:id="@+id/fl_tab">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <ImageView
            android:id="@+id/btn_back"
            android:layout_width="39dp"
            android:layout_height="39dp"
            android:layout_centerVertical="true"
            android:onClick="backClick"
            android:padding="11dp"
            android:src="@mipmap/icon_back"
            android:tint="@color/gray1"
            />
        <TextView
            android:id="@+id/titleView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:textColor="@color/textColor"
            android:textSize="18sp"
            android:textStyle="bold"
            />
        <TextView
            android:id="@+id/tv_right_title"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:layout_alignParentRight="true"
            android:layout_marginRight="11dp"
            android:textColor="@color/enable_right_title"
            android:textSize="15sp"
            tools:text="假文字"
            />
    </RelativeLayout>
</FrameLayout>

Is this a bug for android studio or something?

A: I do nothing on it and it just works automatically. I surely did clean, rebuild, restart Android studio... something at that time but not working. Maybe link another layout in another class would trigger something just fix it under the hood cause I set aside this problem and keep going.

A: in my case I was including a layout from another module and was not able to access the inner views in the included layout via binding and the problem was that I was not enabling the viewBinding in the module that contains the xml file that I wanted to include so adding
buildFeatures {
        viewBinding true
    }

to the gradle.build of that module fixed it for me!

A: xml level inclose your xml root with  tag
   <?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

    <include
        android:id="@+id/topBar"
        layout="@layout/view_title"/>
</layout>


text:
Q: Altering MySQL InnoDB table with minimal downtime I've got a huge InnoDB table(>500 millions rows) which I'd like to partition by hash in order to decrease the index size. I'd like to achieve this with a minimal downtime(e.g 10 minutes is acceptable), what are the possible options?
I was thinking about something as follows:

*

*create the new partitioned table

*insert into this new table all the data from the old one using "insert ... select ..."

*make server unavailable for clients

*somehow sync changes which happened to the old table during step 2 with the new table

*replace the old table with the new one

*make server available for clients

The main question is what tool can be used in the step 4. The problem is that during step 2 there can be lots of changes to the original table: new inserts, updates, deletes - the sync tool should take all of this into account...
Another possible way, I believe, is:

*

*setup a replicating slave server

*sync this slave server with master

*switch master/slave roles and re-configure all clients to connect to the new master

*alter table on the previous master

*wait for master/slave synchronization

*switch master/slave roles again, re-configure all clients

Which one would you recommend?

A: I would go with master/slave replication.  If the master and slave can be on the same subnet, I would also add a new IP to the master, change the clients to point to the new IP.  Then when you are about to switch to the slave, just:

*

*stop mysql on the master

*ifconfig down the extra IP on the master

*ifconfig up the extra IP on the new master
Clients will just connect to the new master without any client reconfig.  Then you do the same thing when you switch back to the original master (if you switch back).
I recommend that a slave always be equivalent hardware to its master so that when it takes over for the master you don't find out it's so much slower that it can't keep up and your whole system fails.  If you do that, then you need only switch once (from the current master to the new master).


text:
Q: Iterating through c# array & placing objects sequentially into other arrays Okay, so this seems simple, but I can't think of a straightforward solution;
Basically I have an object array in C# that contains, say, 102 elements. I then also have 4 other empty arrays. I want to iterate through  the original array and distribute the 100 elements evenly, then distribute 101 and 102 to the 1st and 2nd new arrays respectively.
int i = 1,a=0, b=0, c=0, d = 0;

foreach (ReviewStatus data in routingData)
{
    if (i == 1)
    {
        threadOneWork[a] = data;
        a++;
    }
    if (i == 2)
    {
        threadTwoWork[b] = data;
        b++;
    }
    if (i == 3)
    {
        threadThreeWork[c] = data;
        c++;
    }
    if (i == 4)
    {
        threadFourWork[d] = data;
        d++;
        i = 0;
    }
    i++;

}

Now the above code definitely works, but I was curious, does anybody know of a better way to do this??

A: var workArrays = new[] {
    threadOneWork,
    threadTwoWork,
    threadThreeWork,
    threadFourWork,
};

for(int i=0; i<routingData.Length; i++) {
    workArrays[i%4][i/4] = routingData[i];
}

A: Put the four arrays into an array of arrays, and use i%4 as an index. Assuming that thread###Work arrays have enough space to store the data, you can do this:
var tw = new[] {threadOneWork, threadTwoWork, threadThreeWork, threadFourWork};
var i = 0;
foreach (ReviewStatus data in routingData) {
    tw[i%4][i/tw.Length] = data;
    i++;
}

A: Linq is your friend! Use modulo to group the items via the total number of arrays in your case 4.
For example the code splits them up into four different lists:
var Items = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Items.Select( ( i, index ) => new {
                                      category = index % 4,
                                      value = i
                                  } )
        .GroupBy( itm => itm.category, itm => itm.value )
        .ToList()
        .ForEach( gr => Console.WriteLine("Group {0} : {1}", gr.Key, string.Join(",", gr)));
/* output
Group 0 : 1,5,9
Group 1 : 2,6,10
Group 2 : 3,7
Group 3 : 4,8
*/


text:
Q: RoR Selecting data to show data How is the easiest way to make a selectio field which will retrive other information? I have an Ajax script to make this, i think i can make it work. But srsly, i can't figure out how to make in the view or controller actions to let me select a data from the table and get other data related to it.
This is my code, this may help understand what i'm trying to say.
<%= form_for(@page) do |f| %>

 <%= f.collection_select :cliente_id, Cliente.order(:name), :id, :name, prompt: "Selecionar", :required => true %>

<%= f.projeto.name %>

<%= f.task.descr %>


text:
Q: Oracle SQL Developer Output Number Formatting (To_Char Problem)

Amount

1000000

My table is above. When I realise the query, I would like to see number format output like '1.000.000'.  No decimals.
select Amount = TO_CHAR(Number, '.') from Table

It is easy question but what is wrong with my code? (SQL Oracle Developer). Thanks in advance

A: Try this:
SELECT  TO_CHAR(amount, '999G999G999', 'NLS_NUMERIC_CHARACTERS="."')

...etc...


text:
Q: image and carousel not responsive bootstrap5.2 I have a problem of responsiveness. When I open my website on the phone, the icon images that I put in the  tag disappear while they are visible on the computer. I tried to add img-fluid from bootstrap but it doesn't work on it I don't understand why. On this link you can see all the code in full https://jsfiddle.net/z3hx2Lcr and in this link you can see result https://testportfolio111.000webhostapp.com/ I also have a responsivity problem in the carousel since I put the text effects in it. When I open the site on my phone the carousel goes down, I tried to fix this problem but I can't. Can anyone give me the solution?

A: there is a problem on your bottom sections, the element with class .skills-bar
break the page and caused gap from right because it has fixed width value
so change it to this code
.skills-bar {
  width: 100%;
  max-width: 600px;
}

and in the container which your icons are change this in mobile version
instead of

use this

about your slider:
your .carousel-item has height: 100vh
change it to height: auto in mobile version
and the reason why it's text is not showing is these slides(carousel-caption) get the class d-none


text:
Q: Click on a row to open a modal with the row's data I am using react-table and here's my table:
<ReactTable
          data={this.props.data}
          columns={[
            {
              Header: "id",
              accessor: "id",
              width: 50
            },
            {
              Header: "Name",
              accessor: "name",
              width: 200
            },
            {
              Header: "",
              id: "id",
              Cell: ({ row }) => (
                <button onClick={e => this.handleButtonClick(e, row)}>
                  Click Me
                </button>
              )
            }
          ]}
          defaultPageSize={10}
          showPaginationBottom
       />

the action after the button click
handleButtonClick = (e, row) => {
    this.setState({ visible: true});
    return
       <Modal
          title="title"
          visible={this.state.visible}
        >
        // show data here
    </Modal>
  };

So this is how I am working right now, but the modal isn't getting displayed. Can anyone help me with this? What am I doing wrong?

A: Why you return the modal with handleButtonClick function instead of add it with ReactTable
<ReactTable
          data={this.props.data}
          columns={[
            {
              Header: "id",
              accessor: "id",
              width: 50
            },
            {
              Header: "Name",
              accessor: "name",
              width: 200
            },
            {
              Header: "",
              id: "id",
              Cell: ({ row }) => (
                <button onClick={e => this.handleButtonClick(e, row)}>
                  Click Me
                </button>
              )
            }
          ]}
          defaultPageSize={10}
          showPaginationBottom
       />

      {this.state.visible && <Modal
          title="title"
          visible={this.state.visible}
        >
        // show data here
    </Modal>}

handleButtonClick = (e, row) => {
    this.setState({ visible: true});
  };


text:
Q: Openshift can not add node due to self-signed certification I am trying to add a node to my openshift master via openshift ansible playbooks. I try to add the node with the following command(it starts from systemd)
/usr/bin/docker run --name origin-node --rm --privileged --net=host --pid=host --env-file=/etc/sysconfig/origin-node -v /:/rootfs:ro -e CONFIG_FILE=${CONFIG_FILE} -e OPTIONS=${OPTIONS} -e HOST=/rootfs -e HOST_ETC=/host-etc -v /var/lib/origin:/var/lib/origin:rslave -v /etc/origin/node:/etc/origin/node -v /etc/localtime:/etc/localtime:ro -v /etc/machine-id:/etc/machine-id:ro -v /run:/run -v /sys:/sys:rw -v /sys/fs/cgroup:/sys/fs/cgroup:rw -v /usr/bin/docker:/usr/bin/docker:ro -v /var/lib/docker:/var/lib/docker -v /lib/modules:/lib/modules -v /etc/origin/openvswitch:/etc/openvswitch -v /etc/origin/sdn:/etc/openshift-sdn -v /etc/systemd/system:/host-etc/systemd/system -v /var/log:/var/log -v /dev:/dev $DOCKER_ADDTL_BIND_MOUNTS openshift/node

The problem is that the node can not fetch configuration from the master. I have tried to add the certificate with  CURL_CA_BUNDLE export, curl works but openshift still doesn't. Anyway, the error I get is this:
I0130 19:19:44.029170   76719 start_node.go:250] Reading node configuration from /etc/origin/node/node-config.yaml
F0130 19:19:44.041799   76719 start_node.go:139] cannot fetch "default" cluster network: Get https://10.4.254.28:8443/oapi/v1/clusternetworks/default: x509: certificate signed by unknown authority

Keep in mind that I also have trusted the certificate from the local OS, still no luck..


text:
Q: Como verficar input text antes de fazer post? Segue o código:
@using (Html.BeginForm("Update", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
.
.
.
<input type="text" name="lastname">
<input type="submit" class="btn btn-success" value="Criar" />
}

Quero verificar input usando javascript ou jquery, pra depois fazer post.
Se input for branco ou vazio, não fazer post.
Se for diferente que branco, fazer post

A: Utilizando jquery no final do carregamento da página:

$(function(){
  var status = !($("input[name=lastname]").length == 1);
  $("input[type=submit]").attr('disabled', status);
});

<input type="text" name="lastname">
<input type="submit" class="btn btn-success" value="Criar" />

Com jQuery e jQuery Validation
Form:
<form name="form1" id="form1">
  <input type="text" name="lastname" class="form-control" id="lastname" >
  <input type="submit" class="btn btn-success" value="Criar" />
</form>

Js:
$(document).ready(function() {
  $('#form1').validate({
        rules: {
            lastname: {
                required: true
            }
        },
        messages: {
            lastname: {
                required:'Digite o último nome'
            }
        }
    });
});

Exemplo Online

Com jQuery e Bootstrap Validation
Referencias:
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js
https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css
https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.8/validator.min.js
https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js
https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.css

$(function(){
 $('#form1').validator();
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.css" rel="stylesheet"/>

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<form id="form1" data-toggle="validator">

        Nome
        <input type="text" name="name" class="form-control" required />

        Último nome
        <input type="text" name="lastname" class="form-control" required />

    <button class="btn btn-success btn-block" type="submit">Criar</button>
</form>

Exemplo OnLine

A: Se não for usar nenhuma validação mais complexa, você pode utilizar required do HTML5 Aqui não sendo necessário JavaScript. Dessa forma:
<input type="text" name="lastname" required>
<input type="submit" class="btn btn-success" value="Criar">


text:
Q: IOS: Project crashing due to possibly using to much memory (Using ARC but might be due to image size) Hey all I am having some problems with my app. This is my first big project for the IOS and I have been doing pretty good so far some parts that troubled here and there. But now that development is basically over over I have the biggest problem and it has been troubling me for while and I have hit a wall. I am not sure what to do yet ( I have one idea but not sure if that will work).  On my computer it works most of the time. Sometime it
crashes and I get an error(see below). What I do when I get the error is usually the game is working and then all of a sudden just stop. I actually have not received the error in a while and I mostly got it when it was in development.
When the app is ran on either my bosses machine or on the actual device (side note we upload the app from her machine to the device not from my machine), it crashes. It always crashes at the same point. The fist view, the title screen, appears. Then they click the start button and a new view is launched. However, they click the start button and the app ends up crashing. What happens is the app closes and the debugger goes to this part of the code.
int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([MyAppDelegate class]));
    }
}

Also, the app is a game. All the views use OpengelEs.
I am thinking what is happening is that to much memory is being used. The game is running; the system needs more memory and the system kills a process to release memory; the process being the app. This is based on what I know about the IOS and the application life cycle. I am using ARC but I have tested the game a lot specifically with their tools and I have not found any memory leaks or similar things that could cause the problem. I am thinking that the image might be to big file size wise. Images range from 100kb to 5 MB. We are having them sized down but I am not sure if that is the problem. Right now the only lead I have for why it is crashing is it is running out of memory and the only reason for that I have found is the file sizes. I am not 100% sure that this is the cause because it does not explain why it does not crash (at least not recently) on my machine but it does on her(it explains why it does for her machine and the device and it explains why it sometimes happen on mine but not that they happen under different conditions). Also I have always heard that some type of low memory warning should occur under conditions when this happen. Can someone confirm deny this (I have researched this but have not found a lot
So what I am asking is if anyone might have any more suggestions on the cause of this problem or at least lead me into topics that I should research more. Do you think lowering the file size of the images would work. There tends to be 1 background that is about 1-3 and then anywhere from 8 to 40 images that are 100kb.
EDIT
I used the profile mode instruments. The app started using 100mb and then while playing it went up to 500mb (this is in real memory). I noticed that it only went up memory when I switched to a new level. I figured it was because each level had more images display but then I did a test. In the test instead of going to the next level when a level is finish level one is played again.
Each level is an object of Class Level. My ViewControler (which is a subclass of GLKViewController) has an property called currentLevel. The game switches to the next level with the following code:
-(void) nextLevel: (Level) newLevel
{
    //play sound
    MyAppDelage *del=[[UIApplication sharedApplication] delegate];
    UIWindow *main=[delegate window];
    MyViewControler *view=(MyViewControler*) main.rootViewController;
    view.currentLevel=newLevel;
 }

So what I think is happening is that the old level never gets garbage collected for some reason; currentLevel is strong if that makes any different.
Also I had
@synthesize currentLevel =_currentLevel;
This is really old code that I wrote when I was first learning Objective C. I was just following examples at time. Would possibly changing either strong type or removing the @synthesize  part would help this problem?
I am use to more C++/C#/Java syntax so I am really not use to some of objective C styles yet.

A: Without seeing any of your code I suggest to check the following:

*

*Check if the images you use have small pixel dimensions, since Apple advices that images which have width/height larger than 1024 pixels SHOULD better be split into tiles. Look for example at Apple's PhotoScroller.app code. Note that although an image may be small in size (say 100 kb), in order to display it iOS needs to decode it using 4 bytes per pixel! Thus an image of 3000x3000 pixels uses 3000x3000*4=36,000,000 bytes equalling about 34 MB of memory.

*Although you are using ARC, look at for/while loops in your code which may handle images and surround (where applicable) the image handling code with @autoreleasepool { .. }. For example:
for (NSString *imageName in imageNames) {
    @autoreleasepool {
        //... code here to get your images for display ...
    }
}

*Look critically in how you handle retrieving a lot of images, i.e. iOS caches images fetched using 'imageNamed' versus 'imageWithContentsOfFile'. This technique is especially used in handling large images using CATiledLayers. The following code fragment show the two flavors of getting an image:
// The fetched image is cached by iOS when using:
UIImage *image1 = [UIImage imageNamed:@"myimagename.png"];
// You can control memory usage and freeing of the image when using:
UIImage *image2 = [UIImage imageWithContentsOfFile:@"myPath/myimagename.png

*You may also look at the code used in the LargeImageDownsizing example from Apple, but note that this didn't work for me when handling PNG files. I submitted a bug-report (last year November) to Apple but haven't heard anything yet.

*Finally don't wait too long with testing on a real device, since your development Mac is at least 10 times faster than the target iDevice and has also a whopping more memory available before you start to notice memory related issues. It is by the way always a good habit by using the Instruments.app for profiling your app.
Hope the above suggestions may help you! Just my 2 (Euro)cents, for what its worth yet.


text:
Q: Extension that makes wrapper that dispenses self typed as self Sorry for the weird title. Here's a toy sketch of my code:
extension UIControl {
    func makeHolder() -> ControlHolder {
        ControlHolder(control: self)
    }
}

struct ControlHolder {
    let control : UIControl
    init(control: UIControl) {
        self.control = control
    }
    func retrieve() -> UIControl {
        return self.control
    }
}

I admit this is a toy reduction, and I don't like when people do that, but it illustrates the syntactical issue perfectly, so let's go with it.
Okay, so we have an extension on UIControl that is a method that returns a wrapper object. Now, the problem is this:
let holder = UISwitch().makeHolder()
let output = holder.retrieve()

The result, output, is typed as UIControl, obviously. But that isn't what I want. I want it to be typed as UISwitch, because I started with a UISwitch. OK, so that sounds like a generic. The problem is, I can't figure out how to make that generic.
It's easy, I think, to make ControlHolder a generic:
struct ControlHolder<T:UIControl> {
    let control : T
    init(control: T) {
        self.control = control
    }
    func retrieve() -> T {
        return self.control
    }
}

I'm pretty sure I've got that part right. But then how do I write the extension declaration in such a way as to resolve that generic to the actual type of self, the UIControl on which makeHolder is called?
I tried introducing a generic to the extension, obeying the compiler until I got it to compile:
extension UIControl {
    func makeHolder<T>() -> ControlHolder<T> {
        ControlHolder<T>(control: self as! T)
    }
}

But that's pretty silly, and output is still typed as UIControl.
Obviously I can add another parameter passing the type explicitly into makeHolder and thus resolving it:
extension UIControl {
    func makeHolder<T>(ofType: T.Type) -> ControlHolder<T> {
        ControlHolder<T>(control: self as! T)
    }
}

Now when I call makeHolder I pass in the type:
let holder = UISwitch().makeHolder(ofType: UISwitch.self)
let output = holder.retrieve()

And now of course output is typed as UISwitch. But this is idiotic! I want the extension to just know that the type is UISwitch, because I'm calling makeHolder on a UISwitch.
I feel like I'm coming at this all wrong. Maybe someone can straighten me out? Or am I aiming for something that's just impossible?

A: The trick to this is to define a protocol, an extension of that protocol, and put the makeHolder method in that extension. That way, you can use Self as the generic type for the returned ControlHolder.
First define a new protocol (let's call it "HoldableControl") and require that conformers must be UIControls. It doesn't need any other requirements because we just care about adding the makeHolder function to an extension.
protocol HoldableControl: UIControl {}

Then, add an extension of HoldableControl and define makeHolder in it, returning ControlHolder<Self>. We are allowed to use Self here because it is allowed in protocol extensions, unlike in an extension to UIControl.
extension HoldableControl {
    func makeHolder() -> ControlHolder<Self> {
        ControlHolder(control: self)
    }
}

Then, we just need to have UIControl conform to this protocol:
extension UIControl: HoldableControl {}

And make your ControlHolder generic, as you've already done:
struct ControlHolder<T: UIControl> {
    let control: T

    init(control: T) {
        self.control = control
    }

    func retrieve() -> T {
        control
    }
}

And now it will work:
let holder = UISwitch().makeHolder() // type is ControlHolder<UISwitch>
let output = holder.retrieve()       // type is UISwitch


text:
Q: Displaying HTML code In PHP I can use the following to stop HTML from rendering, so it actually displays html as text on the web page:
$html = "
Some text
";

echo htmlentities($html);

How do I do the same with asp.net pages (vb.net).  I am using .NET 3.5.

A: You could try:
var html = @"
Some text
";
Response.Write(Server.HtmlEncode(html));

which is the exact translation of your snippet.
BTW, you can find more info on Server.HtmlEncode here.

A: You could use HttpServerUtility.HtmlEncode for this:
<%= Server.HtmlEncode("
Some text
") %>

In .NET 4 you could use a shorthand for this:
<%: "
Some text
" %>

A: Server.HtmlEncode("`<div>Some text</div>`");


text:
Q: Can I run/debug files with babel-node in WebStorm? I know there are Run/Debug configurations in WebStorm, but I don't know how to configure the context menu (when I right click in a file, it has Run... and Debug... in the menu, but I can't find where to configure this).

A: Run configurations are created via Run | Edit Configurations... : press +, choose Node.js, in created configuration specify babel-node as Node Interpreter:

But note that debugging doesn't work well when using it. I'd strongly recommend using -r @babel/register Node.js parameter instead - see comments in https://youtrack.jetbrains.com/issue/WEB-21949


text:
Q: find if any checkbox is checked in a specific column of the GridView using jQuery Please let me know how to check if any checkbox is checked in a specific column (for example first column) of the GridView control using jQuery? there are checkboxes in other columns too, but I need to check if any checkbox is checked in a specific column. thanks in advance.

A: thanks for the reply. solved it myself with help from the following link
if ($("#<%=GridView1.ClientID %> >tbody >tr >td:first-child > input[type=checkbox]:checked").length > 0) {}

http://www.codedigest.com/CodeDigest/63-Check-All-Checkboxes-in-a-Particular-Column-in-GridView-using-JQuery-.aspx

A: You could do this:
var checked = $('selectorForColumn :checkbox:checked').length > 0;

or this:
var checked = $('selectorForColumn :checkbox').is(':checked');

...which will return true if at least one checkbox in the column is checked.
Not sure what the proper selector is without seeing your markup, but if it is the first column, you would do something like this:
$('table > tbody > tr > td:first-child :checkbox')


text:
Q: Error when running minted package I get the following error after I compile the file in TeX:
! Package minted Error: You must invoke LaTeX with the -shell-escape flag.

I searched a bit but I couldnt find any solution.The MikTeX is up to date.What can I do?
Thanks


text:
Q: Can't resolve all parameters for TemlComponent: (?). at syntaxError (compiler.js:1016) Im new to Angular and Im trying to find out where Im going wrong with this and why Im getting this error.
Can't resolve all parameters for TemlComponent: (?).     at syntaxError (compiler.js:1016).
I have created a working example here
https://stackblitz.com/edit/angular-w8jyjs with all the pertinent files.
The code probably contains several redundant items and methods that I created while attempting to fix this.  removing a;ll parameters from the constructor  in teml.component.ts gets rid of the error.
Guidance to what i've done wrong here would be appreciated.

A: The constructor property in Angular is meant for defining dependencies for the initialisation of your component and not for declaring a property, which explains why you're getting the error.
Consider using an @Input() instead.
Here's an updated demo.

EDIT: For more info about constructors in Angular, check out this StackOverflow question.

A: So this was entirely a result of my inexperience and trying to apply examples without full knowledge.  I appreciate the feedback and quick answer.
I was trying to use the constuctor to pass a parameter which is not the correct way in Typescript.


text:
Q: Are there additional external data parameters for vbulletin 3.6 feed URLs? I'm able to see new posts in a particular forum as a js or rss response by using a url like:
http://sitename.com/external.php?type=js&forumids=123&lastpost=1
Are there additional parameters for paging results? I could not see mention of this in the documentation. VBulletin version is 3.6.8

A: I found what I was looking for here:
Maximum External Records
This option limits the maximum amount of records that can be returned by the external data provider. By default 15 records will be returned. This option allows the user to tack on &count=X to their RSS feed to retrieve more records.


text:
Q: ¿Se puede deshabilitar un botón con datatable.js? Hola comunidad espero me puedan apoyar, Estoy creando una aplicación net core MVC, quiero deshabilitar el botón de color morado cuando mi campo ComentariosaAuto no contenga nada o este vacio.

Estuve leyendo que se podia lograr con .render pero leyendo la documentación necesito mandar llamar la data y yo solo estoy usando datatables para poder filtrar, buscar y paginar.
Yo muestro toda la información mandandola llamar desde un controlador:
    public async Task<IActionResult> Index()
    {
        var idUsuario = servicioUsuario.ObtenerIdUsuario();
        var vacantes = await repositorioVacante.ObtenerVacantes(idUsuario);
        return View(vacantes);
    }

Y en mi repositorio tengo lo siguiente para obtener la información desde mi SP:
     public async Task<IEnumerable<VacantesModel>> ObtenerVacantes(int idUsuario)
    {
        using var connection = new SqlConnection(connectionString);
        return await connection.QueryAsync<VacantesModel>("WebCHObtenerVacantes", new {idUsuario}, commandType: CommandType.StoredProcedure);
    }

Asi es como muestro la información en mi tabla con mi modelo:

                @foreach (var vacante in Model)
                {

                        @vacante.FechaInicio
                        @vacante.NombrePlaza
                        @vacante.NombreEntrevistador
                        @vacante.NombreDepartamento
                        @vacante.NombrePuesto
                        @vacante.NombreEstatus
                        @vacante.ComentariosAuto

                            @**@

                }

Y la unica configuración que tengo para datatable es la siguiente, lo cual es el lenguaje:
$(document).ready( function () {
        $('#tablaVacantes').DataTable({
            ordering: false,
            "language": {
                "processing": "Procesando...",
                "lengthMenu": "Mostrar _MENU_ registros",
                "zeroRecords": "No se encontraron resultados",
                "emptyTable": "Ningún dato disponible en esta tabla",
                "info": "Mostrando registros del _START_ al _END_ de un total _TOTAL_",
                "infoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
                "infoFiltered": "(filtrado de un total de _MAX_ registros)",
                "search": "Buscar:",
                "infoThousands": ",",
                "loadingRecords": "Cargando...",
                "paginate": {
                    "first": "Primero",
                    "last": "Último",
                    "next": "Siguiente",
                    "previous": "Anterior"
                }
            }
        });
    } );

Alguien me podría apoyar con alguna idea en como poder ocultar ese botón o deshabilitarlo, si no se puede con datables, si es posible otra opción, se los agradeceria mucho.


text:
Q: Get the id of the next closest location I have an application in which the user can select a location and view it's distance from several Points Of Interests (POIs).
When I retrieve these distances, I would also like to retrieve the ID's of the locations that are the next closest and the next furthest away from each POI. eg. If we have 10 locations, each of them a mile further away from a certain POI the I would like to return: The name of the POI, The distance from that POI, The ID of the next closest location, and the ID of the next furthest location. An example row of the result set could be: 'Football Ground', '1.5', 24, 784 (because the location we are viewing is 1.5 miles from the football ground and location 24 is the next closest and 784 is the next furthest away.
Note: it is possible that the location we are viewing is the closest to or furthest from a POI, in that case we would need to return -1 as the id of the next closest or furthest location to let the front end know that we can't get any closer or further.
I would like to do this in one statement if possible. I created a function that will calculate the distance between 2 points, and have been using it around the application:
 create FUNCTION [dbo].[fnc_calc_distance]
(
    @lat1 as float,
    @lng1 as float,
    @lat2 as float,
    @lng2 as float
)
RETURNS float
AS
BEGIN
    declare @result as float
    select @result = (3959*acos(cos(radians(@lat2))*cos(radians(@lat1))*cos(radians(@lng1)-radians(@lng2))+sin(radians(@lat2))*sin(radians(@lat1))))
    RETURN @result
END

And sample table structures/ data are as follows:
CREATE TABLE tbl_locations(
    [houseID] [int] NOT NULL,
    [lat] [decimal](14, 10) not NULL,
    [lng] [decimal](14, 10) not NULL)

insert into tbl_locations
    values (1, 54.9834400000, -1.6314250000)
insert into tbl_locations
    values (2, 54.9860420000, -1.5912680000)
insert into tbl_locations
    values (3, 54.9882050000, -1.5707710000)

CREATE TABLE tbl_poi(
    [ID] [int] NOT NULL,
    [name] [varchar](32) NOT NULL,
    [lat] [decimal](14, 10) NOT NULL,
    [lng] [decimal](14, 10) NOT NULL)

insert into tbl_poi
    values (1, 'Football Ground', 54.9752430000, -1.6219210000)
insert into tbl_poi
    values (1, 'Train Station', 54.9898610000, -1.6047600000)

I'm using SQL Server 2008.
Thanks in advance.
Chris

A: The way I would handle this is to return an ordered set of locations relative to the POI.  Depending on your application you could limit this to just the first N items or within X distance.  If limiting to a certain number, then it would be handy to know how many items there are to know whether you should indicate that more are available.  Unfortunately I don't know how to do all of that in a single query.
My tack would be to store the name, id, lat, and long of the chosen point of interest on the page where the user makes the choice (1 query).  Then I would pass these back to the server and use them in the second query (to get the ordered list).  If necessary, I'd perform a third query to find out how many total items there were (count(*)) to see if I needed to provide a "more items" link.
The second query might look like:
 select TOP 10 t.id, t.name, t.lat, t.long, t.distance
 from (select id, name, lat, long, fnc_calc_distance(lat,@house_lat,long,@house_long) as distance
       from tbl_poi) t
 order by t.distance desc

where you pass in the selected parameters from the user's selection.


text:
Q: Can't seem to get RequiredFieldValidator in nested user control to fire I have a user control (form) inside a user control (grid) with a Validator in the form.  A snippet from the code is below
<asp:tablerow>
    <asp:tablecell HorizontalAlign="center" columnspan="2" >
        <asp:ValidationSummary runat="server" id="ValidationSummary1" />
    </asp:tablecell>
</asp:tablerow>
<asp:tablerow>
    <asp:tablecell HorizontalAlign="left" style="padding-left:250px;" >
        <asp:label ID="Label1" runat="server" Text="Foo:" AssociatedControlId="txtFoo" />
    </asp:tablecell>
    <asp:tablecell HorizontalAlign="left" style="padding-right:200px;" >
        <asp:textbox runat="server" id="txtFoo" Text="" />
        &nbsp
        <asp:RequiredFieldValidator
                            ID="RequiredFieldValidator1"
                            runat="server"
                            ErrorMessage="Foo is a Required Field"
                            Text="*"
                            ControlToValidate="txtFoo" />
    </asp:tablecell>
</asp:tablerow>

This code is identical to code in another user control where the parent is not a user control and that page works fine, but on this page the Validator doesn't fire and the Foo_ItemCommand method fires instead.  I tried searching Google and StackOverFlow but haven't been able to find anything that helps.
Thanks for any assistance you might have.
Dan

A: try to use ValidationGroup for validation controls and submit control.


text:
Q: Spritekit drastic frame rate drop I have tried my best to boil this question down as simple as possible. I have a coin object in  my game:
@implementation
-(CollectableCoin*)initWithLocation:(CGPoint) Location andValue: (int) val
{
self = [super initWithImageNamed:@"coin"];
[self setScale:.35];
_value = val;
_collected = false;

self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.size];
self.physicsBody.categoryBitMask = APAColliderTypeCoin;
self.physicsBody.collisionBitMask = APAColliderTypeBall;
self.physicsBody.mass = 0.00009;
self.physicsBody.restitution = .35;
self.position = Location;
self.name = @"collectableCoin";
return self;
}
@end

I also have a shelf object:
@implementation Shelf

-(Shelf*)initWithLocation:(CGPoint) location andWidth:(NSInteger) width
{
self = [super initWithImageNamed:@"shelf"];
if(self)
{
    self.size = CGSizeMake(width, HEIGHT);

    self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.size];
    self.physicsBody.dynamic = false;
    self.physicsBody.restitution = 0;
    self.position = location;
    self.name = @"shelf";

    SKSpriteNode* topOfShelf;

    if(width > 5)
        topOfShelf = [[SKSpriteNode alloc] initWithColor:[UIColor yellowColor] size:CGSizeMake(width-2, 1)];
    else
        topOfShelf = [[SKSpriteNode alloc] initWithColor:[UIColor yellowColor] size:CGSizeMake(width, 1)];

    topOfShelf.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:topOfShelf.size];
    topOfShelf.physicsBody.restitution = 1;
    topOfShelf.physicsBody.dynamic = false;
    topOfShelf.position = CGPointMake(0, location.y + self.size.height/2);
    NSLog([NSString stringWithFormat:@"%f", location.y + self.size.height/2]);
    NSLog([NSString stringWithFormat:@"%f", location.y]);
    topOfShelf.name = @"shelf";

    [self addChild:topOfShelf];
}
return self;
}

@end

I create a scene like so:
-(id)initWithSizeTest:(CGSize)size
{

self.physicsWorld.gravity = CGVectorMake(0, 0);
_gameState = READYTOSTART;
self.physicsWorld.contactDelegate = self;

if (self = [super initWithSize:size])
{
    self.physicsWorld.gravity = CGVectorMake(0, 0);

    for(int i = 0; i < 25; i++)
    {
        CollectableCoin* orb = [[CollectableCoin alloc] initWithLocation:CGPointMake(i*10, self.size.height*.75) andValue:1];
        [self addChild:orb];
    }

    Shelf* shelf = [[Shelf alloc] initWithLocation:CGPointMake(self.size.width/2, self.size.height/2) andWidth:self.size.width];
    [self addChild:shelf];
}
return self;

}
Here is the touchesBegan method:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
if(_gameState == READYTOSTART)
{
    self.physicsWorld.gravity = CGVectorMake(0, -2.0);
    _gameState = PLAYING;
    [[self childNodeWithName:@"taptostart"] removeFromParent];
}

When the scene starts, I have a row of coins hovering above a shelf, gravity is disabled, and I have a solid 60fps. When I tap the screen, the touchesbegan function enables gravity and the coins fall on the shelf, and the frame rate drops to 5fps. The didBeginContact function is not being called because the shelf object is not dynamic nor does it have contact or collision bitmasks, so I am fairly sure that it is not being overloaded by extraneous calls to didBeginContact. This happens on an iPad mini and an iPhone 4s, but not in any of the simulators. This is a very simple example of the actual problem that I am having. Anyone have any insights?


text:
Q: efficient solution how to? (Facebook & SQL) I'm building one of my first facebook apps, and I'm in a bit of a bind as to the most efficient way to solve this problem:
My app's mySQL db has a table containing users, and a table containing activities. I need to be able to show a user which of their friends is participating in which activity. Many users can participate in each activity, but a user can only participate in one activity.
What is the best way to approach this problem? Is there a way to query FB for my user's friends, compare that to my table of users, take the matches and return their selected activities to the user efficiently enough to not take for ever to load? If anyone could point me in the right direction for this it would be much appreciated.

A: Once you have the logged-in user's Facebook ID and an authorized Facebook Session, you can query FB for the user's friends using the graph API.  You can click the example link to see the Graph API response for your own Facebook account.
Here's the relevant page in the API docs:
https://developers.facebook.com/docs/reference/api/friendlist
Here's the API overview:
https://developers.facebook.com/docs/api
Since your app is in PHP, you can grab the official php SDK here and get to work!
https://github.com/facebook/php-sdk/

A: You can query FB for the user's friends. But there is no reason to query for all of their friends. You probably want to filter it on friends that are using your app. If a friend isn't using your app, they probably have no activity to link to.
$query = 'SELECT uid, name FROM user WHERE uid IN
(SELECT uid2 FROM friend WHERE uid1 = [user ID] )
AND is_app_user=1';
$fqlresult  = $facebook->api_client->fql_query($query);


text: Q: sum of textbox and value in mysql database can someone give me a hand on how will I be able to add the value in a textbox and existing data on my database and change the existing value in database to the sum of the value in textbox and database ?


text:
Q: looping through a array of hashes that nested in another array I have the following Hash with a array inside a array inside the hash. The inner array is a array of hashes. I am having trouble figuring out how to access them.
{"AssetWarrantyResponse"=>
    [{"AssetHeaderData"=>
        {"BUID"=>"11", "ServiceTag"=>"GH3RV12", "ShipDate"=>"2014-06-05T00:00:00", "CountryLookupCode"=>"US", "LocalChannel"=>"45", "CustomerNumber"=>"127963428", "ItemClassCode"=>"RK003", "IsDuplicate"=>false, "MachineDescription"=>"OptiPlex 3020", "OrderNumber"=>"631899941", "ParentServiceTag"=>nil},
      "ProductHeaderData"=>
        {"SystemDescription"=>"OptiPlex 3020", "ProductId"=>"optiplex-3020-desktop", "ProductFamily"=>"Desktops & All-in-Ones", "LOB"=>"OptiPlex", "LOBFriendlyName"=>"OptiPlex"},
     "AssetEntitlementData"=>[
        {"StartDate"=>"2022-06-07T00:00:00", "EndDate"=>"2022-06-08T00:00:00", "ServiceLevelDescription"=>"Dell", "ServiceLevelCode"=>"DL", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"999-0036"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-05T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"422-0052"},
        {"StartDate"=>"2015-06-06T00:00:00", "EndDate"=>"2017-06-05T23:59:59", "ServiceLevelDescription"=>"Next Business Day Onsite", "ServiceLevelCode"=>"ND", "ServiceLevelGroup"=>5, "EntitlementType"=>"EXTENDED", "ServiceProvider"=>"UNY", "ItemNumber"=>"939-7368"},
        {"StartDate"=>"2015-06-06T00:00:00", "EndDate"=>"2017-06-05T23:59:59", "ServiceLevelDescription"=>"ProSupport", "ServiceLevelCode"=>"TS", "ServiceLevelGroup"=>8, "EntitlementType"=>"EXTENDED", "ServiceProvider"=>"DELL", "ItemNumber"=>"939-7738"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2015-06-05T23:59:59", "ServiceLevelDescription"=>"Next Business Day Onsite", "ServiceLevelCode"=>"ND", "ServiceLevelGroup"=>5, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"UNY", "ItemNumber"=>"939-6888"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2015-06-05T23:59:59", "ServiceLevelDescription"=>"ProSupport", "ServiceLevelCode"=>"TS", "ServiceLevelGroup"=>8, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"939-7718"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"422-0008"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"421-9491"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"421-9982"}
    ]}
],
"InvalidFormatAssets"=>{"BadAssets"=>[]}, "InvalidBILAssets"=>{"BadAssets"=>[]}, "ExcessTags"=>{"BadAssets"=>[]}, "AdditionalInformation"=>nil}

The following code returns the full array of hashed instead of looping through the hashes.
@hash['AssetWarrantyResponse'][0]['AssetEntitlementData'].each do |k| k['StartDate'] end

returns:
[{"StartDate"=>"2022-06-07T00:00:00", "EndDate"=>"2022-06-08T00:00:00", "ServiceLevelDescription"=>"Dell", "ServiceLevelCode"=>"DL", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"999-0036"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-05T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"422-0052"}, {"StartDate"=>"2015-06-06T00:00:00", "EndDate"=>"2017-06-05T23:59:59", "ServiceLevelDescription"=>"Next Business Day Onsite", "ServiceLevelCode"=>"ND", "ServiceLevelGroup"=>5, "EntitlementType"=>"EXTENDED", "ServiceProvider"=>"UNY", "ItemNumber"=>"939-7368"}, {"StartDate"=>"2015-06-06T00:00:00", "EndDate"=>"2017-06-05T23:59:59", "ServiceLevelDescription"=>"ProSupport", "ServiceLevelCode"=>"TS", "ServiceLevelGroup"=>8, "EntitlementType"=>"EXTENDED", "ServiceProvider"=>"DELL", "ItemNumber"=>"939-7738"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2015-06-05T23:59:59", "ServiceLevelDescription"=>"Next Business Day Onsite", "ServiceLevelCode"=>"ND", "ServiceLevelGroup"=>5, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"UNY", "ItemNumber"=>"939-6888"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2015-06-05T23:59:59", "ServiceLevelDescription"=>"ProSupport", "ServiceLevelCode"=>"TS", "ServiceLevelGroup"=>8, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"939-7718"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"422-0008"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"421-9491"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"421-9982"}]

Could someone point me in the right direction? I want to loop through each hash.

A: Array#each returns the original array. In calling each with a block on the "AssetEntitlementData", you'll call the block on each hash in the array, and then return the original array. If you're trying to return an array of "StartDate" values, try this:
@hash['AssetWarrantyResponse'][0]['AssetEntitlementData'].map do |h|
  h['StartDate']
end

Array#map will return an array with the result of calling the block on each element.


text:
Q: Color scale conditional formatting for mix of text and number in Excel I would like to use the color scale conditional format on a column in Excel. I had to change some of the numbers to text because I wanted to distinguish between when the value was <1% and actually 0%. But when I did that, it messed up the color scale:

You can see that when there is text that reads "<1%" it removes the color formatting. How do I make it keep the formatting for those? I'd like it to be the same color as 0%.

A: Setup a conditional format with the following formula:
=AND(A1>0,A1<0.01)

And apply the following custom number format:
<1%

Then apply the second condition with the gradient.

You should end up with something like this:

(note the value of cell A1)


text:
Q: Why isn't this webkit keyframe valid .less? I have a little keyframe animation I use occastionally, it looks like so:
@-webkit-keyframes zoom-zoom {
    0% {
        -webkit-transform: scale(.1);
        opacity: 0;
    }
    70% {
        -webkit-transform: scale(1.2);
        opacity: 1;
    }
    100% {
        -webkit-transform: scale(1);
    }
}

Works fine in a .CSS file but I'm converting this site to use less.js so all my stylesheet are getting rewritten, but this won't process. It throws an error when it gets to 0% saying it's not valid.
Any ideas?

A: I'm using less.php to compile .less to .css and it handles CSS3 animations properly. You can use the less.php demo to see it for yourself.
I guess this is a bug in the less.js compiler, you may want to consider reporting in on the github bug tracker of less.js. Till you get an official answer there, you can just use less.php for compiling it.

A: I guess that less was written before people started using these animations, so doesn't nknow what they are.
I use SASS (same thing but better :) ), which parses them fine. Alternatively, maybe less has a newer version where they parse them.


text:
Q: How to connect to a database and get data from multiple tables in nodejs? I created a connection to a database where many tables related to subjects (eg:- subject1, subject2, subject3 ...).
Every subject table has two columns they are, 'IndexNo, Result'. I want to get results related to the same index no. from every table (One student results for many subjects) and push it into an array. How to do that?
This is my code and it returns many errors.
    const mysql = require('mysql');

    var connect = mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'',
    database:'results_center'
    });

    var studentid = 1234;
    var results = [];
    var i =0;
    for(i=1;i++;i<8){

        var newResult;
        connect.query("select result from subject"+i+" WHERE Index_No = " + studentid,(err,result)=>{
            newResult = result;
        });
            results[i] = result;
    }
      connect.end()
      console.log(results);

A: Convert callback to promise and use Promise.all to get all result.
const util = require('util');
const query = util.promisify(connect.query);

var i = 0;
var promises = [];
for(i=1;i++;i<8){
    promises.push(query("select result from subject"+i+" WHERE Index_No = " + studentid));
}

Promise.all(promises).then(results => {
  connect.end()
  console.log(results);
})

A: var mysql = require('mysql');
var con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'results_center'
});

con.connect(function(err) {
    if (err) throw err;
    console.log("connected to mysql");

    var subjectResults = [];
    var studentid = 1234;
    var sql = '';

    var i = 0;
    for (i = 1; i++; i < 8) {
        sql = "select result from subject" + i + " WHERE Index_No = " + studentid;
        con.query(sql, function(err, results, fields) {
            subjectResults.push(results);
        });
    }
});


text:
Q: BigQuery REGEXP_REPLACE referencing capture group in the replacement expression I'm very new to Regex so this may seem a very dumb question.
I've been playing around with captured groups in Google Sheets, without any problems, but when I try and apply it to BigQuery, it doesn't seem to work and I can't find out how to implement the syntax.
I looked round and this seems to be the closest answer, but I can't make it work:
Find and replace using regular expression, group capturing, and back referencing
I want to reference a capture group in the replacement expression to either extract or replace £ 1,000.23 in this text:
random text £ 1,000.23 other text
I've got 3 groups:
(.+)
(£\ *[\d\.\,]+)
(.+)
It may not be the best example, but I really want to understand how to use a capture group in the replacement part so I'm not looking for an alternative solution.
The code below literally returns '$2' rather than '£ 1,000.23'.
SELECT
  note,
  REGEXP_REPLACE(note,r'(.+)(£\ *[\d\.\,]+)(.+)','$2') AS note2
FROM
  `project.dataset.table`
LIMIT
  100

Thanks for any help!

A: According to the replacement note in the doc, I think the following should work:
SELECT
  note,
  REGEXP_REPLACE(note,r'(.+)(£\ *[\d\.\,]+)(.+)','\\2') AS note2
FROM
  `project.dataset.table`
LIMIT
  100


text:
Q: Problem uploading images in cpanel in laravel 7 I am trying to upload images on a shared hosting but am unable to upload. On my machine it works well but when I host i cant figure how to change the paths.All the other pages are working fine except uploading images.
on my controller
foreach ($images as $image){
         $move=$image->move(public_path().'/images2/',time().'_'.$image->getClientOriginalName());
         if($move){
         $imagedata=Images::create([
        'title'=>time().'_'.$image->getClientOriginalName(),
        'filename'=>time().'_'.$image->getClientOriginalName()
        ]);

Displaying the previous images is okay with this code on the view side
 @foreach($product_images as $image)

first ? 'active' : '' }}">

 filename}}"/>

@endforeach

A: i think your problem is here with the wrong "," :
$move=$image->move(public_path().'/images2/',time().'_'.$image->getClientOriginalName());

change it to:
$move=$image->move(public_path().'/images2/'.time().'_'.$image->getClientOriginalName());

and make sure your folders are same name as you wrote in your code because host is sensitive to uppercase or lowercase

A: I added this to index php though not sure whether it is secure but it works
$app->bind('path.public', function() {
  return realpath(__DIR__.'/../public_html/');
});


text:
Q: How does the compiler handle subtraction of unsigned integers? I am unable to understand a simple arithmetic operation between two unsigned integers; why is the result "802"?
Assuming integer number size is 32-bits guaranteed by compiler.
#include <stdio.h>
#include <stdint.h>

int main(int argc, char const *argv[])
{
    uint32_t Temp1;
    Temp1 = (uint32_t)801 - (uint32_t)0xFFFFFFFF; // Two Unsigned Integers

    uint32_t Temp2;
    Temp2 = 801 - 0xFFFFFFFF;// Two Signed Integers and result assigned to unsigned

    unsigned int Temp3;
    Temp3 = (unsigned int)((unsigned int)801 - (unsigned int)0xFFFFFFFF); // Two Unsigned Integers

    int32_t Temp4;
    Temp4 = 801 - 0xFFFFFFFF;// Two Signed Integers

    printf("Temp1: %d %u\n",Temp1,Temp1 );
    printf("Temp2: %d %u\n",Temp2,Temp2 );
    printf("Temp3: %d %u\n",Temp3,Temp3 );
    printf("Temp4: %d %u\n",Temp4,Temp4 );
    return 0;
}

Output:
Temp1: 802 802
Temp2: 802 802
Temp3: 802 802
Temp4: 802 802

How compiler will deal with it if I put the expression in an if condition? Will it cast the expression ((uint32_t)OPERAND_1 - (uint32_t)0xFFFFFFFF) to signed integer or unsigned integer, and then evaluate?
if(((uint32_t)801 - (uint32_t)0xFFFFFFFF) > (uint16_t)1500)
{
    printf("Hello All\n");
}
else
{
    printf("Hello None\n");
}

A: The hexadecimal constant 0xFFFFFFFF, assuming an int is 32-bit, has type unsigned int.  As a result, when used in an expression with 801, which has type int, the latter is converted to type unsigned int as a result of the usual arithmetic conversions.
At no point in the above examples is arithmetic being done on signed types, so there is no implementation defined behavior regarding signed wraparound or the representation of negative numbers.
Section 6.3.1.8 of the C standard says the following regarding conversion of integer types:

If both operands have the same type, then no further conversion is
  needed.
Otherwise, if both operands have signed integer types or both have
  unsigned integer  types,  the  operand  with  the  type  of  lesser
  integer  conversion  rank  is converted to the type of the operand
  with greater rank.
Otherwise,  if  the  operand  that  has  unsigned  integer  type  has
  rank  greater  or equal  to  the  rank  of  the  type  of  the  other
  operand,  then  the  operand  with signed  integer  type  is
  converted  to  the  type  of  the  operand  with  unsigned integer
  type.
Otherwise, if the type of the operand with signed integer type can
  represent all of the values of the type of the operand with unsigned
  integer type, then the  operand  with  unsigned  integer  type  is
  converted  to  the  type  of  the operand with signed integer type.
Otherwise,   both   operands   are   converted   to   the   unsigned
  integer   type corresponding to the type of the operand with signed
  integer type

The third paragraph is the one that takes effect in this case, since int and unsigned int are of the same rank.  This means that all arithmetic above is done on unsigned int types.
Operations on this type happen modulo 232, which effectively means that the values wrap around.  Subtracting 0xFFFFFFFF from 801 wraps around to result in 802, which is what gets printed in all cases.
To elaborate on the wraparound behavior, let's take as an example an unsigned 3-bit integer type which can have values 0 thru 7.  Suppose we were to calculate 3 - 7 with this type.  This is analogous to the subtraction you're doing since the value being subtracted is the maximum value the datatype can hold.
Now we subtract:

*

*3 - 1 = 2

*3 - 2 = 1

*3 - 3 = 0

*3 - 4 = 7

*3 - 5 = 6

*3 - 6 = 5

*3 - 7 = 4

Note how the value wraps around once the second operand is larger than the first, and that effective result is the same as adding 1.  This is the same as in your examples.

A: In C, the unsigned arithmetic is done at modulo 2^n, where n are the number of bits of the unsigned integer.

A: Most of the time, computers use what's called 2's complement to represent signed integers. 0xFFFFFFFF is -1 for 4 bytes int.
 Two's complement - Wikipedia
#include <stdio.h>
#include <stdint.h>

int main(int argc, char const *argv[])
{
    uint32_t Temp1;
    Temp1 = (uint32_t)801 - (uint32_t)0xFFFFFFFF; // Two Unsigned Integers

    uint32_t Temp2;
    Temp2 = 801 - 0xFFFFFFFF; // Two Signed Integers and result assigned to unsigned

    unsigned int Temp3;
    Temp3 = (unsigned int)((unsigned int)801 - (unsigned int)0xFFFFFFFF); // Two Unsigned Integers

    int32_t Temp4;
    Temp4 = 801 - 0xFFFFFFFF; // Two Signed Integers

    printf("Temp1: %d %X %u %d\n",Temp1,Temp1, Temp1, 0xFFFFFFFF );
    printf("Temp2: %d %X %u %X\n",Temp2,Temp2, Temp2, 0xFFFFFFFF );
    printf("Temp3: %d %X %u %u\n",Temp3,Temp3, Temp3, 0xFFFFFFFF );
    printf("Temp4: %d %X %u %x\n",Temp4,Temp4, Temp4, 0xFFFFFFFF );
    return 0;
}

Output:
Temp1: 802 322 802 -1
Temp2: 802 322 802 FFFFFFFF
Temp3: 802 322 802 4294967295
Temp4: 802 322 802 ffffffff

A: In clock arithmetic, if you add to a set of numbers the modulus minus one, the net effect is the same as adding 1.  On the other side, substracting modulo minus 1 to a number has de effect of adding one.  If you subtract 11h to 06h you get 07h in the clock.  In this case you are substracting 2^32 - 1 to 801, and that should be a negative number.  To conserve unsignedness, you have to add 2^32 to the result, to get the number fitting in the 0..2^32-1 range, so that is 801 - (2^32 - 1) + 2^32 = 801 - 2^32 + 2^32 -(-1) = 802.


text:
Q: how to set Headquarters in schema.org json ld this is my json ld
<script type="application/ld+json">
{ "@context" : "http://schema.org",
  "@type" : "Organization",
  "legalName" : "example",
  "url" : "https://www.example.com/",
  "description" : "Company",
  "logo" : "logo.jpg",
  "sameAs" : [ " https://www.facebook.com/example"]
}
</script>

for Headquarters what attribute need to be used?

A: There is no such property like Headquarters. But there are some possibilities to display relations between different offices and organization levels. Look further to following properties:

*

*https://developers.google.com/search/docs/data-types/corporate-contact

*https://schema.org/department

*https://schema.org/foundingLocation

*https://schema.org/parentOrganization

*https://schema.org/subOrganization
Related to your screenshot:
Informations from your screenshot are actually coming from Wiki / DBpedia entry for the firm. If you look at this page http://dbpedia.org/page/Google you will see, the Headquarters information from your screenshot is actually a kind of location property, like on my screenshot:


text:
Q: Logo Quiz app rejected by App Store three times! I made a Logo Quiz app for my country, and of course it includes protected third-party logos in app icon and screenshots, just like hundreds of other Logo Quiz apps already out on the App Store. Version 1.0 and 1.1 got approved and is out on the App Store, but I want to get version 1.3 out, but it keeps getting rejected.
The reason they give me is this: Your app includes protected third-party logos in the app icon, screenshots, or previews.
And it has now gotten rejected three times! Does anyone have a clue what to do to get it approved? Does same Apple-reviewer review my app? Could it work to delete the app, and create a new one to get a new reviewer?

A: I would probably rip out all the logos and see if your app is viable without the copyright issues involved with third party logos - especially ones in your marketing material.
Barring that, let's assume you can and do get clearance to use the logos of the companies and then resubmit, I'm thinking you're going to have a long road to approval even if you get past using / selling / profiting by / advertising against other people's logos.
If you look at the summary guidelines, your next likely risks of being rejected summarily for "hundreds of other apps" in the same category.

*

*https://developer.apple.com/app-store/review/rejections/
Also the "lasting value" qualifier would likely be a hurdle for you to pass - especially if your app functionality could be easily done as a web app (take or leave that last one if it applies to you - I have no way to know if your logo quiz uses unique iOS API but the broad category seems better done as web apps).
There is also discussion on these two posts about "but officer, other people were speeding" and how to appeal a metadata rejection:

*

*App was rejected for use of protected 3rd party material

*How to react on Appstore rejection of screenshots?