text:
Q: Using typedef array to declare an array Okay i'm currently studying 2D arrays and I'm confused as to what the dimensions are of a 2D array if the situation is this:
#define ROW 5
#define COL 10

typedef int arrint[COL]

and it's declared in the main function as this:
arrint a2D[ROW]

Is the 2D array a2D[5][10] or a2D[10][5]?

A: Since you have declared arrint to be an int[COL==10], and a2D is an array of 5 of those, so you have ended up with the equivalent of:
int a2D[5][10];

Typedef is fine to use, but better to typedef a 2D array as a 2D array to avoid confusion. In C, two-D arrays are stored in memory as row-major. Read this post for a good explanation. Arrays are arranged in memory such that the first row appears first, followed by the second and so on. Each row consists of COL elements, so the way to define this would be:
typedef int A2D[ROW][COL];
A2D     a2d  = {0}; // Declares 2D array a2d and inits all elements to zero

Then to access the element at row i, column j, use:
a2d[i][j]

Here is a sample program:
#include <stdio.h>
#define ROW 5
#define COL 10
typedef int A2D[ROW][COL];

int main(int argc, char** argv)
{
  A2D a2d = {0};
  int r,c;

  a2d[1][2] = 12;

  for(r=0; r<ROW; r++)
  {
    printf("Row %d: ", r);
    for(c=0; c<COL; c++)
       printf("%2d ", a2d[r][c]);
    printf("\n");
  }
}

This produces the following output:
Row 0:  0  0  0  0  0  0  0  0  0  0
Row 1:  0  0 12  0  0  0  0  0  0  0
Row 2:  0  0  0  0  0  0  0  0  0  0
Row 3:  0  0  0  0  0  0  0  0  0  0
Row 4:  0  0  0  0  0  0  0  0  0  0


text:
Q: For loop only way to copy array content to another array? I have some code that has heavy use of arrays. It all works but there are many for loops where I iterate and copy contents from several arrays to a new array with more dimensions to fit all content.
As I understand it, there is no way to do this without a for loop (to copy array content to another array). Is this correct?

A: There is the method Array.Copy(arSource,arTarget,length). But it does not work with more dimensions arrays. The new one is that jagged arrays()arrays of arrays are more perfomant than 2D ARRAYS,if you move along the vectors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: problem with reading UTF-8 characters from TXT file in Angular application I am reading a TXT file in my Angular application. This TXT file contains some characters in UTF-8, such as "Prénom annuaire".
When I read this file and print data in console it displays as "Pr�nom annuaire". I am bit confused of this behavior, Below is my code to read the data:
let reader = new FileReader();
reader.onloadend = function (){}
reader.readAsText(evt.target.files[0], "UTF-8");

Can anyone help, How can I read data in UTF-8.
Edit: 1
When I compare strings in my application, "Pr�nom annuaire" and "Prénom annuaire" shows as two different strings.
Edit: 2
Problem i am facing because of this behavior,
I have a JSON object fetched from server as below:
{"First_Name": "Prénom annuaire",...}

Then, I read the TXT file as mentioned above, and each Text I read from the file I need to fetch the respective Key from the above JSON. So when I read the 'Prénom annuaire' from the TXT file, I should compare in the above JSON for this value and It should return the "First_Name" back to me.
But When I compare 'Prénom annuaire' text read from the file with the JSON, I am unable to get respective KEY i.e. 'First_Name'. So When I debug, the Text which read from TEXT file shows as 'Pr�nom annuaire' and couldn't match to the 'Prénom annuaire'.
So, how could I do this comparison?


text:
Q: Background Position Array when generate pdf using dompdf I try to generate pdf file using library dompdf in php but found the following error.
A PHP Error was encountered

Severity: Warning
Message: explode() expects parameter 2 to be string, array given
Filename: include/style.cls.php
Line Number: 1061

I tried to debug and found this array that cause error
array
  'background_position' =>
    array
      0 => string '0%' (length=2)
      'x' => string '0%' (length=2)
      1 => string '0%' (length=2)
      'y' => string '0%' (length=2)
  'background' => string 'none' (length=4)

My question is how can i fixed this error, where this array come from?
Appreciate for any response.
thanks,
Frans

A: you must set background_position as string with space separator. Look for class code here line 989 - begin of method


text:
Q: I get "ALERT Error in Content Enumeration." whener I try to save in GTA 5? Whenever I try to save whether it is with my phone, autosave or sleeping in a bed it always says:

ALERT Error in Content Enumeration.

What can I do?

A: Rockstar have stated that you should contact support if this error occurs:

Please create a ticket and we will troubleshoot through all these issues with you. We apologize for an inconveniences you have witnessed.

A: From the same article link posted by Rishit Bansal:

My problem was fixed when I changed my power settings on my xbox one, to energy savings. Which turns off the console and the power supply completely. White light is stand by mode, orange light is completely off.
Here is a link to the video on Youtube that helped me out. For me, I have an Xbox One.

Hope this helps. As for PS4 goes, I don't have an answer.

In other words, try cutting power to your Xbox or PS3 completely. Shut it down so it goes into 'standby' mode, and turn it off at the wall. Wait 30 seconds, and turn it back on.


text:
Q: I'm putting in the numbers 1,3,5,7,0 the outcome should be 8 but I only get 7 since it's the fourth element, what do I do wrong? import java.util.ArrayList;
import java.util.Scanner;

public class ToisenJaKolmannenSumma {

    public static void main(String[] args) {
        Scanner lukija = new Scanner(System.in);

        ArrayList<Integer> numbers = new ArrayList<>();
        while (true) {
            int number = Integer.valueOf(lukija.nextLine());

            if (number == 0) {
                break;
            }

            numbers.add(number);
        }

        System.out.println(numbers.get(1+2));
    }
}

A: System.out.println(numbers.get(1+2));
Will evaluate to
System.out.println(numbers.get(3));
and return the fourth element.
To achieve what you want, you will probably want to do something like
System.out.println(numbers.get(1) + numbers.get(2));


text: Q: How to close tab in Incognito mode in javascript how can I close a tab in incognito mode in chrome? I'm using window.close(), which is working in Chrome but not in Incognito mode. I searched a lot and cannot find the proper answer. Any help will be appreciated.


text:
Q: Display results only on search I need the search results div to only show when results of a search have been returned (not when the user is searching a term), and then be able to clear the results divs when a new term is searched.
I should be able to use something like $(".results").empty(), but this will keep the results div always blank.
$("#searchterm").keyup(function(e) {
  var q = $("#searchterm").val();
  //Only begin search with at least 3 characters.
  if (q.length > 3) {
    ajax_search();
  }
  //Send search query
  function ajax_search() {
    $.getJSON("//url-to-search?q=" + q, {},
      //Get results and make 'em look good
      function(data) {
        console.log(data);
        //  $(".results").append("Results for  " + q + "");
        $.each(data.data, function(i, data) {
          if (data.type === "category-1") {
            if ($(".category-1").text() == '') {
              $(".category-1-results-header, .category-1").hide()
            }
            $(".category-1").append("
" + data.title + "
");
          } else if (data.type === "category-2") {
            $(".category-2").append("
" + data.title + "
");
            if ($(".category-2").text() == '') {
              $(".category-2-results-header, .category-2").hide()
            }
          } else if (data.type === "category-3") {
            $(".category-3").append("
" + data.title + "
");
            if ($(".category-3").text() == '') {
              $(".category-3-results-header, .category-3").hide()
            }
          }
        });
      });
  }
});

JSFIDDLE: LINK

A: Try doing something like
if (q.length > 3) {
    ajax_search();
} else {
    $(".results").empty();
}


text:
Q: onCreate(Bundle savedInstanceState) not recovering the saved data - mysql involved Activity 1:SelectBatchStep. RecyclerView populated with MySQL database data
Activity 2: DoneBy. Simple activity inserting new data in the database.
Activity 1 is reloaded after Activity 2 finishes in order to show the updated recyclerView item.
I am trying to save the scrolling position in a recyclerview activity 1. I start a new activity 2 but the scroll position is not recovered when I call back the recyclerview activity 1.
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt(SCROLL,scrollpositionkeeper);
    super.onSaveInstanceState(savedInstanceState);
    Log.v(TAG,"scrollpositionsaved"+savedInstanceState);
}

Logcat shows the bundle Is saved and the scroll position is correctly saved when I start the new activity 2.
Activity 2 is started from the recycler adapter using com.daimajia.swipe.SwipeLayout library.
Activity 1 is recalled from activity 2 as follows:
Intent intent1 = new Intent(DoneBy.this, SelectBatchStep.class);

Activity 1 has the following:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        scrollrecovered = savedInstanceState.getInt(SCROLL);
    }
    else {
        scrollrecovered=0;
    }
    Log.v(TAG,"scrollpositionrecovered"+savedInstanceState);
    setContentView(R.layout.activity_select_batch_step);

Activity 1 comes to the front and logcat shows that the Bundle is null
Why is the saved bundle null?


text:
Q: What do the green underscores in the Script section of my cshtml indicate, and how can I ungreenify them? In Visual Studio (2013, if it's significant) I see this in the "Scripts" section of a .cshtml file:

The green undersscores may actually be being rendered by Resharper (version 2016.1, if it's significant).
I suspect this is some sort of warning, but how can I see what the warning is, and how to resolve whatever is causing the warning? Hovering does nothing; 2-clicking does invoke a "Format Selection" icon (doubtless from Resharper), but selecting it does nothing.

A: This is a ReSharper hint - it's saying that it can make a change here that is likely to improve your code, but isn't necessarily important (if it were more important it would be displayed as a full squiggly underline, green for suggestion, blue for warning, red for error).
You can find out what ReSharper wants to do by hovering over the green dots. If you like the hint, put the text cursor inside the green dots, hit Alt+Enter and select the option that will update the code. If you don't like the hint at all, and never want to see it again, you can also do that from the Alt+Enter menu - select inspection options, and change the severity of the inspection from "Hint" to "Do not show".


text:
Q: MongoDB : update a specific field in all documents of a collection, given a specific array with just targeted field and new values Fairly new to MongoDB, I'm searching for the command to update a collection created like:
db.students.insertMany([
   { "_id": 1, "fld1": "11", "fld2": "12", "fld3": "13" },
   { "_id": 2, "fld1": "21", "fld2": "22", "fld3": "23" },
   { "_id": 3, "fld1": "31", "fld2": "32", "fld3": "33" }
])

updated with :
[
  { "fld1": "11-new" }, { "fld1": "21-new" }, {"fld1": "31-new" }
]

giving the result:
[
   { "_id": 1, "fld1": "11-new", "fld2": "12", "fld3": "13" },
   { "_id": 2, "fld1": "21-new", "fld2": "22", "fld3": "23" },
   { "_id": 3, "fld1": "31-new", "fld2": "32", "fld3": "33" }
]

I cannot seem to find this exact update type in the MongoDB doc.
db.collection.findAndModify ? db.collection.update() db.collection.updateMany() ?
Would this be considered as a bulk operation ?
providing a
[
{updateOne:{"filter":{"_id":1},"update":{$set:{"fld1":"11-new"}}},
{updateOne:{"filter":{"_id":2},"update":{$set:{"fld1":"21-new"}}},
{updateOne:{"filter":{"_id":3},"update":{$set:{"fld1":"31-new"}}}
]

Let me test this. any other simpler mean to achieve this ? Thanks

A: Since you are trying to update several documents with different _id, I suggest you use the bulkWrite() function, which takes as argument a list of operations to be performed on the collection.
In this case all the operations are updateOne queries for which you must specify the filter to identify the relevant document, and the update that must be performed on that document.
You can send this command in the Mongo Shell as follows:
try {
    db.students.bulkWrite([
        {
            updateOne : {
                "filter": {"_id": "1"},
                "update": {"$set":{"fld1":"11-new"}}
            }
         },
         {
            updateOne : {
                "filter": {"_id": "2"},
                "update": {"$set":{"fld1":"21-new"}}
            }
         },
         {
            updateOne : {
                "filter": {"_id": "3"},
                "update": {"$set":{"fld1":"31-new"}}
            }
         }
    ]);
}
catch(e) { print(e); }

If you don't care about the order in which the operations are performed, you may also pass the optional argument ordered to the function and set it to false, which speeds up the execution time.
{ ordered : false }

Script option
This second part of the answer may not be relevant to your case, but if the number of operations to be performed were very high (e.g. you have to change the fields of hundreds of documents, manually writing all the operations would be incredibly expensive. In this case, a script might be for you.
Here is an example in Python that does the following:

*

*connects to the mongo database and extracts the students collection,

*defines a function that takes two arguments: field and new_values, representing the field to be updated and an ordered list of the new values to set for that field.

*the function collects all the _ids currently present in the collection and builds a list of operations by iterating through both the ids and the new values.

*finally the bulkwrite query is sent, returning a result object that summarizes the operations performed.

from pymongo import MongoClient, UpdateOne
client = MongoClient(your_host)
db = client["database_name"]
students = db["students"]

def updateCollection(field, new_values):

    operations = []
    _ids = students.distinct("_id")

    for _id, new_value in zip(_ids, new_values):
        operations.append(UpdateOne({"_id": _id}, {"$set":{field : new_value}}))

    return students.bulk_write(operations, ordered=False)

Following your own example, the function would be called like this:
updateCollection("fld1", ["11-new", "21-new", "31-new"])


text:
Q: Drag and drop a div tag on grids row with jQuery widgets I try to drag a div on a grids system rows, and to find out on witch rows he is positioned after is drop it:
https://jsfiddle.net/johnidevo/08f83op9/5/
________________________________________________
droppable_area_(grids)__________________________
1row____________________________________________
2row____________________________________________
3row___-----------------------------------------
4row___| draggable
                       |
5row___|                                       |
6row___-----------------------------------------
7row____________________________________________
(
's)_______________________________________

My code is as follow:
jQuery( object ).draggable({
    snap: ".selectable",
    containment: "#droppable_area",
    axis: "y",
    drag: function( event, ui ){
        console.log( jQuery( this ).parent() );
    }
});

jQuery('.selectable').droppable({
    drop: function( event, ui ) {
        console.log( jQuery( this ) );
    }
});

With console.log( jQuery( this ) ); when draggable
 is only one row height size it's work fine, after if is bigger than 1 row size it's fails why?

A: What's happening is not an error IMO. I changed the size of the 'draggable' element to match the height of the 'droppable' elements, and then correct event.target.id is selected. I think the problem is when the 'draggable' height is larger than the 'droppabe' height. The draggable is covering more than one droppable element, and at this point, there are multiple event.target.id's being covered. If I were you, I would rethink how I'm approaching the task. Also, maybe there is jquery plugin you can try that has already solved this.
To show this, I added a ".moveable" class to the draggable element, and gave it a a height of 20px, and I gave the same height to the ".selectable" elements. As expected, the correct ID is displayed.
I have an unreliable solution that may help you figure something out - use the droppable tolerance : "pointer" option, demonstrated with a draggable height of 40px and droppable height of 20px. This isn't reliable though, as you would always need to grab the draggable at the very bottom or very top of the element - but this might help you find a way or rethink your approach. Good luck!

$(document).ready(function() {
 $(".moveable").draggable({
  snap: ".selectable",
  containment: "#day_kalendar",
  axis: "y",
  drag: function( event, ui ){
    //console.log( event.target.id );
  }
 });

 $(".selectable").droppable({
  drop: function( event, ui ) {

    $("#response").text(event.target.id);
    console.log(this.id);

          //var hfrom=$( this ).attr("data-hour");
    //var hto=$( this ).attr("data-nexthour");
    //$("#1463419359713").children("#eventHours").text( hfrom+" - "+hto );
  },
  over: function( event, ui) {
   //console.log(event, ui);
  },
  tolerance: "pointer"
 });
});
.ui-selectable .ui-selected {
  background-color: #a6c9e2;
}

.ui-selectable .ui-selecting {
  background: #FECA40;
}

.ui-selectable-helper {
  position: absolute;
  z-index: 100;
  border: none;
}

.ui-dialog-titlebar {
  background: transparent;
  border: none;
}

[class*="col-"] {
  float: left;
  padding: 0px;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

.row::after {
  content: "";
  clear: both;
  display: block;
}

.text-right {
  text-align: right;
}

.cornsilk {
  background-color: #E0E0E0;
}

.forestgreen {
  background-color: forestgreen;
}

.limegreen {
  background-color: limegreen;
}

.dimgrey {
  background-color: dimgrey;
  color: white;
}

.border-up {
  border-top: 1px solid white;
}

.border-up-dashed {
  border-top: 1px dashed white;
}

.fix-border {
  border-top: 1px solid dimgrey;
}
.newevent {
  position: absolute;
  top: 0;
  left: 0;
  margin: 0px;
  width: 100%;
  height: auto;
  z-index: 1;
  /*opacity: 0.7;*/
  border-radius: 4px;
}

#console {
  margin-top: 10px;
  font-size: 9px;
  background-color: white;
  padding: 10px;
}

.selectable {
 position: relative;
 margin:0;
 padding:0;
 height: 20px;
}
.moveable {
 padding:0;
 margin:0;
 height: 40px;
}
#response {
 height: 20px;
}

10AM

11AM

12PM

  12 pm - 2 pm
        (No title)

1PM

2PM

3PM

4PM

A: Try using 'event.target.id' to identify which row it was dropped on.
jQuery('.selectable').droppable({
    drop: function( event, ui ) {
        console.log( event.target.id );
    }
});

Also, I noticed that your row ID names start with a number, and that could cause problems. Try renaming them to words (id="one" or id="row1", id="row2"..)

A: For now I will use this code until later versions!

jQuery(document).ready(function() {
  var target;
  jQuery('#1463419359713').draggable({
    snap: ".selectable",
    containment: "#day_kalendar",
    axis: "y",
    cursor: "crosshair",
    cursorAt: {
      top: 0
    }
  });

  jQuery('.selectable').droppable({
    tolerance: "pointer",
    drop: function(event, ui) {
      var wrapper = jQuery(event.target).parent().attr("id");
      var eventHeight = jQuery('#1463419359713').height() / (jQuery(".selectable:first").height() + 1);
      var starthour = jQuery(event.target).attr("data-hour");
      var nexthour = parseInt(wrapper) + Math.round(eventHeight);
      nexthour = jQuery('#' + nexthour + ' div:nth-child(2)').attr("data-hour");
      jQuery('#1463419359713').children('#eventHours').text(starthour + ' - ' + nexthour);
    }
  });
});
.ui-selectable .ui-selected {
  background-color: #a6c9e2;
}
.ui-selectable .ui-selecting {
  background: #FECA40;
}
.ui-selectable-helper {
  position: absolute;
  z-index: 100;
  border: none;
}
.ui-dialog-titlebar {
  background: transparent;
  border: none;
}
[class*="col-"] {
  float: left;
  padding: 0px;
}
.col-1 {
  width: 8.33%;
}
.col-2 {
  width: 16.66%;
}
.col-3 {
  width: 25%;
}
.col-4 {
  width: 33.33%;
}
.col-5 {
  width: 41.66%;
}
.col-6 {
  width: 50%;
}
.col-7 {
  width: 58.33%;
}
.col-8 {
  width: 66.66%;
}
.col-9 {
  width: 75%;
}
.col-10 {
  width: 83.33%;
}
.col-11 {
  width: 91.66%;
}
.col-12 {
  width: 100%;
}
.row::after {
  content: "";
  clear: both;
  display: block;
}
.text-right {
  text-align: right;
}
.cornsilk {
  background-color: #E0E0E0;
}
.forestgreen {
  background-color: forestgreen;
}
.limegreen {
  background-color: limegreen;
}
.dimgrey {
  background-color: dimgrey;
  color: white;
}
.border-up {
  border-top: 1px solid white;
}
.border-up-dashed {
  border-top: 1px dashed white;
}
.fix-border {
  border-top: 1px solid dimgrey;
}
.selectable {
  position: relative;
}
.newevent {
  position: absolute;
  top: 0;
  left: 0;
  margin: 0px;
  width: 100%;
  height: auto;
  z-index: 1;
  /*opacity: 0.7;*/
  border-radius: 4px;
}

10AM

11AM

12PM

12 pm - 2 pm

(No title)

1PM

2PM

3PM

4PM


text:
Q: KeyCode returns undefined when function is bound to the class react I want to be able to check for the user hitting enter and if they do submit the form. However if the form is bound then keyCode returns undefined, and I believe I need to bind the form in-order to access the refs one of which is a ref to the form which needs to be submitted. Here is my current code...
class ChatInput extends React.PureComponent {

constructor(){
    super();
    this.onKeyDown = this.onKeyDown.bind(this)
}

onKeyDown(e) {
    var textarea = this.refs['chat_input'];
    var chatForm = this.refs['chat_form'];

    console.log(code);

    var code = (e.keyCode ? e.keyCode : e.which);
    if (code === 13) {
        console.log('submit the form here');
    }

}

render() {
    return(
        <form ref="chat_form" className="chat-form" onSubmit={this.handleSubmit} >
            <fieldset>
                <textarea ref="chat_input" required name="chat_input" onKeyPress={this.onKeyDown} placeholder={`${ !this.props.parentId ? 'Type your message...' : 'Reply to thread...' }`}></textarea>
                <button type="submit"><i className="fas fa-chevron-circle-right"></i></button>
            </fieldset>
        </form>
    )
}
}

A: Your console.log of code is before the assignment, otherwise it seems to work : https://codesandbox.io/s/vjpvr5jxpl

A: You're code works. you are logging an unassigned variable (you assign to it later). this will work:
onKeyDown(e) {
    var textarea = this.refs['chat_input'];
    var chatForm = this.refs['chat_form'];

    var code = (e.keyCode ? e.keyCode : e.which);
    console.log(code);

    if (code === 13) {
        console.log('submit the form here');
    }

}


text:
Q: Cannot delete S3 object, "Access Denied" I'm attempting to delete an object through the REST API and getting an AccessDenied 403.
My bucket policy is as follows:
{
     "Version": "2012-10-17",
     "Id": "<redacted>",
     "Statement": [
         {
             "Sid": "<redacted>",
             "Effect": "Allow",
             "Principal": {
                 "AWS": "arn:aws:iam::<redacted>:user/ts-user"
             },
             "Action": [
                 "s3:PutObject",
                 "s3:PutObjectAcl",
                 "s3:GetObject",
                 "s3:GetObjectAcl",
                 "s3:DeleteObject"
             ],
             "Resource": "arn:aws:s3:::<redacted>/*"
         }
     ]
}

The weird thing is that if I change my Principle to "*" (public), the DELETE works.
The user ts-user has the policy AmazonS3FullAccess attached and so does the group it belongs to. I have also tried using the credentials of the root user who is also the bucket owner.
I can see that the bucket policy file is being read from because if I remove the PutObject permissions I can no longer upload files. But I don't understand what else is needed so that I can delete files I have uploaded.
The files are being uploaded with public-read ACL but I have also tried bucket-owner-full-control.
Been stuck for hours and not sure what else to try!


text:
Q: Heroku shows "Build Succeeded" for Python App, but the App does not open open, only showing a Heroku "default page" I am new to Heroku. I have built a python app that I deployed on Heroku. The log (reproduced below) does not show any error (Heroku "Overview" page shows "Build Succeeded"). However, when I open the app, a Heroku default page ("Getting Started with Python on Heroku") pops out and my app does not show up. Any idea? Thanks for helping.
[Log shows: https://dynamo-presentation.herokuapp.com/ deployed to Heroku]


text:
Q: PostgreSQL non-overlapping ranges I use PostgreSQL database and have a cards table.
Each record(card) in this table have card_drop_rate integer value.
For example:
id | card_name |card_drop_rate
-------------------------------
1  |card1      |34
2  |card2      |16
3  |card3      |54

max drop rate is 34 + 16 + 54 = 104.
In accordance to my application logic I need to find a random value between 0 and 104 and then retrieve card according to this number, for example:
random value: 71
card1 range: 0 - 34(0 + 34)
card2 range: 34 - 50(34 + 16)
card3 range: 50 - 104(50 + 54)

So, my card is card3 because 71 is placed in the range 50 - 104
What is the proper way to reflect this structure in PostgreSQL ? I'll need to query this data often under so the performance is a criterion number one for this solution.

A: You can do this using cumulative sums and random.  The "+ 1"s might be throwing me off, but it is something like this:
with c as (
      select c.*,
             sum(card_drop_rate + 1) - card_drop_rate as threshhold
      from cards c
     ),
     r as (
      select random() * (sum(card_drop_rate) + count(*) - 1) as which_card
      from cards c
     )
select c.*
from c cross join
     r
where which_card >= threshhold
order by threshhold
limit 1;

For performance, I would simply take the cards and generate a new table with 106 slots.  Assign the card value to the slots and build an index on the slot number.  Then get a value using:
select s.*
from slots s
where s.slotid = floor(random() * 107);

A: Following query works fine:
SELECT
b.id,
b.card_drop_rate
FROM (SELECT a.id, sum(a.card_drop_rate) OVER(ORDER BY id) - a.card_drop_rate as rate, card_drop_rate FROM cards as a) b
WHERE b.rate < 299 ORDER BY id DESC LIMIT 1


text:
Q: Swift version & update Swift version I'm using swift script in my terminal and it shows

Welcome to Swift version 1.2. Type :help for assistance.

Is it the right way to show Swift's version?
And how to update Swift's version to 2.0?

A: You can get Swift 2.0 by installing Xcode 7.
You can get Swift 3.0 by installing Xcode 8.
You can get Swift 4.0 by installing Xcode 9.
You can get more information here: https://developer.apple.com/xcode/


text:
Q: why don't I get an error if I am assigning a variable's value, that has not been initialized to another variable in JavaScript? i) Here the numbers of squares are 6. And I am only providing 3 colors. when the for loop runs it assign background-color to the first 3 squares.
I want to know why it is not giving error when it is assigning colors[3] to squares[3]. when colors[3] have no value.
ii) And how is it different from other languages like java and c++?

var squares = document.querySelectorAll(".square");
var colors = ["rgb(146, 162, 109)", "rgb(204, 160, 23)", "rgb(9, 106, 144)"];
var resetButton = document.querySelector("#reset");

resetButton.addEventListener("click", function() {
    // change colors of squares
    for(var i = 0; i < squares.length; i++) {
        squares[i].style.backgroundColor = colors[i];
    }
});
body {
    background-color: #232323;
}

.square {
    width: 30%;
    background-color: purple;
    padding-bottom: 30%;
    float: left;
    margin: 1.66%;
}

#container {
    max-width: 600px;
    margin: 0 auto;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Color Game</title>
    <link rel="stylesheet" href="style.css">

    <button id="reset">Change Colors</button>

A:
I want to know why it is not giving error when it is assigning colors[3] to squares[3]. when colors[3] have no value.

colors[3] has a value: accessing a non-existing property evaluates to undefined.

console.log([][3]);

A: Yes, in this case javascript is different from languages like Java and c++.
In java or c++, if you access any index greater then the length of array you will get index out of bound exception. But in javascript you will get undefined, and undefined is considered a data type in javascript.
For example:
const arr = [1];
console.log(arr[5]); //undefined

Same is the case with objects, if you try to access any property of object which does not exists it will give you undefined. but in java or c++ it will throw an error.
Here you are just assigning undefined to your backgroundColor property that is why it is not throwing any error.


text:
Q: How do I backup a database with a stored procedure in SQL? I'm trying to create a stored procedure that backs up a database, however whenever I execute it, the folder I'm trying to backup to remains empty.
Here is my stored procedure:
USE [HarvestMan_SoutheskFarm_03_05_22]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:      Will Sewell
-- Create date: 03-05-2022
-- Description: Procedure to back up a database
-- =============================================

ALTER PROCEDURE [dbo].[BackupDatabases]
    @name VARCHAR(MAX) = 'HarvestMan_SoutheskFarm_03_05_22' -- DB NAME TO CREATE BACKUP
AS
BEGIN
    DECLARE @path VARCHAR(256) -- path of backup files
    DECLARE @fileName VARCHAR(256) -- filename for backup
    DECLARE @fileDate VARCHAR(20) -- used for file name

    SET @path = 'C:\Users\will.sewell\Documents\Database_Test'

    -- specify filename format
    SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

    BEGIN
        SET @fileName = @path + @name + '_' + @fileDate + '.BAK'

        BACKUP DATABASE @name TO DISK = @fileName
    END
END

I have tried changing the drive that it is writing to.
I've copy and pasted the database name I want to backup to ensure no spelling mistakes.
I'm assuming it might be a permissions issue or a visible files in the folder.
When I execute the stored procedure, I get this:
Processed 24472 pages for database 'HarvestMan_SoutheskFarm_03_05_22', file 'HarvestMan_dat' on file 2.

Processed 1 pages for database 'HarvestMan_SoutheskFarm_03_05_22', file 'HarvestMan_log' on file 2. BACKUP DATABASE successfully processed 24473 pages in 5.039 seconds (37.941 MB/sec).

Completion time: 2022-05-04T10:27:30.2344290+01:00

A: Dear you have to create the stored procedure first
also your path missing the last slash
BIG Note you must define an actual path
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[BackupDatabases]
    @name VARCHAR(MAX) = 'ActualDataBaseName' -- DB NAME TO                                 CREATE BACKUP
AS
BEGIN
DECLARE @path VARCHAR(256) -- path of backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name

SET @path = 'C:\ActualPath\'

-- specify filename format
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

BEGIN
    SET @fileName = @path + @name + '_' + @fileDate + '.BAK'

    BACKUP DATABASE @name TO DISK = @fileName
END
END


text:
Q: How to insert stored procedure resultset into Temp table and query it I am trying to insert the data into temp table from stored procedure. For instance
Insert into TempTable
EXEC dbo.MyProcedure(CustomerID)

In SQL Server it worked fine but in Sybase ASE 16 it gives me error:

Incorrect syntax near the keyword 'EXEC'.

Can you advice is it possible or a workaround?


text:
Q: look for most matching word I have a table with Tags (words). Each time I want to add a new item (word) to the table, I want to first see words that look the most like the word I am entering, so I could come realize I already have a word in the table that looks like it.
Kind of like using the match() function in Mysql, but I don't want a score of how many words are corresponding. But a score of within a word, how many characters are corresponding.
So something like:  select * from tags order by look_a_like_score(@newword)
But is there such a function like look_a_like_score() ?
Example, I already have in table:

Restaurant
Elevator
Swimming pool
Wifi

Now I want to add:

Free swimmer facilities

What I would like to have now is a list with 'Swimming pool' on top, because the part 'swimm' is most matching.
Can you help me do this?
PS. I collect the entire table into PHP and then put them into an array. So a PHP approach is also welcome.

A: On MySQL side you have soundex, not really working good as I like.
You may want to implement a MySQL module to use levenshtein (you'll need to compile in C either).
On PHP side you have levenshtein() available which is quite decent to have similarity score
You may use too:
soundex() - Calculate the soundex key of a string
similar_text() - Calculate the similarity between two strings
metaphone() - Calculate the metaphone key of a string
Check the manual to know how to use them

A: You can look here here for an implementation of the levenshtein distance formula this is good for finding the edit distance between to string.
Other things that might work out for you is using soundex or possibly double metaphone to do "Sounds like" matches.

A: There is no function.  But, you can do this with some SQL.  Let me assume that @newtag contains your new tag and that you have a numbers table.  You can do something like this:
select t.tag, max(len) as biggestmatch
from (select concat('%', substr(@newtag, n1.n, n2.n), '%') as pat,
             n1.n as start, n2.n as len
      from numbers n1 cross join
           numbers n2
      where n1.n <= length(@newtag) and n1+n2 <= length(@newtag)
     ) patterns join
     tags t
     on t.tag like patterns.pat
group by t.tag
order by max(len)
limit 1  /* you only need this if you want the best one */

I'm not promising that this will perform particularly well.  But for a handful of tags and strings that are not too long, it might suit your purposes.


text:
Q: Stackviews and dismissing a keyboard I am new to programming and new to this forum.. I have a problem with stack views. Once I had implemented stack views: https://i.stack.imgur.com/7Lgf0.png my code to dismiss keyboard stopped working. When I hit the text box the keyboard appears and I can enter values. When clicking outside the text box the keyboard remains. Without Stack views all is well.. Here is the code for dismiss keyboard:
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // Hide the keyboard.
    textField.resignFirstResponder()
    return true
                                                             }

    func textFieldDidEndEditing(_ textField: UITextField) {

       }

    // dismiss keyboard on touch outside textfield
   override func touchesBegan(_ touches: Set<UITouch>, with event:   UIEvent?) {
    for txt in self.view.subviews {
        if txt.isKind(of: UITextField.self) && txt.isFirstResponder {
            txt.resignFirstResponder()
                                                                    }
                                  }
                                                                                }

What am I doing wrong?? how do I get the keyboard dismiss function to work again while keeping stack views?

A: Try to remove everything in the touchesBegan function and just add self.view.endEditing(true) in it. I tried this with my textfield in UIStackView and this line does it all.
Swift 4.1:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}


text:
Q: Magento 2 - Get Catalog rule name and end date on product page I am trying to display a countdown timer using http://keith-wood.name/countdown.html on my product page to show the remaining time of the catalog rule that applies to that product
I have started with
   $_product = $block->getProduct();

if($_product->getSpecialPrice()){
    echo('<!-- special price -->');
    echo $_product->getSpecialPrice();
    // get special end date
    echo $_product->getSpecialToDate();

}

But it returns nothing, I need the end date to set the timer.
Any tips would be helpful.

A: this question is a bit broad.
My suggestion would be to look into create a custom widget type, there's a good tutorial here: (http://inchoo.net/magento-2/magento-2-custom-widget/)
In that widget you can allow the admin to select which catalog rule to be displayed, along with necessary logic to check if the rule is still active or not.
Then you would add the widget to PDP using custom layout / template rewrite.


text:
Q: combining and working with multiple JSON files I'm very new to working with JSON files and am really struggling. The software I'm working with outputs 1 JSON file for each image it processes. At any one time I'm ending up with 100's of individual JSON files. The main issues I'm having at the moment is that I don't know how to get everything into one cohesive, workable file in R. So far I have done this:
# character vector with each file name represented by an entry
filenames <- list.files("~/JSON_output/", pattern="*.json", full.names=TRUE)

# a list in which each element is one of the original JSON files
myJSON <- lapply(filenames, function(x) rjson::fromJSON(file = x))

# investigate the structure of the list
str(myJSON, max.level = 1, list.len = 10)

So far so good. The files all seem to be in there, but the element lithic_contours contains a data.frame.
If I was working with an individual image I can easily access this with
# Subset the list on lithic_contours with $ ...
df <- jsonlite::fromJSON(<file>, flatten = TRUE)$lithic_contours

# ... and it's already a data.frame
class(df)
#> [1] "data.frame"

However, I am unable to do this with the entire collection of images (myJON from above). I'm at a loss as how to get this data set together into a workable data frame. Any help would be appreciated. I've included 3 JSON files below. Thank you for any help.
{
  "id": "rub_al_khali",
  "conversion_px": 0.0395882818685669,
  "n_surfaces": 4,
  "lithic_contours": [
    {
      "surface_id": 0,
      "classification": "Ventral",
      "total_area_px": 530565.5,
      "total_area": 831.5,
      "max_breadth": 22.4,
      "max_length": 54,
      "polygon_count": 7,
      "scar_count": 0,
      "percentage_detected_scars": 0,
      "scar_contours": []
    },
    {
      "surface_id": 1,
      "classification": "Dorsal",
      "total_area_px": 530503.5,
      "total_area": 831.4,
      "max_breadth": 22.4,
      "max_length": 54,
      "polygon_count": 7,
      "scar_count": 4,
      "percentage_detected_scars": 0.62,
      "scar_contours": [
        {
          "scar_id": 0,
          "total_area_px": 129337,
          "total_area": 202.7,
          "max_breadth": 10.3,
          "max_length": 41.7,
          "percentage_of_surface": 0.24,
          "scar_angle": 1.85,
          "polygon_count": 5
        },
        {
          "scar_id": 1,
          "total_area_px": 100130,
          "total_area": 156.9,
          "max_breadth": 7.2,
          "max_length": 43,
          "percentage_of_surface": 0.19,
          "scar_angle": 357.36,
          "polygon_count": 4
        },
        {
          "scar_id": 2,
          "total_area_px": 93162,
          "total_area": 146,
          "max_breadth": 6.5,
          "max_length": 41.4,
          "percentage_of_surface": 0.18,
          "scar_angle": 5.01,
          "polygon_count": 4
        },
        {
          "scar_id": 3,
          "total_area_px": 6148.5,
          "total_area": 9.6,
          "max_breadth": 4,
          "max_length": 7.1,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 9
        }
      ]
    },
    {
      "surface_id": 2,
      "classification": "Lateral",
      "total_area_px": 176204,
      "total_area": 276.2,
      "max_breadth": 8.6,
      "max_length": 54.2,
      "polygon_count": 3,
      "scar_count": 2,
      "percentage_detected_scars": 0.33,
      "scar_contours": [
        {
          "scar_id": 0,
          "total_area_px": 44605,
          "total_area": 69.9,
          "max_breadth": 5,
          "max_length": 50,
          "percentage_of_surface": 0.25,
          "scar_angle": "NaN",
          "polygon_count": 3
        },
        {
          "scar_id": 1,
          "total_area_px": 12877,
          "total_area": 20.2,
          "max_breadth": 1.5,
          "max_length": 22.3,
          "percentage_of_surface": 0.07,
          "scar_angle": "NaN",
          "polygon_count": 2
        }
      ]
    },
    {
      "surface_id": 3,
      "classification": "Platform",
      "total_area_px": 55252.5,
      "total_area": 86.6,
      "max_breadth": 20.3,
      "max_length": 6.6,
      "polygon_count": 5,
      "scar_count": 1,
      "percentage_detected_scars": 0.42,
      "scar_contours": [
        {
          "scar_id": 0,
          "total_area_px": 23298.5,
          "total_area": 36.5,
          "max_breadth": 15,
          "max_length": 4.1,
          "percentage_of_surface": 0.42,
          "scar_angle": "NaN",
          "polygon_count": 4
        }
      ]
    }
  ]
}

{
  "id": "160",
  "conversion_px": 0.06443298969072166,
  "n_surfaces": 3,
  "lithic_contours": [
    {
      "surface_id": 0,
      "classification": "Dorsal",
      "total_area_px": 147674,
      "total_area": 613.1,
      "max_breadth": 21.5,
      "max_length": 36.1,
      "polygon_count": 5,
      "scar_count": 10,
      "percentage_detected_scars": 0.81,
      "scar_contours": [
        {
          "scar_id": 0,
          "total_area_px": 37128,
          "total_area": 154.1,
          "max_breadth": 10.1,
          "max_length": 26.4,
          "percentage_of_surface": 0.25,
          "scar_angle": 169.05,
          "polygon_count": 9
        },
        {
          "scar_id": 1,
          "total_area_px": 25267.5,
          "total_area": 104.9,
          "max_breadth": 6.6,
          "max_length": 24.7,
          "percentage_of_surface": 0.17,
          "scar_angle": 343.61,
          "polygon_count": 6
        },
        {
          "scar_id": 2,
          "total_area_px": 19178.5,
          "total_area": 79.6,
          "max_breadth": 5.2,
          "max_length": 21.7,
          "percentage_of_surface": 0.13,
          "scar_angle": 0,
          "polygon_count": 5
        },
        {
          "scar_id": 3,
          "total_area_px": 17053,
          "total_area": 70.8,
          "max_breadth": 6.1,
          "max_length": 15.7,
          "percentage_of_surface": 0.12,
          "scar_angle": 3.3,
          "polygon_count": 7
        },
        {
          "scar_id": 4,
          "total_area_px": 5279.5,
          "total_area": 21.9,
          "max_breadth": 6.3,
          "max_length": 6.6,
          "percentage_of_surface": 0.04,
          "scar_angle": 162.35,
          "polygon_count": 8
        },
        {
          "scar_id": 5,
          "total_area_px": 4290.5,
          "total_area": 17.8,
          "max_breadth": 5.2,
          "max_length": 9.8,
          "percentage_of_surface": 0.03,
          "scar_angle": "NaN",
          "polygon_count": 5
        },
        {
          "scar_id": 6,
          "total_area_px": 4013,
          "total_area": 16.7,
          "max_breadth": 3.4,
          "max_length": 8.1,
          "percentage_of_surface": 0.03,
          "scar_angle": 184.57,
          "polygon_count": 4
        },
        {
          "scar_id": 7,
          "total_area_px": 3166,
          "total_area": 13.1,
          "max_breadth": 3.1,
          "max_length": 6.7,
          "percentage_of_surface": 0.02,
          "scar_angle": "NaN",
          "polygon_count": 6
        },
        {
          "scar_id": 8,
          "total_area_px": 2022,
          "total_area": 8.4,
          "max_breadth": 5.8,
          "max_length": 3.1,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 6
        },
        {
          "scar_id": 9,
          "total_area_px": 1569.5,
          "total_area": 6.5,
          "max_breadth": 6.7,
          "max_length": 2.3,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 4
        }
      ]
    },
    {
      "surface_id": 1,
      "classification": "Lateral",
      "total_area_px": 117898,
      "total_area": 489.5,
      "max_breadth": 20.4,
      "max_length": 36.6,
      "polygon_count": 7,
      "scar_count": 8,
      "percentage_detected_scars": 0.4,
      "scar_contours": [
        {
          "scar_id": 0,
          "total_area_px": 11067.5,
          "total_area": 45.9,
          "max_breadth": 7.5,
          "max_length": 10.5,
          "percentage_of_surface": 0.09,
          "scar_angle": "NaN",
          "polygon_count": 5
        },
        {
          "scar_id": 1,
          "total_area_px": 9583,
          "total_area": 39.8,
          "max_breadth": 7.9,
          "max_length": 10.7,
          "percentage_of_surface": 0.08,
          "scar_angle": "NaN",
          "polygon_count": 8
        },
        {
          "scar_id": 2,
          "total_area_px": 8745,
          "total_area": 36.3,
          "max_breadth": 18.2,
          "max_length": 7.2,
          "percentage_of_surface": 0.07,
          "scar_angle": 96.34,
          "polygon_count": 6
        },
        {
          "scar_id": 3,
          "total_area_px": 7579.5,
          "total_area": 31.5,
          "max_breadth": 4.4,
          "max_length": 16.3,
          "percentage_of_surface": 0.06,
          "scar_angle": "NaN",
          "polygon_count": 4
        },
        {
          "scar_id": 4,
          "total_area_px": 4452,
          "total_area": 18.5,
          "max_breadth": 4.8,
          "max_length": 8.2,
          "percentage_of_surface": 0.04,
          "scar_angle": "NaN",
          "polygon_count": 10
        },
        {
          "scar_id": 5,
          "total_area_px": 2655.5,
          "total_area": 11,
          "max_breadth": 3.2,
          "max_length": 9,
          "percentage_of_surface": 0.02,
          "scar_angle": "NaN",
          "polygon_count": 4
        },
        {
          "scar_id": 6,
          "total_area_px": 1492,
          "total_area": 6.2,
          "max_breadth": 2.5,
          "max_length": 4.5,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 5
        },
        {
          "scar_id": 7,
          "total_area_px": 1433.5,
          "total_area": 6,
          "max_breadth": 3.5,
          "max_length": 5.7,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 5
        }
      ]
    },
    {
      "surface_id": 2,
      "classification": "Platform",
      "total_area_px": 63556,
      "total_area": 263.9,
      "max_breadth": 22.2,
      "max_length": 17.3,
      "polygon_count": 8,
      "scar_count": 0,
      "percentage_detected_scars": 0,
      "scar_contours": []
    }
  ]
}

{
  "id": "194",
  "conversion_px": 0.12406947890818858,
  "n_surfaces": 3,
  "lithic_contours": [
    {
      "surface_id": 0,
      "classification": "Ventral",
      "total_area_px": 65777,
      "total_area": 1012.5,
      "max_breadth": 38.6,
      "max_length": 33.6,
      "polygon_count": 8,
      "scar_count": 8,
      "percentage_detected_scars": 0.19,
      "scar_contours": [
        {
          "scar_id": 0,
          "total_area_px": 3408,
          "total_area": 52.5,
          "max_breadth": 8.7,
          "max_length": 9.7,
          "percentage_of_surface": 0.05,
          "scar_angle": "NaN",
          "polygon_count": 7
        },
        {
          "scar_id": 1,
          "total_area_px": 3010,
          "total_area": 46.3,
          "max_breadth": 16.9,
          "max_length": 4.7,
          "percentage_of_surface": 0.05,
          "scar_angle": "NaN",
          "polygon_count": 5
        },
        {
          "scar_id": 2,
          "total_area_px": 1530,
          "total_area": 23.6,
          "max_breadth": 3.8,
          "max_length": 10.9,
          "percentage_of_surface": 0.02,
          "scar_angle": "NaN",
          "polygon_count": 10
        },
        {
          "scar_id": 3,
          "total_area_px": 1346.5,
          "total_area": 20.7,
          "max_breadth": 8.8,
          "max_length": 4.2,
          "percentage_of_surface": 0.02,
          "scar_angle": "NaN",
          "polygon_count": 5
        },
        {
          "scar_id": 4,
          "total_area_px": 1001,
          "total_area": 15.4,
          "max_breadth": 7.2,
          "max_length": 4.3,
          "percentage_of_surface": 0.02,
          "scar_angle": "NaN",
          "polygon_count": 7
        },
        {
          "scar_id": 5,
          "total_area_px": 884,
          "total_area": 13.6,
          "max_breadth": 5.5,
          "max_length": 6.5,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 7
        },
        {
          "scar_id": 6,
          "total_area_px": 844,
          "total_area": 13,
          "max_breadth": 3.6,
          "max_length": 5.3,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 7
        },
        {
          "scar_id": 7,
          "total_area_px": 674,
          "total_area": 10.4,
          "max_breadth": 5.3,
          "max_length": 4.2,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 8
        }
      ]
    },
    {
      "surface_id": 1,
      "classification": "Dorsal",
      "total_area_px": 65223.5,
      "total_area": 1004,
      "max_breadth": 38.7,
      "max_length": 33.6,
      "polygon_count": 8,
      "scar_count": 13,
      "percentage_detected_scars": 0.72,
      "scar_contours": [
        {
          "scar_id": 0,
          "total_area_px": 12230.5,
          "total_area": 188.3,
          "max_breadth": 17.7,
          "max_length": 16.9,
          "percentage_of_surface": 0.19,
          "scar_angle": "NaN",
          "polygon_count": 9
        },
        {
          "scar_id": 1,
          "total_area_px": 6169,
          "total_area": 95,
          "max_breadth": 12.4,
          "max_length": 10.7,
          "percentage_of_surface": 0.09,
          "scar_angle": 63.43,
          "polygon_count": 7
        },
        {
          "scar_id": 2,
          "total_area_px": 6132,
          "total_area": 94.4,
          "max_breadth": 13.6,
          "max_length": 12.5,
          "percentage_of_surface": 0.09,
          "scar_angle": "NaN",
          "polygon_count": 13
        },
        {
          "scar_id": 3,
          "total_area_px": 5921,
          "total_area": 91.1,
          "max_breadth": 12.8,
          "max_length": 11.5,
          "percentage_of_surface": 0.09,
          "scar_angle": 201.8,
          "polygon_count": 9
        },
        {
          "scar_id": 4,
          "total_area_px": 3866.5,
          "total_area": 59.5,
          "max_breadth": 7.6,
          "max_length": 12.9,
          "percentage_of_surface": 0.06,
          "scar_angle": 160.35,
          "polygon_count": 9
        },
        {
          "scar_id": 5,
          "total_area_px": 3411.5,
          "total_area": 52.5,
          "max_breadth": 10.7,
          "max_length": 7.6,
          "percentage_of_surface": 0.05,
          "scar_angle": "NaN",
          "polygon_count": 7
        },
        {
          "scar_id": 6,
          "total_area_px": 2272.5,
          "total_area": 35,
          "max_breadth": 5.5,
          "max_length": 9.8,
          "percentage_of_surface": 0.03,
          "scar_angle": "NaN",
          "polygon_count": 8
        },
        {
          "scar_id": 7,
          "total_area_px": 2019.5,
          "total_area": 31.1,
          "max_breadth": 5.8,
          "max_length": 7.2,
          "percentage_of_surface": 0.03,
          "scar_angle": "NaN",
          "polygon_count": 7
        },
        {
          "scar_id": 8,
          "total_area_px": 1684.5,
          "total_area": 25.9,
          "max_breadth": 9.8,
          "max_length": 8.8,
          "percentage_of_surface": 0.03,
          "scar_angle": "NaN",
          "polygon_count": 9
        },
        {
          "scar_id": 9,
          "total_area_px": 862,
          "total_area": 13.3,
          "max_breadth": 3.3,
          "max_length": 6.5,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 5
        },
        {
          "scar_id": 10,
          "total_area_px": 827.5,
          "total_area": 12.7,
          "max_breadth": 6.3,
          "max_length": 4,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 5
        },
        {
          "scar_id": 11,
          "total_area_px": 787,
          "total_area": 12.1,
          "max_breadth": 4,
          "max_length": 4.8,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 6
        },
        {
          "scar_id": 12,
          "total_area_px": 699.5,
          "total_area": 10.8,
          "max_breadth": 4,
          "max_length": 4.2,
          "percentage_of_surface": 0.01,
          "scar_angle": "NaN",
          "polygon_count": 6
        }
      ]
    },
    {
      "surface_id": 2,
      "classification": "Lateral",
      "total_area_px": 15128,
      "total_area": 232.9,
      "max_breadth": 10,
      "max_length": 33.9,
      "polygon_count": 7,
      "scar_count": 5,
      "percentage_detected_scars": 0.69,
      "scar_contours": [
        {
          "scar_id": 0,
          "total_area_px": 6122,
          "total_area": 94.2,
          "max_breadth": 6.5,
          "max_length": 28.7,
          "percentage_of_surface": 0.4,
          "scar_angle": "NaN",
          "polygon_count": 7
        },
        {
          "scar_id": 1,
          "total_area_px": 1477,
          "total_area": 22.7,
          "max_breadth": 1.9,
          "max_length": 20.6,
          "percentage_of_surface": 0.1,
          "scar_angle": "NaN",
          "polygon_count": 3
        },
        {
          "scar_id": 2,
          "total_area_px": 1415,
          "total_area": 21.8,
          "max_breadth": 3.1,
          "max_length": 13.6,
          "percentage_of_surface": 0.09,
          "scar_angle": "NaN",
          "polygon_count": 5
        },
        {
          "scar_id": 3,
          "total_area_px": 800,
          "total_area": 12.3,
          "max_breadth": 4.5,
          "max_length": 6.6,
          "percentage_of_surface": 0.05,
          "scar_angle": "NaN",
          "polygon_count": 7
        },
        {
          "scar_id": 4,
          "total_area_px": 596,
          "total_area": 9.2,
          "max_breadth": 2.1,
          "max_length": 9.7,
          "percentage_of_surface": 0.04,
          "scar_angle": "NaN",
          "polygon_count": 6
        }
      ]
    }
  ]
}

A: I've saved your three json files as file#.json in the current directory. Let's first figure out how to read in one file into a single data.frame, and then we'll iterate over all of them.
First, helper functions. These make a couple of simple assumptions:

*

*within each lithic_contours, there are 0 or 1 scar_contours frame, and then all other values are length 1 (easily converted into a 1-row data.frame);

*within each json, there are 0 or more lithic_contours lists, and then all other values are length 1 (again, easily converted into a 1-row data.frame).

each_lith <- function(onelith) {
  scar_contours <- do.call(rbind.data.frame, onelith$scar_contours)
  if (length(scar_contours)) names(scar_contours) <- paste0("scar_contour.", names(scar_contours))
  onelith$scar_contours <- NULL
  onelith <- as.data.frame(onelith)
  if (nrow(scar_contours)) {
    cbind(onelith, scar_contours, row.names = NULL)
  } else onelith
}
each_json <- function(onejson) {
  liths <- lapply(onejson$lithic_contours, each_lith)
  onejson$lithic_contours <- NULL
  onejson <- as.data.frame(onejson)
  cbind(onejson, data.table::rbindlist(liths, use.names = TRUE, fill = TRUE),
        row.names = NULL)
}

Working on one json:
filenames <- list.files(pattern = "\\.json$", full.names = TRUE)
each_json(jsonlite::read_json(filenames[1]))
#             id conversion_px n_surfaces surface_id classification total_area_px total_area max_breadth max_length polygon_count scar_count percentage_detected_scars scar_contour.scar_id scar_contour.total_area_px scar_contour.total_area scar_contour.max_breadth scar_contour.max_length scar_contour.percentage_of_surface scar_contour.scar_angle scar_contour.polygon_count
# 1 rub_al_khali    0.03958828          4          0        Ventral      530565.5      831.5        22.4       54.0             7          0                      0.00                   NA                         NA                      NA                       NA                      NA                                 NA                    <NA>                         NA
# 2 rub_al_khali    0.03958828          4          1         Dorsal      530503.5      831.4        22.4       54.0             7          4                      0.62                    0                   129337.0                   202.7                     10.3                    41.7                               0.24                    1.85                          5
# 3 rub_al_khali    0.03958828          4          1         Dorsal      530503.5      831.4        22.4       54.0             7          4                      0.62                    1                   100130.0                   156.9                      7.2                    43.0                               0.19                  357.36                          4
# 4 rub_al_khali    0.03958828          4          1         Dorsal      530503.5      831.4        22.4       54.0             7          4                      0.62                    2                    93162.0                   146.0                      6.5                    41.4                               0.18                    5.01                          4
# 5 rub_al_khali    0.03958828          4          1         Dorsal      530503.5      831.4        22.4       54.0             7          4                      0.62                    3                     6148.5                     9.6                      4.0                     7.1                               0.01                     NaN                          9
# 6 rub_al_khali    0.03958828          4          2        Lateral      176204.0      276.2         8.6       54.2             3          2                      0.33                    0                    44605.0                    69.9                      5.0                    50.0                               0.25                     NaN                          3
# 7 rub_al_khali    0.03958828          4          2        Lateral      176204.0      276.2         8.6       54.2             3          2                      0.33                    1                    12877.0                    20.2                      1.5                    22.3                               0.07                     NaN                          2
# 8 rub_al_khali    0.03958828          4          3       Platform       55252.5       86.6        20.3        6.6             5          1                      0.42                    0                    23298.5                    36.5                     15.0                     4.1                               0.42                     NaN                          4

We can iterate fairly easily now,
alljsons <- lapply(setNames(nm = filenames), jsonlite::read_json)
alldata <- lapply(alljsons, each_json)
alldata <- rbindlist(alldata, idcol = "filename")
alldata
#         filename           id conversion_px n_surfaces surface_id classification total_area_px total_area max_breadth max_length polygon_count scar_count percentage_detected_scars scar_contour.scar_id scar_contour.total_area_px scar_contour.total_area scar_contour.max_breadth scar_contour.max_length scar_contour.percentage_of_surface scar_contour.scar_angle scar_contour.polygon_count
#           <char>       <char>         <num>      <int>      <int>         <char>         <num>      <num>       <num>      <num>         <int>      <int>                     <num>                <int>                      <num>                   <num>                    <num>                   <num>                              <num>                  <char>                      <int>
#  1: ./file1.json rub_al_khali    0.03958828          4          0        Ventral      530565.5      831.5        22.4       54.0             7          0                      0.00                   NA                         NA                      NA                       NA                      NA                                 NA                    <NA>                         NA
#  2: ./file1.json rub_al_khali    0.03958828          4          1         Dorsal      530503.5      831.4        22.4       54.0             7          4                      0.62                    0                   129337.0                   202.7                     10.3                    41.7                               0.24                    1.85                          5
#  3: ./file1.json rub_al_khali    0.03958828          4          1         Dorsal      530503.5      831.4        22.4       54.0             7          4                      0.62                    1                   100130.0                   156.9                      7.2                    43.0                               0.19                  357.36                          4
#  4: ./file1.json rub_al_khali    0.03958828          4          1         Dorsal      530503.5      831.4        22.4       54.0             7          4                      0.62                    2                    93162.0                   146.0                      6.5                    41.4                               0.18                    5.01                          4
#  5: ./file1.json rub_al_khali    0.03958828          4          1         Dorsal      530503.5      831.4        22.4       54.0             7          4                      0.62                    3                     6148.5                     9.6                      4.0                     7.1                               0.01                     NaN                          9
#  6: ./file1.json rub_al_khali    0.03958828          4          2        Lateral      176204.0      276.2         8.6       54.2             3          2                      0.33                    0                    44605.0                    69.9                      5.0                    50.0                               0.25                     NaN                          3
#  7: ./file1.json rub_al_khali    0.03958828          4          2        Lateral      176204.0      276.2         8.6       54.2             3          2                      0.33                    1                    12877.0                    20.2                      1.5                    22.3                               0.07                     NaN                          2
#  8: ./file1.json rub_al_khali    0.03958828          4          3       Platform       55252.5       86.6        20.3        6.6             5          1                      0.42                    0                    23298.5                    36.5                     15.0                     4.1                               0.42                     NaN                          4
#  9: ./file2.json          160    0.06443299          3          0         Dorsal      147674.0      613.1        21.5       36.1             5         10                      0.81                    0                    37128.0                   154.1                     10.1                    26.4                               0.25                  169.05                          9
# 10: ./file2.json          160    0.06443299          3          0         Dorsal      147674.0      613.1        21.5       36.1             5         10                      0.81                    1                    25267.5                   104.9                      6.6                    24.7                               0.17                  343.61                          6
# ---
# 44: ./file3.json          194    0.12406948          3          1         Dorsal       65223.5     1004.0        38.7       33.6             8         13                      0.72                    8                     1684.5                    25.9                      9.8                     8.8                               0.03                     NaN                          9
# 45: ./file3.json          194    0.12406948          3          1         Dorsal       65223.5     1004.0        38.7       33.6             8         13                      0.72                    9                      862.0                    13.3                      3.3                     6.5                               0.01                     NaN                          5
# 46: ./file3.json          194    0.12406948          3          1         Dorsal       65223.5     1004.0        38.7       33.6             8         13                      0.72                   10                      827.5                    12.7                      6.3                     4.0                               0.01                     NaN                          5
# 47: ./file3.json          194    0.12406948          3          1         Dorsal       65223.5     1004.0        38.7       33.6             8         13                      0.72                   11                      787.0                    12.1                      4.0                     4.8                               0.01                     NaN                          6
# 48: ./file3.json          194    0.12406948          3          1         Dorsal       65223.5     1004.0        38.7       33.6             8         13                      0.72                   12                      699.5                    10.8                      4.0                     4.2                               0.01                     NaN                          6
# 49: ./file3.json          194    0.12406948          3          2        Lateral       15128.0      232.9        10.0       33.9             7          5                      0.69                    0                     6122.0                    94.2                      6.5                    28.7                               0.40                     NaN                          7
# 50: ./file3.json          194    0.12406948          3          2        Lateral       15128.0      232.9        10.0       33.9             7          5                      0.69                    1                     1477.0                    22.7                      1.9                    20.6                               0.10                     NaN                          3
# 51: ./file3.json          194    0.12406948          3          2        Lateral       15128.0      232.9        10.0       33.9             7          5                      0.69                    2                     1415.0                    21.8                      3.1                    13.6                               0.09                     NaN                          5
# 52: ./file3.json          194    0.12406948          3          2        Lateral       15128.0      232.9        10.0       33.9             7          5                      0.69                    3                      800.0                    12.3                      4.5                     6.6                               0.05                     NaN                          7
# 53: ./file3.json          194    0.12406948          3          2        Lateral       15128.0      232.9        10.0       33.9             7          5                      0.69                    4                      596.0                     9.2                      2.1                     9.7                               0.04                     NaN                          6

FYI: I use data.table::rbindlist twice here, you can also switch to dplyr::bind_rows (changing idcol= to .id=) for the same effect. If the number of columns were always identical (they are not), then one can get away with do.call(rbind, liths) and similar, but since some of the lithic_contours have no scar_contours, it takes a bit more work. If you cannot use data.table or dplyr, one can fashion an rbind-workflow that accounts for these: find the missing columns, add them with NA values, and ensure all frames have the same column-order.
Also, I'm using jsonlite::read_json, but I believe rjson is compatible-enough that it should be a drop-in replacement. YMMV, though hopefully it does not vary :-)


text:
Q: During the Cycle of Foundation, were there any robots helping humanity? I finished Prelude to Foundation (after reading The Cycle of Foundation), and we learn that:

 Dors is a robot

 Demerzel is a robot. And not just a robot, but Daneel itself.

Considering that Daneel intervenes only when necessary and that, in the prelude, we are only before the collapsing of the Empire, I came to wondering if, during the existence of the Foundation, robots were present within human society to help them during the many years of collapse, as did Daneel before.

A: "During the existence of the Foundation" covers about 500 years in the series as written. The final book, chronologically, is Foundation and Earth (1986). In this novel,

 Daneel is found living inside Earth's moon. He has been orchestrating his Plan A, which is the Gaia living planet that might eventually become Galaxia. He also had a Plan B, psychohistory. In the final sections of the book, he says "Over a period of years, the humaniform robots that have been working with me have been, one by one, called home. Their last tasks have been to remove all references to Earth in the planetary archives." Their withdrawal, to conserve Daneel's scarce resources, means that Gaia's development will be very slow.

 It is not explicitly stated what the robots have been doing with respect to the Foundation itself. But it appears that they are not doing it any more, perhaps for a period of centuries. Their censorship efforts were certainly long ago enough to affect Pelorat's research, but probably not Lord Dorwin from the original Foundation, who seems to know about Alpha Centauri and Sol.

Consequently, I would guess that robots have mostly not been involved in the Foundation or Second Foundation, since they were either busy with other things, or deliberately kept home. But we do not have an explicit statement either way.


text:
Q: Changes index of elements in Array in a C# console app, but when runs it return index remain same I've just changed the indexes of elements in an array. When I run the code and search a specific element using Array.BinarySearch(); It still returns the same indexes as before I changed them.
static void Main(string[] args)
    {
        int indexno;
        string schooltype;
        Array schools= Array.CreateInstance(typeof(string), 3);
        schools.SetValue("Middle School", 0);
        schools.SetValue("High School", 1);
        schools.SetValue("Univercity", 2);
        Array.Sort(schools);
        Console.Write("What type of school are you looking for: ");
        schooltype = Console.ReadLine();
        indexno = Array.BinarySearch(schools, schooltype.ToString());
        if (indexno<0)
        {
            Console.WriteLine("School type not exist. ");
        }
        else
        {
            Console.WriteLine("Index of the school type is " + indexno);
        }

A: I've never seen a variable declared as Array in real production code. We might use the Array static methods, but declaring a variable that way just doesn't happen.
static void Main(string[] args)
{
    string[] schools = {"Middle School", "High School", "University"};
    Array.Sort(schools); //uses default comparer... be careful of mixed case values

    //verify new order
    Console.WriteLine(String.Join("\n", schools));

    Console.Write("What type of school are you looking for: ");
    var schooltype = Console.ReadLine();

    var result = "School type not exist. ";
    var index = Array.BinarySearch(schools, schooltype);
    if (index >= 0)
    {
        result = $"Index of the school type is {index}";
    }
    Console.WriteLine(result);
}

This code returned correct indexes for all three possible school types:

https://dotnetfiddle.net/fjpOOb


text:
Q: problem retrieving data in sinatra when behind a firewall In my Sinatra app, I'm displaying a continuously updating list of random tweets on my front page: (the tweets aren't real-time, they're just a list of tweets I have stored in a MongoDB database on MongoHQ)
:javascript
  function addTweet() {
    $.get("/tweet", function(data) {
      $("table tr#header:first").after(data);
    });
    setTimeout(addTweet, 2000);
  }

  $(function() {
    setTimeout(addTweet, 2000);
  });

The /tweet page simply gets a random tweet from the database and displays it as a row:
get '/tweet' do
  @tweet = coll.find().limit(-1).skip(rand(coll.count())).first()['text'] # get a random tweet
  haml :tweet, :layout => false
end

I've deployed the app on Heroku, and it works fine when I access it at home. However, when I access the app at work (from the same laptop and browser as at home), it simply displays the same tweet over and over again on the front page (but going to "/tweet" correctly displays random tweets each time). Any ideas on what the problem is? Is my javascript update call not working for some reason because I'm behind a firewall (but the problem isn't that only a single row gets displayed and then the updating stops, the problem is that the list keeps adding the same tweet over and over again to the list)?

A: Sounds like a caching issue. Try disabling caching explicitely:
$.ajax({
    method: 'GET',
    url: '/tweet',
    cache: false,
    success: function(data) {
        $("table tr#header:first").after(data);
    }
});


text:
Q: Java ArrayList Sort on the basis of dynamic objects fields? I am getting a issue i have below code
public void columnsList(List<TableRecord> records){

    for(TableRecord record : records){
        Table table = record.getTable();
        //Do sort here on stampDate
        Field[] fields = table.fields();
        for(Field field : fields){
            field.getName();
            record.getValue(field);

        }
    }

}

and records object contain Object of different class type
List<TableRecord> records = new List<TableRecord>();
records.add(new AddressRecord());
records.add(new CityRecord());
records.add(new UserRecord());

Now how i need to sort them by stampDate variable which is in each class how can we do it when we have different classes in list

A: If your code above is correct, that means AddressRecord, CityRecord and UserRecord all extend TableRecord:
class AddressRecord extends TableRecord {
    // other fields and methods here
}
class CityRecord extends TableRecord {
    // other fields and methods here
}
class UserRecord extends TableRecord {
    // other fields and methods here
}

You only have to write a Comparator for this class. It should look something like this:
class TableRecord {
    private Date timeStamp;

    public Date getTimeStamp() {
        return timeStamp;
    }
// other fields and methods here
}

class RecordStampDateComparator implements Comparator<TableRecord>{

    public int compare(TableRecord tr1, TableRecord tr2) {
        Date tr1Date = tr1.getTimeStamp();
        Date tr2Date = tr2.getTimeStamp();
        return tr1Date.compareTo(tr2Date);
    }
}

A: Just write abstract class Record with protected field stampDate, that implements Comparable and override compareTo method.
public abstract class Record implements Comparable<Record> {
    protected Date stampDate;

    @Override
    public int compareTo(Record anotherRecord){
        return this.stampDate.compareTo(anotherRecord.stampDate);
    }
}

Then extend this class with your record classes:
public class AddressRecord extends Record{
...
}

public class CityRecord extends Record{
...
}

public class UserRecord extends Record{
...
}

A: If you can't change the classes write your comparator( Comparator<Object>), that will try to find the field stampDate and compare them. Than use it for sorting the list.
Comparator implementation:
import java.util.Comparator;
import java.util.Date;

public class StampDateComparator implements Comparator<Object> {

@Override
public int compare(Object o1, Object o2) {

    try {
        Date d1 = (Date) o1.getClass().getDeclaredField("stampDate").get(o1);
        Date d2 = (Date) o2.getClass().getDeclaredField("stampDate").get(o2);
        return compare(d1, d2);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException("Missing variable stampDate");
    }catch (ClassCastException e) {
        throw new RuntimeException("stampDate is not a Date");
    } catch (IllegalArgumentException e) {
        //shoud not happen
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

}

A: Use following Comparator class on List.
class TableRecordCompare implements Comparator<TableRecord>{
     if(TableRecord instanceof AddressRecord){
       // return compareTo for sample data of address.
     }
     else if(TableRecord instanceof CityRecord){
     // return compareTo for sample data of CityRecord.
      }
     else{
     // return compareTo for sample data of UserRecord.
    }

}


text:
Q: componentWillUnmount lifecycle with react useeffect hook Is there any difference with these 3 useEffects
useEffect(() => {
    return console.log('useEffect with undefined dep');
});

useEffect(() => {
    return console.log('useEffect with empty array dep');
}, []);

useEffect(() => {
    return console.log('useEffect with filled dep');
}, [filledDep]);

A: As React docs says:

*

*when an empty array [] is supplied

If you want to run an effect and clean it up only once (on mount and
unmount), you can pass an empty array ([]) as a second argument. This
tells React that your effect doesn't depend on any values from props
or state, so it never needs to re-run. This isn't handled as a special
case — it follows directly from how the dependencies array always
works.

*

*When there is no second argument, it works as both componentDidMount and componentDidUpdate:
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
});

*and if you supply arguments, then it will re-run the effect when arguments were changed and it will also still run after the initial render
useEffect(() => {
    document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

A: To clean up after a component unmounts, we have a simple way to perform the equivalent of the componentWillUnmount using the useEffect Hook.
The only thing that we need to do is to return a function inside the callback function of the useEffect Hook.

if a component renders multiple times (as they typically do), the
previous effect is cleaned up before executing the next effect.

A: Yes there are...

*

*It will run on every-time when component renders/re-renders

*It will run only once when the component first renders

*It will run when component first renders and every-time when its dependency filledDep changes.


text:
Q: Git push unresponsive Facing an issue with git where it does not complete the process of "git push" and just stands still like it would happen in an infinite loop.
I read a little bit about this online, Would this be space problem may be ?
I also tried "git config --global http.postBuffer 524288000". That did not help either.
Pasting my steps below:
$ git status -s
M cli/filename1.php
M cli/filename2.php
M cli/filename3.php
M cli/testDelete.php

$ git add -A

$ git commit -m " my msg "
[branch_name 45ec72e]  my msg
4 files changed, 93 insertions(+), 15 deletions(-)

$ git push origin branch_name
Password for 'https://username@bitbucket.org':
<cursor keeps blinking here, it has been such since more than 20 mins now.>

I do not get any error .
Also another interesting thing to note is (1) I do get a fatal: authentication failed when I feed in the incorrect password, it goes into an unresponsive state when I feed in the correct password and (2) when I interrupt by ctrl+C and run git status -s again - it shows no files. But when I check it in my repo online, the files do no exist there.

A: For anyone still having this issue, try configuring your username and email just as it is set in bitbucket.
git config --global user.name "JohnDoe"
git config --global user.email johndoe@example.com


text:
Q: Undefined symbol rom external library with Swig/Python I have looked at this question but it doesn't seem to help my case.
I have a C++ library that I am wrapping parts of using SWIG (unfortunately swig 2.0).  This library performs some socket communications with a remote server and I need to make use of it from Python.  I am finally able to compile and link a .so file but during my testing, when importing the generated module, I get the following:
...
    _mod = imp.load_module('_YBB', fp, pathname, description)
ImportError: ./_YBB.so: undefined symbol: _Z11IPV4Gatewayhhhh

This undefined symbol equates to:
IPV4Gateway(unsigned char, unsigned char, unsigned char, unsigned char)

This is frustrating as I don't have a call to this function anywhere in the wrapped library.  So it must be in the underlying socket library that I am calling.
Does anyone know what I have to do to clear up this undefined symbol?

A: Ah, never mind.  It turns out that it was declared in a header file but never implemented.  So swig (correctly) wrote a wrapper for it but was never able to link against the underlying implementation (which didn't exist).


text:
Q: No java command after installing JDK I have downloaded and installed JDK 9 with NetBeans. NetBeans runs fine and I build test application that also runs fine from IDE. But if I run java command in terminal I have error
'java' can not be found in the following package:
...

So, where is my java? Should I download JRE separately?
Command
sudo update-alternatives --config java

gives
update-alternatives: error: no alternatives for java

A: Edit your .bashrc file by
gedit .bashrc

Add these line at the last of the file
JAVA_HOME=/usr/lib/jvm/jdk1.7.0

(this path may change according to your system)
(this you copy as it is)
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

then logout and login


text:
Q: problem about connecting to my Postgres with node.js through knex I am facing this problem with connecting to my Postgres with node.js through knex. I am trying this for the first time and I ask humbly to help me solving the issue. please help me.
My code is the following. Every time I make a request, PostgreSQL doesn't connect so nothing happens.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex')

const db = knex({
    client: 'pg',
    connection: {
        host: '127.0.0.1',
        user: 'postgres',
        password: '',
        database: 'smart-brain'

    }
});

db.select('*').from('users').then(console.log).catch(console.log);

app.use(cors());

app.post('/signin', (req, res) => {
    if (req.body.email === database.users[0].email &&
        req.body.password === database.users[0].password) {
        res.json('success');
    } else {
        res.status(400).json('error logging in');
    }

})
app.post('/register', (req, res) => {
    const {
        name,
        email,
        password
    } = req.body;
    db('users')
        .returning('*')
        .insert({
            email: email,
            name: name,
            joined: new Date()
        })
        .then(respons => {
            res.json(response);
        }).
    catch(err => res.status(400).json('unable to register'))
})

app.listen(3000, () => {
    console.log('app is running on the port 3000');
});

and the response is these on npm
Error: connect ECONNREFUSED 127.0 .0 .1: 5432
at TCPConnectWrap.afterConnect[as oncomplete](net.js: 1141: 16) {
    errno: 'ECONNREFUSED',
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 5432
}

A: If you are in Ubuntu, then go to the following folder.
/etc/postgresql/{your_pg_version}/main
Or If you are in Windows, then go to the following folder,
C:\Program Files\PostgreSQL\{your_pg_version}\data\
Open the file pg_hba.conf to write with SuperUser/Administrative permission,
Go to the bottom, and put trust at the end of following lines.
# Database administrative login by Unix domain socket
local   all             postgres                                trust

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

After that, restart your PostgreSQL server and try again with your code.


text:
Q: How to cause a form to be submitted automatically on page load in JavaScript? This may have an obvious answer, but I am very new to js so I have no idea how to do this. I would like a form on a page to be submitted automatically when that page is loaded without requiring any user action like pressing a button. How to do this?

A: I'd go with what sAc suggests, but I'd use an event listener rather than just writing to window.onload:
function submit_form() { document.formName.submit(); }

if(window.attachEvent){
    window.attachEvent("onload", submit_form);
}else{
    window.addEventListener("load", submit_form, false);
}

A: <form id=lol action="file.php"></form>
<script>document.getElementById('lol').submit();</script>

A: Like this:
window.onload = function(){
  document.formName.submit();
};


text:
Q: Choosing projection for running polygon intersections at global scale (i.e, geodesic intersections)? How do I choose a projection for intersecting two global polygon datasets in WGS-84 (4326), and get accurate estimates of their overlap area?
I searched the internet for answers to this question, and all turned out to be wrong I think, except for the lovely projection table posted by Jochen Albrecht.
So, when you are intersecting two polygons in 4326, you will need currently in R (sf package, as of 12/2020) to reproject them into a common projection, run the intersection, and then back-transform them into 4326 to get a correct estimate of the overlap area (using sf::st_area).
Most sources (e.g. Chapter 6 Reprojecting geographic data of Geocomputation with R) will recommend an azimuthal equidistant or equal-area projection centered on the focal polygon, which if you have lots of polygons (I have >200K), means a for-loop.  Not that slow actually, but many of the suggested projections will do geodesic intersections between polygons with some bias.

A: You should not use a projection (except for making maps; or when you must use an algorithm that really cannot deal with angular data). For area computations in R, you should use the lon/lat data. That is the best way to avoid inaccuracies. The thing to consider is the vertex density of the polygons. If that is too low, the intersection does not happen at the right (close enough) place. But you can increase the vertex density (see my example below). If low vertex density is a problem, making lon/lat intersections inaccurate, projecting the data to a planar crs does not help at all. That is a common, but big, misconception.
Here is an extreme example. I do not know sf very well, so I use sp/raster/geosphere
Example data
library(raster)
crs = "+proj=longlat +datum=WGS84"
# very large polygons with very few vertices
p1 <- spPolygons(rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20)), crs=crs)
p2 <- spPolygons(rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0)), crs=crs)

First the naïve approach
x1 <- intersect(p1, p2)
raster::area(x1) / 1e+12
#[1] 50.02117

plot(bind(p1, p2), border=c("red", "blue"), lwd=5)
plot(x1, add=TRUE, density=20)

Now add vertices (in this case I ask for at least one every 1000 m)
pp1 <- geosphere::makePoly(p1, interval=1000, sp=TRUE)
pp2 <- geosphere::makePoly(p2, interval=1000, sp=TRUE)

The number of vertices was
nrow(geom(p1)) - 1
#[1] 4

And is now
nrow(geom(pp1))-1
[1] 40785

Try again. The area of intersection is 2.5 times larger.
x2 <- intersect(pp1, pp2)
raster::area(x2) / 1e+12
#[1] 127.8921

plot(bind(pp1, pp2), border=c("red", "blue"), lwd=5)
plot(x2, add=TRUE, density=20)

I am implementing these things in terra to streamline and speed things up.
A comparison using a projection:
crs2 <- "+proj=sinu"
p1q <- spTransform(p1, crs2)
p2q <- spTransform(p2, crs2)
qi <- intersect(p1q, p2q)

Areas are way off
area(p1) / 1e+12
#[1] 211.2407
area(p1q) / 1e+12
#[1] 127.7939
area(p2) / 1e+12
#[1] 161.2815
area(p2q )/ 1e+12
#[1] 107.1201

And the intersected area is about as bad as the naive approach
area(x1) / 1e+12
#[1] 50.02117
area(x2) / 1e+12
#[1] 127.8921
area(qi) / 1e+12
#[1] 56.00833

plot(bind(p1q, p2q), border=c("red", "blue"), lwd=5)
plot(qi, add=TRUE, density=20)

From the comment (sinu is not a great example):
 crs3 <- "+proj=eqc";
 p1q <- spTransform(p1, crs3);
 p2q <- spTransform(p2, crs3);
 qi <- intersect(p1q, p2q);
 qi2 <-spTransform(qi, crs);
 area(x1) / 1e+12;
 #[1] 50.02117
 area(qi2) / 1e+12
 #[1] 50.02117

Notes (in repsonse to the comments):
raster::intersect is a wrapper for rgeos::gIntersection that also keeps the attributes (but the latter should be faster if you do not care about that). You can also use sf::st_intersection. Since you are not projecting, the data-line should not be an issue?.
You can find out if it matters by changing interval in makePoly. You can check the number of vertices with nrow(geom(p1) (see above). My experience with the WDPA is that it has poor topology (e.g. self intersections), but much detail, so none of this might be of much practical concern.
Whether adding vertices adds unintended realism would depend on how the data were created. If they were GPS points it would avoid losing accuracy and I it would be good practice (best practice would be an algorithm that finds the correct intersection without such help, e.g. s2)). But the boundaries are more likely from tracing on a map. Then it would depend on the underlying map projection that was used for that. So it may be impossible to really know?

A: Jochen's table led me to an accurate answer (I think/hope).
Here is the answer I came up with.  First, if you can run this in ArcGIS Pro, go for it, because it has a geodesic option, but it is not a possibility for my analysis (too much data, etc.).  Second, try the new s2 functionality in sf in R. Sadly, I could not use the new s2 functionality since my data kept throwing validity errors. But it turns out there may be a simple solution.
If you have a global dataset that stretches over the international dateline, the first step is to clip it in two at the dateline.  That solves a lot of problems and makes the solution below possible. if you can't do that, and the solutions above don't work, try the local azimuth solution (see below).
So I did some trial analyses, and I think what you actually want is a projection that preserves SHAPE, not distance or area.  And the best projections for shape are cylindrical, which means that sf's basic equirectangular projection is best for geodesic intersection (i.e., the default st_intersection on 4326 data, which throws an error you can ignore).
Here's an example set of analyses that show that equirectangular works best, with zero bias in area estimation between two large example polygons.  An equidistant azimuthal projection, centered on the local polygon centroid, had the second lowest bias.
library(sf)

#  create a polygon box (pol) centered on 0,0 lat/long, a second shifted half a degree east (pol2, and a third (pol1b) representing the area of overlap.

center_loc = 0
a=center_loc-0.5
b=center_loc+0.5
pol = st_polygon(list(rbind(c(a,a), c(b,a), c(b,b), c(a,b), c(a,a))))
pol2 = st_polygon(list(rbind(c(0,a), c(1,a), c(1,b), c(0,b), c(0,a))))
pol1b=st_polygon(list(rbind(c(0,a), c(b,a), c(b,b), c(0,b), c(0,a))))

plot(pol); plot(pol2, add=TRUE); plot(pol1b, add=TRUE, col="red")

pol=st_sfc(pol)
st_crs(pol)=4326
pol2=st_sfc(pol2)
st_crs(pol2)=4326
pol1b=st_sfc(pol1b)
st_crs(pol1b)=4326

#  okay!  now you can calculate the area of each:
st_area(pol)
st_area(pol2)
st_area(pol1b); truval=st_area(pol1b)

#  now to transform the focal poly,  pol, to a few different azimuthal systems.
pol_aeqd=st_transform(pol, "+proj=aeqd +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs") #aeqd
pol_l=st_transform(pol, "+proj=laea") #lambert
pol_st=st_transform(pol, "+proj=stere") #stereographic

#  now to do the same for pol2 (note that the projection is centered on the neighboring polygon, which we would do for a local azimuthal projection)
pol2_aeqd=st_transform(pol2, "+proj=aeqd +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs") #aeqd
pol2_l=st_transform(pol2, "+proj=laea") #lambert
pol2_st=st_transform(pol2, "+proj=stere") #stereographic

#  and to intersect and back convert to 4326.
inter_a=st_intersection(pol_aeqd, pol2_aeqd)
inter_l=st_intersection(pol_l, pol2_l)
inter_st=st_intersection(pol_st, pol2_st)
fin_a=st_transform(inter_a, st_crs(4326))
fin_l=st_transform(inter_l, st_crs(4326))
fin_st=st_transform(inter_st, st_crs(4326))

#  I added equirectangular here for fun...
inter_fun=st_intersection(pol, pol2)

#  now for the results, showing the bias of different projections.
st_area(fin_a); truval-st_area(fin_a)
st_area(fin_l); truval-st_area(fin_l)
st_area(fin_st); truval-st_area(fin_st)
st_area(inter_fun); truval-st_area(inter_fun)

#  So it appears that equirectangular does the best job maintaining shape, so it is the most accurate for intersection, as long as you back-transform to 4326 for overlap area calc following intersection.

##  and it hold true if you go to a random location, like y+20, x+100
coords=rbind(c(a,a), c(b,a), c(b,b), c(a,b), c(a,a))
coord_rhalf=rbind(c(0,a), c(b,a), c(b,b), c(0,b), c(0,a))
plot(coords[,1]+10, coords[,2])
pol3=st_polygon(list(cbind(coords[,1]+100, coords[,2]+20)))
pol3b=st_polygon(list(cbind(coords[,1]+100.5, coords[,2]+20)))
pol3c=st_polygon(list(cbind(coord_rhalf[,1]+100, coord_rhalf[,2]+20)))
pol3=st_sfc(pol3); st_crs(pol3)=4326
pol3b=st_sfc(pol3b); st_crs(pol3b)=4326
pol3c=st_sfc(pol3c); st_crs(pol3c)=4326

st_area(pol3); st_area(pol3b); st_area(pol3c); truval2=st_area(pol3c)
#
st_area(st_intersection(pol3, pol3b)); truval2-st_area(st_intersection(pol3, pol3b))
pol3_a=st_transform(pol3, "+proj=aeqd +lat_0=20 +lon_0=100 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs") #aeqd
pol3b_a=st_transform(pol3b, "+proj=aeqd +lat_0=20 +lon_0=100 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs") #aeqd
st_intersection(pol3_a, pol3b_a) %>% st_transform(st_crs(4326)) %>% st_area()
truval2-st_intersection(pol3_a, pol3b_a) %>% st_transform(st_crs(4326)) %>% st_area()
#