text:
Q: Geolocation API Permissions Web Browser I'm using this code to get the user geoposition. All goes well until the user deny permission to get the location. It seems this option gets cached and I don't know how reset it.
Is there any way to re-ask permission? Thanks in advance!
if (navigator.geolocation) {

        navigator.geolocation.getCurrentPosition(function(position) {

            // Success Callback

        }, function(error) {
            //error Callback

        },{
                  //options
            });
     }else{
        //geolocation not available
     }

A: Pretty sure this is a browser/device setting stored per site.  I think the point is that you can't reset this from a script as it would defeat the point of the prompt in the first place.  I believe the only way to reset is to change the setting in the browser/device.

A: Like bgreater said, it depends on browser. But when user deny permission to get location error function will be called with error object. This error object contains error code. When error code equals 1 it means that user deny permission.
var errorTypes = {
    0: "Unknown error",
    1: "Permission denied by user",
    2: "Position is not available",
    3: "Request timed out"
};

I think, you can check this error code and display some kind of information to user.


text:
Q: Is there a way to define "area" of a non-discrete & non-empty open or closed bounded subset of complex plane, topologically? One of the properties of a non-discrete & non-empty , open or closed bounded subset of a complex plane could be "Area". Is there a way to define "area" of such a set in topological terms ?

A: No, not in any useful way, as $f(z)= \alpha z$ for $\alpha >0$ in the reals is a homeomorphism of $\Bbb C$ and if we could define $\operatorname{area}(U)$ in purely topological terms, $U$ and $\alpha U = f[U]$ would have the same value, even though we stretched or shrunk $U$ by $\alpha$. E.g. You would intuitively expect that the unit disk has a smaller area than the disk of radius 2, but they're homeomorphic, so a topological definition would have to give them the same value, so no monotonicity (larger subsets have larger area) can hold.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Making a button semi-transparent in android
Possible Duplicate:
How to Set Opacity (Alpha) for View in Android

i want to ask two questions:
1) i want to make the buttons in my main.xml i.e simply the first screen look semi-transparent.
It should be such that the background image can be partly-seen through it. But the button should maintain its normal size and looks.
2)(This is regarding another button in another view) i changed the background of buttons using
android:background="#2563EA"

but now when it is clicked it does not change its color. how can i reset it. also can anyone tell me how to give it a new onClick color.

A: To change the appearance of a button depending on state, use a StateList.

A: *

*Use the alpha property for the transparency of the color. Also see this thread.

*You can dynamically change the color by using the OnTouch event. Or better, you can assign the background in the XML to be a selector.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/button_pressed" /> <!-- pressed -->
    <item android:state_focused="true"
          android:drawable="@drawable/button_focused" /> <!-- focused -->
    <item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>


text:
Q: Probabilities in infinite Bernoulli type of series While I was trying to solve the 1st problem from here I run into the following problem: find the probability of the events such as $1122213$ or $2122111116$ in infinite series of dice rolls which end on $\geq 3$ roll. The thing that the length of such series is not limited confuses my intuition a lot. How does one think about such problems. Is there a good book or article where I can find math that is relevant to such problems? I'm not interested in solving the original problem from the link, but finding the probabilities of aforementioned events.

A: The probability to roll a number $\ge3$ is $\frac23$. Thus the expected number of rolls is $\frac32$, of which exactly one will be $\ge3$ and thus an expected number of $\frac12$ will be $\lt3$. Then by linearity of expectation, the expected total is
$$
\frac12\cdot\frac{1+2}2+1\cdot\frac{3+6}2=\frac{21}4\;.
$$

A: You can gain some intuition, if you are familiar with this problem:
A 2-dimensional plane is given. what is the probability of hitting a point on the plane. It is zero. But you can have non-zero probabilities by considering a region in the plane.
The same is applied to this problem. an infinite sequence happens with zero probability, while a limited sequence has a non-zero probability. So, for the first case, you may assume that the rest of the sequence exists, but it can have all the possibilities.
Hope it helps.


text:
Q: Backbone Marionette / ItemView tag I want to render a <select> with <option>'s based on a collection using Marionette's ItemView. Because the options need to have actual "values" in order for my App to work, I'm a bit unsure as to how I get Marionette to handle this? If I set a tagName: 'option' in my ItemView, I'm not sure how to add the option after rendering. I thought I could just let the <option value="<%= id %>"> in the template, but that causes a double <option> element to render because I had already specified it in the tagName attribute of my ItemView. What's a best practice for doing this? My template looks like this:
<script type="text/template" id="sport-item-view">
    <option value="<%= id %>"><%= name %></option>
</script>

A: Are you using a CollectionView as the parent view type to render the collection of models in to the select? If you are, you shouldn't be.
Since the option items need everything in attributes, rendering a template for each option becomes painful as you've already encountered. Instead, use a single ItemView for the entire select box. An ItemView can take a collection in to it, and you can access that collection at items inside of the template. This makes it very trivial to create a select box out of a collection, with a single view:
<script type="text/html" id="select-template">
  <% _.each(items, function(item){ %>
    <option value="<%= item.id %>"><%= item.get("someValue") %></option>
  <% }) %>
</script>

var SelectView = Marionette.ItemView.extend({
  tagName: "select"
});

var s = new SelectView({
  collection: myData
});

s.render();

The downside to this is that you only have 1 view for your select box, which means you have to read the selected value from the select box to figure out which model you are dealing with. But this is only a couple of lines of code, and it saves a ton of headache otherwise.

A: You can simply use attributes.
You can override constructor in this way:
constructor : function (options) {
  this.attributes = {
    value : options.model.id
  };
  ItemView.prototype.constructor.apply(this, arguments);
}

And your template will be like this:
<%= name %>

http://jsfiddle.net/vpetrychuk/6Bk9T/

A: Perhaps it's better to handle this type of view in a more traditional sense by just adding options after render or perhaps on a triggered event. Here is what I did to add options dynamically based on fetched data:
        var mySelect = this.ui.mySelect; // a reference to select from ui hash
        mySelect.html('');  //clear

        //for each data item add an option
        _.each(items, function (item) {
            mySelect .append($('<option/>', {
                value: item.id,
                text: item.description
            }));
        });


text:
Q: WCF Service Implementation I've scoured the internet, several books, and even consulted some peers.  Nothing really states if what I'm attempting to do is bad practice or not.  The short; is I'm just doing a fire-and-forget from the client.
[ServiceContract]
public interface ICustomerInformation
{

       [OperationContract(IsOneWay = true, IsTerminating = true, IsInitiating = false)]
       ICustomerAccount GetCustomerDetails (string First);

}

[DataContract]
public interface ICustomerAccount
{
      _firstName = firstName;

      [DataMember]
      string FirstName
      {
            get { return _firstName; }
            set { _firstName = value; }
      }
}

My original thought was an implementation similar to this to abstract the properties; so the server and application tied to the server could make use of these properties.  But is that really a smart thing to do?  Or even good practice?
My assumption was; by adding this layer to the service it will allow user interfaces accessing the service to simply push it's data; while allowing the functionality to tie straight into the data.  So if a users data changes, the service will change it for the functionality on the server.
Is that a bad way to view?  Or attempt this?  Am I misguided on this interpretation?
Like I said above; the goal is a logical abstraction where multiple styles of interfaces push its data to the service.  The service then takes the input; performs a function based on those variable input values.
If I've worded it poorly let me know so I can edit; or think of a better means of explanation.  Any assistance would be great.

Update:
I'm trying to create a universal interface; where any application or client interface for that matter inputs data.  Once the data is submitted to the service; the server takes it.  No data needs to be returned; but the server just runs through commands utilizing the client side information.
Essentially, I'm attempting to make data universally pushed through the service for the server to do task.  The client doesn't need to be aware of any of the server task that it's doing.
My thought process was to logically separate UI / user input through the service; then the service invokes server side functions with information it gathered from the user.
Example:
Textbox(Name) --> Service --> Server stores Name as variable to perform a series of task: Write Name to database, name textfile by user name, and so on.

A: If I understand correctly, it seems like you want to implement some sort of message/command passing model, which seems completely legitimate to me. Take a look at this article for instance that talks about utilizing commands as architectural pattern. Those commands can be serialized over the wire from client to (WCF) service which allows you to create a highly maintainable service layer (as explained here).
So back to your original question: yes this seems like a legitimate model to use. Though I would advise to read those articles. They might give you some more background on these kinds of models.


text:
Q: the best way to know if a website used my script? i want the best php way
to know if some one used my script of his server

A: You have 2 choices (that I can think of):

*

*Make your script "hot linking" something on your server.

*Use CURL (or something similar) in your script to send something to your server (of course the end user can always remove these calls from your script).

Bottom line, this is quite unusual and unreliable (and can even break privacy policies), you should avoid this.

A: The best way?  Include a request in the header comment of the script saying to the effect of "if you use this script, please drop me a line at myname@email.com".
Placing any hotlinks, pop-ups or any other kind of nonsense not only discourages people from using your script, but could actually impose a performance penalty and can be easily disabled.
If you don't want people to use your script, don't place it anywhere where the public can get to the source.  If you want people to use it, don't obsess over usage....if it becomes popular you definitely will hear from users (who will be asking for enhancements and/or bug fixes).

A: If you mean he took the code and put it in his code on his server, then you can't.
If you mean him 'hot linking' to a script on your server, then put some code to generate a js popup or something like that

A: Place some code in your script that sends you an email with the name of the root address.. not sure how ethical that is.


text:
Q: Reactjs not rendering information correctly I'm trying to implement a form where I can delete specific inputs using React. The problem is, react doesn't seem to be rendering the information correctly. This is my render function:
render: function(){
  var inputItems;
    if (this.state.inputs){
      inputItems = this.state.inputs.map(function(input){
      console.log(input)
      return (
        <Input
          input={input}
          onDestroy={this.destroy.bind(this, input)}
          onEdit={this.edit.bind(this, input)}
          editing={this.state.editing === input.id}
          onCancel={this.cancel} />
      );
    }, this);
  }

(...)
// this isn't the actual render return
return {inputItems}

and my destroy function:
destroy: function (input) {
  var newInputs = this.state.inputs.filter(function (candidate) {
    return candidate.id !== input.id;
  });

  this.setState({
    inputs: newInputs
  });
},

The actual destroy function is getting called through a child component via (Remove). The interesting thing is that when I console log my inputs, as seen in the render function, the correct inputs are shown - the one I called the destroy function on is gone. But the incorrect inputs are rendered - it's always the very last one that disappears, not the one I called the destroy function on. So for example, I'll initially log:
First Name
Last Name
Email

and call the destroy function on the Last Name. The console.log will show:
First Name
Email

but the actual rendered information will show:
First Name
Last Name

Thanks!

A: Figured it out. Has to do with React child reconciliation. Added a key={input.id} to the <Input> tag and it works.
More information here under child reconciliation and dynamic children.
http://facebook.github.io/react/docs/multiple-components.html


text:
Q: Loosing old aggregated records after adding repartitioning in Kafka I had a Kafka stream with following operations:
stream.mapValues.groupByKey.aggregate. Aggregation is adding records into the list basically.
Now I changed implementation to that:
stream.flatMap.groupByKey.aggregate. FlatMap is duplicating record: first record is exactly the same like in old implementation and second one has key changed. So after the change of implementation repartitioning is happening, while before, it wasn't (and it's fine). My problem is that after releasing the change, old aggregated records for old key disappeared. From the moment of change everything works as it should, but I don't understand this behaviour. As I understand, as I did not change the key, it should land on the same partition as previously and aggregation should continue adding messages to old list, not starting from beginning. Could anyone help me understand why it's happening?

A: If you change your processing topology, in general, you need to reset your application and reprocess all data from the input topic to recompute the state.
In your case, I assume that the aggregation operator has a different name after the change and thus, does not "find" its local state and changelog topic any longer.
You can compare the names for both topologies via Topology#describe().
To allow for a smooth upgrade, you would need to provide a fixed name for aggregate() via Materialized.as(...). If you provide a fixed name (ie, same in old and new topology) the issue would go away. However, because your original topology did not provide a fixed name, it's hard to get out of the situation.


text:
Q: Checking if matrix of 1s and 0s are connected - C++ The goal is to create a matrix where all the 0s are connected (touching either up, down, left or right). I generated a 10/19 matrix of 0s and randomly added 1s. Now I want to step through the matrix and change values such that all 0s are connected, but I am struggling with that part. Any help is greatly appreciated!
#include <iostream>

#include <string>
#include <vector>
using namespace std;

int main () {
  //generate matrix of 0s
  int map[10][19] = {{0}};
  int a = 10;
  int b = 19;

  //display matrix

  for (int i = 0; i < a; ++i) {
          for (int j = 0; j < b; ++j) {
              std::cout << map[i][j] << ' ';
          }
          std::cout << std::endl;
   }
   cout << "\n" << endl;

  //adds 1s to matrix
  for (int i = 0; i < a; ++i) {
      for (int j = 0; j < b; ++j) {
                  map[i][j] = 0 + rand() % 2;
          }
  }

  //display matrix
  for (int i = 0; i < a; ++i) {
          for (int j = 0; j < b; ++j) {
              std::cout << map[i][j] << ' ';
          }
          std::cout << std::endl;
   }
   cout << "\n" << endl;

First output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Second output:
1 1 1 0 0 0 0 0 1 1 0 1 0 0 1 1 1 1 0
0 1 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1 1 1
1 1 1 0 1 0 1 1 0 1 0 1 1 1 0 0 0 0 0
0 0 1 0 0 1 0 1 1 1 0 0 1 0 1 1 1 1 0
1 0 1 1 1 0 1 1 1 1 1 0 1 0 0 1 1 0 0
0 0 1 0 0 1 1 1 0 1 0 1 1 0 0 1 1 1 1
1 0 0 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 0
0 1 1 1 0 1 1 0 1 0 1 0 0 0 1 1 0 0 0
1 1 0 1 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 1 1 1 1 1 0 1 1 1 0 1 1 0


text:
Q: IndexedDB crashes when adding record with Image When I add an image (2-3mb base64 string) into my indexedDB it seems to crash with using the web app from an iPad/Safari (works fine in Chrome on Desktop).
InvalidStateError (DOM IDBDatabase Exception 11): Failed to execute 'transaction' on 'IDBDatabase': The database connection is closing.

Object trying to insert:
{
categoryNo: "C0103"
imageData: [{base64Image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD…aUOUbIHsTUsVwQRZJF8/94dMe9TxKzK7ugwhK1s4su8T/2Q==",
imageUploaded: false
}

I have used indexedDB for storing strings and it works fine, just when i try to add the object, with the base64 image.
bcUpdateIDB: function(sInspectionNo, sLineNo, sCategory, oRecord){
            var oController = this;
            var objectStore = oController.myDB.transaction("imageDB").objectStore("imageDB");

        var items = [];
        objectStore.openCursor().onsuccess = function(event) {
            var cursor = event.target.result;
            if (cursor) {
                items.push(cursor.value);
                cursor.continue();
            } else {
                dataRecords = items;
                var oTransaction = oController.myDB.transaction(["imageDB"], "readwrite");
                var oDataStore = oTransaction.objectStore("imageDB");

                var recordFound = false;
                for (var i=0; i<dataRecords.length;i++){
                    var oDataRecord = dataRecords[i];
                    if(oDataRecord.lineNo === sLineNo && oDataRecord.inspectionNo === sInspectionNo && oDataRecord.category === sCategory){
                        recordFound = true;
                        oDataStore.delete(oDataRecord.id);
                        if(oRecord.imageData.length > 0){
                            oDataStore.add(oRecord);
                        }

                    }
                }

                if(!recordFound){
                    oDataStore.add(oRecord);
                }

            }
        };

In Safari it seems to hang on '.add()', this works in Chrome. Also, other add add/delete operations on a different transaction work fine.

A: This error is not related to what you are trying to store. This error is due to when you are trying to store an object in the database within your code. You did not post a sufficient amount of code to investigate and explain the problem.
Without knowing what the code looks like, my go to guess is the usual one. Do not use a global database variable. Become more familiar with how to write asynchronous javascript.
Edit:
Based on your revisions, my next guess is that you are starting a new transaction from within another transaction. Transactions automatically end after a certain period of time, after the point in time when there are no more requests processing that use that transaction. The error message indicates the transaction is inactive, which means you did some request call (request.add, request.remove, etc) too late, after the point in time the transaction ended.
There are many ways to fix it, but without getting two complicated, try the following. Whenever you are going to perform an unknown amount of requests, share the same transaction for everything. Use one transaction instead of two. This will keep the transaction alive.
Briefly:
bcUpdateIDB: function(sInspectionNo, sLineNo, sCategory, oRecord){
        var oController = this;
        var oTransaction = oController.myDB.transaction("imageDB", "readwrite");
        var objectStore = oTransaction.objectStore("imageDB");
// ...
        } else {
            dataRecords = items;
            // Now this reuses the one transaction instead of a new one
            var oDataStore = oTransaction.objectStore("imageDB");

As to why you only encounter the error sometimes? Well my guess is small string operations are faster so the transaction doesn't timeout, but with larger objects the requests are slower so the timeout actually happens.


text:
Q: Chromecast displays weird artifacts in my custom receiver web app So I built a Chromecast receiver -- which is just a web app that can communicate with another device.
When I display it on the cc it sometimes puts a dark tint over the picture with weird boxes of no tint around my elements. The element margins are far smaller than those clear boxes. In fact, there are no elements that have margins or padding that looks like these clear boxes.
This only happens on Chromecast. On my chrome browser it doesn't happen. I use Materializecss as my stylesheet if that matters.


text:
Q: how to add price in cart from dropdown I want to add price when click one of them

                            <select class="form-control" type="text" value="">
                              <option value="0">Not Required</option>
                              <option value="50">Before Care only(6am to 9am)</option>
                              <option value="60">After Care Only (5pm to 7pm)</option>
                              <option value="110">Both</option>
                              </select>

It should be added their in cart total

{{$cdetail ->c_price}}

         <form action="{{ route('/payment') }}" id="theForm" method="POST">
          @csrf
          <input type="hidden" id="price" name="price" value="{{$cdetail ->price}}">

          <button type="submit" class="btn radius-xl text-uppercase">Buy This Courses</button>
         </form>

Using ajax and getting value and put in "prictot"

A: You can simply get value of select-box and
 and add them and put total value to your div and hidden inputs . i.e :

$(document).ready(function() {
//on change of slect
  $("#priceadd").on('change', function() {
  //get select value
    var optionText = parseInt($(this).val());
    //get text inside h4
    var realprice = parseInt($("#prictot").text());
    //add
    var total =optionText +  realprice;
    //add total to div nd inputs
    $("#prictot").text(total)
    $("#price").val(total)
  });
});

  <select class="form-control" id="priceadd">
    <option value="0">Not Required</option>
    <option value="50">Before Care only(6am to 9am)</option>
    <option value="60">After Care Only (5pm to 7pm)</option>
    <option value="110">Both</option>
  </select>

110

<form action="{{ route('/payment') }}" id="theForm" method="POST">
  @csrf
  <input type="text" id="price" name="price" value="110">

  <button type="submit" class="btn radius-xl text-uppercase">Buy This Courses</button>
</form>

If you need to get the total which was already there inside
 before the value of it get change you can add a custom attribute to
 tag which will have the previous value . i.e :

$(document).ready(function() {
//on change of slect
  $("#priceadd").on('change', function() {
    //get old value
    var old_value = parseInt($("#prictot").attr('total-price'))
  //get select value
    var optionText = parseInt($(this).val());

    //add
    var total =optionText +  old_value;
    //add total to div nd inputs
    $("#prictot").text(total)
    $("#price").val(total)
  });
});

  <select class="form-control" id="priceadd">
    <option value="0">Not Required</option>
    <option value="50">Before Care only(6am to 9am)</option>
    <option value="60">After Care Only (5pm to 7pm)</option>
    <option value="110">Both</option>
  </select>

110

<form action="{{ route('/payment') }}" id="theForm" method="POST">
  @csrf
  <input type="text" id="price" name="price" value="110">

  <button type="submit" class="btn radius-xl text-uppercase">Buy This Courses</button>
</form>

A: There's probably no need to use a hidden input for the price you get from laravel. You can insert that value directly in the js code from your blade template. See solution below.

$("#priceadd").on('change', function () {
    let price = 100 // this is only for stackoverflow
    // in your project you do
    // let price = {{$cdetail->price}}
    let optionPrice = parseInt($("#priceadd option:selected").val())
    document.getElementById("prictot").innerHTML = optionPrice + price
});

Nothing selected

<select class="form-control" type="text" value="" id="priceadd">
  <option value="0">Not Required</option>
  <option value="50">Before Care only(6am to 9am)</option>
  <option value="60">After Care Only (5pm to 7pm)</option>
  <option value="110">Both</option>
</select>


text:
Q: Can anyone explain this snippet of Javascript? Can anyone explain the following code?  Forget the sine and cosine parts.  Is it trying to build a space for the object?
objectsInScene = new Array();

for (var i=space; i<180; i+=space) {

  for (var angle=0; angle<360; angle+=space) {

    var object = {};

    var x = Math.sin(radian*i)*radius;
    object.x = Math.cos(angle*radian)*x;
    object.y = Math.cos(radian*i)*radius;
    object.z = Math.sin(angle*radian)*x;
    objectsInScene.push(object);
  }
}

A: If I'm not much mistaken it's arranging objects in a hemispherical shape.
objectsInScene is an array of all these objects.

A: It's filling objectsInScene with a sphere of points (not a hemisphere), spaced space degrees apart.   The diameter is 2 times radius.


text:
Q: Decode Signature I've one signature field containing encoded values like 'iVBORw0KGgoAAAANSUhEUgAAApAAAACNCAYAAAAAYko8AAAAHGlET1QAAAACAAAAAA...' and i want to restore it back and put them into a list and display the signature as it was captured, in the page.
Please suggest me how to use Apex crypto class methods to solve my purpose.
<apex:page controller="AccountPDF11" contentType="image/png">
  <apex:image url="{!URLFOR($Resource.Hospital_Main)}"/>
  <apex:repeat value="{!m1}" var="key">
    <apex:pageBlock >
      <apex:outputText value="{!key}" />
      <apex:pageBlockTable value="{!m1[key]}" var="c">
        <apex:column value="{!c.name}"/>
        <apex:column value="{!c.call_Date_vod__c}"/>
        <apex:column value="{!c.signature_Date_vod__c}"/>
        <apex:column headerValue="signature">
          <apex:image value="data:image;base64,{!c.signature_vod__c}" />
        </apex:column>
      </apex:pageBlockTable>
    </apex:pageBlock>
  </apex:repeat>
</apex:page>

Here is my code, had to avoid crypto class It's working fine, showing signatures, but I need this page in pdf and render as pdf not supported here. Please help me here.


text:
Q: iOS: How to set the device serial number via application configuration in airwatch? In JAMF, you can use "App Configuration" to tell the device it's own serial number using something like this:
<dict>
    <key>device_serial_number</key>
    <string>$SERIALNUMBER</string>
</dict>

You just paste that directly into the "App Configuration" box in the "Mobile App" area of the dashboard:

This will tell the device it's own serial number, as that information is not available otherwise.
I'm wondering if you can do the same thing in AirWatch.  For their configuration, it's a list of key value fields.  I've tried a bunch of different items in the "value" field, such as:
{SerialNumber}, {serialNumber}, {Serial}, $SERIALNUMBER, {serialnumber}, {serial}, but it does not seem to work.
Anyone know how to inform an iOS device of it's serial number using AirWatch?

A: The AppConfig variable for serial number on AirWatch is {DeviceSerialNumber}.  Here's the full list:
{EmailDomain}
{EmailUserName}
{EmailAddress}
{EnrollmentUser}
{EnrollmentUserId}
{DeviceUid}
{DynamicScepChallenge}
{GroupIdentifier}
{SessionToken}
{DeviceFriendlyName}
{DeviceSerialNumber}
{UserPrincipalName}
{DeviceSerialNumberLastFour}
{DevicePlatform}
{DeviceModel}
{DeviceOperatingSystem}
{EmailUserNamePrompt}
{DeviceUidLastFour}
{DeviceReportedName}
{EmailPassword}
{DeviceAssetNumber}
{DeviceWLANMac}
{UserSmimeSigning}
{UserSmimeEncryption}
{SecureDeviceUdid}
{UserDistinguishedName}
{FirstName}
{LastName}
{EmailAddressPrompt}
{EmailDomainPrompt}

You can put this into the "Assignment" for an app here:

Once it's there you can access it via UserDefaults like this:
/**
 Retrieve the dictionary of keys stored by the MDM server

 - returns: dictionary of key/value pairs
 */
public func appConfig ()  -> Dictionary<String, Any>? {
    if let serverConfig = UserDefaults.standard.dictionary(forKey: "com.apple.configuration.managed")
    {
        return serverConfig
    }
    return nil
}


text:
Q: onCreate runs 2 times with singletop launch mode set Problem:
My Launching Activity creatively named LoadingActivity's onCreate method is called 2 times.
Manifest Content:
<manifest>
    <application>
        ...
        <activity
            android:launchMode="singleTop"
            android:name="com.awesome.app.activites.LoadingActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        ...
    </application>
</manifest>

First onCreate call is called with Bundle savedInstanceState which is null, shortly after which the onCreate method is called again, but this time with Bundle savedInstanceState which contains the following serialized content:
Bundle[{com.google.app_measurement.screen_service=Bundle[{referrer_name=LoadingActivity, id=1612091517631091562, name=null}], android:viewHierarchyState=Bundle[{android:views={16908290=android.view.AbsSavedState$1@a24446f, 2131296302=android.view.AbsSavedState$1@a24446f, 2131296313=android.view.AbsSavedState$1@a24446f, 2131296424=android.view.AbsSavedState$1@a24446f, 2131296445=android.widget.ProgressBar$SavedState@b25257c, 2131296581=android.view.AbsSavedState$1@a24446f, 2131296582=android.view.AbsSavedState$1@a24446f}}], androidx.lifecycle.BundlableSavedStateRegistry.key=Bundle[{}], android:lastAutofillId=1073741823, android:fragments=android.app.FragmentManagerState@a24ee05}]

Yes, this doesn't mean much, but it may be related to something at the bottom of the post.
Tried:
I have tried setting launchmode settings with android:launchMode="singleTop" for the LoadingActivty in my AndroidManifest.xml, but this does not help at all, it still runs the onCreate 2 times.
I have gone through my onCreate method, no where do I onCreate again or change ApplicationContext settings i.e. Orientation (physically or programmatically), etc.
Any idea why this happens and what I can do to resolve it.
For what it is worth, I have recently updated my deps and see this in my Manifest:

It compiles (change the package name for obv reasons) with the portrait launchmode, but I think this may have something to do with the double launch


text:
Q: How can System.String be properly wrapped for case-insensitivy? This question is not about managing Windows pathnames; I used that only as a specific example of a case-insensitive string.  (And I if I change the example now, a whole bunch of comments will be meaningless.)

This may be similar to Possible to create case insensitive string class?, but there isn't a lot of discussion there.  Also, I don't really care about the tight language integration that string enjoys or the performance optimizations of System.String.
Let's say I use a lot of Windows pathnames which are (normally) case-insensitive (I'm not actually concerned with the many details of actual paths like \ vs. /, \\\\ being the same as \, file:// URLs, .., etc.).  A simple wrapper might be:
sealed class WindowsPathname : IEquatable<WindowsPathname> /* TODO: more interfaces from System.String */
{
    public WindowsPathname(string path)
    {
        if (path == null) throw new ArgumentNullException(nameof(path));
        Value = path;
    }

    public string Value { get; }

    public override int GetHashCode()
    {
        return Value.ToUpperInvariant().GetHashCode();
    }

    public override string ToString()
    {
        return Value.ToString();
    }

    public override bool Equals(object obj)
    {
        var strObj = obj as string;
        if (strObj != null)
            return Equals(new WindowsPathname(strObj));

        var other = obj as WindowsPathname;
        if (other != null)
            return Equals(other);

        return false;
    }
    public bool Equals(WindowsPathname other)
    {
        // A LOT more needs to be done to make Windows pathanames equal.
        // This is just a specific example of the need for a case-insensitive string
        return Value.Equals(other.Value, StringComparison.OrdinalIgnoreCase);
    }
}

Yes, all/most of the interfaces on System.String should probably be implemented; but the above seems like enough for discussion purposes.
I can now write:
var p1 = new WindowsPathname(@"c:\foo.txt");
var p2 = new WindowsPathname(@"C:\FOO.TXT");
bool areEqual = p1.Equals(p2); // true

This allows me to "talk about" WindowsPathnames in my code rather than a implementation detail like StringComparison.OrdinalIgnoreCase.  (Yes, this specific class could also be extended to handle \ vs / so that c:/foo.txt would be equal to C:\FOO.TXT; but that's not the point of this question.)  Furthermore, this class (with additional interfaces) will be case-insensitive when instances are added to collections; it would not necessary to specify an IEqualityComparer.  Finally, a specific class like this also makes it easier to prevent "non-sense" operations such as comparing a file system path to a registry key.
The question is: will such approach be successful?  Are there any serious and/or subtle flaws or other "gotchas"? (Again, having to do with trying to setup a case-insensitive string class, not managing Windows pathnames.)

A: I would create an immutable struct that hold a string, converting the string in the constructor to a standard case (e.g. lowercase).
Then you could also add the implicit operator to simplify the creation and override the compare operators.
I think this is the simplest way to achieve the behaviour, plus you get only a small overhead (the conversion is only in the constructor).
Here's the code:
public struct CaseInsensitiveString
{
    private readonly string _s;

    public CaseInsensitiveString(string s)
    {
        _s = s.ToLowerInvariant();
    }

    public static implicit operator CaseInsensitiveString(string d)
    {
        return new CaseInsensitiveString(d);
    }

    public override bool Equals(object obj)
    {
        return obj is CaseInsensitiveString && this == (CaseInsensitiveString)obj;
    }

    public override int GetHashCode()
    {
        return _s.GetHashCode();
    }

    public static bool operator ==(CaseInsensitiveString x, CaseInsensitiveString y)
    {
        return x._s == y._s;
    }

    public static bool operator !=(CaseInsensitiveString x, CaseInsensitiveString y)
    {
        return !(x == y);
    }
}

Here is the usage:
CaseInsensitiveString a = "STRING";
CaseInsensitiveString b = "string";

// a == b --> true

This works for collections as well.

A: So you want a something that converts a string to an object, and if you convert two strings to two of those objects, you want to be able to compare these objects for equality with your own set of rules about the equality of the two objects.
In your example it is about upper and lower case, but it could also be about forward slashes and backward slashes, maybe you even want to define that the "word" USD equals to $.
Suppose you divide the collection of all possible strings in subcollections of strings that you'd define to be equal. In that case "Hello" would be in the same subcollection as "HELLO" and "hElLO". Maybe "c:\temp" would be in the same collection as "c:/TEMP".
If you could find something to identify your subcollection, then you could say that all strings that belong to the same subcollection would have the same identifier. Or in other words: all strings that you defined equal would have the same identifier.
If that would be possible, then it would be enough to compare the subcollection identifier. If two strings have the same subcollection identifier, then they belong to the same subcollection and thus are considered equal according to our equality definition.
Let's call this identifier the normalized value of the string. The constructor of your CaseInsensitiveString could convert the input string into the normalized value of the string. To check two objects for equality all we have to do is check if they have the same normalized value.
An example of the normalization of a string would be:

*

*Make the string lower case

*make all slashes backward slashes

*convert all words USD to $

*remove all thousand separators in numbers without thousand seperator

*etc, depending on when you want the strings to be equal.

According to the above the following Strings would all lead to the same normalized string:

*

*White House $ 1,000,000

*White House $ 1000000

*white house USD 1000000

We can define anything as a normalized string, as long as all strings that we define equal have the same normalized string. A good example would be

*

*white house $ 1000000

Note: I'm not going into detail about how to find words like USD and thousand separator. The importance is that you understand the meaning of normalized string.
Having said this, the only difficult part is to find the stringIdentifier. The rest of the class is fairly straightforward:
Code for the construction. The constructor takes a string and determines the subcollection it belongs to. I also added a default constructor.
public class CaseInsensitiveString : IEquatable<CaseInsensitiveString>
{
    private string normalized = "";

    public CaseInsensitiveString(string str)
    {
        this.normalized = Normalize(str);
    }

    public CaseInsensitiveString()
    {
         this.Normalize = Normalize(null);
    }
}

Equality: by definition, two objects are the same if they have the same  normalized value
See MSDN How to Define Value Equality for a Type
public bool Equals (CaseInsensitiveString other)
{
    // false if other null
    if (other != null) return false;

    // optimization for same object
    if (object.ReferenceEquals(this, other) return true;

    // false if other a different type, for instance subclass
    if (this.Gettype() != other.Gettype()) return false;

    // if here: everything the same, compare the stringIdentifier
    return this.normalized==other.normalized;
}

Note that this last line is the only code where we do actual equality checking!
All other equality functions only use the Equals function defined above:
public override bool Equals(object other)
{
    return this.Equals(other as CaseInsensitiveString);
}

public override int GetHashCode()
{
    return this.Normalized.GetHashCode();
}

public static bool operator ==(CaseInsensitiveString x, CaseInsensitiveString y)
{
    if (object.ReferenceEquals(x, null)
    {   // x is null, true if y also null
        return y==null;
    }
    else
    {   // x is not null
        return x.Equals(y);
    }
}

public static bool operator !=(CaseInsensitiveString x, CaseInsensitiveString y)
{
    return !operator==(x, y);
}

So now you can do the following:
var x = new CaseInsensitiveString("White House $1,000,000");
var y = new CaseInsensitiveString("white house $1000000");
if (x == y)
    ...

Now the only thing we have to implement is the Normalize function. Once you know when two strings are considered equal you know how to normalize.
Suppose consider two strings equal if they are equal case insensitive and forward slashes are the same as backward slashes. (bad English)
If the normalize function returns the same string in lower case with all backward slashes, then two strings that we consider equal will have the same normalized value
private string Normalize(string str)
{
    return str.ToLower().Replace('/', '\');
}

A: A shorter and more lightweight approach might be to create an extension method:
public static class StringExt
{
    public static bool IsSamePathAs(this string @this, string other)
    {
        if (@this == null)
            return other == null;

        if (object.ReferenceEquals(@this, other))
            return true;

        // add other checks
        return @this.Equals(other, StringComparison.OrdinalIgnoreCase);
    }
}

This requires far less coding than creating a whole separate class, has no performance overhead (might even get inlined), no additional allocations, and also expresses the intent pretty clearly IMO:
var arePathsEqual = @"c:\test.txt".IsSamePathAs(@"C:\TEST.txt");

A: Hmm... I don't think string case is the only challenge you have.  Let me ask you a couple of questions:
Is c:\myPath the same as c:/myPath?  How about file:////c:/myPath? Or how about \\myMachine\c$\myPath?
I kind of understand where you are headed and what you want accomplished, but it just seems like you're tunnel-visioned on a simple problem  - why build a framework that does what a simple .ToLower() vs ToLower() comparison does?
That being said, if your problem scope, in addition to the string casing, involves trying to assess absolute equality of two given paths, it makes sense to write up a class. But that would require a lot more involved solution than what you are proposing...

A: First, Call a Spade a Spade
You must define what is the clear responsibility of the class.
Either you want the class to manage Windows Path names and then you can't discard all remarks regarding that because the "code managing case" will be merged with the "code managing paths". Coupling will make you then unable to test (and ensure proper behaviour) casing without path consideration.
Or you want to implement a CaseInvariantString and then you name it adequately (and maybe use it in another class named WindowsPathname).
For references about Class Responbility, Cohesion, Coupling and other great concepts, I would recommend the following books:

*

*Clean Code from Robert C. Martin (Uncle Bob)

*Code Complete from Steeve McConnell

Second, wrapping strings inside a class to check for case invariance can be viewed as wrapping integer in a PositiveInteger class. It can (and will) be considered by some as over-engineering. It is a common tendency from all developers to try to reach the pinnacle of object oriented dogma. Here it seems like the practice of wrapping all value types in class (like int into an ID class). However, don't forget to ask you questions.

*

*What is the cost of adopting such practice?

*What are the benefits?

*What are the difficulties it may lead to?

*Could I adopt the general approach for all my projects?

*Do I have an enactment of my tech lead/architect (or similar authority) that it is a good practice?

Finally, as a simple technical point. You shouldn't create a string inside your class. It's deleterious for performance. In fact, because strings are invariant, when you do a ToUpperInvariant() in GetHashCode() it creates a new String.
And for the sake of path invariance... It doesn't work outside Windows (For Mono, obviously "/foo" != "/Foo").


text:
Q: Crafting a dynamic base url I have a constant building a dynamic base_url:
define('BASE_URL', "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);

The current base_url

http://training:8888/php/PHP6:MySQL%205/16/user_registration/htdocs/test.php/index.php

I've used:
echo(BASE_URL . '/index.php' . "<br />"); // Define the URL:

echo str_ireplace('htdocs/','', BASE_URL ); //Not the desired result

I found these forum post with an almost identical query as mine:Post One and Post 2.
If you could add insight to there solutions it would be appreciated. Your patience is appreciated.

A: You are using it correctly: http://ideone.com/b7Mo8
$url = 'http://training:8888/php/PHP6:MySQL%205/16/user_registration/htdocs/index.php';
echo str_ireplace('htdocs/','', $url);


text:
Q: Tool to generate Class Diagrams from code (Visual Studio) Title says it all, really. I'm hoping there's some extension out there, or full blown software, that'll automatically generate class diagrams from my code. I looked over the Extension Gallery website but couldn't quite find something that meets my criteria.
I've inherited an application that looks like it was written by a CompSci 101 student-- no folder structure, lots of repeated code. Lots of mess spread out over 50 windows forms. There's absolutely no inheritance, no interfaces or anything. It's tremendously simple code, there's just a lot of it.
It'd be great to have something generate a diagram of the whole project so I can quickly see where there's redundant code so I can go back and refactor the hell out of this monstrosity. I really don't need any bells and whistles, just to see the class name, fields and methods. I would however like it to leave out any controls that were added on the form.
So, hypothetically, say I have MyForm which contains 2 Textbox one it and 1 private int in the code view, the class Diagram should look something like this:
| MyForm |
----------
| -int i |
----------

INSTEAD OF:
| MyForm |
----------
| -int i |
| -txt1  |
| -txt2  |
----------

Excuse the crude drawing :)

A: To analyze code, I usually run doxygen on it first. It helps to generate an overview.
Don't forget to include the dot diagrams in the configuration file, which is needed to visualize caller and callee trees.


text:
Q: Pure function inside another pure function I have the following working expression:
In[15]:= Length[Select[IntegerPartitions[10],First[#1]==5&]]
Out[15]= 7

But, instead of using the constant 5 I want to map all values from 1 to 10 into this function. If I nest the pure function inside another it doesn't work:
In[18]:= Map[Length[Select[IntegerPartitions[10],First[#]==#&]]&,Range[10]]
Out[18]= {0,0,0,0,0,0,0,0,0,0}

What is the way to do this?

A: You can have a pure function inside a pure function even in this case, you just can't have the name of the parameter being "#" in both. This works:
Map[Function[x,
  Length[Select[IntegerPartitions[10], First[#] == x &]]], Range[10]]

A: This is probably not going to be the best answer but offering it as an opener or as a guide to towards a better solution
Setting your initial input as a function
f[n_]:=Length[Select[IntegerPartitions[10],First[#]==n&]]

then
Map[f,Range[10]]

{1, 5, 8, 9, 7, 5, 3, 2, 1, 1}

No doubt regular contributors can improve on this

A: You can also perform this without "netsted functions" issue. For example:
Count[IntegerPartitions[10][[All, 1]], #] & /@ Range[10]

It could be even faster but we have to assume that you know the output of IntegerPartitions (explained on the bottom):
Reverse @ Tally[IntegerPartitions[10][[All, 1]]][[All, 2]]

Description

*

*IntegerPartitions[10][[All, 1]] because only first elements are important

*[[All, 2]] after Tally -> here we assume that we know that there will be a set of values from 1 to 10, otherwise some sort of filtering is needed.

*Reverse because IntegerPartitions list values are decreasing.

A: Using Curry or OperatorApplied
Pure function nesting is one of the use cases for Curry, introduced in version 11.3:
Length[
  Select[IntegerPartitions[10], Curry[First[#] == #2 &][#]]
] & /@ Range[10]

(* {1, 5, 8, 9, 7, 5, 3, 2, 1, 1} *)

First[#1] == #2 & defines a two argument pure function.  By wrapping Curry[...][#] around this, we bind the inner slot reference #2 to the value of the outer slot reference #.  After binding, we are left with a single argument function that is suitable for use with Select.  For example, in one mapping iteration the outer # has the value 7 and the curried function Curry[First[#1] == #2 &][7] is essentially equivalent to First[#1] == 7 &.
Update for version 12.1
In version 12.1, OperatorApplied is the new name for Curry.  The documentation for Curry states that it is now being phased out.
Currying The Hard Way
A rather obscure idiom makes it possible to perform such currying in pure functions, even before version 11.3:
Length[
  Select[IntegerPartitions[10], #0[[0]][First[#[1]] == #2] &[Slot, #]]
] & /@ Range[10]

(* {1, 5, 8, 9, 7, 5, 3, 2, 1, 1} *)

The cryptic expression #0[[0]][First[#[1]] == #2]&[Slot, #] performs the necessary currying.  #0[[0]] expands to Function.  The disguised use of the symbol Function is necessary to avoid shadowing the inner slot references.  #[1] expands to Slot[1], i.e. #1.  #2 expands to the value of the outer #.  So, if the outer # were 7, then we would get First[#1] == 7 & as desired.
This construction is likely too ugly to actually use.  Thank goodness for the arrival of Curry :)


text:
Q: Accessing data passed to External Learning Tool from D2L When setting up a link to an External Learning Tool, there are checkboxes labelled as 'Security Settings' which allow information (context information, for example) to be passed to the external tool.
How can this information be accessed from the tool?

A: Per the LTI spec parameters are passed as form post variables.
For example, php code to access the contact email address would be:
//Grab some LTI related parameters
if (isset($_REQUEST['lis_person_contact_email_primary']))
{
    $email = $_REQUEST['lis_person_contact_email_primary'];
}

In D2L you can also combine LTI launches with Valence API calls as explained in the LTI and Valence article.
(You should also be validating the LTI oauth signature in order to be confident in your tool the request comes from the D2L Instance that has the key and secret for your tool)


text:
Q: How to use a range of values in a PostgreSQL function and to loop with a distinct interval I have a very simple example for the summation of two numbers.
CREATE OR REPLACE FUNCTION add(a integer, b integer) RETURNS integer AS
$$
  SELECT $1+$2;
$$ LANGUAGE 'sql';

My question is how to define a range b 10:20, whose values will counted up by one until the end of the range (20) is reached.
The result hast to be like this
res = a + b
res = a + 10
res = a + 11
res = a + 12
res = a + 13

When I retrieve the function add with:
SELECT add(1);

there should be the results: 11,12,13,...,21.
I didn't use loops like FOR EACH before (especially in the LANGUAGE sql).
Is it better to write those functions in plpgsql?

A: I think you are looking for the function generate_series(), documented here.
So,
select generate_series(1, 3)

Will return three rows:
1
2
3

You can use these numbers in arithmetic expressions.

A:
I didn't use loops like FOR EACH before (especially in the LANGUAGE sql).

There are no loops in SQL. (The only exception being RECURSIVE CTEs.) Functions with LANGUAGE sql (no quotes!), consist of SQL statements exclusively. If you need procedural elements like loops, you need to switch to PL/pgSQL (or any other procedural language) where looping is easy enough.
Of course, the simple example you presented would best be solved with generate_series(), as other answers already pointed out.
A word of caution: best use generate_series() in the FROM list. Using it in the SELECT list is allowed but frowned upon because non-standard. SRF (set returning functions) might be confined to the FROM list in future releases.

A: select add(1, b)
from generate_series(10, 20) b


text:
Q: Shift letter position in a word I want a command/function, preferably bash, that takes a word/string and a number and shifts the letter positions in the word by that number, rotating the overflow back to the beginning.
e.g. with input stack and 2 the output would be cksta
I have thought about using tr but I couldn't quite figure out how to make it general so as to work with any word, and not just translating specific letters from a target word.

A: You can use bash's built-in string manipulation:
#!/bin/bash

string=$1
shift=$2

length=${#string}
echo ${string:$length-$shift:$shift}${string:0:$length-$shift}

Example:
$ ./script stack 1
kstac
$ ./script stack 2
cksta
$ ./script stack 3
ackst
$ ./script stack 4
tacks

A: Another common approach is to "double" the string, which simplifies the substringery:
str=stack
len=${#str}
n=2
strstr=$str$str
echo ${strstr:$len-$n:$len}   # -> cksta

A: A bit shorter is the usage of negative values, to count from right:
string=$1
shift=$2
length=${#string}
echo ${string: -shift}${string:0:length-shift}

since :- has an own meaning, you have to put a blank before it.


text:
Q: Accessing Simple Feature geometry column for density calculation I work with spatial data and I am used to work with Spatial* objects. I recently started using sf package and it seems to make life easier in some cases. However I have a trouble when trying to work with raster package. In kde2d function I need to provide X and Y of each point which is easy in sp package:
library(sp)
library(sf)
library(MASS)
library(tibble)
library(raster)

x <- tibble(a = 1:3, lon = 19:21, lat = 19:21)
coordinates(x) <- ~ lon + lat
proj4string(x) <- "+init=epsg:4326"
density_x <- kde2d(x$lon, x$lat, n = 30, h = 1)
plot(raster(density_x))

But then I was trying to achieve the same using sf package and an error occurred:
y <- st_as_sf(x, coords = c("lon", "lat"), crs = 4326)
density_y <- kde2d(y$lon, y$lat, n = 30, h = 1)
plot(raster(density_y))

I do not know how to get into geometry column the same way as with sp package. I tried workaround, but it looks ugly:
y <- st_as_sf(x, coords = c("lon", "lat"), crs = 4326)
coords <- as.data.frame(st_coordinates(y$geometry))
density_y <- kde2d(coords$X, coords$Y, n = 30, h = 1)
plot(raster(density_y))

Is there any other way to achieve that? Maybe you use some better packages than raster to deal with density?

A: Setting the "remove" argument to FALSE in st_as_sf() will do the trick:
x <- tibble(a = 1:3, lon = 19:21, lat = 19:21)
y <- st_as_sf(x, coords = c("lon", "lat"), crs = 4326, remove = F)
y

#> Simple feature collection with 3 features and 3 fields
#> geometry type:  POINT
#> dimension:      XY
#> bbox:           xmin: 19 ymin: 19 xmax: 21 ymax: 21
#> epsg (SRID):    4326
#> proj4string:    +proj=longlat +datum=WGS84 +no_defs
#> # A tibble: 3 x 4
#>       a   lon   lat         geometry
#>   <int> <int> <int> <simple_feature>
#> 1     1    19    19  <POINT (19 19)>
#> 2     2    20    20  <POINT (20 20)>
#> 3     3    21    21  <POINT (21 21)>

density_y <- kde2d(y$lon, y$lat, n = 30, h = 1)
plot(raster(density_y))


text: Q: java.lang.NoClassDefFoundError: org/springframework/core/NativeDetector Error while running IT cases I'm working on something which required Integration test cases, and unit test cases. When I'm trying to run the test cases, junit are running but IT cases (classIT.java) are failing with error java.lang.NoClassDefFoundError: org/springframework/core/NativeDetector.


text:
Q: Using python list as node properties in py2neo I have a list of urls:
urls = ['http://url1', 'http://url2', 'http://url3']

Mind you the list can have any number of entries including 0 (none). I want to create new node property for each url (list entry).
Example how the node will look like
(label{name='something', url1='http://url1', url2='http://url2'}, etc...)

It is possible to expand a dictionary with ** with the same effect I need but is there any way to do this with a list?

A: You can put your list in a dictionary and use this to create a node:
from py2neo import Node

urls = ['http://1', 'http://2']

props = {}

for i, url in enumerate(urls):
    # get a key like 'url1'
    prop_key = 'url' + str(i)
    props[prop_key] = url

my_node = Node('Person', **props)

graph.create(my_node)


text:
Q: Why use standard error to approximate the true mean? We use the SE in order to tell, how far away are we to the true mean.
Why does this formula use the standard deviation of a sample to compute the mean of the sample means ? (with other words, true population mean)
Wouldn't it somehow be more intuitive it the formula for computing the mean of the sample means would have the mean of the actual sample inside it ?
$$SE = \frac{s}{\sqrt{n}}$$

A: You appear to be operating under some misunderstanding - your question seems to rely on a false premise.
If you're trying to give a point estimate of the mean of the distribution of sample means, that would indeed (often) be the sample mean.
The standard error of the mean is used to give some idea of the associated uncertainty in the location of the mean of that distribution. The standard error of the mean is the standard deviation of the distribution of sample means. It tells you something about how far away from the thing you're trying to estimate your sample mean will typically be.
e.g. if you wanted to give a confidence interval for that population mean of the distribution of sample means, it would typically be based on that sample mean $\pm$ a margin of error (interval halfwidth) that is a multiple of that standard error.


text:
Q: Android set bitmap as pathEffect for paint I want to know is there any way in Android draw a custom curve line with the effect which i set. I want to set the bitmap path effect. Like in image below.
I want to get next result :

If this effect i can do with another way i want to know how i can do it.

A: I think the example here will get you started (see the answer with the most votes, not the accepted answer). You can modify the path in the snippet such that it uses quadTo or cubicTo`  calls to draw a curve like in your picture, then step along it using the loop shown, drawing multiple bitmaps with, for each, random offsets for scale and distance from the path (using a separate set of matrices).


text:
Q: How to set timestamp to spreadsheet using google script i need help here.
I want to get a timestamp in the spreadsheet everytime i submit a row.  i try so many ways, but it failed. can anyone help me? these are my GoogleApp Script :
function doGet(e) {
   var ss = SpreadsheetApp.openByUrl("Spreadsheet link");
   var sheet = ss.getSheetByName("Sheet1");

   addUser(e, sheet);
}

function doPost(e) {

   var ss = SpreadsheetApp.openByUrl("Spreadsheet link");
   var sheet = ss.getSheetByName("Sheet1");

   addUser(e, sheet);
}

function addUser(e, sheet) {

   var id = e.parameter.id;
   var name = e.parameter.name;
   sheet.appendRow([id, name])
}

what i already try :
var row = e.range.getRow();
e.source.getActiveSheet().getRange(row,3).setValue(new Date());

A: You can add the Timestamp at the time of appending other Details
function addUser(e,sheet) {

  var id = e.parameter.id;
  var name = e.parameter.name;
  sheet.appendRow([new Date(),id,name])
}


text:
Q: When a service both sends and receives a topic. The data doesn't go to MQ public interface EventStream {
    String STREAM = "event_stream";

    @Output(EventStream.STREAM)
    MessageChannel publisher();

    @Input(EventStream.STREAM)
    SubscribableChannel stream();
}

When I do this, it just goes local and doesn't send to MQ.

A: The framework is not designed to do that.
In that scenario there will be two consumers on the channel - the output binding and the consumer; messages will alternately go to each.


text:
Q: RPy2 cannot import _rinterface_capi I haven't used RPy2 for a number of years (and then I only played around a bit). However, I now want to start using Python and R a bit more seriously and decided to re-explore the RPy2 library.
I'm using a Mac running El Capitan. I created a new virtual environment (called env34) using Python 3.4.4 and installed the latest version of pip (19.1.1) using get-pip.py. I then pip installed numpy, pandas and jupyter into the activated environment. I also pip installed RPy2 (but had to include a trusted-host flag):
(env34) $ pip install rpy2 --trusted-host=https://pypi.org/simple/cffi

I also installed the latest version of R (3.6.0) in the default location in Applications folder and edited .bash_profile to create a RHOME environment variable by adding the following:
RHOME="/Library/Frameworks/R.framework/Resources"
export RHOME

Now when I launch Python in the virtual environment, I can import rpy2 with no problems. However, I'm trying to follow the tutorial given at http://heather.cs.ucdavis.edu/~matloff/rpy2.html and when I try to import rpy2.robjects using:
>>> from rpy2.robjects import r

I get the following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path_to_virtual_environment/env34/lib/python3.4/site-packages/rpy2/robjects/__init__.py", line 14, in <module>
    import rpy2.rinterface as rinterface
  File "/path_to_virtual_environment/env34/lib/python3.4/site-packages/rpy2/rinterface.py", line 5, in <module>
    import rpy2.rinterface_lib._rinterface_capi as _rinterface
  File "/path_to_virtual_environment/env34/lib/python3.4/site-packages/rpy2/rinterface_lib/_rinterface_capi.py", line 8, in <module>
    from . import conversion
  File "/path_to_virtual_environment/env34/lib/python3.4/site-packages/rpy2/rinterface_lib/conversion.py", line 8, in <module>
    from . import _rinterface_capi as _rinterface
ImportError: cannot import name '_rinterface_capi'

As far as I can see, all the files referenced in the message exist in the correct locations.
Can anyone interpret this error message and perhaps offer a workaround?
Thanks in advance.


text:
Q: Python pickle load trained model I'm trying to apply a loaded trained model onto a new dataset. I pickle and unpickle the model:
classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
classifier = classifier.fit(features, classes)

saved_pickle_file = open('saved_model.pkl', 'wb')
pickle.dump(classifier, saved_pickle_file)
saved_pickle_file.close()

load_pickle_file = open('saved_model.pkl', 'rb')
loaded_model = pickle.load(load_pickle_file)

But when I apply the loaded model to a new dataset, it produces this error:
loaded_model.predict(new_dataset)

AttributeError: 'function' object has no attribute 'predict'

Any reason as to why this is happening?


text:
Q: Generating of query in wrong format I have a problem with piece of code, which is generated (output) in wrong format and not requested form:
I wanted generate query/sql with foreign key without "ALTER TABLE NameOfTab ADD" so I used this piece of code:
DSL.constraint(DSL.name("fk_example"))
   .foreignKey("id1","id2")
   .references("referecnedTableName", "referencedColumn1", "referencedColumn2");

And here comes a problem because it returns as string this form:
constraint "fk_example"
foreign key (
"id1",
"id2"
)
references "referecnedTableName" (
"referencedColumn1",
"referencedColumn2"
)

Expected result is:
constraint fk_example foreign key (id1, id2)
references referecnedTableName (referencedColumn1, referencedColumn2)

Something similar in correct format does ALTER table:
ctx.alterTable(tableName)
   .add(
      DSL.constraint(DSL.name("fk_example"))
         .foreignKey("id1","id2")
         .references("referecnedTableName","referencedColumn1","referencedColumn2"))
   .getSQL(ParamType.INLINED));

But it returns it with "alter table t3 add ... " and I don't want "alter table" part.

A: You should use DSLContext.render(QueryPart) instead of QueryPart.toString(). The toString() behaviour defaults to calling render() with some unspecified default Settings including the generation of those double quoted identifiers, which I'm suspecting you don't want to have.


text:
Q: Oracle 9i index error I have the following query:
select *
from gps_servicio ser
where ser.id in (select idserv from gps_agentes where idagen = 8073061);

This query works perfectly until I make an index in the table gps_agentes, on the field idserv (asc one). If I do that, the query brokes and I get no results from it. Is this a bug?
Both gps_servicio.id and gps_agentes.idserv are number(10,0) fields, and I have a FK on gps_agentes.idserv that points to gps_servicio.id.
Thx for your time!

A: If the results of a query change when you create an index, that indicates a bug, yes.  If you are encountering a bug, you would need to report that to Oracle Support to determine whether the bug you are encountering is already fixed by an existing patch or whether it is a new bug that no one has encountered before.
However, given that you say that you are using 9i, a version of the database that is at least 5 major releases old and has been out of primary support for many years, my wager is that you are running without a support contract and without access to Oracle Support.  Are you at least running the latest patchset of whatever version of Oracle you are using ("9i" covers two major releases, 9.0.1 and 9.2)?


text:
Q: Date Time from Django views to be used in Javascript I have this view in views.py:
def endtime(request, *args, **kwargs):
    end_time = datetime.datetime.now() + timedelta(hours=10)
    return HttpResponse(end_time)

The value returned by this view is 2016-01-31 16:25:09.622489
I have a Javascript function that sends an Ajax request to above view and the returned value is recieved by data parameter,
function myfun(){
  $.get('/endtime/',function(data){
        var date = new Date();
        var diff = data - date; //not working
  });
}

The value of data is 2016-01-31 16:25:09.622489 and date is Sun Jan 31 2016 06:38:47 GMT+0530 (IST)
How can I convert either data into date format or vice-versa so that I can take the difference between them.

A: you got data as a string, and convert it to Date object first.
by function  Date.parse(dateString) or new Date(dateString)


text:
Q: Creating a set in C++ I am coding this thing and it would be helpful to have a static const set<char> containing some elements that won't change.
class MyClass {
     private:
         static const set<char> mySet = ??
}

How can I do this? It would be nice if you could create them from a string, like mySet("ABC"), but I can't get the syntax to work.

A: Something like this will work just fine:
// my_class.h
class MyClass
{
  static const std::set<char> mySet;
};

// my_class.cpp
const char *tmp = "ABCDEFGHI";
const std::set<char> MyClass::mySet(tmp,tmp+strlen(tmp));

A: Something like the following ought to work..
#include <iostream>
#include <set>

struct foo
{
  static std::set<char> init_chars();

  static const std::set<char> myChars;
};

const std::set<char> foo::myChars = foo::init_chars();

std::set<char> foo::init_chars()
{
  std::string sl("ABDCEDFG");
  return std::set<char>(sl.begin(), sl.end());
}

int main()
{
  std::cout << foo::myChars.size() << std::endl;
  return 0;
}

A: You can't initialize the variable inside the class, because it technically hasn't been defined yet (only declared).
In the class, keep static const set<char> mySet;.
In the implementation (i.e. .cpp file):
const char[] _MyClassSetChars = "ABC";

// Define and initialize the set, using
// the constructor that takes a start and end iterator
const set<char> MyClass::mySet(
    _MyClassSetChars,
    _MyClassSetChars + sizeof(_MyClassSetChars) / sizeof(_MyClassSetChars[0])
);

This also includes the terminating null character (\0) in the set, which is probably not what you want -- instead, use this:
const set<char> MyClass::mySet(
    _MyClassSetChars,
    _MyClassSetChars + (sizeof(_MyClassSetChars) / sizeof(_MyClassSetChars[0]) - 1)
);

Note that here you can use <cstring>'s strlen() (as per Let_Me_Be's answer) in place of the more general form above:
const set<char> MyClass::mySet(
    _MyClassSetChars,
    _MyClassSetChars + strlen(_MyClassSetChars)
);

Also see this question.

A: Have you tried static set <const char> mySet; ? Of course you need to initialize it first otherwise if you try to insert after you declare your set, it will fail.

A: header file:
#include<set>
class MyClass {
private:
    static const std::set<char> mySet;
}

source file:
#include<boost/assign.hpp>
const MyClass::mySet = boost::assign::list_of('A')('B')('C');


text:
Q: fputcsv causing "Headers Already Sent" error I am writing a PHP export script for my copy of magento. For some reason, the following code gives me a "Headers already sent" error:

//Load magento and set to match frontend
require_once '../../app/Mage.php';
umask(0);
Mage::app();
Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_FRONTEND);

//Send headers to browser to prep for csv file download
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exportSKUs.csv');

//Load only product collection details that we need.
$product    = Mage::getModel('catalog/product');
$product->getCollection()->getSelect()->limit(5);
$products   = $product->getCollection()
    ->addFieldToFilter('status','1')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('sku')
    ->addAttributeToSelect('upc')
    ->addAttributeToSelect('status')
    ->addAttributeToSelect('price')
    ->addAttributeToSelect('special_price')
    ->addAttributeToSelect('description')
    ->addAttributeToSelect('category_ids')
    ->addAttributeToSelect('short_description');

//Open current output to fputcsv
$fp = fopen('php://output', 'w');

//CSV headers
$headerRow = array(
    'name',
    'sku',
    'upc',
    'status',
    'price',
    'special_price',
    'description',
    'category_ids',
    'short_description'
);
fputcsv($fp, $headerRow);
$count = 0;
//CSV Rows
foreach($products as &$product){
    $categoryIds = implode(',', $product->getCategoryIds());
    $row = array(
        $product->getName(),
        $product->getSku(),
        $product->getUpc(),
        $product->getStatus(),
        $product->getPrice(),
        $product->getSpecialPrice(),
        $product->getDescription(),
        $categoryIds,
        $product->getShortDescription()
    );
    fputcsv($fp, $row);
    $count++;
    if($count>5){
        //Close current output (save csv)
        fclose($fp);
        exit;
    }
}

The line of code here that is causing me problems is this: fputcsv($fp, $headerRow);
For some reason, when this line is commented out the script runs fine. However, when this line is run with the script, it shoots the header already sent error. I don't understand why I am able to run fputcsv INSIDE my foreach loop any number of times (fputcsv($fp, $row);)but I can not run it before the foreach loop at all.
I have ways around this issue, so it's not super critical, but I really wish I could understand what was going on here to cause this.
Thanks for your time!

A: i have change your code ... check this.I have using magento process to export...
<?php
//Load magento and set to match frontend
require_once '../../app/Mage.php';
umask(0);
Mage::app();
Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_FRONTEND);

//Send headers to browser to prep for csv file download
//header('Content-Type: text/csv');
//header('Content-Disposition: attachment;filename=exportSKUs.csv');
//
$filename="exportSKUs.csv";

//Load only product collection details that we need.
$product    = Mage::getModel('catalog/product');
$product->getCollection()->getSelect()->limit(5);
$products   = $product->getCollection()
    ->addFieldToFilter('status','1')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('sku')
    ->addAttributeToSelect('upc')
    ->addAttributeToSelect('status')
    ->addAttributeToSelect('price')
    ->addAttributeToSelect('special_price')
    ->addAttributeToSelect('description')
    ->addAttributeToSelect('category_ids')
    ->addAttributeToSelect('short_description');

 $io = new Varien_Io_File();
                $path = Mage::getBaseDir('var') . DS . 'export' . DS;
                $name = md5(microtime());
                $file = $path . DS . $name . '.csv';
                $io->setAllowCreateFolders(true);
                $io->open(array('path' => $path));
                $io->streamOpen($filename, 'w+');
                $io->streamLock(true);
                $headerRow = array(
                    'name',
                    'sku',
                    'upc',
                    'status',
                    'price',
                    'special_price',
                    'description',
                    'category_ids',
                    'short_description'
                );
                $io->streamWriteCsv($headerRow);

                    foreach($products as &$product){
                    $categoryIds = implode(',', $product->getCategoryIds());
                    $row = array(
                    $product->getName(),
                    $product->getSku(),
                    $product->getUpc(),
                    $product->getStatus(),
                    $product->getPrice(),
                    $product->getSpecialPrice(),
                    $product->getDescription(),
                    $categoryIds,
                    $product->getShortDescription()
                    );
                    $io->streamWriteCsv($row);
                }
?>


text:
Q: Concatenated variables as class object $var = 'Foo';
$object = new {$var . 'Controller'}(); // new FooController()

Is there any syntax that makes this possible? The example above doesn't work of course.

A: Yes, simply store the full class name in a variable:
$class = $var . 'Controller';
$instance = new $class();

A: Not sure why you wouldn't want to use the simplest method available (I'd recommend TheifMaster's method...), the only other ways I could figure this out is to define a function or another class to handle the concatenation and class creation. This is actually more work, although it looks more professional, I must say.
A function could look like:
function createObject($prefix, $type)
{
    $objectName = $prefix . $type;

    return new $objectName();
}

And call it like this:
$var = 'Foo';
$object = createObject($var, 'Controller');

Or simply:
$object = createObject('Foo', 'Controller');

Or define the class creation object, something like:
class objectHandler
{
    public function createObject($prefix, $type)
    {
        $objectName = $prefix . $type;

        return new $objectName();
    }
}

Now, whenever you want to use this to create a new object, you just need to call:
$var = 'Foo';
$object = objectHandler::createObject($var, 'Controller');

Or simply:
$object = objectHandler::createObject('Foo', 'Controller');

Only reason to use this is if you have multiple Controller classes (FooController, BarController, etc). Other than that, I'd always recommend the KISS method (keep it simple, stupid (That's what it's called, not directed toward you)). That's all I got, let me know if that works for you.


text:
Q: How to Display name of image using onclick and this.title My assignment is to display the image name on an image using onclick.
I need to add an onClick handler to set the title property of the image to My New Title(Hint You can access the image title using this.title)
This is my code,

my instructor is not being much help as I keep asking what I'm missing but instead answers something else
I know this is something simple, but I just cannot get it to work. Any ideas what I'm doing wrong ?

A: Your answer is more simple. You only need minor alterations to what is provided in the text. You cannot have an alt="" attribute and expect JavaScript to fire a change directed at 'title'. You must apply a title attribute before you can alter one.

alt="" and title="" are pretty much the same thing. Remove the alt="" to reduce redundancy and replace with title="".
Once you have done this, hover over your image and wait a moment for the title to appear, then click and hold more a moment and you will see the title appear with your new code.
Good Luck in your JavaScript course.

A: Is hard to diagnose without seeing the setimagename code but probably the issue is that you are missing quotes in the string My New Title that you are passing as argument:

Also notice in your code that when the function is called you have ' char which will cause you another syntax error.

A:

A: You are passing a String on a function you should put a quote on it.
onClick="setimagename('My New Title');"

A:
or
bind click event in script.


text:
Q: Late Binding Global Variables? I'm using VBA for Excel.  From my understanding, global variables need to be declared outside of any subs.  That's the only way they can be accessed by all subs.
At the meantime, I want to do late binding to reference the "Microsoft Scripting Runtime" library(in order to use the dictionary object type) so that an end user doesn't have to do it himself.
My code is as below:
On Error Resume Next
strGUID = "{420B2830-E718-11CF-893D-00A0C9054228}"
ThisWorkbook.VBProject.References.AddFromGuid GUID:=strGUID, Major:=1, Minor:=0

Dim Dic1 As Object
Set Dic1 = CreateObject("Scripting.Dictionary")
Dim Dic2 As Object
Set Dic2 = CreateObject("Scripting.Dictionary")

What if I want to declare global dictionary object with late binding?  It looks like VBA won't allow me to put any code outside of the subs (other than the declarations).
How may I declare a global dictionary object without needing the end user configure library reference himself?  Shall I don the following?
Dim Dic1 As Object
Dim Dic2 As Object

Sub Prog1()
    On Error Resume Next
    strGUID = "{420B2830-E718-11CF-893D-00A0C9054228}"
    ThisWorkbook.VBProject.References.AddFromGuid GUID:=strGUID, Major:=1, Minor:=0

    Set Dic1 = CreateObject("Scripting.Dictionary")
    Set Dic2 = CreateObject("Scripting.Dictionary")
End Sub

A: Like the VBA code itself, project references don't magically disappear when your user opens your host workbook. They're saved along with the code in the host document.
So, the premise of your question is wrong: users never need to tweak project references.
Also the Scripting Runtime type library is standard issue and has been shipped the exact same version on every single Windows machine built this century (even before that), which means unless your code needs to run on a Mac, there's no need to ever late-bind the Scripting Runtime library.
And if your code needs to run on a Mac, the library won't late-bind anyway because it won't be found on the host machine, so late-binding the Scripting Runtime only serves to make silly typos and introduce other easily avoidable bugs that IntelliSense helps preventing.

ThisWorkbook.VBProject.References.AddFromGuid GUID:=strGUID, Major:=1, Minor:=0

This defeats the entire purpose of late-binding: it's using the VBIDE extensibility library (which requires lowered macro security settings) to programmatically add a reference that you can easily add at design-time through the VBE's Tools menu.
Late-bound code doesn't need the reference at all. Not at compile-time, not at run-time.
Add the reference, save, then declare your objects As Scripting.Dictionary and enjoy the benefits of early-bound code.
Set Dic1 = New Scripting.Dictionary

That's all you need.

What if I want to declare global dictionary object with late binding? It looks like VBA won't allow me to put any code outside of the subs (other than the declarations).

Late binding isn't any different than early binding in that aspect. The only difference between late and early bound code is the As clause of the declaration:
Private foo As Object ' no compile-time type knowledge: late-bound
Private bar As Dictionary ' compile-time type knowledge: early-bound

How you're initializing that object reference makes no difference to the late/early binding nature of the declaration.
This looks up a ProgID in the registry to find the library and the type:
Set foo = CreateObject("Scripting.Dictionary")

This uses the project references:
Set foo = New Scripting.Dictionary

Both are correct, and both will work against either early or late-bound declarations. Except, if you already have a reference to the type library, there's not really a need to go hit the registry to locate that library - just New it up!

A: Global variables are really not needed and should be avoided. However, if you have decided to use them for a your own reasons, you can put them in the Workbook_Open event:
Option Explicit

Dim Dic1 As Object
Dim Dic2 As Object

Private Sub Workbook_Open()

    Set Dic1 = CreateObject("Scripting.Dictionary")
    Set Dic2 = CreateObject("Scripting.Dictionary")

End Sub

Thus, it would create the object every time the workbook is opened.


text:
Q: The tilde operator in C I've seen the tilde operator used in the ELF hashing algorithm, and I'm curious what it does. (The code is from Eternally Confused.)
unsigned elf_hash ( void *key, int len )
{
  unsigned char *p = key;
  unsigned h = 0, g;
  int i;

  for ( i = 0; i < len; i++ ) {
    h = ( h << 4 ) + p[i];
    g = h & 0xf0000000L;

    if ( g != 0 )
      h ^= g >> 24;

    h &= ~g;
  }

  return h;
}

A: The tilde character is used as an operator to invert all bits of an integer (bitwise NOT).
For example: ~0x0044 = 0xFFBB.

A: It is the bitwise NOT operator. It inverts all bits in an integer value.

A: ~ is the bitwise NOT operator. It inverts the bits of the operand.
For example, if you have:
char b = 0xF0;  /* Bits are 11110000 */
char c = ~b;    /* Bits are 00001111 */

A: The ~ operator is bitwise NOT, it inverts the bits in a binary number:
NOT 011100
  = 100011

A: This is the bitwise NOT operator.
It flips all the bits in a number: 100110 -> 011001

A: Tilde operator (~) also called bitwise NOT operator,  performs one's complement of any binary number as argument. If the operand to NOT is decimal number then it convert it as binary and perform's one's complement operation.
To calculate one's complement simply invert all the digit [0-->1] and [1-->0]
Ex : 0101 = 5;  ~(0101) = 1010.
Use of tilde operator :
1. It is used in masking operation , Masking means setting and resetting the values inside any register . for ex :
char mask ;
mask = 1 << 5 ;

It will set mask to a binary value of 10000  and this mask can be used to check the bit value present inside other variable .
int a = 4;
int k = a&mask ; if the 5th bit is 1 , then k=1 otherwise k=0.

This is called Masking of bits.
2.To find binary equivalent of any number using masking properties.
#include<stdio.h>
void equi_bits(unsigned char);
int main()
{
    unsigned char num = 10 ;
    printf("\nDecimal %d is same as binary ", num);
    equi_bits(num);
    return 0;
}
void equi_bits(unsigned char n)
{
  int i ;
  unsigned char j , k ,mask ;
  for( i = 7 ; i >= 0 ; i--)
  {
     j=i;
     mask = 1 << j;
     k = n&mask ; // Masking
     k==0?printf("0"):printf("1");
  }
}

Output  : Decimal 10 is same as 00001010
My observation :For the maximum range of any data type , one's complement provide the negative value decreased by 1 to any corresponding value.
ex: ~1 --------> -2
~2---------> -3
and so on... I will show you this observation using little code snippet
#include<stdio.h>
int main()
{
    int a , b;
    a=10;
    b=~a; // b-----> -11
    printf("%d\n",a+~b+1);// equivalent to a-b
    return 0;
}
Output: 0

Note : This is valid only for the range of data type. means for int data type this rule will be applicable only for the value of range[-2,147,483,648 to 2,147,483,647].
 Thankyou .....May this help you


text:
Q: Read the keyboard in protected mode I'm trying to do a PS/2 keyboard controller, and I can't get it work.
outb(0x60, 0xED);
outb(0x60, 2); /* Turn on CapsLock LED (doesn't works)*/
char c = 0;
while (c != 1)
{
    if (inb(0x60) != c)
    {
        c = inb(0x60);
        if (c > 0)
            putch(scan2char(c));
    }
}

scan2char function:
char scan2char(char scn)
{
    char keych;
    switch (scn)
    {
        case 0x15:
            keych = 'q';
            break;
        case 0x1D:
            keych = 'w';
            break;
        case 0x24:
            keych = 'e';
            break;
        case 0x2D:
            keych = 'r';
            break;
        case 0x2C:
            keych = 't';
            break;
        case 0x35:
            keych = 'y';
            break;
    }
    return keych;
}

It reads the keys, but the keyboard layout shifted in an weird way; e.x: if I press 9 I get q, if I press 0 I get w, you understand.
At first I thought it might be the putch function, but doing some tests, I saw that putch wasn't the problem.

A: There's 2 or more separate pieces of hardware involved:

*

*the PS/2 controller (which is mostly just a glorified serial port controller)

*whatever happens to be plugged into the first PS/2 port (keyboard, mouse, touch screen, bar-code scanner, ...)

*whatever happens to be plugged into the second PS/2 port

When there's separate pieces of hardware involved it's best to have separate drivers:

*

*something that handles the PS/2 controller; including handling "hot-insert device", device identification and starting the appropriate driver for the identified device; and including providing a "get_byte()/send_byte()" interface for other drivers to use.

*a driver for each kind of device that might be plugged in (keyboard, mouse, touch screen, bar-code scanner, ...); which doesn't touch any of the PS/2 controller's IO ports and only communicates with the PS/2 controller driver (via. the "get_byte()/send_byte()" interface provided by the PS/2 controller driver).
Note that (in general, excluding "hard-wired device" scenarios in laptops) there is absolutely no reason why you can't have two PS/2 keyboards plugged in (with 2 separate instances of the exact same "PS/2 keyboard driver" running); or two PS/2 mouses, or a bar code scanner and a touch screen (with no keyboard and no mouse), or any other combination of any types of devices in any PS/2 ports. Also (if you like portability) there's no reason why the same PS/2 keyboard/mouse/whatever device drivers can't work "as is" (with a recompile and nothing more) on completely different architectures with completely different PS/2 controllers (e.g. the PL050 PS/2 controller that some ARM systems have), simply because the driver for the completely different PS/2 controller can provide the exact same "get_byte()/send_byte()" interface.
For the "8042" PS/2 controller on 80x86 PCs; you should probably read (if not follow) the initialisation sequence described here: https://wiki.osdev.org/%228042%22_PS/2_Controller#Initialising_the_PS.2F2_Controller
If you don't initialise the PS/2 controller properly (e.g. just use "random whatever state the thing happened to be left in by boot loader") then it may have been left with an awful translation feature enabled where data from the device is deliberately mangled by the controller for backward compatibility with the original IBM XT machines (from before scan code set 2 existed); where a modern keyboard sends bytes for scan code set 2, but the PS/2 controller converts them into "scan code set 1 compatible" values, causing things like (e.g.) "if you press 9 you get q, if you press 0 you get w, ...".


text:
Q: Calculate Automatically And Conversion to Format Money Javascript I wanna ask again .. hope you know
I want to calculate automatically but with format money..
this demo : https://jsfiddle.net/xp4ky2gg/
This my code ...
code html

                      Pendapatan Keluarga (A) Bersumber dari
                      Jumlah (Rp/Bulan)

                        Usaha Pokok Suami

                          <input type="text" name="pendapatan_suami" id="nominal1" class="pendapatan" style="width: 200px; text-align:right;"onkeyup="angka(this)" >

                        Usaha Pokok Istri

                          <input type="text" name="pendapatan_istri" id="nominal2" class="pendapatan" style="width: 200px; text-align:right;" onkeyup="angka(this)" >

                        Usaha Lainnya

                          <input type="text" name="pendapatan_usaha" id="nominal3" class="pendapatan" style="width: 200px;  text-align:right;" onkeyup="angka(this)">

                        Dari orangtua

                          <input type="text" name="pendapatan_ortu" id="nominal3" class="pendapatan" style="width: 200px; text-align:right;" onkeyup="angka(this)">

                        Dari anak/menantu

                          <input type="text" name="pendapatan_anak" id="nominal4" class="pendapatan" style="width: 200px; text-align:right;" onkeyup="angka(this)">

                        Penghasilan Lainnya sebutkan
                        <input type="text" name="pendapatan_lain" id="nominal6" class="pendapatan" style="width: 200px; text-align:right;" onkeyup="angka(this)">

                        Total

                          <input type="text" name="total" id="total" style="width: 200px;">

                        Kesimpulan III*

                          <select id="k3"  class="tes3" name="kelayakan3" size="1" >
                            <option value="">-- Pilih Salah Satu --</option>
                              <option value="1">Layak</option>
                              <option value="0">Tidak Layak</option>
                          </select>

                        Ket Kelayakan III
                        <textarea name="ketkel3" maxlength="100"></textarea>

code javascript
      function NilaiRupiah(jumlah){
    var titik = ".";
    var nilai = new String(jumlah);
    var pecah = [];
    while(nilai.length > 3)
    {
        var asd = nilai.substr(nilai.length-3);
        pecah.unshift(asd);
        nilai = nilai.substr(0, nilai.length-3);
    }

    if(nilai.length > 0) { pecah.unshift(nilai); }
    nilai = pecah.join(titik);
    return nilai;
  }

  function angka(e) {
    if (!/^[0-9]+$/.test(e.value)) {
      e.value = e.value.substring(0,e.value.length-1);
    }
  }

   $(document).ready(function () {
      //Iterate through each Textbox and add keyup event handler
      $(".pendapatan").each(function () {
          $(this).keyup(function () {
              //Initialize total to 0
              var total = 0;
              $(".pendapatan").each(function () {
                  // Sum only if the text entered is number and greater than 0
                  if (!isNaN(this.value) && this.value.length != 0) {
                      total += parseFloat(this.value);
                      $(this).css("background-color", "#FEFFB0");
                  }
                  else if (this.value.length != 0){
                      $(this).css("background-color", "red");
                  }
              });
              //Assign the total to label
              //.toFixed() method will roundoff the final sum to 2 decimal places
              jml = "Rp. " + NilaiRupiah(total) + ",00";
              $("#total").val(jml);
          });
      });
  });

this demo : https://jsfiddle.net/xp4ky2gg/
if  calculate
Output Now
  9000
  9000
-------
18.000

I want to input and output like this 9000 convert to 9.000 and the result 18.000
  9.000
  9.000
---------
18.0000

A: Maybe what you mean is decorate (number format) the value, but still keep the calculation, something like this
      $('.pendapatan').focus(function(){
        var v = $(this).val().replace(/[^0-9]/, '');
        $(this).val(v);
      }).blur(function(){
        var v = NilaiRupiah($(this).val());
        $(this).val(v);
      })

https://jsfiddle.net/gn0a2h8h/

A: You can utilize filter for that, to pass an argument to a filter in the HTML form, we pass it with a colon after the filter name (for multiple arguments, we can simply append a colon after each argument). For example, the number
filter allows us to limit the number of decimal places a number can show. To pass the argument 2, we'll append :2 to the number filter:

    {{ 123.456789 | number:2 }}

    {{ 9000 | number:3 }}


text:
Q: How to put a text in between the buttons inside a modal dialog box in jQuery? I want to put a text in between the buttons "Login" and "Sign_Up" inside the modal dailog box using jQuery. How to do it?
And , How can I link some anchor tags with those buttons?
Here is my snippet of code:
Any help will be much appreciated , Thanks.
<!doctype html>

<meta charset="utf-8">
<title>jQuery UI Dialog - Default functionality</title>

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/ui-darkness/jquery-ui.css" rel="stylesheet">

This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

<input type="button" id="Dialog_Modal" value="Click to open a modeless dialog" />

A: You can try adding a custom button and changing it's style according to your needs. Code:
Link : http://jsfiddle.net/lotusgodkk/GCu2D/69/
Javascript:
$(function () {
    $("#dialog_nav").dialog({
        autoOpen: false,
        modal: true,
        dialogClass: "First_Dialog",
        resizable: false,
        buttons: [{
            text: "Cancel",
                "class": 'cancelButtonClass',
            click: function () {
                // Cancel code here
            }
        }, {
            text: "Custom",
                "class": 'custom',
            click: function () {
                //  code here
            }
        }, {
            text: "Cancel",
                "class": 'cancelButtonClass',
            click: function () {
                // Cancel code here
            }
        }, ],
    });

    $("#Dialog_Modal").on("click", function (event) {
        $("#dialog_nav").dialog("open");
    });
});

HTML:

This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

<input type="button" id="Dialog_Modal" value="Click to open a modeless dialog" />


text:
Q: Can't figure out what this JS code means I've been romping through a piece of JS I came across online and can't figure out what this piece of code means.
global$string$newLines = function(a) {
    return a.replace(/(\r\n|\r|\n)/g, "\n");
},

I'm specifically wondering about the piece /(\r\n|\r|\n)/g
Also - Is this machine generated code? Is that why the variable name is full of $s?

A: They are regular expresions
\r = Find a carriage return character
\n = Find a new line character

the /g (g only) mean to find all
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
So the code mean to find all \r\n or just \r or just \n and replace it with \n
They are whitespace characters so they not visible.

A: It's a regular expression for replacing newline characters.
There are different types of new line characters inserted by various browsers/editors/OSes etc.
\n is the default on all (true) Unix systems with \r having no meaning, C, Java, C++, etc, adopted this convention.
\r is from the days of Mac before it was a Unix system, while the duplicate \r\n is the Windows way.
The /g flag represents a global setting telling the regular expression to search the entire document.
So what the code is doing is using a regular expression to globally find all possible equivalents of a newLine, and replacing them with the defacto standard, '\n'

A: This is just a regular expression used to replace Carriage Returns and New Line characters with new line characters.
Your Regex: /(\r\n|\r|\n)/g
Explanation:

1st Capturing group (\r\n|\r|\n)

1st Alternative: \r\n

\r matches a carriage return (ASCII 13)
    \n matches a line-feed (newline) character (ASCII 10)

2nd Alternative: \r

\r matches a carriage return (ASCII 13)

3rd Alternative: \n

\n matches a line-feed (newline) character (ASCII 10)

g modifier: global. Give All matches (i.e Don't return on first match).
PS: Check out regex101.com for generating such beautiful explanation for any Regex.

A: The code replaces carriage-return/new-line combinations with a single newline.
The $'s in the variable name is done by several javascript compilers out there.  Developers will often break their code up into namespaces of the form global.string.newline, for example.  But when we want to run that code on a client, it's safer and more efficient to turn this object-within-an-object-within-an-object into a single variable.  Usually, the javascript compiler will go one step further and then turn this long variable name into some short unique sequence, but it will also preserve this intermediate form for easier debugging.

A: It is a regex to remove the carriage return/new line/carriage return + new line with new line from a string.
/(\r\n|\r|\n)/g

the /g in the end signifies globally, hence throughout the string and not just the first occurence.
Working Fiddle
JS Code:
global$string$newLines = function (a) {
    return a.replace(/(\r\n|\r|\n)/g, "\n")
}

function abc() {
    var text = document.getElementById("test").value;
    console.log(global$string$newLines(text));
}

HTML Code:
<textarea id="test"></textarea>
<button id="testClick" onclick="abc()">Click</button>

A: This is a regular expression replace that means:
Find any occurence of either:

*

*\r\n

*\r

*\n

And replace it with \n.
Comments:

*

*The /g means it will mach all findings, not only the first occurence.

*The third option to replace \n by \n is nonsense as it has no effect.

Doc of the replace and link to regex: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace


text:
Q: How to get the directory of a current script on Spyder (without using '__file__')? When I open Spyder (version 4.1.4), it opens a script that I was previously working with. However, the directory is set to 'C:\\Users\\UserName' (this is what I get with os.getcwd()).
I like to change the directory to where the script is, but I couldn't find a simple way to get the directory of the script and use os.chdir(path).
As it's mentioned here, os.path.dirname(__file__) gives NameError: name '__file__' is not defined when I run it on Spyder console, and I like to get the path without running the whole script.
In Spyder, what command(s) can I use to find a currently opened script?

A: I haven't found a solution either. This is the way I deal with it on Windows:

*

*Select and comment the whole script (Ctrl + a + Ctrl + 1)

*Run file (F5)

*Uncomment or undo (Ctrl + z).

At least in my case, the current directory changes to that of the script.