问:
Android -given a hexagon drawable how to put a number inside of it?
I have a hexagon jpg file that looks like this:

I would like to put a number of my choice inside the center of it.  so the final output would look something like this:

I want the number to be directly centered always.  Is there a way to do this with the shape tag in android xml ?  I also need to specify a width and height of the hexagon.  I dont think the shape tag will help here as i already have the shape defined. do you think my best bet is to use a button and write the number on it while keeping the hexagon as a background ?

答:
There are two main ways that I can think of you could use. Like you said, you could use a Button/TextView and set the background as the hexagon resource. As you said though, that requires inflating that view every time. The other way would be to use a Canvas and draw the number directly on the image, then put the image into an ImageView or other similar view. To draw on the image:

```<code>int fontSize = 200; //set your font size
Bitmap baseImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.hexagon); //load the hexagon image
Bitmap image = baseImage.copy(Bitmap.Config.ARGB_8888, true); //create mutable bitmap for canvas. see: http://stackoverflow.com/a/13119762/1896516

//the "paint" to use when drawing the text
Paint paint = new Paint(); //see here for all paint options: https://developer.android.com/reference/android/graphics/Paint.html
paint.setTextSize(fontSize); //sets your desired font size
paint.setColor(Color.BLACK); //set the desired color of the text
paint.setTextAlign(Paint.Align.CENTER); //set the alignment of the text

Canvas canvas = new Canvas(image); //create a canvas from the bitmap
canvas.drawText("#", image.getWidth()/2, image.getHeight()/2 + fontSize/4, paint); //draw the number onto the hexagon

ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(image);
</code>```

You may need to play with the text positioning depending on if your image has borders, etc. In addition, note that I haven't really tested these two against eachother for performance, so I'm not sure which one will be the most effecient way in the end. That said, the first way is likely easier to do as it will take care of positioning by itself. Hope this helps!

Body:
There are two main ways that I can think of you could use. Like you said, you could use a Button/TextView and set the background as the hexagon resource. As you said though, that requires inflating that view every time. The other way would be to use a Canvas and draw the number directly on the image, then put the image into an ImageView or other similar view. To draw on the image:

int fontSize = 200; //set your font size
Bitmap baseImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.hexagon); //load the hexagon image
Bitmap image = baseImage.copy(Bitmap.Config.ARGB_8888, true); //create mutable bitmap for canvas. see: http://stackoverflow.com/a/13119762/1896516

//the "paint" to use when drawing the text
Paint paint = new Paint(); //see here for all paint options: https://developer.android.com/reference/android/graphics/Paint.html
paint.setTextSize(fontSize); //sets your desired font size
paint.setColor(Color.BLACK); //set the desired color of the text
paint.setTextAlign(Paint.Align.CENTER); //set the alignment of the text

Canvas canvas = new Canvas(image); //create a canvas from the bitmap
canvas.drawText("#", image.getWidth()/2, image.getHeight()/2 + fontSize/4, paint); //draw the number onto the hexagon

ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(image);

You may need to play with the text positioning depending on if your image has borders, etc. In addition, note that I haven't really tested these two against eachother for performance, so I'm not sure which one will be the most effecient way in the end. That said, the first way is likely easier to do as it will take care of positioning by itself. Hope this helps!


来源: stackexchange

问:
jquery attributes from multiple elements
I am trying ot figure how to use jQuery to get the value of html attribute of many elements. My webpage updates dynamically using ajax. I have an attribute called number for in element in the part that is updated. I want to use the attribute value from each element so that i can use that data as parameters to a php file link. I have come across jquery's .attr() function, but it only seems to take the attribute value of the first element if finds. But what I want to do is get the attribute value for each element so that when I click on that element its corresponding attribute value is sent as parameters to the php file.

Thanks

答:
you can combine attr() with .each() method.

e.g.

```<code>$("div").each(function(){
     $(this).attr("number");
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
you can combine attr() with .each() method.

e.g.

$("div").each(function(){
     $(this).attr("number");
});


问:
EMR Hadoop processing whole S3 file
I have a bunch of small (1KB to 1MB) text files stored in Amazon S3 that I would like to process using Amazon EMR's Hadoop.

Each record given to the mapper needs to contain the entire contents of a text file as well as some way to determine the filename, so I cannot use the default TextInputFormat.

What is the best way to accomplish this? Is there anything else I can do (like copying files from S3 to hdfs) to increase performance?

答:
I had the same issue. Please refer following questions.

s3fs on Amazon EMR: Will it scale for approx 100million small files?

Write 100 million files to s3

Too many open files in EMR

If you don't have any large files, but have a lot of files, it's sufficient to use s3cmd get --recursive s3://<url> . command. After retrieved files into EMR instance, you could create tables with Hive. For example, you can load whole files with LOAD DATA statement with partition.

sample

This is a sample code

```<code>#!/bin/bash

s3cmd get --recursive s3://your.s3.name .

# create table with partitions
hive -e "SET mapred.input.dir.recursive=true; DROP TABLE IF EXISTS import_s3_data;"
hive -e "CREATE TABLE import_s3_data( rawdata string )
         PARTITIONED BY (tier1 string, tier2, string, tier3 string);"

LOAD_SQL=""

# collect files as array
FILES=(`find . -name \*.txt -print`)

for FILE in ${FILES[@]}
do
    DIR_INFO=(`echo ${FILE##./} | tr -s '/' ' '`)
    T1=${DIR_INFO[0]}
    T2=${DIR_INFO[1]}
    T3=${DIR_INFO[2]}
    LOAD_SQL="${LOAD_SQL} LOAD DATA LOCAL INPATH '${FILE}' INTO TABLE
              import_s3_data PARTITION (tier1 = '${T1}', tier2 = '${T2}', tier3 = '${T3}');"
done
hive -e "${LOAD_SQL}"
</code>```

another option

I think there are some another options to retrieve small S3 data

S3DistCp ... it will merge small file as large one in order to deal with Hadoop

Hive - External Tables ... it will create an external table referring s3 storages. However, it has almost same performance compared with the case to use s3cmd get. It might more effective in such a case, there are many large raw or gziped files on S3.

ContentLicense: CC BY-SA 3.0

Title: EMR Hadoop processing whole S3 file

Body:
I had the same issue. Please refer following questions.

s3fs on Amazon EMR: Will it scale for approx 100million small files?

Write 100 million files to s3

Too many open files in EMR

If you don't have any large files, but have a lot of files, it's sufficient to use s3cmd get --recursive s3://<url> . command. After retrieved files into EMR instance, you could create tables with Hive. For example, you can load whole files with LOAD DATA statement with partition.

sample

This is a sample code

#!/bin/bash

s3cmd get --recursive s3://your.s3.name .

# create table with partitions
hive -e "SET mapred.input.dir.recursive=true; DROP TABLE IF EXISTS import_s3_data;"
hive -e "CREATE TABLE import_s3_data( rawdata string )
         PARTITIONED BY (tier1 string, tier2, string, tier3 string);"

LOAD_SQL=""

# collect files as array
FILES=(`find . -name \*.txt -print`)

for FILE in ${FILES[@]}
do
    DIR_INFO=(`echo ${FILE##./} | tr -s '/' ' '`)
    T1=${DIR_INFO[0]}
    T2=${DIR_INFO[1]}
    T3=${DIR_INFO[2]}
    LOAD_SQL="${LOAD_SQL} LOAD DATA LOCAL INPATH '${FILE}' INTO TABLE
              import_s3_data PARTITION (tier1 = '${T1}', tier2 = '${T2}', tier3 = '${T3}');"
done
hive -e "${LOAD_SQL}"

another option

I think there are some another options to retrieve small S3 data

S3DistCp ... it will merge small file as large one in order to deal with Hadoop

Hive - External Tables ... it will create an external table referring s3 storages. However, it has almost same performance compared with the case to use s3cmd get. It might more effective in such a case, there are many large raw or gziped files on S3.


问:
Block request in Sails (via CORS settings)
I want to restrict/block request that comes not from my domain where app is running. As an example I want to disable POST request on /contact that comes from Postman.

So I thought it is a job for CORS configuration in sails and I did described my route as following:

```<code>'POST /contact':                            {
    controller: "ContactController",
    action: "contact",
    cors: {
        origin: "http://some-domain.com"
    }
}
</code>```

What I expected is that only requests that come from some-domain.com will be accepted, others, as well as my test one from Postman will be rejected.

Unfortunately if I open postman app and try to make a POST request to /contact it will be accepted.

What am I configuring wrong?

答: You need to set securityLevel to 2.</p>

Body:
I want to restrict/block request that comes not from my domain where app is running. As an example I want to disable POST request on /contact that comes from Postman.

So I thought it is a job for CORS configuration in sails and I did described my route as following:

'POST /contact':                            {
    controller: "ContactController",
    action: "contact",
    cors: {
        origin: "http://some-domain.com"
    }
}

What I expected is that only requests that come from some-domain.com will be accepted, others, as well as my test one from Postman will be rejected.

Unfortunately if I open postman app and try to make a POST request to /contact it will be accepted.

What am I configuring wrong?

Body: You need to set securityLevel to 2.


问:
Error while trying to destructure an array of possible length 2
I am trying to destructure an array of length 2, but I get a typescript error:

```<code>[ts] Tuple type '[string]' with length '1' cannot be assigned
to tuple with length '2'.
</code>```

```<code>    let output = {status: false};
    if(execute.permission) {
        let message: [string] = execute.params;
        if(message.length >= 2) {
            // Destructuring follows
            [output['position'], output['message']] = message;
        }
    }
</code>```

How do I tell typescript, that the array could possiblly be of length  2?

答:
Try to change type of message variable. Array of strings suits better than array with single string

```<code>let message: string[] = execute.params;
</code>```

Body:
I am trying to destructure an array of length 2, but I get a typescript error:

[ts] Tuple type '[string]' with length '1' cannot be assigned
to tuple with length '2'.

    let output = {status: false};
    if(execute.permission) {
        let message: [string] = execute.params;
        if(message.length >= 2) {
            // Destructuring follows
            [output['position'], output['message']] = message;
        }
    }

How do I tell typescript, that the array could possiblly be of length  2?

Body:
Try to change type of message variable. Array of strings suits better than array with single string

let message: string[] = execute.params;


问:
How to disable scrolling in UITableView table when the content fits on the screen
I have a few (grouped style) tables in my iphone app (only on part of the screen and added with Interface Builder though, not subclassed from UITableViewController) that 80% of the time are small and will fit on the screen.  When the table fits on the screen, I'd like to disable scrolling, to make it a bit cleaner.  But if the table goes off the screen (when rows are later added to it), I'd like to enable scrolling again (because otherwise you can't see that content.)

Is there a way to do this?  I can't seem to figure it out.  I do know to do:

```<code>tableView.scrollEnabled = NO;
</code>```

but I'm not sure where, or if I have to calculate the table object size or something to get this to work.

Update:
Here's the solution that finally worked for me:

```<code>if (table.contentSize.height < table.frame.size.height) {
   table.scrollEnabled = NO;
 }
else {
   table.scrollEnabled = YES;
 }
</code>```

I run this code after calling reloadData on the table, and it calculates the right sizes and appears to work.

table.frame.size.height is the actual size of the object (you can see this in Interface Builder) displayed on the screen, whereas table.contentSize.height is the heights of: the header, the footer, and the height of every cell added together.

答:
// Enable scrolling based on content height
self.tableView.scrollEnabled = table.contentSize.height > table.frame.size.height;

Body:
I have a few (grouped style) tables in my iphone app (only on part of the screen and added with Interface Builder though, not subclassed from UITableViewController) that 80% of the time are small and will fit on the screen.  When the table fits on the screen, I'd like to disable scrolling, to make it a bit cleaner.  But if the table goes off the screen (when rows are later added to it), I'd like to enable scrolling again (because otherwise you can't see that content.)

Is there a way to do this?  I can't seem to figure it out.  I do know to do:

tableView.scrollEnabled = NO;

but I'm not sure where, or if I have to calculate the table object size or something to get this to work.

Update:
Here's the solution that finally worked for me:

if (table.contentSize.height < table.frame.size.height) {
   table.scrollEnabled = NO;
 }
else {
   table.scrollEnabled = YES;
 }

I run this code after calling reloadData on the table, and it calculates the right sizes and appears to work.

table.frame.size.height is the actual size of the object (you can see this in Interface Builder) displayed on the screen, whereas table.contentSize.height is the heights of: the header, the footer, and the height of every cell added together.


问:
Is it possible to process the push notification data in Windows Phone 7
i have a question for my student project.

I am currently using push notification an the Windows Phone 7 and wanted to ask if it is possible - like as it is in Android - to process the delivered data in background, creating a wakelock or something.

Here the scenerio how it works in Android:
1. I send a notification to the device (more precise to the C2DM Server, but that doesn't matters now).
2. The App receives my notification while it is closed, shows a tile on the screens and saves the data in a database so i can work with them later.

Is it possible to store the data received by a push notification in a database/isolated storage in Windows Phone 7 while the Application is not running?

答:
As Mick said. That's not possible at the moment.

Tile and toast notifications are intended to be used provide updated information to the user or prompt the user that there is more information availabel.

If this then prompts the user to open the app, that should be the trigger for the app to get any new information from the server. You can then save/store this information as appropriate.


问:
Determine if a tableview cell is visible
Is there any way to know if a tableview cell is currently visible?
I have a tableview whose first cell(0) is a uisearchbar.
If a search is not active, then hide cell 0 via an offset.
When the table only has a few rows, the row 0 is visible.
How to determine if row 0 is visible or is the top row?</p>

答:
Note that "Somewhat visible" is "visible". Also, in viewWillAppear, you might get false positives from indexPathsForVisibleRows as layout is in progress, and if you're looking at the last row, even calling layoutIfNeeded() won't help you for tables. You'll want to check things in/after viewDidAppear.

This swift 3.1 code will disable scroll if the last row is fully visible. Call it in/after viewDidAppear.

```<code>    let numRows = tableView.numberOfRows(inSection: 0) // this can't be in viewWillAppear because the table's frame isn't set to proper height even after layoutIfNeeded()
    let lastRowRect = tableView.rectForRow(at: IndexPath.init(row: numRows-1, section: 0))
    if lastRowRect.origin.y + lastRowRect.size.height > tableView.frame.size.height {
        tableView.isScrollEnabled = true
    } else {
        tableView.isScrollEnabled = false
    }
</code>```

Body:
Note that "Somewhat visible" is "visible". Also, in viewWillAppear, you might get false positives from indexPathsForVisibleRows as layout is in progress, and if you're looking at the last row, even calling layoutIfNeeded() won't help you for tables. You'll want to check things in/after viewDidAppear.

This swift 3.1 code will disable scroll if the last row is fully visible. Call it in/after viewDidAppear.

    let numRows = tableView.numberOfRows(inSection: 0) // this can't be in viewWillAppear because the table's frame isn't set to proper height even after layoutIfNeeded()
    let lastRowRect = tableView.rectForRow(at: IndexPath.init(row: numRows-1, section: 0))
    if lastRowRect.origin.y + lastRowRect.size.height > tableView.frame.size.height {
        tableView.isScrollEnabled = true
    } else {
        tableView.isScrollEnabled = false
    }


问:
How to separate an variable array into smaller arrays using swift
I have a question I cannot figure out. Is there an easier way to separate an array into other arrays. In the code below I do a Trace route and filter out everything except the ping rates.

Then I break down that array into individual nodes. The only downside is if it only takes 2 hops then I get an error, "fatal error: Index out of range." because I have it set up to create 15 node arrays. I have also tried putting ..

```<code>let count = pingRate.count
if count < 15 {
aNodeArray += pingRate[14]
}
</code>```

Is there an easier way? I wish there was a way to do a .count and then populate the Int the is required on each node.

```<code>let task = Process()
    task.launchPath = "/bin/sh"
    task.arguments = ["-c", "traceroute -nm 15 -q 1 8.8.8.8"]

    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
    var array = output.components(separatedBy: " ")

    array = array.filter({ $0.contains(".")})
    let pingRate: [[Double]] = array.enumerated().filter({ index, _ in
        index % 2 != 0
    }).map { [Double($0.1)!] }
    let aNode = pingRate[0]
    let bNode = pingRate[1]
    let cNode = pingRate[2]
    let dNode = pingRate[3]
    let eNode = pingRate[4]

    aNodeArray += aNode
    bNodeArray += bNode
    cNodeArray += cNode
    dNodeArray += dNode
    eNodeArray += eNode
</code>```

Once I get that done then I sort and find the min, max, and average.

```<code>    let sorted = aNodeArray.sorted()
    let numbers = sorted
    print(numbers)
    let min = numbers[0]

    var sum = 0 as Double
    for number in numbers {
        sum += number
    }
    let mean = Double(sum) /
        Double (numbers.count)
    let x = mean
    let avg = round(1000.0 * x) / 1000.0
    let maxBR = numbers.last! as Double
    let max = round(1000.0 * maxBR) / 1000.0

    print(min)
    print(max)
    print(avg)
</code>```

Edit

I did stumble upon chunks and stride from...
Swift: what is the right way to split up a [String] resulting in a [[String]] with a given subarray size?

I am trying to figure a way to implement that for my needs

Edit

And looking at that code. Can anyone tell me why I get the Color spinning wheel until the process() is finished?

答:
I know that there are more efficient algorithms to calculate your ping rate statistics but the code below should do the job.

```<code>let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "traceroute -nm 15 -q 1 8.8.8.8"]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard
  let pingRates = String(data: data, encoding: .utf8)?
    .components(separatedBy: " ")
    .filter({ $0.contains(".") })
    .flatMap({ Double($0) }),
  pingRates.count > 0
else {
  return
}
print("ping rate(min) = \(pingRates.min()!.rounded())")
print("ping rate(max) = \(pingRates.max()!.rounded())")
print("ping rate(avg) = \((pingRates.reduce(0, +) / Double(pingRates.count)).rounded())")
</code>```

The trick to eliminating the IP addresses in your output is to let Double.init fail on them and then flatMap will remove those nil values.

Body:
I have a question I cannot figure out. Is there an easier way to separate an array into other arrays. In the code below I do a Trace route and filter out everything except the ping rates.

Then I break down that array into individual nodes. The only downside is if it only takes 2 hops then I get an error, "fatal error: Index out of range." because I have it set up to create 15 node arrays. I have also tried putting ..

let count = pingRate.count
if count < 15 {
aNodeArray += pingRate[14]
}

Is there an easier way? I wish there was a way to do a .count and then populate the Int the is required on each node.

let task = Process()
    task.launchPath = "/bin/sh"
    task.arguments = ["-c", "traceroute -nm 15 -q 1 8.8.8.8"]

    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
    var array = output.components(separatedBy: " ")

    array = array.filter({ $0.contains(".")})
    let pingRate: [[Double]] = array.enumerated().filter({ index, _ in
        index % 2 != 0
    }).map { [Double($0.1)!] }
    let aNode = pingRate[0]
    let bNode = pingRate[1]
    let cNode = pingRate[2]
    let dNode = pingRate[3]
    let eNode = pingRate[4]

    aNodeArray += aNode
    bNodeArray += bNode
    cNodeArray += cNode
    dNodeArray += dNode
    eNodeArray += eNode

Once I get that done then I sort and find the min, max, and average.

    let sorted = aNodeArray.sorted()
    let numbers = sorted
    print(numbers)
    let min = numbers[0]

    var sum = 0 as Double
    for number in numbers {
        sum += number
    }
    let mean = Double(sum) /
        Double (numbers.count)
    let x = mean
    let avg = round(1000.0 * x) / 1000.0
    let maxBR = numbers.last! as Double
    let max = round(1000.0 * maxBR) / 1000.0

    print(min)
    print(max)
    print(avg)

Edit

I did stumble upon chunks and stride from...
Swift: what is the right way to split up a [String] resulting in a [[String]] with a given subarray size?

I am trying to figure a way to implement that for my needs

Edit

And looking at that code. Can anyone tell me why I get the Color spinning wheel until the process() is finished?

Body:
I know that there are more efficient algorithms to calculate your ping rate statistics but the code below should do the job.

let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "traceroute -nm 15 -q 1 8.8.8.8"]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard
  let pingRates = String(data: data, encoding: .utf8)?
    .components(separatedBy: " ")
    .filter({ $0.contains(".") })
    .flatMap({ Double($0) }),
  pingRates.count > 0
else {
  return
}
print("ping rate(min) = \(pingRates.min()!.rounded())")
print("ping rate(max) = \(pingRates.max()!.rounded())")
print("ping rate(avg) = \((pingRates.reduce(0, +) / Double(pingRates.count)).rounded())")

The trick to eliminating the IP addresses in your output is to let Double.init fail on them and then flatMap will remove those nil values.


问:
Nested JTabbedPane contents not rendering as expected
I am building a Java Swing application, and am trying to use nested JTabbedPane components in it, and am having mixed results.

In my top-level JFrame, I am able to successfully construct and load tabbed panes with JPanels. In the top level of the application, there are two sections, each assigned to a tab: General and Stream, both based on JPanels. Stream possesses its own JTabbedPane, as it is composed of three subordinate sections: Metadata, Input, and Instance, all also based on JPanels. All of the code written in the JFrame component works as expected. Tabs are initialized, JFrames are assigned to tabs, and it all displays correctly up to a point. Here is the code so far in my JFrame component:

```<code>package gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JTabbedPane;

public class AppFrame extends JFrame {

    private static final long serialVersionUID = 5294140238998011273L;
    private GeneralPanel generalPanel;
    private JTabbedPane appTabs;
    private JTabbedPane streamTabs;
    private MetadataPanel metadataPanel;
    private InputPanel inputPanel;

    public AppFrame() {

        super("Sourcecast");

        setIconImage(Toolkit.getDefaultToolkit()
            .getImage(getClass()
            .getResource("/images/Apple-icon-64.png")));

        setLayout(new BorderLayout());

        appTabs = new JTabbedPane(JTabbedPane.TOP);

        generalPanel = new GeneralPanel();
        appTabs.add("General", generalPanel);

        streamTabs = new JTabbedPane(JTabbedPane.TOP);

        metadataPanel = new MetadataPanel();
        streamTabs.add("Metadata", metadataPanel);

        inputPanel = new InputPanel();
        streamTabs.add("Input", inputPanel);

        appTabs.add(streamTabs, "Stream");

        add(appTabs);

        setMinimumSize(new Dimension(500, 400));
        setSize(600, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
}
</code>```

Notice that I added the Input JPanel to the tabs, and its tab showed up. I put a JLabel in my Input JPanel to test it and it was visible. However, my Input JPanel is also loading a set of tabs, and those tabs are not visible when I run the app. Here is the Input JPanel:

```<code>package gui;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class InputPanel extends JPanel {

    private static final long serialVersionUID = 7603090258673682140L;
    private JTabbedPane inputTabs;
    private StdinPcmPanel stdinPcmPanel;

    public InputPanel() {

        setLayout(null);

        inputTabs = new JTabbedPane(JTabbedPane.TOP);
        stdinPcmPanel = new StdinPcmPanel();

        inputTabs.add("StdinPCM", stdinPcmPanel);

        add(inputTabs);
    }
}
</code>```

Below is one of the JPanels I am trying to load in the Input panel, and I have removed the other tabs in Input, just for simplicity:

```<code>package gui;

import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JTextField;

public class StdinPcmPanel extends JPanel {

    private static final long serialVersionUID = -916207698149110923L;
    private JComboBox<CbOption> samplerate;
    private JComboBox<CbOption> channels;
    private JComboBox<CbOption> metadata;
    private JTextField metadatafilename;

    public StdinPcmPanel() {

        setLayout(null);

        JLabel lblSampleRate = new JLabel("Sample Rate");
        lblSampleRate.setBounds(12, 12, 230, 15);
        add(lblSampleRate);

        samplerate = new JComboBox<CbOption>();
        samplerate.addItem(new CbOption(48000, "48000 Hz (DAT)"));
        samplerate.addItem(new CbOption(44100, "44100 Hz (CD)"));
        samplerate.addItem(new CbOption(22050, "22500 Hz (FM)"));
        samplerate.addItem(new CbOption(16000, "16000 Hz"));
        samplerate.addItem(new CbOption(11025, "11025 Hz"));
        samplerate.addItem(new CbOption(8000, "8000 Hz"));
        samplerate.setSelectedIndex(1);
        samplerate.setBounds(12, 39, 156, 24);
        add(samplerate);

        JLabel lblChannels = new JLabel("Channels");
        lblChannels.setBounds(12, 75, 230, 15);
        add(lblChannels);

        channels = new JComboBox<CbOption>();
        channels.addItem(new CbOption(1, "Mono"));
        channels.addItem(new CbOption(2, "Stereo"));
        channels.setSelectedIndex(1);
        channels.setBounds(12, 102, 156, 24);
        add(channels);

        JLabel lblMetadata = new JLabel("Metadata");
        lblMetadata.setBounds(12, 138, 230, 15);
        add(lblMetadata);

        metadata = new JComboBox<CbOption>();
        metadata.addItem(new CbOption(0, "None"));
        metadata.addItem(new CbOption(1, "File"));
        metadata.setSelectedIndex(0);
        metadata.setBounds(12, 165, 156, 24);
        add(metadata);

        JLabel lblMetadataFile = new JLabel("Metadata File");
        lblMetadataFile.setBounds(12, 201, 230, 15);
        add(lblMetadataFile);

        metadatafilename = new JTextField();
        metadatafilename.setBounds(12, 228, 251, 24);
        add(metadatafilename);
        metadatafilename.setColumns(10);
    }
}
</code>```

I realize that using all JTabbedPanes is not visually pleasing, and can be confusing. I actually intend to change that. However, I still need to know why this isn't working as expected. Below are two screen shots showing the top level tabs working ok, and then you see when Input is clicked, there is nothing visible.

Imported JPanel shown in nested tab

Imported JPanel with its own JTabbedPane not displayed

答:
However, my Input JPanel is also loading a set of tabs, and those tabs are not visible when I run the app.

Don't use a null layout. All panels should use an appropriate layout manager.

Probably use a BorderLayout, then the added tab will have access to all the space available to the input panel.

In the future (and if you need more help) post a proper MCVE that demonstrates the problem when you post code. That is post minimal code that compiles and demonstrates the problem.

For example, we don't have access to your panel classes, so just use a JPanel to add to the tabbed pane.

Body:
I am building a Java Swing application, and am trying to use nested JTabbedPane components in it, and am having mixed results.

In my top-level JFrame, I am able to successfully construct and load tabbed panes with JPanels. In the top level of the application, there are two sections, each assigned to a tab: General and Stream, both based on JPanels. Stream possesses its own JTabbedPane, as it is composed of three subordinate sections: Metadata, Input, and Instance, all also based on JPanels. All of the code written in the JFrame component works as expected. Tabs are initialized, JFrames are assigned to tabs, and it all displays correctly up to a point. Here is the code so far in my JFrame component:

package gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JTabbedPane;

public class AppFrame extends JFrame {

    private static final long serialVersionUID = 5294140238998011273L;
    private GeneralPanel generalPanel;
    private JTabbedPane appTabs;
    private JTabbedPane streamTabs;
    private MetadataPanel metadataPanel;
    private InputPanel inputPanel;

    public AppFrame() {

        super("Sourcecast");

        setIconImage(Toolkit.getDefaultToolkit()
            .getImage(getClass()
            .getResource("/images/Apple-icon-64.png")));

        setLayout(new BorderLayout());

        appTabs = new JTabbedPane(JTabbedPane.TOP);

        generalPanel = new GeneralPanel();
        appTabs.add("General", generalPanel);

        streamTabs = new JTabbedPane(JTabbedPane.TOP);

        metadataPanel = new MetadataPanel();
        streamTabs.add("Metadata", metadataPanel);

        inputPanel = new InputPanel();
        streamTabs.add("Input", inputPanel);

        appTabs.add(streamTabs, "Stream");

        add(appTabs);

        setMinimumSize(new Dimension(500, 400));
        setSize(600, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

Notice that I added the Input JPanel to the tabs, and its tab showed up. I put a JLabel in my Input JPanel to test it and it was visible. However, my Input JPanel is also loading a set of tabs, and those tabs are not visible when I run the app. Here is the Input JPanel:

package gui;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class InputPanel extends JPanel {

    private static final long serialVersionUID = 7603090258673682140L;
    private JTabbedPane inputTabs;
    private StdinPcmPanel stdinPcmPanel;

    public InputPanel() {

        setLayout(null);

        inputTabs = new JTabbedPane(JTabbedPane.TOP);
        stdinPcmPanel = new StdinPcmPanel();

        inputTabs.add("StdinPCM", stdinPcmPanel);

        add(inputTabs);
    }
}

Below is one of the JPanels I am trying to load in the Input panel, and I have removed the other tabs in Input, just for simplicity:

package gui;

import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JTextField;

public class StdinPcmPanel extends JPanel {

    private static final long serialVersionUID = -916207698149110923L;
    private JComboBox<CbOption> samplerate;
    private JComboBox<CbOption> channels;
    private JComboBox<CbOption> metadata;
    private JTextField metadatafilename;

    public StdinPcmPanel() {

        setLayout(null);

        JLabel lblSampleRate = new JLabel("Sample Rate");
        lblSampleRate.setBounds(12, 12, 230, 15);
        add(lblSampleRate);

        samplerate = new JComboBox<CbOption>();
        samplerate.addItem(new CbOption(48000, "48000 Hz (DAT)"));
        samplerate.addItem(new CbOption(44100, "44100 Hz (CD)"));
        samplerate.addItem(new CbOption(22050, "22500 Hz (FM)"));
        samplerate.addItem(new CbOption(16000, "16000 Hz"));
        samplerate.addItem(new CbOption(11025, "11025 Hz"));
        samplerate.addItem(new CbOption(8000, "8000 Hz"));
        samplerate.setSelectedIndex(1);
        samplerate.setBounds(12, 39, 156, 24);
        add(samplerate);

        JLabel lblChannels = new JLabel("Channels");
        lblChannels.setBounds(12, 75, 230, 15);
        add(lblChannels);

        channels = new JComboBox<CbOption>();
        channels.addItem(new CbOption(1, "Mono"));
        channels.addItem(new CbOption(2, "Stereo"));
        channels.setSelectedIndex(1);
        channels.setBounds(12, 102, 156, 24);
        add(channels);

        JLabel lblMetadata = new JLabel("Metadata");
        lblMetadata.setBounds(12, 138, 230, 15);
        add(lblMetadata);

        metadata = new JComboBox<CbOption>();
        metadata.addItem(new CbOption(0, "None"));
        metadata.addItem(new CbOption(1, "File"));
        metadata.setSelectedIndex(0);
        metadata.setBounds(12, 165, 156, 24);
        add(metadata);

        JLabel lblMetadataFile = new JLabel("Metadata File");
        lblMetadataFile.setBounds(12, 201, 230, 15);
        add(lblMetadataFile);

        metadatafilename = new JTextField();
        metadatafilename.setBounds(12, 228, 251, 24);
        add(metadatafilename);
        metadatafilename.setColumns(10);
    }
}

I realize that using all JTabbedPanes is not visually pleasing, and can be confusing. I actually intend to change that. However, I still need to know why this isn't working as expected. Below are two screen shots showing the top level tabs working ok, and then you see when Input is clicked, there is nothing visible.

Imported JPanel shown in nested tab

Imported JPanel with its own JTabbedPane not displayed


问:
Convert container component implicitly created with `connect()` to explicit container component
I have this stateless functional component called Volume that uses connect() to create the container component:

```<code>const mapStateToProps = (state) => ({
  volume: state.get('volume')
})

let Volume = (props) => {
  if (props.volume === 'Infinity') {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        Incalculable
      </Text>
    )
  } else {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        {props.volume + ' litres'}
      </Text>
    )
  }
}

Volume.propTypes = {
  volume: React.PropTypes.string
}

Volume = connect(
  mapStateToProps,
  null
)(Volume)

export default Volume
</code>```

I now need to implement componentDidMount lifecycle method on it which will run a function that takes the whole redux store as an argument, then dispatch an action to update the store.volume, which can then be passed to the initial Volume presentational component to display. So I want to go back to basics and not use connect() so that I can implement the lifecycle method in the container component. I have never not used connect()

Here is my attempt:

```<code>import { Text } from 'react-native'
import React, { Component } from 'react'
import { formStyles } from '../../style'
import calcVol from '../../calcVol'
import { updateVolume } from '../../actions/updateDimension.action'

export class VolumeContainer extends Component {
  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() =>
      this.forceUpdate()
    )
    let litres = calcVol(store)
    store.dispatch(updateVolume(litres))
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
    const { store } = this.context
    return (
      <VolumePresentational volume={store.getState().volume} />
    )
  }
}

VolumeContainer.contextTypes = {
  store: React.PropTypes.object
}

let VolumePresentational = (props) => {
  if (props.volume === 'Infinity') {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        Incalculable
      </Text>
    )
  } else {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        {props.volume + ' litres'}
      </Text>
    )
  }
}

VolumePresentational.propTypes = {
  volume: React.PropTypes.string
}

const styles = {
  text: {
    marginTop: 20,
    fontSize: 30,
    fontWeight: 'bold'
  }
}

export default VolumeContainer
</code>```

The code is getting inside my volCalc(store) function where it has the error:

state.get is not a function

so my store that i'm passing into calcVol() in componentDidMount must not be the store.

What have I done wrong?

答:
In general if something can be calculated entirely from the state, (i.e. it is a function of that state), then it should not be in state itself.  For example, a state such as:

```<code>{
    x: 3,
    y: 2,
    z: 5,
    volume: 30
}
</code>```

This results in duplication of information within the state, and ultimately all sorts of non-trivial issues with keeping things in sync with each other.  The common theme throughout React and Redux should be having a "single source of truth" i.e. information lives in one place and one place only.  In the above example, the information about volume is being stored in the volume property, but also in the combination of the x, y and z properties - so there are now two sources of truth.

In terms of applying this approach to an application, it is best to keep the most simple form of the data possible in the store, and combine that data in selector functions that return the aggregated data we require.

Taking the example above, we would have:

```<code>const state = {
    x: 3,
    y: 2,
    z: 5
}
</code>```

and a selector function to calculate volume:

```<code>const selectVolume = state => state.x * state.y * state.z;
</code>```

If the calculation is computationally expensive, then we can memoize the selector function to avoid repeatedly calculating the same data:

```<code>const makeSelectVolume = () => {
    const memo = {};
    return state => {
        const (x, y, z} = state;
        // if we have memoized a value for these parameters return it
        if( x in memo && y in memo[x] && z in memo[x][y] ) {
            return memo[x][y][z];
        }
        // otherwise calculate it
        const volume = x * y * z;
        // and memoize it
        memo[x][y][z] = volume;
        return volume;
    }
}
</code>```

Fortunately, the excellent library reselect creates automatically memoized selectors that we can use with redux, so we don't need to go to the trouble of memoizing them ourselves.  With reselect we would make our selector function like this:

```<code>const makeSelectVolume = () => createSelector(
    state => state.x,
    state => state.y,
    state => state.z,
    (x, y, z) => x * y * z
};
</code>```

Now we just need to integrate this with our component:

```<code>// other imports as usual
import { makeSelectVolume } from 'path/to/selector';

const Volume = (props) => {
  if (props.volume === 'Infinity') {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        Incalculable
      </Text>
    )
  } else {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        {props.volume + ' litres'}
      </Text>
    )
  }
}

Volume.propTypes = {
  volume: React.PropTypes.string
}

const mapStateToProps = createStructuredSelector({
    volume: makeSelectVolume()
});

export default connect(
  mapStateToProps
)(Volume);
</code>```

In your case just replace the volume calculation logic in the selector with your calcVol function.  Do note that it is imperative that calcVol is a pure function here i.e. it does not modify state in any way.

Edit

If our state is an ImmutableJS map with the structure:

```<code>{
  widths: {
    width1: 2,
    width2: 7,
  },
  heights: {
    height1: 4,
    height2: 3
  }
}
</code>```

We could write a selector function as either:

```<code>const makeSelectVolume = () => createSelector(
    state => state.get('widths'),
    state => state.get('heights'),
    (widths, heights) => calculateSomething(widths.toJS(), heights.toJS())
};
</code>```

or as:

```<code>const makeSelectVolume = () => createSelector(
        state => state.get('widths').get('width1'),
        state => state.get('widths').get('width2'),
        state => state.get('heights').get('height1'),
        state => state.get('heights').get('height2'),
        (width1, width2, height1, height2) => calculateSomething({ width1, width 2 },{ height1, height2 })
    };
</code>```

If you choose the second one then memoization will work fine, but if you choose the first one you may need to use reselect's createSelectorCreator to implement a custom equality checker.

Essentially reselect checks if any of the composed selectors values have changed, by default using === (which only returns true if they are literally the same object in memory).  If you return Immutable maps from your composed selectors then you will want to check if the maps are the same in terms of their values e.g. using the equals method of your Immutable maps:

```<code>import { createSelectorCreator, defaultMemoize } from 'reselect';

const createImmutableMapSelector = createSelectorCreator(
    defaultMemoize,
    (a, b) => a.equals(b)
);

const makeSelectVolume = () => createImmutableMapSelector(
    state => state.get('widths'),
    state => state.get('heights'),
    (widths, heights) => calculateSomething(widths.toJS(), heights.toJS())
};
</code>```

This comes with some more complexity, but takes advantage of the speediness of Immutables deep comparisons.  Ultimately either way will work though.

Body:
I have this stateless functional component called Volume that uses connect() to create the container component:

const mapStateToProps = (state) => ({
  volume: state.get('volume')
})

let Volume = (props) => {
  if (props.volume === 'Infinity') {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        Incalculable
      </Text>
    )
  } else {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        {props.volume + ' litres'}
      </Text>
    )
  }
}

Volume.propTypes = {
  volume: React.PropTypes.string
}

Volume = connect(
  mapStateToProps,
  null
)(Volume)

export default Volume

I now need to implement componentDidMount lifecycle method on it which will run a function that takes the whole redux store as an argument, then dispatch an action to update the store.volume, which can then be passed to the initial Volume presentational component to display. So I want to go back to basics and not use connect() so that I can implement the lifecycle method in the container component. I have never not used connect()

Here is my attempt:

import { Text } from 'react-native'
import React, { Component } from 'react'
import { formStyles } from '../../style'
import calcVol from '../../calcVol'
import { updateVolume } from '../../actions/updateDimension.action'

export class VolumeContainer extends Component {
  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() =>
      this.forceUpdate()
    )
    let litres = calcVol(store)
    store.dispatch(updateVolume(litres))
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
    const { store } = this.context
    return (
      <VolumePresentational volume={store.getState().volume} />
    )
  }
}

VolumeContainer.contextTypes = {
  store: React.PropTypes.object
}

let VolumePresentational = (props) => {
  if (props.volume === 'Infinity') {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        Incalculable
      </Text>
    )
  } else {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        {props.volume + ' litres'}
      </Text>
    )
  }
}

VolumePresentational.propTypes = {
  volume: React.PropTypes.string
}

const styles = {
  text: {
    marginTop: 20,
    fontSize: 30,
    fontWeight: 'bold'
  }
}

export default VolumeContainer

The code is getting inside my volCalc(store) function where it has the error:

state.get is not a function

so my store that i'm passing into calcVol() in componentDidMount must not be the store.

What have I done wrong?

Body:
In general if something can be calculated entirely from the state, (i.e. it is a function of that state), then it should not be in state itself.  For example, a state such as:

{
    x: 3,
    y: 2,
    z: 5,
    volume: 30
}

This results in duplication of information within the state, and ultimately all sorts of non-trivial issues with keeping things in sync with each other.  The common theme throughout React and Redux should be having a "single source of truth" i.e. information lives in one place and one place only.  In the above example, the information about volume is being stored in the volume property, but also in the combination of the x, y and z properties - so there are now two sources of truth.

In terms of applying this approach to an application, it is best to keep the most simple form of the data possible in the store, and combine that data in selector functions that return the aggregated data we require.

Taking the example above, we would have:

const state = {
    x: 3,
    y: 2,
    z: 5
}

and a selector function to calculate volume:

const selectVolume = state => state.x * state.y * state.z;

If the calculation is computationally expensive, then we can memoize the selector function to avoid repeatedly calculating the same data:

const makeSelectVolume = () => {
    const memo = {};
    return state => {
        const (x, y, z} = state;
        // if we have memoized a value for these parameters return it
        if( x in memo && y in memo[x] && z in memo[x][y] ) {
            return memo[x][y][z];
        }
        // otherwise calculate it
        const volume = x * y * z;
        // and memoize it
        memo[x][y][z] = volume;
        return volume;
    }
}

Fortunately, the excellent library reselect creates automatically memoized selectors that we can use with redux, so we don't need to go to the trouble of memoizing them ourselves.  With reselect we would make our selector function like this:

const makeSelectVolume = () => createSelector(
    state => state.x,
    state => state.y,
    state => state.z,
    (x, y, z) => x * y * z
};

Now we just need to integrate this with our component:

// other imports as usual
import { makeSelectVolume } from 'path/to/selector';

const Volume = (props) => {
  if (props.volume === 'Infinity') {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        Incalculable
      </Text>
    )
  } else {
    return (
      <Text
        style={{ ...formStyles.text, ...styles.text }}>
        {props.volume + ' litres'}
      </Text>
    )
  }
}

Volume.propTypes = {
  volume: React.PropTypes.string
}

const mapStateToProps = createStructuredSelector({
    volume: makeSelectVolume()
});

export default connect(
  mapStateToProps
)(Volume);

In your case just replace the volume calculation logic in the selector with your calcVol function.  Do note that it is imperative that calcVol is a pure function here i.e. it does not modify state in any way.

Edit

If our state is an ImmutableJS map with the structure:

{
  widths: {
    width1: 2,
    width2: 7,
  },
  heights: {
    height1: 4,
    height2: 3
  }
}

We could write a selector function as either:

const makeSelectVolume = () => createSelector(
    state => state.get('widths'),
    state => state.get('heights'),
    (widths, heights) => calculateSomething(widths.toJS(), heights.toJS())
};

or as:

const makeSelectVolume = () => createSelector(
        state => state.get('widths').get('width1'),
        state => state.get('widths').get('width2'),
        state => state.get('heights').get('height1'),
        state => state.get('heights').get('height2'),
        (width1, width2, height1, height2) => calculateSomething({ width1, width 2 },{ height1, height2 })
    };

If you choose the second one then memoization will work fine, but if you choose the first one you may need to use reselect's createSelectorCreator to implement a custom equality checker.

Essentially reselect checks if any of the composed selectors values have changed, by default using === (which only returns true if they are literally the same object in memory).  If you return Immutable maps from your composed selectors then you will want to check if the maps are the same in terms of their values e.g. using the equals method of your Immutable maps:

import { createSelectorCreator, defaultMemoize } from 'reselect';

const createImmutableMapSelector = createSelectorCreator(
    defaultMemoize,
    (a, b) => a.equals(b)
);

const makeSelectVolume = () => createImmutableMapSelector(
    state => state.get('widths'),
    state => state.get('heights'),
    (widths, heights) => calculateSomething(widths.toJS(), heights.toJS())
};

This comes with some more complexity, but takes advantage of the speediness of Immutables deep comparisons.  Ultimately either way will work though.


问:
Change ImageView visibility from certain rows in RecyclerView
I am trying to change the visibility of an ImageView in a row that is selected. Essentially I want to behave when a user clicks on one row, an ImageView is shown in that row and hides the other ImageViews, and when the user clicks on a different row, it switches the ImageView viability to that row and hides the other ImageView in the previously clicked row.

Heres my code in my recyclerview adapter. I have it currently to show the ImageView on the row that is clicked BUT it currently does not hide the other ImageViews in the other rows!

```<code>public void onBindViewHolder(final PreGameSelectRecyclerAdapter.MyViewHolder holder, int position) {
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (holder.isSelected.getVisibility() == View.INVISIBLE) {
                holder.isSelected.setVisibility(View.VISIBLE);
            } else {
                holder.isSelected.setVisibility(View.INVISIBLE);
            }
        }
    });
}
</code>```

答:
you need to add attribute in your recycled view data set that will keep track of vivble and invisble images.

I put this example for you which do what you want.

```<code>public class RecyclerViewActivity extends AppCompatActivity {

private RecyclerView recycler;

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

    List<Item> items = Arrays.asList(
            new Item("1", false),
            new Item("2", false),
            new Item("3", false),
            new Item("4", false),
            new Item("5", false),
            new Item("6", false),
            new Item("7", false),
            new Item("8", false),
            new Item("9", false),
            new Item("10", false),
            new Item("11", false),
            new Item("12", false),
            new Item("13", false),
            new Item("14", false),
            new Item("15", false),
            new Item("16", false),
            new Item("17", false)
    );

    recycler.setAdapter(new ContactsAdapter(items));
    recycler.setLayoutManager(new LinearLayoutManager(this));

}

class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
    private List<Item> mItems;

    public ContactsAdapter(List<Item> items) {
        mItems = items;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(
                parent.getContext()).inflate(R.layout.row_recycler, parent, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.bind(position);
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView mTextView;
        ImageView mImageView;

        ViewHolder(View itemView) {
            super(itemView);

            mTextView = (TextView) itemView.findViewById(R.id.textView);
            mImageView = (ImageView) itemView.findViewById(R.id.imageView);
        }

        void bind(int position) {
            final Item item = mItems.get(position);
            mTextView.setText(item.getText());

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (Item item1 : mItems) {
                        item1.setImageVisible(false);
                    }
                    item.setImageVisible(true);

                    notifyDataSetChanged();
                }
            });

            if (item.isImageVisible) mImageView.setVisibility(View.VISIBLE);
            else mImageView.setVisibility(View.INVISIBLE);
        }
    }
}

class Item {
    private String text;
    private boolean isImageVisible;

    public Item(String text, boolean isImageVisible) {
        this.setText(text);
        this.setImageVisible(isImageVisible);
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public boolean isImageVisible() {
        return isImageVisible;
    }

    public void setImageVisible(boolean imageVisible) {
        isImageVisible = imageVisible;
    }
}

private void initView() {
    recycler = (RecyclerView) findViewById(R.id.recycler);
}

}
</code>```

Body:
I am trying to change the visibility of an ImageView in a row that is selected. Essentially I want to behave when a user clicks on one row, an ImageView is shown in that row and hides the other ImageViews, and when the user clicks on a different row, it switches the ImageView viability to that row and hides the other ImageView in the previously clicked row.

Heres my code in my recyclerview adapter. I have it currently to show the ImageView on the row that is clicked BUT it currently does not hide the other ImageViews in the other rows!

public void onBindViewHolder(final PreGameSelectRecyclerAdapter.MyViewHolder holder, int position) {
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (holder.isSelected.getVisibility() == View.INVISIBLE) {
                holder.isSelected.setVisibility(View.VISIBLE);
            } else {
                holder.isSelected.setVisibility(View.INVISIBLE);
            }
        }
    });
}

Body:
you need to add attribute in your recycled view data set that will keep track of vivble and invisble images.

I put this example for you which do what you want.

public class RecyclerViewActivity extends AppCompatActivity {

private RecyclerView recycler;

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

    List<Item> items = Arrays.asList(
            new Item("1", false),
            new Item("2", false),
            new Item("3", false),
            new Item("4", false),
            new Item("5", false),
            new Item("6", false),
            new Item("7", false),
            new Item("8", false),
            new Item("9", false),
            new Item("10", false),
            new Item("11", false),
            new Item("12", false),
            new Item("13", false),
            new Item("14", false),
            new Item("15", false),
            new Item("16", false),
            new Item("17", false)
    );

    recycler.setAdapter(new ContactsAdapter(items));
    recycler.setLayoutManager(new LinearLayoutManager(this));

}

class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
    private List<Item> mItems;

    public ContactsAdapter(List<Item> items) {
        mItems = items;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(
                parent.getContext()).inflate(R.layout.row_recycler, parent, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.bind(position);
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView mTextView;
        ImageView mImageView;

        ViewHolder(View itemView) {
            super(itemView);

            mTextView = (TextView) itemView.findViewById(R.id.textView);
            mImageView = (ImageView) itemView.findViewById(R.id.imageView);
        }

        void bind(int position) {
            final Item item = mItems.get(position);
            mTextView.setText(item.getText());

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (Item item1 : mItems) {
                        item1.setImageVisible(false);
                    }
                    item.setImageVisible(true);

                    notifyDataSetChanged();
                }
            });

            if (item.isImageVisible) mImageView.setVisibility(View.VISIBLE);
            else mImageView.setVisibility(View.INVISIBLE);
        }
    }
}

class Item {
    private String text;
    private boolean isImageVisible;

    public Item(String text, boolean isImageVisible) {
        this.setText(text);
        this.setImageVisible(isImageVisible);
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public boolean isImageVisible() {
        return isImageVisible;
    }

    public void setImageVisible(boolean imageVisible) {
        isImageVisible = imageVisible;
    }
}

private void initView() {
    recycler = (RecyclerView) findViewById(R.id.recycler);
}

}


问:
Reduce FFmpeg CPU Usage with cpulimit and PHP
I run FFmpeg on my server using PHP exec().

It currently uses 100% of the cpu thread while encoding.

I followed this gude that uses a program called cpulimit to reduce it to 30%.

PHP

```<code>$args = "nice -19 cpulimit -l 30 -- ffmpeg -y -i intput.avi -vcodec libx264 -acodec aac -b:a 192k -threads 1 output.mp4"
exec(escapeshellcmd($args));
</code>```

FFmpeg/PHP works, and it will work with nice/cpulimit through the terminal, but after adding

 nice -19 cpulimit -l 30 -- to the PHP script it no longer works with exec().

Output

FFmpeg output returns blank. I'm not able to see the full output, I tried using:

```<code>$output = shell_exec($args);
echo "<p>$output</p>"
</code>```

and

```<code>file_put_contents("/var/www/mysite/logs/$output.log", $line . PHP_EOL, FILE_APPEND);
</code>```

But they return 1 empty line.

Solution

My thought is that www-data runs FFmpeg and nice/cpulimit may need root?

How can I get PHP exec() to work with FFmpeg args and cpulimit?

Or is there an alternative way to limit the usage %?

答:
I found the answer on this forum post using google translate.

https://murobbs.muropaketti.com/threads/nice-komento-ja-php-n-exec-funktio-ratkaistu.551174/

Define the path to FFmpeg if using nice or cpulimit

```<code>nice -19 cpulimit -l 30 /usr/local/bin/ffmpeg -i ...
</code>```

Now it works through PHP exec().

Body:
I run FFmpeg on my server using PHP exec().

It currently uses 100% of the cpu thread while encoding.

I followed this gude that uses a program called cpulimit to reduce it to 30%.

PHP

$args = "nice -19 cpulimit -l 30 -- ffmpeg -y -i intput.avi -vcodec libx264 -acodec aac -b:a 192k -threads 1 output.mp4"
exec(escapeshellcmd($args));

FFmpeg/PHP works, and it will work with nice/cpulimit through the terminal, but after adding

 nice -19 cpulimit -l 30 -- to the PHP script it no longer works with exec().

Output

FFmpeg output returns blank. I'm not able to see the full output, I tried using:

$output = shell_exec($args);
echo "
$output
"

and

file_put_contents("/var/www/mysite/logs/$output.log", $line . PHP_EOL, FILE_APPEND);

But they return 1 empty line.

Solution

My thought is that www-data runs FFmpeg and nice/cpulimit may need root?

How can I get PHP exec() to work with FFmpeg args and cpulimit?

Or is there an alternative way to limit the usage %?

Body:
I found the answer on this forum post using google translate.

https://murobbs.muropaketti.com/threads/nice-komento-ja-php-n-exec-funktio-ratkaistu.551174/

Define the path to FFmpeg if using nice or cpulimit

nice -19 cpulimit -l 30 /usr/local/bin/ffmpeg -i ...

Now it works through PHP exec().


问:
Basic SQL Subquery
I am working on a project where I am supposed to pull the top 2 Dates of all of my customers last order in MS Access. In the event that there is only one date , it should pull up that single date as well.

```<code>SELECT Customer_t.Customer_ID,
Customer_t.Customer_Name,
Order_t.Order_ID,
Order_t.Order_Date
FROM Customer_t
INNER JOIN Order_t
 ON Customer_t.Customer_ID = Order_t.Customer_ID
WHERE (((Customer_t.Customer_ID)=[Order_t].[Customer_ID]))
</code>```

I am a little new but I am having difficulty following the sub-query information that is currently out on the web.

I know I am trying to use the TOP 2 statement but I continue to    receive syntax errors or statements that will say the most I can pull    is one item
.

Any help would be appreciated. I have seen similar questions to this already but I cannot repeat what the answers have recommended

答:
This type of query is a bit tricky in MS Access.  You can't do what you want easily with JOIN.  Instead, think of this as filtering.  You want to keep only the two most recent order ids for each customer.

That suggests a correlated subquery:

```<code>SELECT c.Customer_ID,  c.Customer_Name, o.Order_ID, o.Order_Date
FROM Customer_t as c INNER JOIN
     Order_t as o
     ON c.Customer_ID = o.Customer_ID
WHERE c.Order_ID IN (SELECT TOP 2 o2.Order_Id
                     FROM Order_t as o2
                     WHERE o2.Customer_Id = o.Customer_Id
                     ORDER BY o2.Order_Date, o2.Order_Id
                    );
</code>```

I'm including Order_id in the ORDER BY so each row has a unique key.  In MS Access, TOP really does TOP WITH TIES, so it is a good idea to add a unique key if you really want at most 2 rows.

Title: Basic SQL Subquery

Body:
I am working on a project where I am supposed to pull the top 2 Dates of all of my customers last order in MS Access. In the event that there is only one date , it should pull up that single date as well.

SELECT Customer_t.Customer_ID,
Customer_t.Customer_Name,
Order_t.Order_ID,
Order_t.Order_Date
FROM Customer_t
INNER JOIN Order_t
 ON Customer_t.Customer_ID = Order_t.Customer_ID
WHERE (((Customer_t.Customer_ID)=[Order_t].[Customer_ID]))

I am a little new but I am having difficulty following the sub-query information that is currently out on the web.

I know I am trying to use the TOP 2 statement but I continue to    receive syntax errors or statements that will say the most I can pull    is one item
.

Any help would be appreciated. I have seen similar questions to this already but I cannot repeat what the answers have recommended

Body:
This type of query is a bit tricky in MS Access.  You can't do what you want easily with JOIN.  Instead, think of this as filtering.  You want to keep only the two most recent order ids for each customer.

That suggests a correlated subquery:

SELECT c.Customer_ID,  c.Customer_Name, o.Order_ID, o.Order_Date
FROM Customer_t as c INNER JOIN
     Order_t as o
     ON c.Customer_ID = o.Customer_ID
WHERE c.Order_ID IN (SELECT TOP 2 o2.Order_Id
                     FROM Order_t as o2
                     WHERE o2.Customer_Id = o.Customer_Id
                     ORDER BY o2.Order_Date, o2.Order_Id
                    );

I'm including Order_id in the ORDER BY so each row has a unique key.  In MS Access, TOP really does TOP WITH TIES, so it is a good idea to add a unique key if you really want at most 2 rows.


问:
500 error on localhost when submitting form using AJAX and PHP
I'm fairly new to PHP and I'm having trouble sending test emails out from my local host.

I have a 3 field form where I'm hoping that I can have a user submit the form & be able to see a success message without the page refreshing. I get the error message that I have set in the code but for some reason, I'm unable to actually get the emails to send/have a success message appear.

Here's my code:

js

```<code>jQuery( document ).ready( function( $ ) {

    var form = $('#ajax-contact');

    var formMessages = $('#form-messages');

    $(form).submit(function(e) {
        e.preventDefault();

        var formData = $(form).serialize();

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {

            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            $(formMessages).text(response);

            $('#name, #email, #number').val('');
        })
        .fail(function(data) {

            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });

    });

});
</code>```

mailer.php

```<code><?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $number = trim($_POST["number"]);

    if ( empty($name) OR empty($number) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
        exit;
    }
    $recipient = "example@example.co.uk";
    $subject = "$name has given you their details to call them back";
    $email_content = "
    <html>
    <style>
    body {
        background-color: white;
    }

    .email-container{
        background-color:#c1c1c1;
        max-width:400px;
        margin:0 auto;
        padding:30px 10px;
        border-radius:10px;
        border: 2px solid #515151;
    }

    </style>
    <body>
    <div class="email-container">

    Dear example, <br />
     <br />
    A potential client has requested a call back. Their details are as follows: <br />
     <br />
    Name: $name\n <br />
    Email: $email\n\n <br />
    Telephone: \n$numer\n
    </div>

    </body>
    </html>"
    $email_headers = "From: $name <$email>";
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        http_response_code(500);
        echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
    }

} else {
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>
</code>```

HTML

```<code><form class="requestcall-form" id="ajax-contact" method="post" action="mailer.php">
  <input type="text" id="name" name="name" placeholder="Full Name" required>
  <input type="text" id="email" name="email" placeholder="Email Address" required>
  <input type="text" id="number" name="number" placeholder="Contact number" required>
  <input class="submit" type="submit" name="submit" value="Submit">
</form>
<div id="form-messages"></div>
</code>```

答:
there is something wrong with how you output $email_content. String is not formatted correctly
check the
 and change it to

also, add a (;) after your $email_content

ContentLicense: CC BY-SA 4.0

Body:
I'm fairly new to PHP and I'm having trouble sending test emails out from my local host.

I have a 3 field form where I'm hoping that I can have a user submit the form & be able to see a success message without the page refreshing. I get the error message that I have set in the code but for some reason, I'm unable to actually get the emails to send/have a success message appear.

Here's my code:

js

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

    var form = $('#ajax-contact');

    var formMessages = $('#form-messages');

    $(form).submit(function(e) {
        e.preventDefault();

        var formData = $(form).serialize();

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {

            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            $(formMessages).text(response);

            $('#name, #email, #number').val('');
        })
        .fail(function(data) {

            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });

    });

});

mailer.php

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $number = trim($_POST["number"]);

    if ( empty($name) OR empty($number) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
        exit;
    }
    $recipient = "example@example.co.uk";
    $subject = "$name has given you their details to call them back";
    $email_content = "

    Dear example,

    A potential client has requested a call back. Their details are as follows:

    Name: $name\n

    Email: $email\n\n

    Telephone: \n$numer\n

    "
    $email_headers = "From: $name <$email>";
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        http_response_code(500);
        echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
    }

} else {
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

HTML

<form class="requestcall-form" id="ajax-contact" method="post" action="mailer.php">
  <input type="text" id="name" name="name" placeholder="Full Name" required>
  <input type="text" id="email" name="email" placeholder="Email Address" required>
  <input type="text" id="number" name="number" placeholder="Contact number" required>
  <input class="submit" type="submit" name="submit" value="Submit">
</form>

Body:
there is something wrong with how you output $email_content. String is not formatted correctly
check the <div class="email-container"> and change it to <div class='email-container'>

also, add a (;) after your $email_content


问:
Mule: How Can I insert a database sequence into a table?
I am trying to insert a database sequence into a table will this work?

```<code>     <db:insert config-ref="Oracle_Configuration" doc:name="INSERT Table">
                <db:parameterized-query><![CDATA[INSERT INTO
    XX.XX_OE_OBJ_HDR
   (ATTRIBUTE1,
    MY_ID,
    MY_NUMBER)
    values (
    #[payload.id],
    XX.XX_HDR_SEQ,
    XX.XX_HDR_NUM_SEQ
    )]]></db:parameterized-query>
    </db:insert>
</code>```

I get the following error:

```<code>    org.mule.exception.DefaultMessagingExceptionStrategy:

    Message               : ORA-00984: column not allowed here
</code>```

答:
This is not Mule question. Oracle tells you that your sql is wrong.
Try to run it in sqlplus and you will see:

```<code>INSERT INTO
    XX.XX_OE_OBJ_HDR
   (ATTRIBUTE1,
    MY_ID,
    MY_NUMBER)
    values (
    abc,
    XX.XX_HDR_SEQ,
    XX.XX_HDR_NUM_SEQ
    )
</code>```

Perhaps ATTRIBUTE1 is a number, not a varchar. Cast this value to appropriate type.

Body:
I am trying to insert a database sequence into a table will this work?

     <db:insert config-ref="Oracle_Configuration" doc:name="INSERT Table">
                <db:parameterized-query><![CDATA[INSERT INTO
    XX.XX_OE_OBJ_HDR
   (ATTRIBUTE1,
    MY_ID,
    MY_NUMBER)
    values (
    #[payload.id],
    XX.XX_HDR_SEQ,
    XX.XX_HDR_NUM_SEQ
    )]]></db:parameterized-query>
    </db:insert>

I get the following error:

    org.mule.exception.DefaultMessagingExceptionStrategy:

    Message               : ORA-00984: column not allowed here

Body:
This is not Mule question. Oracle tells you that your sql is wrong.
Try to run it in sqlplus and you will see:

INSERT INTO
    XX.XX_OE_OBJ_HDR
   (ATTRIBUTE1,
    MY_ID,
    MY_NUMBER)
    values (
    abc,
    XX.XX_HDR_SEQ,
    XX.XX_HDR_NUM_SEQ
    )

Perhaps ATTRIBUTE1 is a number, not a varchar. Cast this value to appropriate type.


问:
Invert an array of booleans in JavaScript
I am trying to invert the values of a string of boolean values so that instead  of

inverted([true, false, true, false, true])

it is  [false, true, false, true, false]

So far I have come up with this:

```<code>function inverted(bools) {
    var inversion = [];
    var string= [];
    while(!bools) {
      string.push(bools);
    }
    return inversion;
}
</code>```

But my code is not working, any and all help will be much appreciated!

答:
You can use .map(), ! operator to invert Boolean value, return array of results

```<code>function inverted(bools) {
   return bools.map(function(bool) {return !bool})
}
</code>```

Body:
I am trying to invert the values of a string of boolean values so that instead  of

inverted([true, false, true, false, true])

it is  [false, true, false, true, false]

So far I have come up with this:

function inverted(bools) {
    var inversion = [];
    var string= [];
    while(!bools) {
      string.push(bools);
    }
    return inversion;
}

But my code is not working, any and all help will be much appreciated!

Body:
You can use .map(), ! operator to invert Boolean value, return array of results

function inverted(bools) {
   return bools.map(function(bool) {return !bool})
}


问:
How to create a multiple selection list?
Basically for part of my university project I want to ask students their availability for a study buddy app. I want them to be able to have multiple options which they can select as well.

Below is the current code I have -

```<code>chosen =""
chosen_list=[]
available_list = ['Monday Morning', 'Monday Afternoon', 'Monday Evening', 'Tuesday Morning', 'Tuesday Afternoon', 'Tuesday Evening']
print ('What is your availability?')
while chosen !="0":
    print ('Available times:' + available_list)
    chosen = input('Choose a time or 0 to quit')
    if chosen in available_list:
        chosen_list.append(chosen)
        print (chosen_list)
</code>```

But I'm coming up with this error:

Traceback (most recent call last):

File "G:/University/Intro to Programming/Assessment Project/Step
  1/.idea/step1new.py", line 132, in  What is enter code
  hereyour availability?
      print ('Available times:' + available_list) TypeError: Can't convert 'list' object to str implicitly

Process finished with exit code 1

Can someone please advise me on this?

答:
Your answer is in the error. Change the + to ,

```<code>print ('Available times:' , available_list)
</code>```

When using the + sign with the list, python is looking for a list to add its values to, however it is met with a str

Body:
Basically for part of my university project I want to ask students their availability for a study buddy app. I want them to be able to have multiple options which they can select as well.

Below is the current code I have -

chosen =""
chosen_list=[]
available_list = ['Monday Morning', 'Monday Afternoon', 'Monday Evening', 'Tuesday Morning', 'Tuesday Afternoon', 'Tuesday Evening']
print ('What is your availability?')
while chosen !="0":
    print ('Available times:' + available_list)
    chosen = input('Choose a time or 0 to quit')
    if chosen in available_list:
        chosen_list.append(chosen)
        print (chosen_list)

But I'm coming up with this error:

Traceback (most recent call last):

File "G:/University/Intro to Programming/Assessment Project/Step
  1/.idea/step1new.py", line 132, in  What is enter code
  hereyour availability?
      print ('Available times:' + available_list) TypeError: Can't convert 'list' object to str implicitly

Process finished with exit code 1

Can someone please advise me on this?

Body:
Your answer is in the error. Change the + to ,

print ('Available times:' , available_list)

When using the + sign with the list, python is looking for a list to add its values to, however it is met with a str


问:
Does OCMockito reset invocation count after a verify() call?
Here is the pseudocode of my unit test:

```<code>int invocationCount
given(mock).willDo {
    invocationCount++
    return value
}
doSomeProcessing()
verify(mock)
doSomeMoreProcessing()
verifyCount(mock, 2)
</code>```

At this point, invocationCount == 2, as expected. However, verifyCount fails, saying it was only called once. In addition, if I exclude the first verify call, the test passes as expected. It might be relevant to note that each verify call is capturing a new argument for assertion later.

My question is this: when the first verify() is called, is the mock's invocation count reset?  If this is not the case, what could be happening?

答:
Yes, verification only counts the matches since the last verification.

Further discussion can be found here: https://github.com/jonreid/OCMockito/issues/116

Body:
Here is the pseudocode of my unit test:

int invocationCount
given(mock).willDo {
    invocationCount++
    return value
}
doSomeProcessing()
verify(mock)
doSomeMoreProcessing()
verifyCount(mock, 2)

At this point, invocationCount == 2, as expected. However, verifyCount fails, saying it was only called once. In addition, if I exclude the first verify call, the test passes as expected. It might be relevant to note that each verify call is capturing a new argument for assertion later.

My question is this: when the first verify() is called, is the mock's invocation count reset?  If this is not the case, what could be happening?


答:
You can do it like this:

Convert the string to a JavaScript array using JSON.parse().

Invert all the booleans using Array.prototype.map();

Convert back to a string using JSON.stringify().

const booleans = "[true, false, true, false, true]";
const inverted = JSON.stringify(JSON.parse(booleans).map(b => !b));

console.log(inverted);```
</div>
</div>
</p>

<p>If by a "string", you actually mean an <em>array</em>, you don't need to convert to/from a string and can just do:</p>

```const booleans = [true, false, true, false, true];
const inverted = booleans.map(b => !b);
```

Title: Invert an array of booleans in JavaScript

Body:
You can do it like this:

Convert the string to a JavaScript array using JSON.parse().

Invert all the booleans using Array.prototype.map();

Convert back to a string using JSON.stringify().

const booleans = "[true, false, true, false, true]";
const inverted = JSON.stringify(JSON.parse(booleans).map(b => !b));

console.log(inverted);

If by a "string", you actually mean an array, you don't need to convert to/from a string and can just do:

const booleans = [true, false, true, false, true];
const inverted = booleans.map(b => !b);


问:
Strategy Pattern the right thing?
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

```<code>switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}
</code>```

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

```<code>abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}
</code>```

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static

答:
You do not need switch or if statements.

Just use delegation.

I.e. the concrete implementations of the abstract class will perform as needed (i.e. SoapV1, SoapV2 etc) and the client sets the appropriate instance in the object reference.

You have only a reference to the base class and the appropriate subclass is set by the client.  Your code just calls the methods of the base class (which in runtime is one of the derived implementations).  E.g. an example (DISCLAIMER:Have not compiled code. Only a sample)

```<code>public abstract class SoapHandler
{

    protected abstract string[] getData();
 }

public class SoapHandlerV1 extends SoapHandler
{

    public string[] getData(){
        //V1 implementation
    }

}
public class SoapHandlerV2 extends SoapHandler
{

    public string[] getData(){
        //V2 implementation
    }

}

public class SoapProcessor{

    public SoapHandler soapHandler;

    public setSoapHandler(SoapHandler h)
    {
                soapHandler = h;
    }

    public String[] getData(){
        //delegate to specific version
        soapHandler->getData();
    }
}

//in your code
SoapProcessor soap = new SoapProcessor();
soap.setSoapHandler(new SoapHandlerV1());
String[] soapData = soap.getData();//Will get the appropriate version
//use soap data
//do stuff
</code>```

Check the example of GoF for strategy to see what I mean, if it is not clear

Title: Strategy Pattern the right thing?

Body:
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static

Body:
You do not need switch or if statements.

Just use delegation.

I.e. the concrete implementations of the abstract class will perform as needed (i.e. SoapV1, SoapV2 etc) and the client sets the appropriate instance in the object reference.

You have only a reference to the base class and the appropriate subclass is set by the client.  Your code just calls the methods of the base class (which in runtime is one of the derived implementations).  E.g. an example (DISCLAIMER:Have not compiled code. Only a sample)

public abstract class SoapHandler
{

    protected abstract string[] getData();
 }

public class SoapHandlerV1 extends SoapHandler
{

    public string[] getData(){
        //V1 implementation
    }

}
public class SoapHandlerV2 extends SoapHandler
{

    public string[] getData(){
        //V2 implementation
    }

}

public class SoapProcessor{

    public SoapHandler soapHandler;

    public setSoapHandler(SoapHandler h)
    {
                soapHandler = h;
    }

    public String[] getData(){
        //delegate to specific version
        soapHandler->getData();
    }
}

//in your code
SoapProcessor soap = new SoapProcessor();
soap.setSoapHandler(new SoapHandlerV1());
String[] soapData = soap.getData();//Will get the appropriate version
//use soap data
//do stuff

Check the example of GoF for strategy to see what I mean, if it is not clear


问:
Accessing values from user-defined functions
I've got a (I think) pretty easy question that I need help with. I'm working on learning pointers with called user-defined functions in C.

I've got two functions, my main() and another which pulls certain data from a file, read_file(). Read_file() pulls data from a specified file - an integer, (coeff_num) and a series of values (coeff_values) - and prints out the data. Then main() is meant to reprint this data as a check, to ensure that it's being called correctly in order to perform further calculations.

My problem is this: everything is printing out fine in the read_file() function. While checking in main(), data_num is printing out fine, but data_values isn't.

The code (with some irrelevant bits edited out, mainly error checking stuff) is as follows:

```<code>int read_file(int *data_num, double **data_values, char *filename);
int main()
{

    int data_num;
    double **data_values;

    char *filename[] = {/*FILES*/};

    read_fule(&data_num, data_values, *filename);

    printf("Check Number:\n%u\n", data_num);
    printf("Check Values:\n);

    for(int i = 0; i<data_num; i++)
    {
        printf("%u\t", data_values[i]);
    }
return(0);
}
</code>```

and:

```<code>int read_file(int *data_num, double **data_values, char *filename)
{
    FILE * fp = fopen(filename, "rb");  //Opening file

/*  Error checking code here - see if file opens, find length
    return if not long enough, etc */

//Find number of values
    char buffer_n[4];
    fread(buffer_n, 4, 1, fp);
    int result = buffer_n[0]|(buffer_n[1] << 8)|(buffer_n[2] << 16)|(buffer_n[3] << 24);    //Change endian
    *data_num = result;

/* Instructed to allocate memory */
    data_values = malloc(8*result); //Allocating memory

//Reads data values
    fread(data_values, 8, result, fp);
//Prints results as float
     printf("Number of data values: %d \n", result);
    for(int i=0; i<result; i++)
    {
        printf("%0.3f\t", data_values[i]);
    }

    fclose(fp);
    return 1;
}
</code>```

I'm fairly certain that this is an issue with my pointers. For the program, I have to use malloc() when reading data_values, and read_file has to have the prototype of: int read_file(int *data_num, double **data_values, char *filename). Can someone give me some guidance about where I've messed up?

Cheers for any help, it'd be greatly appreciated.

答:
I set result = 30 as you told me, changed a few places, and I think now it works fine.

I think you don't need double** pointer, what you need is double* pointer.

And you need cast the void* to double*:

```<code>data_values = (double*)malloc(8*result); //Allocating memory
</code>```

This code works fine:

```<code>//data_values should be defined as double*
int read_file(int *data_num, double *data_values, char *filename)
{
    FILE * fp = fopen(filename, "rb");  //Opening file

/*  Error checking code here - see if file opens, find length
    return if not long enough, etc */

//Find number of values
    char buffer_n[4];
    size_t i;//added
    fread(buffer_n, 4, 1, fp);
    //int result = buffer_n[0]|(buffer_n[1] << 8)|(buffer_n[2] << 16)|(buffer_n[3] << 24);    //Change endian
    int result = 30;
    *data_num = result;

/* Instructed to allocate memory */
    data_values = (double*)malloc(8*result); //Allocating memory

//Reads data values
    fread(data_values, 8, result, fp);

//Prints results as float
    printf("Number of data values: %d \n", result);
    for(int i=0; i<result; i++)
    {
        printf("%0.3f\t", data_values[i]);
    }

    fclose(fp);
    return 1;
}
</code>```

Edit:

If you want to use double**, you can try this solution:

```<code>/* Instructed to allocate memory */
    data_values[0] = (double*)malloc(8 * result); //Allocating memory

//Reads data values
    fread(data_values[0], 8, result, fp);

//Prints results as float
    printf("Number of data values: %d \n", result);
    for(int i=0; i<result; i++)
    {
        printf("%0.3f\t", data_values[0][i]);
    }
</code>```

But you have to notice that this is not a form, this is still used as an array, so you may change it later according to your situation.

Body:
I've got a (I think) pretty easy question that I need help with. I'm working on learning pointers with called user-defined functions in C.

I've got two functions, my main() and another which pulls certain data from a file, read_file(). Read_file() pulls data from a specified file - an integer, (coeff_num) and a series of values (coeff_values) - and prints out the data. Then main() is meant to reprint this data as a check, to ensure that it's being called correctly in order to perform further calculations.

My problem is this: everything is printing out fine in the read_file() function. While checking in main(), data_num is printing out fine, but data_values isn't.

The code (with some irrelevant bits edited out, mainly error checking stuff) is as follows:

int read_file(int *data_num, double **data_values, char *filename);
int main()
{

    int data_num;
    double **data_values;

    char *filename[] = {/*FILES*/};

    read_fule(&data_num, data_values, *filename);

    printf("Check Number:\n%u\n", data_num);
    printf("Check Values:\n);

    for(int i = 0; i<data_num; i++)
    {
        printf("%u\t", data_values[i]);
    }
return(0);
}

and:

int read_file(int *data_num, double **data_values, char *filename)
{
    FILE * fp = fopen(filename, "rb");  //Opening file

/*  Error checking code here - see if file opens, find length
    return if not long enough, etc */

//Find number of values
    char buffer_n[4];
    fread(buffer_n, 4, 1, fp);
    int result = buffer_n[0]|(buffer_n[1] << 8)|(buffer_n[2] << 16)|(buffer_n[3] << 24);    //Change endian
    *data_num = result;

/* Instructed to allocate memory */
    data_values = malloc(8*result); //Allocating memory

//Reads data values
    fread(data_values, 8, result, fp);
//Prints results as float
     printf("Number of data values: %d \n", result);
    for(int i=0; i<result; i++)
    {
        printf("%0.3f\t", data_values[i]);
    }

    fclose(fp);
    return 1;
}

I'm fairly certain that this is an issue with my pointers. For the program, I have to use malloc() when reading data_values, and read_file has to have the prototype of: int read_file(int *data_num, double **data_values, char *filename). Can someone give me some guidance about where I've messed up?

Cheers for any help, it'd be greatly appreciated.

Body:
I set result = 30 as you told me, changed a few places, and I think now it works fine.

I think you don't need double** pointer, what you need is double* pointer.

And you need cast the void* to double*:

data_values = (double*)malloc(8*result); //Allocating memory

This code works fine:

//data_values should be defined as double*
int read_file(int *data_num, double *data_values, char *filename)
{
    FILE * fp = fopen(filename, "rb");  //Opening file

/*  Error checking code here - see if file opens, find length
    return if not long enough, etc */

//Find number of values
    char buffer_n[4];
    size_t i;//added
    fread(buffer_n, 4, 1, fp);
    //int result = buffer_n[0]|(buffer_n[1] << 8)|(buffer_n[2] << 16)|(buffer_n[3] << 24);    //Change endian
    int result = 30;
    *data_num = result;

/* Instructed to allocate memory */
    data_values = (double*)malloc(8*result); //Allocating memory

//Reads data values
    fread(data_values, 8, result, fp);

//Prints results as float
    printf("Number of data values: %d \n", result);
    for(int i=0; i<result; i++)
    {
        printf("%0.3f\t", data_values[i]);
    }

    fclose(fp);
    return 1;
}

Edit:

If you want to use double**, you can try this solution:

/* Instructed to allocate memory */
    data_values[0] = (double*)malloc(8 * result); //Allocating memory

//Reads data values
    fread(data_values[0], 8, result, fp);

//Prints results as float
    printf("Number of data values: %d \n", result);
    for(int i=0; i<result; i++)
    {
        printf("%0.3f\t", data_values[0][i]);
    }

But you have to notice that this is not a form, this is still used as an array, so you may change it later according to your situation.


问:
.Net pass a list of objects to JQuery as parameter
Hi I tried to pass a list of self-defined objects to JQuery as parameter and expect jQuery recognise it as the specific object and loop through it.
The class is:

```<code>public class PriceSummary{
        public string ItemName { get; set; }
        public string ItemPrice { get; set; } }
</code>```

The backend method is:

```<code>public void updatePriceSummary(List<PriceSummary> PriceSummaryList){
        ScriptManager.RegisterStartupScript(Page, GetType(), "changePriceList",
           "updatePriceList('" + PriceSummaryList + "');", true);}
</code>```

JQuery Method

```<code>function updatePriceList(PriceSummaryList) {
    PriceSummaryList.each(function ()
      {$('#ControlSummaryTitle').append('<tr id = "xxx"> <td class="SummaryItem">' +
      this['ItemName'] + '</td> <td class="SummaryPrice">' + this['ItemPrice'] +
      '</td></tr>');   })
;}
</code>```

However, the JQuery function couldn't recognise the parameter as a list and couldn't loop through it. The error message is:

0x800a01b6 - JavaScript runtime error: Object doesn't support property
  or method 'each'

Could anybody advise how to fix it?

答:
Just serialize your list to JSON before you send it across (almost identical issue)
Converting list of objects to json array </p>

Body:
Hi I tried to pass a list of self-defined objects to JQuery as parameter and expect jQuery recognise it as the specific object and loop through it.
The class is:

public class PriceSummary{
        public string ItemName { get; set; }
        public string ItemPrice { get; set; } }

The backend method is:

public void updatePriceSummary(List<PriceSummary> PriceSummaryList){
        ScriptManager.RegisterStartupScript(Page, GetType(), "changePriceList",
           "updatePriceList('" + PriceSummaryList + "');", true);}

JQuery Method

function updatePriceList(PriceSummaryList) {
    PriceSummaryList.each(function ()
      {$('#ControlSummaryTitle').append('
 ' +
      this['ItemName'] + '	 ' + this['ItemPrice'] +
      '
');   })
;}

However, the JQuery function couldn't recognise the parameter as a list and couldn't loop through it. The error message is:

0x800a01b6 - JavaScript runtime error: Object doesn't support property
  or method 'each'

Could anybody advise how to fix it?