问:
Using variables in a function from another function
In function foo() there is a loop that iterates until it finds an optimum set of variables and determines that as the ideal set. The function only returns one variable, in order to pass a unit test.

In the next function bar(), I need to output all of the variables in function foo() as it iterates. First output the optimum set of variables, and then the rest of the possible variable sets seperately.

```<code>int foo(int a, int b) {
    int c, d;
    while ( etc. ) {
        c = arithmetic_for_c;
        d = arithmetic_for_d;
        e = c + d;
    }
    return e;
}

int bar(a, b) {
    cout << e;
    cout << c << d;
}
</code>```

This example is very simple, but you get the idea.

I have a feeling references (int&, string& etc) would help somehow, but I'm not sure how they would be used here.

I tried to put together a global array but that seemed to get a bit too complex for the scope of this assignment.

The loop is a necessity, but also seems to ruin any hope for variables or arrays in the global scope.

Unfortunately there are a number of things we haven't learned yet, so there is likely a solution I can't use yet.

Thoughts?

Thank you!

答:
The CPU is performing one thread at a specific time. So it can only perform the code in function foo or the function bar, but never both. The scope of the variables in the function are called local or auto variables. They are valid only in the context of the execution of the function. At language level you will say they go out of scope at the closing } bracket. Technically, the memory for the variable is allocated temporarily while entering the function and automatically released on exit. It's just a memory location on the stack. The live time of the variable ends at the end of scope.

So, you must always look at the scope of a variable. You can't access anything temporarily allocated on a different function's stack. The game changes if one function calls another. You can pass a reference from the calling function to the called function, but not the other way.

```<code>int foo(int a, int b, int& c, int& d) {
    while ( etc. ) {
        c = arithmetic_for_c;
        d = arithmetic_for_d;
        e = c + d;
    }
    return e;
} // scope of the reference c and  ends here,
  // but not the scope of the referenced variables.

int bar(a, b) {
    int c, d;

    // here you define the role of calling function and called function.
    int e = foo(a, b, c, d);

    cout << e;
    cout << c << d;
} // scope of c and d ends here.
</code>```

Body:
In function foo() there is a loop that iterates until it finds an optimum set of variables and determines that as the ideal set. The function only returns one variable, in order to pass a unit test.

In the next function bar(), I need to output all of the variables in function foo() as it iterates. First output the optimum set of variables, and then the rest of the possible variable sets seperately.

int foo(int a, int b) {
    int c, d;
    while ( etc. ) {
        c = arithmetic_for_c;
        d = arithmetic_for_d;
        e = c + d;
    }
    return e;
}

int bar(a, b) {
    cout << e;
    cout << c << d;
}

This example is very simple, but you get the idea.

I have a feeling references (int&, string& etc) would help somehow, but I'm not sure how they would be used here.

I tried to put together a global array but that seemed to get a bit too complex for the scope of this assignment.

The loop is a necessity, but also seems to ruin any hope for variables or arrays in the global scope.

Unfortunately there are a number of things we haven't learned yet, so there is likely a solution I can't use yet.

Thoughts?

Thank you!

Body:
The CPU is performing one thread at a specific time. So it can only perform the code in function foo or the function bar, but never both. The scope of the variables in the function are called local or auto variables. They are valid only in the context of the execution of the function. At language level you will say they go out of scope at the closing } bracket. Technically, the memory for the variable is allocated temporarily while entering the function and automatically released on exit. It's just a memory location on the stack. The live time of the variable ends at the end of scope.

So, you must always look at the scope of a variable. You can't access anything temporarily allocated on a different function's stack. The game changes if one function calls another. You can pass a reference from the calling function to the called function, but not the other way.

int foo(int a, int b, int& c, int& d) {
    while ( etc. ) {
        c = arithmetic_for_c;
        d = arithmetic_for_d;
        e = c + d;
    }
    return e;
} // scope of the reference c and  ends here,
  // but not the scope of the referenced variables.

int bar(a, b) {
    int c, d;

    // here you define the role of calling function and called function.
    int e = foo(a, b, c, d);

    cout << e;
    cout << c << d;
} // scope of c and d ends here.


来源: stackexchange

问:
CapacitorJS not serving root index.html for angular application
I'm using CapacitorJS to turn my Angular web application into a mobile app.
However, I have an issue.

These are the devices I've tested this on:

Pixel 4a emulator (Android 11),
iPhone XR (iOS 15),
Xiaomi Redmi Note 8 (Android 11)

Version(s):

@angular/core, router 13.0.2

@capacitor/core, android, ios 2.4.0

Repro:

I open my app

Javascript files are taken from /

I click a button to navigate to /example

Javascript files are still taken from /

I set the phone to sleep mode and wait (until js file need to be loaded again on app launch)

I unlock the phone again

Javascript files are taken from /example

Expected behavior:

Application javascript is taken from /

Actual behavior:

Application javascript is taken from /example (where it does not exist because /example is an Angular route)

Has anyone else experienced this issue, or have a solution for this?

答:
Soved

The issue was I was that I had ./ as baseUrl instead of / for angular :(

ContentLicense: CC BY-SA 4.0


问:
MultipartFile recieved null when using vs-upload to upload file in spring boot
I am using vs-upload to upload a file, this is the client code:

```<code><div class="vx-row">
            <vs-upload data multiple="fasle" :headers="{'token' : token}" action="/service/zhuolian/report/org/user/import/list" @on-success="successUpload" />
        </div>
</code>```

and this is the spring boot(2.x) server side code:

```<code>@PostMapping("/list")
Response<SparkUserImportResponse> orgUserImport(@RequestBody MultipartFile file,
                                                    @RequestParam(required = false,value = "override",defaultValue = "false") Boolean override);
</code>```

when I upload xlsx files in the browser, the server side received null MultipartFile. why the server side receive null? what should I do to fix this problem?

答:
add fileName file for the upload component, the code looks like this:

```<code><div class="vx-row">
            <vs-upload data fileName="file" multiple="fasle" :headers="{'token' : token}" action="/service/zhuolian/report/org/user/import/list" @on-success="successUpload" />
        </div>
</code>```

Body:
I am using vs-upload to upload a file, this is the client code:

            <vs-upload data multiple="fasle" :headers="{'token' : token}" action="/service/zhuolian/report/org/user/import/list" @on-success="successUpload" />

and this is the spring boot(2.x) server side code:

@PostMapping("/list")
Response<SparkUserImportResponse> orgUserImport(@RequestBody MultipartFile file,
                                                    @RequestParam(required = false,value = "override",defaultValue = "false") Boolean override);

when I upload xlsx files in the browser, the server side received null MultipartFile. why the server side receive null? what should I do to fix this problem?

Body:
add fileName file for the upload component, the code looks like this:

<div class="vx-row">
            <vs-upload data fileName="file" multiple="fasle" :headers="{'token' : token}" action="/service/zhuolian/report/org/user/import/list" @on-success="successUpload" />
        </div>


问:
On 32-bit ARM Linux, how 2 GB RAM is addressed
Virtual address ranges 0xc0000000 (PAGE_OFFSET) .. 0xffffffff is mapped to physical memory.

If RAM is 1024 MB, then 0xc0000000 .. 0xffffffff is mapped to physical memory 0x00000000 to 0x40000000

How it is handled when we have 2GB of RAM on ARM based boards?

答:
Only pages in the low memory region (below highmem_start_page()) are directly-mapped in the kernel after PAGE_OFFSET. The rest can be dynamically mapped on demand using kmap() and kunmap() if a kernel mapping is needed, and should be unmapped when not needed to avoid running out of virtual address range.

Note that many use cases don't need a kernel memory mapping, as you can directly access the user address space of the running process.


问:
$(this).find("a").attr("onclick"); onclick giving invalid character
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

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

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});
</code>```

And the HTML:

```<code><div>
    <div id="tab1" class="tab_content">01</div>
    <div id="tab2" class="tab_content">02</div>
    <div id="tab3" class="tab_content">03</div>
</div>
<ol class="tabs">
    <li><a onclick="#tab1">Unique benefits</a></li>
    <li><a onclick="#tab2">Insurance</a></li>
    <li><a onclick="#tab3">Business Loan</a></li>
</ol>
</code>```

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out

答:
Your onclick inline attribute is equivalent to this:

```<code>function() {
    #tab1
}
</code>```

which is not valid javascript.  While href is a string value that tells the link where it should go when clicked (default behavior), onclick is a javascript function that is a handler for the click event to provide alternate behavior.

ContentLicense: CC BY-SA 3.0

Body:
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

$(document).ready(function(){

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});

And the HTML:

01

02

03

Unique benefits

Insurance

Business Loan

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out

Body:
Your onclick inline attribute is equivalent to this:

function() {
    #tab1
}

which is not valid javascript.  While href is a string value that tells the link where it should go when clicked (default behavior), onclick is a javascript function that is a handler for the click event to provide alternate behavior.


问:
Spring jdbcTemplate retrieve numeric values from query
I have this query for my jdbcTemplate and I wanna get just the long value from the database, what should be fixed here?</p>
```<code>String query = "SELECT size from users where name = ? AND type = ?";
long size = jdbcTemplate.query(query, new Object[]{id, type}, (rs, rowNum) ->
rs.getLong("size"));
</code>```

答:
If you look at the query javadocs in JdbcOperations it states:

Deprecated. as of 5.3, in favor of query(String, RowMapper, Object...)

So you can use it like this:

List<Long> sizeResults = jdbcTemplate.query(query, (rs, rowNum) ->
        rs.getLong("size"), id, type);
if (sizeResults.isEmpty()){
    System.out.println("Result not found!");
} else {
    System.out.println("Result found!");
}
```

Note: queryForObject throws EmptyResultDataAccessException for empty results. Often it is not desired behavior.

Body:
I have this query for my jdbcTemplate and I wanna get just the long value from the database, what should be fixed here?

String query = "SELECT size from users where name = ? AND type = ?";
long size = jdbcTemplate.query(query, new Object[]{id, type}, (rs, rowNum) ->
rs.getLong("size"));

Body:
If you look at the query javadocs in JdbcOperations it states:

Deprecated. as of 5.3, in favor of query(String, RowMapper, Object...)

So you can use it like this:

List<Long> sizeResults = jdbcTemplate.query(query, (rs, rowNum) ->
        rs.getLong("size"), id, type);
if (sizeResults.isEmpty()){
    System.out.println("Result not found!");
} else {
    System.out.println("Result found!");
}

Note: queryForObject throws EmptyResultDataAccessException for empty results. Often it is not desired behavior.


问:
Android - Getting audio to play through earpiece
I currently have code that reads a recording in from the devices mic using the AudioRecord class and then playing it back out using the AudioTrack class.

My problem is that when I play it out it plays via the speaker phone.

I want it to play out via the ear piece on the device.

Here is my code:

```<code>public class LoopProg extends Activity {

 boolean isRecording; //currently not used
 AudioManager am;
 int count = 0;

 /** Called when the activity is first created. */
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.setMicrophoneMute(true);
        while(count <= 1000000){
        Record record = new Record();
        record.run();
        count ++;
        Log.d("COUNT", "Count is : " + count);
        }
    }

   public class Record extends Thread{
      static final int bufferSize = 200000;
      final short[] buffer = new short[bufferSize];
      short[] readBuffer = new short[bufferSize];

      public void run() {
      isRecording = true;
      android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);

      int buffersize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
      AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize);
      AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM);
      am.setRouting(AudioManager.MODE_NORMAL,1, AudioManager.STREAM_MUSIC);
      int ok = am.getRouting(AudioManager.ROUTE_EARPIECE);
      Log.d("ROUTING", "getRouting = " + ok);
      setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
      //am.setSpeakerphoneOn(true);
      Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn());
      am.setSpeakerphoneOn(false);
      Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn());
      atrack.setPlaybackRate(11025);

      byte[] buffer = new byte[buffersize];
      arec.startRecording();
      atrack.play();

      while(isRecording) {
                         arec.read(buffer, 0, buffersize);
                         atrack.write(buffer, 0, buffer.length);
                         }
      arec.stop();
      atrack.stop();
      isRecording = false;
      }
   }
}
</code>```

As you can see if the code I have tried using the AudioManager class and its methods including the deprecated setRouting method and nothing works, the setSpeakerphoneOn method seems to have no effect at all, neither does the routing method.

Has anyone got any ideas on how to get it to play via the earpiece instead of the spaker phone?

答:
now in 2022 in Android S (12, API31) setSpeakerphoneOn(false) isn't working reliablie, it is in fact deprecated! instead we can use new API and setCommunicationDevice(AudioDeviceInfo) method. (works with AudioManager.STREAM_VOICE_CALL)

some sample

```<code>Boolean result = null;

ArrayList<Integer> targetTypes = new ArrayList<>();
if (earpieceMode) {
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);
} else { // play out loud
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
}

AudioDeviceInfo currentDevice = audioManager.getCommunicationDevice();
if (currentDevice!=null) {
    for (Integer targetType : targetTypes) {
        if (targetType == currentDevice.getType()) {
            Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType ALREADY SET UP!!");
            result = true;
            break;
        }
    }
}

if (result == null) {
    List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
    outer:
    for (Integer targetType : targetTypes) {
        for (AudioDeviceInfo device : devices) {
            if (device.getType() == targetType) {
                result = audioManager.setCommunicationDevice(device);
                Log.i("AUDIO_MANAGER", "setCommunicationDevice type:" + targetType + " result:" + result);
                if (result) break outer;
            }
        }
    }
}

if (result == null) {
    Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType NOT FOUND!!");
}
else if (!result) {
    Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType FAILED TO SET!!");
}
</code>```

Body:
I currently have code that reads a recording in from the devices mic using the AudioRecord class and then playing it back out using the AudioTrack class.

My problem is that when I play it out it plays via the speaker phone.

I want it to play out via the ear piece on the device.

Here is my code:

public class LoopProg extends Activity {

 boolean isRecording; //currently not used
 AudioManager am;
 int count = 0;

 /** Called when the activity is first created. */
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.setMicrophoneMute(true);
        while(count <= 1000000){
        Record record = new Record();
        record.run();
        count ++;
        Log.d("COUNT", "Count is : " + count);
        }
    }

   public class Record extends Thread{
      static final int bufferSize = 200000;
      final short[] buffer = new short[bufferSize];
      short[] readBuffer = new short[bufferSize];

      public void run() {
      isRecording = true;
      android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);

      int buffersize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
      AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize);
      AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM);
      am.setRouting(AudioManager.MODE_NORMAL,1, AudioManager.STREAM_MUSIC);
      int ok = am.getRouting(AudioManager.ROUTE_EARPIECE);
      Log.d("ROUTING", "getRouting = " + ok);
      setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
      //am.setSpeakerphoneOn(true);
      Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn());
      am.setSpeakerphoneOn(false);
      Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn());
      atrack.setPlaybackRate(11025);

      byte[] buffer = new byte[buffersize];
      arec.startRecording();
      atrack.play();

      while(isRecording) {
                         arec.read(buffer, 0, buffersize);
                         atrack.write(buffer, 0, buffer.length);
                         }
      arec.stop();
      atrack.stop();
      isRecording = false;
      }
   }
}

As you can see if the code I have tried using the AudioManager class and its methods including the deprecated setRouting method and nothing works, the setSpeakerphoneOn method seems to have no effect at all, neither does the routing method.

Has anyone got any ideas on how to get it to play via the earpiece instead of the spaker phone?

Body:
now in 2022 in Android S (12, API31) setSpeakerphoneOn(false) isn't working reliablie, it is in fact deprecated! instead we can use new API and setCommunicationDevice(AudioDeviceInfo) method. (works with AudioManager.STREAM_VOICE_CALL)

some sample

Boolean result = null;

ArrayList<Integer> targetTypes = new ArrayList<>();
if (earpieceMode) {
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);
} else { // play out loud
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
}

AudioDeviceInfo currentDevice = audioManager.getCommunicationDevice();
if (currentDevice!=null) {
    for (Integer targetType : targetTypes) {
        if (targetType == currentDevice.getType()) {
            Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType ALREADY SET UP!!");
            result = true;
            break;
        }
    }
}

if (result == null) {
    List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
    outer:
    for (Integer targetType : targetTypes) {
        for (AudioDeviceInfo device : devices) {
            if (device.getType() == targetType) {
                result = audioManager.setCommunicationDevice(device);
                Log.i("AUDIO_MANAGER", "setCommunicationDevice type:" + targetType + " result:" + result);
                if (result) break outer;
            }
        }
    }
}

if (result == null) {
    Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType NOT FOUND!!");
}
else if (!result) {
    Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType FAILED TO SET!!");
}


问:
Python Requests InvalidURL: Failed to parse URL

thanks you very much. it has a "\u200b" follow the .com.
"\u200b" is an invisable character. the reason is i copy the url
from the website.

but something interesting i found: if i use pip install requests==2.21.0(old version), it will not except this err. only use
new version it will err.

InvalidURL: Failed to parse URL, some url will except this error while some other url wouldn't.

already upgrade urllib3 and requests

err

```<code>urllib3.exceptions.LocationParseError: Failed to parse: https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey

requests.exceptions.InvalidURL: Failed to parse: https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey
</code>```

env

```<code>Python 3.8.6 (tags/v3.8.6:db45529) [MSC v.1927 64 bit (AMD64)] on win32

PS C:\Windows\system32> python -m pip install --upgrade urllib3
Requirement already satisfied: urllib3 in c:\python38\lib\site-packages (1.26.8)

PS C:\Windows\system32> python -m pip install --upgrade requests
Requirement already satisfied: requests in c:\python38\lib\site-packages (2.27.1)
Requirement already satisfied: charset-normalizer~=2.0.0 in c:\python38\lib\site-packages (from requests) (2.0.5)
Requirement already satisfied: idna<4,>=2.5 in c:\python38\lib\site-packages (from requests) (3.2)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\python38\lib\site-packages (from requests) (1.26.8)
Requirement already satisfied: certifi>=2017.4.17 in c:\python38\lib\site-packages (from requests) (2021.5.30)
</code>```

code

```<code>import requests
url='https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey'
#res=requests.post(url)
res=requests.post(str(url))
</code>```

error log

```<code>Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\requests\models.py", line 384, in prepare_url
    scheme, auth, host, port, path, query, fragment = parse_url(url)
  File "C:\Python38\lib\site-packages\urllib3\util\url.py", line 394, in parse_url
    return six.raise_from(LocationParseError(source_url), None)
  File "<string>", line 3, in raise_from
urllib3.exceptions.LocationParseError: Failed to parse: https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:/test.py", line 3, in <module>
    res=requests.post(str(url))
  File "C:\Python38\lib\site-packages\requests\api.py", line 117, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Python38\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python38\lib\site-packages\requests\sessions.py", line 515, in request
    prep = self.prepare_request(req)
  File "C:\Python38\lib\site-packages\requests\sessions.py", line 443, in prepare_request
    p.prepare(
  File "C:\Python38\lib\site-packages\requests\models.py", line 318, in prepare
    self.prepare_url(url, params)
  File "C:\Python38\lib\site-packages\requests\models.py", line 386, in prepare_url
    raise InvalidURL(*e.args)
requests.exceptions.InvalidURL: Failed to parse: https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey
</code>```

答:
There's a typo, or invalid invisible character in your url.
please copy from my code:

url='https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey'
```

Body:
thanks you very much. it has a "\u200b" follow the .com.
"\u200b" is an invisable character. the reason is i copy the url
from the website.

but something interesting i found: if i use pip install requests==2.21.0(old version), it will not except this err. only use
new version it will err.

InvalidURL: Failed to parse URL, some url will except this error while some other url wouldn't.

already upgrade urllib3 and requests

err

urllib3.exceptions.LocationParseError: Failed to parse: https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey

requests.exceptions.InvalidURL: Failed to parse: https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey

env

Python 3.8.6 (tags/v3.8.6:db45529) [MSC v.1927 64 bit (AMD64)] on win32

PS C:\Windows\system32> python -m pip install --upgrade urllib3
Requirement already satisfied: urllib3 in c:\python38\lib\site-packages (1.26.8)

PS C:\Windows\system32> python -m pip install --upgrade requests
Requirement already satisfied: requests in c:\python38\lib\site-packages (2.27.1)
Requirement already satisfied: charset-normalizer~=2.0.0 in c:\python38\lib\site-packages (from requests) (2.0.5)
Requirement already satisfied: idna<4,>=2.5 in c:\python38\lib\site-packages (from requests) (3.2)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\python38\lib\site-packages (from requests) (1.26.8)
Requirement already satisfied: certifi>=2017.4.17 in c:\python38\lib\site-packages (from requests) (2021.5.30)

code

import requests
url='https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey'
#res=requests.post(url)
res=requests.post(str(url))

error log

Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\requests\models.py", line 384, in prepare_url
    scheme, auth, host, port, path, query, fragment = parse_url(url)
  File "C:\Python38\lib\site-packages\urllib3\util\url.py", line 394, in parse_url
    return six.raise_from(LocationParseError(source_url), None)
  File "<string>", line 3, in raise_from
urllib3.exceptions.LocationParseError: Failed to parse: https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:/test.py", line 3, in <module>
    res=requests.post(str(url))
  File "C:\Python38\lib\site-packages\requests\api.py", line 117, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Python38\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python38\lib\site-packages\requests\sessions.py", line 515, in request
    prep = self.prepare_request(req)
  File "C:\Python38\lib\site-packages\requests\sessions.py", line 443, in prepare_request
    p.prepare(
  File "C:\Python38\lib\site-packages\requests\models.py", line 318, in prepare
    self.prepare_url(url, params)
  File "C:\Python38\lib\site-packages\requests\models.py", line 386, in prepare_url
    raise InvalidURL(*e.args)
requests.exceptions.InvalidURL: Failed to parse: https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=samplekey


问:
why is it giving output vertically
```<code>public class TrianglePatterns {
    public static void main(String[] args) {
        int i, j, row = 5;
        for (i = 0; i < row; i++) {
            for (j = 0; j <= i; j++) {
                System.out.println("* ");
            }
            System.out.println();
        }
    }
}
</code>```

output:

```<code>*

*
*

*
*
*

*
*
*
*

*
*
*
*
*
</code>```

答:
Because you're using println (read "PRINT LinNe"), that puts a newline after every output:

Prints a String and then terminates the line. This method behaves as though it invokes print(String) and then println().

As commented by Federico.

And because you're printing in each iteration of your for-loop.

How To Print horizontally (in one line)

Use print (the method without ln) instead

        int i, j, row = 5;
        for (i = 0; i < row; i++) {
            for (j = 0; j <= i; j++) {
                System.out.print("* ");  // print within a single line
            }
            System.out.println();  // terminating the line with a line-break
        }
```
<p>It prints the expected <strong>5 rows</strong> plus a final line-break without content in the new line (because loop ends):</p>
```*
* *
* * *
* * * *
* * * * *

```
<p>Try it on <code>jshell</code>:</p>
```|  Welcome to JShell -- Version 17.0.2
|  For an introduction type: /help intro

jshell>         int i, j, row = 5;
   ...>         for (i = 0; i < row; i++) {
   ...>             for (j = 0; j <= i; j++) {
   ...>                 System.out.print("* ");  // print within a single line
   ...>             }
   ...>             System.out.println();  // terminating the line with a line-break
   ...>         }
   ...>
i ==> 0
j ==> 0
row ==> 5
*
* *
* * *
* * * *
* * * * *

jshell>
```

Title: why is it giving output vertically

Body:
public class TrianglePatterns {
    public static void main(String[] args) {
        int i, j, row = 5;
        for (i = 0; i < row; i++) {
            for (j = 0; j <= i; j++) {
                System.out.println("* ");
            }
            System.out.println();
        }
    }
}

output:

*

*
*

*
*
*

*
*
*
*

*
*
*
*
*

Body:
Because you're using println (read "PRINT LinNe"), that puts a newline after every output:

Prints a String and then terminates the line. This method behaves as though it invokes print(String) and then println().

As commented by Federico.

And because you're printing in each iteration of your for-loop.

How To Print horizontally (in one line)

Use print (the method without ln) instead

        int i, j, row = 5;
        for (i = 0; i < row; i++) {
            for (j = 0; j <= i; j++) {
                System.out.print("* ");  // print within a single line
            }
            System.out.println();  // terminating the line with a line-break
        }

It prints the expected 5 rows plus a final line-break without content in the new line (because loop ends):

*
* *
* * *
* * * *
* * * * *

Try it on jshell:

|  Welcome to JShell -- Version 17.0.2
|  For an introduction type: /help intro

jshell>         int i, j, row = 5;
   ...>         for (i = 0; i < row; i++) {
   ...>             for (j = 0; j <= i; j++) {
   ...>                 System.out.print("* ");  // print within a single line
   ...>             }
   ...>             System.out.println();  // terminating the line with a line-break
   ...>         }
   ...>
i ==> 0
j ==> 0
row ==> 5
*
* *
* * *
* * * *
* * * * *

jshell>


问:
Find out the previous year date from current date in javascript
I need to find out the previous year date from current date and then set as minDate in jQuery UIdatepicker in javascript

My date formaqt is dd-mm-yy

Ie

current date is 25-07-2012

I need to get 25-07-2011

答:
I found this very useful:</p>
```<code>new Date(new Date().setFullYear(new Date().getFullYear() - 1)).toISOString().slice(0, 10);
</code>```

Body:
I found this very useful:

new Date(new Date().setFullYear(new Date().getFullYear() - 1)).toISOString().slice(0, 10);


问:
"You must add a reference to assembly" compiler error in weird case
I have two applications App1 and App2. App1 added a reference to App2 and App2 added a reference to System.Drawing.

In App2 there's a function with two overloads, the first one is protected and has a parameter from System.Drawing.Bitmap and the second one is public has an integer parameter.

```<code>namespace App1Namespace
{
    class Program
    {
        static void Main(string[] args)
        {
            App2Namespace.StaticClass.Func(4);
</code>```

```<code>namespace App2Namespace
{
    public class StaticClass
    {
        protected static void Func(System.Drawing.Bitmap bitmapParam) { }
        public static void Func(int intParam) { }
</code>```

When the App1 is built, the following compile time error will be thrown:

Error 1   The type 'System.Drawing.Bitmap' is defined in an assembly
  that is not referenced. You must add a reference to assembly
  'System.Drawing, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a'.

Although Func which has Bimap param is protected, the App1 needs having a reference to System.Drawing.

The questions are that why does App1 need System.Drawing? and why this error appears only when the second overload is called and doesn't appear when another overload (for example with two parameters) is called?

Note: When the first overload becomes private the error will disappear.

答: It may simply be that it needs a reference, because since your App2Namespace.StaticClass.Func could be inherited from (since it's protected) in a class in the App1 namespace.  If that were to happen, it would also need a reference to System.Drawing.</p>

Body:
I have two applications App1 and App2. App1 added a reference to App2 and App2 added a reference to System.Drawing.

In App2 there's a function with two overloads, the first one is protected and has a parameter from System.Drawing.Bitmap and the second one is public has an integer parameter.

namespace App1Namespace
{
    class Program
    {
        static void Main(string[] args)
        {
            App2Namespace.StaticClass.Func(4);

namespace App2Namespace
{
    public class StaticClass
    {
        protected static void Func(System.Drawing.Bitmap bitmapParam) { }
        public static void Func(int intParam) { }

When the App1 is built, the following compile time error will be thrown:

Error 1   The type 'System.Drawing.Bitmap' is defined in an assembly
  that is not referenced. You must add a reference to assembly
  'System.Drawing, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a'.

Although Func which has Bimap param is protected, the App1 needs having a reference to System.Drawing.

The questions are that why does App1 need System.Drawing? and why this error appears only when the second overload is called and doesn't appear when another overload (for example with two parameters) is called?

Note: When the first overload becomes private the error will disappear.


问:
flutter run gives Gradle task assembleDebug failed with exit code 1
I have tried almost everything I could find but I  am not able to resolve this error. This is the first time I'm installing flutter on the computer. The first project I try is giving me this error.

I got flutter from their GitHub repo, master branch and I installed all the SDK tools from the AUR. Installed SDK tools

android-emulator

androind-platform

android-sdk-build-tools

androind-sdk-cmdline-tools-latest

android-sdk-platform-tools

I basically followed this tutorial. I have installed the flutter and dart extensions in VS Code.

I'm doing all this on a vanilla arch system.

I have not done any changes to any part of the code and according to the information that people have asked for, these are the outputs of the commands

flutter run --debug

```<code>Using hardware rendering with device Android SDK built for x86. If you notice graphics artifacts, consider enabling software rendering with
"--enable-software-rendering".
Launching lib/main.dart on Android SDK built for x86 in debug mode...

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings generic class cache for settings file '/home/somannak/Scripts/flutter/anothertry/android/settings.gradle' (/home/somannak/.gradle/caches/6.7/scripts/f0emg6u6oecmxqzgk5g9nn4ui).
> BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 521ms
Running Gradle task 'assembleDebug'...                             978ms
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

flutter run --verbose

```<code>[  +47 ms] executing: uname -m
[  +25 ms] Exit code 0 from: uname -m
[        ] x86_64
[   +6 ms] executing: [/home/somannak/applications/flutter/] git -c log.showSignature=false log -n 1 --pretty=format:%H
[   +4 ms] Exit code 0 from: git -c log.showSignature=false log -n 1 --pretty=format:%H
[        ] fb3f123771d35171b08d1a8b41fccac5816f2f69
[        ] executing: [/home/somannak/applications/flutter/] git tag --points-at fb3f123771d35171b08d1a8b41fccac5816f2f69
[  +11 ms] Exit code 0 from: git tag --points-at fb3f123771d35171b08d1a8b41fccac5816f2f69
[   +1 ms] executing: [/home/somannak/applications/flutter/] git describe --match *.*.* --long --tags fb3f123771d35171b08d1a8b41fccac5816f2f69
[  +32 ms] Exit code 0 from: git describe --match *.*.* --long --tags fb3f123771d35171b08d1a8b41fccac5816f2f69
[        ] 2.6.0-11.0.pre-770-gfb3f123771
[   +6 ms] executing: [/home/somannak/applications/flutter/] git rev-parse --abbrev-ref --symbolic @{u}
[   +4 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[        ] origin/master
[        ] executing: [/home/somannak/applications/flutter/] git ls-remote --get-url origin
[   +5 ms] Exit code 0 from: git ls-remote --get-url origin
[        ] https://github.com/flutter/flutter.git
[  +65 ms] executing: [/home/somannak/applications/flutter/] git rev-parse --abbrev-ref HEAD
[   +4 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[        ] master
[  +47 ms] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterWebSdk' is not required, skipping update.
[   +2 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'WindowsUwpEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[  +55 ms] executing: /opt/android-sdk/platform-tools/adb devices -l
[  +37 ms] List of devices attached
           emulator-5554          device product:sdk_gphone_x86 model:Android_SDK_built_for_x86 device:generic_x86 transport_id:1
[   +6 ms] /opt/android-sdk/platform-tools/adb -s emulator-5554 shell getprop
[  +19 ms] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[   +1 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'WindowsUwpEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[  +96 ms] Skipping pub get: version match.
[  +54 ms] Generating /home/somannak/Scripts/flutter/anothertry/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
[  +45 ms] ro.hardware = ranchu
[  +11 ms] Using hardware rendering with device Android SDK built for x86. If you notice graphics artifacts, consider enabling software rendering with
           "--enable-software-rendering".
[  +31 ms] Initializing file store
[   +9 ms] Skipping target: gen_localizations
[   +7 ms] gen_dart_plugin_registrant: Starting due to {InvalidatedReasonKind.inputChanged: The following inputs have updated contents:
/home/somannak/Scripts/flutter/anothertry/.dart_tool/package_config_subset}
[  +23 ms] gen_dart_plugin_registrant: Complete
[   +1 ms] Skipping target: _composite
[   +4 ms] complete
[   +7 ms] Launching lib/main.dart on Android SDK built for x86 in debug mode...
[   +4 ms] /home/somannak/applications/flutter/bin/cache/dart-sdk/bin/dart --disable-dart-dev
/home/somannak/applications/flutter/bin/cache/artifacts/engine/linux-x64/frontend_server.dart.snapshot --sdk-root
/home/somannak/applications/flutter/bin/cache/artifacts/engine/common/flutter_patched_sdk/ --incremental --target=flutter --debugger-module-names
--experimental-emit-debug-metadata -DFLUTTER_WEB_AUTO_DETECT=true --output-dill /tmp/flutter_tools.PTINBM/flutter_tool.UPUFNQ/app.dill --packages
/home/somannak/Scripts/flutter/anothertry/.dart_tool/package_config.json -Ddart.vm.profile=false -Ddart.vm.product=false --enable-asserts
--track-widget-creation --filesystem-scheme org-dartlang-root --initialize-from-dill build/c075001b96339384a97db4862b8ab8db.cache.dill.track.dill
--flutter-widget-cache --enable-experiment=alternative-invalidation-strategy
[  +12 ms] executing: /opt/android-sdk/platform-tools/adb -s emulator-5554 shell -x logcat -v time -t 1
[  +13 ms] <- compile package:anothertry/main.dart
[  +19 ms] --------- beginning of main
           11-20 04:09:22.351 I/DeviceStateChecker( 3121): DeviceStateChecker cancelled
[  +10 ms] executing: /opt/android-sdk/platform-tools/adb version
[   +7 ms] Android Debug Bridge version 1.0.41
           Version 31.0.3-7562133
           Installed as /opt/android-sdk/platform-tools/adb
[   +2 ms] executing: /opt/android-sdk/platform-tools/adb start-server
[  +25 ms] Building APK
[  +15 ms] Running Gradle task 'assembleDebug'...
[   +3 ms] Using gradle from /home/somannak/Scripts/flutter/anothertry/android/gradlew.
[  +16 ms] executing: [/home/somannak/Scripts/flutter/anothertry/android/] /home/somannak/Scripts/flutter/anothertry/android/gradlew -Pverbose=true
-Ptarget-platform=android-x86 -Ptarget=/home/somannak/Scripts/flutter/anothertry/lib/main.dart -Pbase-application-name=android.app.Application
-Pdart-defines=RkxVVFRFUl9XRUJfQVVUT19ERVRFQ1Q9dHJ1ZQ== -Pdart-obfuscation=false -Ptrack-widget-creation=true -Ptree-shake-icons=false
-Pfilesystem-scheme=org-dartlang-root assembleDebug
[ +557 ms] Welcome to Gradle 6.7!
[        ] Here are the highlights of this release:
[        ]  - File system watching is ready for production use
[        ]  - Declare the version of Java your build requires
[        ]  - Java 15 support
[        ] For more details see https://docs.gradle.org/6.7/release-notes.html
[  +96 ms] FAILURE: Build failed with an exception.
[   +1 ms] * What went wrong:
[        ] Could not open settings generic class cache for settings file '/home/somannak/Scripts/flutter/anothertry/android/settings.gradle'
(/home/somannak/.gradle/caches/6.7/scripts/f0emg6u6oecmxqzgk5g9nn4ui).
[        ] > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61
[        ] * Try:
[        ] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
[        ] * Get more help at https://help.gradle.org
[        ] BUILD FAILED in 572ms
[ +374 ms] Running Gradle task 'assembleDebug'... (completed in 1,044ms)
[+6301 ms] Exception: Gradle task assembleDebug failed with exit code 1
[        ] "flutter run" took 7,909ms.
[   +4 ms]
           #0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
           #1      RunCommand.runCommand (package:flutter_tools/src/commands/run.dart:684:9)
           <asynchronous suspension>
           #2      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1161:27)
           <asynchronous suspension>
           #3      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #4      CommandRunner.runCommand (package:args/command_runner.dart:209:13)
           <asynchronous suspension>
           #5      FlutterCommandRunner.runCommand.<anonymous closure> (package:flutter_tools/src/runner/flutter_command_runner.dart:281:9)
           <asynchronous suspension>
           #6      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #7      FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:229:5)
           <asynchronous suspension>
           #8      run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:62:9)
           <asynchronous suspension>
           #9      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #10     main (package:flutter_tools/executable.dart:94:3)
           <asynchronous suspension>

[  +63 ms] ensureAnalyticsSent: 61ms
[        ] Running shutdown hooks
[        ] Shutdown hooks complete
[        ] exiting with code 1
</code>```

flutter doctor -v

```<code>[✓] Flutter (Channel master, 2.6.0-12.0.pre.770, on Arch Linux 5.14.16-arch1-1, locale en_IN.UTF-8)
    • Flutter version 2.6.0-12.0.pre.770 at /home/somannak/applications/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision fb3f123771 (82 minutes ago), 2021-11-19 23:18:08 +0200
    • Engine revision a3ef1d5351
    • Dart version 2.16.0 (build 2.16.0-20.0.dev)
    • DevTools version 2.8.0

[✓] Android toolchain - develop for Android devices (Android SDK version 31)
    • Android SDK at /opt/android-sdk
    • Platform android-31, build-tools 31
    • ANDROID_HOME = /opt/android-sdk
    • Java binary at: /usr/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.1+12)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).

[✓] Connected device (2 available)
    • Android SDK built for x86 (mobile) • emulator-5554 • android-x86    • Android 8.1.0 (API 27) (emulator)
    • Chrome (web)                       • chrome        • web-javascript • Google Chrome 94.0.4606.71

! Doctor found issues in 1 category.
</code>```

contents of pubspec.yaml file

```<code>name: anothertry
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.16.0-20.0.dev <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

</code>```

答:
My system is:

```<code>  Linux parrot 5.14.0-9parrot1-amd64 #1 SMP Debian 5.14.9-9parrot1 (2021-10-26) x86_64 GNU/Linux
</code>```

Flutter & Dart version

```<code>Flutter 2.2.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 02c026b03c (9 months ago) • 2021-05-27 12:24:44 -0700
Engine • revision 0fdb562ac8
Tools • Dart 2.13.1
</code>```

For me, sometimes this message appears when the disk is full,make sure there is enough space for the emulator to run.

Body:
I have tried almost everything I could find but I  am not able to resolve this error. This is the first time I'm installing flutter on the computer. The first project I try is giving me this error.

I got flutter from their GitHub repo, master branch and I installed all the SDK tools from the AUR. Installed SDK tools

android-emulator

androind-platform

android-sdk-build-tools

androind-sdk-cmdline-tools-latest

android-sdk-platform-tools

I basically followed this tutorial. I have installed the flutter and dart extensions in VS Code.

I'm doing all this on a vanilla arch system.

I have not done any changes to any part of the code and according to the information that people have asked for, these are the outputs of the commands

flutter run --debug

Using hardware rendering with device Android SDK built for x86. If you notice graphics artifacts, consider enabling software rendering with
"--enable-software-rendering".
Launching lib/main.dart on Android SDK built for x86 in debug mode...

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings generic class cache for settings file '/home/somannak/Scripts/flutter/anothertry/android/settings.gradle' (/home/somannak/.gradle/caches/6.7/scripts/f0emg6u6oecmxqzgk5g9nn4ui).
> BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 521ms
Running Gradle task 'assembleDebug'...                             978ms
Exception: Gradle task assembleDebug failed with exit code 1

flutter run --verbose

[  +47 ms] executing: uname -m
[  +25 ms] Exit code 0 from: uname -m
[        ] x86_64
[   +6 ms] executing: [/home/somannak/applications/flutter/] git -c log.showSignature=false log -n 1 --pretty=format:%H
[   +4 ms] Exit code 0 from: git -c log.showSignature=false log -n 1 --pretty=format:%H
[        ] fb3f123771d35171b08d1a8b41fccac5816f2f69
[        ] executing: [/home/somannak/applications/flutter/] git tag --points-at fb3f123771d35171b08d1a8b41fccac5816f2f69
[  +11 ms] Exit code 0 from: git tag --points-at fb3f123771d35171b08d1a8b41fccac5816f2f69
[   +1 ms] executing: [/home/somannak/applications/flutter/] git describe --match *.*.* --long --tags fb3f123771d35171b08d1a8b41fccac5816f2f69
[  +32 ms] Exit code 0 from: git describe --match *.*.* --long --tags fb3f123771d35171b08d1a8b41fccac5816f2f69
[        ] 2.6.0-11.0.pre-770-gfb3f123771
[   +6 ms] executing: [/home/somannak/applications/flutter/] git rev-parse --abbrev-ref --symbolic @{u}
[   +4 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[        ] origin/master
[        ] executing: [/home/somannak/applications/flutter/] git ls-remote --get-url origin
[   +5 ms] Exit code 0 from: git ls-remote --get-url origin
[        ] https://github.com/flutter/flutter.git
[  +65 ms] executing: [/home/somannak/applications/flutter/] git rev-parse --abbrev-ref HEAD
[   +4 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[        ] master
[  +47 ms] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterWebSdk' is not required, skipping update.
[   +2 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'WindowsUwpEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[  +55 ms] executing: /opt/android-sdk/platform-tools/adb devices -l
[  +37 ms] List of devices attached
           emulator-5554          device product:sdk_gphone_x86 model:Android_SDK_built_for_x86 device:generic_x86 transport_id:1
[   +6 ms] /opt/android-sdk/platform-tools/adb -s emulator-5554 shell getprop
[  +19 ms] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[   +1 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'WindowsUwpEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[  +96 ms] Skipping pub get: version match.
[  +54 ms] Generating /home/somannak/Scripts/flutter/anothertry/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
[  +45 ms] ro.hardware = ranchu
[  +11 ms] Using hardware rendering with device Android SDK built for x86. If you notice graphics artifacts, consider enabling software rendering with
           "--enable-software-rendering".
[  +31 ms] Initializing file store
[   +9 ms] Skipping target: gen_localizations
[   +7 ms] gen_dart_plugin_registrant: Starting due to {InvalidatedReasonKind.inputChanged: The following inputs have updated contents:
/home/somannak/Scripts/flutter/anothertry/.dart_tool/package_config_subset}
[  +23 ms] gen_dart_plugin_registrant: Complete
[   +1 ms] Skipping target: _composite
[   +4 ms] complete
[   +7 ms] Launching lib/main.dart on Android SDK built for x86 in debug mode...
[   +4 ms] /home/somannak/applications/flutter/bin/cache/dart-sdk/bin/dart --disable-dart-dev
/home/somannak/applications/flutter/bin/cache/artifacts/engine/linux-x64/frontend_server.dart.snapshot --sdk-root
/home/somannak/applications/flutter/bin/cache/artifacts/engine/common/flutter_patched_sdk/ --incremental --target=flutter --debugger-module-names
--experimental-emit-debug-metadata -DFLUTTER_WEB_AUTO_DETECT=true --output-dill /tmp/flutter_tools.PTINBM/flutter_tool.UPUFNQ/app.dill --packages
/home/somannak/Scripts/flutter/anothertry/.dart_tool/package_config.json -Ddart.vm.profile=false -Ddart.vm.product=false --enable-asserts
--track-widget-creation --filesystem-scheme org-dartlang-root --initialize-from-dill build/c075001b96339384a97db4862b8ab8db.cache.dill.track.dill
--flutter-widget-cache --enable-experiment=alternative-invalidation-strategy
[  +12 ms] executing: /opt/android-sdk/platform-tools/adb -s emulator-5554 shell -x logcat -v time -t 1
[  +13 ms] <- compile package:anothertry/main.dart
[  +19 ms] --------- beginning of main
           11-20 04:09:22.351 I/DeviceStateChecker( 3121): DeviceStateChecker cancelled
[  +10 ms] executing: /opt/android-sdk/platform-tools/adb version
[   +7 ms] Android Debug Bridge version 1.0.41
           Version 31.0.3-7562133
           Installed as /opt/android-sdk/platform-tools/adb
[   +2 ms] executing: /opt/android-sdk/platform-tools/adb start-server
[  +25 ms] Building APK
[  +15 ms] Running Gradle task 'assembleDebug'...
[   +3 ms] Using gradle from /home/somannak/Scripts/flutter/anothertry/android/gradlew.
[  +16 ms] executing: [/home/somannak/Scripts/flutter/anothertry/android/] /home/somannak/Scripts/flutter/anothertry/android/gradlew -Pverbose=true
-Ptarget-platform=android-x86 -Ptarget=/home/somannak/Scripts/flutter/anothertry/lib/main.dart -Pbase-application-name=android.app.Application
-Pdart-defines=RkxVVFRFUl9XRUJfQVVUT19ERVRFQ1Q9dHJ1ZQ== -Pdart-obfuscation=false -Ptrack-widget-creation=true -Ptree-shake-icons=false
-Pfilesystem-scheme=org-dartlang-root assembleDebug
[ +557 ms] Welcome to Gradle 6.7!
[        ] Here are the highlights of this release:
[        ]  - File system watching is ready for production use
[        ]  - Declare the version of Java your build requires
[        ]  - Java 15 support
[        ] For more details see https://docs.gradle.org/6.7/release-notes.html
[  +96 ms] FAILURE: Build failed with an exception.
[   +1 ms] * What went wrong:
[        ] Could not open settings generic class cache for settings file '/home/somannak/Scripts/flutter/anothertry/android/settings.gradle'
(/home/somannak/.gradle/caches/6.7/scripts/f0emg6u6oecmxqzgk5g9nn4ui).
[        ] > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61
[        ] * Try:
[        ] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
[        ] * Get more help at https://help.gradle.org
[        ] BUILD FAILED in 572ms
[ +374 ms] Running Gradle task 'assembleDebug'... (completed in 1,044ms)
[+6301 ms] Exception: Gradle task assembleDebug failed with exit code 1
[        ] "flutter run" took 7,909ms.
[   +4 ms]
           #0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
           #1      RunCommand.runCommand (package:flutter_tools/src/commands/run.dart:684:9)
           <asynchronous suspension>
           #2      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1161:27)
           <asynchronous suspension>
           #3      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #4      CommandRunner.runCommand (package:args/command_runner.dart:209:13)
           <asynchronous suspension>
           #5      FlutterCommandRunner.runCommand.<anonymous closure> (package:flutter_tools/src/runner/flutter_command_runner.dart:281:9)
           <asynchronous suspension>
           #6      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #7      FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:229:5)
           <asynchronous suspension>
           #8      run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:62:9)
           <asynchronous suspension>
           #9      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #10     main (package:flutter_tools/executable.dart:94:3)
           <asynchronous suspension>

[  +63 ms] ensureAnalyticsSent: 61ms
[        ] Running shutdown hooks
[        ] Shutdown hooks complete
[        ] exiting with code 1

flutter doctor -v

[✓] Flutter (Channel master, 2.6.0-12.0.pre.770, on Arch Linux 5.14.16-arch1-1, locale en_IN.UTF-8)
    • Flutter version 2.6.0-12.0.pre.770 at /home/somannak/applications/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision fb3f123771 (82 minutes ago), 2021-11-19 23:18:08 +0200
    • Engine revision a3ef1d5351
    • Dart version 2.16.0 (build 2.16.0-20.0.dev)
    • DevTools version 2.8.0

[✓] Android toolchain - develop for Android devices (Android SDK version 31)
    • Android SDK at /opt/android-sdk
    • Platform android-31, build-tools 31
    • ANDROID_HOME = /opt/android-sdk
    • Java binary at: /usr/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.1+12)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).

[✓] Connected device (2 available)
    • Android SDK built for x86 (mobile) • emulator-5554 • android-x86    • Android 8.1.0 (API 27) (emulator)
    • Chrome (web)                       • chrome        • web-javascript • Google Chrome 94.0.4606.71

! Doctor found issues in 1 category.

contents of pubspec.yaml file

name: anothertry
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.16.0-20.0.dev <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

Body:
My system is:

  Linux parrot 5.14.0-9parrot1-amd64 #1 SMP Debian 5.14.9-9parrot1 (2021-10-26) x86_64 GNU/Linux

Flutter & Dart version

Flutter 2.2.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 02c026b03c (9 months ago) • 2021-05-27 12:24:44 -0700
Engine • revision 0fdb562ac8
Tools • Dart 2.13.1

For me, sometimes this message appears when the disk is full,make sure there is enough space for the emulator to run.


问:
check and count occurrence of particular key in list of dictionaries in python
Question:
Below is response body from GET call of REST API.
I need to check occurrence of status and gender in response body and count how many Male active, Male inactive, Female active and Female Inactive are present.

Given Input:

```<code>[
{"id":3627,
"name":"Arnesh Patil",
"email":"patil_arnesh@moen-mitchell.com",
"gender":"male",
"status":"active"},
{"id":3626,
"name":"Digambara Ahuja",
"email":"digambara_ahuja@monahan.com",
"gender":"male",
"status":"inactive"},
{"id":3625,
"name":"Smriti Sharma Esq.",
"email":"smriti_sharma_esq@wehner-homenick.com",
"gender":"female",
"status":"inactive"},{"id":3624,
"name":"Vedanga Ganaka PhD",
"email":"phd_ganaka_vedanga@medhurst.name",
"gender":"male",
"status":"active"}
]
</code>```

After that we need to store output in below nested dictionary format:

Expected Ouptut

```<code>{
'active':
    {  'male': 2,
       'female': 0
    },
'inactive':
    { 'male': 1,
      'female': 1
    }
}
</code>```

how to parse List of dictionary and get output as shown above?

答:
Get a list of the genders of the people to which each statuses applies, and then count up the frequency of each gender for each status.

The first part can be done using list comprehensions. The Counter object in the built-in collections library is a convenient way to count frequencies for the second part.

Take a look at the following:

```<code>from collections import Counter

response = [
    {"id":3627,"name":"Arnesh Patil","email":"patil_arnesh@moen-mitchell.com","gender":"male","status":"active"},
    {"id":3626,"name":"Digambara Ahuja","email":"digambara_ahuja@monahan.com","gender":"male","status":"inactive"},
    {"id":3625,"name":"Smriti Sharma Esq.","email":"smriti_sharma_esq@wehner-homenick.com","gender":"female","status":"inactive"},
    {"id":3624,"name":"Vedanga Ganaka PhD","email":"phd_ganaka_vedanga@medhurst.name","gender":"male","status":"active"}
]

statuses = ['active', 'inactive']
output_dict = {}

for status in statuses:
    output_dict[status] = [person['gender'] for person in response
                           if (person['status']) == status]
output_dict = {status: dict(Counter(genders))
               for status, genders in output_dict.items()}

print(output_dict)
</code>```

Outputs:

```<code>{'active': {'male': 2}, 'inactive': {'male': 1, 'female': 1}}
</code>```

The 'male'/'female' keys are not included when there are 0 instances for a status, so if you need those keys to exist later you may need to adjust the code slightly.

Body:
Question:
Below is response body from GET call of REST API.
I need to check occurrence of status and gender in response body and count how many Male active, Male inactive, Female active and Female Inactive are present.

Given Input:

[
{"id":3627,
"name":"Arnesh Patil",
"email":"patil_arnesh@moen-mitchell.com",
"gender":"male",
"status":"active"},
{"id":3626,
"name":"Digambara Ahuja",
"email":"digambara_ahuja@monahan.com",
"gender":"male",
"status":"inactive"},
{"id":3625,
"name":"Smriti Sharma Esq.",
"email":"smriti_sharma_esq@wehner-homenick.com",
"gender":"female",
"status":"inactive"},{"id":3624,
"name":"Vedanga Ganaka PhD",
"email":"phd_ganaka_vedanga@medhurst.name",
"gender":"male",
"status":"active"}
]

After that we need to store output in below nested dictionary format:

Expected Ouptut

{
'active':
    {  'male': 2,
       'female': 0
    },
'inactive':
    { 'male': 1,
      'female': 1
    }
}

how to parse List of dictionary and get output as shown above?

Body:
Get a list of the genders of the people to which each statuses applies, and then count up the frequency of each gender for each status.

The first part can be done using list comprehensions. The Counter object in the built-in collections library is a convenient way to count frequencies for the second part.

Take a look at the following:

from collections import Counter

response = [
    {"id":3627,"name":"Arnesh Patil","email":"patil_arnesh@moen-mitchell.com","gender":"male","status":"active"},
    {"id":3626,"name":"Digambara Ahuja","email":"digambara_ahuja@monahan.com","gender":"male","status":"inactive"},
    {"id":3625,"name":"Smriti Sharma Esq.","email":"smriti_sharma_esq@wehner-homenick.com","gender":"female","status":"inactive"},
    {"id":3624,"name":"Vedanga Ganaka PhD","email":"phd_ganaka_vedanga@medhurst.name","gender":"male","status":"active"}
]

statuses = ['active', 'inactive']
output_dict = {}

for status in statuses:
    output_dict[status] = [person['gender'] for person in response
                           if (person['status']) == status]
output_dict = {status: dict(Counter(genders))
               for status, genders in output_dict.items()}

print(output_dict)

Outputs:

{'active': {'male': 2}, 'inactive': {'male': 1, 'female': 1}}

The 'male'/'female' keys are not included when there are 0 instances for a status, so if you need those keys to exist later you may need to adjust the code slightly.


问:
Kubectl command to check if cronjob is active or not
I'm trying to check if a particular cronjob is active or not through a shell script to perform some action if the job is not active. I tried using field-selector attribute for cronjob and the job created by the cron job as below

```<code>kubectl get cronjobs --field-selector status.active==1
kubectl get jobs --field-selector status.succeeded==1
</code>```

But getting these field selectors are not supported. Is there any other field/way where I can check if the cronjob is active?

答:
You could also set a label on your cronjob (and set the same label on the template part of the cronjob so it propagates to the underlying job that gets created), and then use that to select via:

kubectl get cronjob -l label=value

kubectl get job -l label=value

Yes, it doesn't select by active/disabled state, but you did mention in your question you were checking a particular cronjob, so this would bring up the details of the specific cronjob or job for you to check

To get the actual suspend state of the cronjob, you could pipe it to jq

kubectl get cronjob cronjob-name | jq .items[0].spec.suspend

This will give you "false" or "true" if the cronjob is suspended or not:

```<code>$ kubectl get cronjob -n test
NAME      SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
api       */5 * * * *   False     0        78s             5m53s
</code>```
```<code>$ kubectl get cronjob -n test api -o json | jq .spec.suspend
false
</code>```

You could probably also do this with jsonpath

```<code>kubectl get cronjob -n test api -o jsonpath="{.spec.suspend}"
</code>```

From comment below, you use can active (i.e. currently running) , to see how many jobs are active (will be 0 if you don't have anything running)

kubectl get cronjob -n test api -o jsonpath="{.spec.active}"

Body:
I'm trying to check if a particular cronjob is active or not through a shell script to perform some action if the job is not active. I tried using field-selector attribute for cronjob and the job created by the cron job as below

kubectl get cronjobs --field-selector status.active==1
kubectl get jobs --field-selector status.succeeded==1

But getting these field selectors are not supported. Is there any other field/way where I can check if the cronjob is active?

Body:
You could also set a label on your cronjob (and set the same label on the template part of the cronjob so it propagates to the underlying job that gets created), and then use that to select via:

kubectl get cronjob -l label=value

kubectl get job -l label=value

Yes, it doesn't select by active/disabled state, but you did mention in your question you were checking a particular cronjob, so this would bring up the details of the specific cronjob or job for you to check

To get the actual suspend state of the cronjob, you could pipe it to jq

kubectl get cronjob cronjob-name | jq .items[0].spec.suspend

This will give you "false" or "true" if the cronjob is suspended or not:

$ kubectl get cronjob -n test
NAME      SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
api       */5 * * * *   False     0        78s             5m53s

$ kubectl get cronjob -n test api -o json | jq .spec.suspend
false

You could probably also do this with jsonpath

kubectl get cronjob -n test api -o jsonpath="{.spec.suspend}"

From comment below, you use can active (i.e. currently running) , to see how many jobs are active (will be 0 if you don't have anything running)

kubectl get cronjob -n test api -o jsonpath="{.spec.active}"


问:
How to do Expo/react-native Google Authentication in a class based component?
I am trying to implement Google Authentication into my Expo/react native component based class, but the example Expo gives is for functional components.

They use this code for the Google Authentication:

```<code>import * as React from 'react';
import * as WebBrowser from 'expo-web-browser';
import * as Google from 'expo-auth-session/providers/google';
import { Button } from 'react-native';

WebBrowser.maybeCompleteAuthSession();

export default function App() {
  const [request, response, promptAsync] = Google.useAuthRequest({
    expoClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
    iosClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
    androidClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
    webClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
  });

  React.useEffect(() => {
    if (response?.type === 'success') {
      const { authentication } = response;
      }
  }, [response]);

  return (
    <Button
      disabled={!request}
      title="Login"
      onPress={() => {
        promptAsync();
        }}
    />
  );
}
</code>```

My question is how would I go about doing something similar to this for a class based component (export default class App extends Component)

答:
This is actually a general subject, how to call React's functional components from within class components.

Specific to Google Sign In, this answer can help: https://stackoverflow.com/a/66974167/1870873

Body:
I am trying to implement Google Authentication into my Expo/react native component based class, but the example Expo gives is for functional components.

They use this code for the Google Authentication:

import * as React from 'react';
import * as WebBrowser from 'expo-web-browser';
import * as Google from 'expo-auth-session/providers/google';
import { Button } from 'react-native';

WebBrowser.maybeCompleteAuthSession();

export default function App() {
  const [request, response, promptAsync] = Google.useAuthRequest({
    expoClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
    iosClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
    androidClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
    webClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
  });

  React.useEffect(() => {
    if (response?.type === 'success') {
      const { authentication } = response;
      }
  }, [response]);

  return (
    <Button
      disabled={!request}
      title="Login"
      onPress={() => {
        promptAsync();
        }}
    />
  );
}

My question is how would I go about doing something similar to this for a class based component (export default class App extends Component)


问:
How to parse a dynamic JSON key in a Nested JSON result?
I have a JSON result in the following format which JSON Lint shows this as a "Valid Response".

My question is: how do I access the content of "question_mark" since "141", "8911", etc are all dynamic values?

My sample code for accessing value of "product".

```<code>//Consider I have the first <code>JSONObject</code> of the "search_result" array and
//I access it's "product" value as below.
String product = jsonObject.optString("product"); //where jsonObject is of type JSONObject.
//<code>product<code> now contains "abc".
</code>```

JSON:

```<code>{
 "status": "OK",
 "search_result": [

            {
                "product": "abc",
                "id": "1132",
                "question_mark": {
                    "141": {
                        "count": "141",
                        "more_description": "this is abc",
                        "seq": "2"
                    },
                    "8911": {
                        "count": "8911",
                        "more_desc": "this is cup",
                        "seq": "1"
                    }
                },
                "name": "some name",
                "description": "This is some product"
            },
            {
                "product": "XYZ",
                "id": "1129",
                "question_mark": {
                    "379": {
                        "count": "379",
                        "more_desc": "this is xyz",
                        "seq": "5"
                    },
                    "845": {
                        "count": "845",
                        "more_desc": "this is table",
                        "seq": "6"
                    },
                    "12383": {
                        "count": "12383",
                        "more_desc": "Jumbo",
                        "seq": "4"
                    },
                    "257258": {
                        "count": "257258",
                        "more_desc": "large",
                        "seq": "1"
                    }
                },
                "name": "some other name",
                "description": "this is some other product"
            }
       ]
}
</code>```

My question title "dynamic key" could be wrong but I don't know at this point what's a better name for this issue.

Any help would be greatly appreciated!

答:
You can use this logic. use org.json library</p>
```<code><dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20211205</version>
</dependency>

public void parseJson(JSONObject jo, String key) {
Iterator<?> keyIterator;
String key1;
if (jo.has(key)) {
    System.out.println(jo.get(key));
} else {
    keyIterator = jo.keys();
    while (keyIterator.hasNext()) {
    key1 = (String) keyIterator.next();
    if (jo.get(key1) instanceof JSONObject) {
        if (!jo.has(key))
        parseJson(jo.getJSONObject(key1), key);
    } else if (jo.get(key1) instanceof JSONArray) {
        JSONArray jsonarray = jo.getJSONArray(key1);
        Iterator<?> itr = jsonarray.iterator();
        while (itr.hasNext()) {
        String arrayString = itr.next().toString();
        JSONObject jo1 = new JSONObject(arrayString);
        if (!jo1.has(key)) {
            parseJson(jo1, key);
        }
        }

    }
    }
}
}
</code>```

Body:
I have a JSON result in the following format which JSON Lint shows this as a "Valid Response".

My question is: how do I access the content of "question_mark" since "141", "8911", etc are all dynamic values?

My sample code for accessing value of "product".

//Consider I have the first JSONObject of the "search_result" array and
//I access it's "product" value as below.
String product = jsonObject.optString("product"); //where jsonObject is of type JSONObject.
//product now contains "abc".

JSON:

{
 "status": "OK",
 "search_result": [

            {
                "product": "abc",
                "id": "1132",
                "question_mark": {
                    "141": {
                        "count": "141",
                        "more_description": "this is abc",
                        "seq": "2"
                    },
                    "8911": {
                        "count": "8911",
                        "more_desc": "this is cup",
                        "seq": "1"
                    }
                },
                "name": "some name",
                "description": "This is some product"
            },
            {
                "product": "XYZ",
                "id": "1129",
                "question_mark": {
                    "379": {
                        "count": "379",
                        "more_desc": "this is xyz",
                        "seq": "5"
                    },
                    "845": {
                        "count": "845",
                        "more_desc": "this is table",
                        "seq": "6"
                    },
                    "12383": {
                        "count": "12383",
                        "more_desc": "Jumbo",
                        "seq": "4"
                    },
                    "257258": {
                        "count": "257258",
                        "more_desc": "large",
                        "seq": "1"
                    }
                },
                "name": "some other name",
                "description": "this is some other product"
            }
       ]
}

My question title "dynamic key" could be wrong but I don't know at this point what's a better name for this issue.

Any help would be greatly appreciated!

Body:
You can use this logic. use org.json library

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20211205</version>
</dependency>

public void parseJson(JSONObject jo, String key) {
Iterator<?> keyIterator;
String key1;
if (jo.has(key)) {
    System.out.println(jo.get(key));
} else {
    keyIterator = jo.keys();
    while (keyIterator.hasNext()) {
    key1 = (String) keyIterator.next();
    if (jo.get(key1) instanceof JSONObject) {
        if (!jo.has(key))
        parseJson(jo.getJSONObject(key1), key);
    } else if (jo.get(key1) instanceof JSONArray) {
        JSONArray jsonarray = jo.getJSONArray(key1);
        Iterator<?> itr = jsonarray.iterator();
        while (itr.hasNext()) {
        String arrayString = itr.next().toString();
        JSONObject jo1 = new JSONObject(arrayString);
        if (!jo1.has(key)) {
            parseJson(jo1, key);
        }
        }

    }
    }
}
}


问:
Filtering IEnumerable<T> dataset with T as Dictionary<string, object>
There is a data set as IEnumerable<T> GridData which is bound to a data grid. In one scenario data loaded with T as Dictionary<string, object>. When user apply filter/sort on the grid, I can get those as follows.

```<code>filters : [{Property: 'abc', Value: 'aaa'}]
sort: [{Property: 'abc'}]
</code>```

on the Dictionary<string, object> Key represent the Property and Value represent the Value.

I'm stuck with filtering and sorting on IEnumerable<T> GridData. Can anyone show me the direction?

答:
I would go for a helper function like this

```<code>    private static object GetPropValue(object src, string propName)
    {
        return src.GetType().GetProperty(propName)?.GetValue(src, null);
    }
</code>```

then filter the GridData like this asuming the filters is an array you need to check against all filters on it.

```<code>    private static void test<T>(IEnumerable<T> GridData, Dictionary<string, object> filters)
    {

        IEnumerable<T> result = GridData;
        foreach (KeyValuePair<string, object> filter in filters.ToList())
        {
            result = result.Where(x =>
                       (x as Dictionary<string, object>).Values.Any(d =>
                         filter.Value.Equals((T)GetPropValue(d, filter.Key))));
        }
    }
</code>```

IF your filters arent a Dictionary, only a List of Tuples<string, object>:

```<code>    private static void test2<T>(IEnumerable<T> GridData, List<Tuple<string, object>> filters)
    {

        IEnumerable<T> result = GridData;
        foreach (Tuple<string, object> filter in filters.ToList())
        {
            result = result.Where(x =>
                       (x as Dictionary<string, object>).Values.Any(d =>
                         filter.Item2.Equals((T)GetPropValue(d, filter.Item1))));
        }
    }
</code>```

And do the sort using the same aproach

Body:
There is a data set as IEnumerable<T> GridData which is bound to a data grid. In one scenario data loaded with T as Dictionary<string, object>. When user apply filter/sort on the grid, I can get those as follows.

filters : [{Property: 'abc', Value: 'aaa'}]
sort: [{Property: 'abc'}]

on the Dictionary<string, object> Key represent the Property and Value represent the Value.

I'm stuck with filtering and sorting on IEnumerable<T> GridData. Can anyone show me the direction?

Body:
I would go for a helper function like this

    private static object GetPropValue(object src, string propName)
    {
        return src.GetType().GetProperty(propName)?.GetValue(src, null);
    }

then filter the GridData like this asuming the filters is an array you need to check against all filters on it.

    private static void test<T>(IEnumerable<T> GridData, Dictionary<string, object> filters)
    {

        IEnumerable<T> result = GridData;
        foreach (KeyValuePair<string, object> filter in filters.ToList())
        {
            result = result.Where(x =>
                       (x as Dictionary<string, object>).Values.Any(d =>
                         filter.Value.Equals((T)GetPropValue(d, filter.Key))));
        }
    }

IF your filters arent a Dictionary, only a List of Tuples<string, object>:

    private static void test2<T>(IEnumerable<T> GridData, List<Tuple<string, object>> filters)
    {

        IEnumerable<T> result = GridData;
        foreach (Tuple<string, object> filter in filters.ToList())
        {
            result = result.Where(x =>
                       (x as Dictionary<string, object>).Values.Any(d =>
                         filter.Item2.Equals((T)GetPropValue(d, filter.Item1))));
        }
    }

And do the sort using the same aproach


问:
When I use the JavaScript On Screen Menu example, the button of OnScreenMenuButtonType doesn't show the icon
I don't know why, the example in the document can display the icon, but the one I wrote does not display
enter image description here</p>
```<code>this.SpecChart.addOnScreenMenu(
        [
          [
            // Default buttons
            OnScreenMenuButtonType.ZoomInX,
            OnScreenMenuButtonType.ZoomOutX,
            OnScreenMenuButtonType.ZoomInY,
            OnScreenMenuButtonType.ZoomOutY,
            OnScreenMenuButtonType.ZoomToFit,
            OnScreenMenuButtonType.ToggleAnimations,
            // cusrom button
            {
              dimensions: { rows: 1, columns: 1 },
              label: "Show Heatmap",
              opacity: "1",
              color: "blue",
              shape: OnScreenMenuButtonShape.RoundedRectangle,
              action: this.show,
            },
          ],
        ],
        OnScreenMenuButtonShape.RoundedRectangle
      );
</code>```

答:
You have set: this.show. Is it not just show. And by the way. Where is your icon property by custom button?

The last one is a custom button. My question is that the first few yellow buttons do not display icons.I know custom button can set icon url

as you can see in the image

Body:
I don't know why, the example in the document can display the icon, but the one I wrote does not display
enter image description here

this.SpecChart.addOnScreenMenu(
        [
          [
            // Default buttons
            OnScreenMenuButtonType.ZoomInX,
            OnScreenMenuButtonType.ZoomOutX,
            OnScreenMenuButtonType.ZoomInY,
            OnScreenMenuButtonType.ZoomOutY,
            OnScreenMenuButtonType.ZoomToFit,
            OnScreenMenuButtonType.ToggleAnimations,
            // cusrom button
            {
              dimensions: { rows: 1, columns: 1 },
              label: "Show Heatmap",
              opacity: "1",
              color: "blue",
              shape: OnScreenMenuButtonShape.RoundedRectangle,
              action: this.show,
            },
          ],
        ],
        OnScreenMenuButtonShape.RoundedRectangle
      );