Is it possible to stop computers which aren't Bitlocker encrypted logging in?

Question: Is it possible to somehow (startup script?) stop any unencrypted computers from being able to connect to the domain?
Environment:
Windows Active directory, 1000-ish computers, mostly bitlocker encrypted, about 50/50 on win 7 or 10 enterprise.
Comment: There isn't, in general, a solution to the problem "is this untrusted hardware running this trusted software?", which is what it sounds like you're asking for. If it *were* possible, it would revolutionize several fields; e.g. Internet voting would be trivial and computer games would no longer have cheaters.
Comment: Prevent the computer from logging on or prevent users from logging on to the computers?
Comment: Either really, probably best at computer level.
Comment: @DanielWagner In practical IT security you often aren't looking for a 100% malicious-user-proof way of doing something, just one that will stop a "regular person". So if there was a way to do this, and a user had to modify Windows to bypass it, that is much much better than nothing.
Answer: AFAIK it's not possible to automatically check this during AD domain join. However, it's possible to enable Bitlocker using GPO as soon as the computer has joined the domain. If every computer has these settings and no other than Domain Computers can access the resources, the outcome will be the same.
First you should have Turn on TPM Backup to AD Domain Services Enabled from Computer Configuration \ Policies \ Administrative Templates \ System \ Trusted Platform Module Service.
Then, under Computer Configuration \ Policies \ Administrative Templates \ Windows Components \ Bitlocker Drive Encryption you can find all the other related settings:

Provide Unique Identifiers for your organization: Enabled
\ Fixed Data Drive \

Configure use of passwords for fixed data drives: Enabled
Choose how BitLocker-protected fixed drives...: Enabled

\ Operating System Drive \

Require additional authentication at startup: Enabled; configure as required
Configure minimum PIN length for startup: Enabled
Choose how BitLocker-protected fixed drives...: Enabled

\ Removable Data Drives \

Control use of BitLocker on removable drives: Enabled
Configure use of passwords for removable data drives: Enabled
Choose how BitLocker-protected fixed drives...: Enabled

Be sure to fill in the details and modify this example as required in your environment. Enable this GPO for the OU having the computers to be forced to use BitLocker. (And please first test your configuration with a small set of test computers. A small mistake in these settings can cause real pain as all the data will get encrypted.)
Comment: TPM backup should not be used. If fact, it is no longer a valid policy beginning with Windows 10 1607/Windows Server 2016. This is due to it most likely could never be used when needed, but could be used in an offline attack to retrieve the startup key.  More information: https://blogs.technet.microsoft.com/dubaisec/2017/02/28/tpm-owner-password/
Comment: Seems like the OP could do this for all members in the domain, i.e. the `Domain Users` group, then have a secondary group, e.g. `Compliant Domain Users`, that users can then join once their GP is updated such that they have prereqs like BitLocker established.  Would a scheme like that be viable?
Comment: IIRC this is kind of what Measured Boot is aiming for but I'm not sure it's available at log-on.
Answer: While it's probably not exactly what you're asking for, I believe the official answer to this question is MBAM - Microsoft Bitlocker Administration and Monitoring. MBAM comes with (among other things) a bunch of Group Policy settings, and some of those settings allow you to enforce Bitlocker use on any domain-joined device. But of course this means that the domain-joined device has to join and authenticate to the domain first before downloading Group Policy, at which time the Bitlocker status of the device is unknown... but a startup or logon script would be no different in that regard.
Answer: There aren't many good options. Anything that runs in the context of the user logon most likely would not have permissions to check BitLocker status.  A computer startup script such as below may be of some use:
REM Exclude domain controllers. This command may be repeated to check for "3" to exclude member servers.
wmic os get producttype | FIND /I "2"
IF %ERRORLEVEL%==0 GOTO :EOF
manage-bde -status | FIND /I "Protection On"
IF %ERRORLEVEL%==0 GOTO :EOF
REM Not protected
SHUTDOWN /S /F /T 120 /C "Shutting down due to computer does not have BitLocker protection enabled."

The amount of time could be adjusted, and after logging on, it is possible for an administrator to cancel with the shutdown /a command.
If you prefer to not shut down, you could use the SETX command to set a system environment variable in a computer startup script that could be checked during user logon:
SETX BDE 1 /M
wmic os get producttype | FIND /I "2"
IF %ERRORLEVEL%==0 GOTO :EOF
manage-bde -status | FIND /I "Protection On"
IF %ERRORLEVEL%==0 GOTO :EOF
REM Not protected
SETX BDE 0 /M

And the user logon script:
IF %BDE%==0 logoff.exe


Closed-form solution to minimize error for one pdf in a weighted sum of pdfs?

Question: Let $\theta_3$ be a categorical probability distribution that is the weighted sum of two categorical probability distributions $\theta_1$ and $\theta_2$ plus error.
$$\theta_3=\alpha_1\theta_1+\alpha_2\theta_2+\epsilon$$
$$\sum\alpha=1$$
Assume that $\theta_3, \theta_3, \alpha_1, \alpha_2$ are all known. I want to find the probability distribution $\theta_1$ which minimizes the error.
Sometimes it is possible that the error can be zero; in this case, there is a trivial solution, e.g:
$$\alpha_1=0.5,\alpha_2=0.5$$
$$\theta_2=[0.25,0.25,0.5]$$
$$\theta_3=[0.5,0.25,0.25]$$
Here, $\theta_1=\frac{\theta_3-\alpha_2\theta_2}{\alpha_1}=[0.75,0.25,0]$
In many cases, it is not possible for the error to be zero, e.g.:
$$\alpha_1=0.5,\alpha_2=0.5$$
$$\theta_2=[0.25,0.25,0.5]$$
$$\theta_3=[0.5,0.4,0.1]$$
I can define a function $\sum (\theta_3-\alpha_2\theta_2-\alpha_1\theta_1)^2$ and find the values of $\theta_1$ that minimize this using a nonlinear programming solver, e.g. in R:
<code>sqerr = function(theta1){
  sum((c(0.5,0.4,0.1)-0.5*c(0.25,0.25,0.5)-0.5*theta1)^2)
}

Rsolnp::solnp(pars=extraDistr::rdirichlet(1,c(1,1,1)),
      fun=sqerr,
      eqfun=function(x){sum(x)},
      eqB=1,
      LB=c(0,0,0),
      UB=c(1,1,1))
</code>
This is well and good for small problems like this, but if $\theta$ has thousands of categories, solnp takes way too long to solve this for my purposes (I want to nest it will be nested in another optimization). Is there a closed-form solution to this problem?
Answer: Solution 1: Quadratic programming
Your optimization problem is a quadratic program (QP). Using a dedicated QP solver should be faster than your general nonlinear programming solver, because it's explicitly designed for this type of problem. If your current method doesn't take advantage of the analytical gradient/Hessian, this would also slow things down dramatically.
The problem can be written in standard QP form as follows. The function to minimize is:
$$f(\theta_1) = \|\alpha_1 \theta_1 + \alpha_2 \theta_2 - \theta_3\|_2^2$$
where $\|\cdot\|_2^2$ is the squared Euclidean norm (so we're minimizing the sum of squares). Note that the solution won't change if we multiply by a constant, so we can equivalently minimize:
$$\frac{1}{2 \alpha_1^2} f(\theta_1)
= \frac{1}{2} \| \theta_1 - y \|_2^2
= \frac{1}{2} \theta_1^T \theta_1 - y^T \theta_1 + \frac{1}{2} y^T y$$
where $y = \frac{1}{\alpha_1} (\theta_3 - \alpha_2 \theta_2)$ is a known constant. Finally, note that $\frac{1}{2} y^T y$ is constant, so we can drop it from the problem. The QP is then:
$$\min_{\theta_1} \ \frac{1}{2} \theta_1^T \theta_1 - y^T \theta_1 \quad
\quad \text{s.t.} \quad
\begin{matrix} \vec{1}^T \theta_1 = 1 \\ \theta_1 \ge \vec{0} \end{matrix}$$
The constraints ensure that the entries of $\theta_1$ are nonnegative and sum to one (which also implies that no entry is greater than one). This problem can be fed into a standard QP solver.
Solution 2: Euclidean projection
It may be possible to solve the problem even more efficiently, because there's additional structure beyond a generic QP. In particular, the solution can be described geometrically as the Euclidean projection of $y$ onto the probability simplex (the set of vectors whose entries are nonnegative and sum to one). That is, the point $\theta_1$ on the probability simplex that's closest to $y$ in terms of Euclidean distance. The following paper describes an efficient algorithm for solving this problem:
Wang, W., & Carreira-Perpinán, M. A. (2013). Projection onto the probability simplex: An efficient algorithm with a simple proof, and an application. arXiv preprint arXiv:1309.1541.
Comment: Wow that paper is awesome, I would never have known to search for that...
Comment: @NicholasRoot glad to help


Como ler mais de um registro com READ TABLE?

Question: É possível fazer um READ TABLE no ABAP para ler mais que uma linha?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Não tem como fazer diretamente, tem que usar uma laço. Exemplo da documentação:
DATA itab TYPE STANDARD TABLE OF i
          WITH EMPTY KEY
          WITH NON-UNIQUE SORTED KEY sort_key COMPONENTS table_line.

itab = VALUE #( ( 2 ) ( 5 ) ( 1 ) ( 3 ) ( 4 ) ).

DATA(output) = ``.
DATA(idx) = lines( itab ).
WHILE idx > 0.
  READ TABLE itab INDEX idx USING KEY sort_key
             ASSIGNING FIELD-SYMBOL(<fs>).
  idx = idx  - 1.
  CHECK <fs> > 2.
  output = output && <fs> && ` `.
ENDWHILE.

cl_demo_output=>display( output ).

Coloquei no GitHub para referência futura.
Answer: Read Table e feito para selecionar apenas 1 linha de uma tabela transparente. Você precisa usar um loop para selecionar o conteúdo desejada de uma tabela para outra.
Comment: Olá @Igor. Evite colocar imagens de código. Edita a sua resposta e coloque lá o código estruturado ao invés da imagem.
Answer: Como os amigos já mencionaram anteriormente, a expressão READ TABLE na linguagem ABAP não passa de um SELECT SINGLE, se formos trocar por miúdos...
Onde SEMPRE trará apenas UM registro a cada vez que seja processado, a grande diferença entre SELECT SINGLE  e READ TABLE é que no primeiro, a busca dos dados é feita no banco de dados e o segundo é feito pela tabela interna (apenas em tempo de execução ), Tendo isto como base. se você precisa "Juntar" duas tabelas por exemplo, é muito simples...
Vamos supor que você tenha a necessidade de exibir em um relatório os dados de Código de Material (MARA-MATNR), Data de Criação (MARA-ERSDA) e por fim a DESCRIÇÃO de material(MAKT-MAKTX) neste caso, precisamos unir duas tabelas, para completas as informações que necessitamos para a exibição:
O código ficaria basicamente assim:
TYPES: BEGIN OF y_saida_relatorio,
      matnr TYPE mara-matnr,
      ersda TYPE mara-ersda,
      maktx TYPE makt-maktx,
   END OF y_saida_relatorio.
DATA: w_saida_relatorio TYPE y_saida_relatorio,
      t_saida_relatorio TYPE TABLE OF y_saida_relatorio.
* Selecionando dados do banco de dados
SELECT matnr,
       ersda
  FROM mara
INTO TABLE @DATA(t_mara).
IF sy-subrc IS INITIAL.
SELECT matnr,
spras,
maktx
FROM makt
INTO TABLE @DATA(t_makt)
FOR ALL ENTRIES IN @t_mara
WHERE matnr EQ @t_mara-matnr
AND spras EQ 'PT'.
IF NOT sy-subrc IS INITIAL.
FREE t_makt[].
ENDIF.
ENDIF.
* Selecionando dados da minha tabela interna (Existente somente em tempo de processamento)
SORT: t_mara BY matnr,
t_makt BY matnr spras.
LOOP AT t_mara
INTO DATA(w_mara).
* Buscando 1 informação por vez na tabela interna
READ TABLE t_makt INTO DATA(w_makt) WITH KEY matnr = w_mara-matnr
                                                  BINARY SEARCH.
IF sy-subrc IS INITIAL.
w_saida_relatorio-matnr = w_mara-matnr.
w_saida_relatorio-ersda = w_mara-ersda.
w_saida_relatorio-maktx = w_makt-maktx.
APPEND w_saida_relatorio TO t_saida_relatorio.
CLEAR w_saida_relatorio.
ENDIF.
ENDLOOP.


android: Take camera picture without "save" / "delete" confirmation

Question: I want to display an image taken from the camera in an ImageView using
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

This works fine so far but after the user takes the photo using the chosen camera app a dialog (probably from the app) appears asking whether to save or delete the taken picture (at least on Android 2.3 and 4.2 using the default camera app).
I would like to skip this extra dialog and directly display the image in the ImageView (when onActivityResult gets called),  because it means an extra interaction step for the user, which is unneccessary because he will have the possibilty to save or delete the photo in my app.
Is this possible using the simple  ACTION_IMAGE_CAPTURE Intent or will I need something more complex like Camera Preview and SurfaceView for this purpose ?
Answer: You ca use the SurfaceView to capture image
package com.camera;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Camera_capture extends Activity implements SurfaceHolder.Callback {

private Camera mCamera;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Button capture_image;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera_layout);
    capture_image = (Button) findViewById(R.id.capture_image);
    capture_image.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            capture();
        }
    });
    surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(Camera_capture.this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    try {
        mCamera = Camera.open();
        mCamera.setPreviewDisplay(surfaceHolder);
        mCamera.startPreview();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void capture() {
    mCamera.takePicture(null, null, null, new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Toast.makeText(getApplicationContext(), "Picture Taken",
                    Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.putExtra("image_arr", data);
            setResult(RESULT_OK, intent);
            camera.stopPreview();
            if (camera != null) {
                camera.release();
                mCamera = null;
            }
            finish();
        }
    });
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    Log.e("Surface Changed", "format   ==   " + format + ",   width  ===  "
            + width + ", height   ===    " + height);
    try {
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    Log.e("Surface Created", "");
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    Log.e("Surface Destroyed", "");
}

@Override
protected void onPause() {
    super.onPause();
    if (mCamera != null) {
        mCamera.stopPreview();
        mCamera.release();
    }
}
}

And the layout file would be
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<SurfaceView
    android:id="@+id/surfaceview"
    android:layout_width="fill_parent"
    android:layout_weight="100"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/capture_image"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Capture" />

</LinearLayout>

Start this Camera_capture activity with startActivityForResult and onActivityResult you can get the image as byte array as
byte[] image = data.getExtras().getByteArray("image_arr");

where data is the received data.
Decode the byte array to Bitmap using
Bitmap bmp = BitmapFactory.decodeByteArray(image, 0,
                    image.length);

now set this Bitmap

Edit
As there is some problem while returning byte[], the byte[] should be save in a file and the path of the file should be sent to the previous Activity so that file can be read.
In onPictureTaken(), just add
String PATH = "Any path to store a file";
try {
    FileOutputStream fos=new FileOutputStream(PATH);

    fos.write(data);
    fos.close();
  }
  catch (java.io.IOException e) {

  }

and in place of :
intent.putExtra("image_arr", data);

write
intent.putExtra("image_path", PATH);

and receive this path in previous Activity's onActivityResult as :
String imagePath = data.getExtras().getString("image_path");

Comment: Thanks! This gave me a good idea how it will work. I noticed that using the above code the image is rotated by 90 degrees and also after calling finish() the acitivity does not close , so it never gets back to the main activity - the app hangs...
Comment: for the rotated image u can try `Camera.Parameters p = mCamera.getParameters(); p.setRotation(90); mCamera.setParameters(p);`

or `Camera.Parameters p = mCamera.getParameters(); p.set("rotation", 90); mCamera.setParameters(p);`
Comment: will check for your issues.
Comment: and for the app hanging issue, sorry but I did't find it.
Comment: It may be the same problem as described here: http://stackoverflow.com/questions/2264980/failed-binder-transaction-when-returning-camera-image
Comment: I think its a random issue. In that question `Colin O'Dell`'s answer looks good. You should do it like that.
Comment: Yes, it may also depend on the current image resolution ie. how much data will be passed as result argument, 5 MB may be too much...I'm now saving the image inside the capture activity, which takes a few seconds, and then call "finish()" while just passing the filename
Comment: I never found that issue, but know I'll take care of this in future.. thanks. :)
Comment: After I take the picture, the back button doesn't work anymore. I have tried overriding the back button to just call `finish()` but it doesn't allow anything to go through.
Answer: Use "android.intent.extra.quickCapture"
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("android.intent.extra.quickCapture",true);
if (intent.resolveActivity(getPackageManager()) != null) {
    startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}

Comment: Did not change anything, although that would have been nice
Comment: Thanks. Was looking for something like this. Not sure if it'll work on all models though!
Worked on Xiaomi 7A, but not on my S8
Answer: If your image is rotated, you can use this:
mCamera.setDisplayOrientation(90);

after
mCamera.startPreview();

Answer: You can not do it using the default intent. You will have to write a customer camera capture functionality where you can skip the preview with Ok and Cancel buttons.
Pleas see http://developer.android.com/guide/topics/media/camera.html#custom-camera
Answer: You can use the solution of AnujMathur_07, but if you do not want work with paths and files, in the method onPictureTaken, you can return the bitmap:
 @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                Toast.makeText(getApplicationContext(), "Picture Taken",
                        Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();

            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0,
                    data.length);

            intent.putExtra("image", bmp);
            setResult(RESULT_OK, intent);
            camera.stopPreview();
            if (camera != null) {
                camera.release();
                mCamera = null;
            }
            finish();
        }

And in the method onActivityResult you can get bitmap:
 Bundle extras = data.getExtras();
 Bitmap imageBitmap = (Bitmap) extras.get("image");

Answer: Use MediaStore.EXTRA_OUTPUT param for you camera application running intent
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

Comment: Are you sure this fulfils the OPs desire to bypass the save/delete confirmation. It doesn't for me.
Comment: This does not help, the dialog appears although I'm adding   intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
              Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/image11.jpg")));
Comment: Here is the link to official documentation http://developer.android.com/guide/topics/media/camera.html#intent-image
Comment: The documentation in the link posted by user527759 doesn't mention the extra "save / delete dialog". However, the dialog showed up using their demo code.


Obtaining totals from properties of parallel arrays in nested objects

Question: I'm trying to obtain totals from properties that exist in objects in 'parallel' nested arrays. The data describes exercise sets.
I'd like to populate the "totalWeight" fields with the sum of weight lifted for each exercise. The data structure is below. The total should be the "setNum" of the "reps" values x the "setNum" of the "Weight" values where the setNums exist in two parallel arrays. So for the first exercise (Dumbbell Shoulder press) the totalWeight should be 560 ((8 reps x 28 weight)+(6x28)+(6x28)). The measurement types are distinguished by the "mu_id" property from where the "key" property value is obtained.
A complicating factor is that some exercises might have left-hand & right-hand reps so there are 3 parallel arrays as in the second example of the One Arm Cable Front Raise. There, the totalWeight should be 265 ((8 lh reps + 8 rh reps )*6.25 weight)+((7+8)*6.25)+((10+9)*3.75)).
The data structure was created by a d3.js nest routine from a flat database file but I haven't figured out how I can get these values either as part of the nesting (using rollup) or otherwise. I have access to d3.js but no other js libraries.
[
   {
      "exercise":"Dumbbell Shoulder press",
      "totalWeight":0,
      "values":[
         {
            "key":"1",
            "values":[
               {
                  "resultsId":10381,
                  "setNum":"8",
                  "desc":"times",
                  "unit":"Reps",
                  "mu_id":1
               },
               {
                  "resultsId":10382,
                  "setNum":"6",
                  "desc":"times",
                  "unit":"Reps",
                  "mu_id":1
               },
               {
                  "resultsId":10383,
                  "setNum":"6",
                  "desc":"times",
                  "unit":"Reps",
                  "mu_id":1
               }
            ]
         },
         {
            "key":"3",
            "values":[
               {
                  "resultsId":10381,
                  "setNum":"28",
                  "desc":"kilograms",
                  "unit":"Weight",
                  "mu_id":3
               },
               {
                  "resultsId":10382,
                  "setNum":"28",
                  "desc":"kilograms",
                  "unit":"Weight",
                  "mu_id":3
               },
               {
                  "resultsId":10383,
                  "setNum":"28",
                  "desc":"kilograms",
                  "unit":"Weight",
                  "mu_id":3
               }
            ]
         }
      ]
   },
   {
      "exercise":"One Arm Cable Front Raise",
      "totalWeight":0,
      "values":[
         {
            "key":"3",
            "values":[
               {
                  "resultsId":10395,
                  "setNum":"6.25",
                  "desc":"kilograms",
                  "unit":"Weight",
                  "mu_id":3
               },
               {
                  "resultsId":10396,
                  "setNum":"6.25",
                  "desc":"kilograms",
                  "unit":"Weight",
                  "mu_id":3
               },
               {
                  "resultsId":10397,
                  "setNum":"3.75",
                  "desc":"kilograms",
                  "unit":"Weight",
                  "mu_id":3
               }
            ]
         },
         {
            "key":"7",
            "values":[
               {
                  "resultsId":10395,
                  "setNum":"8",
                  "desc":"times",
                  "unit":"Reps (left)",
                  "mu_id":7
               },
               {
                  "resultsId":10396,
                  "setNum":"7",
                  "desc":"times",
                  "unit":"Reps (left)",
                  "mu_id":7
               },
               {
                  "resultsId":10397,
                  "setNum":"10",
                  "desc":"times",
                  "unit":"Reps (left)",
                  "mu_id":7
               }
            ]
         },
         {
            "key":"8",
            "values":[
               {
                  "resultsId":10395,
                  "setNum":"8",
                  "desc":"times",
                  "unit":"Reps (right)",
                  "mu_id":8
               },
               {
                  "resultsId":10396,
                  "setNum":"8",
                  "desc":"times",
                  "unit":"Reps (right)",
                  "mu_id":8
               },
               {
                  "resultsId":10397,
                  "setNum":"9",
                  "desc":"times",
                  "unit":"Reps (right)",
                  "mu_id":8
               }
            ]
         }
      ]
   },
   {...}
]

Answer: You could collect the wanted data in an array and reduce the inner arrays and then add the single values.

var data = [{ exercise: "Dumbbell Shoulder press", totalWeight: 0, values: [{ key: "1", values: [{ resultsId: 10381, setNum: "8", desc: "times", unit: "Reps", mu_id: 1 }, { resultsId: 10382, setNum: "6", desc: "times", unit: "Reps", mu_id: 1 }, { resultsId: 10383, setNum: "6", desc: "times", unit: "Reps", mu_id: 1 }] }, { key: "3", values: [{ resultsId: 10381, setNum: "28", desc: "kilograms", unit: "Weight", mu_id: 3 }, { resultsId: 10382, setNum: "28", desc: "kilograms", unit: "Weight", mu_id: 3 }, { resultsId: 10383, setNum: "28", desc: "kilograms", unit: "Weight", mu_id: 3 }] }] }, { exercise: "One Arm Cable Front Raise", totalWeight: 0, values: [{ key: "3", values: [{ resultsId: 10395, setNum: "6.25", desc: "kilograms", unit: "Weight", mu_id: 3 }, { resultsId: 10396, setNum: "6.25", desc: "kilograms", unit: "Weight", mu_id: 3 }, { resultsId: 10397, setNum: "3.75", desc: "kilograms", unit: "Weight", mu_id: 3 }] }, { key: "7", values: [{ resultsId: 10395, setNum: "8", desc: "times", unit: "Reps (left)", mu_id: 7 }, { resultsId: 10396, setNum: "7", desc: "times", unit: "Reps (left)", mu_id: 7 }, { resultsId: 10397, setNum: "10", desc: "times", unit: "Reps (left)", mu_id: 7 }] }, { key: "8", values: [{ resultsId: 10395, setNum: "8", desc: "times", unit: "Reps (right)", mu_id: 8 }, { resultsId: 10396, setNum: "8", desc: "times", unit: "Reps (right)", mu_id: 8 }, { resultsId: 10397, setNum: "9", desc: "times", unit: "Reps (right)", mu_id: 8 }] }] }];

data.forEach(function (o) {
    o.totalWeight = o.values.map(function (a) {
        return a.values.map(function (b) {
            return +b.setNum;
        });
    }).reduceRight(function (a, b, j) {
        return a.map(function (v, i) {
            return j ? v + b[i] : v * b[i];
        });
    }).reduce(function (a, b) {
        return a + b;
    });
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Eloquent laravel models empty id

Question: I have a problem with inserting order details about order.
Models:
class Order extends Model
{
    protected $fillable = ['user_id','name','surname','fathers_name','phone_number','city','post_office','comment'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function orderDetails()
    {
        return $this->hasMany('App\OrderDetails');
    }

}

class OrderDetails extends Model
{
    protected $fillable = ['order_id','product_id','amount'];

    public function order()
    {
        return $this->belongsTo('App\Order');
    }

    public function product()
    {
        return $this->hasMany('App\Product');

    }

}

Tables:
Orders:
id
user_id
p_number
city
status
...
Order_details:
id
order_id
prod_id
amount
...
Controller:
$data = $request->except('_token','submit');

$order = new Order();
    $order->create($data);
    $order_details = new OrderDetails();

    $cart_content = Cart::content();
    $order_content = [];

    foreach($cart_content as $key=>$cart_item) {
        $order_content[$key]['order_id'] = $order->id;
        $order_content[$key]['id'] = $cart_item->id;
        $order_content[$key]['qty'] = $cart_item->qty;
        $order_content[$key]['price'] = $cart_item->price;
    }

    dd($order_content);

        /*
    foreach($order_content as $order_item)
    {
        $order_details->create($order_item);

    }

        */

So when I print $order_content, im getting 'order_id' null, how should I properly get id of order to fill its field in order_details?
In the end i should get something like this:
Orders:
1
1
+12345678
NY
processing
...

Order_details:
1
1
2
5
-----------
2
1
3
4
-----------
3
1
8
2
-----------

Answer: You need to save result to a variable:
$order = (new Order)->create($data);

Or:
$order = Order::create($data);

Comment: @Batmannn no, you're doing `$order = new Order(); $order->create($data);` Your code will return an empty model after `create()`. And the code from my answer will return created model. And as I said in your another question, your architecture is not good. You should learn about many-to-many relationship and use it for `Order` and `Product` models and get rid of `OrderDetails` model.

Eloquent laravel models empty id


Deleting corrupt git files

Question: I have been using the desktop version of Git Hub for about a month, and I have run into some trouble with deleting a directory. I just moved all of my individual projects into one repository for better organization especially since a lot of the projects were small and basic for school. I am trying to delete the previous files off of my computer, but I was getting an error that the files were not empty despite appearing so. I then tried doing so in cmd prompt and got more information that it was git files that were corrupted. I then went into the git bash and still couldn't find the files. Does anyone know how to delete these?
I should also note that I was using an external hard drive and switching it between my laptop and pc so I wouldn't have to continue to re-download and update the projects over and over. I guess this may have been what caused the problem in the first place? How should I go about using my HD so that I don't ruin files. I think I was encountering problems because my GitHub desktop applications were not synced between the two computers.
Also I am using VS Code. Not sure if the version control within that is messing anything up.
Answer: Whenever "previous files" cannot be deleted, close first all program (or even reboot) in order to ensure no process keep an handle to said files, preventing their deletion.
Then open the git repository folder with VSCode.

Deleting corrupt git files


Beat detective clips move backwards

Question: I've got a drumbeat and a 16th note triplet grid that is adequate to for this beat and the time signature is 4/4. For experiments I mark exactly one bar, and apply beat detective.
Then I set clip conform to 16th note triplets, press conform and watch everything go down the bin. It's not placing the the clips to the closest grid positions, but rather 1-3 grid positions backwards! Why could this be?
I've tried playing around with the markings, making sure that exactly one bar is marked from beat one to beat 3, and one bar + one beat and so but it isn't worked. If I would have made that algorithm I would have created it so that it would simply move the transients to the closest possible grid position. How is this software "thinking"?
Comment: I feel like using triplets in 4/4 is a mistake
Comment: Interesting problem, is beat detective finding the strong points in the drum beat? or is it displaced before then. If so maybe try a different intensity.
Answer: I am assuming you are talking about the Pro Tools Beat Detective? Well I didn't use Pro Tools much, but I'll speak from my understanding of quantizers and electronic music.
It is really important with all music and certainly all programs even more so to keep the beat steady. If you slow down significantly, or even only slightly for quite a few bars, obviously the program will put you back a few beats as it can't tell if you meant the beat to be fast (like at the beginning) or slow (as you slowed down at the end).
That said, that probably isn't your problem, unless you are new to drums and have some trouble keeping a steady beat.
You mention that your beat is 16th triplets in 4/4 time - red flags! 4/4 is quadruple meter, and a simple meter. If you are doing constant triplets, not only intermittently, it may be you are confusing the beat for a complex meter. In that case, you could try changing to 12/8 time, which is the complex quadruple. 12/8 is friendly to all kinds of triplet nonsense. Of course changing the meter may require a bit of bar shifting to make it all align.
Those two errors are very common. Just comment if you had a slightly different problem. Again I am not familiar with the software, but no software currently exists that deals with those issues consistently.
Answer: make sure your capture selection is looking at the right bars. In the selection box, check to see if beat detective doesn't think you are working with a different starting point or ending point. Does it all the time and then you get everything back or forward a bit

Beat detective clips move backwards


Comparing two dataframes on given columns

Question: I have two dataframes DF1 and DF2 with different column sets
------------------------------------------------
DF1
col1 col2 col3  col4 col5   col6    col7
---------------------------------------------
Asr  Suh  dervi xyz  yes    NY      2022-04-11
Bas  nav  dervi xyz  yes    CA      2022-04-11
Naz  adn  otc   xyz   no    NJ      2022-05-01

---------------------------------------------------

DF2
col1 col2 col3 col4
------------------------------------------------------
Asr  Suh  dervi xyz
Bas  nav  dervi xyz
--------------------------------------------------------

I want to compare these two dataframes based on col2 and Col3 and filter out non matching rows from DF1.
So compare operation should give below row in dataset
df3
Naz  adn  otc  xyz   no NJ  2022-05-01

Answer: You can use the pyspark's left anti join to get your desired result. When you join two DataFrame using Left Anti Join (leftanti), it returns only columns from the left DataFrame for non-matched records.
Preparing the dataframes,
data_1 = [('Asr',  'Suh', 'dervi', 'xyz', 'yes', 'NY', '2022-04-11'),
('Bas','nav','dervi','xyz', 'yes', 'CA', '2022-04-11'),
('Naz','adn','otc','xyz', 'no', 'NJ', '2022-05-01')]

col_1 = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7']

df_1 = spark.createDataFrame(data=data_1, schema = col_1)

df_1.show()

+----+----+-----+----+----+----+----------+
|col1|col2| col3|col4|col5|col6|      col7|
+----+----+-----+----+----+----+----------+
| Asr| Suh|dervi| xyz| yes|  NY|2022-04-11|
| Bas| nav|dervi| xyz| yes|  CA|2022-04-11|
| Naz| adn|  otc| xyz|  no|  NJ|2022-05-01|
+----+----+-----+----+----+----+----------+

data_2 = [('Asr',  'Suh', 'dervi', 'xyz'),
('Bas','nav','dervi','xyz')]

col_2 = ['col1', 'col2', 'col3', 'col4']

df_2 = spark.createDataFrame(data=data_2, schema = col_2)

df_2.show()

+----+----+-----+----+
|col1|col2| col3|col4|
+----+----+-----+----+
| Asr| Suh|dervi| xyz|
| Bas| nav|dervi| xyz|
+----+----+-----+----+

So, in your case, you could try something like this,
df_1.join(df_2, (df_1.col2 == df_2.col2) & (df_1.col3 == df_2.col3), "leftanti").show(truncate=False)

+----+----+----+----+----+----+----------+
|col1|col2|col3|col4|col5|col6|col7      |
+----+----+----+----+----+----+----------+
|Naz |adn |otc |xyz |no  |NJ  |2022-05-01|
+----+----+----+----+----+----+----------+

or
df_1.join(df_2, ['col2', 'col3'], "leftanti").select(df_1.columns).show(truncate=False)

+----+----+----+----+----+----+----------+
|col1|col2|col3|col4|col5|col6|col7      |
+----+----+----+----+----+----+----------+
|Naz |adn |otc |xyz |no  |NJ  |2022-05-01|
+----+----+----+----+----+----+----------+

Both of them are the same just different syntax, use which ever you prefer.
Comment: Thanks @Tushar I am somehow getting error "Can only compare identically -labelled series  objects" in this. I tried to reset the index and also use equals but dint helped. I am using 1.3.4 pandas and python 3.7
Answer: There's no left anti join in pandas, use outer join with indicator=True first.
cols = ['col2', 'col3']
# add _merge columns via outer join
_df = df1[cols].merge(df2[cols], how='outer', indicator=True)
_df
col2    col3    _merge
Suh     dervi   both
nav     dervi   both
adn     otc     left_only

# extract left_only, and drop _merge column
_df = _df[_df._merge=='left_only'].drop('_merge', axis=1)
_df
col2    col3
adn     otc

# inner join df1 and _df
df3 = df1.merge(_df, on=cols)
df3

col1    col2    col3    col4    col5    col6    col7
Naz     adn     otc     xyz     no      NJ      2022-05-01

Comment: Well by sorting index it worked for me thanks much !!
Comment: Thanks for your response .. it somehow dint gave me differences on left side. What is _merge here ?
Comment: _merge is the indicator column added by the outer join, see https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html, So we use the outer join to extract left_only part into an auxiliary data frame _df, and inner join df1 with _df
Comment: I added some more detail above ... the code works in pandas 1.3.5, python 3.7
Comment: I am somehow getting error "Can only compare identically -labelled series objects" in this. I tried to reset the index and also use equals but dint helped. I am using 1.3.4 pandas and python 3.7


Limit goes to $\infty$, but wolfram alpha says its limit is $0$

Question: I have $(5/3)^n$, if I input this in wolframalpha.com I can see it goes to infinity as long as n increases, but if I go down in the wolframalpha webpage results it shows .... the limit is zero as long as n increases, am I wrong?
Comment: Of course not (That is, you are right!). Please put a screenshot of the Wolfram Alpha result, along with your input, so that we can decide what's the problem.
Comment: @ChristianAndrews `as long as n increases` Read the screen more carefully. What's $0$ is the limit for $n \to -\infty\,$ which is of course correct.
Comment: oh man, sorry about that, You're right, I was wrong
Comment: Limits don't go anywhere. They either exist or don't, but they're not moving around to a samba beat.
Comment: To expand on what @zhw. said: The standard terminology goes something like, "as $x$ goes to $c$, the value $f(x)$ goes to $L$". That is, it's the dependent and independent variables ($x$ and $y$) that do the going, not the limit ($L$).
Comment: Don't see that [here](http://www.wolframalpha.com/input/?i=lim+(5%2F3)%5En+for+n+to+infinity). It helped if you posted the exact text you typed into WA.
Comment: I am trying to post a screenshot, but I don't know how to do it
Answer: As you've correctly said, the value of the limit approaches $\infty$ as $n \to \infty$.
I typed the limit into Wolfram|Alpha using these inputs:

limit n to infinity (5/3)^n
lim_{n to infinity} (5/3)^n

And they both gave me the correct answers.
What I suspect you've done is this:

limit n to infinity 5/3^n
lim_{n to infinity} 5/3^n

Which is $\lim_{n \to \infty} \frac{5}{3^n}=0$ instead of the correct limit $\lim_{n \to \infty} \left(\frac{5}{3}\right)^n=\lim_{n \to \infty} \left(\frac{5^n}{3^n}\right)=\infty$
Edit: After you provided the screenshot:
Look carefully at the input given by Wolfram Alpha on your screenshot.
$$\lim_{\color{red}{n \to -\infty}} \left(\frac{5}{3}\right)^n=0$$
The limit tends to $-\infty$ instead of $+\infty$.
To avoid this problem in the future: Type the limit explicitly rather than just typing $(\frac{5}{3})^n$ on Wolfram|Alpha as I have done on my top two examples.
Comment: Look closely:  $n \to -\infty$.
Comment: As zhw said in another comment, limits don't go anywhere. So I think you should not use that kind of phrasing as it misleads students.
Answer: I suspect you are missing a pair of parentheses:  If you type
Limit[5/3^n, n -> Infinity]
You will get 0, because the order of operations makes this equivalent to $$\lim_{n \to \infty} \frac{5}{3^n} = 0.$$  If you type
Limit[(5/3)^n, n -> Infinity]
you will get your intended result, which is $$\lim_{n \to \infty} \left(\frac{5}{3}\right)^n = \infty.$$
Comment: Occam's razor agrees.
Answer: You said down the page was a limit of 0. That's because they took $n -> -\infty$.  Edit OP shows the same thing circled on screen print.
Answer: This sequence definitely approaches infinity as $n$ goes to infinity.
Comment: When I enter it into Wolfram Alpha, the limit comes back as infinity.
Comment: so, It could be a wolframalpha's mistake? because I trust in wolfram blind eye
Comment: My guess is that you forgot a parenthesis or input the limit incorrectly into Wolfram.


How to reduce the space between the x-ticks in matplotlib?

Question: I already checked this but the answers did not help.
I have the following code that generates 4 plots:
import matplotlib.pyplot as plt
import numpy as np

group_x = [5, 0, 1, 16, 3, 1, 2, 0, 8, 2, 11, 5]
group_y = [8, 10, 6, 0, 0, 5, 12, 0, 14, 2, 1, 7]
group_w = [1, 3, 13, 9, 0, 15, 6, 2, 3, 7, 1, 0]
group_z = [0, 1, 2, 0, 10, 12, 12, 0, 8, 12, 4, 6]
ranges = ['a', '(a, b)', '(b, c)', '(c, d)', '(d, e)', '(e, f)',
          '(f, g)', '(g, h)', '(h, i)', '(i, j)', '(j, k)', 'k']

colors = ['red', 'blue', 'green', 'purple']
participants = ['Group X', 'Group Y', 'Group W', 'Group Z']

fig, axes = plt.subplots(2, 2, figsize=(12, 5))
c = 0
for i, ax_row in enumerate(axes):
    for j, ax in enumerate(ax_row):
        data = [group_x, group_y, group_w, group_z][c]
        ax.text(.5, .9, f'{participants[i]}',
                horizontalalignment='center',
                transform=ax.transAxes)

        bars = ax.bar(ranges, data, color=colors[c], width=0.2)
        ax.set_yticks(np.arange(0, 21, 5))
        ax.set_yticklabels(range(0, 21, 5), fontsize=9)
        ax.set_xticks(np.arange(12))
        ax.set_xticklabels(ranges, rotation=30, ha='right', fontsize=8.5)
        ax.set_xlabel('Characters')
        ax.set_ylabel('Frequency', fontsize=8)
        for bar, score in zip(bars, data):
            ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), str(score), ha='center', va='bottom')
        c += 1
plt.tight_layout()
plt.savefig('stackover.png', dpi=600, bbox_inches='tight')
plt.show()

The output is:

I want to reduce the space between the x-axis ticks so that the bars and their corresponding x-ticks will be very close next to each other. Also, I want the a bar to be very close to the y-axis and reduce the space between the k bar and the right edge of the corresponding frame. How do I change my code to have the mentioned effects?
Comment: What should it actually look like with this reduced space?!  The only suggestion I could have would be to make the figure less wide which would decrease the gaps.   Or maybe you mean make the bars wider, but then the ticks would stay the same distance.
Answer: The answer to your problem consists of two steps:

adjust the width parameter of ax.bar, e.g., set it to 1 (bars touch each other) or 0.95 (a little bit of space between them)
adjust the x-limit of the horizontal axis so that the bars are closer to the y-axis.

Here are just the two lines that need to be changed:
for i, ...
   for j, ...
        # ...
        bars = ax.bar(ranges, data, color=colors[c], width=0.95)
        # ...
        ax.set_ylabel('Frequency', fontsize=8)
        ax.set_xlim(-0.6, len(ranges) - 0.4)

And this is the result:

For the bar plot, each bar is located at an integer x-value. The first is at "x=0" with a width of  approximately 1. Therefore, the left side is at ~-0.5 and the right one at ~0.5 (I said "approximately 1" because this depends on the width parameter of the bar plot).
P.S.: In cases like yours, it might be helpful for the reader of a diagram if you remove some redundant ticklabels and axis labels. E.g. by using
axes[0,0].set(xticklabels=[], xlabel="")
axes[0,1].set(xticklabels=[], xlabel="", yticklabels=[], ylabel='')
axes[1,1].set(yticklabels=[], ylabel='')

just before plt.tight_layout() it becomes directly clear to the reader that, e.g., the x-axis of the subplots in columns are the same.
PPS.: There is a good reason to set width=0.95 and to leave a bit of space: in doing so you make it clear that this is not a histogram but a bar plot. The values in a histogram cover a whole range without empty spots and can be summed while this does not make sense in your case where you use categorical data.
Answer: Not sure if this is what you are looking for, but as Sam Mason stated, you can either:
Increase bars width:
bars = ax.bar(ranges, data, color=colors[c], width=1)

Reduce figsize:
fig, axes = plt.subplots(2, 2, figsize=(9, 5))

Or a combination of both. You can iterate numbers until you find what best adapts to your need.

If in other case you are looking for something different, it would help to clarify what you want. I hope it helps.


how to update interface to MainActivity from thread activity in different class?

Question: now i'm making socket connection to connect multiple client to one server. everything fine, i make thread in different class. But when i will fill textView with string from thread activity, i can't. please help
this MainActivity:
public class MainActivity extends Activity {
private static int port = 6000;
TextView txt;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt = (TextView) findViewById(R.id.txtCommand);
    txt.setText("Server : ");
    ServerSocket server1 = null;
    Server gameServer = new Server();
    try {
        server1 = new ServerSocket(port);
        // .. server setting should be done here
    } catch (IOException e) {
        System.out.println("Could not start server!");
       // return ;
    }

    while (true) {
        Socket client = null;
        try {
            client = server1.accept();
            gameServer.handleConnection(client);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class Server  {
    private ExecutorService executor = Executors.newCachedThreadPool();

    public void handleConnection(Socket client) throws IOException {
        PlayerConnection newPlayer = new PlayerConnection(this, client);
        txt.setText(newPlayer.getuname());
        this.executor.execute(newPlayer);
    }

    // add methods to handle requests from PlayerConnection
}

and this thread adctivity :
public class PlayerConnection implements Runnable {
    private Server parent;
private Socket socket;
private PrintWriter out;
private BufferedReader in;
String line;

protected PlayerConnection(Server parent, Socket socket) throws IOException {
    this.parent = parent;
    this.socket = socket;

    this.in = new BufferedReader(new InputStreamReader(socket
            .getInputStream()));
    this.out = new PrintWriter(new OutputStreamWriter(
            socket.getOutputStream()));
}

public void run() {
    while(!this.socket.isClosed()) {
        try {
            //int nextEvent = this.in.readInt();
            line = in.readLine();
            System.out.println("Server Receive : "
                    + line);
            out.println("Server Sent :" +line);
            System.out.println("SEND : "
                    + line);
            out.flush();
             if (line == null){
                 this.socket.isClosed();
                 break;
             }
        } catch (IOException e) {}
    }

Comment: can you please post some of your codes? I may have to ask you if you are using an inner class to determine if you have access to the textView you want to be filled. thanks
Answer: you can use handler or runOnUiThread method.
Answer: I realized that you have a while loop that never ends in your onCreate method. try to move that loop in to your thread. this loop blocks inputs of your application.
while (true) {
    Socket client = null;
    try {
        client = server1.accept();
        gameServer.handleConnection(client);
    } catch (IOException e) {
        e.printStackTrace();
    }


Is the use of cutoffs for dichotomisation of biomarkers really that bad?

Question: Tissue microarrays are commonly used to assess potential prognostic biomarkers. For decades now, many authors (I would even say the majority) feel the need to categorise their continuous predictors, either by dichotomising after data collection, or by using scoring systems that pre-categorise (e.g. Allred and immunoreactive score).
The pitfalls of this approach are numerous and have been highlighted for years. Douglas Altman and Patrick Royston have been some of the most vocal critics, alongside prediction model experts like Frank Harrell.
I completely agree with their arguments, but does it really matter in practice? A frequent defence of dichotomisation, or categorisation of continuous predictors in general, is that it greatly simplifies clinical decision making. Indeed, a physician may have to weigh up what is essentially a binary choice – to treat or not to treat; or to present the patient with one prognosis or another – and so the belief is that predictors should be dichotomised to reflect this. I would argue that keeping a predictor continuous, however, allows for more granular information to be obtained and lessens the risk of misclassifying patients whose predictor values lie just above or below the arbitrary threshold.
However, countless clinical decisions are made off back of categorised predictors. For example, breast cancer patients are assessed for oestrogen, progesterone and HER2 expression status and are classified as receptor positive or negative as per some threshold. Although this approach may not be 'statistically sound', its widespread use in guiding decisions over treatment surely points to categorisation at least being somewhat useful?
Comment: Yes, it is that bad.  As I argue [here](https://stats.stackexchange.com/questions/558403/visual-demonstration-of-residual-confounding/558494#558494) dichotomizing can yield biased predictions, meaning the dichotmomization is good for some but can be bad in many more cases.  Risk estimates are either too high or too large, which effects decision quality.
Comment: @DemetriPananos sometimes in medicine you do have true biological dichotomies, as in breast cancer. That becomes a classification rather than a continuous-outcome prediction problem, if the classes respond differently to therapy. The difficulty is then how to assign a particular case to the best therapy. In practice, pathologists might use a trichotomy for a marker: upper and lower cutoffs that have very high probability of correct assignment, with intermediate cases assigned to more testing or more cautious application of findings.
Answer: It's really that bad, as detailed in many of Patrick and my writings.  Think about it these ways, for starters: If you categorize a marker the loss of information is so great that you will need to go an collect more markers to make up for the loss.  Why not instead get the most information out of a single marker?  Then there is the issue that it is easy to show that the threshold for a marker is a function of the continuous values of all the other predictors. See the Information Loss chapter in BBR.  For example, if the sex of the patient is an important factor with regard to the likelihood of disease, you'll find that a different biomarker threshold is needed for females vs. males.
Categorization simplifies decision making but only by making it worse.  Many things only seem to be simple precisely because they are wrong.
We are taught to assess goodness of fit of models.  A model that assumes a piecewise flat relationship between a biomarker and outcome will be easily shown to have poor fit to the data.  For example look at the log-likelihood for a piecewise flat model (i.e., one using thresholding) and a flexible but everywhere-smooth model.
Comment: The example I gave of breast cancer patients being treated according to pre-defined receptor expression thresholds was nicely expanded on by @EdM. Thinking about it a little further, I suppose that ER, PR and HER2 are more examples of predictive rather than prognostic biomarkers. Although the two are not mutually exclusive, the clinic utility of the aforementioned lies in their ability to discriminate different treatment groups.

For the most part, and certainly where lung cancer prognostic models are concerned, categorisation of biomarker data is not the way to go...
Comment: @user333336 prognostic biomarkers can become predictive biomarkers, as for HER2 in breast cancer. Patients with HER2-overexpressing tumors were first found to have worse outcomes, leading to attempts to target HER2. That led to trastuzumab as (part of) therapy, and clinical trials that showed the predictive benefit of HER2 expression levels for that therapy. But with HER2 there is an order of magnitude difference between the small percentage of over-expressors and others; see the density plots I added to my answer. I don't think you'll find anything so dramatic in TMA of lung adenocarcinoma.
Comment: @EdM and others. Thank you all for your contributions (sorry I can't tag you all in these replies). To give some context, I'm a PhD student looking at the use of Cox modelling in lung adenocarcinoma. I'm investigating the use of common prognostic variables (e.g. node metastasis, T-stage, tumour pathology) along with TMA biomarker data in the prediction of survival.
Comment: With respect to lung cancer, the field seems awash with models that pay scant attention to the correct handling of biomarker data. Indeed, I initially only read papers in this area and came away with the impression that categorisation was the way to go. It was purely by chance that I came across the writings of Frank Harrell et al. and thought that there might be a different way to handle my data.
Answer: Although cutoffs in biomarker values are admittedly not helpful for modeling within a single population (+1 to Frank Harrell's answer on that basis), they make sense when, together with extensive subject-matter knowledge, they can delineate fundamentally different populations that benefit from different therapy. In such situations, testing can classify most cases with high probability (based on separate high and low cutoffs) while assigning intermediate cases to further testing or more cautious application of the findings. Breast cancer, the example of the OP in which tumors are evaluated for estrogen receptor alpha (ER), progesterone receptor (PR) and human epidermal growth factor receptor 2 (HER2), is such a situation.

This hexbin plot illustrates the 2-dimensional distribution of the expression of HER2 versus ER among 1093 primary breast cancers, based on RNA sequencing data from The Cancer Genome Atlas. Note the logarithmic scales on both axes.
Density plots for ER and HER2 make the class distinctions clearer.

ER shows a clearly bimodal distribution with modal values differing by 2 orders of magnitude and few tumors having intermediate values. HER2 values show a major peak encompassing about 90% of tumors, but about 10% show substantially larger expression, up to 20-fold more than that of the major peak.
Decades of clinical and laboratory research have shown that these distributions represent fundamentally different biological classes of breast cancer, driven by different tumorigenic processes and responding best to different types of therapy. For example, with respect to tumors having high expression of HER2 (also called ERBB2), Wikipedia summarizes:

Amplification, also known as the over-expression of the ERBB2 gene, occurs in approximately 15-30% of breast cancers. It is strongly associated with increased disease recurrence and a poor prognosis; however, drug agents targeting HER2 in breast cancer have significantly positively altered the otherwise poor-prognosis natural history of HER2-positive breast cancer... HER2 is the target of the monoclonal antibody trastuzumab (marketed as Herceptin). Trastuzumab is effective only in cancers where HER2 is over-expressed.

Similarly, patients with high ER expression can benefit from "endocrine therapy" that interrupts cellular signaling pathways mediated by estrogens. But cases at the lower left of the hexbin plot represent "triple-negative" breast cancers, low in all of ER, PR and HER2, that do not respond to therapies that target either estrogen signaling or HER2 signaling.* They need different therapies.
In practice, expression of ER, PR and HER2 is evaluated at the protein level by immunohistochemistry (IHC) rather than by the RNA sequencing that provided data for this plot. IHC makes at best semi-quantitative assessments of protein expression. For example, the Allred score cited by the OP combines the intensity and extent of IHC staining into an 8-point scale.
Nevertheless, given the large differences between high- and low-expressing tumors with respect to levels of these particular proteins, it's generally possible to assign a tumor to one of those biologically distinct classes based on IHC. The current recommendation of the College of American Pathologists (CAP) is to use the percentage of tumor-cell nuclei showing ER expression as the criterion, with tumors having <1% called ER-negative and those with >10% ER-positive. Tumors having 1% to 10% on that scale are reported as "ER Low Positive" with specific cautions about therapeutic choices that might be based on that finding. Similar guidelines for HER2 suggest an additional type of assay, in-situ hybridization, when IHC results are equivocal.
In that respect, behavior in practice follows what Harrell says on page 258 of Regression Modeling Strategies: "Physicians sometimes profess to desiring a binary decision model, but if given a probability they will rightfully apply different thresholds for treating different patients or for ordering other diagnostic tests." Based on clinical outcome studies, the CAP guidelines identify levels of expression that have high probability of correct classification, and recommend further tests and caution otherwise.
Finally, the classifications based on ER, PR, and HER2 expression are only part of what's considered in choosing therapy. Those are considered together with the tumor's histological appearance and size, whether it has spread to lymph nodes or beyond, further gene-expression or genetic tests, and patient preferences for breast conservation to select a combination of surgery, radiation, and pre-operative and adjuvant (post-surgical) drug therapies. The National Comprehensive Cancer Network publishes a 200+ page book of Guidelines for breast cancer therapy based on such considerations, documenting the level of evidence behind its recommendations, with 700+ references to the literature.
Data and code:
From Firebrowse, select BRCA for breast cancer, click on the mRNASeq bar, and select illuminahiseq_rnaseqv2-RSEM_genes_normalized. Restrict to primary tumors (sample type 01). Put into a data frame, here called brcaRNAseqPrimDF. Then in R:
library(ggplot2)
## for hexbin
ggplot(brcaRNAseqPrimDF, aes(x=ESR1.2099, y=ERBB2.2064)) + scale_x_log10() + scale_y_log10() + geom_hex(bins=50) + xlab("ER") + ylab("HER2") + theme(aspect.ratio = 1)
## for density plots
pHER2 <- ggplot(brcaRNAseqPrimDF,aes(x=ERBB2.2064))+scale_x_log10()+geom_density()+xlab("HER2")+geom_rug(alpha=0.2)
pESR1 <- ggplot(brcaRNAseqPrimDF,aes(x=ESR1.2099))+scale_x_log10()+geom_density()+xlab("ER")+geom_rug(alpha=0.2)
library(gridExtra)
grid.arrange(pESR1,pHER2,ncol=2)

ESR1 is Estrogen Receptor alpha. ERBB2 is the currently accepted name for HER2.

*For simplicity I'm not trying to incorporate the third classic immunohistochemical marker, prostaglandin receptor, as essentially all cases with low ER also have low prostaglandin receptor expression (called PGR.5241 in the data).
Comment: @Lodinn I think you underestimate the ability and desire of clinicians to deal with complexity. I've edited the question to explain what is done when the classification scheme based on ER, PR and HER2 is equivocal, and how that classification is combined with other types of information to direct therapy choices.
Comment: @Lodinn the fundamentally respectful give-and-take among users on this site it one of its strengths. Thinking about your comment led me to improve my answer, and I learned more in the process. What I hoped to covey was a sense of the (limited) type of situation when biomarker cutoffs might be other than "bad." And you are correct about the variance in clinician competence. Admittedly, not all might follow NCCN and CAP guidelines or deal properly with classifications that aren't of very high probability.
Comment: The apparent clustering in the HER2-ER plane is actually a demonstration to the contrary point.  There is no discontinuity in the data, and HER2 and ER have been arbitrarily dichotomized.   This is why so much of cancer research involves finding new markers and subpopulations that are just making up for the discarding of quantification of HER2 and ER.  If markers were captured using the fullest amount of information possible, I conjecture that subpopulations found by other markers tend to collapse.
Comment: That all makes sense, and does not support torturing the data to come up with a cutpoint.
Comment: Not a medical professional here, but this pattern of several clusters being over-simplified is UBIQUITOUS: seen it in plant biology, particle physics, material science...  Doctors in particular won't really do do anything too complex, they have their own share of issues to be overwhelmed with. Better decision tree is a great boon but it HAS to be streamlined to be usable. Until there emerges an eponymously-named scale where you compare numbers coming from the lab with provided ranges and assign them numbers 1 to 5 and out goes the treatment plan and the prognosis, it goes nowhere...
Comment: That's fair - I did exaggerate quite a bit and I also don't expect whatever information I have to be representative. I just know for a fact that the best clinicians are able to navigate very complex environments very successfully... but not everyone is getting treated by them. My close contacts in medicine seem to be concerned with bad doctors not screwing up things about as much as with good doctors getting better. Re-reading that earlier comment - I'm sorry, it came through as over-generalization. Glad you made use of it nonetheless.
Comment: @FrankHarrell [CALGB 9840](https://doi.org/10.1200/jco.2007.11.6699) randomized the anti-HER2 agent trastuzumab to patients with HER2-non-overexpressing metastatic breast cancer and showed no benefit for those patients. During the study, the benefit of trastuzumab to those with HER2-overexpressing tumors became so clear that all such patients were given trastuzumab. As the authors said, "no assessment of HER-2 status is perfect"; IHC and ISH are at best semi-quantitative, and with intermediate determinations potential benefits are weighed against the cardiac risk of trastuzumab.


java Interpretation correct

Question: I have the below question, and would like to know if I have interpreted the question right or not. I am new to the Java and programming so the technical terms even thought I read my textbook and understood them I am not sure that if I have programmed them correctly. Please see the question and let me know if what I am doing is in the right direction.

The question itself:
<code>You are asked to implement a class to keep track of the students' academic result for a module. The system requires the following information about a student:
 Student identification - a unique 7-digit identification that begins with 'S' for local students and 'F' for foreign student. E.g. S1234567.
 Student name
 Quiz mark - an integer number in the range of 0 to 100
 Assignment mark - an integer number in the range of 0 to 100
 Exam mark - a floating point number in the range of 0 to 100
 Resit student - true if the student is retaking the paper, false otherwise. Resit student does not have quiz and assignment marks.
Write a Java class called Student and provide the following:
 suitable instance variables for the information described above
 constructor(s) with the appropriate actions on the instance variables
 the accessor methods for the instance variables
 the computeScore() method to compute the score as follows:
for resit students, take only the exam mark as the score
for other students, score is calculated by using the formula
9% * quiz + 21% * assignment + 70% * exam
The score calculated is to be rounded up to the nearest integer and returned.
 the findGrade() method that returns the grade based on the score:

Score range
Grade
80 to 100
A
70 to 79
B
60 to 69
C
50 to 59
D
0 to 49
F
 the toString() method that returns the attribute values as a string with description.
</code>
then this is the code i have so far is that correct? i mean the way i declared the constructors and such...tks
<code>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package student_qn4;

/**
 *
 * @author
 */
public class Student
{
   private String student_idno, student_name;
   private int mark_quiz, mark_assig;
   private float mark_exam;
   private boolean student_resit;

   public Student (String id, String name , int quizM , int assignM , int examM) {

 studentId = id;
 studentName = name;
 quizMark = quizM;
 assignMark = assignM;
 examMark = examM;
 }

   public void setStudentnumber(String number)
   {
       student_idno = number;
   }

   public String getStudentnumber()
   {
       return student_idno;
   }

   public void setStudentname(String name)
   {
       student_name = name;
   }

   public String getStudentname()
   {
       return student_name;
   }

    public void setquizMark(int quizmarks)
   {
       mark_quiz = quizmarks;
   }

   public int getquizMark()
   {
       return mark_quiz;
   }

    public void setassigMark(int assigmarks)
   {
       mark_assig = assigmarks;
   }

   public int getassigMark()
   {
       return mark_assig;
   }

   public int computerScore()
   {
       /*do as the program asks then return the computer score */

   }

   public String findGrade()
   {
       // Based on the computeScore() I have to access what is the grade and return that
   }

   public String toString()
   {
       // What is this method supposed to do?
   }

}
</code>
Comment: Hint: the string "-ve" is not a word in the English language.
Comment: haha asked a first question and got that -ve... such a looser me.. is it just me or stackoverflow is not helping begining programmer
Comment: Your question covers quite simple notions of OOP, there are tons of examples and sources that can help you to improve your code. So don't expect upvotes for that kind of questions. For me, I have so much free time to answer you.
Answer: generally ok, if you take on board the comments made in the other answer.
However, your naming conventions are a bit wacky. Standard java bean convention is to name your properties (your ints and so on) with camelCase (so markQuiz rather than mark_quiz) and your getters and setters as getMarkQuiz and setMarkQuiz (the 1st letter after get/set is now capitalized) For boolean properties, use isXxx() rather than getXxx().
These conventions are widely used and will make your code more tool friendly (with ides such as ecliipse/netbeans)
Regards to your comment after your question, homework questions are generally frowned upon, which is why you got down voted. You will learn far more by playing and experimenting, getting it wrong and then fixing it, than by coming here asking for an answer. At least you did provide a skeleton answer, so you are thinking about it, so well done for that.Keep at it!
Comment: +1 for the naming convention. This link on ["Java Programming Style Guide"](http://www.cwu.edu/~gellenbe/javastyle/naming.html) might come in handy!
Comment: thanks and +1 for pointing camelCase notation, I totally forgot it to point in my answer since I haven't coded in Java for a year or two.
Comment: Tks for the support and tks for pointing in the right direction. I managed to complete my assignment finally.

java Interpretation correct


Get row item instead of index-# from iterrows()

Question: I am new in Python, and trying to understand how the iterrows-function works in Pandas. I am trying to iterate over each row in the csv-file below and print the values in the name, month and day-columns. It works for all except for the name-column. Index-numbers are printed instead of "Brond" and "Birdie".
### Below is the content of a file named examples.csv:
name,email,year,month,day
Brond,firstname.lastname@example.com,1985,09,30
Birdie,email@example.com,1985,08,29

My attempt is:
with open("examples.csv") as examples_file:
examples = pandas.read_csv(examples_file)
for (index, row) in examples.iterrows():
    print(row.name)

### The printed result is "0" and "1", instead of "Brond" and "Birdie".

Answer: You should avoid using the attributes (row.name) and rather slice with indices (row['name']).
Using attributes has many pitfalls, you just fell in one! .name gives the Series name so if an indices name clashes, this doesn't work.
for (index, row) in examples.iterrows():
    print(row['name'])

output:
Brond
Birdie


$C_1\le C_2x^{-2\alpha}+C_3x^{2\beta+1}\le C_4$...can one deduce $c\le x\le C$?

Question: Suppose we have the inequality
$$C_1\le C_2x^{-2\alpha}+C_3x^{2\beta+1}\le C_4$$
where $C_1,C_2,C_3,C_4>0$ are positive constants which depend on $\alpha,\beta>0$ and $x>0$.
Can one deduce an inequality of the form
$c\le x\le C$,
for $c,C>0$ positive constants?
Answer: Yes.
As everything is positive, $ C_3x^{2\beta+1}\le C_4$ implies
 $$x\le (C_4/C3)^{1/(2\beta+1)}$$
and $C_2x^{-2\alpha}\le C_4$  implies
$$ x\ge (C_2/C_4)^{1/2\alpha}.$$


When calling api from web application using ajax (error 401 unauthorize)?

Question: api calling from web application ajax (401 unauthorize error).
all cookie get in api ,in this cookie access token available but api will not authorize
in this code used a withCredentials: true
and using identity server 6
web application ajax code below hare
<code>    $(document).ready(function () {
        GetData();
        function GetData() {
            $.ajax({
                type: "GET",
                url: "https://localhost:7129/Customer",
                crossDomain: true,
                xhrFields: {
                    withCredentials: true
                },
                dataType: "json",
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Methods": "*",
                    "Access-Control-Allow-Headers": "*",
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                success: function (data)
                {
                    alert(JSON.stringify(data));

                    }); //End of foreach Loop

                }, //End of AJAX Success function

                failure: function (data) {
                    alert( "failure " + data.responseText);
                }, //End of AJAX failure function
                error: function (xhr, status, error) {
                    // Handle the error
                    console.log("AJAX request failed.");
                    console.log("Status: " + status);
                    console.log("Error: " + error);
                } //End of AJAX error function

            });
        }

    });
</code>
in this ajax code send access token in header api authorize successful
<code>  headers: {
               "Authorization": "Bearer " + "Access Token",

            },
</code>
but cookie base authorize not working getting (error 401 unauthorize)
solving this error 401 unauthorized when calling api from web appllication
Comment: please confirm that the cookies are correctly set and include the necessary authentication information
Comment: yes cookie are same and correctly set
Comment: how to api authorize cookie base when calling form web application using ajax
Comment: try placing breakpoints on your controller, moreover is server configured for CORS properly, could be issues with auth type, does your api allow it?
Comment: How do you authenticate your cookie?
Answer: I don't know whether this code will help you or not, I am also attaching the link
along with the code, hope this might help you
https://datatables.net/forums/discussion/45615/how-to-load-table-from-ajax-request
<code>
    // this is the DataTable initializer  apply the ajax call
    $(".display").DataTable({
        "ajax":function(data, callback, settings) {

                // code

        }
    });

    // this ajax function sends credentials required for authorization
    // and receives the data from the API.

    $.ajax({
        url: 'http://testdomain/api/testtables',
        method: "GET",
        xhrFields: {
            withCredentials: true
        },
        success: function (data) {
            // loop data to console to verify it is
            // arriving to browser

            $.each(data, function(a, b) {
                console.log(b);
            });
        }
    });

});```

  [1]: https://datatables.net/forums/discussion/45615/how-to-load-table-from-ajax-request
</code>
Comment: this code also not working


Como é a leitura de sentenças com virgula em JavaScript?

Question: Hoje estava testando minificar meu código e fiquei em duvida quanto a conversão
Código Original
Loader = (function(Configure){

    var CurrentAction = null;
    var loaded = [];

    loader = function(){}

    loader.prototype = {
        check : function(action){
            var _return = false;
            if(CurrentAction == null || Configure.get('reload')){
                loaded.push(action);
                _return = true;
            }

            if(CurrentAction != action && loaded.indexOf(action) == -1){
                loaded.push(action);
                _return = true;
            }
            CurrentAction = action;
            return _return;
        }
    }

    return new loader();
}(Configure));

Código Minificado
Loader = function(e) {
    var n = null,
        r = [];
    return loader = function() {}, loader.prototype = {
        check: function(o) {
            var u = !1;
            return (null == n || e.get("reload")) && (r.push(o), u = !0), n != o && -1 == r.indexOf(o) && (r.push(o), u = !0), n = o, u
        }
    }, new loader
}(Configure);

Duvida

Como se lê esse código com virgulas?

Adendo
Eu ate entendo ele não executar (r.push(o), u = !0) se -1 == r.indexOf(o) já ter gerado false, mas eu não compreendo quando é executado o que vem apos a virgula, n = o, u
Answer: Isso é uma técnica de precedência de operador, e o nome de desse operador é operador de vírgula (comma operator) ou também conhecido como operador de avaliação múltipla.
Ele funciona da seguinte forma, ele avalia ou cálcula todos as expressões passadas separadas por vírgula da esquerda para a direita e retorna a última expressão passada.
Segue um exemplo:
var expr1 = 10 + 10,//Cálcula
    expr2 = 100 * 10,//Cálcula
    expr3 = 10 == "10",//Avalia
    expr4 = expr1 === expr2 && expr3;//Essa expressão expr4 que será retornada.

expr1, expr2, expr3, expr4;

Esse operador é mais usado quando você quer usar mais de uma expressão em um local onde normalmente se usaria uma só.
Normalmente esse operador é mais usado em loops for, por exemplo:
var vetor = [
  [1, 2, 3, 4], [5, 6, 7, 8]
];

for (var i = 0, j = 2; i < vetor.length; i++, j--) {
   console.log(vetor[i][j]);
}

Agora em relação ao seu código minificado, o que é retornado depois da vírgula é um valor booleano, que é essa variável u, que no seu código original representa sua variável _return.
var u = !1;

Igual a:
var _return = false;

E:
u = !0

Igual a:
_return = true;

Obs.: Essa expressão !1 é igual a false e !0 igual a true.
Analiando a conversão (Guilherme Lautert)
(null == n || e.get("reload")) && (r.push(o), u = !0)

(r.push(o), u = !0) esta parte do código sempre ira retonar true, contudo ela só é executada se a sentença anterior tbm for verdadeira
(null == n || e.get("reload")) é uma verificação real, que caso seja false ignora a proxima sentença pois se trata de um &&

n != o && -1 == r.indexOf(o) && (r.push(o), u = !0)

Similar ao anterior

n = o

Esta é a parte que é sempre executada CurrentAction = action;

u

Como comentado a ultima parte é retornada, esta que seria o _return
Comment: Só um adendo para que ninguém confunda: a vírgula em `var n = null, r = [];` é outra coisa: faz parte da sintaxe do `var`, não é o *comma operator*.
Comment: Compreendi, e analisando novamente o código ficou mais claro. Se não se importa gostaria de acrescentar alguns deleta-lhes.
Comment: Ok, tudo bem, pode acrescentar.
Answer: O que está ali na frente de return é uma sequência de expressão, e a última expressão (onde foi declarado o identificador u) vai ser retornada para o próprio statement return. Uma sequência de expressão vai para blocos, grupos ((...)) e outros lugares também, não apenas aí.
Em uma sequência de expressão não são declarados statements, somente expressões; Já, se você o declarar o statement var (let ou const), você não inicia uma sequência de expressão, mesmo se usar vírgulas, porém var só vai em blocos de comandos (como eu disse, statements não são declarados em sequência de expressão) e em outros lugares, por exemplo, nos argumentos do for que são separados por semicolons (;).

E outra, as chavetas declaradas depois das funções e depois dos statements for, while, with, etc, elas iniciam um bloco, que pode ter um novo escopo de variáveis dependendo do tipo. Se essas chavetas não são declaradas, é possível declarar apenas uma sequência de expressão, e também é possível declarar o statement var. Exemplo: if(true) var a, b;
Observação: try, catch e finally são statements que necessitam que as chavetas sejam declaradas porque o interpretador dos navegadores requerem, atualmente. Principalmente function...(...).


Investment calculator - returned number format issue

Question: I've created a function, which returns DataFrame with 3 columns - Year, Principal amount and End balance. It works fine, however the format number of End balance is weird, but I'm not sure, what I've done wrong.
If the input is investment_calculator(15000,7,10). It returns End balance in correct format:

However if it exceeds particular amount, e.g. investment_calculator(15000,10,10). The format of End balance is different, although nothing's changed:

Function:
def investment_calculator(amount,years,interest):
    """
    Investment calculator calculates returned amount.

    Args:
        amount: monthly invested amount
        years: number of years
        interest: average yearly interest

    Returns:
        DataFrame
    """
    col_names = ['Year', 'Principal', 'End balance']
    df = pd.DataFrame(columns = col_names)

    i = 1
    while i <= years:
        invested_amount = (amount * 12) * i
        year = datetime.datetime.now().year + (i - 1)

        if i == 1:
            investment = (amount * 12) * (1 + (interest / 100))
            new_row = {'Year':year, 'Principal':invested_amount, 'End balance':investment}
            df = df.append(new_row, ignore_index=True)
        else:
            investment = (df.iloc[-1,2] + (amount * 12)) * (1 + (interest / 100))
            new_row = {'Year':year, 'Principal':invested_amount, 'End balance':investment}
            df = df.append(new_row, ignore_index=True)

        i += 1

    return df

Any ideas, what's wrong, please?
Answer: Apparently pandas switches to scientific number notation when the numbers are sufficiently large. Your code does not contain the actual printing. When you print the results, format them as suitable, possibly by using f-strings: f"{df['End Balance']:.2f}".
Answer: I am sure you know your values are simply displayed using scientific notation. If its bother you, you can set a different default format, for instance:
pd.options.display.float_format = '{:.2f}'.format


how to encrypt/decrypt with crypto-js

Question: I'm using crypto-js library:
https://github.com/brix/crypto-js
I want to encrypt some value and decrypt them.
but it returns wrong output.
my codes:
import CryptoAES from 'crypto-js/aes'

componentDidMount(){
  var ciphertext = CryptoAES.encrypt('my message', 'secret key 123');
  var _ciphertext = CryptoAES.decrypt(ciphertext, 'secret key 123');
  console.log(_ciphertext.toString(CryptoAES.Utf8));
}

but my console doesn't return my message. it returns like this:
6d79206d657373616765

Comment: I got this error message : `cannot read property 'Utf8' of undefined`
Answer: import CryptoAES from 'crypto-js/aes';
import CryptoENC from 'crypto-js/enc-utf8';

var ciphertext = CryptoAES.encrypt('my message', 'secret key 123');
var _ciphertext = CryptoAES.decrypt(ciphertext.toString(), 'secret key 123');
console.log(_ciphertext.toString(CryptoENC));

Answer: I have never used this library, but a small check shows your result is your input's ASCII code as hex string.
0x6d=m
...
0x65=e

6d|79|20|6d|65|73|73|61|67|65
m |y |  |m |e |s |s |a |g |e

So this code is working correctly. Probably that _ciphertext.toString() mess everything up. You need to check how to use _ciphertext correctly.
Answer: Currently you are getting a hexa string 6d79206d657373616765 as you can check on this convertor when you enter my message it will return you 6d79206d657373616765
As used in the crypto-js Documentation
You need to make use of .toString() inside your decrypt method as currently you are getting hex for your my message and you need to convert that back to string, So you need to change this :
var _ciphertext = CryptoAES.decrypt(ciphertext, 'secret key 123');

To
var _ciphertext = CryptoAES.decrypt(ciphertext.toString(), 'secret key 123');

It will be like :
import CryptoAES from 'crypto-js/aes'

componentDidMount(){
  var ciphertext = CryptoAES.encrypt('my message', 'secret key 123');
  var _ciphertext = CryptoAES.decrypt(ciphertext.toString(), 'secret key 123');
  console.log(_ciphertext.toString(CryptoAES.Utf8));
}

Comment: this is the answer, because without `.toString` the result should be object type not string
Answer: You can use this. cippertext use output algorytms.
ciphertext.toString("base64")

or
ciphertext.toString("hex")

how to encrypt/decrypt with crypto-js


Cross join returning row from only one table

Question: I'm trying to get two different columns by cross joining on same table but getting only on e column. Following is the sample query  :
select 1 from dual cross join (select 2 from dual) t1;
Expected Result : 1 2
but getting only 1.
Comment: Please provide actual details
Comment: You're selecting `1`. Perhaps, you want to select all columns (`select *`).
Comment: I was selecting columns in an incorrect manner. Selecting all required columns in 1st select statement solved the problem
Answer: You have the select clause of
select 1

where you select a single column. If you want an output of 1 2 then use
select 1, 2

as your select clause.
Comment: Thanks, yes all required columns should be a part of first select statement
Comment: @ProgrammingEnthusiast since your problem has been solved, please, mark the best answer as the correct answer, so later visitors will see the solution at first glance.
Answer: You are not retrieving data from t1
select 1 as id, t1.*
from dual cross join (select 2 id1 from dual) t1;


Is there any way to know if a string is not translated?

Question: I have my own module that I want to translate to some languages. I use the t function and also I have my lang.po files.
I try to update the lang.po files every time I use the t function but maybe I forget to update some text string.
Is there any way to know if there are some t-strings without translation in the lang.po files?
I can go to admin/config/regional/translate/translate but I only need to check the strings of my module.
Answer: Install l10n_client then flush your cache.
If you switch to any other language you'll see a small box with blue bg in the bottom right. Click it and in the left it'll show all translated & untranslated strings. The green ones have been translated, while other ones you'll need to. Just select one and add the translation there itself.


Kill all Gradle Daemons Regardless Version?

Question: Summary
I would like to know how to kill every single gradle daemon and process running on a machine regardless of the version of gradle or the version of the daemon, but the "--kill" or "--stop" command will only stop those processes that match the same version of gradle.
Use case
My CI build box will have several gradle daemons running with different versions (because I'm a good boy that uses the wrapper to execute builds). Occasionally I will find issues with caching or incremental builds, and as a precaution I like to kill the daemons. The same is true for my development boxes, although the conflicts are more often with whichever VCS or IDE I am using.
What I am looking for

I'm hoping there is a flag or property I am missing that I could
pass to gradle to do this in a simple one line command, but if it's
simple enough I would be ok with more.
No scripting (looping,
if-else etc).
Killing all java processes is not acceptable.

Helpful links to the gradle docs
Disabling the Daemon
Stopping an existing Daemon
Answer: Under linux you may use pkill:
pkill -f '.*GradleDaemon.*'

Under windows you may use wmic:
WMIC PROCESS where "Name like 'java%' AND CommandLine like '%GradleDaemon%'" Call Terminate

PS. Why "no scripting" when it is probably the easiest solution?
Comment: I basically wanted something that would be really easy for developers on my team to remember and I needed it to be OS agnostic. I can write a script on my own, but I am (or was) hoping for something that was part of gradle (like a "--stop-all" flag). Your solution is also nice, so I could use it in a script that checks for the OS first and then executes one of those two commands, but I'm going to wait a but before accepting this as the answer.
Comment: The windows command doesn't work on my machine, presumably because the CommandLine argument doesn't contain the string, "GradleDaemon".
Answer: The gradle daemons did not disappear after 3hrs; this could be since I am running as Linux Guest in VirtualBox.
And hence, the following removes all gradle daemons but it could be "frowned upon" since it might be excessive...

./gradlew --stop   to ensure all daemons are stopped

delete all folders/files in .gradle folder in the project

delete .gradle folder in /home/username/
Linu

reboot

All daemons are gone. The next build takes a bit longer but worthwhile as do not like seeing 6 stopped daemons everytime a gradle build or even clean is started.
Comment: I think all you need to do is delete `/home/username/.gradle/daemons`
Comment: gradlew --stop worked for me.  Killing Java didn't work.
Answer: The gradle --status command will show you the process ids for each of the daemons. You can then use your OS to kill those processes.
I'm assuming this is cross-platform functionality, but this is the output on Windows:
  PID STATUS   INFO
10276 IDLE     5.4.1
14068 IDLE     5.4.1

It's a bit better than playing whack-a-mole with every java.exe process running on your system. Although it would be nice if gradle had a command that could terminate all running gradle daemons built-in.
Comment: `gradle --status` works the same as `--stop` and only lists daemons of the same version as the one you're running.
Answer: I have a similar problem and I made this:

Go To C:\Users\"Username"\.gradle\daemon
There are a Folder for each version of gradle
Delete the folder of your actual running version
Check with --status


How to respond to a Web Services request via WebSockets

Question: I have a WebSockets connection between a server and a client. This allows me to send a command to a client, and he responds me with data. The server has web services too. I can then tell, "do this command on that client". So we have:
Client1 ---webservices--> server ---websockets---> Client2
The problem is, the method on the server which receives the data from Client2 is void.
How can I send back the data to Client1 ?
WebServices:
@Path("/ws")
public class QOSResource {
    public QOSResource(){}

    @Produces(MediaType.TEXT_PLAIN)
    @Path("/ping/{macAddr}")
    @GET
    public String getPing(@PathParam("macAddr") String macAddr){
    return"Mac adresse : "+macAddr;
    //WebSocketsCentralisation.getInstance().ping(macAddr);
    }
}

WebSockets
@OnWebSocketMessage
    public **void** onText(Session session, String message) {
        if (session.isOpen()) {
            if(firstConnection){
                firstConnection = false;
                this.macAddr = message;
                WebSocketsCentralisation.getInstance().join(this);
            }
            ObjectMapper mapper = new ObjectMapper();
                Object o;
                try {
                    o = mapper.readValue(message, Object.class);
                    if(o instanceof PingResult){
                         **// TODO return result to ws**

                        }
                } catch (JsonParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JsonMappingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    }

Thanks in advance for your help
Answer: The Session object you get in your method parameters contains the scope of your conversation with the remote endpoint.
You'll want to use the RemoteEndpoint that the Session.getRemote() returns in order to send messages.
Examples:
// Send BINARY websocket message (async)
byte data[] = mapper.toBytes(obj);
session.getRemote().sendBytesByFuture(data);

// Send TEXT websocket message (async)
String text = mapper.toString(obj);
session.getRemote().sendStringByFuture(text);

Be aware though that the session.getRemote() call will throw a WebSocketException if the remote endpoint connection is no longer in an open state (such as the case where the remote endpoint send you a message and then immediately initiated a CLOSE handshake control message).
// How to handle send message if remote isn't there
try {
    // Send message to remote
    session.getRemote().sendString(text);
} catch(WebSocketException e) {
    // WebSocket remote isn't available.
    // The connection is likely closed or in the process of closing.
}

Note: this style of websocket use, where you have a Session and a RemoteEndpoint is consistent with the upcoming JSR-356 standard (javax.websocket).  In the standard API you will have javax.websocket.Session and javax.websocket.RemoteEndpoint to work with.
Comment: I'm sorry, I think I can't explain myself correctly in english(i speak french). What you explain here is right and I use it. Where my problem is: my server has both websockets and webservices. The webservices allow me to reach a client via websockets. In my example, I want to get the ping of a remote device. So I use the API /ws/ping/macAddr. Here, I can access to the correct session and send my command (ping). What I can't do is get the answer back, because the method on the server which receive the data via websockets is void.
Comment: That is correct, the Jetty API for a WebSocket @onMessage call are return type of `void`.  This is because the Jetty internal WebSocket parser eventually calls this message and does not expect a return type.  The upcoming Jetty 9.1 will support JSR-356 (javax.websocket) and it has the concept of a return type for @OnMessage calls, but be aware that this is also managed by the WebSocket implementation, you cannot hook into this JSR-356 return type outside of websockets.
Comment: So here is my problem :) How can I send back the response to my webservices, if the "onText" method is void...
Comment: The `onText` is a method for the WebSocket implementation to use.  It would be difficult to use it arbitrarily as the Session parameter would need to be tracked and looked up.  Consider a new method say `String onWebsocketMessage(String message)` and do the logic there, having `onText` just use this new method and returning the response.
Comment: This other answer might be relevant in tracking the `Session` objects for multiple websockets - http://stackoverflow.com/a/15649791/775715
Comment: Like I said the Session is not the problem. Really, the problem comes when the websocket server gets the answer back from the remote device on the "onText" message, because it is void and it's an event. I can get back this result to the webservices
Answer: Your websocket handler should have an associated Connection instance on which you can call sendMessage().
Comment: I'm sorry I don't really see what you're saying. The communication between my websockets and my client2 is ok. The problem comes when client1 uses the webservice. How can I be synchronized between the moment where I tell "do the ping" (getPing) and the reception.
Comment: @brunettia - your code indicates a void method for the _websockets_ call, but your question seems to refer tot the _webservices_ call.  which is it?
Comment: Both actually. The websocket server will receive the data, but in a void method. So how can I send the datas back to the webservices, and make it wait the response!


Recuperando textos digitados em EditText gerado em tempo de execução

Question: Em meu projeto tenho alguns EditText sendo gerados em tempo de execução, o número de EditText é variável.
Preciso recuperar os textos digitados e armazenar em variáveis diferentes, para depois criar um objeto Json com isso.
Aqui está o método que utilizo para criar o EditText:
public View editText(String nmLabel, String tpRender) {
    EditText e = new EditText(getBaseContext());
    e.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    // e.setHint("DATE");

    if(tpRender.equals("NUMBER")) {
        e.setHint("NUMBER");
    }
    else if(tpRender.equals("DATE")) {
        e.setHint("DATE");
    }
    else if(tpRender.equals("TEXT")) {
        e.setHint("TEXT");
    }
    e.setTextColor(Color.BLACK);
    e.setTextSize(20);

    return(e);
}

Como obtenho os textos digitados separadamente?
Answer: Atribua um id diferente a cada um deles usando e.setId(int id)
Pode depois aceder a eles utilizando o método findViewById() da view(layout) onde eles foram inseridos.
Comment: Funcionou 100%, obrigado!