问:
Extracting text from generated PDF document with variables
I'm extracting text from a PDF document.
This PDF was generated using a WS reading Data From AS400 . So when printing text, the output is like :

```<code>orem ipsum dolor sit amet, **«VS123»**  In eros risus, «VS124» sed felis quis, commodo interdum tellus. Donec vitae massa
</code>```

And «VS123» , «VS124» are variables from AS400.The Java APi is not able to read Value from variable and its printing Variable name instead of variable values.

I'm using PDFBox https://pdfbox.apache.org/ to extract text.
The code source is like :

```<code>import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public class App
{
     public static void main( String[] args ) throws IOException
        {
        try (PDDocument document = PDDocument.load(new File("C:/my.pdf"))) {

            document.getClass();

            if (!document.isEncrypted()) {

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);

                PDFTextStripper tStripper = new PDFTextStripper();

                String pdfFileInText = tStripper.getText(document);

                // split by whitespace
                String lines[] = pdfFileInText.split("\\r?\\n");
                for (String line : lines) {
                    System.out.println(line);
                }
                document.close();
            }
        }
    }
}
</code>```

The output starts with this stack of error :

AVERTISSEMENT: Invalid ToUnicode CMap in font ArialMT nov. 16, 2017
  8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode
  AVERTISSEMENT: No Unicode mapping for CID+77 (77) in font ArialMT nov.
  16, 2017 8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font
  toUnicode AVERTISSEMENT: No Unicode mapping for CID+111 (111) in font
  ArialMT nov. 16, 2017 8:08:24 PM
  org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode AVERTISSEMENT: No
  Unicode mapping for CID+110 (110) in font ArialMT nov. 16, 2017
  8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode
  AVERTISSEMENT: No Unicode mapping for CID+116 (116) in font ArialMT
  nov. 16, 2017 8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font
  toUnicode AVERTISSEMENT: No Unicode mapping for CID+97 (97) in font
  ArialMT nov. 16, 2017 8:08:24 PM
  org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode AVERTISSEMENT: No
  Unicode mapping for CID+32 (32) in font ArialMT

I'tried also to exract text using iText :

```<code>import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

import java.io.IOException;

public class App {
    private static final String FILE_NAME = "C:/my.pdf";

    public static void main(String[] args) {

        PdfReader reader;

        try {

            reader = new PdfReader(FILE_NAME);

            String textFromPage = PdfTextExtractor.getTextFromPage(reader, 1);

            System.out.println(textFromPage);

            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
</code>```

Here is the part of the PDF document :

When Tryin to extract text, or with Copy-paste, The output will be this :

CLIENT N° «VS35» « VS36 »
CONTRAT N° «VS28»

The link to the PDF File:
https://drive.google.com/file/d/1RNea028nCReIVS8nRWNlBwUwBsDOhDYg/view?usp=sharing

答:
AFAIK, the PDF doesn't contain variable data as displayed in the text. If there are any variables there, they might have converted to be used by it's own interactivity interface. (e.g. SVG interactivity).

So when the PDF was generated, the variable names were converted to string and the actual variable data might have been renamed.

Body:
I'm extracting text from a PDF document.
This PDF was generated using a WS reading Data From AS400 . So when printing text, the output is like :

orem ipsum dolor sit amet, **«VS123»**  In eros risus, «VS124» sed felis quis, commodo interdum tellus. Donec vitae massa

And «VS123» , «VS124» are variables from AS400.The Java APi is not able to read Value from variable and its printing Variable name instead of variable values.

I'm using PDFBox https://pdfbox.apache.org/ to extract text.
The code source is like :

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public class App
{
     public static void main( String[] args ) throws IOException
        {
        try (PDDocument document = PDDocument.load(new File("C:/my.pdf"))) {

            document.getClass();

            if (!document.isEncrypted()) {

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);

                PDFTextStripper tStripper = new PDFTextStripper();

                String pdfFileInText = tStripper.getText(document);

                // split by whitespace
                String lines[] = pdfFileInText.split("\\r?\\n");
                for (String line : lines) {
                    System.out.println(line);
                }
                document.close();
            }
        }
    }
}

The output starts with this stack of error :

AVERTISSEMENT: Invalid ToUnicode CMap in font ArialMT nov. 16, 2017
  8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode
  AVERTISSEMENT: No Unicode mapping for CID+77 (77) in font ArialMT nov.
  16, 2017 8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font
  toUnicode AVERTISSEMENT: No Unicode mapping for CID+111 (111) in font
  ArialMT nov. 16, 2017 8:08:24 PM
  org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode AVERTISSEMENT: No
  Unicode mapping for CID+110 (110) in font ArialMT nov. 16, 2017
  8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode
  AVERTISSEMENT: No Unicode mapping for CID+116 (116) in font ArialMT
  nov. 16, 2017 8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font
  toUnicode AVERTISSEMENT: No Unicode mapping for CID+97 (97) in font
  ArialMT nov. 16, 2017 8:08:24 PM
  org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode AVERTISSEMENT: No
  Unicode mapping for CID+32 (32) in font ArialMT

I'tried also to exract text using iText :

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

import java.io.IOException;

public class App {
    private static final String FILE_NAME = "C:/my.pdf";

    public static void main(String[] args) {

        PdfReader reader;

        try {

            reader = new PdfReader(FILE_NAME);

            String textFromPage = PdfTextExtractor.getTextFromPage(reader, 1);

            System.out.println(textFromPage);

            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Here is the part of the PDF document :

When Tryin to extract text, or with Copy-paste, The output will be this :

CLIENT N° «VS35» « VS36 »
CONTRAT N° «VS28»

The link to the PDF File:
https://drive.google.com/file/d/1RNea028nCReIVS8nRWNlBwUwBsDOhDYg/view?usp=sharing


来源: stackexchange

问:
catch IndexOutOfBoundsException Exception
I'm trying to catch made up IndexOutOfBoundsException  error in catch block. But every time its returning -1 and not going into catch block

May I know please why its happening ? I want to reach to catch block.

```<code>  public class Mars {

    public int Setname(String Input) {

        int output = 0;

        try {
            output = Input.indexOf("L");
            System.out.println("Error:" + Input.indexOf("L"));

            if (output == -1){

                throw new IndexOutOfBoundsException();
            }

        }

        catch (IndexOutOfBoundsException e) {

            System.out.println("Error:2" + e.getStackTrace());
        }

        return output;

    }

    public static void main(String[] args) {

        Mars O = new Mars();
        O.Setname("London");

    }

}
</code>```

Second thing is: When we write IndexOutOfBoundsException e in catch block, its creating an instance of IndexOutOfBoundsException class ?Am I right ?

So why we can't write like in below manner ? It could be a really silly question, but just for curiosity I want to know.

```<code>catch(IndexOutOfBoundsException e = new IndexOutOfBoundsException())
</code>```

答:
use an if statement and throw the exception

```<code>if(output == -1){
    throw new IndexOutOfBoundsException()
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to catch made up IndexOutOfBoundsException  error in catch block. But every time its returning -1 and not going into catch block

May I know please why its happening ? I want to reach to catch block.

  public class Mars {

    public int Setname(String Input) {

        int output = 0;

        try {
            output = Input.indexOf("L");
            System.out.println("Error:" + Input.indexOf("L"));

            if (output == -1){

                throw new IndexOutOfBoundsException();
            }

        }

        catch (IndexOutOfBoundsException e) {

            System.out.println("Error:2" + e.getStackTrace());
        }

        return output;

    }

    public static void main(String[] args) {

        Mars O = new Mars();
        O.Setname("London");

    }

}

Second thing is: When we write IndexOutOfBoundsException e in catch block, its creating an instance of IndexOutOfBoundsException class ?Am I right ?

So why we can't write like in below manner ? It could be a really silly question, but just for curiosity I want to know.

catch(IndexOutOfBoundsException e = new IndexOutOfBoundsException())

Body:
use an if statement and throw the exception

if(output == -1){
    throw new IndexOutOfBoundsException()
}


问:
Quartz vs. ScheduledExecutorService in Java web application
For a system monitoring Java application which currently runs on the command line and uses ScheduledExecutorService, I would like to write a simple web application version, to be run in a Servlet container like Apache Tomcat or Eclipse Jetty.

I have read about Quartz as one of the popular job schedulers for web applications. Would it be better (maybe because of better servlet container integration) to port this application from ScheduledExecutorService to Quartz?

Adding another library dependency to the application is not a problem, I am interested in technical reasons against usage of ScheduledExecutorService.

答:
It depends on what you are using it for.

Quartz is useful for programmed times e.g. every hour on the hour.

ScheduledExecutorService is useful for repeating tasks which don't have to occur at a specific time. Its simpler and possibly more efficient. If you have this working it indicates to me that you don't need Quartz.

ContentLicense: CC BY-SA 2.5


问:
Check if value exists in the list
Let’s say I have 123-0-1 and I want to check if this value exists inside the list. Below is the list that I have:

```<code> df = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]
</code>```

In SQL I would use:

```<code>select mpls, source from df where source = 192.168.10.10
</code>```

From the list, I would like extract mpls 123-0-1 from the source 192.168.10.10 such that I can get the correct destination 12.168.100.10.

答:
The other answers are just fine; just wanted to show how next could also be used:

```<code>df = [{'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'}, {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}]

try:
  target = next(x for x in df if x['source'] == '192.168.10.10')
except StopIteration:
  print('Value not found!')
else:
  print(target['mpls'])         # -> 123-0-1
  print(target['destination'])  # -> 12.168.100.10
</code>```

Note that this returns only the first dictionary that meets the criteria. based on your SQL statement, it seems that you want to get them all.

Title: Check if value exists in the list

Body:
Let’s say I have 123-0-1 and I want to check if this value exists inside the list. Below is the list that I have:

 df = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]

In SQL I would use:

select mpls, source from df where source = 192.168.10.10

From the list, I would like extract mpls 123-0-1 from the source 192.168.10.10 such that I can get the correct destination 12.168.100.10.

Body:
The other answers are just fine; just wanted to show how next could also be used:

df = [{'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'}, {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}]

try:
  target = next(x for x in df if x['source'] == '192.168.10.10')
except StopIteration:
  print('Value not found!')
else:
  print(target['mpls'])         # -> 123-0-1
  print(target['destination'])  # -> 12.168.100.10

Note that this returns only the first dictionary that meets the criteria. based on your SQL statement, it seems that you want to get them all.


问:
Pass move_lines into stock.picking from another model - Odoo v8
I have this method:

```<code>@api.multi
def create_printy(self):
    copy_record = self.env['stock.picking']
    for record in self:

        order_lines = []
        for rec in record.order_lines:
            order_lines.append(
            (0,0,
            {
                'product_id': rec.isbn.id,
                'product_qty': rec.qty,
                }
            ))
        sp_types = self.env['stock.picking.type'].search([
        ('code', '=', 'outgoing')
        ])
        if len(sp_types) > 0:
            copy_record.create({
                'origin': record.name,
                'picking_type_id': sp_types[0].id,
                'move_lines': order_lines,
                'move_type': 'direct',
                'priority': '1',
                'company_id': record.company_id.id,
            })
</code>```

I'm trying to create a stock.picking from another model.

But, with this method, I have problems for move_lines which on stock.picking is related to stock.move.

Right now, it throws me this:

```<code>        Integrity Error

The operation cannot be completed, probably due to the following:
- deletion: you may be trying to delete a record while other records still reference it
- creation/update: a mandatory field is not correctly set

[object with reference: Product Unit of Measure - product.uom]
</code>```

I know there are a few stock.move required fields which aren't present in my order_lines field.

So, my question is, how can I pass for example product.uom or date_expected which are required from my model?

Is there some similar way as it is done with picking_type_id in my example. for One2many field?

答:
You could take a look of what happens when you do not fill these fields in the interface (and look what they get by default). For example, in stock.move Odoo takes the product_uom from product_id field (through an onchange method). And the date_expected is filled in by default with the current date. So:

```<code>@api.multi
def create_printy(self):
    copy_record = self.env['stock.picking']
    for record in self:
        order_lines = []
        for rec in record.order_lines:
            order_lines.append(
            (0,0,
            {
                'product_id': rec.isbn.id,
                'product_uom': rec.isbn.uom_id.id,
                'date_expected': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT),
                'product_qty': rec.qty,
                }
            ))
        sp_types = self.env['stock.picking.type'].search([
        ('code', '=', 'outgoing')
        ])
        if len(sp_types) > 0:
            copy_record.create({
                'origin': record.name,
                'picking_type_id': sp_types[0].id,
                'move_lines': order_lines,
                'move_type': 'direct',
                'priority': '1',
                'company_id': record.company_id.id,
            })
</code>```

For date_expected you will have to import in your .py file (out of your classes) the following:

```<code>import time
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
</code>```

Body:
I have this method:

@api.multi
def create_printy(self):
    copy_record = self.env['stock.picking']
    for record in self:

        order_lines = []
        for rec in record.order_lines:
            order_lines.append(
            (0,0,
            {
                'product_id': rec.isbn.id,
                'product_qty': rec.qty,
                }
            ))
        sp_types = self.env['stock.picking.type'].search([
        ('code', '=', 'outgoing')
        ])
        if len(sp_types) > 0:
            copy_record.create({
                'origin': record.name,
                'picking_type_id': sp_types[0].id,
                'move_lines': order_lines,
                'move_type': 'direct',
                'priority': '1',
                'company_id': record.company_id.id,
            })

I'm trying to create a stock.picking from another model.

But, with this method, I have problems for move_lines which on stock.picking is related to stock.move.

Right now, it throws me this:

        Integrity Error

The operation cannot be completed, probably due to the following:
- deletion: you may be trying to delete a record while other records still reference it
- creation/update: a mandatory field is not correctly set

[object with reference: Product Unit of Measure - product.uom]

I know there are a few stock.move required fields which aren't present in my order_lines field.

So, my question is, how can I pass for example product.uom or date_expected which are required from my model?

Is there some similar way as it is done with picking_type_id in my example. for One2many field?

Body:
You could take a look of what happens when you do not fill these fields in the interface (and look what they get by default). For example, in stock.move Odoo takes the product_uom from product_id field (through an onchange method). And the date_expected is filled in by default with the current date. So:

@api.multi
def create_printy(self):
    copy_record = self.env['stock.picking']
    for record in self:
        order_lines = []
        for rec in record.order_lines:
            order_lines.append(
            (0,0,
            {
                'product_id': rec.isbn.id,
                'product_uom': rec.isbn.uom_id.id,
                'date_expected': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT),
                'product_qty': rec.qty,
                }
            ))
        sp_types = self.env['stock.picking.type'].search([
        ('code', '=', 'outgoing')
        ])
        if len(sp_types) > 0:
            copy_record.create({
                'origin': record.name,
                'picking_type_id': sp_types[0].id,
                'move_lines': order_lines,
                'move_type': 'direct',
                'priority': '1',
                'company_id': record.company_id.id,
            })

For date_expected you will have to import in your .py file (out of your classes) the following:

import time
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT


问:
Use Angular2 component in Angular4
Is there any chance to use angular2 components in angular4?
In my case i want to use library to generate charts:
https://devarchy.com/angular/ng2-nvd3, but unfortunately its dependencies are too low for my app. Aren't angular2 components compatible with angular4?

NPM trying install of pck

```<code>QLOOK2@0.0.0 D:\QLook2\App\trunk\QLook2.Client
+-- UNMET PEER DEPENDENCY @angular/common@4.2.4
+-- UNMET PEER DEPENDENCY @angular/core@4.2.4
+-- UNMET PEER DEPENDENCY @ngrx/store@2.2.2
`-- ng2-nvd3@2.0.0-rc3
  +-- d3@3.5.17
  +-- nvd3@1.8.5
  `-- rxjs@5.2.0

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN @ngrx/devtools@1.4.0 requires a peer of @angular/core@^2.0.0-rc.0 but none was installed.
npm WARN @ngrx/devtools@1.4.0 requires a peer of @ngrx/store@^1.5.0 but none was installed.
npm WARN angular2-google-maps@0.17.0 requires a peer of @angular/common@^2.3.1 but none was installed.
npm WARN angular2-google-maps@0.17.0 requires a peer of @angular/core@^2.3.1 but none was installed.
npm WARN ng2-select2@1.0.0-beta.10 requires a peer of @angular/core@^2.2.0 but none was installed.
</code>```

PS. I'm not able to downgrade apps' libraries
PS2. I need this lib because there are multi Y-axis which are necessary in my app.

答: Components built in Angular 2 can be used in Angular 4 but the modules which are used in angular 2 version are only compatible with that version.So the answer your query you have to install the module which is compatible with angular 4 version.</p>

Title: Use Angular2 component in Angular4

Body:
Is there any chance to use angular2 components in angular4?
In my case i want to use library to generate charts:
https://devarchy.com/angular/ng2-nvd3, but unfortunately its dependencies are too low for my app. Aren't angular2 components compatible with angular4?

NPM trying install of pck

QLOOK2@0.0.0 D:\QLook2\App\trunk\QLook2.Client
+-- UNMET PEER DEPENDENCY @angular/common@4.2.4
+-- UNMET PEER DEPENDENCY @angular/core@4.2.4
+-- UNMET PEER DEPENDENCY @ngrx/store@2.2.2
`-- ng2-nvd3@2.0.0-rc3
  +-- d3@3.5.17
  +-- nvd3@1.8.5
  `-- rxjs@5.2.0

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN @ngrx/devtools@1.4.0 requires a peer of @angular/core@^2.0.0-rc.0 but none was installed.
npm WARN @ngrx/devtools@1.4.0 requires a peer of @ngrx/store@^1.5.0 but none was installed.
npm WARN angular2-google-maps@0.17.0 requires a peer of @angular/common@^2.3.1 but none was installed.
npm WARN angular2-google-maps@0.17.0 requires a peer of @angular/core@^2.3.1 but none was installed.
npm WARN ng2-select2@1.0.0-beta.10 requires a peer of @angular/core@^2.2.0 but none was installed.

PS. I'm not able to downgrade apps' libraries
PS2. I need this lib because there are multi Y-axis which are necessary in my app.


问:
Can I add a process to every component's ngOnInit and OnDestroy?
I have an observable that I need to bind and remove on every component.

Is it possible to write the subscribe/unsubscribe logic somewhere and have it implicitly included in every component?

Like a middleware on the creation/destruction of a component

Here is an example of what I'd like to see:
https://i.imgur.com/K8XtaFv.png

edit: yurzui gave me the idea to use super.ngOnInit()
Not as clean as I'd like, but hey - it works.

```<code>import { Component, OnInit, OnDestroy } from '@angular/core';

export class ExtendHooks {
  ngOnDestroy() {
    console.log("Want this to fire first")
  }

  ngOnInit() {
    console.log('Want to fire first')
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends ExtendHooks implements OnInit, OnDestroy {

  constructor(){
    super()
  }

  ngOnDestroy() {
    super.ngOnDestroy()
    console.log("Want this to fire second")
  }

  ngOnInit() {
    super.ngOnInit()
    console.log("Want to fire second")
  }
}
</code>```

答: Try router lifecycle hooks navigationstart and navigationend</p>

Body:
I have an observable that I need to bind and remove on every component.

Is it possible to write the subscribe/unsubscribe logic somewhere and have it implicitly included in every component?

Like a middleware on the creation/destruction of a component

Here is an example of what I'd like to see:
https://i.imgur.com/K8XtaFv.png

edit: yurzui gave me the idea to use super.ngOnInit()
Not as clean as I'd like, but hey - it works.

import { Component, OnInit, OnDestroy } from '@angular/core';

export class ExtendHooks {
  ngOnDestroy() {
    console.log("Want this to fire first")
  }

  ngOnInit() {
    console.log('Want to fire first')
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends ExtendHooks implements OnInit, OnDestroy {

  constructor(){
    super()
  }

  ngOnDestroy() {
    super.ngOnDestroy()
    console.log("Want this to fire second")
  }

  ngOnInit() {
    super.ngOnInit()
    console.log("Want to fire second")
  }
}


问:
How to detect video in Android WebView with HitTestResult?
Like we detect anchor text using hitTestResult.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE, How can I detect a video playing on Facebook?

I want to know the hitTestResult.GetExtra() for a video file and then search for its valid extension (.mp4) and then download the file.

答:
So as I understand based on what you described you load your FB page in a WebView and want to download .mp4 videos if there is one. This code will do it for you

```<code>@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.addJavascriptInterface(this, "FBDownloader");
    webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url)
            {
                if (swipeLayout.isRefreshing())
                {
                    swipeLayout.setRefreshing(false);
                }

                webView.loadUrl("javascript:(function() { "
                                + "var el = document.querySelectorAll('div[data-sigil]');"
                                + "for(var i=0;i<el.length; i++)"
                                + "{"
                                + "var sigil = el[i].dataset.sigil;"
                                + "if(sigil.indexOf('inlineVideo') > -1){"
                                + "delete el[i].dataset.sigil;"
                                + "var jsonData = JSON.parse(el[i].dataset.store);"
                                + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\");');"
                                + "}" + "}" + "})()");
            }

            @Override
            public void onLoadResource(WebView view, String url)
            {
                webView.loadUrl("javascript:(function prepareVideo() { "
                                + "var el = document.querySelectorAll('div[data-sigil]');"
                                + "for(var i=0;i<el.length; i++)"
                                + "{"
                                + "var sigil = el[i].dataset.sigil;"
                                + "if(sigil.indexOf('inlineVideo') > -1){"
                                + "delete el[i].dataset.sigil;"
                                + "console.log(i);"
                                + "var jsonData = JSON.parse(el[i].dataset.store);"
                                + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\",\"'+jsonData['videoID']+'\");');"
                                + "}" + "}" + "})()");
                webView.loadUrl("javascript:( window.onload=prepareVideo;"
                                + ")()");
            }
        });

    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    CookieSyncManager.getInstance().startSync();

    webView.loadUrl(target_url);
}

@JavascriptInterface
public void processVideo(final String vidData, final String vidID)
{
    try
    {
        String mBaseFolderPath = android.os.Environment
            .getExternalStorageDirectory()
            + File.separator
            + "FacebookVideos" + File.separator;
        if (!new File(mBaseFolderPath).exists())
        {
            new File(mBaseFolderPath).mkdir();
        }
        String mFilePath = "file://" + mBaseFolderPath + "/" + vidID + ".mp4";

        Uri downloadUri = Uri.parse(vidData);
        DownloadManager.Request req = new DownloadManager.Request(downloadUri);
        req.setDestinationUri(Uri.parse(mFilePath));
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        DownloadManager dm = (DownloadManager) getSystemService(getApplicationContext().DOWNLOAD_SERVICE);
        dm.enqueue(req);
        Toast.makeText(this, "Download Started", Toast.LENGTH_LONG).show();
    }
    catch (Exception e)
    {
        Toast.makeText(this, "Download Failed: " + e.toString(), Toast.LENGTH_LONG).show();
    }
}
</code>```

Body:
So as I understand based on what you described you load your FB page in a WebView and want to download .mp4 videos if there is one. This code will do it for you

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.addJavascriptInterface(this, "FBDownloader");
    webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url)
            {
                if (swipeLayout.isRefreshing())
                {
                    swipeLayout.setRefreshing(false);
                }

                webView.loadUrl("javascript:(function() { "
                                + "var el = document.querySelectorAll('div[data-sigil]');"
                                + "for(var i=0;i<el.length; i++)"
                                + "{"
                                + "var sigil = el[i].dataset.sigil;"
                                + "if(sigil.indexOf('inlineVideo') > -1){"
                                + "delete el[i].dataset.sigil;"
                                + "var jsonData = JSON.parse(el[i].dataset.store);"
                                + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\");');"
                                + "}" + "}" + "})()");
            }

            @Override
            public void onLoadResource(WebView view, String url)
            {
                webView.loadUrl("javascript:(function prepareVideo() { "
                                + "var el = document.querySelectorAll('div[data-sigil]');"
                                + "for(var i=0;i<el.length; i++)"
                                + "{"
                                + "var sigil = el[i].dataset.sigil;"
                                + "if(sigil.indexOf('inlineVideo') > -1){"
                                + "delete el[i].dataset.sigil;"
                                + "console.log(i);"
                                + "var jsonData = JSON.parse(el[i].dataset.store);"
                                + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\",\"'+jsonData['videoID']+'\");');"
                                + "}" + "}" + "})()");
                webView.loadUrl("javascript:( window.onload=prepareVideo;"
                                + ")()");
            }
        });

    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    CookieSyncManager.getInstance().startSync();

    webView.loadUrl(target_url);
}

@JavascriptInterface
public void processVideo(final String vidData, final String vidID)
{
    try
    {
        String mBaseFolderPath = android.os.Environment
            .getExternalStorageDirectory()
            + File.separator
            + "FacebookVideos" + File.separator;
        if (!new File(mBaseFolderPath).exists())
        {
            new File(mBaseFolderPath).mkdir();
        }
        String mFilePath = "file://" + mBaseFolderPath + "/" + vidID + ".mp4";

        Uri downloadUri = Uri.parse(vidData);
        DownloadManager.Request req = new DownloadManager.Request(downloadUri);
        req.setDestinationUri(Uri.parse(mFilePath));
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        DownloadManager dm = (DownloadManager) getSystemService(getApplicationContext().DOWNLOAD_SERVICE);
        dm.enqueue(req);
        Toast.makeText(this, "Download Started", Toast.LENGTH_LONG).show();
    }
    catch (Exception e)
    {
        Toast.makeText(this, "Download Failed: " + e.toString(), Toast.LENGTH_LONG).show();
    }
}


Title: error converting dataframe to dictionary in pandas

Body:
I have a data frame as follows

         0    1    2    3    4    5    6    7    8    9
window
1000    210  227  224  223  215  239  224  217  228  218
1500    306  304  262  267  304  294  291  283  272  267
2000    294  252  362  315  286  302  358  284  318  291
2500    322  326  332  262  367  251  272  354  360  373
3000    400  253  388  400  345  400  400  359  264  310
3500    260  400  400  321  365  285  374  335  308  342
4000    400  400  400  386  304  400  332  305  350  386

I want to convert it into dictionary like

   {'1000   :[210  227  224  223  215  239  224  217  228  218]
    '1500'  :[306  304  262  267  304  294  291  283  272  267]
    '2000'  :[294  252  362  315  286  302  358  284  318  291]
    '2500'  :[322  326  332  262  367  251  272  354  360  373]
    '3000'  :[400  253  388  400  345  400  400  359  264  310]
    '3500'  :[260  400  400  321  365  285  374  335  308  342]
    '4000'  :[400  400  400  386  304  400  332  305  350  386]}

I have tried mentioned solution by following this link

dictionary= df.set_index('window').T.to_dict('list')

print dictionary

But I am getting following error

Body:
window is already index, so need remove set_index('window'):

print (df.index)
Int64Index([1000, 1500, 2000, 2500, 3000, 3500, 4000], dtype='int64', name='window')

print (df.index.name)
window

dictionary = df.T.to_dict('list')
print (dictionary)

{2000: [294, 252, 362, 315, 286, 302, 358, 284, 318, 291],
 3000: [400, 253, 388, 400, 345, 400, 400, 359, 264, 310],
 4000: [400, 400, 400, 386, 304, 400, 332, 305, 350, 386],
 2500: [322, 326, 332, 262, 367, 251, 272, 354, 360, 373],
 1000: [210, 227, 224, 223, 215, 239, 224, 217, 228, 218],
 3500: [260, 400, 400, 321, 365, 285, 374, 335, 308, 342],
 1500: [306, 304, 262, 267, 304, 294, 291, 283, 272, 267]}


问:
Generating sources by running a project's java class in Maven
I'm converting a largish Ant build to Maven. As part of the Ant build, we have several steps which created Java classes by invoking one of the project's classes, simplified as:

```<code>javac SomeGenerator.java
java  SomeGenerator  generated # generate classes in generated/
javac generated/*.java
</code>```

I've split each generator in its own Maven module, but I have the problem of not being able to run the generator since it's not yet compiled in the generate-sources phase.

I've tried something similar to

```<code>        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.1.1</version>
            <executions>
                <execution>
                    <id>generate-model</id>
                    <goals>
                        <goal>java</goal>
                    </goals>
                    <phase>generate-sources</phase>

                    <configuration>
                        <mainClass>DTOGenerator</mainClass>
                        <arguments>
                            <argument>${model.generated.dir}</argument>
                        </arguments>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

Which sadly does not work, for the reasons outlined above. Splitting the code generators into two projects each, one for compiling the generator and another for generating the DTOs seems overkill.

What alternatives are there?

Using Maven 2.2.1.

答:
I posted a minimal working setup here https://github.com/baloise/inlinesourcecodegenerator
It uses build-helper compiler and exec plugins and has all code in the same project.</p>

Body:
I'm converting a largish Ant build to Maven. As part of the Ant build, we have several steps which created Java classes by invoking one of the project's classes, simplified as:

javac SomeGenerator.java
java  SomeGenerator  generated # generate classes in generated/
javac generated/*.java

I've split each generator in its own Maven module, but I have the problem of not being able to run the generator since it's not yet compiled in the generate-sources phase.

I've tried something similar to

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.1.1</version>
            <executions>
                <execution>
                    <id>generate-model</id>
                    <goals>
                        <goal>java</goal>
                    </goals>
                    <phase>generate-sources</phase>

                    <configuration>
                        <mainClass>DTOGenerator</mainClass>
                        <arguments>
                            <argument>${model.generated.dir}</argument>
                        </arguments>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Which sadly does not work, for the reasons outlined above. Splitting the code generators into two projects each, one for compiling the generator and another for generating the DTOs seems overkill.

What alternatives are there?

Using Maven 2.2.1.


问:
Rails: how to enable PaperTrail auditing for tags
I have a Rails 4.2 app and I'd like to keep audit history for tags by using PaperTrail.

Ideally the tags would be logged as if they were simply an attribute of the tagged model i.e. Model#tag_list.

I have enabled logging of Taggings by putting this in an initializer:

```<code>module ActsAsTaggableOn
  class Tagging
    has_paper_trail
  end
end
</code>```

... This does create versions for the Tagging but does not give me the desired behavior which is have the tags appear as simply a tag_list attribute of the tagged model.

答:
It probably makes sense to include versioning associations

```<code>PaperTrail.config.track_associations = true
</code>```

after that, you can do for example

```<code>subject.versions.last.reify(has_many: true)
</code>```

if you need "tag_list" you can write a wrapper that returns the list you need

```<code>def tag_list
  tagging.pluck(:title) #for_example
end
</code>```

Body:
I have a Rails 4.2 app and I'd like to keep audit history for tags by using PaperTrail.

Ideally the tags would be logged as if they were simply an attribute of the tagged model i.e. Model#tag_list.

I have enabled logging of Taggings by putting this in an initializer:

module ActsAsTaggableOn
  class Tagging
    has_paper_trail
  end
end

... This does create versions for the Tagging but does not give me the desired behavior which is have the tags appear as simply a tag_list attribute of the tagged model.

Body:
It probably makes sense to include versioning associations

PaperTrail.config.track_associations = true

after that, you can do for example

subject.versions.last.reify(has_many: true)

if you need "tag_list" you can write a wrapper that returns the list you need

def tag_list
  tagging.pluck(:title) #for_example
end


问:
how to filter hashmap and find 1st occurance
i have converted my hashmap to json as i dont know what itt looks like in java

so my hashmap looks like

```<code>{"1":[true,false],
"2":[true,true],
"3":[true]}
</code>```

i need to get the first occurance of all true in the array list in a single key

in this case its 2 is the 1st occurance

so if there is an occurance   ///do something   else //do somethig else

```<code>   hm.forEach((key, value) -> {

            for (Object object : value) {

                   boolean b = (boolean)object;
                   if(!b){
                   break;
                    }else{
                       System.out.println(key+"->"+b);
                   }

            }
});
</code>```

i tried something like this but im getting lost in the mix  here its testing alotall the cases

any help would be greatly appreciated

答:
try the snippet below.</p>

```<code>hm.forEach((key, value) -> {
            boolean allTrue=true;
                        for (Object object : value) {
                            allTrue = (boolean)object;
                            if(!allTrue){ //stop if you found a false in the true/false array
                                break;
                            }
                        }//out of the inner iteration
                        if(allTrue){//if this variable is true, it means the above iteration had all values true
                            //do your stuff
                            break;
                        }
                        allTrue=true; //reset
            });
</code>```

Body:
i have converted my hashmap to json as i dont know what itt looks like in java

so my hashmap looks like

{"1":[true,false],
"2":[true,true],
"3":[true]}

i need to get the first occurance of all true in the array list in a single key

in this case its 2 is the 1st occurance

so if there is an occurance   ///do something   else //do somethig else

   hm.forEach((key, value) -> {

            for (Object object : value) {

                   boolean b = (boolean)object;
                   if(!b){
                   break;
                    }else{
                       System.out.println(key+"->"+b);
                   }

            }
});

i tried something like this but im getting lost in the mix  here its testing alotall the cases

any help would be greatly appreciated

Body:
try the snippet below.

hm.forEach((key, value) -> {
            boolean allTrue=true;
                        for (Object object : value) {
                            allTrue = (boolean)object;
                            if(!allTrue){ //stop if you found a false in the true/false array
                                break;
                            }
                        }//out of the inner iteration
                        if(allTrue){//if this variable is true, it means the above iteration had all values true
                            //do your stuff
                            break;
                        }
                        allTrue=true; //reset
            });


问:
Setting up development environment for OpenBTS
I want to make some little changes in OpenBTS code and use it. Currently I am following this process

Make some changes in code. ( Can't do testing of these changes at runtime)

Build the packages

Install the packages

Setup or Run OpenBTS

Test the behavior of OpenBTS to see that those changes are reflected or not.

If not working, goto step 1

This a quite hectic process, is there any smarter way to do it. Like OpenBTS is directly run from code, rather than packages installed on Ubuntu. If I make change in code, and they are directly reflected in my setup. How i can setup this dev environment.

答:
This answer is a bit late, I have just started to work on this my self. I don't bother installing the packages each time. My cycle is more like this:

Build the packages

Setup/run the database scripts (init the databases)

Install the packages that I don't need to re-build

Run each package manually (from the open BTS folders), e.g. run ../Transceiver, ../sipauthserver, ../OpenBTS, ../OpenBTSCLI ...etc...

Then when I want to make a code change - I do:

Stop everything

Code change

Re-build (e.g. just openBTS)

Re-run everything as before.

I also scripted the startup / stop sequences to make this faster (open/run each app in new terminals)


问:
How to add claims to the HttpContext User on sign in
This post may be long, but will have all the pertinent detail required for an answer.

I have been searching, and found that many others have as well, for the proper methodology to add claims to the HttpContext User so that those claims can be retrieved when needed, using Razor, in a view.

For example,

In the default Asp.Net Core 2.0 web application, the _LoginPartial has code that displays the users email. If I wanted to change that to the users full name (this assumes the registration process includes the first and last name entries, with the appropriate changes to the ApplicationUser class)

```<code> // Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime DateOfBirth { get; set; }

    public Gender Gender { get; set; }
    ...balance of code removed for brevity
}
</code>```

I would want to add a claim on the User for their full name and gender to use instead of the UserManager method currently employed in the default app. (And others down the road)

Current default wep app code

```<code>@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
            </li>
            <li>
                <button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
            </li>
        </ul>
    </form>
}
else
{
...code removed for brevity
}
</code>```

What I am hoping to accomplish;
Replacing this,

```<code><a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</code>```

with this

```<code><a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @((ClaimsIdentity) User.Identity).GetSpecificClaim("avatarUrl")!</a>
</code>```

Note: GetSpecificClaim is an extension method to retrieve the claim.

I believe the best place to add the claims would be in the login method.

```<code> public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
         if (!ModelState.IsValid) return View(model);
        // Now model is valid, require the user to have a confirmed email before they can log on.
        var user = await _userManager.FindByEmailAsync(model.Email);
        if (user != null)
        {
            if (!await _userManager.IsEmailConfirmedAsync(user))
            {
                ModelState.AddModelError(string.Empty,
                    "You must have a confirmed email to log in.");
                return View(model);
            }
        }
        else
        {
            ModelState.AddModelError(string.Empty,
                "There is no registered account for the email address supplied.");
            return View(model);
        }

        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in.");

            // Add claims to signed in user
            var userClaims = HttpContext.User.Claims.ToList();
            userClaims.Add(new Claim("fullname", user.GetFullName(user.UserName)));
            userClaims.Add(new Claim("avatarUrl", user.AvatarUrl));

           // Using ClaimsTransformer
           // Add claims here for the logged in user using AddUserInfoClaimsAsync extension method
            **var ct = new ClaimsHelpers.ClaimsTransformer();
            var identityWithInfoClaims = await ct.AddUserInfoClaimsAsync(User, user);**

            return RedirectToLocal(returnUrl);
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToAction(nameof(LoginWith2Fa), new { returnUrl, model.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToAction(nameof(Lockout));
        }

        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        return View(model);
    }
</code>```

But the userClaims variable is always empty

Questions:

Why is the claims list empty when the claims were just set?

Is there a different type of claim for identity?

Is there a better method for doing this?

UPDATE:
  I had put a ClaimsTransformer together on some earlier attempts, I can get claims added using that (see the change above in bold in the login controller code) but what do I now do with the ClaimsPrincipal variable identityWithinfoClaims? I can't set User equal to it because User is readonly so how does that object with the claims added get used appropriately?

答:
To add or transform custom claims, implement and use a custom ClaimsAuthenticationManager. How To: Transform Incoming Claims.

```<code>public class ClaimsTransformationModule : ClaimsAuthenticationManager {
    public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal) {
        if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated == true) {
           var identity = (ClaimsIdentity)incomingPrincipal.Identity;
           var user = GetUserData(identity);

           identity.AddClaim(new Claim("fullname", user.GetFullName(user.UserName)));
           identity.AddClaim(new Claim("avatarUrl", user.AvatarUrl));
        }

        return incomingPrincipal;
    }
}
</code>```

Here, GetUserData() retrieves the User entity from the DB, given the user name.

Register this transformer in the web.config:

```<code><system.identityModel>
   <identityConfiguration>
      <claimsAuthenticationManager type="MyProject.ClaimsTransformationModule , MyProject, Version=1.0.0.0, Culture=neutral" />
   </identityConfiguration>
</system.identityModel>
</code>```

Body:
This post may be long, but will have all the pertinent detail required for an answer.

I have been searching, and found that many others have as well, for the proper methodology to add claims to the HttpContext User so that those claims can be retrieved when needed, using Razor, in a view.

For example,

In the default Asp.Net Core 2.0 web application, the _LoginPartial has code that displays the users email. If I wanted to change that to the users full name (this assumes the registration process includes the first and last name entries, with the appropriate changes to the ApplicationUser class)

 // Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime DateOfBirth { get; set; }

    public Gender Gender { get; set; }
    ...balance of code removed for brevity
}

I would want to add a claim on the User for their full name and gender to use instead of the UserManager method currently employed in the default app. (And others down the road)

Current default wep app code

@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">

                Hello @UserManager.GetUserName(User)!

                <button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>

    </form>
}
else
{
...code removed for brevity
}

What I am hoping to accomplish;
Replacing this,

Hello @UserManager.GetUserName(User)!

with this

Hello @((ClaimsIdentity) User.Identity).GetSpecificClaim("avatarUrl")!

Note: GetSpecificClaim is an extension method to retrieve the claim.

I believe the best place to add the claims would be in the login method.

 public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
         if (!ModelState.IsValid) return View(model);
        // Now model is valid, require the user to have a confirmed email before they can log on.
        var user = await _userManager.FindByEmailAsync(model.Email);
        if (user != null)
        {
            if (!await _userManager.IsEmailConfirmedAsync(user))
            {
                ModelState.AddModelError(string.Empty,
                    "You must have a confirmed email to log in.");
                return View(model);
            }
        }
        else
        {
            ModelState.AddModelError(string.Empty,
                "There is no registered account for the email address supplied.");
            return View(model);
        }

        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in.");

            // Add claims to signed in user
            var userClaims = HttpContext.User.Claims.ToList();
            userClaims.Add(new Claim("fullname", user.GetFullName(user.UserName)));
            userClaims.Add(new Claim("avatarUrl", user.AvatarUrl));

           // Using ClaimsTransformer
           // Add claims here for the logged in user using AddUserInfoClaimsAsync extension method
            **var ct = new ClaimsHelpers.ClaimsTransformer();
            var identityWithInfoClaims = await ct.AddUserInfoClaimsAsync(User, user);**

            return RedirectToLocal(returnUrl);
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToAction(nameof(LoginWith2Fa), new { returnUrl, model.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToAction(nameof(Lockout));
        }

        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        return View(model);
    }

But the userClaims variable is always empty

Questions:

Why is the claims list empty when the claims were just set?

Is there a different type of claim for identity?

Is there a better method for doing this?

UPDATE:
  I had put a ClaimsTransformer together on some earlier attempts, I can get claims added using that (see the change above in bold in the login controller code) but what do I now do with the ClaimsPrincipal variable identityWithinfoClaims? I can't set User equal to it because User is readonly so how does that object with the claims added get used appropriately?

Body:
To add or transform custom claims, implement and use a custom ClaimsAuthenticationManager. How To: Transform Incoming Claims.

public class ClaimsTransformationModule : ClaimsAuthenticationManager {
    public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal) {
        if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated == true) {
           var identity = (ClaimsIdentity)incomingPrincipal.Identity;
           var user = GetUserData(identity);

           identity.AddClaim(new Claim("fullname", user.GetFullName(user.UserName)));
           identity.AddClaim(new Claim("avatarUrl", user.AvatarUrl));
        }

        return incomingPrincipal;
    }
}

Here, GetUserData() retrieves the User entity from the DB, given the user name.

Register this transformer in the web.config:

<system.identityModel>
   <identityConfiguration>
      <claimsAuthenticationManager type="MyProject.ClaimsTransformationModule , MyProject, Version=1.0.0.0, Culture=neutral" />
   </identityConfiguration>
</system.identityModel>


问:
Powershell using Regex finding a string within a string
Need help using regex and powershell to accomplish the following.
I have the following example string:

```<code><INPUT TYPE="hidden" NAME="site2pstoretoken" VALUE="v1.2~04C40A77~23"\><INPUT TYPE="hidden" NAME="p_error_code" VALUE="">
</code>```

The only thing I want to extract from this example string is the hash stored in VALUE.
The hash is very long so I need to catch everything between VALUE=" ....HASH.... "\>

How will the regex look like?

答:
Try this one with warning, that parsing html with regexes is bad idea:

```<code>$regex = [regex]'(?<=VALUE=")[^"]*'
$regex.Match('te2pstoretoken" VALUE="v1.2~04C40A77~23"\><INP').Value
</code>```

Edit:
And this code works as well:

```<code>if ('te2pstoretoken" VALUE="v1.2~04C40A77~23"\><INP' -match '(?<=VALUE=")[^"]*') {
   $matches[0]
}
</code>```

Body:
Need help using regex and powershell to accomplish the following.
I have the following example string:

<INPUT TYPE="hidden" NAME="site2pstoretoken" VALUE="v1.2~04C40A77~23"\><INPUT TYPE="hidden" NAME="p_error_code" VALUE="">

The only thing I want to extract from this example string is the hash stored in VALUE.
The hash is very long so I need to catch everything between VALUE=" ....HASH.... "\>

How will the regex look like?

Body:
Try this one with warning, that parsing html with regexes is bad idea:

$regex = [regex]'(?<=VALUE=")[^"]*'
$regex.Match('te2pstoretoken" VALUE="v1.2~04C40A77~23"\><INP').Value

Edit:
And this code works as well:

if ('te2pstoretoken" VALUE="v1.2~04C40A77~23"\><INP' -match '(?<=VALUE=")[^"]*') {
   $matches[0]
}


问:
convert json string to hashmap in java using collector
i am having string in form of [{"roll":1,"name":"Alok"},{"roll":2,"name":"Ayush kumar"}]  want to convert it in hashmap. I have tried HashMap<String, String> map = (HashMap<String, String>) Arrays.asList(emp.split(",")).stream().map(s -> s.split(":")).collect(Collectors.toMap(e -> e[0], e -> e[1]));
  But getting error Duplicate key "Ayush kumar"}] with root cause

答:
Assuming you're using Jackson, your JSON can be parsed like this:

```<code>String input = "[{\"roll\":1,\"name\":\"Alok\"},{\"roll\":2,\"name\":\"Ayush kumar\"}]";

ObjectMapper om = new ObjectMapper();
List<Map<String, String>> list = om.readValue(input, List.class);
</code>```

Note that your JSON is actually a list of objects (ie. maps), so you need to deserialize to a List instance. Go through the list and join the maps to get a single map.

Body:
Assuming you're using Jackson, your JSON can be parsed like this:

String input = "[{\"roll\":1,\"name\":\"Alok\"},{\"roll\":2,\"name\":\"Ayush kumar\"}]";

ObjectMapper om = new ObjectMapper();
List<Map<String, String>> list = om.readValue(input, List.class);

Note that your JSON is actually a list of objects (ie. maps), so you need to deserialize to a List instance. Go through the list and join the maps to get a single map.


问:
JUnit 5 TestTemplates and Extensions: Accessing TestTemplateInvocationContext?
Use case:

A test shall be executed with different parameters.

For this test we want to use an extension doing some pre-/postprocessing. This step needs access to the current set parameter.

Initially I tried implementing this with a @ParameterizedTest. Here the extension has no chance to access the parameter (The parameter is evaluated after the beforeTestExecution call). As a matter of this I used @TemplateTest with TestTemplateInvocationContextProvider (as described in the guide). Now I could see my parameters in the extensionContext. Unfortunately there are accessor methods missing for that:

on MethodExtensionContext (resp. super class): getTestDescriptor() : TestTemplateInvocationTestDescriptor

on TestTemplateInvocationTestDescriptor: getInvocationContext()

As a hopefully temporary workaround I do some reflection to access my invocationContext.
Is there something that tells against introducing these accessor methods? Is there even a better / simpler way for doing this?

答:
This would mean that I have to one extension to the other. Currently I have two extensions: One (MyProvider) implementing TestTemplateInvocationContextProvider (used for test parametrization) and one (MyCallback) implementing BeforeTestExecutionCallback for doing some preparation work.

This looks like:

```<code>  @ExtendWith(MyCallback.class)
  public class WebTest {
    @TestTemplate
    @ExtendWith(MyProvider.class)
    public void showPage() throws Exception {
    }
  }
</code>```

My goal would be getting the current parameter in the class level extension:

```<code>  public class MyCallback implements BeforeAllCallback, BeforeTestExecutionCallback {
  public void beforeAll(ExtensionContext ctx) {
  }
  public void beforeTestExecution(ExtensionContext ctx) {
    // HERE I WANT CURRENT PARAMETER VALUE:
    ((TestTemplateInvocationTestDescriptor) ((MethodExtensionContext) ctx).testDescriptor).invocationContext;
  }
</code>```

If I had two public methods added (as mentioned in first edit) it would be possible but maybe it is against the concept?

Body:
This would mean that I have to one extension to the other. Currently I have two extensions: One (MyProvider) implementing TestTemplateInvocationContextProvider (used for test parametrization) and one (MyCallback) implementing BeforeTestExecutionCallback for doing some preparation work.

This looks like:

  @ExtendWith(MyCallback.class)
  public class WebTest {
    @TestTemplate
    @ExtendWith(MyProvider.class)
    public void showPage() throws Exception {
    }
  }

My goal would be getting the current parameter in the class level extension:

  public class MyCallback implements BeforeAllCallback, BeforeTestExecutionCallback {
  public void beforeAll(ExtensionContext ctx) {
  }
  public void beforeTestExecution(ExtensionContext ctx) {
    // HERE I WANT CURRENT PARAMETER VALUE:
    ((TestTemplateInvocationTestDescriptor) ((MethodExtensionContext) ctx).testDescriptor).invocationContext;
  }

If I had two public methods added (as mentioned in first edit) it would be possible but maybe it is against the concept?


问:
Hide code in Jupyter Notebook presentation
I have a jupyter notebook that is a mixture of markdown and code.  In the end I want to render it out as a pdf report and hide the code.  I still want to see the output of the code, the plots and tables, I just don't want to see the code in the final report.  I found the post below that has the code below, which if added to the notebook creates a toggle button that can be used to hide or display the input code.  The problem with that is I wind up with a toggle button at the top of my report.  Does anyone know how to do this?

Post:

http://chris-said.io/2016/02/13/how-to-make-polished-jupyter-presentations-with-optional-code-visibility/

Code:

```<code><script>
  function code_toggle() {
    if (code_shown){
      $('div.input').hide('500');
      $('#toggleButton').val('Show Code')
    } else {
      $('div.input').show('500');
      $('#toggleButton').val('Hide Code')
    }
    code_shown = !code_shown
  }

  $( document ).ready(function(){
    code_shown=false;
    $('div.input').hide()
  });
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form>
</code>```

答:
You can easily achieve what you want by creating a custom nbconvert template. This means that your live notebook can still have the input visible but that when you convert to pdf it hides the input.

Create a template file that extends the standard latex template article.tplx (latex template is used for pdf convert too)

custom.tplx:

```<code>% Inherit from the article.tplx
((* extends 'article.tplx' *))

% remove inputs
((* block input_group *))
((* endblock input_group *))
</code>```

Then convert your notebook using the following command

jupyter nbconvert --template=custom.tplx --to=pdf your_notebook.ipynb

Here's the docs on using custom templates: http://nbconvert.readthedocs.io/en/latest/customizing.html#Custom-Templates

ContentLicense: CC BY-SA 4.0

Body:
I have a jupyter notebook that is a mixture of markdown and code.  In the end I want to render it out as a pdf report and hide the code.  I still want to see the output of the code, the plots and tables, I just don't want to see the code in the final report.  I found the post below that has the code below, which if added to the notebook creates a toggle button that can be used to hide or display the input code.  The problem with that is I wind up with a toggle button at the top of my report.  Does anyone know how to do this?

Post:

http://chris-said.io/2016/02/13/how-to-make-polished-jupyter-presentations-with-optional-code-visibility/

Code:

<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form>

Body:
You can easily achieve what you want by creating a custom nbconvert template. This means that your live notebook can still have the input visible but that when you convert to pdf it hides the input.

Create a template file that extends the standard latex template article.tplx (latex template is used for pdf convert too)

custom.tplx:

% Inherit from the article.tplx
((* extends 'article.tplx' *))

% remove inputs
((* block input_group *))
((* endblock input_group *))

Then convert your notebook using the following command

jupyter nbconvert --template=custom.tplx --to=pdf your_notebook.ipynb

Here's the docs on using custom templates: http://nbconvert.readthedocs.io/en/latest/customizing.html#Custom-Templates


问:
Should I test (duplicate) data, or only the behavior?
From the design perspective, I am wondering should I test the data, especially if it's a generally known data (not something very configurable) - this can apply to things like popular file extensions, special IP addresses etc.

Suppose we have a emergency phone number classifier:

```<code>public class ContactClassifier {

    public final static String EMERGENCY_PHONE_NUMBER = "911";

    public boolean isEmergencyNumber(String number) {
        return number.equals(EMERGENCY_PHONE_NUMBER);
    }
}
</code>```

Should I test it this way ("911" duplication):

```<code>@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber("911"));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}
</code>```

or (test if properly recognized "configured" number):

```<code>@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber(ContactClassifier.EMERGENCY_PHONE_NUMBER));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}
</code>```

or inject "911" in the constructor,which looks the most reasonable for me, but even if I do so - should I wrote a test for the "application glue" if the component was instantiated with proper value? If someone can do a typo in data (code), then I see no reasons someone can do a typo in tests case (I bet such data would be copy-paste)

答:
I'd opt for

```<code>@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber("911"));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}
</code>```

as this doesn't test against something from the class under test that might be faulty. Testing with

```<code>@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber(ContactClassifier.EMERGENCY_PHONE_NUMBER));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}
</code>```

will never catch if someone introduces a typo into ContactClassifier.EMERGENCY_PHONE_NUMBER.

Body:
From the design perspective, I am wondering should I test the data, especially if it's a generally known data (not something very configurable) - this can apply to things like popular file extensions, special IP addresses etc.

Suppose we have a emergency phone number classifier:

public class ContactClassifier {

    public final static String EMERGENCY_PHONE_NUMBER = "911";

    public boolean isEmergencyNumber(String number) {
        return number.equals(EMERGENCY_PHONE_NUMBER);
    }
}

Should I test it this way ("911" duplication):

@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber("911"));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}

or (test if properly recognized "configured" number):

@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber(ContactClassifier.EMERGENCY_PHONE_NUMBER));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}

or inject "911" in the constructor,which looks the most reasonable for me, but even if I do so - should I wrote a test for the "application glue" if the component was instantiated with proper value? If someone can do a typo in data (code), then I see no reasons someone can do a typo in tests case (I bet such data would be copy-paste)

Body:
I'd opt for

@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber("911"));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}

as this doesn't test against something from the class under test that might be faulty. Testing with

@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber(ContactClassifier.EMERGENCY_PHONE_NUMBER));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}

will never catch if someone introduces a typo into ContactClassifier.EMERGENCY_PHONE_NUMBER.


问:
catch IndexOutOfBoundsException Exception
I'm trying to catch made up IndexOutOfBoundsException  error in catch block. But every time its returning -1 and not going into catch block

May I know please why its happening ? I want to reach to catch block.

```<code>  public class Mars {

    public int Setname(String Input) {

        int output = 0;

        try {
            output = Input.indexOf("L");
            System.out.println("Error:" + Input.indexOf("L"));

            if (output == -1){

                throw new IndexOutOfBoundsException();
            }

        }

        catch (IndexOutOfBoundsException e) {

            System.out.println("Error:2" + e.getStackTrace());
        }

        return output;

    }

    public static void main(String[] args) {

        Mars O = new Mars();
        O.Setname("London");

    }

}
</code>```

Second thing is: When we write IndexOutOfBoundsException e in catch block, its creating an instance of IndexOutOfBoundsException class ?Am I right ?

So why we can't write like in below manner ? It could be a really silly question, but just for curiosity I want to know.

```<code>catch(IndexOutOfBoundsException e = new IndexOutOfBoundsException())
</code>```

答:
Method indexOf() of String doesn't throw any exception. In fact, it returns -1 if the char you're looking for isn't in the String

Here you can check it

If you need to throw the exception, you must do something like Ayo K suggested

Body:
I'm trying to catch made up IndexOutOfBoundsException  error in catch block. But every time its returning -1 and not going into catch block

May I know please why its happening ? I want to reach to catch block.

  public class Mars {

    public int Setname(String Input) {

        int output = 0;

        try {
            output = Input.indexOf("L");
            System.out.println("Error:" + Input.indexOf("L"));

            if (output == -1){

                throw new IndexOutOfBoundsException();
            }

        }

        catch (IndexOutOfBoundsException e) {

            System.out.println("Error:2" + e.getStackTrace());
        }

        return output;

    }

    public static void main(String[] args) {

        Mars O = new Mars();
        O.Setname("London");

    }

}

Second thing is: When we write IndexOutOfBoundsException e in catch block, its creating an instance of IndexOutOfBoundsException class ?Am I right ?

So why we can't write like in below manner ? It could be a really silly question, but just for curiosity I want to know.

catch(IndexOutOfBoundsException e = new IndexOutOfBoundsException())


问:
how to "sort" polygons 3d?
I am still working on my "javascript 3d engine" (link inside stackoverflow).
at First, all my polygons were faces of cubes, so sorting them by average Z was working fine.
but now I've "evolved" and I want to draw my polygons (which may contain more than 4 vertices)
in the right order, namely, those who are close to the camera will be drawn last.

basically,
I know how to rotate them and "perspective"-ize them into 2D,
but don't know how to draw them in the right order.

just to clarify:

```<code>//my 3d shape = array of polygons
//polygon = array of vertices
//vertex = point with x,y,z
//rotation is around (0,0,0) and my view point is (0,0,something) I guess.
</code>```

can anyone help?

p.s: some "catch phrases" I came up with, looking for the solution: z-buffering, ray casting (?!), plane equations, view vector, and so on - guess I need a simple to understand answer so that's why I asked this one. thanks.

p.s2: i don't mind too much about overlapping or intersecting polygons... so maybe the painter's algorthm indeed might be good. but: what is it exactly? how do I decide the distance of a polygon?? a polygon has many points.

答:
how do I decide the distance of a polygon?? a polygon has many points.

Painter's algorithm is the simplest to implement, but it works only in very simple cases because it assumes that there is only a single "distance" or z-value for each polygon (which you could approximate to be the average of z-values of all points in the polygon). Of course, this will produce wrong results if two polygons intersect each other.

In reality, there isn't a single distance value for a polygon -- each point on the surface of a polygon can be at a different distance from the viewer, so each point has its own "distance" or depth.

You already mentioned Z-buffering, and that is one way of doing this. I don't think you can implement this efficiently on a HTML canvas, but here's the general idea:

You need to maintain an additional canvas, the "z-buffer", where each pixel's colour represents the z-depth of the corresponding pixel on the main canvas.

To draw a polygon, you go through each point on its surface and draw only those points which are closer to the viewer than any previous objects, as indicated by the z-buffer.

Title: how to "sort" polygons 3d?

Body:
I am still working on my "javascript 3d engine" (link inside stackoverflow).
at First, all my polygons were faces of cubes, so sorting them by average Z was working fine.
but now I've "evolved" and I want to draw my polygons (which may contain more than 4 vertices)
in the right order, namely, those who are close to the camera will be drawn last.

basically,
I know how to rotate them and "perspective"-ize them into 2D,
but don't know how to draw them in the right order.

just to clarify:

//my 3d shape = array of polygons
//polygon = array of vertices
//vertex = point with x,y,z
//rotation is around (0,0,0) and my view point is (0,0,something) I guess.

can anyone help?

p.s: some "catch phrases" I came up with, looking for the solution: z-buffering, ray casting (?!), plane equations, view vector, and so on - guess I need a simple to understand answer so that's why I asked this one. thanks.

p.s2: i don't mind too much about overlapping or intersecting polygons... so maybe the painter's algorthm indeed might be good. but: what is it exactly? how do I decide the distance of a polygon?? a polygon has many points.


问:
JSONException : at jsonData of type java.lang.String cannot be converted to JSONArray
As title said I'm new to JSON and I can't get out of my problem. I'm working on this error for 1 week I'm really desperate to get out.

My error :

```<code>JSONException: Value [{"data":"11-13-2017","numeVanzator":"Clau","numarClient":0}] at jsonData of type java.lang.String cannot be converted to JSONArray
</code>```

My JSON:

```<code>{
 "jsonData" : {
    "11-13-2017" : {
      "Clau" : {
        "-KyokKjL9UQpsfKZYZqM" : [ {
          "pret" : "80",
          "produs" : "Shirt",
          "produsId" : "-Kyok58s0dOAnVOnbJPk"
        } ]
      }
    }
  }
}
</code>```

I looked over tutorials on StackOverFlow but absolutely no solution.

My code :

```<code> private void writeJSON(String metodaPlata) throws JSONException {
    String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
    String jsonDataFromShared = SharedPreference.getString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");

    int totalPrice = 0;
    for(VanzatorProduse v : Util.getInstance().getVanzatorProduse())
    {
        int vPrice = Integer.parseInt(v.getPret());
        totalPrice = totalPrice + vPrice;

    }
    String pretTotal = Integer.toString(totalPrice);
    String produseSelectate = Integer.toString(listaProdusePreview.getAdapter().getCount());

    JSONObject jsonData;
    JSONArray dateJSON;
    JSONObject obj;
    JSONArray arrayForList;

    if (jsonDataFromShared.equals("")) {

        jsonData = new JSONObject();
        dateJSON = new JSONArray();
        obj = new JSONObject();
        arrayForList = new JSONArray();

        JSONObject objListaSiModalitate = new JSONObject();

        //       arrayForList.put(stock_list.toString());

        objListaSiModalitate.put("lista", new JSONArray(Util.getInstance().getVanzatorProduse()));
        objListaSiModalitate.put("metodaPlata", metodaPlata);

        obj.put("data", getDate(calendarData.getTimeInMillis()));
        obj.put("numeVanzator", numeVanzator);
        obj.put("numarClient", numarVanzare);

        dateJSON.put(obj);
        jsonData.put("jsonData", dateJSON.toString());

        SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());

    } else {

        jsonData = new JSONObject(jsonDataFromShared);
        dateJSON = jsonData.getJSONArray("jsonData");

        obj = new JSONObject();

        JSONObject objListaSiModalitate = new JSONObject();
        objListaSiModalitate.put("metodaPlata", metodaPlata);
        obj.put("produseSelectate", produseSelectate);
        obj.put("sumaProduse", pretTotal);
        obj.put("data", getDate(calendarData.getTimeInMillis()));
        obj.put("numeVanzator", numeVanzator);
        obj.put("numarClient", numarVanzare);

        dateJSON.put(obj);

        jsonData.put("jsonData", dateJSON);

        System.out.println("jsonData" + dateJSON);
        SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());

    }
}
</code>```

Please help me I have no idea what to idea even if I look over tutorials.

答:
I think your json parsing will be,</p>

```<code>try {
            JSONObject jsonObject = new JSONObject("jsonData");
            JSONObject jsonObject1 = jsonObject.getJSONObject("11-13-2017");
            JSONObject jsonObject2 = jsonObject1.getJSONObject("Clau");
            JSONArray jsonArray = jsonObject2.getJSONArray("-KyokKjL9UQpsfKZYZqM");
            JSONObject jsonObject3 = (JSONObject) jsonArray.getJSONObject(0);
            String string = jsonObject3.getString("pret");
            String string1 = jsonObject3.getString("produs");
            String string2 = jsonObject3.getString("produsId");
        } catch (JSONException e) {
            e.printStackTrace();
        }
</code>```

Body:
As title said I'm new to JSON and I can't get out of my problem. I'm working on this error for 1 week I'm really desperate to get out.

My error :

JSONException: Value [{"data":"11-13-2017","numeVanzator":"Clau","numarClient":0}] at jsonData of type java.lang.String cannot be converted to JSONArray

My JSON:

{
 "jsonData" : {
    "11-13-2017" : {
      "Clau" : {
        "-KyokKjL9UQpsfKZYZqM" : [ {
          "pret" : "80",
          "produs" : "Shirt",
          "produsId" : "-Kyok58s0dOAnVOnbJPk"
        } ]
      }
    }
  }
}

I looked over tutorials on StackOverFlow but absolutely no solution.

My code :

 private void writeJSON(String metodaPlata) throws JSONException {
    String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
    String jsonDataFromShared = SharedPreference.getString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");

    int totalPrice = 0;
    for(VanzatorProduse v : Util.getInstance().getVanzatorProduse())
    {
        int vPrice = Integer.parseInt(v.getPret());
        totalPrice = totalPrice + vPrice;

    }
    String pretTotal = Integer.toString(totalPrice);
    String produseSelectate = Integer.toString(listaProdusePreview.getAdapter().getCount());

    JSONObject jsonData;
    JSONArray dateJSON;
    JSONObject obj;
    JSONArray arrayForList;

    if (jsonDataFromShared.equals("")) {

        jsonData = new JSONObject();
        dateJSON = new JSONArray();
        obj = new JSONObject();
        arrayForList = new JSONArray();

        JSONObject objListaSiModalitate = new JSONObject();

        //       arrayForList.put(stock_list.toString());

        objListaSiModalitate.put("lista", new JSONArray(Util.getInstance().getVanzatorProduse()));
        objListaSiModalitate.put("metodaPlata", metodaPlata);

        obj.put("data", getDate(calendarData.getTimeInMillis()));
        obj.put("numeVanzator", numeVanzator);
        obj.put("numarClient", numarVanzare);

        dateJSON.put(obj);
        jsonData.put("jsonData", dateJSON.toString());

        SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());

    } else {

        jsonData = new JSONObject(jsonDataFromShared);
        dateJSON = jsonData.getJSONArray("jsonData");

        obj = new JSONObject();

        JSONObject objListaSiModalitate = new JSONObject();
        objListaSiModalitate.put("metodaPlata", metodaPlata);
        obj.put("produseSelectate", produseSelectate);
        obj.put("sumaProduse", pretTotal);
        obj.put("data", getDate(calendarData.getTimeInMillis()));
        obj.put("numeVanzator", numeVanzator);
        obj.put("numarClient", numarVanzare);

        dateJSON.put(obj);

        jsonData.put("jsonData", dateJSON);

        System.out.println("jsonData" + dateJSON);
        SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());

    }
}

Please help me I have no idea what to idea even if I look over tutorials.

Body:
I think your json parsing will be,

try {
            JSONObject jsonObject = new JSONObject("jsonData");
            JSONObject jsonObject1 = jsonObject.getJSONObject("11-13-2017");
            JSONObject jsonObject2 = jsonObject1.getJSONObject("Clau");
            JSONArray jsonArray = jsonObject2.getJSONArray("-KyokKjL9UQpsfKZYZqM");
            JSONObject jsonObject3 = (JSONObject) jsonArray.getJSONObject(0);
            String string = jsonObject3.getString("pret");
            String string1 = jsonObject3.getString("produs");
            String string2 = jsonObject3.getString("produsId");
        } catch (JSONException e) {
            e.printStackTrace();
        }


问:
PHP Iframes and Sessions
I have iframe which will be accessed from different domains.

Eg.

```<code>Iframe - www.iframe.com
Domain1 - www.domain1.com
Domain2 - www.domain2.com`
</code>```

Both domain will access iframe with
 different userid

Problem is when i access the domain1 the same session is being used in domain2. But i don't want to use the same because both domains will be having different userid.

How to fix this?

答:
I'm not sure what you aim, but i'll edit the answer if you give more details.
Let's say...

DOMAIN 1 index.php

```<code><?php
// here you have a specific userid
$userid = "user1";
// when you load the iframe, you send userid as parameter
?>
<iframe src="www.iframe.com?userid=<?php echo $userid; ?>"></iframe>
</code>```

DOMAIN 2 index.php

```<code><?php
// the same thing, but different userid
$userid = "user2";
?>
<iframe src="www.iframe.com?userid=<?php echo $userid; ?>"></iframe>
</code>```

IFRAME index.php

```<code><?php
// start session
session_start();
//let's say you already have a defined user structure in the SESSION
if (!isset($_SESSION["users"])) {
  $_SESSION["users"] = array(
    "user1" => array("name" => "USER 1"),
    "user2" => array("name" => "USER 2")
  );
}
// now, you can check the userid from the GET parameters to select the correct session
$userid = false;
if (isset($_GET["userid"]))
  $userid = $_GET["userid"];
// check if user is valid
if ($userid && isset($_SESSION["users"][$userid])) {
  // userid is valid
  echo "Welcome ".$_SESSION["users"][$userid]["name"];
} else {
  // userid is not valid
  echo "Who are you, stranger?";
}
</code>```

Note: you have to make sure the users are logged in somehow (validate the user with a password, because anyone can change the GET parameters...)

Title: PHP Iframes and Sessions

Body:
I have iframe which will be accessed from different domains.

Eg.

Iframe - www.iframe.com
Domain1 - www.domain1.com
Domain2 - www.domain2.com`

Both domain will access iframe with
 different userid

Problem is when i access the domain1 the same session is being used in domain2. But i don't want to use the same because both domains will be having different userid.

How to fix this?

Body:
I'm not sure what you aim, but i'll edit the answer if you give more details.
Let's say...

DOMAIN 1 index.php

<?php
// here you have a specific userid
$userid = "user1";
// when you load the iframe, you send userid as parameter
?>
<iframe src="www.iframe.com?userid=<?php echo $userid; ?>"></iframe>

DOMAIN 2 index.php

<?php
// the same thing, but different userid
$userid = "user2";
?>
<iframe src="www.iframe.com?userid=<?php echo $userid; ?>"></iframe>

IFRAME index.php

<?php
// start session
session_start();
//let's say you already have a defined user structure in the SESSION
if (!isset($_SESSION["users"])) {
  $_SESSION["users"] = array(
    "user1" => array("name" => "USER 1"),
    "user2" => array("name" => "USER 2")
  );
}
// now, you can check the userid from the GET parameters to select the correct session
$userid = false;
if (isset($_GET["userid"]))
  $userid = $_GET["userid"];
// check if user is valid
if ($userid && isset($_SESSION["users"][$userid])) {
  // userid is valid
  echo "Welcome ".$_SESSION["users"][$userid]["name"];
} else {
  // userid is not valid
  echo "Who are you, stranger?";
}

Note: you have to make sure the users are logged in somehow (validate the user with a password, because anyone can change the GET parameters...)


问:
NodeJS Express - Global Unique Request Id
Is it possible to define a unique request Id that is included in each log statement without handing the logger to each method/function call?

Technologies in use: NodeJS, Express, Winston

答:
Edited

Finally, I have created a library that makes all the work.
https://github.com/davicente/express-logger-unique-req-id

It is a wrapper of Winston library, so you can use it the same way.

Let me know if it helps you

We had this same problem in several projects, and I couldn't finde any complete solution for this question. We are using same technologies (Node.js, Express.js and Winston for logs)
I found a solution to this using a couple of libraries and wrapping Winston library:
- node-uuid for creating unique identificators for each request
- continuation-local-storage for sharing this IDs among different modules without sending req object in all the calls.

First I need to create and set the unique identificator with each request. I do it in the middleware:

```<code>var uuid = require('node-uuid');
var createNamespace = require('continuation-local-storage').createNamespace;
var myRequest = createNamespace('my request');

// Run the context for each request. Assign a unique identifier to each request
app.use(function(req, res, next) {
    myRequest.run(function() {
        myRequest.set('reqId', uuid.v1());
        next();
    });
});
</code>```

After that I had to wrap Winston library, recovering the id from the context and adding to the message of the log:

```<code>var winston = require('winston');
var getNamespace = require('continuation-local-storage').getNamespace;

// Wrap Winston logger to print reqId in each log
var formatMessage = function(message) {
    var myRequest = getNamespace('my request');
    message = myRequest && myRequest.get('reqId') ? message + " reqId: " + myRequest.get('reqId') : message;
    return message;
};

var logger = {
    log: function(level, message) {
        winstonLogger.log(level, formatMessage(message));
    },
    error: function(message) {
        winstonLogger.error(formatMessage(message));
    },
    warn: function(message) {
        winstonLogger.warn(formatMessage(message));
    },
    verbose: function(message) {
        winstonLogger.verbose(formatMessage(message));
    },
    info: function(message) {
        winstonLogger.info(formatMessage(message));
    },
    debug: function(message) {
        winstonLogger.debug(formatMessage(message));
    },
    silly: function(message) {
        winstonLogger.silly(formatMessage(message));
    }
};
module.exports = logger;
</code>```

I think it was a little bit complex, so I decided to write it down in a post. You can get more information from there: Express.js: Logging info with global unique request ID – Node.js

I hope this helps with your problem.

Body:
Edited

Finally, I have created a library that makes all the work.
https://github.com/davicente/express-logger-unique-req-id

It is a wrapper of Winston library, so you can use it the same way.

Let me know if it helps you

We had this same problem in several projects, and I couldn't finde any complete solution for this question. We are using same technologies (Node.js, Express.js and Winston for logs)
I found a solution to this using a couple of libraries and wrapping Winston library:
- node-uuid for creating unique identificators for each request
- continuation-local-storage for sharing this IDs among different modules without sending req object in all the calls.

First I need to create and set the unique identificator with each request. I do it in the middleware:

var uuid = require('node-uuid');
var createNamespace = require('continuation-local-storage').createNamespace;
var myRequest = createNamespace('my request');

// Run the context for each request. Assign a unique identifier to each request
app.use(function(req, res, next) {
    myRequest.run(function() {
        myRequest.set('reqId', uuid.v1());
        next();
    });
});

After that I had to wrap Winston library, recovering the id from the context and adding to the message of the log:

var winston = require('winston');
var getNamespace = require('continuation-local-storage').getNamespace;

// Wrap Winston logger to print reqId in each log
var formatMessage = function(message) {
    var myRequest = getNamespace('my request');
    message = myRequest && myRequest.get('reqId') ? message + " reqId: " + myRequest.get('reqId') : message;
    return message;
};

var logger = {
    log: function(level, message) {
        winstonLogger.log(level, formatMessage(message));
    },
    error: function(message) {
        winstonLogger.error(formatMessage(message));
    },
    warn: function(message) {
        winstonLogger.warn(formatMessage(message));
    },
    verbose: function(message) {
        winstonLogger.verbose(formatMessage(message));
    },
    info: function(message) {
        winstonLogger.info(formatMessage(message));
    },
    debug: function(message) {
        winstonLogger.debug(formatMessage(message));
    },
    silly: function(message) {
        winstonLogger.silly(formatMessage(message));
    }
};
module.exports = logger;

I think it was a little bit complex, so I decided to write it down in a post. You can get more information from there: Express.js: Logging info with global unique request ID – Node.js

I hope this helps with your problem.


问:
combining datasets in R: for each value in two datasets, create a new row in third dataset
I've been thinking really hard on this problem, and it can be boiled down to this:

I have the following two vectors (actually columns in two different dataframes):

```<code> TIME <- 2000+1:3
 ID <- c("A", "B")
</code>```

And I want this output

```<code>  ID2 <- c("A", "A", "A", "B", "B", "B")
  TIME2 <- c(2000+1:3, 2000+1:3)
  data.frame(ID2, TIME2)
</code>```

The usual methods for combining datasets (I usually uses dplyr) assumes that there are shared values between the two datasets, or combines as seperate rows, and does not seem to fit the purpose.
I also looked into creating this from within a for loop. (appending a row for each unique value and time in ID2 into a new dataframe, but I couldn't figure it out, and it seems to me like I'm stuck in a wrong way of thinking about this.

I guess that one approach might be to  repeat each unique ID (length(TIME))-times into a vector, and cbind that with a vector of repeated TIME (length(unique(ID)).

Or maybe you have an elegant solution?

答:
Thanks to Ronak Shah and amrrs that both answered the question.
Both solutions works.</p>

```<code> expand.grid(TIME, ID)
 tidyr::crossing(TIME,ID)
</code>```

Body:
I've been thinking really hard on this problem, and it can be boiled down to this:

I have the following two vectors (actually columns in two different dataframes):

 TIME <- 2000+1:3
 ID <- c("A", "B")

And I want this output

  ID2 <- c("A", "A", "A", "B", "B", "B")
  TIME2 <- c(2000+1:3, 2000+1:3)
  data.frame(ID2, TIME2)

The usual methods for combining datasets (I usually uses dplyr) assumes that there are shared values between the two datasets, or combines as seperate rows, and does not seem to fit the purpose.
I also looked into creating this from within a for loop. (appending a row for each unique value and time in ID2 into a new dataframe, but I couldn't figure it out, and it seems to me like I'm stuck in a wrong way of thinking about this.

I guess that one approach might be to  repeat each unique ID (length(TIME))-times into a vector, and cbind that with a vector of repeated TIME (length(unique(ID)).

Or maybe you have an elegant solution?

Body:
Thanks to Ronak Shah and amrrs that both answered the question.
Both solutions works.

 expand.grid(TIME, ID)
 tidyr::crossing(TIME,ID)


问:
converting bytes array into long
I am trying to convert the following array to long number.

my expected results: 153008 ( I am not sure if it's decimal or hexa)

my actual results (what I am getting): 176

this is what I did, what am I doing wrong?

```<code>  byte bytesArray [] = { -80,85,2,0,0,0,0,0};

  long Num = (bytesArray[7] <<56 |
                bytesArray[6] & 0xFF << 48 |
                bytesArray[5] & 0xFF << 40 |
                bytesArray[4] & 0xFF << 32 |
                bytesArray[3] & 0xFF << 24 |
                bytesArray[2] & 0xFF << 16 |
                bytesArray[1] & 0xFF << 8 |
                bytesArray[0] & 0xFF << 0 );
</code>```

答:
Add brackets like this:

```<code>    long num = (bytesArray[7] << 56 |
                  (bytesArray[6] & 0xFF) << 48 |
                  (bytesArray[5] & 0xFF) << 40 |
                  (bytesArray[4] & 0xFF) << 32 |
                  (bytesArray[3] & 0xFF) << 24 |
                  (bytesArray[2] & 0xFF) << 16 |
                  (bytesArray[1] & 0xFF) << 8 |
                  (bytesArray[0] & 0xFF) << 0 );
</code>```

Otherwise you do << on 0xFF so it becomes really big, before you do bytesArray[x] & [large number] which always evaluates to 0.

Result 153008, hence success!

Title: converting bytes array into long

Body:
I am trying to convert the following array to long number.

my expected results: 153008 ( I am not sure if it's decimal or hexa)

my actual results (what I am getting): 176

this is what I did, what am I doing wrong?

  byte bytesArray [] = { -80,85,2,0,0,0,0,0};

  long Num = (bytesArray[7] <<56 |
                bytesArray[6] & 0xFF << 48 |
                bytesArray[5] & 0xFF << 40 |
                bytesArray[4] & 0xFF << 32 |
                bytesArray[3] & 0xFF << 24 |
                bytesArray[2] & 0xFF << 16 |
                bytesArray[1] & 0xFF << 8 |
                bytesArray[0] & 0xFF << 0 );

Body:
Add brackets like this:

    long num = (bytesArray[7] << 56 |
                  (bytesArray[6] & 0xFF) << 48 |
                  (bytesArray[5] & 0xFF) << 40 |
                  (bytesArray[4] & 0xFF) << 32 |
                  (bytesArray[3] & 0xFF) << 24 |
                  (bytesArray[2] & 0xFF) << 16 |
                  (bytesArray[1] & 0xFF) << 8 |
                  (bytesArray[0] & 0xFF) << 0 );

Otherwise you do << on 0xFF so it becomes really big, before you do bytesArray[x] & [large number] which always evaluates to 0.

Result 153008, hence success!