问:
ant - how to get a zero resource count if the folder does not exist
I'm trying to base a task on whether a folder has content, not on whether it merely exists. I know there is probably a long winded solution, is there a better solution that I'm missing ?

I've tried two different methods to set a property depending on whether or not a folder has files in it.

My understanding is that 'available' does not permit wildcards like:

```<code>  <available property="has.test.data" file="${test.data.dir}/**" type="file"/>
</code>```

I tried this but it does not work if the folder (test.data.dir) does not exist:

```<code>  <fileset id="test.data.files" dir="${test.data.dir}" includes="**/*" />
  <condition property="has.test.data">
    <resourcecount when="greater" count="0"> <fileset refid="test.data.files" /> </resourcecount>
  </condition>
</code>```

Ideally, I want to base a task on whether the folder actually has content, not just an empty folder.

答:
You can use erroronmissingdir="false", to avoid the error for a non-existing directory. Add else="false" if you need the property to always exist

```<code><?xml version="1.0" encoding="utf-8"?>
<project name="Test resourcecount" xmlns:if="ant:if">

  <fileset id="test.data.files" dir="${test.data.dir}" includes="**/*" erroronmissingdir="false"/>
  <condition property="has.test.data" else="false">
    <resourcecount when="greater" count="0"> <fileset refid="test.data.files" /> </resourcecount>
  </condition>

  <echo if:true="${has.test.data}">${test.data.dir} is exists and is not empty</echo>

</project>
</code>```

related  Ant: How can I ignore build error if directory doesn't exist?

Body:
I'm trying to base a task on whether a folder has content, not on whether it merely exists. I know there is probably a long winded solution, is there a better solution that I'm missing ?

I've tried two different methods to set a property depending on whether or not a folder has files in it.

My understanding is that 'available' does not permit wildcards like:

  <available property="has.test.data" file="${test.data.dir}/**" type="file"/>

I tried this but it does not work if the folder (test.data.dir) does not exist:

  <fileset id="test.data.files" dir="${test.data.dir}" includes="**/*" />
  <condition property="has.test.data">
    <resourcecount when="greater" count="0"> <fileset refid="test.data.files" /> </resourcecount>
  </condition>

Ideally, I want to base a task on whether the folder actually has content, not just an empty folder.

Body:
You can use erroronmissingdir="false", to avoid the error for a non-existing directory. Add else="false" if you need the property to always exist

<?xml version="1.0" encoding="utf-8"?>
<project name="Test resourcecount" xmlns:if="ant:if">

  <fileset id="test.data.files" dir="${test.data.dir}" includes="**/*" erroronmissingdir="false"/>
  <condition property="has.test.data" else="false">
    <resourcecount when="greater" count="0"> <fileset refid="test.data.files" /> </resourcecount>
  </condition>

  <echo if:true="${has.test.data}">${test.data.dir} is exists and is not empty</echo>

</project>

related  Ant: How can I ignore build error if directory doesn't exist?


来源: stackexchange

问:
Cannot find type 'ParseCloud' in scope - Back4App ios implementation
I am developing an ios app using Swift, Xcode, and back4app(Parse). I am trying to write an application launched function that connects to a function on the back end but am receiving this error. Any help would be great! Thank you in advance.

```<code>struct CloudUser: ParseCloud {
      typealias ReturnType = String
      var functionJobName: String
      var username: String
      var password: String
      var email: String
    }

    let cloudUser = CloudUser(functionJobName: "userRecord", username: self.userName.text!, password: self.password.text!, email: self.email.text!)
    cloudUser.runFunction { result in
          switch result {
          case .success(let response):
            print("Response from cloud function sumNumbers: \(response)")
          case .failure(let error):
            assertionFailure("Error calling cloud function sumNumbers: \(error)")
          }
        }
</code>```

Error: Cannot find type 'ParseCloud' in scope

答:
If ParseCloud isn't in scope, it seems you didn't add import ParseSwift at the top of your file. Make sure you installed the SDK properly. The preferred way is Swift Package Manager, but cocoapods and carthage should work as well.

Be sure to look at the Playground files for examples on how to use the Swift SDK:

import ParseSwift

//: Create your own value typed `ParseCloud` type.
struct Hello: ParseCloud {

    //: Return type of your Cloud Function
    typealias ReturnType = String

    //: These are required by `ParseCloud`, you can set the default value to make it easier
    //: to use.
    var functionJobName: String = "hello"
}

//: Create another `ParseCloud` type.
struct TestCloudCode: ParseCloud {

    //: Return type of your Cloud Function
    typealias ReturnType = [String: Int]

    //: These are required by `ParseCloud`, you can set the default value to make it easier
    //: to use.
    var functionJobName: String = "testCloudCode"

    //: If your cloud function takes arguments, they can be passed by creating properties:
    var argument1: [String: Int]
}

//: Create another `ParseCloud` type.
struct TestCloudCodeError: ParseCloud {

    //: Return type of your Cloud Function
    typealias ReturnType = String

    //: These are required by `ParseCloud`, you can set the default value to make it easier
    //: to use.
    var functionJobName: String = "testCloudCodeError"
}

/*: Assuming you have the Cloud Function named "hello" on your parse-server:
     // main.js
     Parse.Cloud.define('hello', async (request) => {
       console.log('From client: ' + JSON.stringify(request));
       return 'Hello world!';
     });
 */
let hello = Hello()

// Using async/await, the Playgounds shows how to use a completion handler
do {
  let result = try await hello.runFunction()
  print("Response from cloud function: \(response)")

} catch {

  print("Error calling cloud function: \(error)")
}
```

ContentLicense: CC BY-SA 4.0

Body:
I am developing an ios app using Swift, Xcode, and back4app(Parse). I am trying to write an application launched function that connects to a function on the back end but am receiving this error. Any help would be great! Thank you in advance.

struct CloudUser: ParseCloud {
      typealias ReturnType = String
      var functionJobName: String
      var username: String
      var password: String
      var email: String
    }

    let cloudUser = CloudUser(functionJobName: "userRecord", username: self.userName.text!, password: self.password.text!, email: self.email.text!)
    cloudUser.runFunction { result in
          switch result {
          case .success(let response):
            print("Response from cloud function sumNumbers: \(response)")
          case .failure(let error):
            assertionFailure("Error calling cloud function sumNumbers: \(error)")
          }
        }

Error: Cannot find type 'ParseCloud' in scope


问:
What do you suggest to make undo?
I use a series of data as follows:

```<code>[
  {
    name: 'name1',
    background:'red',
    child:[
        {
          name:'',
          id:'',
          color:'',
          text:'',
          border:''

        },
        {
          name:'',
          id:'',
          color:'',
          text:'',
          border:''

        }

      ]
  },
  {
    name: 'name2',
    background:'red',
    child:[
        {
          name:'',
          id:'',
          color:'',
          text:'',
          border:''

        },
        {
          name:'',
          id:'',
          color:'',
          text:'',
          border:''

        }

      ]
  }

  ]

</code>```

I'm going to save all the changes to another variable, and I used a deep copy to do that, but when I log in, the variables are the same.I need to children all the children changes too.

I wrote it in Reducers

```<code>
const Reducers =(state = initialState, action) => {
    switch (action.type) {
        case NEW_OBJECTS_PAST:

            const OldPast = JSON.parse(JSON.stringify(state.past))
            const newDate = JSON.parse(JSON.stringify(state.present))
            // const newDate = _.cloneDeep(state.present);

            const newPast = [
                                OldPast,
                                newDate
                            ];
            return {
                ...state,
                past : _.cloneDeep(newPast) ,
            }

        case OBJECTS:

            return  {
                        ...state,
                        present: action.objects,
                        // future:[]
            }

</code>```

Do you suggest another way to build undo in REACT and REDUX ?
I tried the libraries available for this, but got no answer.

答:
First two remarks :

you should never deep clone parts of your state, it doesn't bring you any benefits as the state is immutable anyway, but is very detrimental for memory usage and for performance (both when doing the deep cloning and then when using the deep cloned state),

you should use Redux toolkit, which makes it way easier to write immutable reducers and prevent many errors.

To implement undo, I'm not sure what your actions are supposed to mean but you can do it as follows

the state contains state.present (the current state) and state.past (an array of past states)

whenever you do an action that you want to undo, you push the current state.present at the end of state.past and compute the new state.present

whenever you want to undo, you pop the last element of state.past and put it in state.present.

In your code I can't see any undo action, and you're also building nested arrays because of new Past = [oldPast, new Date], you most likely meant to spread oldPast.

Title: What do you suggest to make undo?

Body:
I use a series of data as follows:

[
  {
    name: 'name1',
    background:'red',
    child:[
        {
          name:'',
          id:'',
          color:'',
          text:'',
          border:''

        },
        {
          name:'',
          id:'',
          color:'',
          text:'',
          border:''

        }

      ]
  },
  {
    name: 'name2',
    background:'red',
    child:[
        {
          name:'',
          id:'',
          color:'',
          text:'',
          border:''

        },
        {
          name:'',
          id:'',
          color:'',
          text:'',
          border:''

        }

      ]
  }

  ]

I'm going to save all the changes to another variable, and I used a deep copy to do that, but when I log in, the variables are the same.I need to children all the children changes too.

I wrote it in Reducers

const Reducers =(state = initialState, action) => {
    switch (action.type) {
        case NEW_OBJECTS_PAST:

            const OldPast = JSON.parse(JSON.stringify(state.past))
            const newDate = JSON.parse(JSON.stringify(state.present))
            // const newDate = _.cloneDeep(state.present);

            const newPast = [
                                OldPast,
                                newDate
                            ];
            return {
                ...state,
                past : _.cloneDeep(newPast) ,
            }

        case OBJECTS:

            return  {
                        ...state,
                        present: action.objects,
                        // future:[]
            }

Do you suggest another way to build undo in REACT and REDUX ?
I tried the libraries available for this, but got no answer.


问:
AWS API gateway return XML
I have a lambda function which returns an string(xml to string) to the API gateway. Now the API gateway returns the string but it is not an valid XML.
I already set the content type to application/xml.

The XML looks like this:

```<code>"<TEST xmlns:ns0=\"https://www.w3.org/2001/XMLSchema-instance\" version=\"3.0\" >\n  <InLine>\n  <tag1>valuetag1</tag1>\n</InLine>\n   \n</TEST>"
</code>```

How can I fix this?

答:
When returning a JSON object from AWS Lambda to API Gateway, send a 'Content-Type': 'text/xml' header and the XML string in the body.

```<code>exports.handler = async function (event) {
    const response = {
        statusCode: 200,
        headers: { 'Content-Type': 'text/xml' },
        body: "<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello</Message></Response>"
    };

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

If you are new to Lambda, the docs code examples don't address this XML but notably show important details on how the function parameters, return, and possible callback should be structured for async vs sync, promises, etc.

ContentLicense: CC BY-SA 3.0

Title: AWS API gateway return XML

Body:
I have a lambda function which returns an string(xml to string) to the API gateway. Now the API gateway returns the string but it is not an valid XML.
I already set the content type to application/xml.

The XML looks like this:

"<TEST xmlns:ns0=\"https://www.w3.org/2001/XMLSchema-instance\" version=\"3.0\" >\n  <InLine>\n  <tag1>valuetag1</tag1>\n</InLine>\n   \n</TEST>"

How can I fix this?

Body:
When returning a JSON object from AWS Lambda to API Gateway, send a 'Content-Type': 'text/xml' header and the XML string in the body.

exports.handler = async function (event) {
    const response = {
        statusCode: 200,
        headers: { 'Content-Type': 'text/xml' },
        body: "<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello</Message></Response>"
    };

    return response;
};

If you are new to Lambda, the docs code examples don't address this XML but notably show important details on how the function parameters, return, and possible callback should be structured for async vs sync, promises, etc.


问:
Not getting correct output using recursion in python sort because of arguments
I am trying merge with a different type, and I am unable to get the correct output. I just want to pass the list in the final function and get the sorted output. Can anyone please guide me where I am wrong??

```<code>def merge(arr, start, mer1, mer2, end):

    left_array = arr[start - 1 : mer1]
    mid_array = arr[mer1: mer2 + 1]
    right_array = arr[mer2 + 1 : end]

    left_array.append(float('inf'))
    mid_array.append(float('inf'))
    right_array.append(float('inf'))

    ind_left = 0
    ind_mid = 0
    ind_right = 0

    for i in range(start - 1, end):
        minimum = min([left_array[ind_left], mid_array[ind_mid], right_array[ind_right]])
        if minimum == left_array[ind_left]:
            arr[i] = left_array[ind_left]
            ind_left += 1
        elif minimum == mid_array[ind_mid]:
            arr[i] = mid_array[ind_mid]
            ind_mid += 1
        else:
            arr[i] = right_array[ind_right]
            ind_right += 1

def merge_sort(L, start = None, end = None):

    start = start or 1
    end = end or (len(L) - 1)

    if len(L[start - 1: end]) < 2:
        return L
    else:
        meg1 = start + ((end - start) // 3)
        meg2 = start + 2 * ((end - start) // 3)

        merge_sort(L, start, meg1)
        merge_sort(L, meg1 + 1, meg2 + 1)
        merge_sort(L, meg2 + 2, end)
        merge(L, start, meg1, meg2, end)
        return L

arr = [312,413,3,423,5,3,342,1,2, 69, 69, 76]
print (merge_sort(arr))
</code>```

The output I am getting is

[1, 2, 3, 3, 5, 69, 69, 312, 342, 413, 423, 76]

答:
I think you're just computing the wrong initial end position in the second line of your merge_sort function.  When I change the line:

```<code>end = end or (len(L) - 1)
</code>```

to:

```<code>end = end or len(L)
</code>```

I get the right result:

```<code>[1, 2, 3, 3, 5, 69, 69, 76, 312, 342, 413, 423]
</code>```

Body:
I am trying merge with a different type, and I am unable to get the correct output. I just want to pass the list in the final function and get the sorted output. Can anyone please guide me where I am wrong??

def merge(arr, start, mer1, mer2, end):

    left_array = arr[start - 1 : mer1]
    mid_array = arr[mer1: mer2 + 1]
    right_array = arr[mer2 + 1 : end]

    left_array.append(float('inf'))
    mid_array.append(float('inf'))
    right_array.append(float('inf'))

    ind_left = 0
    ind_mid = 0
    ind_right = 0

    for i in range(start - 1, end):
        minimum = min([left_array[ind_left], mid_array[ind_mid], right_array[ind_right]])
        if minimum == left_array[ind_left]:
            arr[i] = left_array[ind_left]
            ind_left += 1
        elif minimum == mid_array[ind_mid]:
            arr[i] = mid_array[ind_mid]
            ind_mid += 1
        else:
            arr[i] = right_array[ind_right]
            ind_right += 1

def merge_sort(L, start = None, end = None):

    start = start or 1
    end = end or (len(L) - 1)

    if len(L[start - 1: end]) < 2:
        return L
    else:
        meg1 = start + ((end - start) // 3)
        meg2 = start + 2 * ((end - start) // 3)

        merge_sort(L, start, meg1)
        merge_sort(L, meg1 + 1, meg2 + 1)
        merge_sort(L, meg2 + 2, end)
        merge(L, start, meg1, meg2, end)
        return L

arr = [312,413,3,423,5,3,342,1,2, 69, 69, 76]
print (merge_sort(arr))

The output I am getting is

[1, 2, 3, 3, 5, 69, 69, 312, 342, 413, 423, 76]

Body:
I think you're just computing the wrong initial end position in the second line of your merge_sort function.  When I change the line:

end = end or (len(L) - 1)

to:

end = end or len(L)

I get the right result:

[1, 2, 3, 3, 5, 69, 69, 76, 312, 342, 413, 423]


问:
How to create a loop from Excel worksheet names?
A very basic question here from a new python user.

I have an Excel sheet with 3 tabs

```<code>from openpyxl import load_workbook
# Load in the workbook and assign wb as name
wb = load_workbook('example.xlsx')
# Get sheet names
print(wb.sheetnames)
</code>```

Which gives these 3 in this example:

```<code>['Sheet1', 'Fuel', 'Games']
</code>```

So my question is how do I make these into a loop list (not sure why I'd want to other than I cannot figure out how to!)

答:
Here's how you can do it</p>
```<code>from openpyxl import load_workbook
# Load in the workbook and assign wb as name
wb = load_workbook('example.xlsx')
# Get sheet names
for sheet_name in wb.sheetnames:
    print(sheet_name)
</code>```

Body:
A very basic question here from a new python user.

I have an Excel sheet with 3 tabs

from openpyxl import load_workbook
# Load in the workbook and assign wb as name
wb = load_workbook('example.xlsx')
# Get sheet names
print(wb.sheetnames)

Which gives these 3 in this example:

['Sheet1', 'Fuel', 'Games']

So my question is how do I make these into a loop list (not sure why I'd want to other than I cannot figure out how to!)

Body:
Here's how you can do it

from openpyxl import load_workbook
# Load in the workbook and assign wb as name
wb = load_workbook('example.xlsx')
# Get sheet names
for sheet_name in wb.sheetnames:
    print(sheet_name)


问:
JQuery doesnot support custom attribute in IE*?
In html I have on table like this:

then I user jquery to find the table

```<code>var table = $("table[for='availableTimeRanges']");
</code>```

In firefox and chrome, this works,can return the table, but in IE8, nothing return
Then i run below code in IE8, found the attribute value is empty:

```<code>$.each($("table"), function(i,n){
        alert($(n).attr("for")

});
</code>```

what's the reason

答:
To add to what Šime Vidas said, Try Changing the name from for to something else like forparam, htmlfor, etc. (You can not use for with a table its for labels that are for an input)

```<code>$(function () {

        $('table[forparam=availableTimeRanges]').each(function () {
            alert($(this).attr('forparam'));
        });

    });
</code>```

Body:
In html I have on table like this:

then I user jquery to find the table

var table = $("table[for='availableTimeRanges']");

In firefox and chrome, this works,can return the table, but in IE8, nothing return
Then i run below code in IE8, found the attribute value is empty:

$.each($("table"), function(i,n){
        alert($(n).attr("for")

});

what's the reason

Body:
To add to what Šime Vidas said, Try Changing the name from for to something else like forparam, htmlfor, etc. (You can not use for with a table its for labels that are for an input)

$(function () {

        $('table[forparam=availableTimeRanges]').each(function () {
            alert($(this).attr('forparam'));
        });

    });


问:
A problem from python crash course by google
The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, … For example, group_list("g", ["a","b","c"]) returns "g: a, b, c". Fill in the gaps in this function to do that.

```<code>def group_list(group, users):
  members = ___
  return ___

print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha"
print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom"
print(group_list("Users", "")) # Should be "Users:"
</code>```

I have tried sth like this:

```<code>members = " "
for i in users:
    members += ",".join(i)
return ("{}:{}".format(group, members))
</code>```

output comes:

Marketing: M,i,k,eK,a,r,e,nJ,a,k,eT,a,s,h,a
Engineering: K,i,mJ,a,yT,o,m
Users:
```

but it didn't give the expected answer. Can anyone solve it with filling the blanks please ?

答:
This should give desired results:</p>
```<code> def group_list(group, users):
 members = ""
 for user in users:
   members += user + ", "
 return "{}: ".format(group) + members
</code>```

Body:
The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, … For example, group_list("g", ["a","b","c"]) returns "g: a, b, c". Fill in the gaps in this function to do that.

def group_list(group, users):
  members = ___
  return ___

print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha"
print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom"
print(group_list("Users", "")) # Should be "Users:"

I have tried sth like this:

members = " "
for i in users:
    members += ",".join(i)
return ("{}:{}".format(group, members))

output comes:

Marketing: M,i,k,eK,a,r,e,nJ,a,k,eT,a,s,h,a
Engineering: K,i,mJ,a,yT,o,m
Users:

but it didn't give the expected answer. Can anyone solve it with filling the blanks please ?

Body:
This should give desired results:

 def group_list(group, users):
 members = ""
 for user in users:
   members += user + ", "
 return "{}: ".format(group) + members


问:
Remove one index from the array in codeigniter controller
```<code>Array (
    [issuer_id] => in.gsvm
    [org_id] => 00738648
    [doc_type] => ABCDS
    [RROLL] => 12589
    [YEAR] => 2020
)
</code>```

I want to remove org_id from array and store that data in another variable

答:
Store the value in a variable:

```<code>$orgId = $array['org_id'];
</code>```

and remove it from the array:

```<code>unset($array['org_id']);
</code>```

This is just ordinary PHP which works the same in CodeIgniter.

Body:
Array (
    [issuer_id] => in.gsvm
    [org_id] => 00738648
    [doc_type] => ABCDS
    [RROLL] => 12589
    [YEAR] => 2020
)

I want to remove org_id from array and store that data in another variable

Body:
Store the value in a variable:

$orgId = $array['org_id'];

and remove it from the array:

unset($array['org_id']);

This is just ordinary PHP which works the same in CodeIgniter.


问:
natrsort function not returning values
I am trying to sort a flat file (.txt) in descending order.

Here's the list inside file.txt (name, age, ID No.) :

```<code>Jason, 24, 18299
Bryan, 19, 12999
James, 32, 72990
</code>```

My goal is to arrange the list in descending natural order based on the second column.
I tried making a natrsort function to reverse the arrangement.

Here's what i came up with:

```<code>    <?php
$rows = array();
$result = '';
$data = file('file.txt');

function natrsort(&$array) //the function i made to arrange them in descending order
{
    natsort($array);
    $array = array_reverse($array);
}

foreach($data as $key => $val) {
    $rowarray = explode(",", $val);
    $rows[] = $rowarray[1];
}

natrsort($rows);

//print_r($rows); When I use this, everything seems to work.

foreach($rows as $key => $val) {
 $result .= trim($data[$key]) . "<br/>";
}

echo $result; //display the new sorted list
</code>```

The output keeps displaying the same list. No Sorting happened. Maybe I am missing something?

答:
When you use $data[$key], $key is equals to 0,1 and 2, because array_reverse() re-index the array. So, your printed array is in the same order than your data in the file.

You could use natsort(), then, reverse the array of keys only:

natsort($rows);
$indexes = array_reverse(array_keys($rows));
foreach ($indexes as $key) {
    $result .= trim($data[$key]) . '
';
}
```
<p>Prints:</p>
```James, 32, 72990
Jason, 24, 18299
Bryan, 19, 12999

```
<hr />
<p><strong>Another way</strong> is to sort using a custom sort function like <code>usort()</code>:</p>
<pre class="lang-php prettyprint-override"><code>$result = '';
$data   = file('file.txt');

usort($data, function($a, $b) {
   [, $ageA] = explode(',', $a);
   [, $ageB] = explode(',', $b);
   return intval($ageB) <=> intval($ageA);
});

foreach ($data as $val) {
    $result .= trim($val) . '<br>';
}
echo $result;
</code>```

Output:

```<code>James, 32, 72990<br>Jason, 24, 18299<br>Bryan, 19, 12999<br>
</code>```

Title: natrsort function not returning values

Body:
I am trying to sort a flat file (.txt) in descending order.

Here's the list inside file.txt (name, age, ID No.) :

Jason, 24, 18299
Bryan, 19, 12999
James, 32, 72990

My goal is to arrange the list in descending natural order based on the second column.
I tried making a natrsort function to reverse the arrangement.

Here's what i came up with:

    <?php
$rows = array();
$result = '';
$data = file('file.txt');

function natrsort(&$array) //the function i made to arrange them in descending order
{
    natsort($array);
    $array = array_reverse($array);
}

foreach($data as $key => $val) {
    $rowarray = explode(",", $val);
    $rows[] = $rowarray[1];
}

natrsort($rows);

//print_r($rows); When I use this, everything seems to work.

foreach($rows as $key => $val) {
 $result .= trim($data[$key]) . "
";
}

echo $result; //display the new sorted list

The output keeps displaying the same list. No Sorting happened. Maybe I am missing something?

Body:
When you use $data[$key], $key is equals to 0,1 and 2, because array_reverse() re-index the array. So, your printed array is in the same order than your data in the file.

You could use natsort(), then, reverse the array of keys only:

natsort($rows);
$indexes = array_reverse(array_keys($rows));
foreach ($indexes as $key) {
    $result .= trim($data[$key]) . '<br>';
}

Prints:

James, 32, 72990<br>Jason, 24, 18299<br>Bryan, 19, 12999<br>

Another way is to sort using a custom sort function like usort():

$result = '';
$data   = file('file.txt');

usort($data, function($a, $b) {
   [, $ageA] = explode(',', $a);
   [, $ageB] = explode(',', $b);
   return intval($ageB) <=> intval($ageA);
});

foreach ($data as $val) {
    $result .= trim($val) . '<br>';
}
echo $result;

Output:

James, 32, 72990<br>Jason, 24, 18299<br>Bryan, 19, 12999<br>


问:
Using Imagick in Symfony2?
I am trying to use Imagick with Symfony2, but every time I try and use it, it gives me the following error:

```<code>Fatal error: Class 'Acme\TestBundle\Services\Imagick' not found...
</code>```

I am using Imagick in a service I have setup to manage my images. What do I need to do to be able to use this class?

I can confirm the Imagick extension is working on the server and is in use by other sites.

Thanks in advance for any help.

答:
When you instantiate the Imagick class, use a full quallified class-name:

```<code>new \Imagick;
</code>```

This will make PHP not look for the class Imagick within the current namespace.

For a more detailed explanation see a similar Question/Answer: Problems with PHP namespaces and built-in classes, how to fix? and How to use "root" namespace of php?.

Title: Using Imagick in Symfony2?

Body:
I am trying to use Imagick with Symfony2, but every time I try and use it, it gives me the following error:

Fatal error: Class 'Acme\TestBundle\Services\Imagick' not found...

I am using Imagick in a service I have setup to manage my images. What do I need to do to be able to use this class?

I can confirm the Imagick extension is working on the server and is in use by other sites.

Thanks in advance for any help.

Body:
When you instantiate the Imagick class, use a full quallified class-name:

new \Imagick;

This will make PHP not look for the class Imagick within the current namespace.

For a more detailed explanation see a similar Question/Answer: Problems with PHP namespaces and built-in classes, how to fix? and How to use "root" namespace of php?.


问:
VBA Excel Button to Hide/Unhide Cells with password protection
I want to Hide or Unhide Cells, (not worksheet, I can use Range), using VBA and protect the button so to hide or unhide needs a password to make it work.
Can you help?

Thank you!

答: Call a inputbox and set the password there on buttonclick, if correct run your code.</p>


问:
Springboot not returning index.jsp
When I am running my Sprinboot Application, it is just returning index as string. It is not giving me index.jsp page. Also I have tried to add some jstl compiler in it still it is not working

The code of Main file:

```<code>package com.hello.first;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FirstApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstApplication.class, args);
    }

}
</code>```

The Controller file:

```<code>package com.hello.first;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class firstpage {

    @RequestMapping("/")
    public String hello(){
        return "index";
    }
}
</code>```

Application.properties:

server.port=8000

spring.mvc.view.prefix=/WEB-INF/

spring.mvc.view.suffix= .jsp

POM.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hello</groupId>
    <artifactId>first</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>first</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <!-- JSTL for JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- Need this to compile JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jdt.core.compiler</groupId>
            <artifactId>ecj</artifactId>
            <version>4.6.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

index.jsp:

```<code><%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    Hello this is my page!!
</body>
</html>
</code>```

Output I am getting:

```<code>index
</code>```

答:
use</p>
```<code>return "index.jsp"  instead
 return "index"
</code>```

Title: Springboot not returning index.jsp

Body:
When I am running my Sprinboot Application, it is just returning index as string. It is not giving me index.jsp page. Also I have tried to add some jstl compiler in it still it is not working

The code of Main file:

package com.hello.first;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FirstApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstApplication.class, args);
    }

}

The Controller file:

package com.hello.first;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class firstpage {

    @RequestMapping("/")
    public String hello(){
        return "index";
    }
}

Application.properties:

server.port=8000

spring.mvc.view.prefix=/WEB-INF/

spring.mvc.view.suffix= .jsp

POM.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/>
    </parent>
    <groupId>com.hello</groupId>
    <artifactId>first</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>first</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jdt.core.compiler</groupId>
            <artifactId>ecj</artifactId>
            <version>4.6.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

index.jsp:

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    Hello this is my page!!

Output I am getting:

index

Body:
use

return "index.jsp"  instead
 return "index"


问:
How can I have my button link to another js file using React?
FYI, I am new to React. How can I have my button on my home page of my restaurant website link my menu.js file? I'm assuming this is fairly simple, but I couldn't find the syntax to link my menu page to my home page.

Here is my code so far.

```<code>         <div>
            <Card className="text-center">
                <Card.Header>Featured</Card.Header>
                <Card.Body>
                    <Card.Title>Menu</Card.Title>
                    <Card.Text>
                    orem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. At consectetur lorem donec massa sapien. Euismod lacinia at quis risus sed vulputate odio ut.
                    </Card.Text>
                    <Button onClick={clickMe}>
                        View Full Menu
                    </Button>
                </Card.Body>
                <Card.Footer className="text-muted"></Card.Footer>
            </Card>
        </div>
</code>```

答:
You can use the Link component and define the menu component in the Route component.

```<code>import { Link,Route } from 'react-router-dom';

<Link to='/menu'>
    View Full Menu
</Link>
<Route path="/menu">
   <Menu />
</Route>
</code>```

Read more: https://reactrouter.com/web/api/Link

Body:
FYI, I am new to React. How can I have my button on my home page of my restaurant website link my menu.js file? I'm assuming this is fairly simple, but I couldn't find the syntax to link my menu page to my home page.

Here is my code so far.

            <Card className="text-center">
                <Card.Header>Featured</Card.Header>
                <Card.Body>
                    <Card.Title>Menu</Card.Title>
                    <Card.Text>
                    orem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. At consectetur lorem donec massa sapien. Euismod lacinia at quis risus sed vulputate odio ut.
                    </Card.Text>
                    <Button onClick={clickMe}>
                        View Full Menu
                    </Button>
                </Card.Body>
                <Card.Footer className="text-muted"></Card.Footer>
            </Card>

Body:
You can use the Link component and define the menu component in the Route component.

import { Link,Route } from 'react-router-dom';

<Link to='/menu'>
    View Full Menu
</Link>
<Route path="/menu">
   <Menu />
</Route>

Read more: https://reactrouter.com/web/api/Link


问:
Is it possible to alter Math Equations in a loop?
Take this array of math expressions, which are NOT strings:

```<code>let eqs = [ 1+n, 2+n, 3+n]
</code>```

Is it possible to loop through these equations and modify them WITHOUT evaluating them in javascript somehow?

```<code>eqs.map(eq => eq + 1)
</code>```

...and return this:

```<code>// [ 1+n+1, 2+n+1, 3+n+1]
</code>```

Is something like that even possible at all? Doesn't have to be .map() just using that as an example. Doesn't have to be that syntax, i just can't imagine what the syntax for something like that might be is all...

Been googling around but I haven't found much yet...but I am getting the feeling that this might NOT be possible...is that the case?

Thank you for any assistance :-)

答:
This could be a starting point:

let eqs = [ "1+n", "2+n", "3+n"]
let modeqs = eqs.map(eq => eq+"+1")
console.log(modeqs);
[0,8,15].map(n=>console.log(modeqs.map(s=>(new Function('n','return '+s))(n))))```
</div>
</div>
</p>
<p>The <strong>updated</strong> snippet now contains a part that  converts each formula into a function and then executes it in a <code>.map()</code> structure.</p>
<p>Alternatively you could start with and manipulate actual functions:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let eqs = [ n=>1+n, n=>2+n, n=>3+n]
let modeqs = eqs.map(fn => eval(fn.toString()+"+1") )
console.log(modeqs);

[0,8,15].map(n=>console.log(modeqs.map(fn=>fn(n))));</code>```

The last example uses eval() which by many is seen as a possible security risk. So, please think about where and when you want to use it.

Body:
Take this array of math expressions, which are NOT strings:

let eqs = [ 1+n, 2+n, 3+n]

Is it possible to loop through these equations and modify them WITHOUT evaluating them in javascript somehow?

eqs.map(eq => eq + 1)

...and return this:

// [ 1+n+1, 2+n+1, 3+n+1]

Is something like that even possible at all? Doesn't have to be .map() just using that as an example. Doesn't have to be that syntax, i just can't imagine what the syntax for something like that might be is all...

Been googling around but I haven't found much yet...but I am getting the feeling that this might NOT be possible...is that the case?

Thank you for any assistance :-)

Body:
This could be a starting point:

let eqs = [ "1+n", "2+n", "3+n"]
let modeqs = eqs.map(eq => eq+"+1")
console.log(modeqs);
[0,8,15].map(n=>console.log(modeqs.map(s=>(new Function('n','return '+s))(n))))

The updated snippet now contains a part that  converts each formula into a function and then executes it in a .map() structure.

Alternatively you could start with and manipulate actual functions:

let eqs = [ n=>1+n, n=>2+n, n=>3+n]
let modeqs = eqs.map(fn => eval(fn.toString()+"+1") )
console.log(modeqs);

[0,8,15].map(n=>console.log(modeqs.map(fn=>fn(n))));

The last example uses eval() which by many is seen as a possible security risk. So, please think about where and when you want to use it.


问:
AWS EKS service ingress and ALB --no ADDRESS
I seem to be having an issue with the way my ports are setup on this manifest, which is a simple go app. The app is configured to listen on port 3000.
This container runs fine on my local machine (localhost:3000), but I get no ADDRESS when I look at the Ingress (k get ingress ...).
I am getting an error logged in the AWS aws-load-balancer-controller log when I try to run this image on EKS:

```<code>controller-runtime.manager.controller.ingress","msg":"Reconciler error","name":"fiber-demo","namespace":"demo","error":"ingress: demo/fiber-demo: unable to find port 3000 on service demo/fiber-demo"
</code>```

This is my k8s manifest:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: fiber-demo
  namespace: demo
  labels:
    app: fiber-demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: fiber-demo
  template:
    metadata:
      labels:
        app: fiber-demo
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: kubernetes.io/arch
                    operator: In
                    values:
                      - amd64
                      - arm64
      containers:
        - name: fiber-demo
          image: 240195868935.dkr.ecr.us-east-2.amazonaws.com/fiber-demo:0.0.2
          resources:
            requests:
              memory: "64Mi"
              cpu: "250m"
            limits:
              memory: "128Mi"
              cpu: "500m"
          ports:
            - containerPort: 3000

---
apiVersion: v1
kind: Service
metadata:
  name: fiber-demo
  namespace: demo
  labels:
    app: fiber-demo
spec:
  selector:
    app: fiber-demo
  ports:
  - protocol: TCP
    port: 80
    targetPort: 3000

---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: fiber-demo
  namespace: demo
  annotations:
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/scheme: internet-facing

  labels:
    app: fiber-demo
spec:
  rules:
    - http:
        paths:
          - path: /
            backend:
              serviceName: fiber-demo
              servicePort: 3000
</code>```

Am I simply not able to specify a targetPort other than port 80 in the Service?

答:
Am I simply not able to specify a targetPort other than port 80 in the Service?

backend.servicePort refers to port exposed by service, not container.

```<code>...
backend:
  serviceName: fiber-demo  # <-- ingress for this service, not container
  servicePort: 80          # <-- port which the service exposed, not the port which the container exposed.
</code>```

Body:
I seem to be having an issue with the way my ports are setup on this manifest, which is a simple go app. The app is configured to listen on port 3000.
This container runs fine on my local machine (localhost:3000), but I get no ADDRESS when I look at the Ingress (k get ingress ...).
I am getting an error logged in the AWS aws-load-balancer-controller log when I try to run this image on EKS:

controller-runtime.manager.controller.ingress","msg":"Reconciler error","name":"fiber-demo","namespace":"demo","error":"ingress: demo/fiber-demo: unable to find port 3000 on service demo/fiber-demo"

This is my k8s manifest:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: fiber-demo
  namespace: demo
  labels:
    app: fiber-demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: fiber-demo
  template:
    metadata:
      labels:
        app: fiber-demo
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: kubernetes.io/arch
                    operator: In
                    values:
                      - amd64
                      - arm64
      containers:
        - name: fiber-demo
          image: 240195868935.dkr.ecr.us-east-2.amazonaws.com/fiber-demo:0.0.2
          resources:
            requests:
              memory: "64Mi"
              cpu: "250m"
            limits:
              memory: "128Mi"
              cpu: "500m"
          ports:
            - containerPort: 3000

---
apiVersion: v1
kind: Service
metadata:
  name: fiber-demo
  namespace: demo
  labels:
    app: fiber-demo
spec:
  selector:
    app: fiber-demo
  ports:
  - protocol: TCP
    port: 80
    targetPort: 3000

---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: fiber-demo
  namespace: demo
  annotations:
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/scheme: internet-facing

  labels:
    app: fiber-demo
spec:
  rules:
    - http:
        paths:
          - path: /
            backend:
              serviceName: fiber-demo
              servicePort: 3000

Am I simply not able to specify a targetPort other than port 80 in the Service?

Body:
Am I simply not able to specify a targetPort other than port 80 in the Service?

backend.servicePort refers to port exposed by service, not container.

...
backend:
  serviceName: fiber-demo  # <-- ingress for this service, not container
  servicePort: 80          # <-- port which the service exposed, not the port which the container exposed.


问:
how to return promise from an async code block
I want to send an http request and return the result using typescript, before send the http request, I want to get the token from google chrome local storage and put the token into http header. This is my typescript code looks like:

```<code>api_post:<T>(url: string, data: any): Promise<T> => {
    chrome.storage.local.get("token", function (result:any) {
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
                'x-access-token': result,
            },
            body: JSON.stringify(data),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(response.statusText);
                }
                return response.json() as Promise<T>;
            });
    });
},
</code>```

the problem is the promise return from the inner of an async code block, this function shows error:

```<code>interface Promise<T>
Represents the completion of an asynchronous operation

A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)
</code>```

what should I do to return the promise inside the chrome local storage get and make the code works?

答:
To follow-up on my comment, you could do something like:

```<code>api_post: async (url: string, data: any): Promise<T> => {
    const { result } = await chrome.storage.local.get("token");
    const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
                'x-access-token': result,
            },
            body: JSON.stringify(data),
        });
    return response;
},
</code>```

Note: This is just to give you an idea of how you could refactor your method using async/await. This code will probably require some tweaking.

Body:
I want to send an http request and return the result using typescript, before send the http request, I want to get the token from google chrome local storage and put the token into http header. This is my typescript code looks like:

api_post:<T>(url: string, data: any): Promise<T> => {
    chrome.storage.local.get("token", function (result:any) {
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
                'x-access-token': result,
            },
            body: JSON.stringify(data),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(response.statusText);
                }
                return response.json() as Promise<T>;
            });
    });
},

the problem is the promise return from the inner of an async code block, this function shows error:

interface Promise<T>
Represents the completion of an asynchronous operation

A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)

what should I do to return the promise inside the chrome local storage get and make the code works?

Body:
To follow-up on my comment, you could do something like:

api_post: async (url: string, data: any): Promise<T> => {
    const { result } = await chrome.storage.local.get("token");
    const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
                'x-access-token': result,
            },
            body: JSON.stringify(data),
        });
    return response;
},

Note: This is just to give you an idea of how you could refactor your method using async/await. This code will probably require some tweaking.


问:
Print() for breaking line in python
I had to write a program to print the below pattern.

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

Now , the code which is given is as :

num = int(input())

for i in range (1,num+1):
     for j in range (1 , i +1):
          print(j, end = " ")
     print()
```

But I don't understand that how a new line will be started after each loop without using \n  . My teacher told that the print() in the last is used to break line . But I don't understand that what is going on .

答:
By default, print function has end='\n' as argument. That's why it provides a new line after its' execution.
you can change that with anything, like end=' '(this will put an extra space ), end = '.' (this will add a full stop at the end)

the print function bears this Infos

```<code>print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
</code>```

Title: Print() for breaking line in python

Body:
I had to write a program to print the below pattern.

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

Now , the code which is given is as :

num = int(input())

for i in range (1,num+1):
     for j in range (1 , i +1):
          print(j, end = " ")
     print()

But I don't understand that how a new line will be started after each loop without using \n  . My teacher told that the print() in the last is used to break line . But I don't understand that what is going on .

Body:
By default, print function has end='\n' as argument. That's why it provides a new line after its' execution.
you can change that with anything, like end=' '(this will put an extra space ), end = '.' (this will add a full stop at the end)

the print function bears this Infos

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)


问:
C++ : read a csv file and extract some parts
A .csv file is written like this:

```<code>    M9005U00-X30A0S00-1;BAS;X;-0.002;-0.095
    S707RY00-X30AOS00-1;HMV;X;+0.002;+0.081
    W3005U00-X30BOJ00-1;BAS;X;+0.026;-0.138
    H307QZ00-X30BOJ00-1;HMV;X;-0.025;+0.122
    ....
</code>```

now I want to create a function, i.e.

```<code>      double find_and_extract (string sss)
</code>```

when this function is used with a keyword as its parameter, for example

```<code>      find_and_extract (W3005U00-X30BOJ00-1);
</code>```

it will search in the .csv file line by line, find corresponding line (in this case it should be the third line), and extract the certin part "+0.026" in this line, return as a double.

How should I write this function?

edit: Here is the code i've written so far:

```<code>    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdio.h>
    #include <vector>
    #include <iterator>
    #include <cstdlib>
    #include <cstdio>
    #include <sstream>
    #include <stdlib.h>

    using namespace std;

    void main()
        {
           find_and_extract (W3005U00-X30BOJ00-1);
        }

    double find_and_extract (string sss)
         {
             vector<string> vecarray;
             ifstream infile("C:\\Data\\testdata.csv");
             string temppo;
             string contnt;
             char csv_extract[40];
             stringstream ss;
             vector <string>::iterator ptr;
             while (!infile.eof())
               {
                 infile.getline(csv_extract,40);
                 ss << csv_extract;
                 ss >> contnt;
                 vecarray.push_back(contnt);
                }
             for (ptr=vecarray.begin();ptr!=vecarray.end();ptr++)
             {
                 if ((*ptr).find(sss)==0)
                     temppo = (*ptr).substr(27,6);
             }
             return (strtod(temppo.c_str(),NULL,0));
        }
</code>```

Could anyone help me out to point out the errors?

答:
If the text lines in the file are the same length, you may want to read the lines as blocks (i.e. many lines == 1 block) into a buffer, then search the buffer.

Your performance bottleneck will the reading the data from the file.  In general, the search method you choose will be faster than reading in the data.

Body:
A .csv file is written like this:

    M9005U00-X30A0S00-1;BAS;X;-0.002;-0.095
    S707RY00-X30AOS00-1;HMV;X;+0.002;+0.081
    W3005U00-X30BOJ00-1;BAS;X;+0.026;-0.138
    H307QZ00-X30BOJ00-1;HMV;X;-0.025;+0.122
    ....

now I want to create a function, i.e.

      double find_and_extract (string sss)

when this function is used with a keyword as its parameter, for example

      find_and_extract (W3005U00-X30BOJ00-1);

it will search in the .csv file line by line, find corresponding line (in this case it should be the third line), and extract the certin part "+0.026" in this line, return as a double.

How should I write this function?

edit: Here is the code i've written so far:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdio.h>
    #include <vector>
    #include <iterator>
    #include <cstdlib>
    #include <cstdio>
    #include <sstream>
    #include <stdlib.h>

    using namespace std;

    void main()
        {
           find_and_extract (W3005U00-X30BOJ00-1);
        }

    double find_and_extract (string sss)
         {
             vector<string> vecarray;
             ifstream infile("C:\\Data\\testdata.csv");
             string temppo;
             string contnt;
             char csv_extract[40];
             stringstream ss;
             vector <string>::iterator ptr;
             while (!infile.eof())
               {
                 infile.getline(csv_extract,40);
                 ss << csv_extract;
                 ss >> contnt;
                 vecarray.push_back(contnt);
                }
             for (ptr=vecarray.begin();ptr!=vecarray.end();ptr++)
             {
                 if ((*ptr).find(sss)==0)
                     temppo = (*ptr).substr(27,6);
             }
             return (strtod(temppo.c_str(),NULL,0));
        }

Could anyone help me out to point out the errors?


答:
You can use unset().

php > $array = Array (0 => 123, 1 => 456);
php > unset($array[0]);
php > print_r($array);
Array
(
    [1] => 456
)

```
<p>It destroys the variable, which in this case is the array item matching the index that you want to delete.</p>
<p>You assign the value to a new variable before removing it.</p>
<pre class="lang-php prettyprint-override"><code>php > $array = Array (0 => 123, 1 => 456);
php > $v = $array[0];
php > unset($array[0]);
php > print_r($array);
Array
(
    [1] => 456
)
php > echo $v;
123

</code>```

Title: Remove one index from the array in codeigniter controller

Body:
Array (
    [issuer_id] => in.gsvm
    [org_id] => 00738648
    [doc_type] => ABCDS
    [RROLL] => 12589
    [YEAR] => 2020
)

I want to remove org_id from array and store that data in another variable

Body:
You can use unset().

php > $array = Array (0 => 123, 1 => 456);
php > unset($array[0]);
php > print_r($array);
Array
(
    [1] => 456
)

It destroys the variable, which in this case is the array item matching the index that you want to delete.

You assign the value to a new variable before removing it.

php > $array = Array (0 => 123, 1 => 456);
php > $v = $array[0];
php > unset($array[0]);
php > print_r($array);
Array
(
    [1] => 456
)
php > echo $v;
123


问:
Trying to do a flutter pub get and got Process finished with exit code 66
```<code>Running "flutter pub get" in mobile...
Because mobile depends on charts_flutter from path which doesn't exist (could not find package charts_flutter at "../mobile-dependencies/pub.dartlang.org/charts_flutter-0.12.0"), version solving failed.
pub get failed (66; Because mobile depends on charts_flutter from path which doesn't exist (could not find package charts_flutter at "../mobile-dependencies/pub.dartlang.org/charts_flutter-0.12.0"), version solving failed.)
Process finished with exit code 66

/Users/H025712/development/flutter/bin/flutter --no-color pub get
Running "flutter pub get" in mobile...
Because mobile depends on charts_flutter from path which doesn't exist (could not find package charts_flutter at "../mobile-dependencies/pub.dartlang.org/charts_flutter-0.12.0"), version solving failed.
pub get failed (66; Because mobile depends on charts_flutter from path which doesn't exist (could not find package charts_flutter at "../mobile-dependencies/pub.dartlang.org/charts_flutter-0.12.0"), version solving failed.)
</code>```

答:
Talked to my tech lead, who is familiar with the code; he said to check out the missing code that was referencing overrides in the pubspec.yaml:

https://dart.dev/tools/pub/dependencies

Dependency overrides

You can use dependency_overrides to temporarily override all references to a dependency.

For example, perhaps you are updating a local copy of transmogrify, a
published library package. Transmogrify is used by other packages in
your dependency graph, but you don’t want to clone each package
locally and change each pubspec to test your local copy of
transmogrify.

In this situation, you can override the dependency using
dependency_overrides to specify the directory holding the local copy
of the package.

The pubspec would look something like the following:

```<code>name: my_app
dependencies:
  transmogrify: ^1.2.0
dependency_overrides:
  transmogrify:
    path: ../transmogrify_patch/
</code>```

Body:
Talked to my tech lead, who is familiar with the code; he said to check out the missing code that was referencing overrides in the pubspec.yaml:

https://dart.dev/tools/pub/dependencies

Dependency overrides

You can use dependency_overrides to temporarily override all references to a dependency.

For example, perhaps you are updating a local copy of transmogrify, a
published library package. Transmogrify is used by other packages in
your dependency graph, but you don’t want to clone each package
locally and change each pubspec to test your local copy of
transmogrify.

In this situation, you can override the dependency using
dependency_overrides to specify the directory holding the local copy
of the package.

The pubspec would look something like the following:

name: my_app
dependencies:
  transmogrify: ^1.2.0
dependency_overrides:
  transmogrify:
    path: ../transmogrify_patch/


问:
How to use `Environ("USERPROFILE")` to open workbook on desktop , while desktop location changed to another drive (D)?
On my work PC, I have no write on system drive (c).

So, I have used properties of desktop folder and changed location of it to another drive (d).

From windows 10,  I am using my desktop from that drive (d) similarly as it was on drive (c).

Problem: I tried this vba code to open workbook on my desktop

```<code>Dim wb1 As Workbook: Set wb1 = Workbooks.Open(Environ("USERPROFILE") & "\Desktop\Query1.xls")
</code>```

,but I got this error

Run-time error 1004:Sorry, we couldn't find C:\Users\Waleed\Desktop\Query1.xls. Is it possible it was moved, renamed or deleted?

I am asking this question, as I use excel files on my work pc and my laptop (no restriction) interchangeably

And it is hard to change my vba codes every time I change my machine.

As always , thanks for any help.

答: Do a check if it finds the file, else set a different path.</p>

Body:
On my work PC, I have no write on system drive (c).

So, I have used properties of desktop folder and changed location of it to another drive (d).

From windows 10,  I am using my desktop from that drive (d) similarly as it was on drive (c).

Problem: I tried this vba code to open workbook on my desktop

Dim wb1 As Workbook: Set wb1 = Workbooks.Open(Environ("USERPROFILE") & "\Desktop\Query1.xls")

,but I got this error

Run-time error 1004:Sorry, we couldn't find C:\Users\Waleed\Desktop\Query1.xls. Is it possible it was moved, renamed or deleted?

I am asking this question, as I use excel files on my work pc and my laptop (no restriction) interchangeably

And it is hard to change my vba codes every time I change my machine.

As always , thanks for any help.


问:
Twitter OAuth Login Page on the iPhone
I have Twitter integrated into my application, with the help of Sharekit. Everything works pretty well except, if the user happens to tap on the "Sign Up" link on the Login/allow page, it goes to a non-sign up error page. Either a "Sorry that page doesn't exist" or "Hold up! Sorry the profile you were trying to view was suspended due to strange activity."

The account I'm using is working as far as logging in, posting etc. But that link seems to go off into space. Also if I click on the "Twitter Gear"/Application Icon the dialog (web view with the Twitter OAuth Authorize page loaded) just closes.

I can't find anything about how to configure stuff like this and everything else seemed to work pretty easily. The closest reference I could find was,this link Twitter API Issue 1045

Thanks in Advance for any help

Update:
I've been checking a few other apps with Twitter support. Most of the ones I've checked (TUAW,Joystiq,TFLN) seem to have rolled their own Twitter Login Page (using XAuth I assume) the one I found that uses the Twitter OAuth page (Shazam) actually takes you to mobile Safari and it exhibits the same behavior. Maybe I need to roll my own login?

答: I suggest using a packet sniffer on your device to determine the exact URL being called when you click the "Sign Up" link. There are plenty of ways to do this, but it is easier on jailbroken phones. Armed with the URL, you can see if it is potentially something you are doing wrong or indeed a twitter bug. </p>

ContentLicense: CC BY-SA 2.5

Title: Twitter OAuth Login Page on the iPhone


问:
Fabric.js / fabricjs in Svelte, is there any workaround?
I have tried this code in REPL but couldn't find any working example. I am trying to free drawing on canvas using fabric pencil brush, however, this is only a rectangle:</p>
```<code><script>

    const fabric = () => {
        fabric = new window.fabric();
    }

    function drawMD(){
        let canvas = new fabric.Canvas('c')
        let rect =  new fabric.Rect({
            left:150, top, 150, fill: 'red, width: 200, height: 200, angle: 45
        })

        canvas.add(rect)
    }
</script>

<svelte:head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/500/fabric.min.js" on:load={fabric}></script>
</svelte:head>

<div className="MarkdownEditor">
    <canvas id="c" width="600" height="600" style="border:1px solid #000000;" on:click={drawMD}>
</canvas>
</div>
</code>```

答:
You don't need the window part, there are some typos in the Rect object and className won't work in Svelte. If you want to directly draw without having to click on the canvas, you can do this inside onMount. Here's a working REPL

(when opening the REPL there might be an errorfabric is not defined - just move the <svelte:head> one line down, then it's working...)

```<code><svelte:head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/500/fabric.min.js"></script>
</svelte:head>

<script>
    import {onMount} from 'svelte'

    onMount(() => {
        let canvas = new fabric.Canvas('c2')
        let rect =  new fabric.Rect({
            left:120, top: 10, fill: 'teal', width: 150, height: 150, angle: 45
        })
        canvas.add(rect)
    })

    function drawMD(){
        let canvas = new fabric.Canvas('c')
        let rect =  new fabric.Rect({
            left:120, top: 10, fill: 'red', width: 150, height: 150, angle: 45
        })
        canvas.add(rect)
    }
</script>

<div class="MarkdownEditor">
    <canvas id="c" width="250" height="250" style="border:1px solid #000000;" on:click={drawMD}></canvas>
</div>

<canvas id="c2" width="250" height="250" style="border:1px solid #000000;"></canvas>
</code>```

Body:
I have tried this code in REPL but couldn't find any working example. I am trying to free drawing on canvas using fabric pencil brush, however, this is only a rectangle:

<svelte:head>

</svelte:head>

    <canvas id="c" width="600" height="600" style="border:1px solid #000000;" on:click={drawMD}>
</canvas>

Body:
You don't need the window part, there are some typos in the Rect object and className won't work in Svelte. If you want to directly draw without having to click on the canvas, you can do this inside onMount. Here's a working REPL

(when opening the REPL there might be an errorfabric is not defined - just move the <svelte:head> one line down, then it's working...)

<svelte:head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/500/fabric.min.js"></script>
</svelte:head>

<script>
    import {onMount} from 'svelte'

    onMount(() => {
        let canvas = new fabric.Canvas('c2')
        let rect =  new fabric.Rect({
            left:120, top: 10, fill: 'teal', width: 150, height: 150, angle: 45
        })
        canvas.add(rect)
    })

    function drawMD(){
        let canvas = new fabric.Canvas('c')
        let rect =  new fabric.Rect({
            left:120, top: 10, fill: 'red', width: 150, height: 150, angle: 45
        })
        canvas.add(rect)
    }
</script>

<div class="MarkdownEditor">
    <canvas id="c" width="250" height="250" style="border:1px solid #000000;" on:click={drawMD}></canvas>
</div>

<canvas id="c2" width="250" height="250" style="border:1px solid #000000;"></canvas>


问:
Creating an instance of a generic
This is probably a noob question, so sorry in advance for my inexperience...

So I have a list with thousands of elements which fluctuates frequently, so I created this Coroutine to update it without creating a whole new list and populating it every time it changes...

```<code>    public static IEnumerator ListSetup(List<Vector3> list, int resolution)
    {
        while (list.Count != resolution)
        {
            if (list.Count < resolution)
                list.Add(new Vector3());
            if (list.Count > resolution)
                list.RemoveAt(list.Count - 1);
        }
        yield return null;
    }
</code>```

...and it works a treat.

Then, I wanted to modify it so that it can take any type of list, not just Vector3's, but I have been having some trouble with the syntax..

```<code>    public static IEnumerator ListSetup<T>(List<T> list, int resolution)
    {
        while (list.Count != resolution)
        {
            if (list.Count < resolution)
                list.Add(new T());//Error Here
            if (list.Count > resolution)
                list.RemoveAt(list.Count - 1);
        }
        yield return null;
    }
</code>```

I've tried typeof(T), GetType(T), typeof(T).MakeGenericType(), Add(T), and tons of other variations, but it is clear that I just don't understand how Types and Generics work.

Any help would be appreciated.

答:
You have not been to far away from the answer. The missing part is to restrict the type T to only allow objects with a public parameter-less constructor.

This is done with the generic type-constraint where and the new-constraint

```<code>public static IEnumerator ListSetup<T> (List<T> list, int resolution) where T : new()
{
    while (list.Count != resolution)
    {
        if (list.Count < resolution)
            list.Add(new T());
        if (list.Count > resolution)
            list.RemoveAt(list.Count - 1);
    }
    yield return null;
}
</code>```

Title: Creating an instance of a generic

Body:
This is probably a noob question, so sorry in advance for my inexperience...

So I have a list with thousands of elements which fluctuates frequently, so I created this Coroutine to update it without creating a whole new list and populating it every time it changes...

    public static IEnumerator ListSetup(List<Vector3> list, int resolution)
    {
        while (list.Count != resolution)
        {
            if (list.Count < resolution)
                list.Add(new Vector3());
            if (list.Count > resolution)
                list.RemoveAt(list.Count - 1);
        }
        yield return null;
    }

...and it works a treat.

Then, I wanted to modify it so that it can take any type of list, not just Vector3's, but I have been having some trouble with the syntax..

    public static IEnumerator ListSetup<T>(List<T> list, int resolution)
    {
        while (list.Count != resolution)
        {
            if (list.Count < resolution)
                list.Add(new T());//Error Here
            if (list.Count > resolution)
                list.RemoveAt(list.Count - 1);
        }
        yield return null;
    }

I've tried typeof(T), GetType(T), typeof(T).MakeGenericType(), Add(T), and tons of other variations, but it is clear that I just don't understand how Types and Generics work.

Any help would be appreciated.

Body:
You have not been to far away from the answer. The missing part is to restrict the type T to only allow objects with a public parameter-less constructor.

This is done with the generic type-constraint where and the new-constraint

public static IEnumerator ListSetup<T> (List<T> list, int resolution) where T : new()
{
    while (list.Count != resolution)
    {
        if (list.Count < resolution)
            list.Add(new T());
        if (list.Count > resolution)
            list.RemoveAt(list.Count - 1);
    }
    yield return null;
}


问:
Divi - Slide Navigation On Button Optimisation
I have a slide navigation script that allows me to navigate to a particular slide using an "nth-child(#) that triggers a click event.

Each button currently has its own slide reference, i.e Slide-1 button will link to nth-child(1) and so forth through to slide/button 8

I am looking for ways to optimise the below script using a loop or something similar so that it is more manageable and still keeps the same functionality.

```<code><script>

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

var selector = '.activelinks a';
$(selector).on('click', function(){
    $(selector).removeClass('active');
    $(this).addClass('active');
});

$("#Slide-1").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(1)").trigger("click");
});

$("#Slide-2").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(2)").trigger("click");
});

$("#Slide-3").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(3)").trigger("click");
});

$("#Slide-4").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(4)").trigger("click");
});

$("#Slide-5").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(5)").trigger("click");
});

$("#Slide-6").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(6)").trigger("click");
});

$("#Slide-7").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(7)").trigger("click");
});

$("#Slide-8").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(8)").trigger("click");
});
});
</script>
</code>```

答:
you can give a class to all slide buttons like : slideBtn

then :

```<code>jQuery(document).ready(function ($) {
                var selector = ".activelinks a";
                $(selector).on("click", function () {
                    $(selector).removeClass("active");
                    $(this).addClass("active");
                });

                $(".slideBtn").on("click", function (e) {
                    e.preventDefault();
                    var slideNumber = e.target.id.replace( /^\D+/g, '');
                    $(".et-pb-controllers a:nth-child("+slideNumber+")").trigger("click");
                });
            });
</code>```

Body:
you can give a class to all slide buttons like : slideBtn

then :

jQuery(document).ready(function ($) {
                var selector = ".activelinks a";
                $(selector).on("click", function () {
                    $(selector).removeClass("active");
                    $(this).addClass("active");
                });

                $(".slideBtn").on("click", function (e) {
                    e.preventDefault();
                    var slideNumber = e.target.id.replace( /^\D+/g, '');
                    $(".et-pb-controllers a:nth-child("+slideNumber+")").trigger("click");
                });
            });


问:
Install libc++ on ubuntu
I am wondering what is the right/easy way to install a binary libc++ on Ubuntu, in my case Trusty aka 14.04?

On the LLVM web site there are apt packages http://apt.llvm.org/ and I have used these to install 3.9. However these packages don't seem to include libc++. I install the libc++-dev package but that seems to be a really old version. There are also binaries that can be downloaded http://llvm.org/releases/download.html#3.9.0. These do seem to contain libc++ but I'm not sure if I can just copy bits of this into places like /usr/include/c++/v1, in fact I'm not really sure what bits I would need to copy. I am aware I can use libc++ from an alternate location as documented here http://libcxx.llvm.org/docs/UsingLibcxx.html which I have tried. However I can't modify the build system of the large code base I work on to do this.

So is three any reason the apt packages don't include libc++ and any pointers to installing a binary would be gratefully recieved.

答:
Just build it yourself, as explained here. I added -D CMAKE_CXX_COMPILER=clang++ -D CMAKE_C_COMPILER=clang to use clang as the compiler:

```<code>$ git clone https://github.com/llvm/llvm-project.git
$ cd llvm-project
$ mkdir build
$ cmake -G Ninja -S runtimes -B build -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind" -D CMAKE_CXX_COMPILER=clang++ -D CMAKE_C_COMPILER=clang # Configure for clang++
$ ninja -C build cxx cxxabi unwind # Build
$ ninja -C build check-cxx check-cxxabi check-unwind # Test
$ ninja -C build install-cxx install-cxxabi install-unwind # Install
</code>```

Title: Install libc++ on ubuntu

Body:
Just build it yourself, as explained here. I added -D CMAKE_CXX_COMPILER=clang++ -D CMAKE_C_COMPILER=clang to use clang as the compiler:

$ git clone https://github.com/llvm/llvm-project.git
$ cd llvm-project
$ mkdir build
$ cmake -G Ninja -S runtimes -B build -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind" -D CMAKE_CXX_COMPILER=clang++ -D CMAKE_C_COMPILER=clang # Configure for clang++
$ ninja -C build cxx cxxabi unwind # Build
$ ninja -C build check-cxx check-cxxabi check-unwind # Test
$ ninja -C build install-cxx install-cxxabi install-unwind # Install


问:
Euclidean Distance
Hacker Rank - Weather Observation Station 19

Given a table STATION that holds data for five fields namely ID, CITY,
  STATE, NORTHERN LATITUDE and WESTERN LONGITUDE.

```<code>+-------------+------------+
| Field       |   Type     |
+-------------+------------+
| ID          | INTEGER    |
| CITY        | VARCHAR(21)|
| STATE       | VARCHAR(2) |
| LAT_N       | NUMERIC    |
| LONG_W      | NUMERIC    |
+-------------+------------+
</code>```

Consider P1(a, b) and P2(c, d) be two points on 2D plane, where (a,
  b) be minimum and maximum values of Northern Latitude and (c, d) be
  minimum and maximum values of Western Longitude. Write a query to
  print the Euclidean Distance between points P1 and P2 up to 4 decimal
  digits.

my solution for oracle is :

```<code>select round((abs(max(lat_n)-max(long_w)) + abs(min(long_w)-min(lat_n))),4) from station;
</code>```

but it is giving answer to the 3 decimal points but i need 4 decimal points.

答:
In Euclidean plane

Distance

dist((x, y), (a, b)) = sqrt ((x - a)² + (y - b)²)

This query do this operation

```<code>select round(sqrt (power(max(lat_n)-min(lat_n),2)+power(max(long_w)-min(long_w),2)),4)
from station
</code>```

Title: Euclidean Distance

Body:
Hacker Rank - Weather Observation Station 19

Given a table STATION that holds data for five fields namely ID, CITY,
  STATE, NORTHERN LATITUDE and WESTERN LONGITUDE.

+-------------+------------+
| Field       |   Type     |
+-------------+------------+
| ID          | INTEGER    |
| CITY        | VARCHAR(21)|
| STATE       | VARCHAR(2) |
| LAT_N       | NUMERIC    |
| LONG_W      | NUMERIC    |
+-------------+------------+

Consider P1(a, b) and P2(c, d) be two points on 2D plane, where (a,
  b) be minimum and maximum values of Northern Latitude and (c, d) be
  minimum and maximum values of Western Longitude. Write a query to
  print the Euclidean Distance between points P1 and P2 up to 4 decimal
  digits.

my solution for oracle is :

select round((abs(max(lat_n)-max(long_w)) + abs(min(long_w)-min(lat_n))),4) from station;

but it is giving answer to the 3 decimal points but i need 4 decimal points.

Body:
In Euclidean plane

Distance

dist((x, y), (a, b)) = sqrt ((x - a)² + (y - b)²)

This query do this operation

select round(sqrt (power(max(lat_n)-min(lat_n),2)+power(max(long_w)-min(long_w),2)),4)
from station


问:
How to stop Maybe from being passed into another function in Haskell
I have already looked at this answer, but it is unclear to me how to apply it in my situation.

I have the following function:

```<code>designC :: DesignC -> Maybe CDef -> String
designC FirstString _ = "first_string"
designC SecondString _ = "second_string"
designC UnknownString c = getName c
</code>```

The getName function takes a CDef as it's argument. However the above code will not work and has the following error:

```<code>No instance for (getIdea (Maybe CDef))
arising from a use of ‘getName’
In the expression: getName c
</code>```

I tried:

```<code>designC UnknownString c = getName (Just c)
</code>```

but the error shows that this made things worse

```<code>No instance for (getIdea (Maybe (Maybe CDef)))
</code>```

How can I pass just the CDef to getName?

答:
You have to handle a situation when your Maybe is Nothing.

Either provide some default value

```<code>defaultValue = ""

designC :: DesignC -> Maybe CDef -> String
designC FirstString _ = "first_string"
designC SecondString _ = "second_string"
designC UnknownString (Just c) = getName c
designC UnknownString Nothing = defaultValue

-- or shorter
designC UnknownString c = maybe defaultValue getName c
</code>```

Or raise an exception

```<code>data MyException = VeryNastyError

designC :: MonadError MyException m => DesignC -> Maybe CDef -> m String
designC FirstString _ = pure "first_string"
designC SecondString _ = pure "second_string"
designC UnknownString (Just c) = pure $ getName c
designC UnknownString Nothing = throwError VeryNastyError
</code>```

Body:
I have already looked at this answer, but it is unclear to me how to apply it in my situation.

I have the following function:

designC :: DesignC -> Maybe CDef -> String
designC FirstString _ = "first_string"
designC SecondString _ = "second_string"
designC UnknownString c = getName c

The getName function takes a CDef as it's argument. However the above code will not work and has the following error:

No instance for (getIdea (Maybe CDef))
arising from a use of ‘getName’
In the expression: getName c

I tried:

designC UnknownString c = getName (Just c)

but the error shows that this made things worse

No instance for (getIdea (Maybe (Maybe CDef)))

How can I pass just the CDef to getName?

Body:
You have to handle a situation when your Maybe is Nothing.

Either provide some default value

defaultValue = ""

designC :: DesignC -> Maybe CDef -> String
designC FirstString _ = "first_string"
designC SecondString _ = "second_string"
designC UnknownString (Just c) = getName c
designC UnknownString Nothing = defaultValue

-- or shorter
designC UnknownString c = maybe defaultValue getName c

Or raise an exception

data MyException = VeryNastyError

designC :: MonadError MyException m => DesignC -> Maybe CDef -> m String
designC FirstString _ = pure "first_string"
designC SecondString _ = pure "second_string"
designC UnknownString (Just c) = pure $ getName c
designC UnknownString Nothing = throwError VeryNastyError


问:
Cypress : The submit button is disabled even after all the text fields have filled
I was trying to automate a text submit form using cypress. The 'Create student'  button is disabled even after all the fields have been filled

Please see the cypress error

code :

it('should be able to add a new student and update the details, remove from the class and delete the account', function () {
        cy.visit(
            'https://readingeggs.blake-staging.com/district_ui#/reading/manage-schools/students/195286/new'
        )
        cy.findByLabelText('First Name').type('ark')
        cy.get('#first-name').should('have.value', 'ark')
        cy.findByLabelText('Last Name').type('last')
        cy.get('#last-name').should('have.value', 'last')
        cy.get('[data-test-select-grade]').select('1')
        cy.get('#grade-dropdown').should('have.value', '1')
        cy.get('[data-test-select-teacher]').select('Lehner, Abbey')
        cy.get('#teacher-dropdown').should('have.value', '3068134')

        cy.get('[data-test-submit-new-student]').click()
        cy.get('#main')
            .findByRole('alert')
            .should('include.text', `Successfully created a student`)
    })
})
```

答:
If using .should('not.be.disabled') does not work (I agree, it should be the first thing to try), try adding a trigger event to each input - in case the .type() command is not triggering the validation change.

cy.findByLabelText('First Name').type('ark').trigger('change')
cy.get('#first-name').should('have.value', 'ark')

cy.findByLabelText('Last Name').type('last').trigger('change')
cy.get('#last-name').should('have.value', 'last')

cy.get('[data-test-select-grade]').select('1').trigger('change')
cy.get('#grade-dropdown').should('have.value', '1')

cy.get('[data-test-select-teacher]').select('Lehner, Abbey').trigger('change')
cy.get('#teacher-dropdown').should('have.value', '3068134')

cy.get('[data-test-submit-new-student]').click()
```
<p>If still no joy, use <code>.click({force:true})</code></p>
<p>By the way, <code>cy.get('[data-test-select-grade]').select('1')</code> looks a bit suspicious. The select command can take a display value as a string or a position value as a number. The screenshot shows "K" is selected, so I would expect either of these to work</p>
<pre class="lang-js prettyprint-override"><code>cy.get('[data-test-select-grade]').select(1)   // number passed

// or

cy.get('[data-test-select-grade]').select('K')  // string passed
</code>```

Body:
If using .should('not.be.disabled') does not work (I agree, it should be the first thing to try), try adding a trigger event to each input - in case the .type() command is not triggering the validation change.

cy.findByLabelText('First Name').type('ark').trigger('change')
cy.get('#first-name').should('have.value', 'ark')

cy.findByLabelText('Last Name').type('last').trigger('change')
cy.get('#last-name').should('have.value', 'last')

cy.get('[data-test-select-grade]').select('1').trigger('change')
cy.get('#grade-dropdown').should('have.value', '1')

cy.get('[data-test-select-teacher]').select('Lehner, Abbey').trigger('change')
cy.get('#teacher-dropdown').should('have.value', '3068134')

cy.get('[data-test-submit-new-student]').click()

If still no joy, use .click({force:true})

By the way, cy.get('[data-test-select-grade]').select('1') looks a bit suspicious. The select command can take a display value as a string or a position value as a number. The screenshot shows "K" is selected, so I would expect either of these to work

cy.get('[data-test-select-grade]').select(1)   // number passed

// or

cy.get('[data-test-select-grade]').select('K')  // string passed


问:
Post API getting invalid character '-' in numeric literal
I'm trying to make a POST function to insert data in my database using go.

My Model:

```<code>type Funcstruct {
    Name      string `json:"Name"`
    Status    string `json:"Status"`
}
</code>```

My post function:

```<code>//POST FUNC
func (app *App) createFunc(w http.ResponseWriter, r *http.Request) {

    decoder := json.NewDecoder(r.Body)

    var data Func
    err := decoder.Decode(&data)
    if err != nil {
        panic(err)
    }

    Name := data.Name
    Status := data.Status

    database, err := db.CreateDatabase()
    if err != nil {
        log.Fatal("Not connect to db")
    }
    _, err = database.Exec("INSERT INTO `func` (Name, Status) VALUES ($1, $2)", Name, Status)
    if err != nil {
        log.Fatal("Error inserting data")
    }

    log.Println("Alright!")
    w.WriteHeader(http.StatusOK)
}
</code>```

So i make one go build and after i make a ./nameproject

So, i go in the PostMan and make a post http request passing the Name and Status in form-data but i receive:

2019/07/12 22:20:38 http: panic serving [::1]:54600: invalid character
  '-' in numeric literal

答:
You should change form-data to raw->JSON and send like this:

```<code>{
    "Name" : "morefeizi",
    "Status" : "1"
}
</code>```

Body:
I'm trying to make a POST function to insert data in my database using go.

My Model:

type Funcstruct {
    Name      string `json:"Name"`
    Status    string `json:"Status"`
}

My post function:

//POST FUNC
func (app *App) createFunc(w http.ResponseWriter, r *http.Request) {

    decoder := json.NewDecoder(r.Body)

    var data Func
    err := decoder.Decode(&data)
    if err != nil {
        panic(err)
    }

    Name := data.Name
    Status := data.Status

    database, err := db.CreateDatabase()
    if err != nil {
        log.Fatal("Not connect to db")
    }
    _, err = database.Exec("INSERT INTO `func` (Name, Status) VALUES ($1, $2)", Name, Status)
    if err != nil {
        log.Fatal("Error inserting data")
    }

    log.Println("Alright!")
    w.WriteHeader(http.StatusOK)
}

So i make one go build and after i make a ./nameproject

So, i go in the PostMan and make a post http request passing the Name and Status in form-data but i receive:

2019/07/12 22:20:38 http: panic serving [::1]:54600: invalid character
  '-' in numeric literal

Body:
You should change form-data to raw->JSON and send like this:

{
    "Name" : "morefeizi",
    "Status" : "1"
}


问:
Linq Query Need - Looking for a pattern of data
Say I have a collection of the following simple class:

```<code>public class MyEntity
{
   public string SubId { get; set; }
   public System.DateTime ApplicationTime { get; set; }
   public double? ThicknessMicrons { get; set; }
}
</code>```

I need to search through the entire collection looking for 5 consecutive (not 5 total, but 5 consecutive) entities that have a null ThicknessMicrons value. Consecutiveness will be based on the ApplicationTime property. The collection will be sorted on that property.

How can I do this in a Linq query?

答:
You can write your own extension method pretty easily:

```<code>public static IEnumerable<IEnumerable<T>> FindSequences<T>(this IEnumerable<T> sequence, Predicate<T> selector, int size)
{
    List<T> curSequence = new List<T>();
    foreach (T item in sequence)
    {
        // Check if this item matches the condition
        if (selector(item))
        {
            // It does, so store it
            curSequence.Add(item);

            // Check if the list size has met the desired size
            if (curSequence.Count == size)
            {
                // It did, so yield that list, and reset
                yield return curSequence;
                curSequence = new List<T>();
            }
        }
        else
        {
            // No match, so reset the list
            curSequence = new List<T>();
        }
    }
}
</code>```

Now you can just say:

```<code>var groupsOfFive = entities.OrderBy(x => x.ApplicationTime)
                            .FindSequences(x => x.ThicknessMicrons == null, 5);
</code>```

Note that this will return all sub-sequences of length 5. You can test for the existence of one like so:

```<code>bool isFiveSubsequence = groupsOfFive.Any();
</code>```

Another important note is that if you have 9 consecutive matches, only one sub-sequence will be located.

Body:
Say I have a collection of the following simple class:

public class MyEntity
{
   public string SubId { get; set; }
   public System.DateTime ApplicationTime { get; set; }
   public double? ThicknessMicrons { get; set; }
}

I need to search through the entire collection looking for 5 consecutive (not 5 total, but 5 consecutive) entities that have a null ThicknessMicrons value. Consecutiveness will be based on the ApplicationTime property. The collection will be sorted on that property.

How can I do this in a Linq query?

Body:
You can write your own extension method pretty easily:

public static IEnumerable<IEnumerable<T>> FindSequences<T>(this IEnumerable<T> sequence, Predicate<T> selector, int size)
{
    List<T> curSequence = new List<T>();
    foreach (T item in sequence)
    {
        // Check if this item matches the condition
        if (selector(item))
        {
            // It does, so store it
            curSequence.Add(item);

            // Check if the list size has met the desired size
            if (curSequence.Count == size)
            {
                // It did, so yield that list, and reset
                yield return curSequence;
                curSequence = new List<T>();
            }
        }
        else
        {
            // No match, so reset the list
            curSequence = new List<T>();
        }
    }
}

Now you can just say:

var groupsOfFive = entities.OrderBy(x => x.ApplicationTime)
                            .FindSequences(x => x.ThicknessMicrons == null, 5);

Note that this will return all sub-sequences of length 5. You can test for the existence of one like so:

bool isFiveSubsequence = groupsOfFive.Any();

Another important note is that if you have 9 consecutive matches, only one sub-sequence will be located.


问:
Count number of objects in JSON array on a URL in swift5
I have a JSON array at url = https://api.github.com/users/greenrobot/starred .

I want to count how many objects are there in that array using swift. I don't want data present, I just want count of it.

答:
The GitHub starred API returns a maximum of 30 items by default, in the case of greenrobot with a total number of 372 it's not meaningful.

A smart way to get the actual number of starred items is to specify one item per page and to parse the Link header of the HTTP response which contains the number of the last page

```<code>Task {
    do {
        let url = URL(string: "https://api.github.com/users/greenrobot/starred?per_page=1")!
        let (_, response) = try await URLSession.shared.data(from: url)
        guard let link = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Link") else {
            throw URLError(.badServerResponse)
        }
        let regex = try NSRegularExpression(pattern: "page=(\\d+)")
        if let lastMatch = regex.matches(in: link).last {
            let range = Range(lastMatch.range(at: 1), in: link)!
            let numberOfStarredItems = String(link[range])
            print(numberOfStarredItems)
        } else {
            print("No match found")
        }
    } catch {
        print(error)
    }
}
</code>```

Body:
The GitHub starred API returns a maximum of 30 items by default, in the case of greenrobot with a total number of 372 it's not meaningful.

A smart way to get the actual number of starred items is to specify one item per page and to parse the Link header of the HTTP response which contains the number of the last page

Task {
    do {
        let url = URL(string: "https://api.github.com/users/greenrobot/starred?per_page=1")!
        let (_, response) = try await URLSession.shared.data(from: url)
        guard let link = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Link") else {
            throw URLError(.badServerResponse)
        }
        let regex = try NSRegularExpression(pattern: "page=(\\d+)")
        if let lastMatch = regex.matches(in: link).last {
            let range = Range(lastMatch.range(at: 1), in: link)!
            let numberOfStarredItems = String(link[range])
            print(numberOfStarredItems)
        } else {
            print("No match found")
        }
    } catch {
        print(error)
    }
}


问:
Python GoogleSearch module error : "TypeError: search() got an unexpected keyword argument 'tld' "
Here is my code, it was working properly before I was not getting an error while using it. I don't understand how it happened even though I didn't change with it. :

```<code>    results = []
for query in my_list:
    results.append(search(query, tld="com", num=1, stop=1, pause=2))
</code>```

Error:

```<code>results.append(search(query, tld="com", num=1, stop=1, pause=2))
TypeError: search() got an unexpected keyword argument 'tld'
</code>```

答:
It is necessary to install the google library, installing this library stopped producing the error:

```<code>pip install google
</code>```

Body:
Here is my code, it was working properly before I was not getting an error while using it. I don't understand how it happened even though I didn't change with it. :

    results = []
for query in my_list:
    results.append(search(query, tld="com", num=1, stop=1, pause=2))

Error:

results.append(search(query, tld="com", num=1, stop=1, pause=2))
TypeError: search() got an unexpected keyword argument 'tld'

Body:
It is necessary to install the google library, installing this library stopped producing the error:

pip install google