问:
PHP CURL Couldn't connect to server
I'm trying to connect to a API with PHP7 CURL that return JSON data.
It's about the following URL's:

http://api.infcache.com/get.php?format=json&itemnumber=all

http://api.infcache.com/get.php?format=json&itemnumber=10550 (foreach item)

With the following PHP Code:

```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://api.infcache.com/get.php?format=json&itemnumber=all');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);

$products = curl_exec($ch);

if($errno = curl_errno($ch)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):\n {$error_message}";
}

curl_close($ch);
echo'```';
print_r($products);
echo '```';
</code>```

When I PING on the host in my Ubuntu Terminal on api.infcache.com it works.

I can also get the complete curl with the terminal:
curl -X GET 'http://api.infcache.com/get.php?fl&itemnumber=all'
The above returns all json but not in my php script

If I change the url in my curl to google.com there is full response. What is the issue with: api.infcache.com? And I already tried file_get_contents().

Can somebody tell me what to do next?

The error:

```<code>cURL error (7): Couldn't connect to server
</code>```

答: My solution was at my webhoster. They added the Ip-address to the whitelist. So when you have this error with CURL. Just check your network setting or Firewall.</p>

Title: PHP CURL Couldn't connect to server

Body:
I'm trying to connect to a API with PHP7 CURL that return JSON data.
It's about the following URL's:

http://api.infcache.com/get.php?format=json&itemnumber=all

http://api.infcache.com/get.php?format=json&itemnumber=10550 (foreach item)

With the following PHP Code:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://api.infcache.com/get.php?format=json&itemnumber=all');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);

$products = curl_exec($ch);

if($errno = curl_errno($ch)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):\n {$error_message}";
}

curl_close($ch);
echo'
';
print_r($products);
echo '
';

When I PING on the host in my Ubuntu Terminal on api.infcache.com it works.

I can also get the complete curl with the terminal:
curl -X GET 'http://api.infcache.com/get.php?fl&itemnumber=all'
The above returns all json but not in my php script

If I change the url in my curl to google.com there is full response. What is the issue with: api.infcache.com? And I already tried file_get_contents().

Can somebody tell me what to do next?

The error:

cURL error (7): Couldn't connect to server


来源: stackexchange

问:
javascript modify css class property while knowing only the class' name
Here's my css class:

```<code>.my-css-class-name
{
    display: block;
}
</code>```

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.

I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.

How do I get there, cross-browser (major ones) solution?

Edit #1:

I'm looking for compatibility with newer browsers.

答:
Following your response in the comment, if the element is being generated by Jquery, then the library is most likely installed.  Here is something you can try to select it via Jquery and change the require property.

```<code>$(document).ready( function(){
$('.my-class-name').css('display', 'block');
});
</code>```

Substituting 'block' for whatever setting you require.

If Jquery is included it should do what your require on page load.  You can also attach it to other events as well.

```<code>$(document).ready(function(){
$('.my-class-name').click(classClicked);
})

function classClicked(){
$(this).css('display','block')
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here's my css class:

.my-css-class-name
{
    display: block;
}

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.

I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.

How do I get there, cross-browser (major ones) solution?

Edit #1:

I'm looking for compatibility with newer browsers.

Body:
Following your response in the comment, if the element is being generated by Jquery, then the library is most likely installed.  Here is something you can try to select it via Jquery and change the require property.

$(document).ready( function(){
$('.my-class-name').css('display', 'block');
});

Substituting 'block' for whatever setting you require.

If Jquery is included it should do what your require on page load.  You can also attach it to other events as well.

$(document).ready(function(){
$('.my-class-name').click(classClicked);
})

function classClicked(){
$(this).css('display','block')
}


问:
Invalid Outside Procedures and Syntax in VBA/Excel
I'm new to programming/coding, and I'm having problems with my code.

I'm currently trying to write a macro in excel that will go through an excel document and insert a partially blank row on duplicate columns.

I'm currently using Excel 2010

So for example if the excel sheet contained:

```<code>Column A, Column B, Column C, Column D, Column E
       1     Apples        1        40      Blue
       1    Bananas        2        50       Red
       1    Oranges        3        60      Pink
       2   Cherries
       3      Kiwis
</code>```

Then the script would sort it into:

```<code>Column A, Column B, Column C, Column D, Column E
       1     Apples        1        40      Blue
       1    Bananas
       1    Oranges
       2   Cherries        2        50       Red
       3      Kiwis        3        60      Pink
</code>```

Thus sorting the data by Column A and C while also creating blank spaces in C, D, and E if the value in Column A does not equal the value found in Column C.

My code so far:

```<code>Sub Main()
Dim a As Long, c As Long
Dim objRange As Range
Dim strCIDCol1 As String, strCIDCol3 As String

a = 1 'row counter for Column A
c = 1 'row counter for Column C

Do Until ActiveSheet.Cells(a, 1) = ""
    'sets the loop to run until A1 is blank
    strCIDCol1 = ActiveSheet.Cells(a, 1)
        'sets the value of A1 as CIDCol1
    strCIDCol3 = ActiveSheet.Cells(c, 3)
        'sets the value of C1 as CIDCol3
    If (strCIDCol1 <> strCIDCol2) Then
        'runs until A(a) and C(c) are not equal
        Set objRange = ActiveSheet.Cells(c, 3).Range(Cells(c, 3), Cells(c, 5))
        objRange.Activate
            'Selects Columns C, D, and E
        objRange.Insert (xlShiftDown)
            'Inserts "Shift Row Down"
        strCIDCol1 = ActiveSheet.Cells(a + 1, 1)
            'moves on
    End If
    a = a + 1 'adds 1 to counter to move to next row
    c = c + 1 'adds 1 to counter to move to next row
Loop
End Sub
</code>```

I keep getting "invalid outside procedure" errors on

```<code>a = 1
c = 1
</code>```

and

```<code>a = a + 1
c = c + 1
</code>```

I'm also getting a 1004 error "insert method of range class failed" on

```<code>objRange.Insert (xlShiftDown)
</code>```

I have no idea what I'm doing with objRange. I saw the code online and tried to adapt it to fit what I needed. The way it was explained was that objRange was used to highlight the selected areas Column C, D, and E in this case. And then Insert would shift the cells down by inserting a row above the highlighted cells.

答:
```<code> If (strCIDCol1 <> strCIDCol2) Then
</code>```

You have never defined strCIDCoL2. I think you meant str CIDCol3 here.

```<code>Set objRange = ActiveSheet.Cells(c, 3).Range(Cells(c, 3), Cells(c, 5))
</code>```

This is wrong syntax for setting range. Try using:

```<code>Set objRange = Range(ActiveSheet.Cells(c,3).Range(Cells(c,3), Cells(c,5)))
</code>```

Also are you sure about using objRange.activate instead of objRange.select ?

ContentLicense: CC BY-SA 3.0

Body:
I'm new to programming/coding, and I'm having problems with my code.

I'm currently trying to write a macro in excel that will go through an excel document and insert a partially blank row on duplicate columns.

I'm currently using Excel 2010

So for example if the excel sheet contained:

Column A, Column B, Column C, Column D, Column E
       1     Apples        1        40      Blue
       1    Bananas        2        50       Red
       1    Oranges        3        60      Pink
       2   Cherries
       3      Kiwis

Then the script would sort it into:

Column A, Column B, Column C, Column D, Column E
       1     Apples        1        40      Blue
       1    Bananas
       1    Oranges
       2   Cherries        2        50       Red
       3      Kiwis        3        60      Pink

Thus sorting the data by Column A and C while also creating blank spaces in C, D, and E if the value in Column A does not equal the value found in Column C.

My code so far:

Sub Main()
Dim a As Long, c As Long
Dim objRange As Range
Dim strCIDCol1 As String, strCIDCol3 As String

a = 1 'row counter for Column A
c = 1 'row counter for Column C

Do Until ActiveSheet.Cells(a, 1) = ""
    'sets the loop to run until A1 is blank
    strCIDCol1 = ActiveSheet.Cells(a, 1)
        'sets the value of A1 as CIDCol1
    strCIDCol3 = ActiveSheet.Cells(c, 3)
        'sets the value of C1 as CIDCol3
    If (strCIDCol1 <> strCIDCol2) Then
        'runs until A(a) and C(c) are not equal
        Set objRange = ActiveSheet.Cells(c, 3).Range(Cells(c, 3), Cells(c, 5))
        objRange.Activate
            'Selects Columns C, D, and E
        objRange.Insert (xlShiftDown)
            'Inserts "Shift Row Down"
        strCIDCol1 = ActiveSheet.Cells(a + 1, 1)
            'moves on
    End If
    a = a + 1 'adds 1 to counter to move to next row
    c = c + 1 'adds 1 to counter to move to next row
Loop
End Sub

I keep getting "invalid outside procedure" errors on

a = 1
c = 1

and

a = a + 1
c = c + 1

I'm also getting a 1004 error "insert method of range class failed" on

objRange.Insert (xlShiftDown)

I have no idea what I'm doing with objRange. I saw the code online and tried to adapt it to fit what I needed. The way it was explained was that objRange was used to highlight the selected areas Column C, D, and E in this case. And then Insert would shift the cells down by inserting a row above the highlighted cells.

Body:
 If (strCIDCol1 <> strCIDCol2) Then

You have never defined strCIDCoL2. I think you meant str CIDCol3 here.

Set objRange = ActiveSheet.Cells(c, 3).Range(Cells(c, 3), Cells(c, 5))

This is wrong syntax for setting range. Try using:

Set objRange = Range(ActiveSheet.Cells(c,3).Range(Cells(c,3), Cells(c,5)))

Also are you sure about using objRange.activate instead of objRange.select ?


问:
List rendering from an external API with VueJS and Axios
I am having a bear of a time getting my VueJs app to render data from an external API. I've attempted to search for a similar issue, but everything I've found has been of no help.

I'm using the the USDA's nutrition database. When I run the code below, I can see through dev tools that my getNutrients function is making a successful call to the database when I click the button, yet my v-for element won't render any data. If I attempt to simply render nutrients from my data object, I'm able to render all of the raw JSON, just not when I try to render singular items within the v-for element.

Any help with getting the render to work would be greatly appreciated.

Thank you in advance

```<code><template>
  <div>
    <button @click="getNutrients">Click</button>
      <ul>
        <li v-for="nutrient in nutrients">{{nutrient.nutrient_id}}</li>
      </ul>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'home',
  data () {
    return {
      nutrients: {}
    }
  },
  methods: {
    getNutrients: function () {
      axios.get('https://api.nal.usda.gov/ndb/nutrients/?format=json&api_key=DEMO_KEY&nutrients=205&nutrients=204&nutrients=208&nutrients=269')
        .then(response => {this.nutrients = response.data})
    }
  }
}
</script>
</code>```

If it helps, I'm using the Vue Webpack template through the Vue-CLI.

答:
The API's returning a report object, which contains an array of foods, each of which contains an array of nutrients, so you'd need to loop through the foods, then through the nutrients in each food:

```<code><ul>
    <li v-for="food in foods">
        <h2>{{food.name}}</h2>
        <ul>
              <li v-for="nutrient in food.nutrients">{{nutrient.nutrient_id}}</li>
        </ul>
    </li>
</ul>

axios.get(url).then(response => {
    this.foods = response.data.report.foods
})
</code>```

Body:
I am having a bear of a time getting my VueJs app to render data from an external API. I've attempted to search for a similar issue, but everything I've found has been of no help.

I'm using the the USDA's nutrition database. When I run the code below, I can see through dev tools that my getNutrients function is making a successful call to the database when I click the button, yet my v-for element won't render any data. If I attempt to simply render nutrients from my data object, I'm able to render all of the raw JSON, just not when I try to render singular items within the v-for element.

Any help with getting the render to work would be greatly appreciated.

Thank you in advance

<template>

    <button @click="getNutrients">Click</button>

{{nutrient.nutrient_id}}

</template>

If it helps, I'm using the Vue Webpack template through the Vue-CLI.

Body:
The API's returning a report object, which contains an array of foods, each of which contains an array of nutrients, so you'd need to loop through the foods, then through the nutrients in each food:

<ul>
    <li v-for="food in foods">
        <h2>{{food.name}}</h2>
        <ul>
              <li v-for="nutrient in food.nutrients">{{nutrient.nutrient_id}}</li>
        </ul>
    </li>
</ul>

axios.get(url).then(response => {
    this.foods = response.data.report.foods
})


问:
Checked change event is not firing
I want to enable and disable textfields on checked change event but this event is not firing.
Following is my radio button code

```<code><asp:RadioButton ID="submitter" runat="server" GroupName="rd2" OnCheckedChanged="submitter_CheckedChanged" Text="Submitter" />

        <asp:RadioButton ID="following" runat="server" ForeColor="Black" Text="Following" GroupName="rd2" OnCheckedChanged="following_CheckedChanged" />
</code>```

Following is my checked change event code

```<code>protected void following_CheckedChanged(object sender, EventArgs e)
    {
        if (submitter.Checked == true)
        {
            contactName.Enabled = false;
            Contactmail.Enabled = false;
            Response.Write("<script LANGUAGE='JavaScript' >alert('following event submitter check')</script>");
        }
       if (following.Checked == true)
        {
            contactName.Enabled = true;
            Contactmail.Enabled = true;
            Response.Write("<script LANGUAGE='JavaScript' >alert('following event following check')</script>");
        }
    }

    protected void submitter_CheckedChanged(object sender, EventArgs e)
    {
        if (submitter.Checked == true)
        {
            contactName.Enabled = false;
            Contactmail.Enabled = false;
            Response.Write("<script LANGUAGE='JavaScript' >alert('submitter event submitter check')</script>");
        }
        if (following.Checked == true)
        {
            contactName.Enabled = true;
            Contactmail.Enabled = true;
            Response.Write("<script LANGUAGE='JavaScript' >alert('submitter event following check')</script>");
        }
</code>```

Please tell me where is problem. thanks

答:
set AutoPostBack="true"

Postback means sending Data to server. It will execute server side events.
for more Details Click Here

```<code><asp:RadioButton ID="submitter" runat="server" GroupName="rd2" OnCheckedChanged="submitter_CheckedChanged" Text="Submitter" AutoPostBack="true" />

        <asp:RadioButton ID="following" runat="server" ForeColor="Black" Text="Following" GroupName="rd2" OnCheckedChanged="following_CheckedChanged" AutoPostBack="true" />
</code>```

Title: Checked change event is not firing

Body:
I want to enable and disable textfields on checked change event but this event is not firing.
Following is my radio button code

<asp:RadioButton ID="submitter" runat="server" GroupName="rd2" OnCheckedChanged="submitter_CheckedChanged" Text="Submitter" />

        <asp:RadioButton ID="following" runat="server" ForeColor="Black" Text="Following" GroupName="rd2" OnCheckedChanged="following_CheckedChanged" />

Following is my checked change event code

protected void following_CheckedChanged(object sender, EventArgs e)
    {
        if (submitter.Checked == true)
        {
            contactName.Enabled = false;
            Contactmail.Enabled = false;
            Response.Write("");
        }
       if (following.Checked == true)
        {
            contactName.Enabled = true;
            Contactmail.Enabled = true;
            Response.Write("");
        }
    }

    protected void submitter_CheckedChanged(object sender, EventArgs e)
    {
        if (submitter.Checked == true)
        {
            contactName.Enabled = false;
            Contactmail.Enabled = false;
            Response.Write("");
        }
        if (following.Checked == true)
        {
            contactName.Enabled = true;
            Contactmail.Enabled = true;
            Response.Write("");
        }

Please tell me where is problem. thanks

Body:
set AutoPostBack="true"

Postback means sending Data to server. It will execute server side events.
for more Details Click Here

<asp:RadioButton ID="submitter" runat="server" GroupName="rd2" OnCheckedChanged="submitter_CheckedChanged" Text="Submitter" AutoPostBack="true" />
                        &nbsp;&nbsp;
        <asp:RadioButton ID="following" runat="server" ForeColor="Black" Text="Following" GroupName="rd2" OnCheckedChanged="following_CheckedChanged" AutoPostBack="true" />


答:
You need to add AutoPostBack="true".

Change the aspx code to as below:

```<code><asp:RadioButton AutoPostBack="true" ID="submitter" runat="server" GroupName="rd2" OnCheckedChanged="submitter_CheckedChanged" Text="Submitter" />

<asp:RadioButton AutoPostBack="true" ID="following" runat="server" ForeColor="Black" Text="Following" GroupName="rd2" OnCheckedChanged="following_CheckedChanged" />
</code>```

Title: Checked change event is not firing

Body:
You need to add AutoPostBack="true".

Change the aspx code to as below:

<asp:RadioButton AutoPostBack="true" ID="submitter" runat="server" GroupName="rd2" OnCheckedChanged="submitter_CheckedChanged" Text="Submitter" />
                        &nbsp;&nbsp;
<asp:RadioButton AutoPostBack="true" ID="following" runat="server" ForeColor="Black" Text="Following" GroupName="rd2" OnCheckedChanged="following_CheckedChanged" />


问:
std::fstream crashes after main while using pre-allocated memory
I currently have a std::ofstream being created on the stack, and when it allocates off a global operator new that assigns it memory from a pre-allocated buffer the program will crash after main completes citing std::locale0 : line 59. Read Access Violation. nodeptr was 0x... as the program crash point. nodeptr's memory address is a real address. I have no idea why this is happening, and I can only assume it was because I misunderstand what the allocations are actually doing.

This behaviour happens on a release build tested on MSVC Version 19.10.25019 x86, building on debug has the program complete without a crash. Dr. Memory reports no leaks in debug mode.

Minimal Code:

```<code>#include <fstream>
#include <cstdlib>

std::uint8_t *byte = static_cast<std::uint8_t*>(malloc(134217728)); // 134217728 = 128 MiB

void *operator new(size_t bytes) throw(std::bad_alloc)
    {
        return static_cast<void*>(byte); // Tested empirically, and this is only called once so this shouldnt be a cause of a problem
    }

void operator delete(void *memory) throw()
    {}

int main()
    {
        std::ofstream out("abc");

        free(byte);
    }
</code>```

答: It appears as it is a Visual Studio bug regarding custom allocations and std::locale.

Body:
I currently have a std::ofstream being created on the stack, and when it allocates off a global operator new that assigns it memory from a pre-allocated buffer the program will crash after main completes citing std::locale0 : line 59. Read Access Violation. nodeptr was 0x... as the program crash point. nodeptr's memory address is a real address. I have no idea why this is happening, and I can only assume it was because I misunderstand what the allocations are actually doing.

This behaviour happens on a release build tested on MSVC Version 19.10.25019 x86, building on debug has the program complete without a crash. Dr. Memory reports no leaks in debug mode.

Minimal Code:

#include <fstream>
#include <cstdlib>

std::uint8_t *byte = static_cast<std::uint8_t*>(malloc(134217728)); // 134217728 = 128 MiB

void *operator new(size_t bytes) throw(std::bad_alloc)
    {
        return static_cast<void*>(byte); // Tested empirically, and this is only called once so this shouldnt be a cause of a problem
    }

void operator delete(void *memory) throw()
    {}

int main()
    {
        std::ofstream out("abc");

        free(byte);
    }


问:
How to fix Slow Rendering (Android vitals)
I have an app that is listed as in the bottom 25% in the new Google Play Console - Android vitals section for Slow Rendering. I am concerned of this because of such articles that seem to say Google Play may penalize your app in the Play Store rankings if you fall in the bottom 25%.

However, it seems impossible to improve this metric for my app. It plays music and has a SeekBar and TextView which is updated every 250ms as any music player would. I made the minimum basic program to demonstrate:

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

    int count;
    SeekBar seekBar;
    TextView textView;

    Runnable runnable =
            new Runnable() {
                @Override
                public void run() {
                    textView.setText(Integer.toString(count));
                    seekBar.setProgress(count);
                    ++count;
                    seekBar.postDelayed(runnable, 250);
                }
            };

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

        seekBar = (SeekBar) findViewById(R.id.seek);
        textView = (TextView) findViewById(R.id.text);
        seekBar.post(runnable);
    }
}
</code>```

Full project here: https://github.com/svenoaks/SlowRendering.git

When I run this program on hardware similar to the Nexus devices, I get these results for a

adb shell dumpsys gfxinfo com.example.xyz.slowrendering command:

```<code>Stats since: 19222191084749ns
Total frames rendered: 308
Janky frames: 290 (94.16%)
90th percentile: 32ms
95th percentile: 36ms
99th percentile: 44ms
Number Missed Vsync: 2
Number High input latency: 0
Number Slow UI thread: 139
Number Slow bitmap uploads: 0
Number Slow issue draw commands: 283
</code>```

This would mean almost all my frames taking >16ms to render, I guess due to the periodic nature of the updating. All other music player apps I have tested also have this Slow Rendering problem as far as I can see. I fear Google's algorithm ruining my app ranking, is there any way I can improve my score?

答:
I checked your code. Not sure if this is the actual code or if you have more to this. In any case I will draw attention to some of the Rendering issues in android.

1. OverDraw

Overdraw is where you waste GPU processing time by coloring in pixels that only get colored in again by something else. These can be common if you have added a background to your parent container layout and then the children are also added a background or if you have added a common background on you styles file for the application theme and then added backgrounds to the rest of the xml layout files you have created.

The causes for the overdraw can be anything, try checking your code for this. There is a developer tool installed in all mobile devices to check Overdraw in developer options. Here is the official documentation for overdraw.

2. View hierarchy

To render each view, Android goes through three stages:

1.measure

2.layout

3.draw

The time it takes Android to complete these stages is proportional to the number of views in your hierarchy. I see in your layout file that you have constraint layout which includes a linear layout. I don't see the use of this. Constraint layout was introduced to help developers reduce view hierarchy. Reduce the number of childs a particular layout can have. There is also a tool to help you with this. Here is the official android guide to it.
Try these steps to figure out the GPU rendering issues.

Body:
I have an app that is listed as in the bottom 25% in the new Google Play Console - Android vitals section for Slow Rendering. I am concerned of this because of such articles that seem to say Google Play may penalize your app in the Play Store rankings if you fall in the bottom 25%.

However, it seems impossible to improve this metric for my app. It plays music and has a SeekBar and TextView which is updated every 250ms as any music player would. I made the minimum basic program to demonstrate:

public class MainActivity extends AppCompatActivity {

    int count;
    SeekBar seekBar;
    TextView textView;

    Runnable runnable =
            new Runnable() {
                @Override
                public void run() {
                    textView.setText(Integer.toString(count));
                    seekBar.setProgress(count);
                    ++count;
                    seekBar.postDelayed(runnable, 250);
                }
            };

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

        seekBar = (SeekBar) findViewById(R.id.seek);
        textView = (TextView) findViewById(R.id.text);
        seekBar.post(runnable);
    }
}

Full project here: https://github.com/svenoaks/SlowRendering.git

When I run this program on hardware similar to the Nexus devices, I get these results for a

adb shell dumpsys gfxinfo com.example.xyz.slowrendering command:

Stats since: 19222191084749ns
Total frames rendered: 308
Janky frames: 290 (94.16%)
90th percentile: 32ms
95th percentile: 36ms
99th percentile: 44ms
Number Missed Vsync: 2
Number High input latency: 0
Number Slow UI thread: 139
Number Slow bitmap uploads: 0
Number Slow issue draw commands: 283

This would mean almost all my frames taking >16ms to render, I guess due to the periodic nature of the updating. All other music player apps I have tested also have this Slow Rendering problem as far as I can see. I fear Google's algorithm ruining my app ranking, is there any way I can improve my score?


问:
Scanner only picking up certain input
I am making a Blackjack program using a Card and Deck class. Everything works except for one method in the main Class. Before every round of Blackjack, the player is asked if he would like to keep the same bet amount, change the bet, or exit the program (sentinel value of 0). The getBet() method is called at least twice(it could be called more than twice if this problem didn't stop the program). However, unlike the first time the method is called, the method only recognizes and acts on input of the sentinel. If you try and change the number or press enter, the player gets stuck in an endless loop on the console screen.

Why does the getBet() method, when called a second time, not return any input unless 0 is the value entered? All 3 classes are provided below. I would have provided a Minimal, Complete, and Verifiable example, but, I thought the reader might prefer to run my actual code and, since the getBet() method seemed free of errors, I couldn't narrow down what the problem was.

CARD CLASS

```<code>import java.util.Random;

public class Card
{
    private String suit, valueString;
    private int value, valueNum, suitNum;
    private final String[] SUITS = {"Clubs", "Diamonds", "Hearts", "Spades"};
    private final int[] VALUES = {2,3,4,5,6,7,8,9,10};
    private static int tot = 0;
    private static boolean[][] duplicateCheck = new boolean[4][13];//to see if suit/value pair has been used yet
    Random rand = new Random();

    public Card()
    {
        suit = createSuit();
        value = createValue();
        valueString = createValueString();

        tot += value;
    }
    private String createSuit()
    {
        String suit;

        do
        {
            suitNum = rand.nextInt((3 - 0) + 1) + 0;
            suit = SUITS[suitNum];
            valueNum = rand.nextInt((12 - 0) + 1) + 0;
        }
        while(duplicateCheck[suitNum][valueNum]);

        duplicateCheck[suitNum][valueNum] = true;

        return suit;
    }
    private int createValue()
    {
        int value;

        if(valueNum >= 9 && valueNum <= 11)
            value = 10;
        else if(valueNum == 12)
        {
            if(tot + 11 > 21)
                value = 1;
            else
                value = 11;
        }
        else
            value = VALUES[valueNum];

        return value;
    }
    private String createValueString()
    {
        String valueString;

        if(valueNum >= 9 && valueNum <= 11)
        {
            switch(valueNum)
            {
                case 9:
                    valueString = "Jack";
                    break;
                case 10:
                    valueString = "King";
                    break;
                case 11:
                    valueString = "Queen";
                    break;
                default:
                    valueString = Integer.toString(valueNum);//not really needed
                    break;
            }
        }
        else if(valueNum == 12)
            valueString = "Ace";
        else
            valueString = Integer.toString(VALUES[valueNum]);

        return valueString;
    }
    public String getSuit()
    {
        return suit;
    }
    public int getValue()
    {
        return value;
    }
    public String getValueString()
    {
        return valueString;
    }
    @Override
    public String toString()
    {
        String str;

        str = valueString + " (" + suit + ")";

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

DECK CLASS

```<code>import java.util.ArrayList;

public class Deck
{
    ArrayList <Card> deck = new ArrayList<>();
    private static int drawCard = 0;

    public Deck()//creates shufffled deck (each card is made at random)
    {
        for(int x = 0; x < 52; x++)
        {
            deck.add(new Card());
        }
    }
    public Card draw()
    {
        Card drawn;

        drawn = deck.get(drawCard);
        drawCard++;

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

MAIN CLASS AND METHOD

```<code>import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;

public class Blackjack
{
    public static void main(String[] args)
    {
        Deck newDeck;
        Card c = null;
        String name;
        int bal = 1000, currentBet = 25;
        char move = 'h';//hit by default
        int[] handValues = new int[2];
        ArrayList<Card> dealer = new ArrayList<>();
        ArrayList<Card> player = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#,###");

        name = getName();
        System.out.println(name + " has $" + df.format(bal));
        currentBet = getBet(currentBet);

        while(currentBet != 0 && bal > 0)//determines when program ends
        {
            newDeck = new Deck();

            //player 2 cards, dealer 1 card
            firstDeal(c, newDeck, player, dealer, name, handValues, currentBet);
            System.out.println();
            move = nextMove();

            //loop: player hits until bust, stand, or hits 21
            while(handValues[0] != 21 && handValues[0] < 21 && move != 's')
            {
                System.out.println("\nBet: $" + df.format(currentBet));
                dealerStand(dealer, handValues);
                playerHit(c, newDeck, player, name, handValues);
                if(handValues[0] != 21 && handValues[0] < 21 && move != 's')
                    move = nextMove();
            }

            if(move == 's')//player stands
            {
                //loop: dealer hits until bust or stand
                while(handValues[1] < 17)
                {
                    System.out.println("\nBet: $" + df.format(currentBet));
                    dealerHit(c, newDeck, dealer, handValues);
                    playerStand(name, player, handValues);
                }

                if(handValues[1] >= 17 && handValues[1] <= 20 &&
                        handValues[1] > handValues[0])//dealer wins
                {
                    System.out.println("Dealer wins\n");
                    bal -= currentBet;
                }
                if(handValues[1] >= 17 && handValues[1] <= 20 &&
                        handValues[1] < handValues[0])//player wins
                {
                    System.out.println(name + " wins\n");
                    bal += currentBet;
                }
                if(handValues[1] > 21)//dealer bust, player wins
                {
                    System.out.println("Dealer bust\n");
                    bal += currentBet;
                }
                if(handValues[0] == handValues[1])//push
                    System.out.println("The game is a push\n");
            }
            else if(handValues[0] > 21)//player busts
            {
                System.out.println(name + " bust\n");
                bal -= currentBet;
            }
            else if(handValues[0] == 21)//player wins
            {
                System.out.println(name + " wins\n");
                bal += currentBet;
            }
            else if(handValues[0] == handValues[1])//both tie at 21
                System.out.println("The game is a push\n");

            System.out.println(name + " has $" + df.format(bal));
            currentBet = getBet(currentBet);//does stuff with 0, but not enter or new num
        }
    }
    public static String getName()
    {
        Scanner input = new Scanner(System.in);
        String name;

        System.out.print("Name? ");
        name = input.nextLine();

        return name;
    }
    public static int getBet(int currentBet)
    {
        Scanner input = new Scanner(System.in);
        String temp;

        System.out.print("Bet? (0 to quit, Enter to stay at $" + currentBet + ", or a new number to change bet) ");
        temp = input.nextLine();

        if(!temp.isEmpty())
            currentBet = Integer.parseInt(temp);

        return currentBet;
    }
    public static char nextMove()
    {
        Scanner input = new Scanner(System.in);
        String moveStr;
        char move;

        System.out.print("Move? (\"h\" for hit/\"s\" for stand) ");
        moveStr = input.nextLine();
        /*while(moveStr.charAt(0) != 'h' || moveStr.charAt(0) != 's')
        {
            System.out.println("Invalid choice. Enter either \"h\" or \"s\".");     //input validation
            moveStr = input.nextLine();
        }*/
        move = moveStr.charAt(0);

        return move;
    }
    public static int[] firstDeal(Card c, Deck newDeck, ArrayList player,
            ArrayList dealer, String name, int[] handValues, int currentBet)
    {
        DecimalFormat df = new DecimalFormat("#,###");
        System.out.println("\nBet: $" + df.format(currentBet));

        //dealer 1 card
        c = newDeck.draw();
        dealer.add(c);
        System.out.print("Dealer's hand: ");
        for(int cardNum = 0; cardNum < dealer.size(); cardNum++)
            System.out.print(dealer.get(cardNum) + "  ");
        System.out.println();
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[1] >= 11)
                handValues[1] += 1;
            else
                handValues[1] += 11;
        }
        else
            handValues[1] += c.getValue();
        System.out.print("Value: " + handValues[1] + "\n");

        //player 2 cards
        c = newDeck.draw();
        player.add(c);
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[0] >= 11)
                handValues[0] += 1;
            else
                handValues[0] += 11;
        }
        else
            handValues[0] += c.getValue();
        c = newDeck.draw();
        player.add(c);
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[0] >= 11)
                handValues[0] += 1;
            else
                handValues[0] += 11;
        }
        else
            handValues[0] += c.getValue();
        System.out.print(name + "'s hand: ");
        for(int cardNum = 0; cardNum < player.size(); cardNum++)
            System.out.print(player.get(cardNum) + "  ");
        System.out.println();
        System.out.print("Value: " + handValues[0] + "\n");

        return handValues;
    }
    public static int playerHit(Card c, Deck newDeck, ArrayList player,
            String name, int[] handValues)
    {
        c = newDeck.draw();
        player.add(c);
        System.out.print(name + "'s hand: ");
        for(int cardNum = 0; cardNum < player.size(); cardNum++)
            System.out.print(player.get(cardNum) + "  ");
        System.out.println();
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[0] >= 11)
                handValues[0] += 1;
            else
                handValues[0] += 11;
        }
        else
            handValues[0] += c.getValue();
        System.out.println("Value: " + handValues[0] + "\n");

        return handValues[0];
    }
    public static void playerStand(String name, ArrayList player,
            int[] handValues)
    {
        System.out.println(name + "'s hand: ");
        for(int cardNum = 0; cardNum < player.size(); cardNum++)
            System.out.print(player.get(cardNum) + "  ");
        System.out.println();
        System.out.println("Value: " + handValues[0] + "\n");
    }
    public static int[] dealerHit(Card c, Deck newDeck, ArrayList dealer,
            int[] handValues)
    {
        c = newDeck.draw();
        dealer.add(c);
        System.out.print("Dealer's hand: ");
        for(int cardNum = 0; cardNum < dealer.size(); cardNum++)
            System.out.print(dealer.get(cardNum) + "  ");
        System.out.println();
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[1] >= 11)
                handValues[1] += 1;
            else
                handValues[1] += 11;
        }
        else
            handValues[1] += c.getValue();
        System.out.println("Value: " + handValues[1]);

        return handValues;
    }
    public static int[] dealerStand(ArrayList dealer, int[] handValues)
    {
        System.out.print("Dealers's hand: ");
        for(int cardNum = 0; cardNum < dealer.size(); cardNum++)
            System.out.print(dealer.get(cardNum) + "  ");
        System.out.println();
        System.out.println("Value: " + handValues[1]);

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

答:
The problem is not with the Scanner!

I plugged this code into a debugger, and it gets stuck in an infinite loop in the Card.createSuit() function. The duplicateCheck dictionary gets filled with true so it can never pick the next suit.

Note: duplicateCheck is declared as static, so it will maintain its instance between "deals". duplicateCheck should probably not be inside the Card class, but in the Deck class instead, and NOT static. That way, each Deck instance will have a reference to which cards have been used. You can still call new Card() to generate a random card, but check the suit and value of the new Card instance inside the Deck instance.

Another note: this will still be a very busy deck generator since you are always generating a random card each time, which may be already part of the deck. I would recommend maybe having some Lists (or Sets) of "available" cards, and each time you want a card, you pick a random index in that List to get the card value/suit. Then remove that item from the List so that it is not available for the next card selection. I will leave that all up to you though. Have fun!

Title: Scanner only picking up certain input

Body:
I am making a Blackjack program using a Card and Deck class. Everything works except for one method in the main Class. Before every round of Blackjack, the player is asked if he would like to keep the same bet amount, change the bet, or exit the program (sentinel value of 0). The getBet() method is called at least twice(it could be called more than twice if this problem didn't stop the program). However, unlike the first time the method is called, the method only recognizes and acts on input of the sentinel. If you try and change the number or press enter, the player gets stuck in an endless loop on the console screen.

Why does the getBet() method, when called a second time, not return any input unless 0 is the value entered? All 3 classes are provided below. I would have provided a Minimal, Complete, and Verifiable example, but, I thought the reader might prefer to run my actual code and, since the getBet() method seemed free of errors, I couldn't narrow down what the problem was.

CARD CLASS

import java.util.Random;

public class Card
{
    private String suit, valueString;
    private int value, valueNum, suitNum;
    private final String[] SUITS = {"Clubs", "Diamonds", "Hearts", "Spades"};
    private final int[] VALUES = {2,3,4,5,6,7,8,9,10};
    private static int tot = 0;
    private static boolean[][] duplicateCheck = new boolean[4][13];//to see if suit/value pair has been used yet
    Random rand = new Random();

    public Card()
    {
        suit = createSuit();
        value = createValue();
        valueString = createValueString();

        tot += value;
    }
    private String createSuit()
    {
        String suit;

        do
        {
            suitNum = rand.nextInt((3 - 0) + 1) + 0;
            suit = SUITS[suitNum];
            valueNum = rand.nextInt((12 - 0) + 1) + 0;
        }
        while(duplicateCheck[suitNum][valueNum]);

        duplicateCheck[suitNum][valueNum] = true;

        return suit;
    }
    private int createValue()
    {
        int value;

        if(valueNum >= 9 && valueNum <= 11)
            value = 10;
        else if(valueNum == 12)
        {
            if(tot + 11 > 21)
                value = 1;
            else
                value = 11;
        }
        else
            value = VALUES[valueNum];

        return value;
    }
    private String createValueString()
    {
        String valueString;

        if(valueNum >= 9 && valueNum <= 11)
        {
            switch(valueNum)
            {
                case 9:
                    valueString = "Jack";
                    break;
                case 10:
                    valueString = "King";
                    break;
                case 11:
                    valueString = "Queen";
                    break;
                default:
                    valueString = Integer.toString(valueNum);//not really needed
                    break;
            }
        }
        else if(valueNum == 12)
            valueString = "Ace";
        else
            valueString = Integer.toString(VALUES[valueNum]);

        return valueString;
    }
    public String getSuit()
    {
        return suit;
    }
    public int getValue()
    {
        return value;
    }
    public String getValueString()
    {
        return valueString;
    }
    @Override
    public String toString()
    {
        String str;

        str = valueString + " (" + suit + ")";

        return str;
    }
}

DECK CLASS

import java.util.ArrayList;

public class Deck
{
    ArrayList <Card> deck = new ArrayList<>();
    private static int drawCard = 0;

    public Deck()//creates shufffled deck (each card is made at random)
    {
        for(int x = 0; x < 52; x++)
        {
            deck.add(new Card());
        }
    }
    public Card draw()
    {
        Card drawn;

        drawn = deck.get(drawCard);
        drawCard++;

        return drawn;
    }
}

MAIN CLASS AND METHOD

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;

public class Blackjack
{
    public static void main(String[] args)
    {
        Deck newDeck;
        Card c = null;
        String name;
        int bal = 1000, currentBet = 25;
        char move = 'h';//hit by default
        int[] handValues = new int[2];
        ArrayList<Card> dealer = new ArrayList<>();
        ArrayList<Card> player = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#,###");

        name = getName();
        System.out.println(name + " has $" + df.format(bal));
        currentBet = getBet(currentBet);

        while(currentBet != 0 && bal > 0)//determines when program ends
        {
            newDeck = new Deck();

            //player 2 cards, dealer 1 card
            firstDeal(c, newDeck, player, dealer, name, handValues, currentBet);
            System.out.println();
            move = nextMove();

            //loop: player hits until bust, stand, or hits 21
            while(handValues[0] != 21 && handValues[0] < 21 && move != 's')
            {
                System.out.println("\nBet: $" + df.format(currentBet));
                dealerStand(dealer, handValues);
                playerHit(c, newDeck, player, name, handValues);
                if(handValues[0] != 21 && handValues[0] < 21 && move != 's')
                    move = nextMove();
            }

            if(move == 's')//player stands
            {
                //loop: dealer hits until bust or stand
                while(handValues[1] < 17)
                {
                    System.out.println("\nBet: $" + df.format(currentBet));
                    dealerHit(c, newDeck, dealer, handValues);
                    playerStand(name, player, handValues);
                }

                if(handValues[1] >= 17 && handValues[1] <= 20 &&
                        handValues[1] > handValues[0])//dealer wins
                {
                    System.out.println("Dealer wins\n");
                    bal -= currentBet;
                }
                if(handValues[1] >= 17 && handValues[1] <= 20 &&
                        handValues[1] < handValues[0])//player wins
                {
                    System.out.println(name + " wins\n");
                    bal += currentBet;
                }
                if(handValues[1] > 21)//dealer bust, player wins
                {
                    System.out.println("Dealer bust\n");
                    bal += currentBet;
                }
                if(handValues[0] == handValues[1])//push
                    System.out.println("The game is a push\n");
            }
            else if(handValues[0] > 21)//player busts
            {
                System.out.println(name + " bust\n");
                bal -= currentBet;
            }
            else if(handValues[0] == 21)//player wins
            {
                System.out.println(name + " wins\n");
                bal += currentBet;
            }
            else if(handValues[0] == handValues[1])//both tie at 21
                System.out.println("The game is a push\n");

            System.out.println(name + " has $" + df.format(bal));
            currentBet = getBet(currentBet);//does stuff with 0, but not enter or new num
        }
    }
    public static String getName()
    {
        Scanner input = new Scanner(System.in);
        String name;

        System.out.print("Name? ");
        name = input.nextLine();

        return name;
    }
    public static int getBet(int currentBet)
    {
        Scanner input = new Scanner(System.in);
        String temp;

        System.out.print("Bet? (0 to quit, Enter to stay at $" + currentBet + ", or a new number to change bet) ");
        temp = input.nextLine();

        if(!temp.isEmpty())
            currentBet = Integer.parseInt(temp);

        return currentBet;
    }
    public static char nextMove()
    {
        Scanner input = new Scanner(System.in);
        String moveStr;
        char move;

        System.out.print("Move? (\"h\" for hit/\"s\" for stand) ");
        moveStr = input.nextLine();
        /*while(moveStr.charAt(0) != 'h' || moveStr.charAt(0) != 's')
        {
            System.out.println("Invalid choice. Enter either \"h\" or \"s\".");     //input validation
            moveStr = input.nextLine();
        }*/
        move = moveStr.charAt(0);

        return move;
    }
    public static int[] firstDeal(Card c, Deck newDeck, ArrayList player,
            ArrayList dealer, String name, int[] handValues, int currentBet)
    {
        DecimalFormat df = new DecimalFormat("#,###");
        System.out.println("\nBet: $" + df.format(currentBet));

        //dealer 1 card
        c = newDeck.draw();
        dealer.add(c);
        System.out.print("Dealer's hand: ");
        for(int cardNum = 0; cardNum < dealer.size(); cardNum++)
            System.out.print(dealer.get(cardNum) + "  ");
        System.out.println();
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[1] >= 11)
                handValues[1] += 1;
            else
                handValues[1] += 11;
        }
        else
            handValues[1] += c.getValue();
        System.out.print("Value: " + handValues[1] + "\n");

        //player 2 cards
        c = newDeck.draw();
        player.add(c);
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[0] >= 11)
                handValues[0] += 1;
            else
                handValues[0] += 11;
        }
        else
            handValues[0] += c.getValue();
        c = newDeck.draw();
        player.add(c);
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[0] >= 11)
                handValues[0] += 1;
            else
                handValues[0] += 11;
        }
        else
            handValues[0] += c.getValue();
        System.out.print(name + "'s hand: ");
        for(int cardNum = 0; cardNum < player.size(); cardNum++)
            System.out.print(player.get(cardNum) + "  ");
        System.out.println();
        System.out.print("Value: " + handValues[0] + "\n");

        return handValues;
    }
    public static int playerHit(Card c, Deck newDeck, ArrayList player,
            String name, int[] handValues)
    {
        c = newDeck.draw();
        player.add(c);
        System.out.print(name + "'s hand: ");
        for(int cardNum = 0; cardNum < player.size(); cardNum++)
            System.out.print(player.get(cardNum) + "  ");
        System.out.println();
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[0] >= 11)
                handValues[0] += 1;
            else
                handValues[0] += 11;
        }
        else
            handValues[0] += c.getValue();
        System.out.println("Value: " + handValues[0] + "\n");

        return handValues[0];
    }
    public static void playerStand(String name, ArrayList player,
            int[] handValues)
    {
        System.out.println(name + "'s hand: ");
        for(int cardNum = 0; cardNum < player.size(); cardNum++)
            System.out.print(player.get(cardNum) + "  ");
        System.out.println();
        System.out.println("Value: " + handValues[0] + "\n");
    }
    public static int[] dealerHit(Card c, Deck newDeck, ArrayList dealer,
            int[] handValues)
    {
        c = newDeck.draw();
        dealer.add(c);
        System.out.print("Dealer's hand: ");
        for(int cardNum = 0; cardNum < dealer.size(); cardNum++)
            System.out.print(dealer.get(cardNum) + "  ");
        System.out.println();
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[1] >= 11)
                handValues[1] += 1;
            else
                handValues[1] += 11;
        }
        else
            handValues[1] += c.getValue();
        System.out.println("Value: " + handValues[1]);

        return handValues;
    }
    public static int[] dealerStand(ArrayList dealer, int[] handValues)
    {
        System.out.print("Dealers's hand: ");
        for(int cardNum = 0; cardNum < dealer.size(); cardNum++)
            System.out.print(dealer.get(cardNum) + "  ");
        System.out.println();
        System.out.println("Value: " + handValues[1]);

        return handValues;
    }
}


问:
Extract json in an array in Jmeter
How do I extract the json object name from the below json data in Jmeter

```<code>[
:   {
:   :   "name":"x",
:   :   "age":"50",
:   :   "gender":"Female"
:   }
]
</code>```

I am doing this $..name in the JsonPath Extractor which is giving me this in the variable I extracted to

```<code>name=["x"]
</code>```

Is there a way I could just get name=x without the array format

Or is there a way I can extract just the x from ["x"]?

Thanks

答:
You need to get name attribute from the first object in the array therefore you need to amend your JSON Path expression to look like $[0].name

References:

JsonPath - Getting Started

JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios

Title: Extract json in an array in Jmeter

Body:
How do I extract the json object name from the below json data in Jmeter

[
:   {
:   :   "name":"x",
:   :   "age":"50",
:   :   "gender":"Female"
:   }
]

I am doing this $..name in the JsonPath Extractor which is giving me this in the variable I extracted to

name=["x"]

Is there a way I could just get name=x without the array format

Or is there a way I can extract just the x from ["x"]?

Thanks


问:
Fastest Way for Comparing Strings Python
Situation: Comparing strings in fileA with pre-defined strings in fileB. Example of said function in my code:

```<code>string = open('fileA', 'r')
stringlist = open('fileB', 'r')

//compare the strings
for i in string:
    for j in stringlist:
        if i == j:
            print("Same String found!" + i + " " + j)
</code>```

Problem: In my actual program, string contains more than 200 strings, while stringlist is a file with more than 50,000 strings. The nested for loop, as I have read, is slow as a comparison function.

Question: What is the fastest way to compare the two files' content?

Additional information 1: Both files are CSV files, and are opened in my program as CSV-delimited.

Additional information 2: Strings are md5 hashes (32 characters).

Additional information 3: I am open to other ways to store the strings, i.e. Compare the strings on-the-fly instead of saving it to fileA.

Additional information 4: I am also open to other methods or modules that I can use (i.e.: Threading/parallel processing) -- speed is the key here.

答:
You should use sets:

```<code>setA = set(listA)
setB = set(listB)
common = setA.intersection(setB)
</code>```

common now holds all the strings that are present in both lists

You can also do this with a one-liner:

```<code>common = set(listA).intersection(set(listB))
</code>```

If you can do this comparison "on the fly" it is of course better and faster than saving the lists to a file and then reading again from that file, you gain nothing by doing that.

And of course, to print duplicates:

```<code>for x in common:
    print(x)
</code>```

Body:
Situation: Comparing strings in fileA with pre-defined strings in fileB. Example of said function in my code:

string = open('fileA', 'r')
stringlist = open('fileB', 'r')

//compare the strings
for i in string:
    for j in stringlist:
        if i == j:
            print("Same String found!" + i + " " + j)

Problem: In my actual program, string contains more than 200 strings, while stringlist is a file with more than 50,000 strings. The nested for loop, as I have read, is slow as a comparison function.

Question: What is the fastest way to compare the two files' content?

Additional information 1: Both files are CSV files, and are opened in my program as CSV-delimited.

Additional information 2: Strings are md5 hashes (32 characters).

Additional information 3: I am open to other ways to store the strings, i.e. Compare the strings on-the-fly instead of saving it to fileA.

Additional information 4: I am also open to other methods or modules that I can use (i.e.: Threading/parallel processing) -- speed is the key here.

Body:
You should use sets:

setA = set(listA)
setB = set(listB)
common = setA.intersection(setB)

common now holds all the strings that are present in both lists

You can also do this with a one-liner:

common = set(listA).intersection(set(listB))

If you can do this comparison "on the fly" it is of course better and faster than saving the lists to a file and then reading again from that file, you gain nothing by doing that.

And of course, to print duplicates:

for x in common:
    print(x)


问:
Can't instantiate class even included
I'm very new to PHP, and I can't solve an issue even I read a lot of tutorials and SO posts.
I've a custom class (user), and I'd like to instantiate it in php code, but even I include it, I get this error.

Fatal error: Class 'User' not found in D:\wamp64\www\MyFirstPhp\formPhp.php on line 17

Please help me find out what I do wrong.

Here is my user class:

```<code>  <?php
/**
 * Created by IntelliJ IDEA.
 * User: molnard
 * Date: 2017. 06. 06.
 * Time: 15:36
 */

namespace infopro;

class User
{
    private $username;
    private $userage;
    private $sex;

    public function __construct($username, $userage, $sex)
    {
        if (!is_null($username)) $this->username = $username;
        if (!is_null($userage)) $this->userage = $this->userage;
        if (!is_null($sex)) $this->sex = $sex;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return mixed
     */
    public function getUserage()
    {
        return $this->userage;
    }

    /**
     * @param mixed $userage
     */
    public function setUserage($userage)
    {
        $this->userage = $userage;
    }

    /**
     * @return mixed
     */
    public function getSex()
    {
        return $this->sex;
    }

    /**
     * @param mixed $sex
     */
    public function setSex($sex)
    {
        $this->sex = $sex;
    }
}
?>
</code>```

And here is my form.php class where I'd like to instantiate user class.

```<code>    <!Doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form php</title>
</head>
<body>
<?php
include("User.php");

$name = $_POST["name"];
$age = $_POST["age"];
$sex = $_POST["sex"];
echo "New user<br>name: " . $name . "<br>" .
    "age: " . $age . "<br>" . "sex: " . $sex."<br>";

$newuser = new User($name, $age, $sex);
$newAge = $newuser->getAge();
echo $newAge;
?>
</body>
</html>
</code>```

答:
Thanks, all answer was good.
I use intelij, and I've just realised namespace just optional, I can use global namespace if I leave it blank.</p>

Title: Can't instantiate class even included

Body:
I'm very new to PHP, and I can't solve an issue even I read a lot of tutorials and SO posts.
I've a custom class (user), and I'd like to instantiate it in php code, but even I include it, I get this error.

Fatal error: Class 'User' not found in D:\wamp64\www\MyFirstPhp\formPhp.php on line 17

Please help me find out what I do wrong.

Here is my user class:

  <?php
/**
 * Created by IntelliJ IDEA.
 * User: molnard
 * Date: 2017. 06. 06.
 * Time: 15:36
 */

namespace infopro;

class User
{
    private $username;
    private $userage;
    private $sex;

    public function __construct($username, $userage, $sex)
    {
        if (!is_null($username)) $this->username = $username;
        if (!is_null($userage)) $this->userage = $this->userage;
        if (!is_null($sex)) $this->sex = $sex;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return mixed
     */
    public function getUserage()
    {
        return $this->userage;
    }

    /**
     * @param mixed $userage
     */
    public function setUserage($userage)
    {
        $this->userage = $userage;
    }

    /**
     * @return mixed
     */
    public function getSex()
    {
        return $this->sex;
    }

    /**
     * @param mixed $sex
     */
    public function setSex($sex)
    {
        $this->sex = $sex;
    }
}
?>

And here is my form.php class where I'd like to instantiate user class.

    <!Doctype html>

    <meta charset="UTF-8">
    <title>Form php</title>

<?php
include("User.php");

$name = $_POST["name"];
$age = $_POST["age"];
$sex = $_POST["sex"];
echo "New user
name: " . $name . "
" .
    "age: " . $age . "
" . "sex: " . $sex."
";

$newuser = new User($name, $age, $sex);
$newAge = $newuser->getAge();
echo $newAge;
?>


问:
How can I iterate through JSON values using Python?
My JSON data looks like this:

```<code>{
    "cameras": [
        {
            "item": "810-00022",
            "name": "front",
            "serial": "000287"
        },
        {
            "item": "810-00022",
            "name": "rear",
            "serial": "000166"
        },
        {
            "item": "810-00022",
            "name": "left",
            "serial": "000492"
        },
        {
            "item": "810-00022",
            "name": "right",
            "serial": "000282"
        },
        {
            "item": "810-00022",
            "name": "inside",
            "serial": "000143"
        }
    ],
    "item": "810-00023",
    "mac": "14:1f:ba:90:01:16",
    "name": 1623,
    "serial": "000408"
}
{
    "cameras": [
        {
            "item": "810-00032",
            "name": "inside",
            "serial": "000007"
        },
        {
            "item": "810-00022",
            "name": "right",
            "serial": "000941"
        },
        {
            "item": "810-00022",
            "name": "front",
            "serial": "000637"
        },
        {
            "item": "810-00022",
            "name": "left",
            "serial": "000430"
        }
    ],
    "item": "810-00023",
    "mac": "14:1f:ba:90:01:9e",
    "name": 1599,
    "serial": "000309"
}
</code>```

How can I output the names (not camera names) for each of my entries?

In theory, I want to be able to print the following 1623 and 1599.

I have the following, but it is not working for some reason:

```<code>json2 = open('C:\\Users\\' + comp_name + '\\Documents\\Python Firmware Script\\curl\\src\\systemidsout.json')
json2_obj = json.load(json2)

for i in json2_obj[]:
     print i['name']
</code>```

I was hoping the above works, as it has for my other JSON file, but I'm guessing because the layout may be different, it's not working.

How can I output the 'name' values within my JSON file?

Furthermore, as a bonus question, how can I output the individual names within my camera array also?

答:
If you change for i in json2_obj[]: to i in json2_obj:, it will work.
If you want to output the individual names within a camera array, use

```<code>for j in i['cameras']:
    print(j['name'])
</code>```

with in your for loop.

Just to mention, your JSON data has actually 2 JSON. If you want to read them from one file, you might want to change it to [{...},{...}] format. Otherwise, json.load() may raise an error.

Body:
My JSON data looks like this:

{
    "cameras": [
        {
            "item": "810-00022",
            "name": "front",
            "serial": "000287"
        },
        {
            "item": "810-00022",
            "name": "rear",
            "serial": "000166"
        },
        {
            "item": "810-00022",
            "name": "left",
            "serial": "000492"
        },
        {
            "item": "810-00022",
            "name": "right",
            "serial": "000282"
        },
        {
            "item": "810-00022",
            "name": "inside",
            "serial": "000143"
        }
    ],
    "item": "810-00023",
    "mac": "14:1f:ba:90:01:16",
    "name": 1623,
    "serial": "000408"
}
{
    "cameras": [
        {
            "item": "810-00032",
            "name": "inside",
            "serial": "000007"
        },
        {
            "item": "810-00022",
            "name": "right",
            "serial": "000941"
        },
        {
            "item": "810-00022",
            "name": "front",
            "serial": "000637"
        },
        {
            "item": "810-00022",
            "name": "left",
            "serial": "000430"
        }
    ],
    "item": "810-00023",
    "mac": "14:1f:ba:90:01:9e",
    "name": 1599,
    "serial": "000309"
}

How can I output the names (not camera names) for each of my entries?

In theory, I want to be able to print the following 1623 and 1599.

I have the following, but it is not working for some reason:

json2 = open('C:\\Users\\' + comp_name + '\\Documents\\Python Firmware Script\\curl\\src\\systemidsout.json')
json2_obj = json.load(json2)

for i in json2_obj[]:
     print i['name']

I was hoping the above works, as it has for my other JSON file, but I'm guessing because the layout may be different, it's not working.

How can I output the 'name' values within my JSON file?

Furthermore, as a bonus question, how can I output the individual names within my camera array also?

Body:
If you change for i in json2_obj[]: to i in json2_obj:, it will work.
If you want to output the individual names within a camera array, use

for j in i['cameras']:
    print(j['name'])

with in your for loop.

Just to mention, your JSON data has actually 2 JSON. If you want to read them from one file, you might want to change it to [{...},{...}] format. Otherwise, json.load() may raise an error.


问:
Adding items from one list to another list in another form in c#
I have a Form1 which displays a list of students in a ListBox.

I use Form2 to populate this list of students, well I want to.

Form2 is meant to update the studentList_Form1 in Form1 every time a button is clicked in Form2.

what I'm trying to figure out is how to actually do this? Because I have tried this

Form1:

```<code>public List<Student> studentList_Form1;

public List<Student> StudentList_Form1
{
    get
    {
        return studentList_Form1;
    }
}
</code>```

Form2:

```<code>public List<Student> studentList = new List<Student>();

private void update_main_student_list()
{
    using (Form1 newForm = new Form1())
    {
        foreach(Student s in studentList)
        {
            newForm.StudentList_Form1.Add(s);
        }
    }
    //As well as the code to populate studentList
}
</code>```

But I keep getting an error saying I need to check if s if null before I use it.

Student is a class which is made up of a string name, string address, int id

答:
Make the List studentList_Form1 in Form1 as static instead of creating a new form </p>

```<code>private static List<Student> studentList_Form1 = new List<Student>();

public static List<Student> StudentList_Form1
{
    get
    {
       return studentList_Form1;
    }
}
</code>```

Body:
I have a Form1 which displays a list of students in a ListBox.

I use Form2 to populate this list of students, well I want to.

Form2 is meant to update the studentList_Form1 in Form1 every time a button is clicked in Form2.

what I'm trying to figure out is how to actually do this? Because I have tried this

Form1:

public List<Student> studentList_Form1;

public List<Student> StudentList_Form1
{
    get
    {
        return studentList_Form1;
    }
}

Form2:

public List<Student> studentList = new List<Student>();

private void update_main_student_list()
{
    using (Form1 newForm = new Form1())
    {
        foreach(Student s in studentList)
        {
            newForm.StudentList_Form1.Add(s);
        }
    }
    //As well as the code to populate studentList
}

But I keep getting an error saying I need to check if s if null before I use it.

Student is a class which is made up of a string name, string address, int id

Body:
Make the List studentList_Form1 in Form1 as static instead of creating a new form

private static List<Student> studentList_Form1 = new List<Student>();

public static List<Student> StudentList_Form1
{
    get
    {
       return studentList_Form1;
    }
}


问:
How to subset data according to date in R?
Simple enough question. I have data of US treasury bill rates, with two columns-
1) Date and 2) Rate. The data ranges back to 1960. I wish to subset the rates from 1990 onward, i.e. according to the date.

Code:-

```<code>data = read.csv("3mt-bill.csv")

rates= ?
</code>```

So, I just want a vector of the t-bill rates, but from 1990 onwards.
How should I write the condition?

答:
We need to first convert the 'Date' to Date class, extract the year with format, check whether it is greater than 1990 and subset the 'Rates' based on that logical vector

```<code>data$Rate[format(as.Date(data$Date), "%Y") >= 1990]
</code>```

If the 'Date' column include only year part, it is easier

```<code>data$Rate[data$Date >= 1990]
</code>```

Just in case, if we need tidyverse

```<code>library(tidyverse)
data %>%
      filter(year(ymd(Date)) >= 1990) %>%
      select(Rate)
</code>```

Or using data.table

```<code>library(data.table)
setDT(data)[year(as.IDate(Date)) >= 1990, Rate]
</code>```

Body:
Simple enough question. I have data of US treasury bill rates, with two columns-
1) Date and 2) Rate. The data ranges back to 1960. I wish to subset the rates from 1990 onward, i.e. according to the date.

Code:-

data = read.csv("3mt-bill.csv")

rates= ?

So, I just want a vector of the t-bill rates, but from 1990 onwards.
How should I write the condition?

Body:
We need to first convert the 'Date' to Date class, extract the year with format, check whether it is greater than 1990 and subset the 'Rates' based on that logical vector

data$Rate[format(as.Date(data$Date), "%Y") >= 1990]

If the 'Date' column include only year part, it is easier

data$Rate[data$Date >= 1990]

Just in case, if we need tidyverse

library(tidyverse)
data %>%
      filter(year(ymd(Date)) >= 1990) %>%
      select(Rate)

Or using data.table

library(data.table)
setDT(data)[year(as.IDate(Date)) >= 1990, Rate]


问:
React JS event handler arguments
I was reading about "Lifting State Up" in React JS documentation and there is something I am not very clear about. The codepen can be found here: https://codepen.io/valscion/pen/jBNjja?editors=0010

In the TemperatureInput component, the onTemperatureChange event handler calls the handleCelsiusChange, but the latter contains a parameter of temperature. How are we passing this parameter? There is no argument passed in the onTemperatureChange. What am I missing here?

Hope someone can help me understand this.

```<code>class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}
</code>```

```<code>class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

  handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

  handleFahrenheitChange(temperature) {
    this.setState({scale: 'f', temperature});
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (
      <div>
        <TemperatureInput
          scale="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />
        <TemperatureInput
          scale="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict
          celsius={parseFloat(celsius)} />
      </div>
    );
  }
}
</code>```

答:
Here to the TemperatureInput component you are passing the function (it acts like a pointer).

This is passed from Calculator to TemperatureInput component.

Now we see, our function handleCelsiusChange requires one argument, Therefore when we call onTemperatureChange function inside TemperatureInput component, we must be passing some variable there.

As you can see below code you are passing the parameter to the function call.

```<code> handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }
</code>```

This where we are passing the argument to the function from TemperatureInput component

Title: React JS event handler arguments

Body:
I was reading about "Lifting State Up" in React JS documentation and there is something I am not very clear about. The codepen can be found here: https://codepen.io/valscion/pen/jBNjja?editors=0010

In the TemperatureInput component, the onTemperatureChange event handler calls the handleCelsiusChange, but the latter contains a parameter of temperature. How are we passing this parameter? There is no argument passed in the onTemperatureChange. What am I missing here?

Hope someone can help me understand this.

class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

  handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

  handleFahrenheitChange(temperature) {
    this.setState({scale: 'f', temperature});
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (

        <TemperatureInput
          scale="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />
        <TemperatureInput
          scale="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict
          celsius={parseFloat(celsius)} />

    );
  }
}

Body:
Here to the TemperatureInput component you are passing the function (it acts like a pointer).

This is passed from Calculator to TemperatureInput component.

Now we see, our function handleCelsiusChange requires one argument, Therefore when we call onTemperatureChange function inside TemperatureInput component, we must be passing some variable there.

As you can see below code you are passing the parameter to the function call.

 handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

This where we are passing the argument to the function from TemperatureInput component


问:
Buttons not showing up on Jframe
```<code>// Creating buttons
JButton b1 = new JButton();
    b1.setText("Add");
    b1.setSize(100, 130);
    b1.setLocation(330, 70);
    b1.setBackground(Color.red);
    b1.setVisible(true);

// Creating second button
JButton b2 = new JButton();
    b2.setText("Add");
    b2.setSize(100,100);
    b2.setLocation(0, 0);
    b2.setBackground(Color.blue);
    b2.setVisible(true);

//adding buttons to Jframe
f.add(b1);
f.add(b2);
</code>```

The buttons don't appear when I run the program or sometimes, they do appear, but take up the whole JFrame completely

答:
Guess #1

Like almost all questions on the subject, you are calling f.setVisible(true) BEFORE you add the components to the UI

So, something like this should fix it

```<code>// In some other part of your code you've not provided us
//f.setVisible(true);

JButton b1 = new JButton();
b1.setText("Add");
b1.setBackground(Color.red);

JButton b2 = new JButton();
b2.setText("Add");
b2.setBackground(Color.blue);

f.add(b1);
f.add(b2);
f.setVisible(true);
</code>```

Guess #2

You've not change the default layout manager of the JFrame, so it's still using a BorderLayout

Something like this should at least allow both buttons to be displayed without overlapping each other

```<code>f.setLayout(new FlowLayout());
f.add(b1);
f.add(b2);
f.setVisible(true);
</code>```

I would recommend spending some time going through Laying out Components within a Container for more details

Title: Buttons not showing up on Jframe

Body:
// Creating buttons
JButton b1 = new JButton();
    b1.setText("Add");
    b1.setSize(100, 130);
    b1.setLocation(330, 70);
    b1.setBackground(Color.red);
    b1.setVisible(true);

// Creating second button
JButton b2 = new JButton();
    b2.setText("Add");
    b2.setSize(100,100);
    b2.setLocation(0, 0);
    b2.setBackground(Color.blue);
    b2.setVisible(true);

//adding buttons to Jframe
f.add(b1);
f.add(b2);

The buttons don't appear when I run the program or sometimes, they do appear, but take up the whole JFrame completely

Body:
Guess #1

Like almost all questions on the subject, you are calling f.setVisible(true) BEFORE you add the components to the UI

So, something like this should fix it

// In some other part of your code you've not provided us
//f.setVisible(true);

JButton b1 = new JButton();
b1.setText("Add");
b1.setBackground(Color.red);

JButton b2 = new JButton();
b2.setText("Add");
b2.setBackground(Color.blue);

f.add(b1);
f.add(b2);
f.setVisible(true);

Guess #2

You've not change the default layout manager of the JFrame, so it's still using a BorderLayout

Something like this should at least allow both buttons to be displayed without overlapping each other

f.setLayout(new FlowLayout());
f.add(b1);
f.add(b2);
f.setVisible(true);

I would recommend spending some time going through Laying out Components within a Container for more details


问:
Which database i have to use to implement the auto-completion of dictionary
I ran across a interview question of implementing a dictionary that can implement the features of auto-completion, auto-correction, spell check etc...

I actually wanted to know which data base i have to use to store all the word like (for location country, city and zip code) .

Please suggest me if there any framework in java with any database or any optimal database that can achieve the solution

Any links that guide me on this are welcome...

答:
The simplest solution for auto-completion is to use a Navigable Set to find all the entries which start with a given String.

For auto-correction/spell check I would a plain set of correct words and to offer suggestions use a "sounds-like" encoder and a multi-map (Map of Lists) for all the words which sound like the word entered.


问:
ORACLE:SQL REGEXP_SUBSTR that returns the column value between 1st semicolon and second one. Also other value after last semi clumn
varchar: BLAH:123:678

need value between first semi column and second one: 123
need value after last semi column: 678

答:
Use the below regex:

```<code>SELECT REGEXP_SUBSTR ('BLAH:123:678', ':(\d+):', 1, 1, NULL, 1) first_val,
       REGEXP_SUBSTR ('BLAH:123:678', '(\d+)$', 1, 1, NULL, 1) second_val
  FROM DUAL
</code>```

Output:

```<code>first_Val  second_val
123        678
</code>```

Body:
Use the below regex:

SELECT REGEXP_SUBSTR ('BLAH:123:678', ':(\d+):', 1, 1, NULL, 1) first_val,
       REGEXP_SUBSTR ('BLAH:123:678', '(\d+)$', 1, 1, NULL, 1) second_val
  FROM DUAL

Output:

first_Val  second_val
123        678


问:
Performant texture region copies in Metal
I've got my eye upon Metal as an option for performing very performant pixel copies at 60fps.

Let me phrase my question in terms of an existing technology...

I have the attached 1920x1080 NSImage and I want to blit this into an NSView in a "mosaic"-type fashion. Assume this image is a frame of video, so it would more likely be an RGBA32-formatted CVPixelBuffer). Each of these 9 coloured regions could end up in random locations on the screen.

I could use the drawInRect function from the NSImage API to perform 9 such copy calls from the source of my image to the target NSView. The data model in this case would involve 9 source-target CGRect pairs, and then 9 such calls to perform the copies.

I suspect this is a very slow approach as compared to what could happen in Metal.  It could possibly be accelerated if the NSView were Metal-backed.

Can someone enlighten me as to what a very performant Metal version of this would be?

The intent would be to upload the entire texture as-is, once to the GPU and then issue a set of GPU-based calls to (eventually) blit the texture's regions onto screen.  Assume that the source pixel format is RGBA32.  The intent obviously is for only one CPU->GPU pixel data transfer (no round trips!).

Would such an approach first involve the use of the copyFromBuffer to get the image on the GPU, then a set of 9 calls to copyFromTexture to finalize the texture for presentation?  Then mapping that texture onto a quad on-screen.  Just surmising.  What would this look like?

(The fact that Metal2 now has some one-time argument buffers is appealing to me and may just be a lower-level implementation of the two aforementioned functions from the MTLBlitCommandEncoder.  If this is a more performant lower-level implementation, what would that look like instead?)

Any guidance on this would be appreciated.

答:
I would think that just about any approach that's not overly complicated would be plenty performant. There are very few vertices and only one texture involved.

You could create the initial texture using MTKTextureLoader and its methods to create a texture from a CGImage or even from the original image data source (URL or image asset). Or, since you mentioned Core Video, you can get Metal textures directly from that.

If you want to draw different sectors of that texture to different sectors of the view, I'd draw 9 quads (in a single draw call) and just use the appropriate texture coordinates for each one. No need to copy chunks of the texture from place to place.


问:
Protractor cssContainingText with function as argument
I'm trying to test if my input field calculates credits correctly.

This test should pick a random number between 1-100(credits) and then multiply them by 5($) and display a total price.

function randomZip() {
  return Math.floor(Math.random() * 100);
}
var creditQuantity = randomZip();

function creditQuantityMultiplied() {
  creditQuantity * 5;
  return;
};

element(by.css("a[href='/credits']")).click();
element(by.css('input[name="count"]')).sendKeys(creditQuantity);
$('.text_per').click();
browser.sleep(1500);

var checkSumCredits = element(by.cssContainingText('.inline-block.price_credit.text_per', creditQuantityMultiplied()));

expect(checkSumCredits.isPresent()).toBeTruthy();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="credits-block" id="creditsBuyForm">
  <h2>Buy Credits</h2>
  <div class="credits">
    <div class="block">
      <span class="text_per">Amount</span>
      <input type="text" name="count" value="25" class="text_per">
      <span class="text_per">x</span>
      <div class="inline-block price_credit">$5.00</div>
      <span class="text_per">per credit</span> </div>
    <div class="block">
      <span class="text_per">Total</span>
      <div class="inline-block price_credit text_per">
        <img width="32" height="32" src="/app-static/css/img/coins_2.png" class="inline-block"> $125.00</div>
      <div class="inline-block">
        <form action="/cart/index.php" method="post" id="remoteadd" class="trackable-init">
          <input type="hidden" name="app" value="ecom"> <input type="hidden" name="ns" value="addcart">
          <input type="hidden" name="cart_api" value="Y"> <input type="hidden" name="price" value="5.00">
          <input type="hidden" name="name" value="Credits ($5.00 per credit)">
          <input type="hidden" name="quantity" value="25">
          <input type="hidden" name="number" value="a:3:{s:7:"user_id";i:7996;s:10:"company_id";i:1;s:9:"item_type";i:1;}">
          <input type="hidden" name="delivery_method" value="N">
          <input type="hidden" name="SUBMIT" value="SUBMIT">
          <input type="hidden" name="taxcountry" value="STANDARD">
          <input type="hidden" name="taxstateprov" value="STANDARD"> <input type="hidden" name="taxclass" value="DIGITAL">
          <button type="submit" class="def-ui-button-buy ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button">
            <span class="ui-button-icon-primary ui-icon ui-icon-cart"></span>
            <span class="ui-button-text">Buy</span>
            </button>
        </form>
      </div>
    </div>
  </div>
</div></code>```

I'm getting Expected false to be truthy when I run this code and I'm not sure if the problem is that cssContainingText requires 2 string args and im passing 1 string 1 integer or something else.

答:
When I look at your code I see the following happening

You fill element(by.css('input[name="count"]')) with creditQuantity, which is random generated, for example it is value 47

You are then doing an assertion with expect(checkSumCredits.isPresent()).toBeTruthy();. checkSumCredits is based on the fact if it can find an element that holds the value that is generated with creditQuantityMultiplied()

The creditQuantityMultiplied() holds 2 errors in my opinion:

It doesn't return a value, it only return's

If you change creditQuantityMultiplied() to also return a value it will also generate a unique value. That will never equal the previous random value of 47

That's why you won't find a match and will return false / fail.

Hope it helps

Body:
I'm trying to test if my input field calculates credits correctly.

This test should pick a random number between 1-100(credits) and then multiply them by 5($) and display a total price.

function randomZip() {
  return Math.floor(Math.random() * 100);
}
var creditQuantity = randomZip();

function creditQuantityMultiplied() {
  creditQuantity * 5;
  return;
};

element(by.css("a[href='/credits']")).click();
element(by.css('input[name="count"]')).sendKeys(creditQuantity);
$('.text_per').click();
browser.sleep(1500);

var checkSumCredits = element(by.cssContainingText('.inline-block.price_credit.text_per', creditQuantityMultiplied()));

expect(checkSumCredits.isPresent()).toBeTruthy();

Buy Credits

      Amount
      <input type="text" name="count" value="25" class="text_per">
      x

$5.00

      per credit

      Total

         $125.00

        <form action="/cart/index.php" method="post" id="remoteadd" class="trackable-init">
          <input type="hidden" name="app" value="ecom"> <input type="hidden" name="ns" value="addcart">
          <input type="hidden" name="cart_api" value="Y"> <input type="hidden" name="price" value="5.00">
          <input type="hidden" name="name" value="Credits ($5.00 per credit)">
          <input type="hidden" name="quantity" value="25">
          <input type="hidden" name="number" value="a:3:{s:7:"user_id";i:7996;s:10:"company_id";i:1;s:9:"item_type";i:1;}">
          <input type="hidden" name="delivery_method" value="N">
          <input type="hidden" name="SUBMIT" value="SUBMIT">
          <input type="hidden" name="taxcountry" value="STANDARD">
          <input type="hidden" name="taxstateprov" value="STANDARD"> <input type="hidden" name="taxclass" value="DIGITAL">
          <button type="submit" class="def-ui-button-buy ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button">

            Buy
            </button>
        </form>

I'm getting Expected false to be truthy when I run this code and I'm not sure if the problem is that cssContainingText requires 2 string args and im passing 1 string 1 integer or something else.


问:
How can I dynamically add a button to the last item in a list?
In Angular, I'm using the ng-repeat directive to print a list of items in an array. What I'd like to do is add a button to the right of the last item in the list. I'm not aware of a non jquery way of adding this dynamically.

Here is an image of what I currently have. My button gets pushed down the list when new things get added. I'd like to see that button on the right side of the last item in the list (here it is 'acculist').

Any ideas help! Thanks everyone.

Edit
The button must be present at all times. Initially there will be no items in the Shopping List, so the user must always have the ability to click the button to add items to a shopping list.

答:
```<code><li ng-repeat="item in items track by $index">
<span>{{item.name}}</span> <button ng-if="$last" >Add To List</button>
</li>
</code>```


问:
Getting values of textfields on page
Lets just say that I have some (many many many) text fields on a page... and i enter a new value in one of them, then click a button... How can I update the database with just that new value? Or, if it would be easier... How can I update all of those textfields to the database?

Thanks :)

答:
```<code><?php
$sql = "UPDATE table_name SET";
foreach($_POST as $key=>$value){
    if($key != 'submit'){
        $sql .= " " . $key . " = '" . $value . "'";
    }
}
$sql = " WHERE ......";
?>
</code>```

This will generate the sql statement for you. You just need to add in security and then the execution.

Title: Getting values of textfields on page

Body:
<?php
$sql = "UPDATE table_name SET";
foreach($_POST as $key=>$value){
    if($key != 'submit'){
        $sql .= " " . $key . " = '" . $value . "'";
    }
}
$sql = " WHERE ......";
?>

This will generate the sql statement for you. You just need to add in security and then the execution.


问:
How do I add all the filenames under a certain folder to an arraylist using Java
I have this much so far

```<code> import java.io.File;
 import java.io.FilenameFilter;
 import java.util.ArrayList;
 import java.util.Arrays;

 import org.pdfbox.util.Splitter;
 public class fileName {
     public static void main(String args[]){
         File file = new File("/Users/apple/Desktop/");
         String[] directories = file.list(new FilenameFilter(){

             @Override
             public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
             }
         });
 System.out.println(Arrays.toString(directories));
 ArrayList<String[]>SSOList = new ArrayList<String[]>();
     }
 }
</code>```

It prints the names of all the files on my desktop but I want to add them to an arraylist. How do I do that?

答:
There are quite a few ways by which you can get the filenames in an ArrayList:

Use the Arrays.asList() method:

ArrayList<String> SSOList = new ArrayList<String>(Arrays.asList(directories));

Use the Collections utility class allAll method:

List<String> SSOList = new ArrayList<String>(directories.length);
Collections.addAll(SSOList , directories);

Traverse the directories array again and add each value to the ArrayList SSOList.

Kepping in mind that these are to be done after you get the values in directories array.

Body:
I have this much so far

 import java.io.File;
 import java.io.FilenameFilter;
 import java.util.ArrayList;
 import java.util.Arrays;

 import org.pdfbox.util.Splitter;
 public class fileName {
     public static void main(String args[]){
         File file = new File("/Users/apple/Desktop/");
         String[] directories = file.list(new FilenameFilter(){

             @Override
             public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
             }
         });
 System.out.println(Arrays.toString(directories));
 ArrayList<String[]>SSOList = new ArrayList<String[]>();
     }
 }

It prints the names of all the files on my desktop but I want to add them to an arraylist. How do I do that?


答:
Form1:

```<code>private List<Student> studentList_Form1=new List<Student>();

        public List<Student> StudentList_Form1
        {
            get
            { return studentList_Form1; }
        }
</code>```

To Load Form2:

```<code>Form2 frm = new Form2(this);
            frm.ShowDialog();
</code>```

Form2:

```<code>    Form1 frm1;
    public List<Student> studentList = new List<Student>();

    public Form2(Form1 frm)
            {
                InitializeComponent();
                frm1 = frm;

                for (int i = 0; i < 10; i++)
                    studentList.Add(new Student() { studentId = i, studentName = "Student " + i });

            }
</code>```

to add items to studentList which exists in Form1:

```<code>private void button1_Click(object sender, EventArgs e)
        {
            foreach (var std in studentList)
                frm1.StudentList_Form1.Add(std);
        }
</code>```

Title: Adding items from one list to another list in another form in c#

Body:
Form1:

private List<Student> studentList_Form1=new List<Student>();

        public List<Student> StudentList_Form1
        {
            get
            { return studentList_Form1; }
        }

To Load Form2:

Form2 frm = new Form2(this);
            frm.ShowDialog();

Form2:

    Form1 frm1;
    public List<Student> studentList = new List<Student>();

    public Form2(Form1 frm)
            {
                InitializeComponent();
                frm1 = frm;

                for (int i = 0; i < 10; i++)
                    studentList.Add(new Student() { studentId = i, studentName = "Student " + i });

            }

to add items to studentList which exists in Form1:

private void button1_Click(object sender, EventArgs e)
        {
            foreach (var std in studentList)
                frm1.StudentList_Form1.Add(std);
        }


问:
Can I concat a string and a variable to select a DOM element in JavaScript?
I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.

I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.

```<code>var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');

for(var i=0;i<4;i++){
 console.log(copy+i);
 console.log("copy"+i);
};
</code>```

Ideally I would be able to select an element and style that via javascript.

Much appreciated

Thanks All.

Moe

答:
You can store the properties in an object where values are set to the DOM element

```<code>let copies = {
 1 : document.getElementById('copy1'),
 2 : document.getElementById('copy2'),
 3 : document.getElementById('copy3')
}

for (let [key, prop] of Object.entries(copies)) {
  console.log(key, prop)
}

console.log(copies[1], copies[2], copies[3]);
</code>```

Or use attribute begins with and attribute ends with selectors with .querySelector()

```<code>let n = 1;
let copy1 = document.querySelector(`[id^=copy][id$='${n}']`); // `#copy1`
let copy2 = document.querySelector(`[id^=copy][id$='${++n}']`); // `#copy2`
</code>```

```<code>for (let i = 1; i < 4; i++) {
  console.log(document.querySelector("[id^=copy][id$=" + i + "]"));
}
</code>```

Body:
I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.

I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.

var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');

for(var i=0;i<4;i++){
 console.log(copy+i);
 console.log("copy"+i);
};

Ideally I would be able to select an element and style that via javascript.

Much appreciated

Thanks All.

Moe

Body:
You can store the properties in an object where values are set to the DOM element

let copies = {
 1 : document.getElementById('copy1'),
 2 : document.getElementById('copy2'),
 3 : document.getElementById('copy3')
}

for (let [key, prop] of Object.entries(copies)) {
  console.log(key, prop)
}

console.log(copies[1], copies[2], copies[3]);

Or use attribute begins with and attribute ends with selectors with .querySelector()

let n = 1;
let copy1 = document.querySelector(`[id^=copy][id$='${n}']`); // `#copy1`
let copy2 = document.querySelector(`[id^=copy][id$='${++n}']`); // `#copy2`

for (let i = 1; i < 4; i++) {
  console.log(document.querySelector("[id^=copy][id$=" + i + "]"));
}


问:
How to use Xcode built-in unit testing framework to test C functions?
I'm trying to unit test C functions with the SenTestingKit framework. I declares functions in a header file and defines implementations in a corresponding C file. And I imports the header file in the unit test class. But when I build the test cases, the build result says the functions 'symbol(s) not found'.
Is there anything I should do to make it work?
Is it the right way to unit test C functions?</p>

答: You need to add the implementation file to the Unit Test target so it gets compiled in. Importing the header is not enough.</p>