text:
Q: GeoJSON filtering based on properties not working I am getting the GeoJSON URL from GeoServer and the data is getting displayed on the map using Leaflet. Now I need to display a few of the features based on the property "status" whether it is pass or rescan.
But I'm getting the following error:
Uncaught TypeError: Cannot read property 'status' of undefined
Below is my code:
var Dupont = new L.GeoJSON.AJAX("http://localhost:8080/geoserver/ABHI/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=ABHI:Dupont_new&maxFeatures=50&outputFormat=application%2Fjson",{dataType:"json"});
Dupont.addTo(map);

var stataupass=L.geoJson(Dupont, {
 filter: function(feature, layer) {
    return (feature.properties.status)=="rescan";
  }

}).addTo(map);

link to Geojson data (fiddle)

A: leaflet-ajax plugin gives you directly an L.GeoJSON Layer Group (what you record in your Dupont variable).
Therefore you cannot feed Dupont into another L.geoJson() factory: it is not a plain GeoJSON data, but a Leaflet Layer Group. Hence the error message.
If you want to set some options (filter in your case) on that Layer Group, you can directly pass options as 2nd argument of L.geoJson.ajax() factory, even though it is not clearly advertised, exactly like for a regular L.GeoJSON group (besides the plugin special options):
L.geoJson.ajax(url, {
  dataType: "json",
  filter: fn
});


text:
Q: Reading text in columns from HTML tables I've been debugging for some time, trying to get the value of a column in a table. I think once I've done this, it should be easy to pass the value in the next column out of my JS function.
My HTML table is:

      Japan
      83.7

      Switzerland
      83.4

My Javascript is:

If I do document.write(td), I get "[object HTMLTableCellElement]" on my page.
If I do document.write(td.fullHTML) I get "undefined" on my page.
When I explore other methods than td.innerHTML, I get this - it looks like I can't use functions based around text.

A: Use this instead. you have used assignment operator instead of comparison operator "=="
if (td.innerHTML == Country)
    {
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: transpose of a marix I am using the following code to take the transpose of the matrix but it gives me again the initial matrix.
---EDITED--------
Now , I am getting zeros for result matrix.
    int  main(int argc,char**argv)
{

    const int  rows=2,cols=2;

    //size in bytes
    const int ARRAY_BYTES = ( rows * cols ) *sizeof(int);

    float *A , *A_Copy;
    A = (float *) malloc(ARRAY_BYTES);
    A_Copy = (float *) malloc(ARRAY_BYTES);

    //initialize
    for (int i=0; i<rows; ++i)
        for (int  j=0; j<cols; ++j)
            A_Copy[i+rows*j] = 0;

            A[0]=0;
            A[1]=1;
            A[2]=2;
            A[3]=3;

    // print matrix
    printf("\nA matrix");
    for (int  i=0; i<rows; ++i) {
        for (int  j=0; j<cols; ++j)
        printf("\nA = %f",A[i+rows*j]);
    printf("\n");
        }

    float *A_dev , *A_Copy_dev;
    cudaMalloc((void **) &A_dev, ARRAY_BYTES);
    cudaMalloc((void **) &A_Copy_dev, ARRAY_BYTES);

    cudaMemcpy(A_dev, A, ARRAY_BYTES, cudaMemcpyHostToDevice);
    cudaMemcpy(A_Copy_dev, A_Copy, ARRAY_BYTES, cudaMemcpyHostToDevice);

    float const alpha(1.0);
    float const beta(0.0);

    cublasHandle_t handle;

    cublasStatus_t status;

    status = cublasCreate(&handle);

    cublasSetPointerMode(handle, CUBLAS_POINTER_MODE_HOST);
    //status = cublasSgeam(handle,CUBLAS_OP_T, CUBLAS_OP_N,  rows, cols , &alpha ,A_Copy ,cols , &beta , A_Copy , rows , A ,rows);
    status = cublasSgeam(handle,CUBLAS_OP_T, CUBLAS_OP_N,  rows, cols , &alpha ,A_Copy_dev ,rows , &beta ,A_Copy_dev ,rows, A_dev , rows);

    cudaMemcpy(A,A_dev, ARRAY_BYTES, cudaMemcpyDeviceToHost);

    printf("\nA transposed ");
    for (int  i=0; i<rows; ++i) {
        for (int  j=0; j<cols; ++j)
        printf("\nA = %f",A[i+rows*j]);
    printf("\n");
        }

    cudaFree(A_dev);
    cudaFree(A_Copy_dev);

    free(A);
    free(A_Copy);

    return 0;
}

A: CUBLAS expects input and output matrices to be allocated on the device. So in your case you should create device copies of A and A_Copy using cudaMalloc, and pass them to the function cublasSgeam.
Also, by default, alpha and beta should also be allocated on the device but cublas provides an option to use host pointers for these variables. All you have to do is to change the pointer mode of cublas handle before calling cublasSgeam.
cublasSetPointerMode(handle, CUBLAS_POINTER_MODE_HOST);

Update:
You are getting zeros, because you are initializing A_Copy with zeros and copying it to A_Copy_dev which is used as the A input matrix to the cublas function. So basically, you provide zeros input and get zeros output.
In the second cudaMemcpy call, instead of A_Copy, you should copy A to A_Copy_dev like this:
cudaMemcpy(A_Copy_dev, A, ARRAY_BYTES, cudaMemcpyHostToDevice);

There is no need of A_Copy in this code.


text:
Q: Post request never getting made, just sends get I am using Mongoose and nodejs to write an API.
My users.js looks as follow:
var express = require('express');
var router = express.Router();
var user = require('../models/users.js');

router.post('/',function(req, res, next) {
  console.log("made a post");

            var user2 = new user();     // create a new instance of the Bear model
            user2.firstName = req.body.firstName;  // set the bears name (comes from the request)
        user2.lastName=req.body.lastName;
        user2.email=req.body.email;

            user2.save(function(err) {
                if (err)
                    res.send(err);

            console.log("User created");
            });

        })

//The model acts as our user object...this returns all users.
    .get('/', function(req, res, next) {
      console.log("sending a get request");
        user.find(function(err, users) {
           if (err)
               res.send(err);

           res.json(users);
       });

      })

module.exports = router;

When I send a get request, it works perfectly. However, I am now trying to develop the POST request. I send a request such as the following:
http://localhost:4000/users?firstName=Han&lastName=Bo@email=haBo@yah.com

and I receive the following in my console:
    sending a get request
GET /users?firstName=Han&lastName=Bo@email=haBo@yah.com
 200 15.522 ms - 1365

And I receive the output of my GET request in the browser.
I'm new to node and would appreciate some help with this.
Thanks.

A: You are putting your parameters as URL parameters, while your POST API reads parameters from body of request.
Here is explanation of POST parameters.
Also, if you are not already using it, use postman to send requests.


text:
Q: What is the best way to present a view controller on top of everything in iOS? I'm trying to present a view controller that will be kept displayed above everything, regardless of the currently presented view controller, so it will be kept as displayed even if the view controller behind it will get dismissed, or starts to present another view controller.
I know how to find the topmost view controller (for example as suggested here) but in this case presenting over this view controller will make the new view controller depends on the hierarchy of the parent controller, which I try to avoid.

A: Present the view from the rearmost view, the window. But give it a high z index so that it shows up in front of everything else.


text:
Q: Are css @keyframes possible natively with Webflow interaction? I want to move a div and while it's moving I want to increase its opacity then decrease it. With css keyframes I'd do something like this:
.animated-element {
  animation: move-and-fade 5s ease-in-out infinite;
}

@keyframes move-and-fade {
  0% {
    transform: translateY(0px);
    opacity: 10%;
  }
  50% {
    opacity: 100%;
  }
  100% {
    transform: translateY(620px);
    opacity: 10%;
  }
}

Is this possible natively with Webflow interaction? It seems I can only add actions with previous action or after.
I want to achieve something similar to this, where the small lines are moving on the border of the hero image.
Here's an example of my implementation in Webflow.


text:
Q: output answer by rounding off in c++ In a programming contest i got a task to print my output this way but i couldnot figure out the correct method to do this.How can we do this in c++?Suppose my output is stored in a double  variable and i need to follow this pattern or format
If output is supposed to be 0.0034567, output should be "3.457 3".
If output is supposed to be 0.3034567, output should be "3.034 1".

A: You can use trunc to truncate to a certain number of digits, use
 #include < cmath >
double output = 0.0034567;
int count=0;

while (output<1)
{
    output *=10;
    count++;
}

output*=1000;
int modul =(int) output%10;
if (modul>=5)
    output++;

output /=1000;
output = trunc(1000 * output)/1000;
std::cout << output << " "  << count << endl;


text:
Q: check box on custom listview  me getting like this it should not only show on particular item
How to make radio buttons in custom listview as single mode. If I click on particular radio button then it has to appear and the other one as unselected. If click on 1st row then radio button on first row selected.click on second row radion button on second row seleceted and first row unselected.click on third row radio button on third row selected and first row and second row unselected.
customlist.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<RadioButton
      android:id="@+id/radioButton1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerVertical="true"
      android:layout_alignParentLeft="true"
      android:text=""

       />

  <TextView
      android:id="@+id/card"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:paddingLeft="10dip" android:layout_centerVertical="true"
      android:layout_toRightOf="@+id/radioButton1"
      android:text=""
      android:textColor="#000000"
      android:textSize="15dip"
      android:textStyle="bold" />

  </RelativeLayout>

  listView = (ListView) findViewById(R.id.cardlist);

adapter =new MyAdapter(this, app.arryList,app.arryList1);

listView.setOnItemClickListener(new OnItemClickListener() {

  @Override
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
      // TODO Auto-generated method stub

      Toast.makeText(getApplicationContext(), "am thelist",Toast.LENGTH_LONG).show();

  }
});

listView.setAdapter(adapter);

listView.setChoiceMode(listView.CHOICE_MODE_SINGLE);
}

public class MyAdapter extends BaseAdapter {

Context context = null;
ArrayList<String> items= null;
ArrayList<String> items1= null;

public MyAdapter(Newcard newcard, ArrayList<String> items,
      ArrayList<String> items1) {
  // TODO Auto-generated constructor stub

  this.items = items;
  this.items1 = items1;

}

@Override
public int getCount() {
  // TODO Auto-generated method stub
  return items.size();
}

@Override
public Object getItem(int position) {
  // TODO Auto-generated method stub
  return items;

  //return items.get(position);
}

@Override
public long getItemId(int position) {
  // TODO Auto-generated method stub
  return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
  // TODO Auto-generated method stub

  View layout = null;
  TextView produ = null;

  TextView desc = null;
  Button edit = null;

  RadioButton radio =null;

  if (convertView == null) {

      lay = LayoutInflater.from(getApplicationContext());
      layout = lay.inflate(R.layout.customlist, null);
  } else {
      layout = convertView;
  }

  produ = (TextView) layout.findViewById(R.id.card);
  produ.setText("" +app.arryList.get(position));

  radio = (RadioButton) layout.findViewById(R.id.radioButton1);

  radio.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
          // TODO Auto-generated method stub

                      //check.setVisibility(View.GONE);

          System.out.println("data "+app.arryList.get(position));

      }
  });

      }
  });

  return layout;

A: Try this, Use ListView.CHOICE_MODE_MULTIPLE
 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

A: I think that ListView.CHOICE_MODE_SINGLE will be more suitable for his needs.
But maybe it will be a not bad idea to save an array of your radio buttons and to set them accordingly.

A: I tried to solve your issue and done from my side.
I explain approach below and for more details and complete Source code go through this blog below.
http://amitandroid.blogspot.in/2013/03/android-custon-single-choice-lsitview.html
Hope this will solve your problem.

I created Custom single Choice list. You can change the layout and add your widget accordingly.
Step1)
package com.custom.view;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.RelativeLayout;

public class CheckableRelativeLayout extends RelativeLayout implements
        Checkable {

    private boolean isChecked;
    private List<Checkable> checkableViews;

    public CheckableRelativeLayout(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
        initialise(attrs);
    }

    public CheckableRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialise(attrs);
    }

    public CheckableRelativeLayout(Context context, int checkableId) {
        super(context);
        initialise(null);
    }

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean isChecked) {
        this.isChecked = isChecked;
        for (Checkable c : checkableViews) {
            c.setChecked(isChecked);
        }
    }
    public void toggle() {
        this.isChecked = !this.isChecked;
        for (Checkable c : checkableViews) {
            c.toggle();
        }
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        final int childCount = this.getChildCount();
        for (int i = 0; i < childCount; ++i) {
            findCheckableChildren(this.getChildAt(i));
        }
    }

    /**
     * Read the custom XML attributes
     */
    private void initialise(AttributeSet attrs) {
        this.isChecked = false;
        this.checkableViews = new ArrayList<Checkable>(5);
    }

    /**
     * Add to our checkable list all the children of the view that implement the
     * interface Checkable
     */
    private void findCheckableChildren(View v) {
        if (v instanceof Checkable) {
            this.checkableViews.add((Checkable) v);
        }

        if (v instanceof ViewGroup) {
            final ViewGroup vg = (ViewGroup) v;
            final int childCount = vg.getChildCount();
            for (int i = 0; i < childCount; ++i) {
                findCheckableChildren(vg.getChildAt(i));
            }
        }
    }
}

Step2)
package com.custom.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.CheckBox;
public class InertCheckBox extends CheckBox {

    public InertCheckBox(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public InertCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public InertCheckBox(Context context) {
        super(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onTrackballEvent(MotionEvent event) {
        return false;
    }
}

Step3)
<?xml version="1.0" encoding="utf-8"?>
<com.custom.view.CheckableRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginRight="10dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <com.custom.view.InertCheckBox
        android:id="@+id/singleitemCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:focusable="false"
        android:button="@drawable/single_radio_chice" />

    <TextView
        android:id="@+id/singleitemId"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_toRightOf="@+id/singleitemCheckBox"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:textSize="14sp"
        android:focusable="false" />

    <TextView
        android:id="@+id/nextitem"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_toRightOf="@+id/singleitemId"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:textSize="14sp"
        android:focusable="false" />

</com.custom.view.CheckableRelativeLayout>

Step4)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="#00000000"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp"
        android:choiceMode="singleChoice"
        android:listSelector="#00000000" />

</RelativeLayout>

Step5) single_radio_chice.xml
 <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">

        <item android:state_checked="false"
            android:drawable="@drawable/radio_off" />

        <item android:state_checked="true"
            android:drawable="@drawable/radio_on" />
    </selector>


text:
Q: Продвинутая система оценки (как в github) к примеру, в Github (да и в facebook), есть интересная система оценки комментария

Пытаюсь понять как все это происходит, понял пока что:
Есть отдельная таблица с полями: id_user, comment_id, flag
Где flag, заранее продуманная таблица (в уме), то есть если flag = 1, то поставили +1, flag = 2 — -1. Обычная связывающая таблица
Как же грамотно организовать запрос к БД, чтобы все нормально получить? Или нужно велосипедами все после получения результата обрабатывать?


text:
Q: Find and display only values that are the same in sql I am doing a query based on a swimming event.  There are unique event codes, as well as unique swimmer codes, and their placing.  I am currently having a problem, as I want to display only swimmers that have TIED in the same event (EG I want to display only the swimmers that tied in the 100m relay).
Is there some syntax which does that?
I was doing something similar to this
SELECT Swimmers, Eventid, Place
FROM Results
WHERE Place=Place
AND Eventid=Eventid

But that includes even swimmers that did not tie.
Any suggestions would be great

A: Try this,
SELECT Swimmers,
       Eventid,
       Place
FROM  Results a INNER JOIN
        (
            SELECT EventID, Place ,COUNT(Place) totalPlace
            FROM Results
            GROUP BY EventID, Place
            HAVING COUNT(Place) > 1
        ) b ON a.eventID = b.EventID AND
                a.Place = b.Place
-- WHERE -- add extra conditions here

A: You could do something like this
    SELECT Swimmers, EventId, Place
    FROM Results r JOIN
      (SELECT EventId, Place
       FROM Results
       GROUP BY EventId, Place
       HAVING COUNT(*) > 1) t ON (r.EventId = t.EventId AND r.Place = t.Place)


text:
Q: Making test cases for a contact form Okay I have a simple contact form with a project type, company name, phone, email, project name, project budget, description, attachment. I'm supposed write 5 tests on it. And I'm supposed to test functionality and what has the highest risk of failure.
When making test cases, should I make some tests fail? like 3 out 5 failed and 2 successes. Or does anyone have any examples of what should I be looking for?

A: Here is what you have, the area of high risk in bold or required fields imho:

*

*project type,

*company name,

*phone,

*email,

*project name,

*project budget (digits or anything),

*description,

*attachment
So if I would write 5 test cases I would outline like this:
Test 1: Positive, meaning all forms complete correctly user able to submit form,
Test 2: Required fields is not complete,
Test 3: Phone number is  not correct:
a). digit wise
b). what if you provide characters instead of digits
Test 4: Email incorrect
Test 5: Attachment:
a). file as expected
b). file to large
c). no file


text:
Q: How can I read a Google spreadsheet in a Team Drive in R? this is probably a really simple question, but I can't seem to figure it out.
We recently moved a project from a shared folder on Google Drive to a Team Drive. I used to directly access the spreadsheet from R with this code:
library(googlesheets)
mydir <- gs_ls() #authenticate to google list sheets
mydir$sheet_title
mygs <- gs_title(x = "FileName", verbose = F) #read file
mygs <- gs_read(ss = mygs, ws = "SheetName", skip=1) # get specific worksheet

But now that we moved the project, it doesn't work anymore, as the googlesheets package only works on my Google Drive directory. I've found a package for accessing my Team Drive (googledrive) and I've managed to find the file within the directory but I can't seem to figure out how to READ my specific worksheet anymore:
library(googledrive)
td <- team_drive_find()
myfile <- drive_find(team_drive = as_id(td$id[td$name=="TDriveName"]),
                     pattern = "FileName")
myfile <- drive_get(id = as_id(myfile$id), verbose = TRUE)

This gives me a tibble with the metadata of the spreadsheet but not the actual spreadsheet like gs_title() does. There has to be a function to do this right?

A: This is currently a work in progress for a new reboot of the googlesheets package, called googlesheets4, which is not yet released on CRAN.
However, you can currently achieve what you want with a combination of the googlesheets package and the googledrive package, as you eluded to above.
First, you have to get the metadata for a particular spreadsheet using drive_get, and specify the team drive, either by name or ID or URL.  Then, register the spreadsheet with any of the functions for this from the googlesheets package, i.e. gs_title, gs_key, or gs_url.
The workaround here is to set the arguments lookup = FALSE and visibility = "private" in gs_key.
I prefer to use team drive IDs and spreadsheets keys, as opposed to names.  You can use team_drive_find to get the IDs of your team drives.
See below:
library(dplyr)   # For pipe operator, %>%
library(googledrive)
library(googlesheets)

data <-
  drive_get(path = "example-googlesheet-name",
          team_drive = as_id("0ABCDefGH2jK_Lm3NPA")) %>%
  select(id) %>%
  combine() %>%
  gs_key(lookup = FALSE,
         visibility = "private") %>%
  gs_read_csv()

The above code reads in the example spreadsheet from a team drive, via the team drive's ID.  From the metadata returned by drive_get, it selects the ID, combines it into a vector, and passes the ID to gs_key to register the spreadsheet.  gs_read_csv then reads in the register spreadsheet and assigns the result to data.
See these Github issues for more information:
https://github.com/jennybc/googlesheets/issues/327
https://github.com/jennybc/googlesheets/pull/318

A: It's been issued and currently there's no solution for this problem yet. Workaround work :  move back to your own drive or create one shared gmail account that accessible for all of your team, then work collaborately with that account.


text:
Q: Why BASE64 encode/decode works differently in javascript and Oracle I encode a string 'test me ąčęėįš' in javascript like this:
  function toBinary(string) {
    const codeUnits = new Uint16Array(string.length);
    for (let i = 0; i < codeUnits.length; i++) {
      codeUnits[i] = string.charCodeAt(i);
    }
    return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
  }

  console.log(btoa(toBinary('test me ąčęėįš')));
  // output:  dABlAHMAdAAgAG0AZQAgAAUBDQEZARcBLwFhAQ==

If I encode the same string i Oracle base64 encoding generates different output:
select utl_encode.BASE64_ENCODE(utl_raw.cast_to_raw('test me ąčęėįš')) from dual;
-- output 6447567A644342745A534467364F62723466413D

Why is that? Does BASE64 encoding/decoding work differently in Oracle and javascript?
Of course when I try in Oracle decode javascript encoded string it not work:
select utl_encode.base64_decode('dABlAHMAdAAgAG0AZQAgAAUBDQEZARcBLwFhAQ==') from dual;
-- output: ORA-01465: invalid hex number

How in Oracle decode in javascript base64 encoded string?


text:
Q: When all AJAX requests complete I have an ajax request that grabs some data and then splits it up into an array.  The array length is variable.
  var ajax1 = $.ajax({
    url: 'myurl.php',
    type: "GET",
    dataType: "jsonp",
    success: function (data) {

      //create an array

    }

  });

Once I have the array, I want to loop through it and in each iteration run another AJAX request.  I put it inside a $.when to make sure the initial ajax request was complete:
  $.when(ajax1).done(
    function() {

      for (i = 0; i < array.length; ++i) {

        $.ajax({
          url: 'anotherurl?=' + myarray[i],
          type: "GET",
          dataType: "jsonp",
          success: function (data) {

            //do stuff here

          }
        });

      }

    }
  )

My question is, how can I get a message box to pop up when the for loop has completed all the AJAX requests? A simple alert('complete') at the end of the loop won't work as the AJAX is done async.

A: As of JQuery 1.5, $.ajax() return an object which implement the promise interface, so you can store all of those promises in an array and wait for them to finish using Promise.all().
Something like:
  var root = 'http://jsonplaceholder.typicode.com';
  var p = [];

  p.push( $.ajax({url: root + '/posts/1', method: 'GET'}));
  p.push( $.ajax({url: root + '/posts/2', method: 'GET'}));
  p.push( $.ajax({url: root + '/posts/3', method: 'GET'}));
  p.push( $.ajax({url: root + '/posts/4', method: 'GET'}));

  Promise.all(p).then(values => {
    console.log( 'Ajax responses after they have all finished: ', values);
  });

See this plnkr for an exemple.
Hope this help !

A: You can achieve this by also using $.when. You just need to store all the AJAX requests you make in an array and apply() that array to $.when. Try this:
$.when(ajax1).done(function() {
    var requests = [];
    for (i = 0; i < array.length; ++i) {
        requests.push($.ajax({
            url: 'anotherurl?=' + myarray[i],
            dataType: "JSONP",
            success: function (data) {
                // do stuff here
            }
        }));
    }
    $.when.apply($, requests).done(function() {
        console.log('complete');
    });
})

You can also shorten the logic slightly by using map(), although be aware this won't work in < IE9.
$.when(ajax1).done(function() {
    var requests = array.map(function() {
        return $.ajax({
            url: 'anotherurl?=' + myarray[i],
            dataType: "JSONP",
            success: function (data) {
                // do stuff here
            }
        });
    });
    $.when.apply($, requests).done(function() {
        console.log('complete');
    });
})

A: jQuery is going to rear its stubborn head pretty quickly here. I'd recommend you reach for something better like Promises that give you more control in this type of situation
const pajax = opts=>
  new Promise((resolve, reject)=>
    $.ajax(opts).done(x => resolve(x)).fail((_,_,err)=> reject(err))

Then you could use it like this with Promise.all
pajax({
  url: 'myurl.php',
  type: "GET",
  dataType: "jsonp",
})
.then(data => {
  // create your arr
  let arr = ...

  return Promise.all(arr.map(x=> {
    return pajax({
     url: 'anotherurl?=' + x,
     type: "GET",
     dataType: "jsonp"
    })
  }))
})
.then(data => {
  console.log('this is called after all promises are done'
})
.catch(err=> {
  console.error(err)
})

EDIT
@RoryMcCrossan's answer is nice if you want to keep everything in the jQuery realm


text:
Q: CI: form validation then inserting data securely (but without characters converted to html code) I'm processing a registration form and this is how I do it currently:
$this->form_validation->set_rules('first_name','First Name','trim|required');
$this->form_validation->set_rules('last_name','Last Name', 'trim|required');
....

if ($this->form_validation->run() === TRUE)
{
    $data = array('first_name' => set_value('first_name')
    ....

// model
$this->db->insert('registration',$data))

Problem:
If the name has an apostrophe in it, it ends up in MySQL as '
What would be the best way to process and input this data into MySQL securely but without encoding these types of characters?


text:
Q: SQL Query seems to multiply results? I am using this query to display how many times a person has been a referee and an assistant referee in matches.
However it seems to be multiplying the ref number by the AR number, so if it should be 11 & 6, it says 66 & 66.  I can't see why?  (And it's probably very obvious to experienced coders):
SELECT CONCAT (lastname,', ',firstname),
    A.gender,
    DATE_FORMAT(dob, '%d %b %y'),
    DATE_FORMAT(dod, '%d %b %y'),
    CASE
        WHEN NOT dod = '0000-00-00'
            THEN TIMESTAMPDIFF(year, dob, dod)
        ELSE TIMESTAMPDIFF(year, dob, Curdate())
        END,
    B.NAME,
    COUNT(M.REF),
    COUNT(M1.AR1),
    refID
FROM refs A
    LEFT JOIN teams B
        ON A.Nationality = B.TeamID
    LEFT JOIN matches M
        ON A.refID = M.REF
    LEFT JOIN matches M1
        ON A.refID = M1.AR1
GROUP BY A.refID
ORDER BY lastname;

Appreciate the help.


text:
Q: How create a debugger for self-made language? I wanna build a language, but I think that to be useful it need at least a REPL and a debugger.
How incorporate a debugger is the thing that look like magic to me. I remember how great the old Visual FoxPro was, and how much sucks the xcode (in comparison) so I suspect is something hard.
Which kind of language make easier to integrate a debugger? A interpreter? Compiled? Imperative? Functional?
Make a difference if the language is made in LLVM, Lua/LuaJit, on top of objective-c? (I ask about this because for my pet language how easier could be is a critical factor. So the easier target that will make a easier answer, I suppose)
Is the best way to use GDB/LLDB or roll my own?
Where to look about this?

A: This will be much easier for an interpreter.  Before executing a statement, you can check whether a global "paused" flag is set and pause if it is.  Before executing a procedure, you can check to see whether a "traced" flag is set on that procedure, and set the "paused" flag, restoring it to its previous value on return.

A: Visual Studio Code offer the possibility to implement your own extensions adding:

*

*Custom Language

*Custom REPL

*Custom Debugger

Here is a tutorial covering all those topics step by step.


text:
Q: How to insert date type value with slashes instead of dashes in mysql? I have been trying to insert a value into a date type column with slashes but keep gives me either null(when success) or fail.
CREATE TABLE if not exists EMPLOYEE (
   id primary key,
   dob Date
)

Above is the structure of the table
INSERT INTO EMPLOYEE VALUES (1, convert(date, "17/12/2015", 103));
INSERT INTO EMPLOYEE VALUES (1, CAST("15/2/1995" AS DATE));

The two lines of code are ones i have tried.
By using the first line, it raises an error.
Second line successfully creates a record but ended up having NULL in the dob column.
I have actually shortened them for readability but if you need anything else i am happy to provide.

A: First, you should just use the standard format for date:
INSERT INTO EMPLOYEE (id, dob)
    VALUES (1, '2015-12-17');

If you want a different format in MySQL, then use str_to_date():
INSERT INTO EMPLOYEE (id, dob)
    VALUES (1, STR_TO_DATE('17/12/2015', '%d/%m/%Y'));

The CONVERT() function you are trying to use is a SQL Server extension.  It does not work in other databases (well, apart from Sybase because it is really a Sybase extension and SQL Server is based on that code base).


text:
Q: Partition of Symmetric Group For symmetric group $S_n$, we need to find a collection of subgroups $G_i$'s such that union of these subgroups is the group $S_n$ and each subgroup found is isomorphic to direct product of cyclic groups, each of order more than 1.
How can we find these subgroups such that sum of sizes of the subgroup is not much more than $S_n$ i.e. $(1 + o_n(1))\cdot|S_n|$?


text:
Q: Do we need to write string name resources tag separately? Since, the text displayed on the button is hard coded. I am trying to pass the string through resources to the text of the button.I learned that we can add it through the resources of string.xml.
I added the resources tag separately, it gave errors. So, I added in the same place, it's still showing errors. As the errors are visible already so I did not compile. The red line error is on these words:
 name="I am the passed string for the button. But, I don't know how to go there?">

<string name="app_name">Wednesday</string>

<string name="I am the passed string for the button. But, I don't know how to go there?">chocobar</string>

I want this text to be displayed on Button. This is a static text.

A: You can't use white and some special character inside String.xml key, you'll be able to white space in value, here is solution.
<string name="app_name">Wednesday</string>

<string name="chocobar">I am the passed string for the button. But, I don't know how to go there?</string>

try this one.

A: You must have the text you need to show in the button inside the <string> tags.
<string name="chocobar">I am the passed string for the button. But, I don't know how to go there?</string>

In your layout file use the reference chocobar to set the string to the button,
android:text="@string/chocobar"

A: Try :
<string name="chocobar">I am the passed string for the button. But, I don't know how to go there?</string>
name is for you to identify the string when assigning the text to the Button
The text between the > and < is what will get displayed on the Button

A: Inside the string.xml resource name should not contain any white space. That is the reason why you are getting such an error. It is not good practice to give such a long name to the identifier, even though there is no harm to do so.
Solution
 string name="chocobar">I am the passed string for the button. But, I don't know how to go there?</string>

if you want to access chocobar from java code or XML

A: '<string name="string_tag">string</string>'

if you want to call the string for xml:
'android:text="@string/string_tag"  '

...for kotlin or java:
'R.string.string_tag'


text:
Q: Finding layout of points on road? The problem I'm trying to solve is finding layout of street lights on a street. The street lights can be arranged in the following layout: one-side, two-side opposite, staggered, or median, etc. as shown in the picture.

I have latitude, longitude of street light points of several cities and I want to build a classifier that can determine the road lighting layout.
I thought of the following approach so far but I'm stuck at what should I do after a step.

*

*Reverse geocode all the street light points using Nominatim and assign each one to a street_id using street name as well as get the OSM way id.

*Use the OSM way id to obtain the polyline of the street.

*Find out which points lie on which side of the polyline using Linear Referencing Toolbox in ArcGIS.

*Find the distance between poles by calculating average distance to nearest neighbor on each side of the road.

I'm stuck here.


text:
Q: Passing multiple values in CASE clause I have 3 set of statuses as follows:

*

*Active, In Process

*Approved, Shipped

*Closed, Rejected

What I am trying to do is construct a sql query and add a CASE clause in the WHERE. So far I have the following:
DECLARE @showFirstSetOfStatuses BIT = 1
DECLARE @showSecondSetOfStatuses BIT = 0
DECLARE @showThirdSetOfStatuses BIT = 0

SELECT RequestId, RequestName, RequestStatus
FROM SomeTable md
WHERE md.RequestStatus IN(CASE WHEN @showFirstSetOfStatuses = 1 THEN 'Active, In Process'
                      WHEN @showSecondSetOfStatuses = 1 THEN 'Approved, Shipped'
                      WHEN @showThirdSetOfStatuses = 1 THEN 'Closed, Rejected' END)

This of course does not bring back any result because it's not matching the statuses. I can't seem to figure out how to pass multiple values in the THEN part of the CASE clause. So something like
THEN 'Active', 'In Progress'
...

Can someone tell me how to go about this or is it not possible?

A: Is this what you want?
SELECT RequestId, RequestName, RequestStatus
FROM SomeTable md
WHERE ( (@showFirstSetOfStatuses = 1 AND md.RequestStatus IN ('Active', 'In Process') ) OR
      ( (@showSecondSetOfStatuses = 1 AND md.RequestStatus IN ('Approved', 'Shipped') ) OR
        (@showThirdSetOfStatuses = 1 AND md.RequestStatus IN ('Closed', 'Rejected') )
      );

Food for thought:  I would use one flag that takes on three values, rather than three different flags:
DECLARE @showSetOfStatuses INT = 1;

SELECT RequestId, RequestName, RequestStatus
FROM SomeTable md
WHERE ( (@showSetOfStatuses = 1 AND md.RequestStatus IN ('Active', 'In Process') ) OR
      ( (@showSetOfStatuses = 2 AND md.RequestStatus IN ('Approved', 'Shipped') ) OR
        (@showSetOfStatuses = 3 AND md.RequestStatus IN ('Closed', 'Rejected') )
      );


text:
Q: Flask-migrate работает наоборот хочу поделиться такой проблемой. Пишу приложение на Flask(бд PostgreSQL) и для миграций использую Flask-migrate. Проблема заключается в том, что при попытке инициализации (flask db init) и последующей миграции(flask db migrate) создается файл с описанием апгрейда и даунгрейда, где в апгрейде УДАЛЯЮТСЯ все мои таблицы, а в даунгрейде СОЗДАЮТСЯ.
Я подозреваю, что проблема решается настройкой файлов alembic, который идет вместе с Flask-migrate, но не могу разобраться где и что именно необходимо поменять/настроить под себя, чтобы все работало правильно, а не наоборот(пока что вручную создаю revisions и пишу все руками, но хотелось бы разобраться в проблеме).


text:
Q: Quartz service is not working using Spring Feign Client I create a real time notification functionality using spring quartz library. I create two services as bellow :
1) quartz-service : Which is used to set schedule a for real time notification.
2) task-service : Which is used to create a task and remind through quartz-service.
When task-service call quartz-service through feign client I'm not get any response. But If I call through Rest Template it's working find.
Actually we are used spring boot microservice architecture, In using Rest Template we need to specify URL Hard coded, So we can't achieved Ribbon concept in this case that's why we not interest to use Rest Template.
So please help me if any once face this problem.
quartz-service :
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-quartz</artifactId>
    </dependency>
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Rest Controller :
 @RestController
    @RequestMapping(value = "/quartz/taks", produces = "application/hal+json")
    public class QuartzTaskController
    {
        @Autowired
        private QuartzTaskServices quartzTaskServices;

        @PostMapping("/reminder")
        public ResponseEntity<Object> saveTaskReminder(@RequestBody Task task)
        {
            quartzTaskServices.saveTaskReminderScheduler(task);
            return ResponseEntity.ok().build();
        }
    }

task-service
Dependency :
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

Feign Client :
@RibbonClient(name="quartz-services")
@FeignClient(name="quartz-services")
public interface QuartzProxy
{
    @PostMapping("/quartz/taks/reminder")
    public ResponseEntity<Object> saveTaskReminder(@RequestBody Task task);
}

Call Feign Client :
@Autowired
private QuartzProxy quartzProxy;
...
.....
......
quartzProxy.saveTaskReminder(task);


text:
Q: LWP UserAgent post @list I still struggle with the most basic Perl syntax and googling operators is near impossible unless you know what you don't know so you can use the right terms.  So 2 questions, 1) what is the right syntax and 2) what are the terms I would have used to find the answer?
The syntax -- I have a list of something (hashes?):
my @list = [ "foo"=> "bar", "foo"=>"orange"];

I need to declare the list and then add each item individually (filling will be done in a loop and other methods), but cannot seem to find the right syntax:
my @list = [];
# add foo=bar
# add foo=orange

The end goal is to post a form that unfortunately uses duplicate keys via LWP::UserAgent and the $ua->post( $url, \@form ) method.  I can get it to work declaring the list and all contents in one go, but can't seem to find the right syntax for splitting it up and building the contents incrementally.

A: You would have used perldoc (either the program on your computer or the website) to find answers.
my @list = [ "foo"=> "bar", "foo"=>"orange"];

You don't have a list, you have an array (called @list). This array has one element, which is a reference to (another) array containing four strings: foo, bar, foo, orange. I doubt this is what you want:
my @list = ("foo" => "bar", "foo" => "orange");

seems more likely (this is an array containing four strings directly, without the additional nested array).
To build this up procedurally, you can do the following:
my @list;
push @list, "foo";
push @list, "bar";
push @list, "foo";
push @list, "orange";

or:
my @list;
push @list, "foo" => "bar";
push @list, "foo" => "orange";

Relevant perldoc pages for this would be perldoc perldata, perldoc perlreftut, and perldoc -f push.


text:
Q: How to get FormatProvider from Autodesk.AutoCAD.Geometry.Point3d I have some Point3d stored as text in the DataGridView cell.
Autodesk.AutoCAD.Geometry.Point3d px = new Point3d ( 100.0 , 123.0 , 0.0); // for example
row.Cells["IDS_ReferenePoint"].Value = px.ToString();

so I have the value: "(100.0,123.0,0.0)"
Now I need to reverse that operation - read that point from DataGridView cell and convert to Point3d object. So I may do it by remove (, ) split text by separating columns sign , and each coordinate parse to double.
But I'm afraid that on other PC with different language settings , will be decimal places separator, and for example [SPACE] would be a coordinate separator.
Is there an easy way to get FormatProvider default used in Point3d.ToString() ? depended on user PC configuration?

A: As far as I know, the Point3d format is not related to the Windows decimal separator. I used to use French versions of AutoCAD and the decimal separator for AutoCAD is the dot whatever the Windows settings (comma is the default windows decimal separator for French versions). And the comma is the coordinate separator for AutoCAD points, vector, matrices.
So, I think you do not have to care to Point3d.ToString() format which is always the same whatever the culture version.


text:
Q: Is there a way to create a dynamic named range in a google sheet? I am working on creating a score keeping and scoring sheet for my FTC (a competitive robotics league) Team, and am trying to make a dynamic named range. it needs to be dynamic, because the range is used in matrix multiplication, so the range needs to end with the data. I frequently add new data, and am automating that part. In an effort to automate the sheet. I would like to be able to define the boundaries of the range to the edge of the data, in both a downwards direction and to the right. currently, the data is 170 something columns wide and nearly 3,000 rows long.
I tried using several online methods, which didn't work, either due to my stupidity, or them being outdated. How to create dynamic named ranges in Google Sheets this link is the way that I tried, and it does not seem to work.
I no longer have the function I wrote, it got deleted in one of my attempts, and I did not notice until it was to far back to return to.


text:
Q: Non-blocking pasv sock and blocking connection (active) socket On my TCP server I would like to have:

*

*non-blocking passive socket to have non-blocking accept();

*after accepting connection I would like to perform some authentication like verifying client provided Id and Password. So I have well defined protocol and I would like to have blocking recv()/send() talk between TCP server and client via connection socket.

*After client identity verification I would like to have non-blocking connection socket to enable server shutdown from external thread.
The problem is that when I firstly set non-blocking PASSIVE socket then accepted CONNECTION sockets are also non-blocking? Why aren't they separate sockets?
I have set passive socket to non-blocking mode using this code:
fcntl(ps_fd, F_SETFL, O_NONBLOCK);

I do authentication through connection socket:
if((n_recv = recv(sock_fd, buf, sizeof(buf) - 1, 0)) <= 0) { ... }

But here recv() doesn't block and client cannot deliver it's authentication id and password on the time before EAGAIN error.
Can I revert connection socket to be in blocking mode again, and passive socket left non-blocking?

A: The blocking-status is not inherited by accepted sockets in Linux. On BSD-derived systems (like macOS and probably Windows (though I can't find anything specified)) the non-blocking is inherited.
One solution is of course to make the accepted socket blocking again, and then non-blocking once the authentication phase is done. This will block the rest of the program if you're single-threaded, meaning you can't accept other connections while one user is authenticating.
Another possible solution is to use threads, or even processes, to handle connections.
Or you could use some polling like select, poll or if you're on Linux use epoll (or corresponding variants on BSD systems) to know when there is data to be received on the accepted socket. For this to work you could use a simple state-machine, where you have states like WAITING_FOR_USERNAME, WAITING_FOR_PASSWORD and LOGGED_IN etc.

A: I have tried such solution and it seems to work.
For me on OS X connection socket received from accept() on passive socket inherits its non-blocking mode. So after accept I am changing the connection socket mode to blocking one again.
Example code
    fcntl(ps_fd, F_SETFL, O_NONBLOCK);

    int cs_fd = accept(ps_fd);
    // revert connection socket to non-blocking
    int opts = fcntl(cs_fd, F_GETFL);
    opts = opts & (~O_NONBLOCK);
    fcntl(cs_fd, F_SETFL, opts);

    // then authentication via cs_fd

    // after authentication change it to non-blocking again
    fcntl(cs_fd, F_SETFL, O_NONBLOCK);


text:
Q: Failed to load resource: the server responded with a status of 404 (Not Found) Angular 7 I have a folder LearningBoard and all my AngularJS content(index.html, js, css files) are inside that folder. I am using grunt.js to generate war file and deploy it on jboss server.
After generating war file all my content is outside web-inf folder.
I am able to load http://localhost:38080/learningboard but I do not see any content loading.
In my index.html I have entry like <base href="/">.
On console I see

Failed to load resource: the server responded with a status of 404
  (Not Found) styles.js:1 Failed to load resource: the server responded
  with a status of 404 (Not Found)

If I put all my content inside web-inf folder then I get 404 resource not found.
How to load js and css content when I hit http://localhost:38080/learningboard ?
I am using Angular 7.
Grunt JS code
module.exports = function ( grunt ) {
    grunt.loadNpmTasks( 'grunt-war' );

    var taskConfig = {
        war: {
            target: {
                options: {
                    war_verbose: true,
                    war_dist_folder: 'warFile',           // Folder path seperator added at runtime.
                    war_name: 'Test',            // .war will be appended if omitted
                    webxml_welcome: 'index.html',
                    webxml_display_name: 'Test'
                },
                files: [
                    {
                        expand: true,
                        cwd: 'dist/learningboard',
                        src: ['**'],
                        dest: ''
                    }
                ]
            }
        }
    };

    grunt.initConfig( taskConfig );
};


text:
Q: Existence of composition series of infinite groups (especially the braid groups and the general linear group) How can I argue that there are no composition series for the braid groups or the general linear group $GL(n,\mathbb{R})$ ?
I have already learned that this is related to the infinite abelianization of these groups.
But it is not clear to me why I can conclude from an infinite abelianization that there is no composition series for these infinite groups.
I would be very happy if someone could explaint this to me.


text:
Q: Qt: Connect Signal QAbstractItemModel::dataChanged to Slot: I want to connect this signal https://doc.qt.io/qt-5/qabstractitemmodel.html#dataChanged to my class. It is defined in qabstractitemmodel.h (QT own):
Q_SIGNALS:
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>());

and emitted in my implementation of qabstractitemmodel:
bool Main::setData(const QModelIndex &index, const QVariant &value, int role){
if ( !index.isValid() || index.column() != 1 )
    return false;
...
emit dataChanged(index, index, QVector<int>( Qt::ItemDataRole::DisplayRole ));
return true;
}

I want to connect the signal so this slot:
void setProperty(const QModelIndex & topLeft, const QModelIndex & bottomRight, const QVector<int> &roles= QVector<int>());

(I copied parameters in hope this is saftiest solution)
and tried different connection methods
connect( _container->_model, SIGNAL(dataChanged () ), this, SLOT(setProperty()) );

connect( _container->_model, SIGNAL(dataChanged (const QModelIndex &, const QModelIndex &, const QVector<int> & )), this, SLOT(setProperty(const QModelIndex &, const QModelIndex &, const QVector<int> & )));

but I always got error: No such signal.


text:
Q: React Native useEffect not run when app first opened I am trying to make an app where the USER_ID is loaded from the device's local storage if found, otherwise, a new id is generated and stored in the local storage. I am trying to make use of React useContext() to make the USER_ID visible to the whole app after it is first run.
import React, {useEffect, useState} from 'react';

import AsyncStorage from '@react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';

export const UserIdContext = React.createContext('undef');

export const UserIdProvider = ({children}) => {
  const [userId, setUserId] = useState('');

  useEffect(() => {
    async function getOrInitUserId() {
      try {
        let temp = await AsyncStorage.getItem('USER_ID');
        if (temp == null) {
          temp = uuid.v4();
          await AsyncStorage.setItem('USER_ID', uuid.v4());
          console.log('USER_ID Generated: ' + temp);
        } else {
          console.log('USER_ID Found: ' + temp);
        }
        setUserId(temp);
      } catch (error) {
        console.error(error);
      }
    }

    if (!userId) {
      getOrInitUserId();
    }
  });

  return (
    <UserIdContext.Provider value={userId}>{children}</UserIdContext.Provider>
  );
};

export const useUserId = () => React.useContext(UserIdContext);

The provider is used as below:
const App = () => {
  useEffect(() => {
    ....
  });

  return (
    <UserIdProvider>
      ...contents of app...
    </UserIdProvider>
  );
};

export default App;

However, the useEffect() of < UserIdProvider /> is not run as the app is launched for the first time after being installed on a device, as there is no log on the console. After the app is closed/quit and relaunched, the console log a USER_ID found, instead of USER_ID generated.

A: Add 2nd argument as [] so it will render only once. Otherwise, it will render every time when any state will be updated.
 const App = () => {
      useEffect(() => {
        ....
      },[]);

      return (
        <UserIdProvider>
          ...contents of app...
        </UserIdProvider>
      );
    };

export default App;

A: In order to trigger useEffect when first run you should enter [] as prop like this:
useEffect(() => {
    async function getOrInitUserId() {
      try {
        let temp = await AsyncStorage.getItem('USER_ID');
        if (temp == null) {
          temp = uuid.v4();
          await AsyncStorage.setItem('USER_ID', uuid.v4());
          console.log('USER_ID Generated: ' + temp);
        } else {
          console.log('USER_ID Found: ' + temp);
        }
        setUserId(temp);
      } catch (error) {
        console.error(error);
      }
    }

    if (!userId) {
      getOrInitUserId();
    }
  }, []);


text:
Q: C++-What is the need of both buffer and stream? Although i have read about  buffer and stream and it's working with files in c++ but i don't know what is the need of a buffer if a stream is there, stream is always there to transfer the data of one file to the program. So why do we use buffers to store data(performing same task that stream does) and what are buffered and unbuffered stream.

A: Consider a stream that writes to a file. If there were no buffer, if your program wrote a single byte to the stream, you'd have to write a single byte to the file. That's very inefficient. So streams have buffers to decouple operations one on side of the stream from operations on the other side of the stream.

A: Ok lets lets start from the scratch suppose you want to work with files. For this purpose you would have to manage how the data is entered into your file and if the sending of data into the file was successful or not, and all other basic working problems. Now either you can manage all that on your own which would take a lots a time and hard work or What you can do is you can use a stream.
Yes, you can allocate a stream for such purposes. Streams work with abstraction mechanism i.e. we c++ programmers don't know how they are working but we only know that we are at the one side of a stream (on our program's side) we offer our data to the stream and it has the responsibility to transfer data from one end to the other (file's side)
Eg-
ofstream file("abc.txt"); //Here an object of output file stream is created
file<<"Hello";            //We are just giving our data to stream and it transfers that
file.close();             //The closing of file

Now if you work with files you should know that working with files is a really expensive operation i.e. it takes more time to access file than to access memory and we also don't have to perform file operations every time. So programmers created a new feature called buffer which is a part of computer's memory and stores data temporarily for handling files.
Suppose at the place of reading file every time to read data you just read some memory location where all the data of file is copied temporarily.Now it would be a less expensive task as you are reading memory not file.
Those streams that have a buffer for their working i.e. they open the file and by default copy all the data of file to the buffer are called as buffered streams whereas those streams which don't use any buffer are called as unbuffered streams.
Now if you enter data to a buffered stream then that data will be queued up until the stream is not flushed (flushing means replacing the data of buffer with that of file). Unbuffered streams are faster in working (from the point of user at one end of the stream) as data is not temporarily stored into a buffer and is sent to the file as it comes to the stream.

A: A buffer and a stream are different concepts.
A buffer is a part of the memory to temporarily store data. It can be implemented and structured in various ways. For instance, if one wants to read a very large file, chunks of the file can be read and stored in the buffer. Once a certain chunk is processed the data can be discarded and the next chunk can be read. A chunk in this case could be a line of the file.
Streams are the way C++ handles input and output. Their implementation uses buffers.

A: I do agree that stream is probably the poorest written and the most badly udnerstood part of standard library. People use it every day and many of them have not a slightest clue how the constructs they use work. For a little fun, try asking what is std::endl around - you might find that some answers are funny.
On any rate, streams and streambufs have different responsibilities. Streams are supposed to provide formatted input and output - that is, translate an integer to a sequence of bytes (or the other way around), and buffers are responsible of conveying the sequence of bytes to the media.
Unfortunately, this design is not clear from the implementation. For instance, we have all those numerous streams - file stream and string stream for example - while the only difference between those are the buffer. The stream code remains exactly the same. I believe, many people would redesign streams if they had their way, but I am afraid, this is not going to happen.


text:
Q: Garbled entries on list of figures using subfloat MWE:
\documentclass[english]{scrbook}
\usepackage{graphicx}
\usepackage{subfig}
\usepackage{babel}

\begin{document}
\listoffigures

\begin{figure}
\subfloat[Figure A.]{\includegraphics[width=5cm]{test1}}
\subfloat[Figure B.]{\includegraphics[width=5cm]{test2}}
\caption{Figures A and B.}
\end{figure}

\end{document}

Output:

This overlapping only occurs if I use subfloats. Both lualatex and pdflatex give the same result.
I am a LyX user, so I would like to stick to what it offers (subfloats, in the case). Some simple fix in the preamble would be best.


text:
Q: Columns not aligned in MS Word As I'm trying to redact my Curiculum, I wrote everything I wanted and then selected all the sections I wanted to have in 2 columns. I applied the layout but I can't get rid of the empty space on top of the second column as seen on the screenshot. Do you have any idea how did this appear ?
I put a column break at the end of the first column and nothing before the title of the 2nd column.

A: I know this is an old post but I just encountered the same problem and think I figured it out.  If the next column begins with a new paragraph, and that paragraph is styled with, say, 12pt spacing before it, the 12pt space will appear.   If you're using something from "Styles" to format the first line of the next column, it's quite possible this is the cause.  Modify the style so the spacing "Before" it is set to 0.  This might mess up the spacing for the rest of your styles and paragraphs, so you may have to remove spacing "Before" and add it "After" all of them.  You can "Modify" a style, click the "Format" menu button in the lower left of the dialog that appears, choose "Paragraph", and then you'll see the choices in the screen shot below.  I hope this helps someone out there.
Modify Style > Format menu > Paragraph:

A: Added a section break after the blurred part, removed 6 pts spacing before the 2nd column and it fixed everything.


text:
Q: Querying-friendly domain objects localization I need to design an application which stores partially multi-lingual content; i.e. some of the domain objects fields are translatable.
note: I'm using NHibernate, but this is just a technical detail in the case.
Let's consider the following domain model:
public class Post {
    public virtual int Id {get; set;}
    public virtual User Author {get; set;}
    public virtual string Title {get; set;} // translatable
    public virtual string Content {get; set;}  // translatable
}

Looking through the internet I've found several approaches, most of them hackish and ugly; many completely unacceptable.
Most of the solutions are based on introducing "special" fields to the model, whether it's like Title_FR, Content_FR, Title_EN, Content_EN or Dictionary<string, string> ContentTranslations.
Pros:

*

*easy to query (first case)

*performance

Cons:

*

*requires schema change when adding language (first case)

*requires adding special fields to the model

Later on I've designed my own solution (which, further investigating, happened to be reinventing the wheel) which intercepts the NHibernate-specific events; i.e. once the instance of domain model is populated with values, the translatable fields are re-populated with translated values from abstract translation provider.
Pros:

*

*seamless integration

*no schema modification

*completely automatic

Cons:

*

*impossible to query on the translated field; filtering on the translated fields causes strange (from user point of view) behavior

I'm looking for the solution which

*

*integrates possibly seamlessly. No special fields introduced to the domain model

*Applies translations automatically

*Takes care not to overwrite original values when updating the (translated) domain object

*is querying friendly; i.e. the introduction of the mechanism doesn't require the LINQ queries to be changed significantly. This probably disqualifies "joinable" translation table

*ideally, the solution should not break the LINQ projection; this however is probably just asking way too much ( * )

( * ) word of explanation on 5. I'm using AutoMapper's Project.To() extensively, to avoid retrieving unnecessary fields and SELECT N+1 problems.
The solution I've came up doesn't work with projection, I believe OnPostLoad event is not fired when using projection
Any recommended reading on the subject?

A: I'm not sure how your DB structure looks like. If you do not want to use IDictionary (which I would prefer), then I would propose implementing a LocalizableString class and a corresponding ICompositeUserType, IUserType or using Component mapping.
public class Post {
    public virtual int Id {get; set;}
    public virtual User Author {get; set;}
    public virtual LocalizableString Title {get; set;} // translatable
    public virtual LocalizableString Content {get; set;}  // translatable
}

You will probably also need to implement some extensions to the linq provider, to allow custom query operations.

Some alternative approaches to consider:

*

*using formula columns formula columns for localized fields

*using my very own DelegateDecompiler to allow queries of the calculated properties.


text:
Q: erro de chamada de classe bom dia a todos!!
galera, eu estou voltando a mexer com php puro e me deparei com um erro meio besta, mas que não estou sabendo resolver...o erro é :
C:\xampp\htdocs\PDO\index.php:5 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\PDO\index.php on line 5

eu vou postar as 2 classes que eu chamo:
<?php

namespace classes\NewConex;

class NewConex{

    protected $Conn;

    protected function Conex(){ $this->$Conn = new PDO('mysql:host=localhost;port=;dbname=pdo', 'root', '');  return $this; }

    protected function Dstroy(){ $this->$Conn=NULL; }

}

e a outra é a crud:
<?php
namespace classes\Crud;
use classes\NewConex;

class Crud{

     function __construct($x = array())
        {
           $x = new NewConex;
           $x->$Conn;
        }

    public function insert(){}
}

e estou chamando essas duas no index.php da seguinte forma:
<?php
require_once("classes/NewConex.php");
require_once("classes/crud.php");

$z = new Crud();

o que está errado aqui pessoal? obrigado pela atenção!!

A: *

*Uso de namespaces

*Encapsulamento de atributos de classes Visibilidade no PHP

*Uso de propriedade de classes - veja

*Métodos Mágicos - Destrutores

Uso de namespaces
Em NewConex:
Para usar a classe PDO (que é global do PHP) dentro do seu namespace, neste caso classes\NewConex, você precisa inserir um barra invertida '\' antes do nome da classe para indicar que essa classe (PDO) não pertence ao escopo de seu namespace, mas sim, ao escopo global. Ou seja, a classe não está inserida no seu namespace.
Dessa forma,
$this->Conn = new PDO('mysql:host=localhost;port=;dbname=pdo', 'root', '');

torna-se
$this->Conn = new \PDO('mysql:host=localhost;port=;dbname=pdo', 'root', '');
# Repare na barra ^^ aqui.

Em Crud:
A classe NewConex pertence ao namespace classes\NewConex.
A classe Crud pertence ao namespace classes\Crud.  Portanto, as duas classes pertencem a namespaces diferentes.
E quando você quer usar uma classe que pertence a outro namespace (ex: NewConex) em um namespace (ex: classes\Crud), você precisa usar
Ao invés de
use classes\NewConex;

digite,
use classes\NewConex\NewConex;

pois, o "endereço" ou nome completo da classe NewConex é classes\NewConex\NewConex;.
Obs: Eu acredito que o que você queria era as duas classes num namespace chamado classes. Sendo assim, os nomes dos namespaces não poderiam conter os nomes das classes. Seriam, portanto, namespace classes;. E quando fosse usá-las, usaria assim use classes\NewConex e use classes\Crud.  Mas se eu estiver errado, desconsidere essa observação.
Em index.php
Para usar Crud, inclua uma referência para a classe
use classes\Crud\Crud;

ou referencie-a com seu nome completo
$z = new classes\Crud\Crud();

Encapsulamento de atributos de classes
Em Crud, você tenta utilizar a propriedade $Conn de classes\NewConex\NewConex. Porém, essa propriedade possui visibilidade protected, o que significa que ela só pode ser acessada e manipulada pela própria classe que a declara (classes\NewConex\NewConex) e eventuais classes que a herda (veja herança de objetos/classes se tiver dúvidas).
Como classes\Crud\Crud não herda classes\NewConex\NewConex, ela não tem acesso a propriedade Conn de NewConex.
Duas opções para corrigir isso é tornar Conn pública
public $Conn;

ao invés de,
protected $Conn;

ou criar um método getter para Conn
protected $Conn;
//...

public function get_conn()
{
    return $this->Conn;
}

Uso de propriedade de classes
Deveria ter colocado este tópico antes do segundo.

*

*Na declaração de uma propriedade você inclui $. Ex: public $Conn.

*No uso, você não inclui $. Exs: $this->Conn;  $NewConex->Conn.

Métodos Mágicos - Destrutores
Eu acredito que com o método classes\NewConex\NewConex\Dstroy(), você quis criar um método mágico destrutor da classe classes\NewConex\NewConex. Se este for o caso, o correto era chamá-lo de __destruct() e não Dstroy().


text:
Q: Issues Positioning Elements I'm having issues positioning these elements on my page, its supposed to be really simple and I don't understand why they are acting like this.
I'm trying to get the buttons to be aligned along the left, with the corresponding randomly generated numbers to the right of them. But whenever I try to move a single element (No matter what selector I use) they all move at the same time, here is my code.
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="Main.css">

<button id="DemoButton" class="button button5" onclick="myFunction()">D20</button>

<button id="DemoButton2" class="button button5" onclick="myFunction1()">D12</button>

<button id="DemoButton3" class="button button5" onclick="myFunction2()">D8</button>

<button class="button button5 demobutton4" onclick="myFunction4()">D6</button>

<button id="DemoButton4" class="button button5" onclick="myFunction3()">D4</button>

and the CSS
#demo {
    display:inline;
}

#demo1 {
  display:inline;

}

#demo2 {
  display:inline;

}

#demo4 {
  display:inline;

}

#demo3 {
  display:inline;

}

.demobutton4 {
 margin-top: 1px;
}

.button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 16px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    -webkit-transition-duration: 0.4s; /* Safari */
    transition-duration: 0.4s;
    cursor: pointer;
}

.button5 {
    background-color: white;
    color: black;
    border: 2px solid #555555;
}

.button5:hover {
    background-color: #555555;
    color: white;
}

Thanks for any help I can get.

A: Here is the updated code with the breaks and with out the inline attribute and it works.

  <link rel="stylesheet" type="text/css" href="Main.css">

<button id="DemoButton" class="button button5" onclick="myFunction()">D20</button>

<button id="DemoButton2" class="button button5" onclick="myFunction1()">D12</button>

<button id="DemoButton3" class="button button5" onclick="myFunction2()">D8</button>

<button class="button button5 demobutton4" onclick="myFunction4()">D6</button>

<button id="DemoButton4" class="button button5" onclick="myFunction3()">D4</button>

and the css
#demo {
    display:inline;
}

#demo1 {
  display:inline;

}

#demo2 {
  display:inline;

}

#demo4 {
  display:inline;

}

#demo3 {
  display:inline;

}

.demobutton4 {
 margin-top: 1px;
}

.button {

    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 16px 32px;
    text-align: center;
    text-decoration: none;

    font-size: 16px;
    margin: 4px 2px;
    -webkit-transition-duration: 0.4s; /* Safari */
    transition-duration: 0.4s;
    cursor: pointer;
}

.button5 {

    background-color: white;
    color: black;
    border: 2px solid #555555;
}

.button5:hover {
    background-color: #555555;
    color: white;
}

A: Try removing the
display: inline-block

from your
.button

element, and add a line break to your html.
<button id="DemoButton" class="button button5" onclick="myFunction()">D20</button>


text:
Q: tmap raster layer not rendering pixels full size I'm trying to produce a basic heatmap and the grid pixels are rendering very small.
require(tmap)
require(dplyr)
require(stars)

d = data.frame(lon = rnorm(1e5, mean = -95.5, sd=4),
               lat = rnorm(1e5, mean = 37.5, sd=4)) |>
  group_by(lat = round(lat), lon = round(lon)) |>
  summarise(n = length(lat), .groups = 'drop') |>
  st_as_sf(coords = c('lon','lat'), crs = 'WGS84') |>
  st_rasterize()

tmap_mode("view")

tm_basemap("Stamen.TonerLite") +
  tm_shape(d) +
  tm_raster("n", palette = c('white','red'), alpha=0.5)

Grateful for any suggestions what I'm doing wrong here.


text:
Q: How to swipe only certain elements? I have several divs, but they are semantically not connected. Therefore I want to have several sets of divs.
Example:
I want to be able to swipe left and right between {1,2,3,4,5}. Some of those pages have a button, which should open (with the slideup page transition) the subpages. For example a button in 4 would slide up page 4.1. Then I want to be able to swipe left and right again, between 4.1, 4.2, and 4.3.

My divs look like this:

            Page 1

        You are in page one.

            Page 2

        You are in page two.
        Go to page 3

Page three

        You are in page three.

With the following Javascript I can nicely swipe left and right, between the data-role="page" divs, however, there is no way for me to differentiate between subpages and main pages. Can I define a swipe for the main pages (basically using the one I already have) and then another for the subpages (maybe differentiate them by using ids or something?)?
$(document).ready( function() {
    $(document).on('swipeleft', 'div.ui-page', function () {
        var nextpage = $(this).next('div[data-role="page"]');
    if (nextpage.length >= 0) {
        $.mobile.changePage(nextpage, {
            transition: "slide",
            reverse: false,
            allowSamePageTransition: true
        });
    }
     });

    $(document).on('swiperight', 'div.ui-page', function () {
    var prevpage = $(this).prev('div[data-role="page"]');
    if (prevpage.length >= 0) {
        $.mobile.changePage(prevpage, {
            transition: "slide",
            reverse: true,
            allowSamePageTransition: true
        });
    }
    });
});

Maybe in with https://stackoverflow.com/questions/14688983/using-javascript-in-subpages-loaded-with-jquerys-changepage .

A: Try this code, it seems to work fine =).
HTML:

            Page 1

        You are in page one.
        Go to page 1.1

            Page 2

        You are in page two.
        Go to page 2.1

Page 3

        You are in page three.

Page 4

        You are in page four.
        Go to page 4.1

Page 5

        You are in page five.

Page 1.1

        You are in page 1.1.

Page 1.2

        You are in page 1.2.

Page 2.1

        You are in page 2.1.

Page 4.1

        You are in page 4.1.

Page 4.2

        You are in page 4.2.

Page 4.3

        You are in page 4.3.

JAVASCRIPT:
var num_pages = 5;
var curr_subpage = 0;
var subpage = false;
var curr_subnum = 0;
var curr_url;

$(document).ready( function() {

    var links = document.getElementsByName("lnk");

    links[0].onclick = function(e) { curr_subpage = 1; curr_subnum = 1; };
    links[1].onclick = function(e) { curr_subpage = 2; curr_subnum = 1; };
    links[2].onclick = function(e) { curr_subpage = 4; curr_subnum = 1; };

    $(document).on('swipeleft', 'div.ui-page', function () {
        var nextpage = $(this).next('div[data-role="page"]');
        var url = $(this).next('div[data-role="page"]').attr('data-url');
        console.log("1: "+url);

        curr_url = $('div.ui-page').attr('data-url');
        console.log("2: "+curr_url);

        if (nextpage.length >= 0)
        {
            if(curr_url == url)
            {
                $.mobile.changePage(nextpage, {
                    transition: "slide",
                    reverse: false,
                    allowSamePageTransition: true
                });
            }else{
                var subpage_url = "subpage"+curr_subpage+"_"+(curr_subnum+1);
                if( url == subpage_url)
                {
                    curr_subnum++;
                    $.mobile.changePage(nextpage, {
                        transition: "slide",
                        reverse: false,
                        allowSamePageTransition: true
                    });
                }
            }
        }
     });

    $(document).on('swiperight', 'div.ui-page', function () {
        var prevpage = $(this).prev('div[data-role="page"]');
        var url = $(this).prev('div[data-role="page"]').attr('data-url');
        console.log(url);

        curr_url = $('div.ui-page').attr('data-url');

        if (prevpage.length >= 0)
        {
            if(curr_url == url && curr_subnum == 0)
            {
                $.mobile.changePage(prevpage, {
                    transition: "slide",
                    reverse: true,
                    allowSamePageTransition: true
                });
            }else{
                var subpage_url = "subpage"+curr_subpage+"_"+(curr_subnum-1);
                if( url == subpage_url)
                {
                    curr_subnum--;
                    $.mobile.changePage(prevpage, {
                        transition: "slide",
                        reverse: false,
                        allowSamePageTransition: true
                    });
                }
            }
        }
    });
});


text:
Q: What is the prior corresponding to a weighted sum of pdfs? Recently, I have read a paper (Bayesian Bridge Regression
, H. Mallick, 2018) which states that since
$$
\frac{\lambda^{1/\alpha}}{2\Gamma(1+1/\alpha)}e^{-\lambda|\beta|^\alpha}=\int_{u>|\beta|^\alpha}\frac{\lambda^{1+1/\alpha}}{2u^{1/\alpha}\Gamma(1+1/\alpha)}u^{(1+1/\alpha)-1}e^{-\lambda u}du
$$
then hierarchical representation is as follows
$$
\beta|u\sim \text{Uniform}(-u^{1/\alpha},u^{1/\alpha})
$$
$$
u\sim \text{Gamma}(1+1/\alpha,\lambda)
$$
My question: Suppose that instead
$$
\frac{\lambda^{1/\alpha}}{2\Gamma(1+1/\alpha)}e^{-\lambda|\beta|^\alpha}=\int_{u>|\beta|^\alpha}\frac{\lambda^{1+1/\alpha}}{2u^{1/\alpha}\Gamma(1+1/\alpha)}(c_1 f(u)+c_2 g(u))du
$$
where $f$ and $g$ are two known pdfs and $c_1,c_2$ some constants. Then, how would we write the hierarchical representation? and are there any problems with this kind of representation?

A: The integral representation
$$\int_{u>|\beta|^\alpha}\frac{\lambda^{1+1/\alpha}}{2u^{1/\alpha}\Gamma(1+1/\alpha)}(c_1 f(u)+c_2 g(u))\,\text du$$
involves unnecessary terms $\lambda^{1+1/\alpha}$  and $\Gamma(1+1/\alpha)$ and should rather be written as
$$\int\frac{\mathbb I_{u>|\beta|^\alpha}}{2u^{1/\alpha}}\times[c_1 f(u)+c_2 g(u)]\,\text du\quad \text{with}\quad c_1+c_2=1$$
meaning that
\begin{align}
\beta|u&\sim \text{Uniform}(-u^{1/\alpha},u^{1/\alpha})\\
u&\sim c_1 f(u)+c_2 g(u)
\end{align}
a mixture of two distributions. Which can be rewritten as a three level hierarchical model:
\begin{align}
\beta|u&\sim \text{Uniform}(-u^{1/\alpha},u^{1/\alpha})\\
u|z=1&\sim f(u)\qquad u|z=2\sim g(u)\\
z &\sim c_1^{\mathbb I_{z=1}}c_2^{\mathbb I_{z=2}}
\end{align}
A trivial mixture that produces the same Gamma marginal on $\beta$ is
$$c_1 f(u) + c_2 g(u) = \frac{\lambda^{1+1/\alpha}}{\Gamma(1+1/\alpha)}u^{(1+1/\alpha)-1}e^{-\lambda u}\mathbb I_{u<\mu} + \frac{\lambda^{1+1/\alpha}}{\Gamma(1+1/\alpha)}u^{(1+1/\alpha)-1}e^{-\lambda u}\mathbb I_{u>\mu}$$
for an arbitrary $\mu$.


text:
Q: How to add .jar files in android studio which include class name like TranslateOptions$TranslateDefault.class I am trying to add Google cloud Translate Library in android studio. I have some issues to add it directly through dependency. So i add jar files. But when i added jar file in lib folder it automatically exclude Classes which have '$' this character in there name. Like TranslateOptions$TranslateDefaults.class. This file shown in zip but after adding in android studio this file is not there. And program shows an error that this file is missing. Error

FATAL EXCEPTION: main
                                                                              Process: edu.nic.dell.naseemchatbot, PID: 15685
                                                                              java.lang.NoClassDefFoundError:
  com.google.cloud.translate.TranslateOptions$TranslateDefaults
                                                                                at
  com.google.cloud.translate.TranslateOptions.(TranslateOptions.java:147)
                                                                                at
  com.google.cloud.translate.TranslateOptions.(TranslateOptions.java:39)
                                                                                at
  com.google.cloud.translate.TranslateOptions$Builder.build(TranslateOptions.java:142)
                                                                                at
  edu.nic.dell.naseemchatbot.ChatActivity.translateTextWithOptionsAndModel(ChatActivity.java:938)
                                                                                at
  edu.nic.dell.naseemchatbot.ChatActivity$5.onClick(ChatActivity.java:272)
                                                                                at android.view.View.performClick(View.java:4766)
                                                                                at android.view.View$PerformClick.run(View.java:19683)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5538)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

and this my gradle file
compile fileTree(include: ['*.jar'], dir: 'libs')
    compile files('libs/grpc-google-cloud-speech-v1-0.1.8.jar')
    compile files('libs/protobuf-java-3.4.0.jar')
    compile files('libs/grpc-protobuf-1.2.0.jar')
    compile files('libs/grpc-google-common-protos-0.1.8.jar')
    compile files('libs/grpc-core-1.2.0.jar')
    compile files('libs/grpc-stub-1.2.0.jar')
    compile files('libs/google-cloud-translate-1.14.0.jar')
    compile files('libs/google-http-client-1.21.0.jar')
    compile project(':google-api-services-translate-v2-rev47-1.22.0')
    compile files('libs/google-cloud-core-0.6.0.jar')
    compile files('libs/grpc-google-common-protos-0.1.8.jar')


text:
Q: Pytorch random tensor generation with one fix value and rest of random value In my testing dataset, I have to always include one specific image(image at position 0) in each batch but others values can be randomly selected. So I am making a tensor which will have 1st value 0 (for 1st image) and the rest of others can be anything other than 0. My code snippet is below.
a= torch.randperm(len(l-1)) #where l is total no of testing image in dataset, code output->tensor([10, 0, 1, 2, 4, 5])
b=torch.tensor([0]) # code output-> tensor([0])
c=torch.cat((b.view(1),a))# gives output as -> tensor([0, 10, 0, 1, 2, 4, 5]) and 0 is used twice so repeated test image

However, above approach can include 0 twice as torch.randperm many times includes 0. Is there a way in torch to generate random number skipping one specific value. Or if you think another approach will be better please comment.

A: You could just remove these 0s using conditional indexing (also assumed you meant len(l) - 1):
a= torch.randperm(len(l)-1) #where l is total no of testing image in dataset, code output->tensor([10, 0, 1, 2, 4, 5])
a=a[a!=0]
b=torch.tensor([0]) # code output-> tensor([0])
c=torch.cat((b,a))# gives output as -> tensor([0, 10, 0, 1, 2, 4, 5]) and 0 is used twice so repeated test image

Or if you want to make sure it's never put in:
a=torch.arange(1,len(l))
a=a[torch.randperm(a.shape[0])]
b=torch.tensor([0])
c=torch.cat((b,a))

The second approach is a bit more versatile as you can have whatever values you'd like in your initial a declaration as well as replacement.


text:
Q: Doubt in basics of inequalities While solving a problem I encountered with this
$ 4m(4m-1) \leq 0 $
Solving this one gets the solution $ 0 \leq m \leq 1/4 $
Now, if the inequation is multiplied with -1 on both sides we get
$ 4m(1-4m) \geq 0 $
Solving this, we get $ m \leq 0 $ or $m \geq 1/4 $
Individually the solutions are correct but the inequalities are the same. So, what is wrong here? Any help is appreciated.

A: You misapplied the theorem on quadratic inequalities. Namely, it says that

A quadratic polynomial has the sign of its leading  coefficient outside of the interval of its roots, and the opposite sign  between these roots, if any.

What you did was that, multiplying both side by $-1$, you also changed the sign of the leading coefficient from + to –.

A: When you have the multiplication of two terms, and you are looking for an inequality with zero, you can use the basics of when the product of two numbers is positive, negative, or zero.
In the first inequality, you have:
$$4m(4m-1) \le 0$$
So, you are looking for one of these factors to be greater than or equal to zero and the other to be less than or equal to zero. Thus, you need:
$$4m\ge 0 \text{ and } 4m-1 \le 0$$
or
$$4m\le 0 \text{ and } 4m-1 \ge 0$$
The first one breaks down to $m\ge 0\text{ and }m\le \dfrac{1}{4}$.
The second breaks down to $m\le 0 \text{ and } m\ge \dfrac{1}{4}$. In order for one factor to be positive and the other negative, we need both inequalities to be satisfied. Note the and between the inequalities. There are no numbers $m$ that satisfy both of these inequalities, so we reject this.
This gives the $0\le m \le \dfrac{1}{4}$ that you already got.
Next, we consider the second inequality:
$$4m(1-4m)\ge 0$$
You need both factors at least zero or both factors at most zero.
$$4m\ge 0\text{ and }1-4m \ge 0$$
or
$$4m\le 0\text{ and } 1-4m \le 0$$
The first inequality gives $0\le m \le \dfrac{1}{4}$.
The second inequality gives $m\le 0\text{ and }\dfrac{1}{4}\le m$. There are no values of $m$ that satisfy both inequalities. So we wind up with the same final solution.


text:
Q: Embed form in outlook email and capture response I am trying to help people do their job. So every morning an email needs to go out to the users with a list to Approve/Reject... Don't want to send this email just like a warning, telling them to go to the app to perform their duty.  The email needs to have the capability to capture their response and update the DB accordingly.
option 1: Embed all items in single email body as a form, something like...
Code - Description  - radiobutton - radio button

111  ABC  o Accept  o Reject
222  DEF  o Accept  o Reject

Submit

On submit need to call a winforms app and need to pass the code and accept/reject status. I have not been able to find any thing to come up with a solution. Need to validate as well, making sure all appropriate radio buttons have been selected. Is it even possible?
Option 2: I am trying to avoid voting route where each item will go as a separate email. when the user will accept/reject, a reply will go to the email. Then some process will monitor that inbox and will pick the not read messages and update DB accordingly. Using the MailItemClass in Microsoft.Office.Interop.Outlook namespace.
var mailItem = (Outlook.MailItem)Application.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.To = "some.address@server.com";
mailItem.Subject = "This is a test";
mailItem.Body = "This is the body of the message.";
mailItem.VotingOptions = "Accept; Reject;";
mailItem.Send();

A: I believe what you are asking for is possible but would be a lot of effort to implement.
For your approach, I assume the information for these emails comes from the DB.  I would write a macro to interrogate the DB and create and send each email to the appropriate user.
On each user's system I would have a rule that recognised these emails and called a macro to process them. The macro would extract the contents of the email, copy it to a form and pass control to the user.  A Submit button would validate the user's choices and save the results in global variables before returning control to the macro.  On regaining control, the macro would update the DB.
This macro will be large and I am sure it will need maintenance.  To protect itself from malware, Outlook does not provide any easy way of importing macros.  The macro and the form will have to be manually imported to each user's system, each time they change.  Unless you have technically able users, it will be you who visits each system and updates it.
I would reject any approach that required code on the user's systems.
To test an alternative approach, I manually created this email:

and sent it to myself.  When I received the email, I actioned it as instructed.  When I received the reply, it looked like:

The Html body for this reply is full of formatting information.  You could extract the responses from it but I believe the text body would be easier.  To create the following, I started with the text body, replaced every carriage return and line feed with [CR] and [LF] and then added a few new lines to make it marginally easier to read.
[CR][LF][CR][LF] [CR][LF][CR][LF]From: Tony Dallimore [mailto:a.j.dallimore@MyIsp.com] [CR][LF]Sent: 25 May 2018 14:22[CR][LF]To: 'Tony Dallimore' <a.j.dallimore@MyIsp.com>[CR][LF]Subject: Test email 2[CR][LF][CR][LF] [CR][LF][CR][LF]
Please:[CR][LF][CR][LF] [CR][LF][CR][LF]
1)      Click Reply within the Home tab.[CR][LF][CR][LF]
2)      You may find it helpful to click Pop Out.[CR][LF][CR][LF]
3)      Enter "A" in the Accept column or "R" in the Reject column of every row in the following table.[CR][LF][CR][LF]
4)      Click Send.[CR][LF][CR][LF] [CR][LF][CR][LF]Code[CR][LF][CR][LF]Description[CR][LF][CR][LF]Accept[CR][LF][CR][LF]Reject[CR][LF][CR][LF]
111[CR][LF][CR][LF]ABC[CR][LF][CR][LF]A[CR][LF][CR][LF][CR][LF][CR][LF]
222[CR][LF][CR][LF]DEF[CR][LF][CR][LF][CR][LF][CR][LF]R[CR][LF][CR][LF]
333[CR][LF][CR][LF]GHI[CR][LF][CR][LF]A[CR][LF][CR][LF][CR][LF][CR][LF]
444[CR][LF][CR][LF]JKL[CR][LF][CR][LF]A[CR][LF][CR][LF] [CR][LF][CR][LF]
 [CR][LF][CR][LF] [CR][LF]

You would need a second macro to process these emails, extract the responses and update the DB.  There is no validation on the user's system but they are not being asked to do anything complicated.  If you telephone and harangue them every time you get an incomplete reply, they will soon realise life is more pleasant if they get it right first time.
I do not know how difficult it is to access your DB from VBA but I do not believe anything else is particularly difficult.
This is not the approach you requested but I believe this will be very much easier to implement. More importantly, all the code is on your system which will make development and maintenance so much easier.


text:
Q: profit drawdown of each column in data.frame I want to calculate the profit/drawdown of each column A:C in the data.frame below. Header A thru C can be considered like a stock ticker symbol. Each row can be considered the hourly closing price. The pricedate and hour could be combined to form a timestamp for this time series of data.
I have tried using the fTrading and PerformanceAnalytics package to calculate the max drawdown, but keep getting errors. I don't care when the  max drawdown occurs. I just need the amount of the max drawdown so I can use it to calculate the the profit/drawdown (profit divided by max drawdown) ratio.
Data:
hourlyclose <- data.frame(pricedate = as.Date('2019-12-18'), hour = c(1,2,3,4,5), A = c(3,5,6,2,4), B = c(1,9,7,11,4), C = c(0,2,5,4,9))

I am desiring an output of second data.frame with a column each for the stock symbol, the profit-drawdown ratio, and just the profit (which is the last row minus the first row in my example hourlyclose data.frame).
The resulting data.frame should look like:
Stock     pdd      profit
 A        0.25        1
 B        0.43        3
 C        9.0         9

I would prefer to use the tidyverse and either of those finance packages for operations as much as possible.
Drawdown definition: A drawdown is a measure of how much the price goes down before it reaches or exceeds the previously high price.
Max Drawdowns for each column:
For "A" the max drawdown is 4 because A was at a high of 6 and then went down to 2.
For "B" there are two drawdowns, but only one max drawdown. There is a reduction in stock price from 9 to 7, for a drawdown of 2. But the stock reaches a new high the next row to 11, but then reduces down to 4, for a drawdown of 7. So the max drawdown is 7 for "B".
For "C" the stock price has a reduction from 5 to 4 for a max drawdown of 1.

A: We can get the data in long format, group_by name and calculate the drawdown value using cummax and max. Profit is calculated by subtracting last by the first value and pdd is division of profit by drawdown.
library(dplyr)

hourlyclose %>%
  tidyr::pivot_longer(cols = A:C) %>%
  group_by(name) %>%
  summarise(drawdown = max(cummax(value) - value),
            profit  = last(value) - first(value),
            pdd = profit/drawdown)

# A tibble: 3 x 4
#  name  drawdown profit   pdd
#  <chr>    <dbl>  <dbl> <dbl>
#1 A            4      1 0.25
#2 B            7      3 0.429
#3 C            1      9 9


text:
Q: How to change the cell value in a Data Grid when clicked on the cell I have created a Data Grid of 17 columns and 65520 rows for some application in form based application in c#.
when ever I click on any of the data grid cell its value should change from 0 to 1. I have gone through the definitions for below click event
private void datagridview1_contentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

where most of them were for specific cell, but for me the value should change from 0 to 1 in any cell when clicked in the range specified(within 17 columns and 65520 rows).Since I am new to C# coding and Please help me in resolving this.

A: If you use Windows Forms, this can help you.
Because you only want to change the CellContentClick event. With this event its easy to change the value of it. This code change the cell value to 1:
    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        dataGridView1[e.ColumnIndex, e.RowIndex].Value = 1;
    }


text:
Q: How to display a php variable in input checkbox I made a small user database with some checkboxes in a html input form.
In there I have some basic infos about the users like value 1 and 2 (among others) and some checkboxes as well (here you see one). Default is always 0, but when I click the checkbox its changes to 1.
<input type="text" placeholder="Value 1" value="<?php echo set_value('value1'); ?>" name="value1" size="6"/>
<input type="hidden" value="0" name="spec1"/><input type="checkbox" value="1" name="spec1"/>
<input type="text" placeholder="Value 2" value="<?php echo set_value('value2'); ?>" name="value2" size="6"/>

Now I  would like to have a form in which I can see all these informations later on and edit it if necessary. But the checkbox I can't display properly. It is always empty. So I had to change it to a textbox. So I can see whether that specific values are 0 or 1.
<input type="text" name="Value 1" value="<?php echo $value1; ?>">
<input type="text" name="spec1" value="<?php echo $spec1; ?>">
<input type="text" name="Value 2" value="<?php echo $value2; ?>">

Is it possible somehow to show the values in a checkbox again, so I can change the type of the second line to "checkbox" again instead of "text"? Means can I display a value 1 as a checked checkbox and 0 as an empty checkbox?

A: check this code , you can use checkbox and check value is set and you need to show user so you checkbox level then you can use
<input type="checkbox" name="Value 1" value="<?php echo $value1; ?>"><?php echo $value1; ?>
<input type="checkbox" name="spec1" value="<?php echo $spec1; ?>"> <?php echo $spec1; ?>
<input type="checkbox" name="Value 2" value="<?php echo $value2; ?>"> <?php echo $value2; ?>

for demo test check this code also
<input type="checkbox" name="Value 1" value="1">Test1
<input type="checkbox" name="spec1" value="2"> Test2
<input type="checkbox" name="Value 2" value="3"> Test3

and if you want to checkbox checked then use also this
<?php
 $value1 = 1;
 $spec1 = 2;
 $value2 = 3;

 $compare_value = 3;
 ?>
 <input type="checkbox" name="Value 1" value="1" <?php if($value1 ==$compare_value) { echo 'checked';}?>>Test1
 <input type="checkbox" name="spec1" value="2" <?php if($spec1 ==$compare_value) { echo 'checked';}?>> Test2
 <input type="checkbox" name="Value 2" value="3" <?php if($value2 ==$compare_value) { echo 'checked';}?>> Test3

A: Checkboxes aren't checked or not by their value attribute. They have a checked attribute:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox
So in your example:
<input type="checkbox" name="..." <?php if($value1) echo 'checked="checked"'; ?> >

A: What checks a checkbox is the checked attribute not value
You can add that attribute depending on the value you are retrieving from your database like so:
<?php if($value == 1): ?>
   <?php echo '<input type="checkbox" checked name="spec1"/>' ?>
<?php else: ?>
   <?php echo '<input type="checkbox" name="spec1"/>' ?>
<?php endif; ?>

or for short
<input type="checkbox" <?php if(value == 1) echo 'checked'; ?> name="spec1"/>


text:
Q: NSPredicate filter class by CGPoint I have that class :
@interface Field : NSObject
@property CGPoint fieldCoordinates;
@property CGPoint ballCoordinates;
@end

and i Try filter NSArray of object of  this class :
NSPredicate * y1 = [NSPredicate predicateWithFormat:@"ballCoordinates.y >= %@",location.y];
NSArray * filtered = [self.fieldsArray filteredArrayUsingPredicate:y1];

but get error :

Terminating app due to uncaught exception 'NSUnknownKeyException',
  reason: '[ valueForUndefinedKey:]: this
  class is not key value coding-compliant for the key y.'

NSPredicate have problem with filter by CGPoint ?

A: Yes, NSPredicate has problems with CGPoint, because it is a struct, not a key-value compliant Objective-C class. You can write a predicate with a block instead, like this:
NSPredicate * y1 = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
    return ((CGPoint)[obj ballCoordinates]).y >= location.y;
}];

A: CGPoint is not an Object it's a plain old C struct.
You could walk around that by making a readonly property on your Field class that look like this.
@property (nonatomic, readonly) CGFloat yBallCoordinates;
- (CGFloat)yBallCoordinates { return self.ballCoordinates.y; }

Edit
The block approach pointed by dasblinkenlight is a better solution.
Because it will not involve the necessity of declaring property for every thing you want to predicate on. Which will be more flexible.