text:
Q: Python Regex trying to find pattern that has two sets of optional characters I'm trying to use python regex on a pattern that has two sets of optional characters that may or may not be there.  Below is what I'm trying to accomplish.
h becomes a when h is preceded by o but can also be preceded by a colon (:)
following the o and then maybe followed by f,y,r (f|y|r)

So this rule would be applied to the following patterns.
o:fh -> o:fa
ofh -> ofa
o:h -> o:a
oh -> oa

Below is what I'm trying.
re.sub(ur"o[(:|)][(f|y|r)]h", "o\1\2a", word);

I'm really struggling with the grouping and the two sets of optional characters : and (f|y|r) that may or may not be there.  Any help is greatly appreciated.  Thanks!

A: Regex elements are made optional by following them with ?, not by enclosing them in brackets.  The correct way (well, a correct way) to write your expression is:
re.sub(ur"o(:?[fyr]?)h", ur"o\1a", word)

Note that the replacement string has to be raw (r" ") so that the \1 won't be interpreted as character 0x01.

A: Your syntax is incorrect, you are trying to use capturing groups inside of character classes.  In  simplest form, it lists the characters that may be matched inside square brackets ( matching any character from the list )

You can simply use one group, following the characters you want to be optional with ?
>>> re.sub(ur'(o:?[yrf]?)h', ur'\1a', word)

Explanation:
(          # group and capture to \1:
  o        #   'o'
  :?       #   ':' (optional)
  [yrf]?   #   any character of: 'y', 'r', 'f' (optional)
)          # end of \1
h          # 'h'

You could use the regex module which supports variable-length lookbehind.
>>> import regex
>>> regex.sub(r'(?<=o:?[yrf]?)h', 'a', word)


text:
Q: Where do I put my modules in an Elixir mix application? I have a simple project that I have started call test. So I did:
mix new test

and I got the usual directory tree. In the lib directory, is test.ex. But I want test.ex to use a module called Mystuff, but I don't know where to put mystuff.ex because I get a compile error.
Here is test.ex (in the test/lib directory):
defmodule Test do

  use Mystuff

  @moduledoc """
  Documentation for Test.
  """

  @doc """
  Hello world.

  ## Examples

      iex> Test.hello
      :world

  """
  def hello do
    Mystuff.bye()
  end
end

and here is mystuff.ex which I have also included in test/lib:
defmodule Test.Mystuff do
  def bye do
    IO.puts "bye"
  end
end

however if I run "iex -S mix" from the project's home directory (test) I get:
Erlang/OTP 19 [erts-8.2] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]

Compiling 3 files (.ex)

== Compilation error on file lib/test/mystuff.ex ==
** (CompileError) lib/test/mystuff.ex:1: cannot define module Test.Mystuff because it is currently being defined in lib/mystuff.ex:1
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6

So am I naming something wrong? Using something wrong? Putting something in the wrong directory?

A: Replace use Mystuff with alias Test.Mystuff.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ambiguous column name 'DELETED' when filtering Good morning.
Without saying to much, I am joining two tables where each contain a row with the same name field DELETED.
I am able to join both tables and get results, the problem is when I try to filter out those orders that are DELETED "X" and not DELETED "NULL", I get the ambiguous column name.
SELECT

OCRI.DDORD#,
OCRH.DCBCUS,
OCRI.DELETED

from ocri
join OCRH on DCORD# = DDORD#
where OCRI.dditst <> 'C'
and DELETED <> 'X'

I have tried and OCRI.DELETED <> 'X' but then I get no results.
I would like to be able to filter out the X
DDORD#  DCBCUS     DELETED
194991  150482      NULL
195000  263609      X
195381  263609      X
195387  246045      NULL
195724  146551      NULL

A: Qualify ALL column references in your query.  You haven't provided enough information to know which columns belong where.
Then, you need to handle NULL values.
An example:
SELECT rh.DDORD#, ri.DCBCUS, ri.DELETED
FROM ocri ri JOIN
     OCRH rh
     ON ri.DCORD# = rh.DDORD#
WHERE rh.rhdditst <> 'C' AND
      (ri.DELETED <> 'X' OR ri.DELETED IS NULL);

Of course, I don't know what the tables look like so the qualifications are probably wrong.
Note that standard SQL has a NULL-safe comparison, which is supported by some databases.  This looks like:
WHERE rh.rhdditst <> 'C' AND
      ri.DELETED IS DISTINCT FROM 'X';


text:
Q: GWT highcharts auto resize (width and height) in layout panel When you open a chart inside the center zone of a DockLayoutPanel (inside a RootLayoutPanel), the first time the chart is rendered (possibly during onModuleLoad) the chart does not have the right height/width. The chart take the size of the RootLayoutPanel not the size of the center zone.
When you resize the browser window, the chart resizes correctly. Does anyone knows how to fix this ?
@Override
public void onModuleLoad()
{
  RootLayoutPanel rootPanel = RootLayoutPanel.get();
  Chart chart = createChart();
  chart.setWidth100();
  chart.setHeight100();

  DockLayoutPanel dock1 = new DockLayoutPanel(Unit.PX);

  SimpleLayoutPanel slp1 = new SimpleLayoutPanel();
  slp1.getElement().getStyle().setBackgroundColor("blue");

  SimpleLayoutPanel slp2 = new SimpleLayoutPanel();
  slp2.getElement().getStyle().setBackgroundColor("yellow");

  SimpleLayoutPanel slp3 = new SimpleLayoutPanel();
  slp3.getElement().getStyle().setBackgroundColor("red");

  SimpleLayoutPanel slp4 = new SimpleLayoutPanel();
  slp4.getElement().getStyle().setBackgroundColor("green");

  dock1.addNorth(slp1, 50);
  // dock1.addSouth(slp3, 50);
  dock1.addWest(slp2, 50);
  // dock1.addEast(slp4, 50);

  dock1.add(chart);
  rootPanel.add(dock1);
}

For info i tried
 chart.redraw();
 rootPanel.forceLayout();

but it does not improve the situation
Github project example : https://github.com/mycom-int/gwthighcharts

A: The only sloution I found so far is to use a scheduler after the dock is added to rootpanel
      Scheduler scheduler = Scheduler.get();
      scheduler.scheduleDeferred(new ScheduledCommand()
      {

         @Override
         public void execute()
         {
            chart.setSizeToMatchContainer();
         }
      });

A: The solution is well described by Ronan Quillevere and available at the link he provided (https://github.com/mycom-int/gwthighcharts). However I would like to point out that the ChartSimpleLayoutPanel he provides as a helper container, must be added inside a container who implements the RequiresResize interface. This is a mandatory requirement to be sure the onResize() method of the ChartSimpleLayoutPanel is called to provide proper resize of the chart every time the browser window is resized.
To make some explicit example, if the container is a page implemented using uibinder, it is necessary that the page extends the ResizeComposite class and not the Composite class. Another maybe useful tip is that your container must not be contained in a FlowPanel because FlowPanel breaks the RequiresResize mechanism.
Hope this helps.

A: Another option can be to extend Chart class and implement RequiresResize. In the onResize method schedule setSizeToMatchContainer().


text:
Q: Error when posting data values in PHP Whenever I try to post data values in PHP I get the following error:

Fatal error: Uncaught exception
  'Exception' with message
  'DateTime::__construct() [datetime.--construct]: Failed to parse time string (this
  wednesday G:i A) at position 16 (:):
  Unexpected character' in
  C:\xampp\htdocs\keypad\end.php:14
  Stack trace: #0
  C:\xampp\htdocs\keypad\end.php(14):
  DateTime->__construct('this wednesday
  ...') #1 {main} thrown in
  C:\xampp\htdocs\keypad\end.php on line
  14

Here is the code I'm using:
<?php require_once('Connections/rent.php'); ?>
<?php

// post

$id = $_GET['id'];
$user = $_GET['user'];
$week = $_GET['week'];
$pRent = $_GET['pRent'];
$status = $_GET['status'];
$rentPaid = $_GET['rentPaid'];
$result = $_GET['result'];
$pDate = date("d/m/Y G:i A");
$lDate = new DateTime('this wednesday G:i A');
$cDate = new DateTime('next tuesday G:i A');

// update

mysql_query("UPDATE rent SET dNo = '$dNo', pdate = '$pDate', pRent = '$result' WHERE rent.id = $id");

// if pRent = 0 then set status to clear, colour to #3C0
if ($pRent == 0 ) {
    mysql_query("UPDATE rent SET status = 'clear', colour = '#3C0' WHERE rent.id = $id");
}

// if pRent =! 0 but just paid then set status to paid/not clear, colour to #FF0
elseif ($pRent =! 0 ) {
    mysql_query("UPDATE rent SET status = 'paid', colour = '#3C0' WHERE rent.id = $id");
}

// if status = on holiday, then set status to clear, colour to #3C0
elseif ($status == 'awaiting' ) {
    mysql_query("UPDATE rent SET status = 'awaiting', colour = '#09F' WHERE rent.id = $id");
}

// check all drivers who have/have not paid rent in the past week
elseif ($lDate < $pDate && $cDate > $pDate) {
    //  date is within desired range
    mysql_query("UPDATE rent SET status = 'paid', colour = '#3C0'");
} else {
    // date is not within desired range
    mysql_query("UPDATE rent SET status = 'awaiting', colour = '#09F' WHERE rent.status =! 'not working'");
}
?>

Any suggestions?

A: You have a problem on line 14, $lDate = new DateTime('this wednesday G:i A') is invalid, take a look at Relative DateTime formats for a list of valid ones. What you need to do is:
 $lDate = new DateTime('this wednesday')
 $lDate->format('G:i A');

Just a suggestion, first two lines should be
 <?php
     require_once 'Connections/rent.php';

And please consider using PDO or another similar library, or at least sanitize your SQL queries.


text:
Q: AngluarJS filter table population by user id I'm trying to filter a GET call by user id.  I keep getting an error that says the userId is undefined.  I'm not entirely sure how to properly set up my factory.  Do I need to put a getter and setter in my factory?
Factory:
angular.module('myApp').factory('homeFactory',['$http', function($http){
            return{

                // GETS current user that is logged in.
                getCurrentUser: function(){
                    return $http.get("user/getCurrent")
                },

                getAllReports: function(userId){
                    return $http.get('report/user/' + userId)
                }
            }
    }])

controller:
angular.module('myApp').controller('homeController',
        ['$scope', '$compile', '$element', 'homeFactory','toastr',
         function($scope, $compile, $element, homeFactory, toastr){

    // Retrieves the current user that is logged into the app.
    $scope.getCurrentUser = homeFactory.getCurrentUser().then(
    function(success){
        $scope.currentUser = success.data;
    },
    function(error){
        $scope.currentUser = error;
    });

    //Trying to get all reports by the userId
    $scope.getAllReports = homeFactory.getAllReports($scope.currentUser).then(
    function(success){
        $scope.reportName = success.data;
        console.log(reportName);
        },
    function(error){
        $scope.reportName = error;
    });

}])

Thank you very much in advance for any help!

A: I think you should just put
$scope.getAllReports = homeFactory.getAllReports($scope.currentUser).then(
function(success){
    $scope.reportName = success.data;
    console.log(reportName);
},
function(error){
    $scope.reportName = error;
});

inside first promise success function:
function(success){
    $scope.currentUser = success.data;
}

A: $scope.getCurrentUser = homeFactory.getCurrentUser().then(
function(success){
    $scope.currentUser = success.data;
    console.log($scope.currentUser);
    $scope.getAllReports = homeFactory.getAllReports($scope.currentUser.userId).then(
            function(success){
                $scope.reportName = success.data;
                console.log()
                },
            function(error){
                $scope.reportName = error;
            });
},
function(error){
    $scope.currentUser = error;
});


text:
Q: Android- Draw line between two views Below is my program where I have created three new views in a frame. On click of two different views I want to draw a line between the views. I am trying to figure out how to do this...
    Ball ball1=new Ball(this,100,100,45);
    Ball ball2=new Ball(this,400,100,45);
    Ball ball3=new Ball(this,250,350,45);
    FrameLayout frame1=(FrameLayout) findViewById(R.id.main_view);
    frame1.addView(ball1);
    frame1.addView(ball2);
    frame1.addView(ball3);

      frame1.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()){
            case MotionEvent.ACTION_DOWN: {
                float x = event.getX();
                float y = event.getY();
                System.out.println("x:"+x+"y:"+y);
                if (x>55 && x<142 && y>55 && y<142)
                    {
                    System.out.println("working1 "+count);
                    Toast toast = Toast.makeText(getBaseContext(), "Works fine", Toast.LENGTH_SHORT);
                    toast.show();
                }

A: For a draw line between your two views.
Create class for view which draw a line.
public class DrawView extends View {
    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);
        paint.setColor(Color.BLACK);
    }

    @Override
    public void onDraw(Canvas canvas) {
            canvas.drawLine(0, 50, 350, 50, paint);
    }

}

now from your activtiy where you want to add this line in your layout.
Create object of this class and add this view in your layout.
According to your requirment try like this.
DrawView drawView;
drawView = new DrawView(this);
frame1.addView(ball1);
                            // add that view here
frame1.addView(drawView);
frame1.addView(ball2);
                            // same way here
frame1.addView(ball3);

A: Just draw line in onDraw() on some condition and set this condition in your activity in onTouch() method. Then call invalidate on Views that you changed their condition.


text:
Q: How am I misunderstanding the C++ standard regarding "trivially copyable"? The static assert in the code below fails.
Of course, I know that this is because of the user-provided move constructor in Bar.
#include <type_traits>

using namespace std;

struct Bar
{
public:
    Bar()               = default;
    Bar(const Bar&)     = default;
    ~Bar()              = default;

    Bar(Bar&&)
    {
    }
};

struct Foo
{
    Bar b;

    Foo()                           = default;
   ~Foo()                           = default;
    Foo(const Foo&)                 = default;
    Foo(Foo&&)                      = delete;
    Foo & operator= (Foo && )       = delete;
    Foo & operator= (const Foo & )  = delete;
};

static_assert(is_trivially_copyable_v<Foo>);  // Fails

What I don't understand is how to interpret the standard regarding trivial copyability.  From the C++ 17 standard:

A trivially copyable class is a class:
(6.1)
where each copy constructor, move constructor, copy assignment operator, and move assignment operator ([class.copy], [over.ass]) is either deleted or trivial,
(6.2)
that has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator, and
(6.3)
that has a trivial, non-deleted destructor.

It seems to me the Foo meets these criteria:
6.1: They're all deleted except the copy constructor which is trivial. Bar also has a trivial copy constuctor, so that should ensure the Foo copy contructor is truly trivial.
6.2: The defaulted copy constructor
6.3: Foo destructor is defaulted and so is the Bar one, so the destructor should be trivial.
What am I not getting?
By the way I'm not actually trying to do anything apart from better understand the standard.

A: Except I miss something fundamentally further on here, I think there's currently no actual vague statement about this within the standard, it's actually quite straight forward on my opinion and that means, you're right. Your class Foo should be trivially copyable.
Beginning at top-level for your class Foo:
class6 says:

A trivially copyable class is a class:
(6.1) where each copy constructor, move constructor, copy assignment
operator, and move assignment operator ([class.copy], [over.ass]) is
either deleted or trivial,
(6.2) that has at least one non-deleted copy constructor, move
constructor, copy assignment operator, or move assignment operator,
and
(6.3) that has a trivial, non-deleted destructor.

Points 2) and 3) are trivial and fulfilled.
Point 1): The only constructor of relevance here, that is not deleted, is the copy constructor. So is it trivial?
class.copy#ctor-11 answers that:

11
A copy/move constructor for class X is trivial if it is not user-provided and if:
(11.1) class X has no virtual functions and no virtual base classes,
and
(11.2) the constructor selected to copy/move each direct base class
subobject is trivial, and
(11.3) for each non-static data member of X that is of class type (or
array thereof), the constructor selected to copy/move that member is
trivial;
otherwise the copy/move constructor is non-trivial.

Again, points 1) and 2) are trivial and fulfilled. For point 3, the standard uses the terminus "copy/move", not copy and move, emphasizing the dual distinguished orthogonal(!) nature here (common and straight forward scheme within the drafts). Since there's a trivial non-deleted copy constructor available for Bar, there's no chance for any trouble here reading the standard strictly, since how should the selected copy constructor for the bar member be the user-defined move constructor (see memberwise copy for the default copy constructor)? The "decay" to the copy-construction way if no selectable move constructor could be found the other way around would be plausible though, but that's not the case here.

A: (6.1) where each copy constructor, move constructor, copy assignment operator, and move assignment operator ([class.copy], [over.ass]) is either deleted or trivial.
A user defined constructor is not trivial. Therefore your user defined move constructor makes your object non trivial.
More here: What is a non-trivial constructor in C++?


text:
Q: How to Output the Index of an Element in array This was the task:
Design, implement and test programs to do each of the following:
a)        Find the sum and number of positive integers in a list of 10 integers.
b)        Find the smallest number in a list of 10 integers.
c)  Determine and output the biggest and smallest numbers in a list of 10 integers.
 The output should be of the form :
"The biggest number 304 was at position 3 in the list"
"The smallest number 4 was at position 8 in the list"
So I tried it and the Problem is that everything works except to give me the position of the biggest and smallest number.
    import java.util.Arrays;

public class a5_2 {
    @SuppressWarnings("unlikely-arg-type")
    public static void main (String [] args) {

        int m [] = {-3,23,7,12,4,-44,2,21,3,43} ;

        System.out.println("Array: " + Arrays.toString(m));
        int[] pos = findNumber(m);
            System.out.println("Array without negatives: ");
                for (int i = 0; i < pos.length; i++)
                    {
                        System.out.println(pos[i]);
                    }

        System.out.println("Number of pos num: " + pos.length);
            int sum = 0;
                for (int i : pos)
                    sum += i;
        System.out.println("Sum of pos num: " + sum);

        int [] small = findSmallest(pos);
                System.out.println("Smallest Number: ");
                System.out.println(small[0] + " at pos: " + Arrays.asList(pos).indexOf(small[0]));

        int [] big = findBiggest(pos);
                System.out.println("Biggest Number: ");
                System.out.println(big[0] + " at pos: " + Arrays.asList(pos).indexOf(big[0]));
        }

        public static int [] findNumber(int[] sum) {
            int num = 0;
            int n [] = new int [sum.length];
                    for(int i = 0; i < sum.length; i++)
                    {
                        if (sum[i] > 0)
                        {
                            n[num] = sum[i];
                            num++;
                        }
                    }
            int [] pos =  new int [num];
                for (int k = 0 ; k < num ; k++)
                {
                    pos[k] = n[k];
                }

            return pos;

        }
    public static int [] findSmallest(int[] pos) {
        int temp;
        for (int i = 0; i < pos.length; i++)
        {
            for (int j = i + 1; j < pos.length; j++)
            {

                if (pos[i] > pos[j])
                    {
                        temp = pos[i];
                        pos[i] =pos[j];
                        pos[j] = temp;
                    }
            }
        }
        return pos;

    }
    public static int [] findBiggest(int[] pos) {
        int temp;
        for (int i = 0; i < pos.length; i++)
        {
            for (int j = i + 1; j < pos.length; j++)
            {

                if (pos[i] < pos[j])
                    {
                        temp = pos[i];
                        pos[i] =pos[j];
                        pos[j] = temp;
                    }
            }
        }
        return pos;

    }
}

Output of the position is -1 instead of the output it should give.
Thank you guys in advance :)

A: Arrays.asList(pos) is converting into List<int[]> convert it into List<Integer> and then get the index
List<Integer> comArray = Arrays.stream(m).boxed().collect(Collectors.toList());

System.out.println(small[0] + " at pos: " + comArray.indexOf(small[0]));

In java-7, i believe you know already how to convert int[] to List<integer>
 List<Integer> comArray = new ArrayList<>();

        List<Integer> intList = new ArrayList<Integer>();
        for (int i : m)
        {
            intList.add(i);
        }

Verified Code
 @SuppressWarnings("unlikely-arg-type")
    public static void main (String [] args) {

        int m [] = {-3,23,7,12,4,-44,2,21,3,43} ;

        List<Integer> comArray = Arrays.stream(m).boxed().collect(Collectors.toList());

        System.out.println("Array: " + Arrays.toString(m));
        int[] pos = findNumber(m);
            System.out.println("Array without negatives: ");
                for (int i = 0; i < pos.length; i++)
                    {
                        System.out.println(pos[i]);
                    }

        System.out.println("Number of pos num: " + pos.length);
            int sum = 0;
                for (int i : pos)
                    sum += i;
        System.out.println("Sum of pos num: " + sum);

        int [] small = findSmallest(pos);
                System.out.println("Smallest Number: ");
                System.out.println(small[0] + " at pos: " + comArray.indexOf(small[0]));

        int [] big = findBiggest(pos);
                System.out.println("Biggest Number: ");
                System.out.println(big[0] + " at pos: " + comArray.indexOf(big[0]));
        }

        public static int [] findNumber(int[] sum) {
            int num = 0;
            int n [] = new int [sum.length];
                    for(int i = 0; i < sum.length; i++)
                    {
                        if (sum[i] > 0)
                        {
                            n[num] = sum[i];
                            num++;
                        }
                    }
            int [] pos =  new int [num];
                for (int k = 0 ; k < num ; k++)
                {
                    pos[k] = n[k];
                }

            return pos;

        }
    public static int [] findSmallest(int[] pos) {
        int temp;
        for (int i = 0; i < pos.length; i++)
        {
            for (int j = i + 1; j < pos.length; j++)
            {

                if (pos[i] > pos[j])
                    {
                        temp = pos[i];
                        pos[i] =pos[j];
                        pos[j] = temp;
                    }
            }
        }
        return pos;

    }
    public static int [] findBiggest(int[] pos) {
        int temp;
        for (int i = 0; i < pos.length; i++)
        {
            for (int j = i + 1; j < pos.length; j++)
            {

                if (pos[i] < pos[j])
                    {
                        temp = pos[i];
                        pos[i] =pos[j];
                        pos[j] = temp;
                    }
            }
        }
        return pos;

    }

 }

Output
Array: [-3, 23, 7, 12, 4, -44, 2, 21, 3, 43]
Array without negatives:
23
7
12
4
2
21
3
43
Number of pos num: 8
Sum of pos num: 115
Smallest Number:
2 at pos: 6
Biggest Number:
43 at pos: 9

A: because Arrays.asList(pos) return List<int[]> not List<Integer>.


text:
Q: How to calculate area of polygon that does not overlap with other polygons in R? I have a SpatialPoints object with the coordinates for several points of interest.
I also have several shapefiles (polygons) with information about the presence of slums. The polygons with info about slums in each of these shapefiles can overlap (they provide somewhat the same information about the presence of slums, but come from different sources).
For each of the points in my SpatialPoints object, I have used the function spCircle to create a circular polygon around each point. What I need to do next is to check what percentage of the area of the circular polygon contains slums. If any of the shapefiles indicates that the slum is present, I will consider that there is a slum in the area.
I have created the following image to help explain my issue. The circles represent the polygon around a single point. For this single point, each of the four shapefiles indicates that the slum is present in somewhat different areas (sometimes they overlap, and sometimes they do not). I want to be able to find the red area (where none of the shapefiles indicate the presence of the slum, and then calculate the percentage of the circle that has slums.

The following code is an attempt to do that:
# Create data with coordinates

lat = c(-22.868879628748203,-22.88511,-22.82166,-22.89692,-22.67945)
long = c(-43.237195000177564,-43.34278,-43.04717,-43.35168,-43.59667)

data_points = cbind.data.frame(lat,long)

coordinates(data_points) = c("lat","long")
proj4string(data_points) = CRS("+init=epsg:4326")

# Transform projection of points to UTM

utmStr <- "+proj=utm +zone=%d +datum=NAD83 +units=m +no_defs +ellps=GRS80"
crs <- CRS(sprintf(utmStr, 23))
data_points = spTransform(data_points, crs)

# Create a list with circular polygons around each point (radius = 2000 meters)

circular_grid = list()

for (i in 1:length(data_points)){

  spc = spCircle(radius = 2000, centerPoint = c(x=as.numeric(data_points@coords[i,1]), y=as.numeric(data_points@coords[i,2])), spID=i,
                 spUnits = CRS("+proj=utm +zone=23 +datum=NAD83 +units=m +no_defs"))
  circular_grid[[i]] = spc
}

# For each circle, check the percentage that overlaps with several different shapefiles:

# I first use gUnion to merge all the shapefiles with info about slums together

allShapes = gUnion(shape1,shape2)
allShapes = gUnion(allShapes, shape3)
allShapes = gUnion(allShapes, shape4)
allShapes = gUnion(allShapes, shape5)
allShapes = gUnion(allShapes, shape6)
allShapes = as(allShapes, "SpatialPolygonsDataFrame")

allShapes = spTransform(allShapes, CRS("+proj=utm +zone=23 +datum=NAD83 +units=m +no_defs"))

# I am unable to reproduce the object "allShapes" (I do not know how),
# but this is its information

# class       : SpatialPolygonsDataFrame
# features    : 1
# extent      : 633347.1, 724692.1, -2547787, -2513212  (xmin, xmax, ymin, ymax)
# crs         : +proj=utm +zone=23 +datum=NAD83 +units=m +no_defs
# variables   : 1
# names       : dummy
# value       :     0

# Next, to get the intersection, I tried the following:

intersection_circle_shape = list()

for (i in 1:length(circular_grid)){

  circle = circular_grid[[i]][["spCircle"]]

  inter = intersect(circle, allShapes)

  intersection_circle_shape[[i]] = inter

}

# The list "intersection_circle_shape" is empty because the command
# "intersect" says that there is no intersection, but I know there is.

Any ideas?


text:
Q: read SQLite db file using java I want to read a SQLite db file using Java. Will you please tell me how to read it?

A: The Java JDBC driver for SQLLite is on the David Crawshaw site http://www.zentus.com/sqlitejdbc/ Add the jar file to your class path and import java.sql.* and you should be good.

A: First read these answers
David Crawshaw developed a JAR file (still available on github here but not touched for 10+ years). Taro Saito has a self-contained straightforward JAR file available on github here that includes the JDBC driver and the native runtimes required. Just add this JAR file to your classpath and import java.sql.*
David's test app will create a database file, send some SQL commands to create a table, store some data in the table, and read it back and display on console. It will create the test.db file in the root directory of the project.
public class Test {
    public static void main(String[] args) throws Exception {
        Class.forName("org.sqlite.JDBC");
        Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
        Statement stat = conn.createStatement();
        stat.executeUpdate("drop table if exists people;");
        stat.executeUpdate("create table people (name, occupation);");
        PreparedStatement prep = conn.prepareStatement(
            "insert into people values (?, ?);");

        prep.setString(1, "Gandhi");
        prep.setString(2, "politics");
        prep.addBatch();
        prep.setString(1, "Turing");
        prep.setString(2, "computers");
        prep.addBatch();
        prep.setString(1, "Wittgenstein");
        prep.setString(2, "smartypants");
        prep.addBatch();

        conn.setAutoCommit(false);
        prep.executeBatch();
        conn.setAutoCommit(true);

        ResultSet rs = stat.executeQuery("select * from people;");
        while (rs.next()) {
            System.out.println("name = " + rs.getString("name"));
            System.out.println("job = " + rs.getString("occupation"));
        }
        rs.close();
        conn.close();
    }
  }


text:
Q: RxJava How to return more than 2 ArrayLists within Observable in a function I'm able to pass two lists via observable as it is mentioned below
fun loadAll(contact: String?): Single<Pair<ArrayList<Contact>, ArrayList<Contact>>> {
    return packageDB.loadAll()
        .map { table ->
            val one = ArrayList< Contact >()
            val two = ArrayList< Contact >()
            val three = ArrayList< Contact >()

            one to two
        }
}

And in Fragment, I'm trying to return as:
  disposables.add(
        viewModel.loadAll(contact)
            .subscribe({
                val firstList = it.first
                val secondList = it.second
                val third = ArrayList<Contact>()
 }))

I'm new to reactive programming so I'm unable to understand how I can pass or return more than two lists as Pair object can have two child objects only. I would be thankful if you can let me know the solution.

A: There is more than one way of doing this, I can list some. You simply have to think of the return object. If you want to return 3 things only, I wouldn't even bother with creating a specific class if it's clear what you're doing. Kotlin has already a class for this - Triple. It's like a pair, but holds 3 values:
fun loadAll(contact: String?): Single<Triple<ArrayList<Contact>, ArrayList<Contact>, ArrayList<Contact>>> {
    return packageDB.loadAll()
        .map { table ->
            val one = ArrayList< Contact >()
            val two = ArrayList< Contact >()
            val three = ArrayList< Contact >()

            Triple(one, two, three)
        }
}

And then access them as:
disposables.add(
        viewModel.loadAll(contact)
            .subscribe({
                val firstList = it.first
                val secondList = it.second
                val third = it.third
 }))

If you have more than 3 values, I'm not sure if there's already a class for this, but there's always the option of using arrays of arrays:
fun loadAll(contact: String?): Single<Array<ArrayList<Contact>> {
    return packageDB.loadAll()
        .map { table ->
            val one = ArrayList< Contact >()
            val two = ArrayList< Contact >()
            val three = ArrayList< Contact >()

            arrayListOf(one, two, three)
        }
}

disposables.add(
        viewModel.loadAll(contact)
            .subscribe({ (firList, secondList, thirdList) ->
                  // the above destructures the list into 3 variables
                  // if the list has less than 3 elements you'll get an index out of bounds exception
                  // otherwise you can just use the variables
 }))

As pointed out in the comments, this might create some problems understanding what each value is, so sometimes it's better to create your own class:
data class Values(
   val primaryContacts: ArrayList< Contact >(),
   val secondaryContacts: ArrayList< Contact >(),
   val emergencyContacts: ArrayList< Contact >(),
)

fun loadAll(contact: String?): Single<Values> {
    return packageDB.loadAll()
        .map { table ->
            val one = ArrayList< Contact >()
            val two = ArrayList< Contact >()
            val three = ArrayList< Contact >()

            Values(one, two, three)
        }
}

disposables.add(
        viewModel.loadAll(contact)
            .subscribe({
                val firstList = it.primaryContacts
                val secondList = it.secondaryContacts
                val third = it.emergencyContacts
 }))

please excuse the naming. It's just an example.


text:
Q: Jquery: How can I make a figure element collapsible? How can I make a figure element collapsible, without adding an extra button?

By default, I would like to place a button to open the image at this point. Can this button be generated automatically?

A: You can use the slideToggle() function assuming you have jQuery included (HIGHLY RECOMMEND).
Then you can simply do:
$( "#myButton" ).click(function() {
  $( "figure" ).slideToggle( "slow" );
});

You will need to of course add a button. You could append one with jQUery (automatically) or you can edit the HTML to get it there.
Here is the HTML way
<button id="myButton">Click Me</button>

Here is the jQuery way (untested)
$('figure').append("<button id='myButton'>Click Me</button>");

Best of Luck to You! (again this is all untested)
Come to think of it you probably want after() instead of append()
because your button will disappear after you toggle once.
Use this
$('figure').after("<button id='myButton'>Click Me</button>");

Link to jQuery slideToggle: http://api.jquery.com/slidetoggle/

A: Check out this simple code snippet to toggle image using figure element itself

$('#accordian_img').click(function () {
    $('.img-toggle').toggleClass("show"); // toggle show class to image element
});
/* Image style to show and hide */
.img-toggle.show {
  display:block;
}
.img-toggle {
  display:none;
}

  Click To Toggle Image


text:
Q: Get context in cordova plugin Hi I'm using this GCM notification plugin for android and works almost perfect, the only issue I have is when the user force close my app or when the device is shutted down the notification service stops working.
I've looked the plugin code problem and realized that the following function causes the problem.
     public static void sendJavascript( JSONObject _json )
      {
        String _d =  "javascript:"+gECB+"(" + _json.toString() + ")";
            Log.v(ME + ":sendJavascript", _d);

            if (gECB != null ) {
              gwebView.sendJavascript( _d );
            }
}

When the device is shutted down and then turned on or the application is force closed, gwebView reference is lost. If I try to use the method gwebView.sendJavascript( _d ) I get a null pointer exception.
Reviewing the plugin code I noticed that gwebView is referenced when registering the device just as this code shows:
public static Plugin gwebView;
  private static String gECB;
  private static String gSenderID;

  @SuppressWarnings("deprecation")
@Override
  public PluginResult execute(String action, JSONArray data, String callbackId)
  {

    PluginResult result = null;

    Log.v(ME + ":execute", "action=" + action);

    if (REGISTER.equals(action)) {

      Log.v(ME + ":execute", "data=" + data.toString());

      try {

        JSONObject jo= new JSONObject(data.toString().substring(1, data.toString().length()-1));

        gwebView = this;

..............................More code here......................

The notifications are received on background but I can't invoke any javascript methods since gwebView points nothing.
My approach is to show a generic notification on statusbar whenever gwebView has a null pointer but I just don't know how to get the application or cordova context in order to use this function.
Any help would be appreciated, thanks

A: I found in google forums that this is a bug of the plugin so I decided to use Pushwhoosh notification service.


text:
Q: Formulating mathematical model that minimizes the largest deviation between the data and the line Can someone help me and explain all the steps of solving this problem which is in the field of Model Fitting and Least-Squares Fit. Thank you.
PROBLEM:  For each of the following data sets, formulate the mathematical model that minimizes the largest deviation between the data and the line y = ax+b. If a computer is available, solve for the estimates of a and b.
x: 1.0 ,  2.3 ,  3.7  , 4.2 ,  6.1 ,  7.0.
y: 3.6  , 3.0 , 3.2  ,  5.1  , 5.3  , 6.8.


text:
Q: How do I subtract time with a variable value in php? I'm trying to create a clock that allows users to select which timezone they are in which updates the clock based on timezone. The variable $timezone is whatevers selected which is an integer between -11 & 12, however I receive the error "A non well formed numeric value encountered"
I've tried converting the integer to a datetime but on the examples on here is subtracting two fixed DateTimes, also i've tried converting the integer to DateTime but that didn't work.
<html>
<head>
</head>
    <body>
        <form action="#" method="post">
            <select id="timezone" name="timezone">
                <option name="time" value=" ">--Select Timezone--</option>
                <option name="time" value="-11">GMT-11</option>
                <option name="time" value="-10">GMT-10</option>
                <option name="time" value="-9">GMT-9</option>
                <option name="time" value="-8">GMT-8</option>
                <option name="time" value="-7">GMT-7</option>
                <option name="time" value="-6">GMT-6</option>
                <option name="time" value="-5">GMT-5</option>
                <option name="time" value="-4">GMT-4</option>
                <option name="time" value="-3">GMT-3</option>
                <option name="time" value="-2">GMT-2</option>
                <option name="time" value="-1">GMT-1</option>
                <option name="time" value="0">GMT</option>
                <option name="time" value="1">GMT+1</option>
                <option name="time" value="2">GMT+2</option>
                <option name="time" value="3">GMT+3</option>
                <option name="time" value="4">GMT+4</option>
                <option name="time" value="5">GMT+5</option>
                <option name="time" value="6">GMT+6</option>
                <option name="time" value="7">GMT+7</option>
                <option name="time" value="8">GMT+8</option>
                <option name="time" value="9">GMT+9</option>
                <option name="time" value="10">GMT+10</option>
                <option name="time" value="11">GMT+11</option>
                <option name="time" value="12">GMT+12</option>
            </select>
            <input type="submit">
        </form>
    </body>
</html>

    <?php
      add_action( 'wp_enqueue_scripts', 'displayHTMLpage' );

      function displayHTMLpage() {
          include( 'index.html' );
      }

      $dateFormat="H:i:s";
      $gmt = gmdate($dateFormat, time());

      echo $gmt;

      if(isset($_POST['timezone']))
      {
      $timezone = $_POST['timezone'];
      $time = $gmt + $timezone;
      echo $time;
      }

    ?>


text:
Q: Custom react hook is not fetching values I have a custom react hook written that is supposed to fetch a list of categories from a firebase firestore. I then map over this return array to display a list of the categories to the user.
However when I call the custom hook it is not creating the list on the front-end. When I console.log the array it first logs null then logs the correct list. I have a feeling that the react component that display the list is trying to display the first value that gets returned which is null.
Below is my custom hook and the component that returns to list:
import { useState, useEffect } from 'react';
import firebase from '../firebase/firebase';

function useCategories() {

  const [categories, setCategories] = useState(null);

  useEffect(() => {
    const unsubscribe = firebase
        .firestore()
        .collection('categories')
        .onSnapshot((snapshot) => {
            const fetchedCategories = snapshot.docs.map((document) => (
                document.data().name
            ))
            setCategories(fetchedCategories)
        })

    return () => unsubscribe() // drop subscription to firestore once components unmounts
  }, []);

  return categories
}

export default useCategories;

import React from 'react';
import useCategories from '../helpers/useCategories';

const CategoriesList = () => {

    const categories = useCategories();

    return (

            {categories && categories.map(category => (

                    {category.name}

            ))}

    );
}

export default CategoriesList;

I feel like this is probably an easy fix but I have brain mush
Cheers


text:
Q: how to solve Poisson equation of inhomogeneous boundary condition by Galerkin method? I'm working on solving 2D Poisson equation with source term f on irregular domain. Assuming I have a function u(x,y) which satisfy the inhomogeneous boundary condition, and I choose my Orthogonal basis function as:inhomogeneous base function, because I think poisson equation makes the problem satisfy homogeneous boundary condition. Then the final solution is final result, the coefficient is achieved through integration on the domain by the definition of galerkin method.
I want to know the whether the method is feasible? if not, how can I make it feasible?
Thanks!


text:
Q: Monitor widget missing from Jupyter What code or configuration or steps to take to restore monitor widget to EMR Jupyter Notebook?
https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-spark-monitor.html
Found this:
https://forums.aws.amazon.com/thread.jspa?threadID=308132
(It is dated August 15, 2019)
sc
Starting Spark application
ID  YARN Application ID Kind    State   Spark UI    Driver log  Current session?
36  application_blahblahblahsomenumber  pyspark idle    Link    Link    ✔
SparkSession available as 'spark'.

But running normal program doesn't show expected monitoring
like number of partitions, seconds elapsed, etc.

It just runs silently with no clue but for the asterisk next to code
In [*]
What gives?
See the graphic in the section under:
"The following is an example of the Spark job monitoring widget.
from the page"
On this page:
https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-spark-monitor.html

A: This issue has been fixed in latest EMR notebooks update.


text:
Q: Find the Median Date between two dates using Java 8 I'm finding it difficult that what it sounds.
So, I have a max date and a min date and I need to find the median date between these two dates. I use Java 8 to find my max and min dates,
LocalDate gerbutsmin = YearMonth.now().plusMonths(2).atDay(1);
LocalDate gerbutsmax = YearMonth.now().plusMonths(15).atDay(1);

How would I go ahead after this? Maybe I need to switch back to Calander?

A: Try using DAYS.between():
LocalDate gerbutsmin = YearMonth.now().plusMonths(2).atDay(1);
LocalDate gerbutsmax = YearMonth.now().plusMonths(15).atDay(1);
long numDays = ChronoUnit.DAYS.between(gerbutsmin, gerbutsmax);
LocalDate median = gerbutsmin.plusDays(numDays / 2L);  // plusDays takes a long
System.out.println(median);

2019-03-17
(output as of today, which is 2019-07-26)

Demo
There is a boundary condition should the difference between your min and max dates be an odd number.  In this case, there is no formal median day, but rather the median would fall in between two days.
Note:
If you're wondering what happens exactly in the edge case, if the low date were today (2018-07-26) and the high date three days away (2018-07-29), then the median would be reported as 2018-07-27.

A: LocalDate gerbutsmin = YearMonth.now().plusMonths(2).atDay(1);
LocalDate gerbutsmax = YearMonth.now().plusMonths(15).atDay(1);

LocalDate median = gerbutsmin.plusDays(ChronoUnit.DAYS.between(gerbutsmin, gerbutsmax) / 2);

A: "Middle of two dates" is not unambiguously defined - you must decide how to handle dates an odd number of days apart (e.g. what is the middle date between 1st and 4th of a month, or between 1st and 2nd), and what to do with the time portion of the date object.
The concrete problem with your approach is that dates are not numbers, so you cannot add them and divide them by two. To do that, use the getTime() method to obtain the number of seconds since the epoch, and operate on that:
var middate = new Date((startdate.getTime() + enddate.getTime()) / 2.0);

This will give you the middle between two dates, treating them as points in time.
Click here

A: LocalDateTime startime = LocalDateTime.now();
LocalDateTime endtime = startime.plusDays(4);

long diff = endtime.until(startime, ChronoUnit.MINUTES);
LocalDateTime middleTime = startime.plusMinutes(diff / 2);


text:
Q: What is the replacement class for SerializerBase in FasterXML Jackson 2? I am upgrading to Jackson 2. I have many custom serializers extending SerializerBase (org.codehaus.jackson.map.ser.std.SerializerBase). What's the new equivalent class in Jackson 2

A: Looks like StdSerializer is the new replacement (com.fasterxml.jackson.databind.ser.std.StdSerializer)


text:
Q: Can I store raster data in a spatialite database (in QGIS)? This might be a super simple question, but I'm a little confused. I don't know what the best way is to share qgis-projects that have raster-data, vector-data and some applied styling. I figured a database would be a good option. And as a spatialite-database can be shared easily, that might be a good option.
But I don't manage to put a raster into it. I think there is some extension-driver called RasterLite, but I also don't know how this works properly...

A: Try using a geopackage format.
In geopackage you can store vector/raster layers, symbology and the same qgis project (from: project => Save to...)


text:
Q: Print all diffrent patterns from a line if there are any using grep/awk myapp.log.2015-03-31:in<username|password>version=1.1.8,type=Login

I want to print only "username" and "version" from this line. If I use
grep -o "username"

it will print only usernames. Similarly if I use
grep -o "version.*,"

it will print out all version numbers. Is there any way that I could print both username and version number together?
like
"username" version=1.1.8,

A: You can use regex alternation:
s='myapp.log.2015-03-31:in<username|password>version=1.1.8,type=Login'
grep -Eo "username|version.*," <<< "$s" | tr '\n' ' '
username version=1.1.8,

A: This should do it:
grep -oP "username|version.*(?=,)"

This will omit the comma after version: version=1.1.8
If you don't want that then simply:
grep -oP "username|version.*,"
#grep -oE "username|version.*,"


text:
Q: Differences between OT and CRDT Can someone explain me simply the main differences between Operational Transform and CRDT?
As far as I understand, both are algorithms that permits data to converge without conflict on different nodes of a distributed system.
In which usecase would you use which algorithm?
As far as I understand, OT is mostly used for text and CRDT is more general and can handle more advanced structures right?
Is CRDT more powerful than OT?

I ask this question because I am trying to see how to implement a collaborative editor for HTML documents, and not sure in which direction to look first. I saw the ShareJS project, and their attempts to support rich text collaboration on the browser on contenteditables elements. Nowhere in ShareJS I see any attempt to use CRDT for that.
We also know that Google Docs is using OT and it's working pretty well for real-time edition of rich documents.
Is Google's choice of using OT because CRDT was not very known at that time? Or would it be a good choice today too?
I'm also interested to hear about other use cases too, like using these algorithms on databases. Riak seems to use CRDT. Can OT be used to sync nodes of a database too and be an alternative to Paxos/Zab/Raft?

A: Both approaches are similar in that they provide eventual consistency. The difference is in how they do it. One way of looking at it is:

*

*OT does it by changing operations. Operations are sent over the wire and concurrent operations are transformed once they are received.

*CRDTs do it by changing state. Operations are made on the local CRDT. Its state is sent over the wire and is merged with the state of a copy. It doesn't matter how many times or in what order merges are made - all copies converge.

You're right, OT is mostly used for text and does predate CRDTs but research shows that:

many OT algorithms in the literature do not satisfy convergence properties
  unlike what was stated by their authors

In other words CRDT merging is commutative while OT transformation functions sometimes are not.
From the Wikipedia article on CRDT:

OTs are generally complex and non-scalable

There are different kinds of CRDTs (sets, counters, ...) suited for different kinds of problems. There are some that are designed for text editing. For example, Treedoc - A commutative replicated data type for cooperative editing.

A: One another notable difference is that:

*

*OT requires a central server for co-ordination.

*CRDT can adopt any network topology like P2P over WebRTC and it is resilient to network partitions, which makes it decentralized.

Reference: https://youtu.be/B5NULPSiOGw?t=643 by Martin Kleppmann, author of "Designing Data-Intensive Applications".


text:
Q: How is Laravel decoding HTTP request body Content-Type: application/x-www-form-urlencoded when using api call I'm using Laravel-5.5 and i'm developing an apis for an iOS app.
Here, i'm using postman to call all apis. I've one registration api with two headers:
1) Authorization: Bearer access_token
2) Content-type: application/x-www-form-urlencoded
Now when i requesting this api i just want to print dd($request->all()); But it's not give me proper request data. I've tried json_decode(urldecode(file_get_contents('php://input'))); to decode it and also tried $request->getContent(); but no luck!
Can anyone knows how to get request data in controller when using Content-type: application/x-www-form-urlencoded??
EDIT:
public function registration(Request $request)
{
     dd($request->all());
     dd($request->getContent());  //also tried but not work
     dd(json_decode(urldecode(file_get_contents('php://input'))));   //no luck
}

A: I've fixed it like this:
$requestData = json_decode($request->getContent(), true);
dd($requestData);

Pass headers Content-Type: application/json in postman and it's fixed!!
You only need to do this:
$requestData = json_decode($request->getContent(), true);

and you can get all request data in your controller in your request!
Hope this will helps to any users in future!!


text:
Q: how to load json data in a seperate method in a seperate file in flutter? I have this json file which i use to change the color of the background:
# settings.json

{
    "view_background_color": "#f5f242",
}

In my main.dart file i have a Future method called initializeThemeData() which loads the file settings.json and then places the json string inside the variable data. The method returns a ThemeData() for the app. ThemeData() uses the data['view_background_color'] as the value for scaffoldBackgroundColor.
# main.dart
Future<ThemeData> initializeThemeData() async {
  String jsonData =
      await rootBundle.loadString('assets/config/client_settings.json');
  Map<String, dynamic> data = jsonDecode(jsonData);

  return ThemeData(
    scaffoldBackgroundColor:
        Color(convertor.getColor(data['view_background_color'])),

  );
}

Inside the ThemeData() i also grab the class Convertor() which i use to convert the hex color to a hexdecimal. This is the class that converts the data['view_background_color']:
# convertor.dart
class Convertor {
  int getColor(String hexColor) {
    return int.parse("0xFF" + hexColor.substring(1));
  }

}

My question is if i can also make a seperate method for loading the json file and place it in a seperate file and then call this method from the main.dart?
I then want to just place a variable like this: scaffoldBackgroundColor: Color(convertor.getColor(backGroundColor))
instead of :
scaffoldBackgroundColor: Color(convertor.getColor(data['view_background_color']))

A: My initial thought is wondering why any of of this needs to come from a json file to begin with.
It's not really the Flutter way of doing things. Unless I'm missing something here, these are just hardcoded values. So you have extra code to make that work, with no added benefit, and actually making the app do more work to accomplish the same thing.
You could just have a constants file and that would spare you any conversion.
const viewBackgroundColor = Color(0xFFf5f242);

Then you pass that into your ThemeData and be done with it.
scaffoldBackgroundColor: viewBackgroundColor,

Or you could put it in a Settings class.
class Settings {
 static const viewBackgroundColor = Color(0xFFf5f242);
}

Then it would look like this
scaffoldBackgroundColor: Settings.viewBackgroundColor,

Edit:
While your designers are still working, you could do something like this.
class SettingsConverter {
  static Future<Color> getColorFromJson(String key) async {
    String jsonData = await rootBundle.loadString('assets/config/client_settings.json');
    Map<String, dynamic> data = jsonDecode(jsonData);
    return Color(ColorConvertor.getColor(data[key]));
  }
}

class ColorConvertor {
  static int getColor(String hexColor) {
    return int.parse("0xFF" + hexColor.substring(1));
  }
}

Then your initializeThemeData would look like this.
Future<ThemeData> initializeThemeData() async {
  final bgColor =
      await SettingsConverter.getColorFromJson('view_background_color');

  return ThemeData(
    scaffoldBackgroundColor: bgColor,
  );
}


text:
Q: Is it possible to create array of suppliers in Java? Can I create array of suppliers? This doesn't compile somewhy:
Supplier<String>[] x = new Supplier<String>[] {
    () -> "f"
};

A: You have to create an array of raw Supplier:
Supplier<String>[] x = new Supplier[] {
    () -> "f"
};

It's not possible to instantiate a generic array.

A: You can do it like this.  But it would be best to use a List.
@SuppressWarnings("unchecked")
Supplier<String>[] sups = new Supplier[]{()->"A", ()->"B", ()->"C"};

for (Supplier<String> s : sups) {
    System.out.println(s.get());
}

prints
A
B
C

This would be my preferred way of doing it.  The List returned by List.of will be immutable.
List<Supplier<String>> sups = List.of(()->"A", ()->"B", ()->"C");


text:
Q: Explanation for the physics behind magnetic monopoles? Ok so I am looking for a simple explanation of how the process is done from the information I could access and the knowledge I was allowed I have the idea that it is a matter of quantum physics and all i have understood is:

*

*They freeze two magnets and split them not allowing the inner particle constellation to move freely and so it is stuck it its state as a monopole.

*At room temperature it will go back to normal state (and doesn't this contradict with Curie I mean the Curie temperature isn't even close to room temperature and they say that magnetic materials maintain their magnetic properties before they reach that temperature).

*When they touch they lose that state and they become regular magnets.
so how does this work being explained for a high school student in simplistic means i have seen some equations about it but they contain some theoretical physics equations and PDEs some even started explaining the theory of everything and so on,and though i love physics i plan not to self-learn PDEs and theoretical physics. I would really appreciate all the help I can get even if you give me a book that i can read to understand it.


text:
Q: How many array types are in javascript? I wish I can create a function that will help me to get the last item from an array, NOT just from a normal array, but from other array types such as NodeList, (the only two types I know are NodeLists and Arrays)
my function:
       const getLastItem = (list) => {
            if (list instanceof Array || OR NODELIST OR ANYTHING ELSE) {
                return list.slice(-1)[0];
            }
            if(typeof list == 'object'){
           // get the last key from an object, it's another thing which I wish to append to this
           // function
              return Object.keys(list).slice(-1)[0]
           //this will return the last key from an object
            }
        }

[EDIT]: and do you think that there is a better implementation than this one?

A: Something like this? The function grabs the last item from iterables and calls itself recursively on Object.entries of non-iterable objects. It returns undefined if it can't do either (or if the iterable is empty).

const getLastItem = obj => {
    if (obj && obj[Symbol.iterator]) {
        const arr = [...obj]

        return arr[arr.length - 1]
    } else if (obj && typeof obj === 'object') {
        // You could also use `Object.keys` or `Object.values`
        // depending what you want to happen.
        // Note that relying on the order of properties
        // in normal objects is typically a bad idea.
        return getLastItem(Object.entries(obj))
    }

    return undefined
}

;[
    // all of the following work
    getLastItem([1, 2]),
    getLastItem({a: 1, b: 2}),
    getLastItem(document.querySelectorAll('p')),
    getLastItem(new Set([1, 2])),
    getLastItem(new Map([['a', 1], ['b', 2]])),
    getLastItem(document.querySelector('p').classList),
    getLastItem('string!'),

    // all of the following are `undefined`
    getLastItem(null),
    getLastItem(undefined),
    getLastItem(0),
    getLastItem(1),
    getLastItem(document.querySelectorAll('fake-element')),
    getLastItem([]),
    getLastItem({}),
    getLastItem(''),
    getLastItem(new WeakMap([[{}, 1], [{}, 2]])), // not iterable
].forEach(x => console.log(x))

// Edge case: if `obj` is an infinite iterable, you'll get
// stuck in an infinite loop due to use of the spread operator...
// So don't do this
//
// const infiniteIterable = (n => ({
//     *[Symbol.iterator] () {
//         while(true) yield n++
//     },
// }))(0)
//
// getLastItem(infiniteIterable)

first

second

last


text:
Q: ReactJS component passing data back to parent component not working I am working on a ReactJS component that is rendering a Google map from the Google Maps Javascript API. On the map I am dynamically placing markers that is showing different distributor locations. Right now the mock data is coming from an array of distributors with different informations and is being iterated by a loop. When a marker is clicked I have the InfoWindow showing the distributors details. Now in this InfoWindow I have a button that allows the customer to select this distributor.
The GoogleMap component is owned by the ChooseDistributor component. When the button is clicked I want an ID (which is right now a string with the name of the distributor) to be sent back to the ChooseDistributor component by a callback function.
The problem is that I get a Uncaught TypeError: Cannot read property 'callbackParent' of undefined when I click the button. This might be a scope issue since this is not referring to the GoogleMap component itself while I am in the loop(?).
I have then tried to create a variable callbackParent outside of the loop which contains this.props.callbackParent that should link back to the receiving function in the ChooseDistributor component. I am then calling this variable on the button onclick. This does not work either as I am getting a Uncaught ReferenceError: callbackParent is not defined.
I would appreciate if anyone has a possible solution to this problem. Am I missing something or is it a plain syntactical error? Thanks in advance.
Below is my code.
ChooseDistributor component
var ChooseDistributor = React.createClass({
    getSelectedDistributor: function(company){
        alert(company);
    },

    render: function(){
        return(

                    <GoogleMap enableIwSelectButton={true} callbackParent={this.getSelectedDistributor}/>

                <NavBar />

        );
    }
})
module.exports = ChooseDistributor;

GoogleMap component:
var GoogleMap = React.createClass({
    getInitialState: function(){
        return {
            // LOCATIONS STATE SHOULD GET DATA FROM STORE
            locations: [
                // ARRAY VALUES: [0]=LAT, [1]=LNG, [2]=COMPANY, [3]=ADDRESS, [4]=CITY, [5]=WEBSITE, [6]=PHONE, [7]=EMAIL
                [55.628353, 12.388910, 'Distributor One', 'First street 11', '1111 Copenhagen', 'www.company.com', '+4512345678', 'distributor@company.dk'],
                [55.623321, 12.388438, 'Distributor Two', 'Second street 22', '2222 Copenhagen', 'www.company.com', '+4512345678', 'distributor@company.dk'],
                [55.670710, 12.389256, 'Distributor Three', 'Third street 33', '3333 Copenhagen', 'www.company.com', '+4512345678', 'distributor@company.dk'],
                [55.581179, 12.295583, 'Distributor Four', 'Fourth street 44', '4444 Copenhagen', 'www.company.com', '+4512345678', 'distributor@company.dk'],
                [55.647296, 12.284211, 'Distributor Five', 'Fifth street 55', '5555 Copenhagen', 'www.company.com', '+4512345678', 'distributor@company.dk']
            ]
        }
    },
    componentDidMount: function(){
        var locations = this.state.locations;
        var enableIwSelectButton = this.props.enableIwSelectButton;
        var callbackParent = this.props.callbackParent;
        var map = new google.maps.Map(document.getElementById('googleMap'), {
            zoom: 11,
            center: new google.maps.LatLng(locations[0][0], locations[0][1]), // CENTER PROPERTY SHOULD GET COORDINATES OF THE DEVICE CURRENT LOCATION IF PERMITTED.
            mapTypeControlOptions: {
              mapTypeIds: [google.maps.MapTypeId.ROADMAP]
            },
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true
        });
        var infoWindow = new google.maps.InfoWindow();

        var marker, i;

        // PLACE MARKER ON MAP FOR EACH DISTRIBUTOR POSITION IN ARRAY.
        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][0], locations[i][1]),
                map: map
            });
            // ADD INFOWINDOW WITH DISTRIBUTOR DETAILS TO EACH MARKER.
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {

                    infoWindow.setContent('
' + locations[i][2] + '
'+
                        '
' + locations[i][3] + '
' +
                        locations[i][4] + '
' +
                        '' + locations[i][5] + '
' +
                        '
' + locations[i][6] + '
' +
                        ''  + locations[i][7] + '
' +
                        (enableIwSelectButton ? '<button type="button" class="iwButton" onclick={this.props.callbackParent(locations[i][3])}>
Select Distributor
</button>' : ''));
                    infoWindow.open(map, marker);
                }
            })(marker, i));
        }
    },
    render: function(){
        return(

        );
    }
})

module.exports = GoogleMap;

UPDATE:
Thanks to @Radio- my problem was solved. The solution was to give each button an Id and then fetch the button afterwards by that Id and add an eventlistener to it like this:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {

                    infoWindow.setContent('
' + locations[i][2] + '
'+
                        '
' + locations[i][3] + '
' +
                        locations[i][4] + '
' +
                        '' + locations[i][5] + '
' +
                        '
' + locations[i][6] + '
' +
                        ''  + locations[i][7] + '
' +
                        (enableIwSelectButton ? '<button type="button" id="btnSelect' + i + '" class="iwButton">
Select Distributor
</button>' : ''));
                    infoWindow.open(map, marker);
                    var el = document.getElementById("btnSelect" + i);
                    el.addEventListener("click", function(){callbackParent(locations[i][2])});
                }
            })(marker, i));

A: 'this' inside callback method refers to callback itself. So you can't access 'this' inside callback function to refer outer scope.
try ES6 syntax:
 myFn:()=>{
this.props.any();
}

or,
var self = this.
myFn:function(){
  self.props.any();
}

A: The button in the InfoWindow isn't a React component. It's raw html, possibly parsed by setContent. So, the button's 'onclick' attribute is going to try to execute a function in the global namespace. It doesn't have any awareness of how it was created, and neither callbackParent nor this.props.callbackParent nor locations[i][3] is in the global namespace for it to reference.
You might be able to use regular DOM manipulation in componentDidMount to add the event listener.
infoWindow.setContent(... '<button type="button" class="iwButton">
Select Distributor
</button>' : ''));
infoWindow.open(map, marker);

var el = document.getElementsByClassName("iwButton");
el.addEventListener("click", function() { callbackParent(locations[i][3]) });


text:
Q: MySQL Connector/Net Exception: Unable to connect to any of the specified MySQL hosts I am using ASP.NET MVC 5 with MySQL (using Connector/Net). I can connect to the Database and everything works fine... but once the server gets busy, I get the following exception:

MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect
to any of the specified MySQL hosts.

I am using Ninject to inject the DbContext in the MVC Controller:
Bind<ApplicationDbContext>().ToSelf().InRequestScope();

I have 3 instances of MySQL server in a Galera Cluster, and this is my ConnectionString:
<add name="MyDB" connectionString="Server=IP1,IP2,IP3; Port=3306; Database=dbname; Uid=u1; Pwd=pswd1;" providerName="MySql.Data.MySqlClient" />

This exception generally happens when a bot starts crawling the website.
I have seen this question which is similar however the problem is that they can never connect to MySQL (I believe their ConnectionString is incorrect) but this answer (on the same question) seems to be describing the problem that I am having:

If your connection works initially, but you begin seeing this error
after many successful connections, it may be this issue.
In summary: if you open and close a connection, Windows reserves the
TCP port for future use for some stupid reason. After doing this many
times, it runs out of available ports.

The answer describes the problem perfectly, however their solution is not really helpful:

*

*They suggest to use Connection Pooling (Connector/Net uses Connection Polling by default - so this is not helpful)

*They suggest to change Windows settings and assign more ports:

netsh int ipv4 set dynamicport tcp start=10000 num=50000
This document also explains a similar error.
However, I am not sure if this issue is caused because Windows is running out of ports?
Has anyone encountered a similar issue?
Here is the stack trace for the error that I am getting:
Exception: UserId: 0 Url: http://www.my-site.com/house-rental/display/109149
UserAgent: facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)
Message: The underlying provider failed on Open.
InnerException: MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
    at MySql.Data.Failover.FailoverManager.AttemptConnection(MySqlConnection connection, String originalConnectionString, String& connectionString, Boolean mySqlPoolManager)
    at MySql.Data.MySqlClient.MySqlConnection.Open() at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
    at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
    at System.Data.Entity.Core.EntityClient.EntityConnection.Open() Exception: System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> MySql.Data.MySqlClient.MySqlException: Unable to connect to any of the specified MySQL hosts.
    at MySql.Data.Failover.FailoverManager.AttemptConnection(MySqlConnection connection, String originalConnectionString, String& connectionString, Boolean mySqlPoolManager)
    at MySql.Data.MySqlClient.MySqlConnection.Open() at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
    at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
    at System.Data.Entity.Core.EntityClient.EntityConnection.Open() --- End of inner exception stack trace ---
    at System.Data.Entity.Core.EntityClient.EntityConnection.Open() at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions)
    at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass41_0.b__0() at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
    at System.Data.Entity.Core.Objects.ObjectQuery`1..GetEnumerator>b__31_0() at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
    at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
    at my-site.Infrastructure.Main.UmbrellaServices.AdPersister`1.GetActiveOrInactiveAd(Int64 adBaseId)
    in C:\my-site\my-site.source\my-site.Infrastructure.Main\UmbrellaServices\AdPersister.cs:line 46
        at my-site.Application.Main.Services.AdService`2.GetActiveOrInactiveAd(Int64 adBaseId)

Update
As suggested by @MarcAlff, I ran the following:
SELECT * from performance_schema.host_cache;

and here is the result:
| IP      | HOST                                       | HOST_VALIDATED | SUM_CONNECT_ERRORS | COUNT_HOST_BLOCKED_ERRORS | COUNT_NAMEINFO_TRANSIENT_ERRORS | COUNT_NAMEINFO_PERMANENT_ERRORS | COUNT_FORMAT_ERRORS | COUNT_ADDRINFO_TRANSIENT_ERRORS | COUNT_ADDRINFO_PERMANENT_ERRORS | COUNT_FCRDNS_ERRORS | COUNT_HOST_ACL_ERRORS | COUNT_NO_AUTH_PLUGIN_ERRORS | COUNT_AUTH_PLUGIN_ERRORS | COUNT_HANDSHAKE_ERRORS | COUNT_PROXY_USER_ERRORS | COUNT_PROXY_USER_ACL_ERRORS | COUNT_AUTHENTICATION_ERRORS | COUNT_SSL_ERRORS | COUNT_MAX_USER_CONNECTIONS_ERRORS | COUNT_MAX_USER_CONNECTIONS_PER_HOUR_ERRORS | COUNT_DEFAULT_DATABASE_ERRORS | COUNT_INIT_CONNECT_ERRORS | COUNT_LOCAL_ERRORS | COUNT_UNKNOWN_ERRORS | FIRST_SEEN          | LAST_SEEN           | FIRST_ERROR_SEEN    | LAST_ERROR_SEEN     |
+--------------+-------------------------------------------------+----------------+--------------------+---------------------------+---------------------------------+---------------------------------+---------------------+---------------------------------+---------------------------------+---------------------+-----------------------+-----------------------------+--------------------------+------------------------+-------------------------+-----------------------------+-----------------------------+------------------+-----------------------------------+--------------------------------------------+-------------------------------+---------------------------+--------------------+----------------------+---------------------+---------------------+---------------------+---------------------+
| 1.2.3.4 | ip-1-2-3-4.ap-southeast-2.compute.internal | YES            |                  0 |                         0 |                               0 |                               0 |                   0 |                               0 |                               0 |                   0 |                     0 |                           0 |                       26 |                   4010 |                       0 |                           0 |                           8 |                0 |                                 0 |                                          0 |                             0 |                         0 |                  0 |                    0 | 2020-06-14 11:55:18 | 2022-02-15 07:00:13 | 2020-06-14 23:11:17 | 2022-02-15 01:00:02 |

These are the columns with error:
COUNT_AUTH_PLUGIN_ERRORS: 26
COUNT_HANDSHAKE_ERRORS: 4010
COUNT_AUTHENTICATION_ERRORS: 8

A: A client seeing a failed connection is only one side of the story.
To troubleshoot this, the best is to look at the other side, and see what the server says about failed connections:
SELECT * from performance_schema.host_cache;

In particular, this table will show statistics on each known root cause.
See the reference manual:
https://dev.mysql.com/doc/refman/8.0/en/performance-schema-host-cache-table.html

A: Firstly I'd like to say that I feel that you've researched your case thoroughly.
The suggestion about reserved ports definitely makes sense. When a connection had been opened Windows reserves the port in case the same client continues. Windows has no way of telling whether the exchange is finished.
If we were in an open source OS we would be trying to find out how the mechanism of port reservation works.With Windows we don't have too much visibility into the inner mechanisms. You could try to reduce the time that the port is reserved. Please see this link    https://support.solarwinds.com/SuccessCenter/s/article/Tweaking-Windows-Server-performance-to-prevent-port-exhaustion-when-using-Orion-modules?language=en_US.
As you've searched all the other avenues and nothing else is working you should try opening up more port numbers. The commande netsh int ipv4 show dynamicport tcp will show the ports currently reserved. It seems that the default range is 49152 to 65535. Is any if this range blocked by your firewall?
The following Microsoft Docs makes the point that dynamic ports for IPR and ip6 are allocated differently: https://learn.microsoft.com/fr-fr/troubleshoot/windows-server/networking/default-dynamic-port-range-tcpip-chang. Do you have the possibility to have part of your connections using ip6?
It may sound like an exaggeration to allow an extra 40 000 open ports as suggested but what have you got to lose?

*

*Today you face a problem, connections are being refused. You have a possible solution. Try opening the ports 10000-50000 for 24 hours and see what happens. You are not taking a security risk. It is totally reversible. You have nothing to lose.
If this solves the problem you can then try reducing the permitted range, probably using the higher end of the range, but before talking about optimising you want to know whether this can solve the problem.

DYNAMIC PORTS

When a client connects on port 3306 the computer assigns a dynamic port to the connection, which is communicated to the client.

A dynamic port -- also called a private port -- is one that is
assigned to a process or service at the time the port is needed,
usually when the process or service is started. When assigning dynamic
ports, the OS can use any ports available from the range of ports
designated for this purpose.

I recommend that you read more on the subject. I have found a good explanation here https://www.techtarget.com/searchnetworking/definition/dynamic-port-numbers?amp=1.
HARDWARE OR BROADBAND CAUSES
I know it sounds obvious have you checked your servers performance and broadband capacities v. use at peak times? If hardware or internet are the limiting factor modifying port settings and MYSQL configuration can't solve it.

A: I believe this issue is caused because of a bug in MySQL connector/net which affects multi-host connection strings.
The best solution was to use MySQLConnector, however this solution does not support Entity Framework 6, which is a dependency in my project.
The way I resolved the issue is to use Amazon RDS instead of Galera Cluster... the difference is when using RDS, you will have only one host (RDS takes care of redundancy behind the scene)... so I no longer need to use a multi-host connection string.


text:
Q: after retired or after retirement or after retiring? I am preparing a speech about the life after retire. But not sure which one is correct below, please help to confirm.
1. After retire, I want to be a happy person.
2. After retirement, I want to be a happy person.
3. After retired, I want to be a happy person.
4. After retiring, I want to be a happy person.

A: *

*Incorrect. Here's what's acceptable:

Once I've retired, my goal is to be a happy person.

*Too macabre. It means "Once my retirement is over, I want to be a happy person."

*Incorrect. The correct way of putting it would be:

After I retire, I want to be happy.

*Awkward. A more natural way of putting it would be:

In retirement, I would like to be as happy as possible.


text:
Q: Typescript: Convert type object keys to comma separated string type I would like to convert an object type to a comma separated string of its keys.
With input
type Obj = {
  val1: string;
  val2: string;
  val3: string;
}

I want the output
type ObjKeys = GetObjKeys<Obj>;
// 'val1,val2,val3'

Is this possible to obtain?
I'm trying to get a better type safety for an api middle layer I'm building. With an expected output certain fields should be fetched, and those should be typed in a specific manner for it to work. I like to make it mandatory to fetch the fields necessary to populate the expected output type. In that way trying to minimise possible errors.

A: If the order of comma separated keys sequence is not important, you can create the type that you want like this :
type CreateCommaSeparatedType<T extends string, K extends string = T> =
 [T] extends [never]
    ? ""
    : K extends any
        ? Exclude<T, K> extends never
            ? `${K}`
            : `${K},${CreateCommaSeparatedType<Exclude<T, K>>}`
        : "";

So if you declare a type based on CreateCommaSeparatedType:
type CommaSepreatedType = CreateCommaSeparatedType<keyof Obj>;

CommaSepreatedType will be :
"val1,val2,val3" | "val1,val3,val2" | "val2,val1,val3" | "val2,val3,val1" | "val3,val1,val2" | "val3,val2,val1"

Remember that due to the recursive and permuting essence of CreateTypeCommaSeparated, the number of unions becomes huge very easily as the number of Obj keys gets more. So this may cause a typescirpt error which says :
Expression produces a union type that is too complex to represent.

But if the order of comma separated keys sequence matters, you can do it as @Tobias S. mentioned in the comment.


text:
Q: How to get values from grid using regex in java I'm working on resume parser and i can get some of data i.e company details from text but not getting if it is kept in a grid or table
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class CmpnyNameex {
    public static void main(String[] args)throws IOException {
        String text="";
        String name="";
            XWPFDocument msDocx = new  XWPFDocument(new FileInputStream("A:\\Resumes\\Anwesh.docx"));
            XWPFWordExtractor extractor = new XWPFWordExtractor(msDocx);
            text = extractor.getText();
        }
        catch(FileNotFoundException ex){ex.printStackTrace();
            JOptionPane.showMessageDialog(null,"The system cannot find the      file specified file it may be because of old file    format","Error",JOptionPane.ERROR_MESSAGE);
        }
        String rx13="(?<=Have been associated with).*.(.*Ltd?)";
        Pattern p1 = Pattern.compile(rx13);
        Matcher found1 = p1.matcher(text);
        while(found1.find())
        {
            name= found1.group(0);
        }
    }
}


text:
Q: javascript inherit from a class Im learning inheritance. In the code below
1)penguin inherits from Animal
2)when I call penguin.sayName();  why does it output "Hi my name is undefined";
function Animal(name,numLegs){
    this.name = name;
    this.numLegs = numLegs;

}
Animal.prototype.sayName = function(){
  console.log("Hi my name is " + this.name);
};

function Penguin(){}

Penguin.prototype = new Animal();

var penguin = new Penguin("Captain Cook", 2);
penguin.sayName();

A: You need to add the name and numLegs properties to the penguin object via the function constructor.  These two properties are specific to the Animal object and will not be assigned simply by calling the Penguin constructor.
function Penguin(name,numLegs){
  this.name = name;
  this.numLegs = numLegs.
}

Working Example: http://jsfiddle.net/5A7hH/
You could also use the constructor on the prototype chain, which is similar to calls of the super() constructor in Java.
function Penguin(name,numLegs){
   this.constructor(name,numLegs);
}


text:
Q: How to chown/chmod after tag checkout in git? On a live environment I need to fetch tags and simply switch between them. After every switch, I need to chown/chmod all files inside the worktree.
I've created a post-checkout hook
#!/bin/bash
chown -R www-data:www-data public/
find public/ -type f -exec chmod 400 {} \;
find public/ -type d -exec chmod 500 {} \;

The .git dir is outside of the public dir, so I've added the following to the git config.
worktree = /var/www/site/public

Now I execute the following commands
# git fetch --tags
# git checkout 0.0.1

But the post-checkout hook does not get executed. Whats wrong?
Another question: What is the relative path of the hook? Is it the same dir where .git lies or is it public/?

A: Check that your .git/hooks/post-checkout has executable flag set, otherwise do chmod +x .git/hooks/post-checkout.
Current working directory of a hook as a repository root (the directory where .git is located).
You can verify that you hook is actually executed and also its current working directory by writing a very simple hook
#!/bin/sh
pwd
echo "This is post-checkout hook"


text:
Q: How to update my map with the restored features from JSON format? I'm trying to implement a CRUD that have a map OpenLayers.

*

*First, I drawed and saved the features with writeFeatures().

*Second, I'm trying to show the polygon that I drawed, and here is my problem:

*

*After I set the map.setLayer my map doesn't show the features.
I would like that when I select the product in the list, my map show the features that I read from my database, in format JSON. I saved using WriteFeatures();

*Could I need a loop to iterate each item of array?
What am I doing wrong?
My configuration:

*

*Laravel v6.18.22 with bootstrap;

*OpenLayers v6.3.1

In my HTML has:
<div id="map" class="map" </div>

  <script>
    const getFeatur = @json(route('homeController.getLavouras'));
  </script>

 <script type="application/javascript" >
  my_map.display();
 </script>

In my external JavaScript file (my_map.js) has:
    import 'ol/ol.css';
    import Feature from 'ol/Feature';
    import Geolocation from 'ol/Geolocation';
    import Map from 'ol/Map';
    import Point from 'ol/geom/Point';
    import View from 'ol/View';
    import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';
    import {OSM, Vector as VectorSource} from 'ol/source';
    import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
    import VectorContext from 'ol/render/VectorContext';
    import GeoJSON from 'ol/format/GeoJSON';
var my_map = {                       // <-- add this line to declare the object
    display: function () {           // <-- add this line to declare a method

      var view = new View({
        center: ol.proj.fromLonLat([-49.450270, -15.496072]),
        zoom: 6 ,
      });

      var map = new Map({
        layers: [
          new TileLayer({
            source: new OSM(),
          }) ],
        target: 'map',
        view: view,
      });

      new VectorLayer({
        map: map,
        source: new VectorSource()
      });

document.getElementById('produtoid').onchange = function(){
var produtoid = document.getElementById('produtoid').value;
var _token = $('input[name="_token"]').val();
        $.ajax({
                        url:getFeatur,
                        method:"GET",
                        data:{produtoid:produtoid, _token:_token},
                        success:function(result)
                        {

                          var newSource = new ol.source.Vector({
                                        format: new ol.format.GeoJSON(),
                                        features: new GeoJSON().readFeatures(result.dados[0].feature,
                                            {
                                                dataProjection: 'EPSG:26918',
                                                featureProjection: 'EPSG:3857'
                                             }),
                                        });

                          var nwLayer = new ol.layer.Vector({
                              title: 'My Title',
                              source: newSource,
                              visible: true,
                          });
                          map.addLayer(nwLayer); --> I think that here my map has to refresh and show the features.

                      }
                  });
                }

}                                // <-- close the method
};                                   // <-- close the object
export default my_map;               // <-- and export the object

A: There is no concept of map refreshing when it comes to OpenLayers, I think in your case style property is missing in the vector layer object
example vector layer looks like this -
  source: new VectorSource(),
  map: map,
  style: new Style({
    stroke: new Stroke({
      color: 'rgba(255, 255, 255, 0.7)',
      width: 2,
    }),
  }),
});

You can refer to this link here - Vector Layer in OpenLayers
Also, you can just update the source of the vector layer, it will reflect on the map directly, and you don't need to create a new layer every time.


text:
Q: Custom Alert control in react-native I am developing react-native app and trying to make a custom alert method (like Alert. alert() as given in  Official site of react-native). React-native alert has no styling property for Font Size and back-ground Color, alert is very small when i'm using on android tab but it's work fine while on using in android scanner and mobile.
enter code here

import React, { Component } from 'react';
import { StyleSheet, Platform, View, Text,TouchableOpacity } from 'react-native';
// import PropTypes from 'prop-types';
// import Dialog from "react-native-dialog";
 import Alertfunction from './src/CustomAlert'

 export default class App extends Component{

    render() {

      return (

        <Alertfunction Title={"Alert"} FontSize = {30} FontColor= '#FF9800'  Visible={true}/>

      );
    }
  }

const styles = StyleSheet.create({

 MainContainer :{

  flex:1,
  paddingTop: (Platform.OS) === 'ios' ? 20 : 0,
  alignItems: 'center',
  justifyContent: 'center',

  }

});

customAlert.js

import React, { Component } from 'react';
import { StyleSheet, Platform, View, Text,TouchableOpacity } from 'react-native';
import PropTypes from 'prop-types';
import Dialog from "react-native-dialog";

class Alertfunction extends Component {
    state = {
        dialogVisible: this.props.Visible
      };

      showDialog = () => {
        this.setState({ dialogVisible: this.props.Visible });
      };

      handleCancel = () => {
         this.setState({ dialogVisible: false });
        // this.props.Visible=false;
      };

      handleDelete = () => {
         this.setState({ dialogVisible: false });
        //this.props.Visible=false;
      };

  render() {

    return (

            <View>
                <TouchableOpacity onPress={this.showDialog}>
                <Text >{this.props.Title}</Text>
                </TouchableOpacity>
                <Dialog.Container visible={this.state.dialogVisible}>
                <Dialog.Title style={{fontSize : this.props.FontSize, color: this.props.FontColor}}>{this.props.Title}</Dialog.Title>
                <Dialog.Description style={{fontSize : this.props.FontSize, color: this.props.FontColor}}>
                    Do you want to delete this account? You cannot undo this action.
                </Dialog.Description>
                <Dialog.Button style={{fontSize : this.props.FontSize, color: this.props.FontColor}} label="Cancel" onPress={this.handleCancel} />
                <Dialog.Button style={{fontSize : this.props.FontSize, color: this.props.FontColor}} label="ok" onPress={this.handleDelete} />
                </Dialog.Container>
            </View>

    );
  }
 }

export default Alertfunction;
Alertfunction.propTypes =
{
    Title: PropTypes.string,
  FontSize: PropTypes.number,
  FontColor: PropTypes.string,
  Visible: PropTypes.bool,

}

Alertfunction.defaultProps =
{
    Title: "Default Name",
  FontColor: "#00E676",
  FontSize: 15,
  Visible:false
}

const styles = StyleSheet.create({

 MainContainer :{

  flex:1,
  paddingTop: (Platform.OS) === 'ios' ? 20 : 0,
  alignItems: 'center',
  justifyContent: 'center',

  }

});

A: You need to declare methods in parent component and pass as props like below:
and update value of dialogVisible using these methods.
import React, { Component } from 'react';
import { StyleSheet, Platform, View, Text,TouchableOpacity } from 'react-native';
import Alertfunction from './src/CustomAlert'

 export default class App extends Component{
      this.state = {
        dialogVisible: true;
      }
      showDialog = () => {
        this.setState({ dialogVisible: this.props.Visible });
      };

      handleCancel = () => {
         this.setState({ dialogVisible: false });
      };

      handleDelete = () => {
         this.setState({ dialogVisible: false });
      };
    render() {
      const { dialogVisible } = this.state;
      return (

        <Alertfunction
            Title={"Alert"}
            FontSize = {30}
            FontColor= '#FF9800'
            Visible={dialogVisible}
            showDialog={this.showDialog}
            handleCancel={this.handleCancel}
            handleDelete={this.handleDelete}
        />

      );
    }
  }

const styles = StyleSheet.create({

 MainContainer :{

  flex:1,
  paddingTop: (Platform.OS) === 'ios' ? 20 : 0,
  alignItems: 'center',
  justifyContent: 'center',

  }

});

and call those methods in child component to update value of dialogVisible
your child component should be like this:
customAlert.js

import React, { Component } from 'react';
import { StyleSheet, Platform, View, Text,TouchableOpacity } from 'react-native';
import PropTypes from 'prop-types';
import Dialog from "react-native-dialog";

class Alertfunction extends Component {
  render() {
    const { Visible } = this.props;
    return (

            <View>
                <TouchableOpacity onPress={this.props.showDialog}>
                <Text >{this.props.Title}</Text>
                </TouchableOpacity>
                <Dialog.Container visible={Visible}>
                <Dialog.Title style={{fontSize : this.props.FontSize, color: this.props.FontColor}}>{this.props.Title}</Dialog.Title>
                <Dialog.Description style={{fontSize : this.props.FontSize, color: this.props.FontColor}}>
                    Do you want to delete this account? You cannot undo this action.
                </Dialog.Description>
                <Dialog.Button style={{fontSize : this.props.FontSize, color: this.props.FontColor}} label="Cancel" onPress={this.props.handleCancel} />
                <Dialog.Button style={{fontSize : this.props.FontSize, color: this.props.FontColor}} label="ok" onPress={this.props.handleDelete} />
                </Dialog.Container>
            </View>

    );
  }
 }

export default Alertfunction;
Alertfunction.propTypes =
{
    Title: PropTypes.string,
  FontSize: PropTypes.number,
  FontColor: PropTypes.string,
  Visible: PropTypes.bool,

}

Alertfunction.defaultProps =
{
    Title: "Default Name",
  FontColor: "#00E676",
  FontSize: 15,
  Visible:false
}

const styles = StyleSheet.create({

 MainContainer :{

  flex:1,
  paddingTop: (Platform.OS) === 'ios' ? 20 : 0,
  alignItems: 'center',
  justifyContent: 'center',

  }

});

A: I fixed this issue by making a custom control here is the link
enter image description here


text:
Q: Is this a good pattern regarding EclipseLink usage? I have found the following pattern in a codebase that use EclipseLink through JPA:
TypedQuery query = ...
...
if(query.getResultList().size() > 0) {
  return query.getSingleResult();
} else {
  return null;
}

Discarding the question about weither or not returning null is a good idea, I am more wondering about the fact that, although the two queries are consecutive in the code, under heavy load (which is expected on this project), the query could be fired twice against the database, rather than using the cache.
Am I wrong and can I safely assume that the second call will always hit the cache, or should this kind of pattern be reworked in order to catch the NoResultException instead?

A: No, this is not a good pattern.  You are unnecessarily executing the query twice and so depending on other settings to prevent the query from hitting the database which may or may not have have been configured -EclipseLink has a query cache, but it is not enabled by default and you really don't need to use it here.  If you haven't configured a query cache, the entities will be cached from the first query, so you are reading in more than one entity into memory, and then potentially hitting the database again just to get one of those entities.
The common pattern is just to check the list and return the first value:
List values = query.getResultList();
if(values.size() > 0) {
  return values.get(0);
} else {
  return null;
}

If this query can return a high number of entities, you might also call query.setMaxResults(1); to limit the results returned.


text:
Q: Is my bracketing the issue here? Or is there really an unexpected identifier? Javascript/jQuery I am making a simple app that increases the count below each picture on click. I think it's having an issue compiling or I'm missing something silly and obvious.
Heres my HTML and JS
HTML
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Cat Clicker</title>

 Cat Clicker

 0

 0

JS
$(document).ready(function() {

var clicks_one = 0;
var clicks_two = 0;

    $('#catpic_one').on("click", "#counter_one", function() {
        clicks_one++
        var clickcount_one = clicks_one.toString();
            $('#counter_one').append("You clicked the cat #1" clickcount_one " times.");
    }

    $('#catpic_two').on("click", "#counter_two", function() {
        clicks_two++
        var clickcount_two = clicks_two.toString();
            $('#counter_two').append("You clicked the cat #1" clickcount_two " times.");
    }

});

A: catpic_one and catpic_two are class, not id. please change from '#'to '.', as
'.catpic_one' and '.catpic_two'

A: Apart from the syntax error in your concatenation, you have not declared any element with ids.
And you are trying to access using id selector.
$('#counter_one')

*

*put id property to 'p' tag, if you want to use # selector.

*Correct the concatenations as suggested in other answers.

*As a good practice, always include end tag for all elements.

*Also, this is javascript. It is not required to convert element to string.

var clickcount_two = clicks_two.toString();

You can directly concatenate variable in a string.


text:
Q: fatal: ambiguous argument 'origin/': unknown revision or path not in the working tree So previously for my lefthook.yml file I was using run: git diff --name-only --diff-filter=AM HEAD origin/${TRAVIS_BRANCH}
Was on TravisCI, but Now on Github Actions, how would I specify this for Github Actions?