text:
Q: toggle a Json data with click event I'm trying to add a class on the div block-grid__item but the toggle class won't work to each div. What am I missing? seems to work randomly.

var module = {

  init: function() {
    this.onClick();
    this.onSubmit();
  },

  onClick: function() {
    $('div.text').on('click', function(event) {
      $(this).closest(".block-grid__item").toggleClass('active');
    });
  },

  onSubmit: function() {

    var apiBase = "https://hacker-news.firebaseio.com/v0/";
    var container = document.querySelector('#latest');
    var el, title, url;

    fetch(apiBase + 'askstories.json')
      .then(function(response) {
        return response.json();
      })
      .then(function(json) {
        return json.slice(0, 16);
      })
      .then(function(ids) {
        ids.forEach(function(id, i) {
          fetchItem(id);

        });
      })
      .catch(function(err) {
        console.log(err);
      });

    function fetchItem(id) {
      var item = apiBase + 'item/' + id + '.json';

      fetch(item)
        .then(function(response) {

          return response.json();
        })
        .then(function(json) {
          console.log(json);
          score = json.score;
          title = json.title;
          author = json.author;
          text = json.text;
          type = json.type;
          by = json.by;
          url = json.url;
          el = document.createElement("div");
          el.className = 'block-grid__item';
          el.id = json.id;
          el.innerHTML = `<ul class="xs-border"><li><a href="${url}" class="anchor"><h4 class="title">${title}</h4></a> <div class="text">${text}</div> <span class="by">${by}</span><span class="score">${score}</span></li></ul>`;
          container.appendChild(el);
          module.onClick();
        })
        .catch(function(err) {
          console.log(err);
        });
    }

  }

}

$(document).ready(function() {
  module.init();
});

A: Just edit the code like this $('body').on('click', 'div.text', function(event) { and it will work. The click event didn't fire on the fetched elements.

var module = {

  init: function() {
    this.onClick();
    this.onSubmit();
  },

  onClick: function() {
    $('body').on('click', 'div.text', function(event) {
      $(this).closest(".block-grid__item").toggleClass('active');
    });
  },

  onSubmit: function() {

    var apiBase = "https://hacker-news.firebaseio.com/v0/";
    var container = document.querySelector('#latest');
    var el, title, url;

    fetch(apiBase + 'askstories.json')
      .then(function(response) {
        return response.json();
      })
      .then(function(json) {
        return json.slice(0, 16);
      })
      .then(function(ids) {
        ids.forEach(function(id, i) {
          fetchItem(id);

        });
      })
      .catch(function(err) {
        console.log(err);
      });

    function fetchItem(id) {
      var item = apiBase + 'item/' + id + '.json';

      fetch(item)
        .then(function(response) {

          return response.json();
        })
        .then(function(json) {
          console.log(json);
          score = json.score;
          title = json.title;
          author = json.author;
          text = json.text;
          type = json.type;
          by = json.by;
          url = json.url;
          el = document.createElement("div");
          el.className = 'block-grid__item';
          el.id = json.id;
          el.innerHTML = `<ul class="xs-border"><li><a href="${url}" class="anchor"><h4 class="title">${title}</h4></a> <div class="text">${text}</div> <span class="by">${by}</span><span class="score">${score}</span></li></ul>`;
          container.appendChild(el);
          module.onClick();
        })
        .catch(function(err) {
          console.log(err);
        });
    }
  }
}

$(document).ready(function() {
  module.init();
});
.active {
  background: #ff0;
}


text:
Q: Making the checkbox non-editable I have an application which loads the result in a table view, there are around 10 columns in the table view. Out of the 10 columns there are 2 columns which are check boxes, Currently the values in the Result set come as 0 and 1. The problem is the values for the check box are coming currently like if its 1 the check box is checked if its 0 the check box is unchecked, but according to my requirement i don't want the check box to be editable, currently the check box is getting editable.
I tried using Editable Binding for the Check box, but it did not work.
Not sure how to achieve this!!
Thanks in Advance!!!

A: You can disable it:
[checkbox setEnabled:NO];

It will be greyed out then, but that should be OK, since that indicates it is not changeable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I specify a CellRange of variable length in DataNitro? I am creating a script and part of it requires a list of names from a cell range to be stored as a list. I need the list to store as many names as are added to the cellrange however it must not store the values of empty cells.
If I simply use a longer range than is necessary like so:
names = CellRange("C10:C99999").value

then my final script will iterate through all the empty values which is extremely inefficient.

A: After quite some searching through the DataNitro documentation I found .vertical property which "returns the values of the cells starting with the cell it's called from, and ending in the last non-empty cell in the same column."
So in my example this would mean:
names = Cell("C10").vertical


text:
Q: I deploy python SimpleHTTPServer and put html file into it. But after a couple of requests to it, the server stops responding I use this command:
python -m SimpleHTTPServer 9023 >/dev/null 2>/dev/null &.

The port is not busy and listening, the firewall is disabled
Аfter which I check the server in the browser: http://localhost:9023
So far so good, but after a couple of attempts the server stops responding.
And this I can see in strace enter image description here


text:
Q: Buscar el valor mas cercano en Crystal Reports Buen día, espero se encuentren bien.
Estoy trabajando con Crystal Reports y necesito agregar un campo que me informe donde esta el valor mas cercano a 80.
En el ejemplo de la imagen el resultado tendría que ser 80.77 ya que es el más próximo a este valor, existe algún función o de que manera puedo saber que valor es el más cercano, de antemano gracias.


text:
Q: Using define in a conditional expression in Scheme In Scheme, the general form of a procedure definition is:

(define (<name> <parameters>) <body>)

where <body> accepts a sequence of expressions, allowing this kind of procedure definitions:
> (define (f) 1 2 3)
> (f)
3

Likewise, the general form of a conditional expression is:

(cond (<predicate> <consequent>) (<predicate> <consequent>) … (<predicate> <consequent>))

where <consequent> in each clause accepts a sequence of expressions, allowing this kind of conditional expressions:
> (cond (#t 1 2 3))
3

But why can't I use define in a clause's consequent of a conditional expression like in the body of a procedure definition?
Compare:
> (define (f) (define x 1) (define y 1) (define z 1) (+ x y z))
> (f)
3

with:
> (cond (#t (define x 1) (define y 1) (define z 1) (+ x y z)))
ERROR on line 1: unexpected define: (define x 1)

Note. — I am using the Chibi-Scheme 0.8.0 implementation on MacOS 10.15.2.

A: define can only be used at either the top-level, or at the beginning of a body. It cannot be used in other places where expressions can be used. Here is the relevant quote from R5RS:

Definitions are valid in some, but not all, contexts where expressions
  are allowed. They are valid only at the top level of a <program> and
  at the beginning of a <body>.

The cases of a cond are not bodys, and so you cannot put a define there.


text:
Q: Why is this simple code returning `none`? I'm trying to do this codefights task:
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
So here's my code:
def almostIncreasingSequence(sequence):
def checa(sequence):
    cont = 0
    copia1 = copia2 = sequence
    for i in range(len(sequence)-1):
        while(cont == 0):
            if(sequence[i] >= sequence[i+1]):
                del(copia1[i])
                del(copia2[i+1])
                cont += 1
    if(all(copia1[j] < copia1[j+1] for j in range(len(copia1)-1)) == True):
        return True
    elif(all(copia2[j] < copia2[j+1] for j in range(len(copia2)-1)) == True):
        return True
    else:
        return False

I can't see my flaws here and it's returning None every single time.

A: You did not include a return statement, thus your function will always return None


text:
Q: Claiming resource with innodb using atomic update If I have an InnoDB table that contains resources (e.g., URLs) that need to be processed (see below):

   RESOURCE_TABLE {
      id int NOT NULL AUTO_INCREMENT,
      resource varchar(100) NOT NULL,
      process_id int DEFAULT NULL
   }

where unprocessed resources have a process_id set to NULL, and there are multiple processes contending to claim each resource, can I do:

update RESOURCE_TABLE set process_id={MY_PROCESS_ID} where process_id is NULL order by id ASC LIMIT 1;

to claim a resource for a given process? Will this update be atomic, or do I need to create a transaction? Also if I claim a new resources in this way, will the resources be claimed sequentially without any gaps in ids?
This question is similar to: MySQL Atomic UPDATE in InnoDB vs MyISAM


text:
Q: F# Iterate over N dimensions What is a good way of iterating over N dimensions in F#? Specifically I want to iterate the levels in a list of lists and display the different paths. Here's a trivial example of what I would like to do in arbitrary list dimensions.
let L1 = ["A"; "B"]
let L2 = ["C"; "D"]
let L3 = ["E"; "F"; "G"]

let pathSteps = [L1; L2; L3]

let printAllPaths =
    let allPaths =
        seq{
            for c1 in L1 do
                for c2 in L2 do
                    for c3 in L3 do
                         yield [c1; c2; c3]
           }
    for ls in allPaths do
        ls
        |> Seq.toList
        |> printfn "%A"


text:
Q: Populate a new column with the value of another column when the value of a third column First time posting here, and new to R. I hope I do it right.
How can use R to populate a new column with the value (just the value) of another column´s row conditional to the value of a third column´s row.
Thank you!

A: Do you want something like this:
for(i in 1:length(df$column1){        #runs the following code for each line
  if(df$thirdcolumn[i] > 0){              #if logical TRUE then it runs the next line
    df$newcolumn[i] <- df$anothercolumn[i]    #gives value of another column to a new column
  }
}


text:
Q: Why isn't this nested loop working? I can't get this to loop through to the next row. The inner two loops are working fine from what i can tell using the debugger but it never goes to the next row. Any help would be appreciated.
Sub PopulateData()
Dim s1 As Worksheet
Dim s2 As Worksheet
Dim locationRow As Integer
Set s1 = ThisWorkbook.Sheets("Order_LVL")
Set s2 = ThisWorkbook.Sheets("sheet1")
Dim Lastrow As Integer
Lastrow = s1.Cells(Rows.Count, 1).End(xlUp).Row
Dim iRow As Integer

For iRow = 1 To Lastrow
Dim cellj As Range
    For Each cellj In s1.Range("B:F")
    locationRow = 1
    Dim celli As Range
        For Each celli In s2.Range("B1:F1")
        Dim currentrow As Long
        currentrow = iRow + 1
            If s1.Cells(currentrow, cellj.Column).Value = 0 Then

            ElseIf s1.Cells(currentrow, cellj.Column).Value <>   s2.Cells(locationRow, celli.Column).Value And s2.Cells(currentrow, celli.Column).Value = 0 Then
            s2.Cells(currentrow, celli.Column).Value = 0
            Else: s2.Cells(currentrow, celli.Column).Value = 1 'indicates that this order features a line from this location
            End If
        Next celli
    Next cellj
Next iRow
End Sub

A: Can you try this on some test data (Note I haven't tested it myself but re-written it with only two loops)
Sub PopulateData()
Dim s1 As Worksheet: Dim s2 As Worksheet
Dim rng As range: Dim rng2 As range
Dim cell: Dim header

With Application
    .ScreenUpdating = False
End With

With ThisWorkbook
    Set s1 = .Sheets("Order_LVL")
    Set s2 = .Sheets("sheet1")
End With

With s1
    Set rng = range(.Cells(1, 2), .Cells(.Cells(Rows.Count, 6).End(xlUp).Row, 6)) ' Used Range in Order_LVL
End With

Set rng2 = range(s2.Cells(1, 2), s2.Cells(1, 6)) 'Header range in sheet1

For Each cell In rng.Cells
    For Each header In rng2.Cells
        If cell.value = 0 Then

        ElseIf cell.value <> header.value And s2.Cells(cell.Row, header.Column).value = 0 Then
            s2.Cells(cell.Row, header.Column).value = 0 ' Not sure why you're doing this - if it is already 0 why set it back to 0. Left it in for continuity
        Else
            s2.Cells(cell.Row, header.Column).value = 1 ' indicates that this order features a line from this location
        End If
    Next header
Next cell

With Application
    .ScreenUpdating = True
End With
End Sub

It should do what you want if I've understood correctly.


text:
Q: The identity column must be of data type int, bigint, smallint, tinyint, decimal, or numeric I have created a database project in Visual Studio 2012, with target platform set to 'Windows Azure SQL Database'. I added a table like:
CREATE TABLE [dbo].[Organization]
(
    [Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY NONCLUSTERED IDENTITY,
    [Name] NVARCHAR(100) NOT NULL,
    [CreationDate] DATETIME NOT NULL DEFAULT GetDate()
)

GO

CREATE CLUSTERED INDEX [IX_Organization_CreationDate] ON [dbo].[Organization] ([CreationDate])

But it keeps complaining about:
Error   1   SQL71518: The identity column '[dbo].[Organization].[Id]' must be of data type int, bigint, smallint, tinyint, decimal, or numeric with a scale of 0, and the column must not be nullable.  C:\Projects\Gastrology\MGP\trunk\Sources\Cfg.Mgp.Infrastructure.Database\Organization.sql   3   2   Cfg.Mgp.Infrastructure.Database

Anyone knows why I can't create a primary key of type guid? What Am I doing wrong?
Thanks!

A: IDENTITY cannot be used with GUID
Use NEWID instead.
CREATE TABLE [dbo].[Organization]
(
    [Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY NONCLUSTERED DEFAULT NEWID(),
    [Name] NVARCHAR(100) NOT NULL,
    [CreationDate] DATETIME NOT NULL DEFAULT GetDate()
)

A: Try something like this :-
CREATE TABLE [dbo].[Organization]
(
    [Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY NONCLUSTERED DEFAULT NEWID(),
    [Name] NVARCHAR(100) NOT NULL,
    [CreationDate] DATETIME NOT NULL DEFAULT GetDate()
)

Check out this link
From the source:-

The main disadvantage to using GUIDs as key values is that they are
  BIG. At 16 bytes a pop, they are one of the largest datatypes in SQL
  Server. Indexes built on GUIDs are going to be larger and slower than
  indexes built on IDENTITY columns, which are usually ints (4 bytes).
  **
  > Not only that, but they're just plain hard to read. Unless you need a
  truly globally unique identifier, you're probably better off sticking
  with an IDENTITY.

**

A: The IDENTITY keyword is used to auto-increment a integer column that is usually used as a primary key. Because you are using a unique identifier, including this keyword makes no sense. (how do you increment a unique identifier?)
Just remove the "IDENTITY" keyword.
http://technet.microsoft.com/en-us/library/ms186775.aspx


text:
Q: How to store values(i.e. 'Y'- for checked, 'N' - for unchecked) of multiple checkbox in database using angularjs? I've attached the screenshot of my module. I want the store the values('Y','N') of selected checkbox in database

    {{$index + 1}}

        {{RoleOperation[$index].vname}}

        {{RoleOperation[$index].id}}

        <input type="checkbox" data-ng-model="data.viewflg[$index]" />

        <input type="checkbox" data-ng-model="data.addflg[$index]" />

        <input type="checkbox" data-ng-model="data.editflg[$index]" />

        <input type="checkbox" data-ng-model="data.deleteflg[$index]" />

Here RoleOperation is Object, which contains names of categories.
How to give value to data-ng-model? And how to access particular checkbox in controller?
plz help me..

A: You can use ng-true-value and ng-false-value to set your preferred values.
To set Y and N use the below code.
<input type="checkbox" data-ng-model="data.viewflg[$index]" ng-true-value="'Y'" ng-false-value="'N'">

-- EDIT --
Here is a sample


text:
Q: Validation alert: An illegal choice has been detected in a CCK form I am loading state select option through ajax for the selected country and by default the state option is

none

with the below reference stackoverflow issue asked few days b4,
how to set multi select CCK Field type for country state city with geoname module?
http://goo.gl/Xpwu0
I couldn't find any answer till now, so tried my own way by
if country selected, based on the country the state have to listed from geoname api so i did it through ajax and appended to the list correspondingly to city.
finally after submitting i got error

An illegal choice has been detected.
  Please contact the site administrator.

A: The form system automatically validates the selected value of a select and only allows those which are defined in '#options'. There is no way around that in D6, in D7, there is a flag to disable that.
You need to use #ahah and rebuild the form on the serverside. The following modules might be useful to you:

*

*http://drupal.org/project/ahah_helper (for building it yourself)

*http://drupal.org/project/hierarchical_select (Maybe you can extend that...?)


text:
Q: What is this topic (competition questions)? I discovered the following question by accident, and found it interesting, but I only resolved it by brute force:
Problem: Let f: $\mathbb{R} \rightarrow \mathbb{R}$ have the property $(\pi)$ iff they satisfy the equation
$$f(s^2 + f(t)) = t + f(s)^2 $$
Determine the family of all functions with the property $(\pi)$.
Solution: If we can show $f(0) := y$ to be zero, then letting $t$ run over all real values, with $s = 0$, shows $f(f(x)) = x$ $\forall x \in \mathbb{R}$, from which it is clear that $\mathrm{Id}(x)$ has the property $(\pi)$.
Taking $s = 0, t = 0$ shows (1) $f(y) = y^2$. Taking $s = y, t = 0$ shows (2) $f(y^2 + y) = (f(y))^2$, so that substitution from (1) gives (3) $f(y^2 + y) = y^4$. However, letting $s = 0, t = y$ shows (4) $f(y^2) = y + y^2$, so that $f(f(y^2)) = y^4$ by substituting the LHS of (4) in (3), while letting $s= 0, t = y^2$ shows directly that (5) $f(f(y^2)) = 2y^2$. Equating (4) and (5) says $2y^2 = y^4$, so $y = -\sqrt{2}, 0,$ or $\sqrt{2}.$
Assume $y = \sqrt{2}.$ Letting $t = f(y^2), s = y$ says (6) $f(f(f(y^2)) + y^2) = f(3y^2)$ $ = f(y^2) + (f(y))^2$; but $s = \sqrt{2}y, t = y$ says (7) $f(3y^2) = (f(\sqrt{2}y))^2 + y = (f(y^2))^2 + y$. Since $(f(y))^2 = y^4$, $f(y^2) = y + y^2$, equating the RHS of (6) and (7) leaves
$$ f(y^2) + (f(y))^2 = (f(y^2))^2 + y \implies y + y^2 + y^4 = (y^4 + 2y^3 + y^2) + y \implies 2y^3 = 0$$
which is absurd. Assuming $y = - \sqrt{2}$ and setting $s = -\sqrt{2}y, t = y$ in (7) similarly shows that $y \neq - \sqrt{2}.$ We conclude that $f(0) = 0$.
That $\forall x \in \mathbb{R} (f(f(x)) = x)$ says that $f(x) = f^{-1}(x);$ this requires that $f$ be one-to-one. Since $f(0) = 0$, we have $t \neq 0 \implies f(t) \neq 0$; we can now show that $f$ is increasing. Pick $x, y \in \mathbb{R}, x < y,$ and set $\delta = y - x.$ By choosing $t = f(x), s = \sqrt{\delta}$, we have
$$f(\delta + f(f(x))) = f(\delta + x) = f(x) + f(\sqrt{\delta})^2 \implies f(x + \delta) - f(x) = f(\sqrt{\delta})^2$$
$$\therefore f(y) - f(x) > 0$$
since we established that $f(\sqrt{\delta}) \neq 0$. This proves that $f$ is increasing.
Since, in fact, $\mathrm{Id}(x)$ is the only $f: \mathbb{R} \rightarrow \mathbb{R}$ which is both increasing and an involution, this says that $f(x) = x$ is the sole function with the property ($\pi$).

So several things:
1) What field(?) of study does this question come from? Is it relevant to quotidian mathematics?
2) This was tricky. It took a lot of messing around with various combinations to get the main result, and I had the uncomfortable feeling that I was being inefficient. (I filled up a page and a half of notebook!) Does anybody know any books/have any advice on how to improve on questions like these?
3) If this is its own field, what other fields are best connected with it? (i.e., furnish handy tools)

A: This is called a functional equation. They are very hard to solve in general, but there are books on the subject. You should not expect an elegant solution in general.


text:
Q: Making cuts on a spiral so that all segments are of the same length Imagine a roll of magnetic strip (about 2 cm in width) which is rolled in a roll of about 30 windings and about 10m length. The strip is about 2cm in width.
The roll is put on a Rod which the user unwinds by hand and with a knife he cuts segments of about 5 cm in length.
Another way of doing this would be to perform the cuts directly on the roll.
The issue is that the inner windings are smaller than the outside windings thus if we make the cuts directly on the roll we come up with different length segments all around.
Is their a geometrically correct way of making the cuts so that all segments will come out the same length?

This is a naive visualisation of the cuts; naturally the segments will come out in different lengths as we approach the centre of the spiral.

And this is how the user cuts them up until now:

There should be a mathematic formula which dictates where to make the cuts directly on the spiral(the roll) so all segments comes out at the same length.

A: If the rolls are round and the windings evenly spaced (radially), I do not believe this is possible.  Most arbitrary lengths, relative to the diameter of the roll, produce scattered cuts (red marks below) that do not align:

Certain lengths result in cuts that more or less align, but they do not form straight lines:

If my simulation is not troubled by numerical inaccuracy it seems local optimums for alignment become worse as segment length increases.  An example of the best I could find in the region of this length:

A: I have a slightly different approach. Basically Archimedes Spiral (as given in the answer by Mr. Wizard) is not accurately describing the curve of the windings... I did not calculate how much difference it makes, but that would depend on the specific parameters. My model does not take the flexibility of the strip into account though!
I modelled the situation by composing circular curve segments with straight lines so that the strip winds around the roll until the tangent line of the inner side of the strip points towards the outer side of the circular part of last winding. This makes the model curve a composition of

*

*circular segments (magenta in my model) centered at the center og the roll

*straight parallel lines (green in my model) defined by the first tangent of the core circle that intersects the beginning of the first circular segment mentioned above

*circular segments (orange in my model) centered at the beginning of the first circular segment mentioned in 1.

This can be seen in my model document in the following link (made with GeoGebra):
GeoGebra-model of the situation
As Mr. Wizard alreay noted, the cuts only become practical for certain matching parameters. In the example given when opening my document it is actually possible to cut most of the segments succesfully from one half of the roll and then one could cut the remaining multiples of the segment length afterwards.
Otherwise you could calculate in some waste in order to have a distance between the cuts that meets the diameter of the roll and thickness of the strip well so that the cuts can be initially of the wrong length but with little waste and then afterwards stacking and cutting these segments. There are many possibilities to consider!


text:
Q: Refresh Activity contents on clicking refresh Button I am building one demo app having pins of all users on Google mapView. I get the data of these users from one php file on server. php file return me one JSONArray of JSONObjects & each JSONObject have data of an individual user. i get it & locate the location of users om map as map pins.
it look ->
GoogleMapView-> This!
public class GoogleMapActivity extends MapActivity implements ActionBar {

Button btnOnMapList, btnProfileHome, btnRefresh;
Intent intent;
GoogleMapActivity gMapActi;

private JSONArray jArray;
private JSONObject jFan_Data;
private ItemBean bean;
private FansData fansdata;//reference of FansData class that return me JSONArray

HelloItemizedOverlay itemizedOverlay;//..........

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    btnProfileHome = (Button) findViewById(R.id.btn_profile_home);
    btnOnMapList = (Button) findViewById(R.id.btn_list_home);
    btnRefresh = (Button) findViewById(R.id.btn_refresh_home);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.googlemapactivity);
    MapView mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapView.displayZoomControls(true);
    // mapView.setSatellite(true);

    /**TG_1 -> Here i write code to get my current location(e.g., through LocationManager)
     * after getting location, i write my location`s latitude & longitude into
     * shearedPreference */

    //geading preference to get my unique id
    SharedPreferences myUid=GoogleMapActivity.this.getSharedPreferences("uid", MODE_WORLD_READABLE);
    String myId=myUid.getString("myId", "");
    Log.i("MyUid", myId);

    /**Calling "jFansData" method of "FansData" class, that return me JSONArray that
     * have JSONObjects as its elements & each JSONObject is the complete data of one Unique
     * Fan Near you. currently i use hard codded  lat & lang are
     */
    fansdata=new FansData();
    jArray=fansdata.jFanDataArray(1000, 12.9716060, 77.5903760, "h9ow0");
    System.out.println(jArray.toString());

    //to showing fans on map as pins
    Drawable drawable = this.getResources().getDrawable(
            R.drawable.small_football_icon);
    HelloItemizedOverlay itemizedOverlay = new HelloItemizedOverlay(
            drawable, getParent());
    for(int i=0;i<jArray.length();i++){
        try {
            jFan_Data=jArray.getJSONObject(i);

            //.........Code Showing different ways of How we can convert one double type value into String type!
            try {
                System.out.println("Normal"+jFan_Data.getDouble("lat"));
                Double lat=new Double(jFan_Data.getDouble("lat"));
                System.out.println("fm_Dbl_Wpr"+lat);
                System.out.println("wpr_toStr"+Double.toString(lat));
                System.out.println("wpr_toStr_jFan"+Double.toString(jFan_Data.getDouble("lat")));

                Log.i("GeoCd_double", Double.toString(lat));
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            //.........
            GeoPoint geoPoint = new GeoPoint((int) (jFan_Data.getDouble("lat")* 1E6),
            (int) (jFan_Data.getDouble("lang")* 1E6));
        //  GeoPoint geoPoint = new GeoPoint(jFan_Data.getInt("lat"),jFan_Data.getInt("lang"));
            //GeoPoint geoPoint = new GeoPoint((int)(jFan_Data.getInt("lat")*1E6), (int)(jFan_Data.getInt("lang")*1E6));

            OverlayItem overlayitem = new OverlayItem(geoPoint, jFan_Data.getString("name"),
            jFan_Data.getString("uniqid"));
            itemizedOverlay.addOverlay(overlayitem);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    List<Overlay> mapOverlays = mapView.getOverlays();

    // Second Overlay
    Drawable drawable2 = this.getResources().getDrawable(
            R.drawable.small_football_icon_yellow);

    HelloItemizedOverlay itemizedOverlay2 = new HelloItemizedOverlay(
            drawable2, getParent());

    GeoPoint geoPoint4 = new GeoPoint(35410000, 139460000);
    OverlayItem overlayItem4 = new OverlayItem(geoPoint4, "Nidhi", "");
    itemizedOverlay2.addOverlay(overlayItem4);

    GeoPoint geoPoint5 = new GeoPoint((int) (41.51738 * 1E6),
            (int) (-0.08186 * 1E6));
    OverlayItem overlayItem5 = new OverlayItem(geoPoint5, "Sapan", "");
    itemizedOverlay2.addOverlay(overlayItem5);

    mapOverlays.add(itemizedOverlay);
    mapOverlays.add(itemizedOverlay2);
}

 //.........................

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public void onHomeList(View view) {
    Intent in = new Intent(getParent(), MapPinsList.class);
    TabGroupActivity prnt = (TabGroupActivity) getParent();
    prnt.startChildActivity("MapPinsList", in);

}

@Override
public void onHomeProfile(View view) {
    Intent in = new Intent(getParent(), ProfileActivity.class);
    TabGroupActivity prnt = (TabGroupActivity) getParent();
    prnt.startChildActivity("ProfileActivity", in);

}

@Override
public void onHomeRefresh(View view) {
    // TODO Auto-generated method stub

   //???????????

    //super.onCreate(null);
}

@Override
public void onListMap(View view) {
    // TODO Auto-generated method stub

}

@Override
public void onListProfile(View view) {
    // TODO Auto-generated method stub

}

}

it have one actionBar on this view having three imageButtons(refresh, List & Profile) over it.
when i click over "List" it will showing me the mapPins in one "ListView". I have one Adapter(LazyAdapter extends BaseAdapter).
listView-> this!
public class MapPinsList extends ListActivity implements OnItemClickListener,ActionBar {

ListView mFansListView;
JSONArray jArray;//jArray that contains jobjects of all fans. each jobj hv data of 1 unique fan!
JSONObject jFan_Data;//contain data of an indivisual fan
JSONObject jFansData;//contain data of an all fans
//ListViewCustomAdapter adapter;//gc
LazyAdapter adapter;
private ArrayList<Object> fansList;
private ArrayList<String> mStrings ;
private ItemBean bean;
private FansData fansData;
String url="http://192.168.200.111/ManU/";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.on_pins_list_clicks);

    prepareArrayLits();

    // mFansListView = (ListView) findViewById(R.id.listView1);
    mFansListView = (ListView) findViewById(android.R.id.list);
    adapter = new LazyAdapter(this, mStrings, fansList);
    mFansListView.setAdapter(adapter);// come null pointer exception when no fan data is returned! hendle it...

    mFansListView.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
    // TODO Auto-generated method stub
    ItemBean bean = (ItemBean) adapter.getItem(position);

    //retrieve MyUniqueId from sheared Preferences
    SharedPreferences myUid=MapPinsList.this.getSharedPreferences("uid", MODE_WORLD_READABLE);
    String myId=myUid.getString("myId", "");

    Toast.makeText(this,"MyUId->"+ myId+"\nFanId => " + bean.getUid() +" \n UID => " + bean.getTitle(), Toast.LENGTH_SHORT).show();

    /**from here-> I am going to start one activity that show the complete profile of a
     * particular Fan... According to the unique id received from clicking on ListItem!
     */
    for(int i=0;i<jArray.length();i++){
        try {
            JSONObject jFan_Data=jArray.getJSONObject(i);
            String fanId=jFan_Data.getString("uniqid");

            if(fanId.equals(bean.getUid())){
                //New Intent that start new Activity that show Profile of a Fan

                Intent in= new Intent(getParent(), FanProfile.class);
                TabGroupActivity prnt = (TabGroupActivity) getParent();
                Bundle fBundle= new Bundle();
                //fBundle.putStringArray("jFanData", jFanData);
                fBundle.putString("fanId", fanId);
                in.putExtras(fBundle);
                prnt.startChildActivity("FanProfile", in);

                //startActivity(in);

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

/** Method used to prepare the ArrayList, Same way, you can also do looping
 * and adding object into the ArrayList.
 */

/** Method used to prepare the ArrayList */
public void prepareArrayLits() {

    /** I read shearedPreference to get my location`s latitude, longitude &
     * myUniqueId */
    //......

    fansData = new FansData();

    //return me array containing data of all fans
    jArray = fansData.jFanDataArray(1000, 12.9716060, 77.5903760, "h9ow0");

    /**preserving this jArray into preference so that i can recieve it any where
     * when i want the data of all fans like in GooglwMapActivity when i tap on pins...
     * I store it in the String formate...But when i get it from preference i can
     * build one JSONArray by passing this String as parameter as
     * SharedPreferences fansData=GoogleMapActivity.this.getShearedPrefrences("jArray",MODE_WORLD_READABLE);
     * String jArr=JArray.getString("allFansData","");
     * -> new JSONArray(jArr); will return me complete jArray same as that of here in MapPinsList!!!
     * */

    SharedPreferences fansData = getSharedPreferences("jArray", MODE_WORLD_READABLE);
    SharedPreferences.Editor edit = fansData.edit();
    edit.putString("allFansData", jArray.toString());
    edit.commit();

    // ++++++++
    try {
        //Initializing ArrayList
        fansList = new ArrayList<Object>();
        mStrings = new ArrayList<String>();
        for (int i = 0; i < jArray.length(); i++) {
            // will return the data of each row fetched from JSONArray returned by location1.php
            String data_of_each_user = jArray.get(i).toString();

            Log.i("Data Of User at index " + i + " is", data_of_each_user);

            // I put the object at index "i" into JSONObject & retrieve data from name-value pair
            jFan_Data = jArray.getJSONObject(i);// data of User at index i
                                                // in array

            AddObjectToList(jFan_Data.getString("uniqid").toString(), jFan_Data.getString("name"),
                    jFan_Data.getString("distance"));

            Log.i("URL", url+"images/"+jFan_Data.get("uniqid").toString()+".png");
            mStrings.add(url+"images/"+jFan_Data.get("uniqid").toString()+".png");
            Log.i("URL....", url+"images/"+jFan_Data.get("uniqid").toString()+".png");

            String nm = jFan_Data.get("name").toString();
            String uid = jFan_Data.get("uniqid").toString();
            String dis = jFan_Data.get("distance").toString();

            System.out.println("Your Name:       " + nm);
            System.out.println("Your Unique Id:  " + uid);
            System.out.println("Your Distance:   " + dis);
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    // ++++++++++
}

// Add one item into the Array List
 public void AddObjectToList(String uid, String title, String desc) {
    bean = new ItemBean();
    bean.setUid(uid);
    bean.setDescription(desc);
    bean.setTitle(title);
    fansList.add(bean);
}

@Override
public void onHomeList(View view) {
    // TODO Auto-generated method stub
}

@Override
public void onHomeProfile(View view) {
    // TODO Auto-generated method stub
}

@Override
public void onHomeRefresh(View view) {
    // TODO Auto-generated method stub
}

@Override
public void onListMap(View view) {
    Intent in = new Intent(getParent(), GoogleMapActivity.class);
    TabGroupActivity prnt = (TabGroupActivity) getParent();
    prnt.startChildActivity("GoogleMapActivity", in);
}

@Override
public void onListProfile(View view) {
    // TODO Auto-generated method stub
    Intent in = new Intent(getParent(), ProfileActivity.class);
    TabGroupActivity prnt = (TabGroupActivity) getParent();
    prnt.startChildActivity("ProfileActivity", in);
}

}

What i need is when i click on Refresh Button on these Views my Activities contents get refreshed! ...?
the contents of JSONArray varies according to my current location & when i click on refresh button it again look my data(e.g., my current LATITUDE & LONGITUDE, distance upto which i want to see the users from my current location) i write these in onCreate of my class.
Now How do i refresh my contents when i click on "Refresh" button on these views???
Any suggestions please, would appreciated any pointer, sample code to do this

A: you should restart your activity with single_Top intent flag as below on button click.
Intent intent = new Intent(context,GoogleMapActivity.class);

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

startactivity(intent);

By this it not call your activity's onCreate() or onResume() but it call onNewIntent().
so do your refresh code inside it as-

onNewIntent(){

   //   your stuff...

    ....
}


text:
Q: Need to remove space between two elements inside of a React-Bootstrap Column I have an SVG and a
 element that are both wrapped together inside of an anchor tag.
The anchor around the SVG and
 element all live inside of container.
I have styles for the container element as well as the
 element to position them next to each other and centered in the middle of the parent element which is a React-Bootstrap column.
Right now the SVG is sitting directly on top of the
 element and if I remove out the anchor tag element there is a large gap between the SVG and the
 element however they sit on the same line together and are aligned correctly.
I have the React HTML and the corresponding styling below. Any ideas on how to get these to line up properly?
HTML
<Col>
  <ClipboardContainer>

      <ClipboardSvgLarge />
view order status >

  </ClipboardContainer>
</Col>

Styled Components CSS
const ClipboardContainer = styled('div')((props) => ({
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  marginTop: '10%',
  p: {
    margin: '0 auto',
    color: props.theme.colors.blueAlt,
    textTransform: 'uppercase',
    fontSize: '.75em',
    fontWeight: 600
  }
}))


text:
Q: Unable to include ux in Ext JS application The application does not include the UX.
The entire extjs library is in -  myexample/js/ext-6.2.0
I copied from myexample/js/ext-6.2.0/ packages the folder "ux" with all the contents into my application
test
|---app.js
|
|---app
|    |---controller
|    |---model
|    |---store
|    |---ux
|    |---view
|---index.html

Then in app.js, before calling the application I connect 'ux':
Ext.Loader.setConfig({enabled:true});
Ext.Loader.setPath('Ext.ux', 'app/ux');
Ext.application({
....

I get the error:

[Ext.Loader] Synchronously loading 'widget.treepicker'; consider
  adding Ext.require('widget.treepicker') above Ext.onReady

Version: Ext JS 6.2.0.981 - JavaScript Library
What am I doing wrong?
How to incldue UX?
Thanks.

A: try adding this in the app.js file
requires:[
    'Ext.ux.your_file_name' //your_file_name inside the ux folder
]

A: In file "app.json" you should find "requires" config similar to this
 "requires": [
        "font-awesome",
        "charts",
        "ux"
    ]

"app.json" will be present in Extjs application folder, this folder will be the result of command :
sencha generate app -ext MyApp /path/to/my-app

This is where you import the package. So part of your code is making "ext" package to be not loaded. This is causing error related to "treepicker". Because "treepicker" is part of "extjs" package.
Try including package this way. It should work.


text:
Q: Spliting and Writing a Text file Lines into dataframe columns I have a text file which is written in Notepad++, which contains a series of numbers at each line. like:
12451
I want to read this text file into python and assign each digit to a specific column of a dataframe, in a same order for all lines (here with 5 columns, as the length of each line).
how can I do that?

A: You can do that by using pd.read_fwf function. e.g.
import pandas as pd
df=pd.read_fwf("file.txt",widths=[1,1,1,1,1],header=None)


text:
Q: This Variation code doesn't work with my code in doStuff Function I'm trying to fetch the data from  the sheet cell B1 and do the math with that data but it doesn't work when I this line
var source = SpreadsheetApp.openById('1mkbnIlDt6WGltQg6peKojBFPz0JwyjAkJGwTYbLYEmk').getSheetByName('HardEdit').getRange('B1').getValue();

But when i remove the above line, it works all fine.can i know the reasone?  here is my code,
document.getElementById("btn").addEventListener("click", doStuff);
    function doStuff() {

      var source = SpreadsheetApp.openById('1mkbnIlDt6WGltQg6peKojBFPz0JwyjAkJGwTYbLYEmk').getSheetByName('HardEdit').getRange('B1').getValue(); //Separate spreadsheet book

      const rate = 0.155;
      const vprice = document.getElementById("price").value;
      const downPayment = document.getElementById("DownPay").value;
      const borrow = vprice-downPayment;
      const period = 12;// add motnhs here
      const opp = vprice*0.5;

      var nf = new Intl.NumberFormat(); //number format

     const subL = Math.round((vprice*source)/2);

A: Unfortunately, in the current stage, at HTML&Javascript side (client side), Google Apps Script cannot be directly used. In your case, I think that google.script.run can be used for retrieving the values from Google Apps Script. So please modify as follows.
HTML&Javascript side:
Please modify doStuff() as follows.
function doStuff() {
  google.script.run.withSuccessHandler(source => {
    const rate = 0.155;
    const vprice = document.getElementById("price").value;
    const downPayment = document.getElementById("DownPay").value;
    const borrow = vprice-downPayment;
    const period = 12;// add motnhs here
    const opp = vprice*0.5;
    var nf = new Intl.NumberFormat(); //number format
    const subL = Math.round((vprice*source)/2);
  }).getValues();
}

Google Apps Script side:
Please add the following function.
function getValues() {
  return SpreadsheetApp.openById('1mkbnIlDt6WGltQg6peKojBFPz0JwyjAkJGwTYbLYEmk').getSheetByName('HardEdit').getRange('B1').getValue();
}

*

*In this modification, when doStuff() is run, getValues() at Google Apps Script is run by google.script.run. And the returned value from getValues() can be retrieved at Javascript side using withSuccessHandler.

References:

*

*Class google.script.run


text:
Q: When to use interfaces (unit testing, IoC?) I suspect I've made a schoolboy error here, and am looking for clarification. A lot of the classes in my solution (C#) - dare I say the majority - I've ended up writing a corresponding interface for. E.g. an "ICalculator" interface and a "Calculator" class that implements it, even though I'm never likely to replace that calculator with a different implementation. Also, most of these classes reside in the same project as their dependencies - they really only need to be internal, but have ended up being public as a side-effect of implementing their respective interfaces.
I think this practice of creating interfaces for everything stemmed from a few falsehoods:-
1) I originally thought that an interface was necessary to create unit test mocks (I'm using Moq), but I've since discovered that a class can be mocked if its members are virtual, and it has a parameterless constructor (correct me if I'm wrong).
2) I originally thought an interface was necessary to register a class with the IoC framework (Castle Windsor), e.g.
Container.Register(Component.For<ICalculator>().ImplementedBy<Calculator>()...

when in fact I could just register the concrete type against itself:
Container.Register(Component.For<Calculator>().ImplementedBy<Calculator>()...

3) Using interfaces, e.g. constructor parameters for dependency injection, results in "loose coupling".
So have I gone mad with interfaces?! I'm aware of the scenarios where you would "normally" use an interface, e.g. exposing a public API, or for things like "pluggable" functionality. My solution has a small number of classes that fit such use cases, but I wonder if all the other interfaces are unnecessary, and should be removed? Regarding point 3) above, won't I be violating "loose coupling" if I was to do this?
Edit:- I'm just having a play with Moq, and it seems to require methods to be public and virtual, and have a public parameterless constructor, in order to be able to mock them. So it looks like I can't have internal classes then?

A: In general, if you make an interface which only has one implementor, you're just writing things twice and wasting your time. Interfaces alone do not provide loose coupling if they're tightly coupled to one implementation... That said, if you want to mock these things in unit tests, that's usually a great sign that you'll inevitably need more than one implementor in real code.
I would consider it a bit of a code smell if nearly all your classes have interfaces though. That means they're almost all working with one another in one way or another. I would suspect that the classes are doing too much (since there's no helper classes) or you've abstracted too much (oh, I want a provider interface for gravity since that might change!).

A: 1) Even if concrete classes are mockable, it still requires that you make members virtual and provide a parameterless constructor, which may be obtrusive and unwanted. You (or new team members) will soon find yourself systematically adding virtual's and parameterless constructors in every new class without a second thought, just because "that's the way stuff works".
An interface is IMO a much better idea when you need to mock a dependency, because it allows you to defer implementation until when you really need it, and makes for a nice clear contract of the dependency.
3) How's that a falsehood ?
I believe interfaces are great for defining messaging protocols between collaborating objects. There might be cases when the need for them is debatable, as with domain entities for instance. However, wherever you have a stable partner (i.e., an injected dependency as opposed to a transient reference) you need to communicate with, you should generally consider using an interface.

A: The idea of IoC is to make the concrete types replaceable. So even if (right now) you only have a single Calculator that implements ICalculator, a second implementation could depend only on the interface and not on implementation details from Calculator.
Therefore, the first version of your IoC-Container registration is the correct one, and the one you should use in future.
If you make your classes public or internal is not really related, and neither is the moq-ing.

A: I'd really be more worried about the fact that you seem to feel the need to "mock" just about every type in your whole project.
Test doubles are mostly useful for isolating your code from the external world (third-party libs, disk IO, network IO, etc.) or from really expensive computations. Being too liberal with your isolation framework (do you even REALLY need it? is your project that complex?) can easily lead to tests that are coupled to the implementation, and it makes your design more rigid. If you write a bunch of tests that verify that some class called method X and Y in that order, and then passed parameters a, b and c to method Z, are you REALLY getting value? Sometimes you get tests like this when testing logging or interaction with third party libs, but it should be the exception, not the rule.
As soon as your isolation framework tells you that you must make stuff public and that you must always have parameterless constructors, it's time to get the heck out of dodge, because at this point your framework is FORCING you to write bad (worse) code.
Speaking more specifically about interfaces, I find they are useful in a few key cases:

*

*When you need to dispatch method calls to different types, e.g. when you have multiple implementations (this is the obvious one, since the definition of an interface in most languages just is a collection of virtual methods)

*When you need to be able to isolate the rest of your code from some class. This is the normal way of abstracting away the file system and network access and the database and so on from the core logic of your application.

*When you need inversion of control to protect application boundaries. This is one of the most powerful ways possible for managing dependencies. We all know high level modules and low level modules shouldn't know about eachother, because they will change for different reasons and you DON'T want to have dependencies on HttpContext in your domain model or on some Pdf rendering framework in your matrix multiplication library. Making your boundary classes implement interfaces (even if they are never ever replaced) helps loosen the coupling between layers, and it drastically reduces the risk of dependencies seeping through the layers from types knowing of too many other types.

A: I lean towards the idea that, if some logic is private, then the implementation of that logic should be of no concern for anyone, and as such shouldn't be tested. If some logic is complex enough that you want to test it, that logic probably has a distinct role and should therefor be public.
E.g. if I extract some code in a private helper method, I find that it's usually something that could just as well sit in a separate public class (a formatter, a parser, a mapper, whatever).
As for interfaces, I let the need for having to stub or mock the class drive me. Stuff like repos, I usually want to be able to stub or mock. A mapper in an integration test, (usually) not so much.


text:
Q: Python | TypeError: unsupported operand type(s) for /: 'NoneType' and 'int' |use Variable to divide a = int(float(input("Add : ")))
b =  int(float(input("Add : ")))
c = print(" = " , a**2 + b**2)

print(c/2)

I'm going to divide the variable and the number but it happens like this, how do I fix it?
| TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

A: print returns None, which you assign to c. None can't be divided by an int, hence your error.
If you want to store the result of a**2 + b**2 in c, then do so directly:
a = int(input("Add: "))
b = int(input("Add: "))
c = a**2 + b**2

print(f"{a=}, {b=}, {c=}")
print(c / 2)

Sample execution:
Add: 3
Add: 5
a=3, b=5, c=34
17.0

A: print is a function which returns None and the side effect of printing its args to stdout.
Therefore c has the value None. And None / 2 gives the TypeError


text:
Q: Javascript only draws last of multiple drawings Okay so i'm embarrassingly unknowledgeable of javascript. I know my ruby and rails pretty solid but have never used js as extensively as i am in my current project.
i have a map that's been drawn on a canvas. on that map, i want drawn multiple position markers (via the provided function). i've given it a list (via rails) of locations to mark. for some reason, it's only drawing the last coordinate.
the javascript is improvised from another source, not mine. this is just the problematic portion:
        function plotPosition(long,lat) {
            // Grab a handle to the canvas
            var canvas = document.getElementById('map'),
                ctx;

            // Canvas supported?
            if (canvas.getContext) {
                // Grab the context
                ctx = canvas.getContext('2d');

                ctx.beginPath();

                // Draw a arc that represent the geo-location of the request
                ctx.arc(
                    degreesOfLongitudeToScreenX(long),
                    degreesOfLatitudeToScreenY(lat),
                    5,
                    0,
                    2 * Math.PI,
                    false
                );

                // Point style
                ctx.fillStyle = 'rgb(0,0,0)';
                ctx.fill();

                ctx.stroke();
            }
        }

        function draw() {
            // Main entry point got the map canvas example

            var canvas = document.getElementById('map'),
                ctx;

            // Canvas supported?
            if (canvas.getContext) {
                ctx = canvas.getContext('2d');

                // Draw the background
                drawBackground(ctx);

                // Draw the map background
                drawMapBackground(ctx);

                // Draw the map background
                // drawGraticule(ctx);

                // Draw the land
                drawLandMass(ctx);

                <% @events.each do |e| %>
                plotPosition('<%= e.longitude %>','<%= e.latitude %>');
                <% end %>

            } else {
                alert("Canvas not supported!");
            }
        }

so my thinking is that the plotPosition function is drawing each coordinate, but every time it's given a new coordinate, the old one is erased/moved and replaced with the new one. probably a simple fix here, but i've been at this for hours and to no avail. banging my head.
any ideas as to the problem?

A: From the code example it seems as you are clearing the background too - you're not showing the calls to these methods but I will assume you do this before drawing the new point(s) (?) somewhere else in the code.
If so -
You need to redraw all the points you have drawn before you clear the canvas.
One way to do this is to store the points you already have in an array and then call a redraw function to draw everything in there. Or store the points from server directly to the array with converted values and when all points has been converted redraw everything.
Simplified example based on latter approach (which will require some re-factoring):
/// GLOBALS (put ctx here instead as well..)

var points = [],
    canvas = document.getElementById('map'),
    ctx = canvas.getContext ? canvas.getContext('2d') : null;

if (ctx === null) {...sorry...};

...

/// somewhere comes the logic to get the points themselves.
...
<% @events.each do |e| %>
storePosition('<%= e.longitude %>','<%= e.latitude %>');
<% end %>
...

/// after new points are added, render them all
renderAll();

function storePosition(long, lat) {

    points.push{
        x: degreesOfLongitudeToScreenX(long)
        y: degreesOfLatitudeToScreenY(lat),
        long: long,
        lat: lat
    }
}

function renderAll();

    /// clear and redraw background of canvas

    drawBackground(ctx);

    // Draw the map background
    drawMapBackground(ctx);

    // Draw the map background
    // drawGraticule(ctx);

    // Draw the land
    drawLandMass(ctx);

    /// now plot all the stored points

    ctx.fillStyle = 'rgb(0,0,0)';

    for(var i = 0, point; point = points[i]; i++) {

        ctx.beginPath();
        ctx.arc(
            point.x,
            point.y,
            5,
            0,
            2 * Math.PI
        );
        ctx.closePath();
        ctx.fill();
    }
}

You can implement a check of x and y to see that they are inside canvas but this is strictly not necessary as canvas will clip them for you and the internal clipping do faster checking than JavaScript will. But for debugging purposes you could always do a check if you suspect this. But you write that the point is plotted but erased when a new point is drawn so I don't think this is the problem here.


text:
Q: Wait for asynchronous block to finish - signal (seems) do not work I am using cryptotokenkit to send/receive data from smart card. The use case is, I must have the response from the card API before I do something else.
In my case I found that this line is always called after kMaxBlockingTimeSmartCardResponse (= 10) seconds.
From
dispatch_semaphore_t sema = dispatch_semaphore_create(0);

it directly goes to
dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kMaxBlockingTimeSmartCardResponse * NSEC_PER_SEC));
        dispatch_semaphore_wait(sema, timeout);

Then wait for 10 seconds to come to the block call. Its not the block callback delaying. If I set the dispatch time 20 or 30 seconds, it wait for 20 or 30 seconds to execute. The wait call really wait for the specified time then callback block is executed.
What I am doing wrong? I wonder if this is related to adObserver.
- (void) updateSlots {
    self.slotNames = [self.manager slotNames];
    self.slotModels = [NSMutableArray new];
    self.slots = [NSMutableArray new];

    if([self.slotNames count] > 0)
    {
        for (NSString *slotName in self.slotNames)
        {
            NSLog(@"SmartCard reader found: %@", slotName);
            // semaphore BLOCK starts
            dispatch_semaphore_t sema = dispatch_semaphore_create(0);
            [self.manager getSlotWithName:slotName reply:^(TKSmartCardSlot *slot)
             {
                 if (slot) {
                     SCSlotModel *slotModel = [SCSlotModel new];
                     [self.slotModels addObject:slotModel];

                     [self.slots addObject:slot];
                     [slot addObserver:self forKeyPath:@"state"
                               options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld | NSKeyValueObservingOptionInitial
                               context:nil];

                     slotModel.suffixedName = slotName; // NOT slot.name; original name is suffixed with 01, 02 etc.
                     slotModel.slot = slot;
                     slotModel.cardStatus = [CardUtil mapCardStatus:slot.state];
                     DLog(@"slot: %@, slotmodel: %@",slot.name, slotModel);
                 } else {
                     NSLog(@"Did not find slot with name: %@", slotName);
                 }
                 dispatch_semaphore_signal(sema);
             }];
            dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kMaxBlockingTimeSmartCardResponse * NSEC_PER_SEC));
            dispatch_semaphore_wait(sema, timeout);
            // semaphore BLOCK ends
            self.errorCode = SCPNoError;
        }

    } else {
        NSLog(@"No slot available.");
        self.errorCode = SCPErrorReaderNotFound;
    }
}

getSlotWithName is the method from TKSmartCardSlotManager
/// Instantiates smartcard reader slot of specified name.  If specified name is not registered, returns nil.
- (void)getSlotWithName:(NSString *)name reply:(void(^)(TKSmartCardSlot *__nullable slot))reply;

But in other places it works as expected, for the same type of asynchronous calls.
- (BOOL) beginSession:(TKSmartCard *)card
{
    __block BOOL response = NO;
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    [card beginSessionWithReply:^(BOOL success, NSError *error) {
        response = success;
        if (!success) {
            NSLog(@"Could not begin session.");
        }
        if (error) {
            NSLog(@"Could not begin session with error %@", error);
        }
        dispatch_semaphore_signal(sema);
    }];

    dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kMaxBlockingTimeSmartCardResponse * NSEC_PER_SEC));
    dispatch_semaphore_wait(sema, timeout);
    return response;
}

A: What thread does getSlotWithName:reply: call its reply handler back on?
If for example updateSlots is executed on the main thread and you are doing something like this:
... // some async operation in `getSlotWithName:reply:` has completed
dispatch_async(dispatch_get_main_queue(), ^{
    reply(slot)
});

then you would have ended up queueing your reply on the main thread however the main thread is currently locked with your semaphore.
Ensuring you call dispatch_semaphore_signal() from a thread other than the one you have locked should fix your issue.

Side Note: GCD and semaphores do the trick here but there are better ways you could perform actions after an async operation completes rather than letting a thread get locked up.. For example, delegate callbacks.
Not got enough information here to suggest anything exact but there are other options out there :)


text:
Q: Shutting down dynamic backend instance in google app engine(python) by sending http request or code? I have created a dynamic backend instance with backend.yaml file . Now i wants some way that it can shutdown after the request is completed.

A: Backends are deprecated.  You want to switch to Modules.  You can use the idle_timeout parameter to have an instance shutdown after a preferred time of idleness:
https://developers.google.com/appengine/docs/python/modules/

A: Dynamic backend supposed to be shut after some idle time. But still if you want to shut it down, you can send a request to stop it. You can get code example from following answer:
https://stackoverflow.com/a/7224387/2594162


text:
Q: How to copy and extract .gz files using python I am just starting to learn python and have a question.
How to create a script to do following:  ( will write how i do it in bash)

*

*Copy <file>.gz from remote server1 to local storage.

cp /dumps/server1/file1.gz /local/

*Then extract that file locally.

gunzip /local/file1.gz

*Then copy the extract file to remote server2 (for archiving and deduplication purposes)

cp /local/file1.dump /dedupmount

*delete local copy of .gz file to free space on "temporary" storage

rm -rf /local/file1.gz

I need to run all that in loop for all files.
All files and directories are NFS mounted on same server.
A for loop goes through /dump/ folder and looks for .gz files.
Each .gz file will be first copied to /local directory, and then extracted there.
Once extracted, the unzipped .dmp file will be copied to /dedupmount folder for archiving.
Just banging my head on wall how to write this.

A: Python Solution
While the shell code might be shorter, the whole process can be done natively in python.  The key points in the python solution are:

*

*With the gzip module, gzipped files are as easy to read as normal files.

*To obtain the list of source files, the glob module is used.  It is modeled after the shell glob feature.

*To manipulate paths, use the python os.path module.  It provides a OS-independent interface to the file system.
Here is sample code:
import gzip
import glob
import os.path
source_dir = "/dumps/server1"
dest_dir = "/dedupmount"

for src_name in glob.glob(os.path.join(source_dir, '*.gz')):
    base = os.path.basename(src_name)
    dest_name = os.path.join(dest_dir, base[:-3])
    with gzip.open(src_name, 'rb') as infile:
        with open(dest_name, 'wb') as outfile:
            for line in infile:
                outfile.write(line)

This code reads from the remote1 server and writes to the remote2 server.  This is no need for a local copy unless you want one.
In this code, all decompression is done by the CPU on the local machine.
Shell code
For comparison, here is the equivalent shell code:
for src in /dumps/server1/*.gz
do
    base=${src##*/}
    dest="/dedupmount/${base%.gz}"
    zcat "$src" >"$dest"
done

Three-Step Python Code
This slightly more complex approach implements the OP's three-step algorithm which uses a temporary file on the local machine:
import gzip
import glob
import os.path
import shutil

source_dir = "./dumps/server1"
dest_dir = "./dedupmount"
tmpfile = "/tmp/delete.me"

for src_name in glob.glob(os.path.join(source_dir, '*.gz')):
    base = os.path.basename(src_name)
    dest_name = os.path.join(dest_dir, base[:-3])
    shutil.copyfile(src_name, tmpfile)
    with gzip.open(tmpfile, 'rb') as infile:
        with open(dest_name, 'wb') as outfile:
            for line in infile:
                outfile.write(line)

This copies the source file to a temporary file on the local machine, tmpfile, and then gunzips it from there to the destination file.  tmpfile will be overwritten with every invocation of this script.
Temporary files can be a security issue.  To avoid this, place the temporary file in a directory that is write-able only by the user who runs this script.

A: you can use the module urlopen
import urllib
#urlretrieve will save the file to local drive
urllib.urlretrieve(url,file_name_to_save)

now you can use gunzip utitlty to extract, use  os.system


text:
Q: sparse matrix matrix multiplication in python for rectangular matrices I am working in python with sparse matrix A of size n x m.
I am using csr_matrix format from scipy and I am wrapping my matrix to be linearoperator, so I could use slinalg package.
I need to compute A^T*A product. However, I can not manage to find proper routine to achieve this.
I could use matmat function of linearoperator, but this requires me to convert matrix to dense format.
Is there any way how could I multiply two sparse matrices in python (even with different package) without converting to dense matrix? My matrices are big and conversion causes crash due to memory requirements.

A: SciPy has very efficient built-in method for matrix multiplication of 'sparse csr_matrix' without converting it into dense matrix.
You can directly use the following:
import scipy

data, row, column = ...
A = scipy.sparse.csr_matrix((data, (row, column)), shape = (...))

matmul = A.T*A


text:
Q: Testing repository method As the title suggests I'm trying to test a method, unfortunately I appear to be going wrong some where. The method should only return customers that have and ID = 1
Here is my test
        [TestMethod]
        public void Returns_Correct_Number_Of_Workout_Dates_For_Valid_UserId()
        {

        //Arrange
        List<GymSession> gymSessions = new List<GymSession>();

        Customer cust = new Customer();

        cust.CustomerId = 1;

        gymSessions.Add(new GymSession() { Customer = cust, SessionId = 1, Date = new DateTime(2010, 1, 1)  });
        gymSessions.Add(new GymSession() { Customer = cust, SessionId = 2, Date = new DateTime(2010, 1, 2) });
        gymSessions.Add(new GymSession() { SessionId = 3, Date = new DateTime(2010, 1, 3) });
        gymSessions.Add(new GymSession() { Customer = cust, SessionId = 4, Date = new DateTime(2010, 1, 4) });

        var mockRepos = new Moq.Mock<IGymSessionRepository>();
        mockRepos.Setup(g => g.GymSession()).Returns(gymSessions.AsQueryable());

        //Act
        var result = mockRepos.Object.GetWorkoutDatesByCustomerId(1);

        //Assert
         Assert.AreEqual(3, result.Count());
        }

Here is the repository method I'm trying to test
        public IQueryable<GymSession> GetWorkoutDatesByCustomerId(int userId)
    {
        var gymSess = db.GymSessions.Where<GymSession>(g => g.Customer.CustomerId == userId);

        return gymSess;
    }

The idea is that setup has all the customers, and the method then filters them. The count never seems to apply the filter. Any ideas?

A: It appears that you really want to stub the call to db.GymSessions and that you should test a concrete GymSessionRepository instance. Traditionally, there are two ways to do this (apart from intercepting calls using aspect-oriented programming):
1) Give your repository an explicit dependency on db and require it in the repository constructor. Here's what I mean, where I'm using IDatabase to represent db:
public class GymSessionRepository: IGymSessionRepository {
    private IDatabase db;
    public GymSessionRepository(IDatabase db) {
        this.db = db;
    }
}

// Then in your test ...
var mockDb = new Moq.Mock<IDatabase>();
mockDb.Setup(d => d.GymSessions()).Returns(gymSessions.AsQueryable());

GymSessionRepository repository = new GymSessionRepository(mockDb);
// ... and so on

2) (Less desirable, but sometimes necessary) Expose the method you want to stub as a virtual member, mock the concrete object you're testing, and stub the behavior directly on the class under test:
public class GymSessionRepository {
    // Because this is virtual, you can override it in your mock object
    protected virtual List<GymSession> GymSessions() {
        return this.db.GymSessions.AsQueryable();
    }
}

// In your test code here: notice the mock object is your concrete class,
// because your test targets another method on that class, not a method
// on an arbitrary implementation (like a mock based on its interface)
var mockRepos = new Moq.Mock<GymSessionRepository>();

// Override its virtual method; take control for your test
mockRepos.Setup(g => g.GymSessions()).Returns(gymSessions.AsQueryable());

Depending on the mocking framework, the second technique is known as using a transparent or partial mock. If you find yourself using it often, it may be a sign that your code is overly-coupled (and it can get confusing fast).


text:
Q: Expand FAQ answers when hovering their titles, with CSS I have a FAQ and want to make the answer for each question appear only when the question is hovered. I want to do this using HTML and CSS.
Bellow you can see what I wrote. I chose to wrap each question in a faq class so that I can select only the ps inside each question. When I hover h3 nothing happens.
<!DOCTYPE html>

foo?

bar, bar

bar, bar

bar, bar

baz?

bar, bar

I know hovering the title might not be the best option, because if the user goes and hovers the answer the answer would disappear. I can handle that later. Right now I am only puzzled why this does not work as is.
Thanks!

A: With .faq h3:hover .faq p you are trying to select another .faq element inside the hovered h3, which does not exists.
Instead, try this css selector ~:

.faq p {
    display: none;
}

.faq h3:hover ~ p {
    display: block;
}

foo?

bar, bar

bar, bar

bar, bar

baz?

bar, bar

A: You can use the ~ selector:

Selects every
 element that are preceded by a h3:hover element ~edited from here

.faq h3:hover ~ p {
  display: block;
}
.faq p {
  display: none;
}
.faq h3:hover .faq p {
  display: block;
}

foo?

bar, bar

bar, bar

bar, bar

baz?

bar, bar


text:
Q: Is it possible to sort the features by an attribute programmatically? I have written a PyQGIS script that loops through an attribute table and finds duplicated values in a target attribute field.
My technique requires that the attribute table is first sorted by the target field.
Is that possible with PyQGIS? I've only been able to have the table sorted by the row number.

A: Using a similar approach to the solution presented by xunilk:
Assuming you have vector layer as the active layer in QGIS with a name column which you want to sort on, you should be able to run the following in the QGIS Python Console:
# Get a reference to the active layer (the layer
# selected in the Layers Panel)
layer = iface.activeLayer()

# Define a custom `key` function for use with `sorted`
# which is passed a feature `f` and returns the value
# of it's `name` attribute
def get_name(f):
    return f['name']

# Create a sorted list of features. The `sorted` function
# will read all features into a list and return a new list
# sorted in this case by the features name value returned
# by the `get_name` function
features = sorted(layer.getFeatures(), key=get_name)

# Loop through the sorted list and print out the name value
# of each just to prove it's now sorted.
for feature in features:
    print feature['name']

References:

*

*sorting using a key function

*pyqgis - accessing attributes

A: This code will sort getFeatures() results by field in descending order. Tested with QGIS 3.6.1:
request = qgis.core.QgsFeatureRequest()

# set order by field
clause = qgis.core.QgsFeatureRequest.OrderByClause('field_name', ascending=False)
orderby = qgis.core.QgsFeatureRequest.OrderBy([clause])
request.setOrderBy(orderby)

layer = qgis.core.QgsVectorLayer('layer_path', 'layer_name', "provider") # add some layer
features = layer.getFeatures(request)

for feature in features:
    attrs = feature.attributes()
    print(attrs)

A: Assuming that I have understood your question correctly… I will provide a purely Python-based solution. There might be a more elegant way to do this, using the QGIS API directly, but I am not aware of it at this point.
Let's say I have a country shapefile, where the first column contains names. Now, the countries are not alphabetically ordered, but I would like to still print them in alphabetical order (that is how I understand the question):
lyr = iface.activeLayer()

features = lyr.getFeatures()

featList = []

for feat in features:
    featList.append(feat.attributes())

featList.sort()

for f in featList:
    print f

My solution requires looping through the features once to push them into a list, and then, in a second step, you would order that list alphabetically, using .sort().
Of course, to make this work, your field that is used to sort needs to be the first field in your table. If that is not the case you can easily achieve that manually by using the Table Manager plugin.
The previous example would then return a table like this:

in alphabetical order:

[...]
So, basically, instead of working with the features themselves you would be working with a list of the features.

A: I used world_borders.shp to test this.
To get features and print a slice of first 6 elements. The shapefile has 3784 records in the attributes table (many of them duplicates).
wb=iface.activeLayer()
iter = wb.getFeatures()
attr=[]
for feature in iter:
    attr.append(feature.attributes())
print len(attr)
3784
print attr[0:5]
[[1.0, u'AA', u'Aruba', 193.0, 71218.0],
[2.0, u'AC', u'Antigua and Barbuda', 443.0, 68320.0],
[2.0, u'AC', u'Antigua and Barbuda', 443.0, 68320.0],
[4.0, u'AG', u'Algeria', 2381740.0, 32129324.0],
[5.0, u'AJ', u'Azerbaijan', 86600.0, 7868385.0]]

To eliminate duplicate records. The attributes list has now 251 records. However, country names (index 2) are not sorted (printed 11 first elements).
attr2=[]
for attribute in attr:
    if attribute not in attr2:
    attr2.append(attribute)
print len(attr2)
251
print attr2[0:10]
[[1.0, u'AA', u'Aruba', 193.0, 71218.0],
[2.0, u'AC', u'Antigua and Barbuda', 443.0, 68320.0],
[4.0, u'AG', u'Algeria', 2381740.0, 32129324.0],
[5.0, u'AJ', u'Azerbaijan', 86600.0, 7868385.0],
[6.0, u'AL', u'Albania', 28748.0, 3544808.0],
[7.0, u'AM', u'Armenia', 29800.0, 2991360.0],
[9.0, u'AO', u'Angola', 1246700.0, 10978552.0],
[10.0, u'AQ', u'American Samoa', 199.0, 57902.0],
[11.0, u'AR', u'Argentina', 2766890.0, 39144753.0],
[12.0, u'AS', u'Australia', 7686850.0, 19913144.0]]

To sort by field (index 2) is necessary to use one anonymous function with lambda in 'sort'. Now, country names are sorted.
attr2.sort(key=lambda x: x[2])
print attr2[0:10]
[[3.0, u'AF', u'Afghanistan', 647500.0, 28513677.0],
[6.0, u'AL', u'Albania', 28748.0, 3544808.0],
[4.0, u'AG', u'Algeria', 2381740.0, 32129324.0],
[10.0, u'AQ', u'American Samoa', 199.0, 57902.0],
[8.0, u'AN', u'Andorra', 468.0, 69865.0],
[9.0, u'AO', u'Angola', 1246700.0, 10978552.0],
[14.0, u'AV', u'Anguilla', 102.0, 13008.0],
[15.0, u'AY', u'Antarctica', 1.0, 1.0],
[2.0, u'AC', u'Antigua and Barbuda', 443.0, 68320.0],
[11.0, u'AR', u'Argentina', 2766890.0, 39144753.0]]

If you want to sort, for example, by 'AREA' (index 3):
attr_id = wb.pendingAllAttributesList()
for i in attr_id: #print index and field names
    print i,wb.attributeDisplayName(i)
0 CAT
1 FIPS_CNTRY
2 CNTRY_NAME
3 AREA
4 POP_CNTRY
attr2.sort(key=lambda x: x[3])


text:
Q: Command Line args in C program using Netbeans I am new to usintg Netbeans in Linux. So, I am facing problem how to specify command line args for example A.txt and B.txt for my program in C using Netbeans. Its pretty simple to pass them as args using command line , but now for debugging purpose i need to use Netbeans 7.1 On Ubuntu version 11.
Any help would be highly appreciated.
Thanks.

A: Specifying command line arguments seems to have changed since netbeans 6.9 (I just checked).  To do this in 7.1, you have to go into Project Properties > Run > Run Command to set the arguments.
For example, to set the arguments -foo -bar, the Run Command setting would read:
"${OUTPUT_PATH}" -foo -bar


text:
Q: Finding Inverse Laplace Transform $\exp\left(-\sqrt{\frac{s}{a}}\right)$ Can somebody help me to find the inverse Laplace transform of
$$F(s)\exp\left(-\sqrt{\frac{s}{a}}\right)$$
or at least
$$\exp\left(-\sqrt{\frac{s}{a}}\right)?$$
I'll be so grateful.

A: According to the definition of Error function, we can find the following strong identity: $$\mathcal{L}\left(\frac{k}{2\sqrt{\pi~t^3}}e^{-k^2/4t}\right)=e^{-k\sqrt{s}},~~k>0$$ It seems that here, we have $$k=\frac{1}{\sqrt{a}}$$

A: Let's work with the exponential only first; I will assume that $a>0$ for simplicity.  You can use a contour integration without that substitution as follows by deforming the Bromwich contour about the negative real axis and exploiting a branch cut of $\sqrt{z/a}$ about that axis.  So, consider the integral
$$\oint_C dz \: e^{-\sqrt{z/a}} e^{z t}$$
where $C$ is a keyhole contour about the negative real axis, as pictured below.

We will define $\text{Arg}{z} \in (-\pi,\pi]$, so the branch is the negative real axis.  There are $6$ pieces to this contour, $C_k$, $k \in \{1,2,3,4,5,6\}$, as follows.
$C_1$ is the contour along the line $z \in [c-i R,c+i R]$ for some large value of $R$.
$C_2$ is the contour along a circular arc of radius $R$ from the top of $C_1$ to just above the negative real axis.
$C_3$ is the contour along a line just above the negative real axis between $[-R, -\epsilon]$ for some small $\epsilon$.
$C_4$ is the contour along a circular arc of radius $\epsilon$ about the origin.
$C_5$ is the contour along a line just below the negative real axis between $[-\epsilon,-R]$.
$C_6$ is the contour along the circular arc of radius $R$ from just below the negative real axis to the bottom of $C_1$.
We will show that the integral along $C_2$,$C_4$, and $C_6$ vanish in the limits of $R \rightarrow \infty$ and $\epsilon \rightarrow 0$.
On $C_2$, the real part of the argument of the exponential is
$$R t \cos{\theta} - \sqrt{R/a} \cos{\frac{\theta}{2}}$$
where $\theta \in [\pi/2,\pi)$.  Clearly, $\cos{\theta} < 0$ and $\cos{\frac{\theta}{2}} > 0$, so that the integrand exponentially decays as $R \rightarrow \infty$ and therefore the integral vanishes along $C_2$.
On $C_6$, we have the same thing, but now $\theta \in (-\pi,-\pi/2]$.  This means that, due to the evenness of cosine, the integrand exponentially decays again as $R \rightarrow \infty$ and therefore the integral also vanishes along $C_6$.
On $C_4$, the integral vanishes as $\epsilon$ in the limit $\epsilon \rightarrow 0$.  Thus, we are left with the following by Cauchy's integral theorem (i.e., no poles inside $C$):
$$\left [ \int_{C_1} + \int_{C_3} + \int_{C_5}\right] dz \: e^{-\sqrt{z/a}} e^{z t} = 0$$
On $C_3$, we parametrize by $z=e^{i \pi} x$ and the integral along $C_3$ becomes
$$\int_{C_3} dz \: e^{-\sqrt{z/a}} e^{z t} = e^{i \pi} \int_{\infty}^0 dx \: e^{-i \sqrt{x/a}} e^{-x t}$$
On $C_5$, however, we parametrize by $z=e^{-i \pi} x$ and the integral along $C_5$ becomes
$$\int_{C_5} dz \: e^{-\sqrt{z/a}} e^{z t} = e^{-i \pi} \int_0^{\infty} dx \: e^{i \sqrt{x/a}} e^{-x t}$$
We may now write
$$-\frac{1}{i 2 \pi} \int_0^{\infty} dx \: e^{- x t} \left ( e^{i \sqrt{x/a}} - e^{-i \sqrt{x/a}} \right ) + \frac{1}{i 2 \pi} \int_{c-i \infty}^{c+i \infty} ds \: e^{-\sqrt{s/a}} e^{s t} = 0$$
Therefore, the ILT of $\hat{f}(s) = e^{-\sqrt{s/a}}$ is given by
$$\begin{align}\frac{1}{i 2 \pi} \int_{c-i \infty}^{c+i \infty} ds \: e^{-\sqrt{s/a}} e^{s t} &= \frac{1}{i 2 \pi} \int_0^{\infty} dx \: e^{- x t} \left ( e^{i \sqrt{x/a}} - e^{-i \sqrt{x/a}} \right )\\ &= \frac{a}{\pi} \int_{-\infty}^{\infty} du\: u \,e^{-a t u^2} \sin{u}\end{align}$$
The last step involved substituting $x=a u^2$ and exploiting the evenness of the integrand.  This integral may be evaluated as follows:
$$\begin{align}\frac{a}{\pi} \int_{-\infty}^{\infty} du\: u \,e^{-a t u^2} \sin{u} &= \frac{a}{\pi} \Im{\left [\int_{-\infty}^{\infty} du\:u\, e^{-a t u^2} e^{i u} \right]}\\ &= \frac{a}{\pi} \Im{\left [\int_{-\infty}^{\infty} du\:u\, e^{-a t (u-i/(2 a t))^2} e^{-1/(4 a t)}\right ]}\\ &= \frac{a}{\pi} e^{-1/(4 a t)} \Im{\left [\int_{-\infty}^{\infty} dv \: \left ( v + \frac{i}{2 a t} \right ) e^{-a t v^2} \right]}\\ &= \frac{a}{\pi} e^{-1/(4 a t)}  \frac{1}{2 a t} \sqrt{\frac{\pi}{ at}} \end{align}$$
Therefore the result is that
$$\mathcal{L}^{-1}[e^{-\sqrt{z/a}}](t) = \frac{1}{i 2 \pi} \int_{c-i \infty}^{c+i \infty} dz \: e^{-\sqrt{z/a}} e^{z t} = \frac{1}{2 \sqrt{\pi a}} t^{-3/2} e^{-\frac{1}{4 a t}}$$
Now, to get the ILT of $F(s) e^{-\sqrt{z/a}}$, you may use the convolution theorem for Laplace transforms:
$$\mathcal{L}^{-1}[F(s) e^{-\sqrt{z/a}}](t) = \frac{1}{2 \sqrt{\pi a}} \int_0^t dt' \, f(t') \, (t-t')^{-3/2}\, e^{-\frac{1}{4 a (t-t')}}$$
where $f$ is the ILT of $F$.

A: Here is what Wolfram Alpha gives (I couldn't think of a way to do this by hand since inverse Laplace transforms are highly nontrivial). You could then use the convolution theorem for the Laplace transform to write the general expression.

A: If you dont mind some of my dirty tricks, I will show you how I would do it... I will denote $\mathscr{L}$ as the Laplace transform from $t\rightarrow s$ and $\mathcal{L}$ will be the Laplace transform from $x$ to $y$.
First, notice, that
$$\mathscr{L}^{-1}(s^{-\lambda})=\frac{t^{\lambda-1}}{\Gamma(\lambda)}\tag{1}$$
for any $\lambda>0$. That means, if we are able to expand a function $F(s)$ in terms of $\frac{1}{s}$ when $s\rightarrow\infty$, we can use this formula to find the Taylor series of $f(x)=\mathscr{L}^{-1}\{F(s)\}$, if it exists.
Also notice that for the transformation $x\rightarrow y$, for any positive $b$:
$$\mathcal{L}\{e^{-b x}\} = \frac{1}{y+b}\tag{2}$$
The ultimate trick is to write $b=\sqrt{s}$ in $(2)$ to get after inversion
$$\exp\left(-\sqrt\frac{s}{a}\right) = \mathcal{L}^{-1}\left\{\frac{1}{y+\sqrt{s}}\right\}\bigg{|}_{x=1/\sqrt{a}}$$
Therefore, due to linearity (and ultimate trickery)
$$\mathscr{L}^{-1}\left\{\exp\left(-\sqrt\frac{s}{a}\right)\right\}= \mathcal{L}^{-1}\left\{\mathscr{L}^{-1}\left\{\frac{1}{y+\sqrt{s}}\right\}\right\}\bigg{|}_{x=1/\sqrt{a}}\tag{3}$$
To find the inner laplace transform, we first find its taylor series at infinity, since
$$\frac{1}{y+\sqrt{s}}=\frac{1}{\sqrt{s}}\frac{1}{1+\frac{y}{\sqrt{s}}}=\frac{1}{\sqrt{s}}\sum_{n=0}^\infty (-1)^n y^n s^{-n/2}$$
Using $(1)$, we then have
$$\mathscr{L}^{-1}\left\{\frac{1}{y+\sqrt{s}}\right\}=\sum_{n=0}^\infty \frac{1}{\sqrt{t}}\frac{(-1)^n \left(y\sqrt{t}\right)^n}{\Gamma\left(\frac{n+1}{2}\right)}$$
EDIT: From now on I will proceed with a newer approach, much shorter and less rigorous, older one is found in the section "Older approach" down below.
Using Legendre duplication formula for gamma function
$$\Gamma\left(n+\frac12\right)=\frac{\sqrt{\pi}}{4^n}\frac{\Gamma(2n+1)}{\Gamma(n+1)},$$
we get, replacing $n\rightarrow n/2$:
$$\mathscr{L}^{-1}\left\{\frac{1}{y+\sqrt{s}}\right\}=\frac{1}{\sqrt{\pi t}}\sum_{n=0}^\infty\frac{\left(-2y\sqrt{t}\right)^n}{n!}\Gamma\left(\frac{n}{2}+1\right)$$
and since
$$\Gamma\left(\frac{n}{2}+1\right) = \int_0^\infty u^{\frac{n}{2}}e^{-u}\mathrm{d}u = 2\int_0^\infty p^{n+1}e^{-p^2}\mathrm{d}p$$
(where we used substitution $u=p^2$), we get finally
$$\mathscr{L}^{-1}\left\{\frac{2}{y\!+\!\sqrt{s}}\right\}\!=\!\frac{2}{\sqrt{\pi t}}\int_0^\infty p  e^{-p^2} e^{-2yp\sqrt{t}} \mathrm{d}p\!=\!\frac{1}{2t\sqrt{\pi t}}\!\int_0^\infty q  e^{-\frac{q^2}{4t}} e^{-yq} \mathrm{d}q = \frac{1}{2t\sqrt{\pi t}} \mathcal{L} \left\{x e^{-\frac{x^2}{4t}} \right\} $$
where we have used the substitution $p=\frac{q}{2\sqrt{t}}$. Combining this result with $(3)$ we get
$$\mathscr{L}^{-1}\left\{\exp\left(-\sqrt\frac{s}{a}\right)\right\} = \frac{x}{2 t\sqrt{\pi t}}\exp\left(-\frac{x^2}{4t}\right)\bigg{|}_{x=1/\sqrt{a}}.$$

OLDER APPROACH:
Let us define a function $g(z)$ as
$$g(z) = \sum_{n=1}^\infty \frac{(-1)^{n-1} z^{n-1}}{\Gamma\left(\frac{n+1}{2}\right)}\tag{4}$$
Clearly
$$g(0) = \frac{1}{\Gamma(1)}=1\tag{5}$$
Clearly, also, $g(z)$ is convergent for all $z$ positive thanks to the Gamma function in the denominator. We have
$$\mathscr{L}^{-1}\left\{\frac{1}{y+\sqrt{s}}\right\}= \frac{1}{\sqrt{\pi t}}-yg(y\sqrt{t})\tag{6}$$
Moreover from $(4)$ and by using $\Gamma\left(\frac{n+1}{2}\right)=\Gamma\left(\frac{n-1}{2}\right)\frac{n-1}{2}$:
$$g'(z) = 2z\sum_{n=0}^\infty \frac{(-1)^{n-1} z^{n-1}}{\Gamma\left(\frac{n+1}{2}\right)} = 2 z g(z) - \frac{2}{\sqrt{\pi}} \tag{7}$$
This is an ordinary differential equation with boundary condition $(5)$. Multiplication with integrating factor $e^{-z^2}$ gives
$$\left(g(z)e^{-z^2}\right)' = -\frac{2}{\sqrt{\pi}} e^{-z^2}$$
the solution for $g(z)$ is then simply, in accordance with $(5)$
$$g(z) = \frac{2}{\sqrt{\pi}}e^{z^2}\int_{z}^\infty e^{-w^2} \, \mathrm{d}w = e^{z^2}\operatorname{erfc}(z)$$
Using the L'Hospital's rule, we get
$$g(\infty) = \lim_{z\rightarrow\infty} \frac{2}{\sqrt\pi}\frac{e^{-z^2}}{2z e^{-z^2}}=0\tag{8}$$
Similarly we would get $$\lim_{z\rightarrow\infty} zg(z) = \frac{1}{\sqrt\pi}\tag{9}$$ etc.
In order to invert the Laplace transform, we need to first find the Taylor expansion of $g(z)$ in infinity. Let us denote $r = \frac{1}{z}$, then via chain-rule
$$\frac{\mathrm{d}g}{\mathrm{d}r}= \frac{\mathrm{d}g}{\mathrm{d}z} \frac{\mathrm{d}z}{\mathrm{d}r} = -\frac{1}{r^2}\frac{\mathrm{d}g}{\mathrm{d}z}$$
so $(7)$ becomes ($\dot{g}$ denotes a derivative with respect to $r$):
$$-r^2 \dot{g}=\frac{2}{r}g + \frac{2}{\sqrt{\pi}}$$
Let us write (summation from $n=1$ since $(8)$)
$$g(r)= \frac{1}{\sqrt{\pi}}\sum_{n=1}^\infty a_n r^n$$
substititiong into the previous equation, we get relations for $a_n$ coefficients:
$$\begin{align}
a_1&=1\\
a_2&=0\\
a_{n+1}&=-\frac{n}{2} a_{n-1} ,\qquad\qquad n\geq 2
\end{align}$$
(note that $a_1 = 1$ is equivalent to $(9)$). Using these conditions, we get, finally
$$g(r) = \frac{r}{\sqrt\pi}\sum_{n=0}^{\infty} \frac{(-1)^n (2n-1)!!}{2^n} r^{2n}=\frac{1}{z\sqrt\pi}\sum_{n=0}^{\infty} \frac{(-1)^n (2n-1)!!}{2^n z^{2n}} \tag{10}$$
(which is divergent, but who cares).
Finally, combining $(10)$ with $(6)$ and $(3)$:
$$\mathscr{L}^{-1}\left\{\exp\left(-\sqrt\frac{s}{a}\right)\right\}= \mathcal{L}^{-1}\left\{\frac{1}{\sqrt{\pi t}}\sum_{n=1}^{\infty} \frac{(-1)^{n-1} (2n-1)!!}{2^n y^{2n} t^{n+\frac12}}\right\}\bigg{|}_{x=1/\sqrt{a}}$$
this further simplifies using $(1)$:
$$\mathscr{L}^{-1}\left\{\exp\left(-\sqrt\frac{s}{a}\right)\right\}= \frac{1}{\sqrt{\pi t}}\sum_{n=1}^{\infty} \frac{(-1)^{n-1} x^{2n-1}(2n-1)!! }{2^n t^{n} (2n-1)!}\bigg{|}_{x=1/\sqrt{a}}$$
and since $(2n-1)!!/(2n-1)! = 2^{1-n}/(n-1)!$, we get
$$\mathscr{L}^{-1}\left\{\exp\left(-\sqrt\frac{s}{a}\right)\right\}= \frac{x}{2 t\sqrt{\pi t}}\sum_{n=0}^{\infty} \frac{(-1)^n x^{2n}}{4^n n! t^n }\bigg{|}_{x=1/\sqrt{a}} = \frac{x}{2 t\sqrt{\pi t}}\exp\left(-\frac{x^2}{4t}\right)\bigg{|}_{x=1/\sqrt{a}}$$
Q.E.D?


text:
Q: Interpreting User Request with Actions On Google Unless I've done something majorly stupid, it appears I only have one entry point into my Action on Google using Actions SDK and Node.js.
Consequently, I have to work out what the user has said by using some keywords with .indexOf() and then calling the appropriate function.
I thought that would also be simpler and there would be a way I could define an action with several phrases and Google would be intelligent enough to work it all out, even if the user said something slightly differently.
I guess one of the things Im doing wrong/different, is just by having a welcome intent that essentially has a conversation and asks "What would you like to do?" then the user responds, then I have to work out what was said, and follow up an appropriate action.
That seems quite long winded. Any better ways?

A: The "better way" is to use a tool that is designed for that and has a powerful and flexible Natural Language Processing engine associated with it. Actions directly support both Dialogflow and Converse.AI, and most other NLP engines should be able to provide information about how they work with Actions.
Dialogflow, for example, lets you specify some sample phrases that will meet an Intent, and then supplements that with "similar" phrases to the ones you've specified. Your Node.js webhook gets told which Intent was called, with what parameters you've specified for that Intent, and you can take action based on that information directly.
At this point, the Actions SDK is mostly intended to be used as the base that these and other NLP engines build on top of.


text:
Q: div alignment based on the content I want to design the layout like  below screenshot.

I tried to do this by using following code.

             Quarter To Date

          830

            OFF TIER2

             Rolling 3 Month

          835

            National 852

css :
.salesDiv {
  width: 313px;
margin-left: 10px;
border: solid 1px gray;
border-radius: 4px;
height: 20px;
display: inline-block;
}

.salesDiv > div {
    float:left;
    margin-left:20px;
}
.offtier {
border-left-style: dotted;
background-color: green;
height: 20px;
width: 88px;

}

but it didn't give the same layout as like above screenshot. I want to do like above screenshot. What's going wrong? Please anyone look into this.
http://jsfiddle.net/zHLMS/
spacing also not good. I need equal spacing for all the content inside the border.
I need to maintain the same width for both the element.
Thanks,
Siva

A: You need to apply
display: inline-block;
float:right;

to the sales > divs and float: right to the offtier divs
Here's the modified code

A: Try this....Updated Link
 .salesDiv {
  width: 313px;
margin-left: 10px;
border: solid 1px gray;
-webkit-border-radius:5px;
border-radius:5px;
height: 20px;
display: inline-block;
position:relative;
}

.salesDiv > div {
    float:left;
    margin-left:20px;
}
.offtier {
 -webkit-border-radius: 0 5px 5px 0;
border-radius: 0 5px 5px 0;
background-color: green;
height: 20px;
width: 88px;
right:0;
position:absolute;
}

Good Luck..Enjoy


text:
Q: create Replicaset with separate pods in Kubernetes I want to create a ReplicaSet with separate pods.
Pods
apiVersion: v1
kind: Pod
metadata:
  name: user-pod
  labels:
    app: user-pod
spec:
  containers:
    - name: user-container
      image: kia9372/store-user

Replicaset
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: user-replicaset
  labels:
    app: user-replicaset
spec:
  replicas: 3
  selector:
    matchLabels:
      app: user-pod

but when i execute the following command, it throws the foloowing error:
kubectl create -f user-replicaset.yml

>error: error validating "user-replicaset.yml":
error validating data: ValidationError(ReplicaSet.spec.selector):
unknown field "app" in io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector;
if you choose to ignore these errors, turn validation off with --validate=false

What's the problem? how can I solve this?

A: matchlabels is missing. Also your pod definition does not define a matching  label.
Have a look at the docs for a proper setup:
https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/

A: Did you try adding that label also in Replicaset :
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  labels:
    app: user-replicaset
    app: user-pod

This example uses that label in both labels

A: you can't create replicaset without spec.template.spec.containers field. as this one is by default required to create replica-set in k8s. so you must need to add template field . and you can actually do what you want , just use your pod as here in template spec. template is the actual pod spec with which you are going to create your replica-set's pods.
this one is going to do the exact thing you are asking for:

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: user-replicaset
  labels:
    app: user-replicaset
spec:
  replicas: 3
  selector:
    matchLabels:
      app: user-pod
  template:
    metadata:
      labels:
        app: user-pod
    spec:
      containers:
      - name: user-container
        image: kia9372/store-user


text:
Q: Converting from batch to shell I have a set of batch commands that I'm trying to convert to shell so I can use them on my linux environment. The command should read
rcontrib -y  < view\inside_NE.rays -o result/%%04d_inside

In windows (using batch), running this command should produce a set of files that are numbered like this:
0001_inside.hdr 0002_inside.hdr  etc.
However, when I ran this command in bash, I expected to get eight files with names that start with 0001 to 0008 but I got only one file which was named 0001_inside. How would I do this in bash?
Please note: rcontrib is a command that is part of a package that runs on both linux and windows
If you like this question please vote up.

A: I think %%04d is to escape '%' in DOS, your rcontrib program probably wants %04d like in c syntax to name the file with a 4 digit integer.  In bash you don't need to escape it, have you try this?
rcontrib -y  < view/inside_NE.rays -o result/%04d_inside


text:
Q: When installing Spotify I get an error This is the error I get installing spotify:
 Errors were encountered while processing:
   /var/cache/apt/archives/spotify-client_1%3a1.0.28.89.gf959d4ce-37_amd64.deb
 E: Sub-process /usr/bin/dpkg returned an error code (1)

A: When installing packages that are external to aptitude (i.e. using sudo dpkg -i packagename.deb), dependency errors often occur.
In most cases, this can be fixed by running the following command immediately after the dpkg installation has failed:
sudo apt-get -f install

This command essentially tries to resolve any outstanding dependency issues.
It could also simply be that the package You are trying to install ins incompatible with Your Ubuntu version.


text:
Q: Changing drives in near future, for an ssd in a server How is it possible to transfer all files including all server files without having to reinstall Cloudron and setup Cloudron all over again. Is there an special terminal command like if i connect external drive it would transfer all files to external drive and makes correct partition and such

A: Boot with an install drive then in then Terminal use.
sudo dd if=/dev/sd? of=/dev/sd*

Replacing the ? with the drive letter of the already installed disk, the * with the new SSD. This will exactly copy everything including the partition table to the new drive. The new drive needing to be at least the same size as the drive it replaces or it will fail. If larger size you would need to resize the partition(s) to regain the lost space.
Alternatively you can partition the new drive then use the rsync program to copy just the information on the drive not all the blank space like the dd method does. Once you have it partitioned like it needs to be.
sudo mkdir /tmp/old
sudo mkdir /tmp/new
sudo mount /dev/sd?1 /tmp/old
sudo mount /dev/sd*1 /tmp/new
sudo rsync -avP /tmp/old/* /tmp/new/

That for a one partition setup with the first (1) partition containing the / partition. You would replace the ? with the drive letter of the old install, the * with the new drive letter. Once done you would need to remove the old drive install the new and boot with the install usb drive to run the boot-repair to re-install GRUB.
https://help.ubuntu.com/community/Boot-Repair


text:
Q: Failed to make bulk upsert using mongo I'm trying to do upsert using mongodb driver, here is a code:
BulkWriteOperation builder = coll.initializeUnorderedBulkOperation();
DBObject toDBObject;
for (T entity : entities) {
    toDBObject = morphia.toDBObject(entity);
    builder.find(toDBObject).upsert().replaceOne(toDBObject);
}
BulkWriteResult result = builder.execute();

where "entity" is morphia object. When I'm running the code first time (there are no entities in the DB, so all of the queries should be insert) it works fine and I see the entities in the database with generated _id field. Second run I'm changing some fields and trying to save changed entities and then I receive the folowing error from mongo:
E11000 duplicate key error collection: statistics.counters index: _id_ dup key: { : ObjectId('56adfbf43d801b870e63be29') }

what I forgot to configure in my example?

A: I don't know the structure of dbObject, but that bulk Upsert needs a valid query in order to work.
Let's say, for example, that you have a unique (_id) property called "id". A valid query would look like:
builder.find({id: toDBObject.id}).upsert().replaceOne(toDBObject);

This way, the engine can (a) find an object to update and then (b) update it (or, insert if the object wasn't found).  Of course, you need the Java syntax for find, but same rule applies: make sure your .find will find something, then do an update.
I believe (just a guess) that the way it's written now will find "all" docs and try to update the first one ... but the behavior you are describing suggests it's finding "no doc" and attempting an insert.


text:
Q: How to switch to Live Mode DHL plugin? I'm having an issue trying to use DHL plugin in Magento 1.9.
I have introduced all the fields with the DHL information but when I'm trying to buy an item it says:

"This shipping method is currently unavailable. If you would like to
  ship using this shipping method, please contact us."

I've found that I need to switch from Test mode to Live mode but I can't find where I can do that (I'm using production URLs given by DHL).
Regards.

A: According to the code, it seems to be using test mode if nothing is specified in Gateway URL field at the admin panel.

// app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl.php:534

     $url = $this->getConfigData('gateway_url');
                    if (!$url) {
                        $url = $this->_defaultGatewayUrl;
                    }

You can see references to this in:
// app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl.php:96::

protected $_defaultGatewayUrl = 'https://eCommerce.airborne.com/ApiLandingTest.asp';

and in:
// app/code/core/Mage/Usa/etc/config.xml:224