问:
JavaScript / jQuery - Program keeps drawing after mouse left the canvas
I am making a paint application using jQuery and I ran into a problem.

```<code>CodePen: https://codepen.io/mistahdukk/pen/dmaKOV

canvas.mousedown(function(e){
    down = true;
    draw(e);
}).mouseover(function(e){
    ctx.beginPath();
    draw(e);
}).mouseout(function(e){
    ctx.beginPath();
}).mousemove(draw).mouseup(function(){
    down =false;
    ctx.beginPath();
});
</code>```

If the mouse leaves the canvas and the click is released and the mouse re-enters the canvas, the app will continue to draw, but I only want to make it so that it draws only when the mouse has been clicked. I don't really know how to solve this issue. Thanks.

答:
JavaScript:

canvas.addEventListener('mouseleave', () => {
    drawing = false;
})
```
<p>CSS:</p>
```body {
    user-select: none; // or even better to your canvas wrapper to disable higlighting once you left click to draw on canvas again
}
```

Body:
I am making a paint application using jQuery and I ran into a problem.

CodePen: https://codepen.io/mistahdukk/pen/dmaKOV

canvas.mousedown(function(e){
    down = true;
    draw(e);
}).mouseover(function(e){
    ctx.beginPath();
    draw(e);
}).mouseout(function(e){
    ctx.beginPath();
}).mousemove(draw).mouseup(function(){
    down =false;
    ctx.beginPath();
});

If the mouse leaves the canvas and the click is released and the mouse re-enters the canvas, the app will continue to draw, but I only want to make it so that it draws only when the mouse has been clicked. I don't really know how to solve this issue. Thanks.

Body:
JavaScript:

canvas.addEventListener('mouseleave', () => {
    drawing = false;
})

CSS:

body {
    user-select: none; // or even better to your canvas wrapper to disable higlighting once you left click to draw on canvas again
}


来源: stackexchange

问:
How to make my javascript code responsive?
how to tell my simple jquery code to activate the click on my .filter_btn

only when I'm on a mobile or tablet (max-width: 768px)

and not on a desktop ?

```<code><script>

document.addEventListener('DOMContentLoaded', function() {

jQuery(function($){

$('.filter_btn').click(function(event){

$('.content_filter').slideToggle('250','swing','hide');

});
});
});

</script>

<style>

  @media all and (max-width: 768px)
{
    .content_filter {
    display:none;
}
}

</style>
</code>```

as you can see here i can click in desktop mode

答:
You could validate the width of the window by using the window.innerWidth property.  Something like:</p>
```<code><script>

document.addEventListener('DOMContentLoaded', function() {

    jQuery(function($){

        $('.filter_btn').click(function(event){
            //Here we validate the size of the window, I've had this act wonky
            //before, so you may have to adjust the value
            if(window.innerWidth <= 768) {
                $('.content_filter').slideToggle('250','swing','hide');
            }
        });
    });
});
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
how to tell my simple jquery code to activate the click on my .filter_btn

only when I'm on a mobile or tablet (max-width: 768px)

and not on a desktop ?

as you can see here i can click in desktop mode

Body:
You could validate the width of the window by using the window.innerWidth property.  Something like:

<script>

document.addEventListener('DOMContentLoaded', function() {

    jQuery(function($){

        $('.filter_btn').click(function(event){
            //Here we validate the size of the window, I've had this act wonky
            //before, so you may have to adjust the value
            if(window.innerWidth <= 768) {
                $('.content_filter').slideToggle('250','swing','hide');
            }
        });
    });
});
</script>


答:
You already have a media query set up to hide content over the specified screensize, but you are hiding the .content-filter.
If you don't want the .filter_btn to be clicked, then hide it.

If you still want the header to be visible, then have two versions of the header: one that is displayed for small screens that IS clickable, and one that displays on large screens and is not clickable.

Title: How to make my javascript code responsive?


问:
Checkbox selectAll\DeselectAll in tableLayout
I have List of route in tablelayout.
CheckBox & TextView created dynamically.
I set the checkbox id.

I want to do the selectall & deselectAll . How we can implement?

I created checkBox using coding.then How can call this CheckBox cb = (CheckBox)view.findViewById(R.id.????);

```<code> tl = (TableLayout) findViewById(R.id.dailyDRoute);
    ArrayList<SalesRoutes> routeList = getSalesRoute();
    for (int i = 0; i < routeList.size(); i++) {
        TableRow tr = new TableRow(this);
        CheckBox ch = new CheckBox(this);
        ch.setHeight(1);
        ch.setId(i);
        TextView tv2 = new TextView(this);
        tr.addView(ch);
        tv2.setText(routeList.get(i).getDescription());
        tv2.setTextColor(Color.BLACK);

        tr.addView(tv2);
        tl.addView(tr);
    }
}

 public void deselectAll(View view){
    // CheckBox cb = (CheckBox)view.findViewById(R.id.);

 }

 public void selectAll(View view){

 }
</code>```

Please help me ...

Thanks in advance..

答:
R.id.* are integer constants generated during build process. Actually, you need to pass an integer id to findViewById (same integer as you set us as id in init block).
Like this:

```<code>for (int i = 0; i < tl.getChildCount(); i++) {
  CheckBox cb = (CheckBox)view.findViewById(i);
  cb.setChecked(true);
}
</code>```

But as for me this is not very reliable because id set in runtime can be not unique and I think this loop is better:

```<code>for (int i = 0; i < tl.getChildCount(); i++) {
  CheckBox cb = (CheckBox)((TableRow)tl.getChildAt(i)).getChildAt(0);
  cb.setChecked(true);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have List of route in tablelayout.
CheckBox & TextView created dynamically.
I set the checkbox id.

I want to do the selectall & deselectAll . How we can implement?

I created checkBox using coding.then How can call this CheckBox cb = (CheckBox)view.findViewById(R.id.????);

 tl = (TableLayout) findViewById(R.id.dailyDRoute);
    ArrayList<SalesRoutes> routeList = getSalesRoute();
    for (int i = 0; i < routeList.size(); i++) {
        TableRow tr = new TableRow(this);
        CheckBox ch = new CheckBox(this);
        ch.setHeight(1);
        ch.setId(i);
        TextView tv2 = new TextView(this);
        tr.addView(ch);
        tv2.setText(routeList.get(i).getDescription());
        tv2.setTextColor(Color.BLACK);

        tr.addView(tv2);
        tl.addView(tr);
    }
}

 public void deselectAll(View view){
    // CheckBox cb = (CheckBox)view.findViewById(R.id.);

 }

 public void selectAll(View view){

 }

Please help me ...

Thanks in advance..

Body:
R.id.* are integer constants generated during build process. Actually, you need to pass an integer id to findViewById (same integer as you set us as id in init block).
Like this:

for (int i = 0; i < tl.getChildCount(); i++) {
  CheckBox cb = (CheckBox)view.findViewById(i);
  cb.setChecked(true);
}

But as for me this is not very reliable because id set in runtime can be not unique and I think this loop is better:

for (int i = 0; i < tl.getChildCount(); i++) {
  CheckBox cb = (CheckBox)((TableRow)tl.getChildAt(i)).getChildAt(0);
  cb.setChecked(true);
}


问:
Error saving e-mail from outlook via Python win32com.client: Unable to write to file
I am trying to save mail via Python and get this error

-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Unable to write to file: C:\...\ docs. Right-click the folder containing the file you want to write to, and then select 'Properties' from the menu and check your permissions for this folder.'

Account has all the permissions and access to the folder.

答: Please show your code. Make sure you pass a fully qualified file name that includes both the path and the file name, not just a path or a file name.  It looks like you are only passing the path (C:\docs).


问:
Can't make function return value wait for fetched result - Now multithreaded
Previously I asked this question in a single threaded situation, and was given an answer that worked in that situation here.  But now I'm trying to answer the same question in a multithreaded environment.

I'm using OpenLayers to draw a UK Ordnance Survey map. I have working examples, but they use a less secure method of accessing the UKOS servers by giving a key in the URL, whereas I'd like to use the more secure OAuth2 arrangement instead. To this end, I already have a CGI script querying the servers to get a session token, and returning this as JSON. The problem can be solved in a single-threaded environment by making the map drawing page wait for its return, as follows:

```<code>UKOS.getToken = async function () {
  if (
    !UKOS.token ||
    new Date().getTime() >
      UKOS.token.issued_at + 1000 * (UKOS.token.expires_in - 15)
  )
    UKOS.token = await fetch(/* CGI Script */).then((response) =>
      response.json()
    );
  console.log(UKOS.token.access_token);
  return UKOS.token.access_token;
};
// ...
UKOS.getToken()
  .then(token => fetch(UKOS.WMTS + "&request=GetCapabilities&version=2.0.0", { headers: {Authorization: "Bearer " + token} }) )
  .then( /* etc */ )
</code>```

However, now that I'm using a multi-threaded environment the above no longer works, because after the first call to getToken() launches the fetching of the token, subsequent calls come crashing through before it can be returned, and, depending on exactly how I try to code getToken(), either launch multiple fetches of tokens when one will do (until it expires), or else don't wait for the token to be returned, and fail because it is still null.  This is my current attempted adaptation of getToken() ...

```<code>UKOS = {
    token:      null,
    tokStat:    0,
    tokProm:    null
    }
UKOS.getToken = async function() {
    var result;
    console.log( "UKOS.tokStat: " + UKOS.tokStat );
    switch( UKOS.tokStat ) {
        case 1: await UKOS.tokProm;
                await UKOS.token;
                // Deliberate fall through
                console.log( "UKOS.token: " + UKOS.token );
                console.log( "Falling through from 1 to 2 ..." );
        case 2: if( new Date().getTime() < UKOS.token.issued_at + 1000*(UKOS.token.expires_in - 15) ) {
                    result = UKOS.token.access_token;
                    break;
                    }
                // Deliberate fall through
                console.log( "Falling through from 2 to 0 ..." );
        case 0: UKOS.tokStat    = 1;
                UKOS.tokProm    = fetch( location.protocol + '//' + location.host + "/cgi-bin/OSDataOAuth.py" );
                UKOS.token      = await UKOS.tokProm.then( response => response.json() );
                UKOS.tokStat    = 2;
                result = UKOS.token.access_token;
        }
    return result;
    };
</code>```

Without the two 'await' qualifiers, of course subsequent calls just crash through into 'case 2' and fail because the token is still null, with them, this is the result [irrelevant detail edited out] ...

```<code>// Debugging console log message from routine calling getToken()
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=1&FORMAT=image%2Fpng
// Debugging console log message from getToken()
UKOS.tokStat: 0
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=5&TILECOL=1&FORMAT=image%2Fpng
UKOS.tokStat: 1
[Repeated multiple times]
url: undefined
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=1&FORMAT=image%2Fpng
[Repeated multiple times]
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=2&FORMAT=image%2Fpng
UKOS.tokStat: 1

// Token fetched successfully
// (see end, the only map tile fetch that succeeds is almost certainly the first to call getToken())
XHRGET http://local.localhost/cgi-bin/OSDataOAuth.py
[HTTP/1.1 200 OK 1590ms]

url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=5&TILECOL=2&FORMAT=image%2Fpng
UKOS.tokStat: 1
[Repeated multiple times]
UKOS.token: null
Falling through from 1 to 2 ...
[Repeated multiple times]
Falling through from 1 to 2 ...
Uncaught (in promise) TypeError: UKOS.token is null
    getToken http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:206
    setImgSrc http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:301
    initImage https://openlayers.org/api/2.13/OpenLayers.debug.js:29733
    renderTile https://openlayers.org/api/2.13/OpenLayers.debug.js:29608
    draw https://openlayers.org/api/2.13/OpenLayers.debug.js:29581
    initGriddedTiles https://openlayers.org/api/2.13/OpenLayers.debug.js:30951
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:30422
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:83261
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:9273
    setCenter https://openlayers.org/api/2.13/OpenLayers.debug.js:9035
    setBaseLayer http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:442
    addLayer https://openlayers.org/api/2.13/OpenLayers.debug.js:8354
    initOSMap http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:457
    onload http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:1
UKOSOpenLayers2.shtml:206:34
[Repeated multiple times]
// I think this one, the only one to successfully fetch a map tile is probably the first attempt to do so, which correctly waited for the returned token
XHRGET https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=Leisure_27700&STYLE=default&TILEMATRIXSET=EPSG:27700&TILEMATRIX=EPSG:27700:0&TILEROW=6&TILECOL=1&FORMAT=image/png
[HTTP/1.1 200 OK 1417ms]
dataUrl: blob:http://local.localhost/2f7fa455-3385-4d10-ab0e-b70999658137
</code>```

What is interesting about the above is that the two 'await's do appear to be accomplishing something, but not enough, because without them each ...

```<code>UKOS.tokStat: 1
</code>```

... is immediately followed by ...

```<code>UKOS.token: null
Falling through from 1 to 2 ...
</code>```

... yet they're obviously not waiting for the token to be returned, as evidenced by the fact that they all fail before the first call ultimately succeeds.  Can anyone suggest how to make the second and subsequent calls wait for the token requested by the first call?

答:
This is a working version of my original code with changes suggested by Quentin's approach, for which, although it was a little further away from working than I first thought, I remain deeply grateful, as it taught me how to approach the problem:</p>
```<code>UKOS.getToken = async function() {
    var result;
    console.log( "UKOS.tokStat: " + UKOS.tokStat );
    do
        switch( UKOS.tokStat ) {
            case 1: UKOS.token      = await UKOS.tokProm;
                    UKOS.tokStat    = 2;
                    // Deliberate fall through
                    console.log( "UKOS.token: " + UKOS.token );
                    console.log( "Falling through from 1 to 2 ..." );
            case 2: if( new Date().getTime() < UKOS.token.issued_at + 1000*(UKOS.token.expires_in - 15) )
                        {
                        result = UKOS.token.access_token;
                        break;
                        }
                    // Deliberate fall through
                    console.log( "Falling through from 2 to 0 ..." );
            case 0: UKOS.tokProm    = null;
                    UKOS.token      = null;
                    UKOS.tokStat    = 1;
                    // First call arrives here, but without 'await' in the
                    // the statement below it fails by returning null while
                    // later calls work.  However, if we put 'await' here,
                    // then the first call succeeds while later calls find
                    // UKOS.tokProm = null and so fail.  Therefore somehow
                    // we must process first and later calls the same, and
                    // this happens by the 'while' statement, which forces
                    // the first call back through the 'switch' statement.
                    UKOS.tokProm    = fetch( location.protocol + '//' + location.host + "/cgi-bin/OSDataOAuth.py" )
                                        .then( response => response.json() );
            }
    while( !UKOS.token )
    return result;
    };
</code>```

Body:
Previously I asked this question in a single threaded situation, and was given an answer that worked in that situation here.  But now I'm trying to answer the same question in a multithreaded environment.

I'm using OpenLayers to draw a UK Ordnance Survey map. I have working examples, but they use a less secure method of accessing the UKOS servers by giving a key in the URL, whereas I'd like to use the more secure OAuth2 arrangement instead. To this end, I already have a CGI script querying the servers to get a session token, and returning this as JSON. The problem can be solved in a single-threaded environment by making the map drawing page wait for its return, as follows:

UKOS.getToken = async function () {
  if (
    !UKOS.token ||
    new Date().getTime() >
      UKOS.token.issued_at + 1000 * (UKOS.token.expires_in - 15)
  )
    UKOS.token = await fetch(/* CGI Script */).then((response) =>
      response.json()
    );
  console.log(UKOS.token.access_token);
  return UKOS.token.access_token;
};
// ...
UKOS.getToken()
  .then(token => fetch(UKOS.WMTS + "&request=GetCapabilities&version=2.0.0", { headers: {Authorization: "Bearer " + token} }) )
  .then( /* etc */ )

However, now that I'm using a multi-threaded environment the above no longer works, because after the first call to getToken() launches the fetching of the token, subsequent calls come crashing through before it can be returned, and, depending on exactly how I try to code getToken(), either launch multiple fetches of tokens when one will do (until it expires), or else don't wait for the token to be returned, and fail because it is still null.  This is my current attempted adaptation of getToken() ...

UKOS = {
    token:      null,
    tokStat:    0,
    tokProm:    null
    }
UKOS.getToken = async function() {
    var result;
    console.log( "UKOS.tokStat: " + UKOS.tokStat );
    switch( UKOS.tokStat ) {
        case 1: await UKOS.tokProm;
                await UKOS.token;
                // Deliberate fall through
                console.log( "UKOS.token: " + UKOS.token );
                console.log( "Falling through from 1 to 2 ..." );
        case 2: if( new Date().getTime() < UKOS.token.issued_at + 1000*(UKOS.token.expires_in - 15) ) {
                    result = UKOS.token.access_token;
                    break;
                    }
                // Deliberate fall through
                console.log( "Falling through from 2 to 0 ..." );
        case 0: UKOS.tokStat    = 1;
                UKOS.tokProm    = fetch( location.protocol + '//' + location.host + "/cgi-bin/OSDataOAuth.py" );
                UKOS.token      = await UKOS.tokProm.then( response => response.json() );
                UKOS.tokStat    = 2;
                result = UKOS.token.access_token;
        }
    return result;
    };

Without the two 'await' qualifiers, of course subsequent calls just crash through into 'case 2' and fail because the token is still null, with them, this is the result [irrelevant detail edited out] ...

// Debugging console log message from routine calling getToken()
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=1&FORMAT=image%2Fpng
// Debugging console log message from getToken()
UKOS.tokStat: 0
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=5&TILECOL=1&FORMAT=image%2Fpng
UKOS.tokStat: 1
[Repeated multiple times]
url: undefined
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=1&FORMAT=image%2Fpng
[Repeated multiple times]
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=2&FORMAT=image%2Fpng
UKOS.tokStat: 1

// Token fetched successfully
// (see end, the only map tile fetch that succeeds is almost certainly the first to call getToken())
XHRGET http://local.localhost/cgi-bin/OSDataOAuth.py
[HTTP/1.1 200 OK 1590ms]

url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=5&TILECOL=2&FORMAT=image%2Fpng
UKOS.tokStat: 1
[Repeated multiple times]
UKOS.token: null
Falling through from 1 to 2 ...
[Repeated multiple times]
Falling through from 1 to 2 ...
Uncaught (in promise) TypeError: UKOS.token is null
    getToken http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:206
    setImgSrc http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:301
    initImage https://openlayers.org/api/2.13/OpenLayers.debug.js:29733
    renderTile https://openlayers.org/api/2.13/OpenLayers.debug.js:29608
    draw https://openlayers.org/api/2.13/OpenLayers.debug.js:29581
    initGriddedTiles https://openlayers.org/api/2.13/OpenLayers.debug.js:30951
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:30422
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:83261
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:9273
    setCenter https://openlayers.org/api/2.13/OpenLayers.debug.js:9035
    setBaseLayer http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:442
    addLayer https://openlayers.org/api/2.13/OpenLayers.debug.js:8354
    initOSMap http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:457
    onload http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:1
UKOSOpenLayers2.shtml:206:34
[Repeated multiple times]
// I think this one, the only one to successfully fetch a map tile is probably the first attempt to do so, which correctly waited for the returned token
XHRGET https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=Leisure_27700&STYLE=default&TILEMATRIXSET=EPSG:27700&TILEMATRIX=EPSG:27700:0&TILEROW=6&TILECOL=1&FORMAT=image/png
[HTTP/1.1 200 OK 1417ms]
dataUrl: blob:http://local.localhost/2f7fa455-3385-4d10-ab0e-b70999658137

What is interesting about the above is that the two 'await's do appear to be accomplishing something, but not enough, because without them each ...

UKOS.tokStat: 1

... is immediately followed by ...

UKOS.token: null
Falling through from 1 to 2 ...

... yet they're obviously not waiting for the token to be returned, as evidenced by the fact that they all fail before the first call ultimately succeeds.  Can anyone suggest how to make the second and subsequent calls wait for the token requested by the first call?

Body:
This is a working version of my original code with changes suggested by Quentin's approach, for which, although it was a little further away from working than I first thought, I remain deeply grateful, as it taught me how to approach the problem:

UKOS.getToken = async function() {
    var result;
    console.log( "UKOS.tokStat: " + UKOS.tokStat );
    do
        switch( UKOS.tokStat ) {
            case 1: UKOS.token      = await UKOS.tokProm;
                    UKOS.tokStat    = 2;
                    // Deliberate fall through
                    console.log( "UKOS.token: " + UKOS.token );
                    console.log( "Falling through from 1 to 2 ..." );
            case 2: if( new Date().getTime() < UKOS.token.issued_at + 1000*(UKOS.token.expires_in - 15) )
                        {
                        result = UKOS.token.access_token;
                        break;
                        }
                    // Deliberate fall through
                    console.log( "Falling through from 2 to 0 ..." );
            case 0: UKOS.tokProm    = null;
                    UKOS.token      = null;
                    UKOS.tokStat    = 1;
                    // First call arrives here, but without 'await' in the
                    // the statement below it fails by returning null while
                    // later calls work.  However, if we put 'await' here,
                    // then the first call succeeds while later calls find
                    // UKOS.tokProm = null and so fail.  Therefore somehow
                    // we must process first and later calls the same, and
                    // this happens by the 'while' statement, which forces
                    // the first call back through the 'switch' statement.
                    UKOS.tokProm    = fetch( location.protocol + '//' + location.host + "/cgi-bin/OSDataOAuth.py" )
                                        .then( response => response.json() );
            }
    while( !UKOS.token )
    return result;
    };


问:
Convert Date type that looks like this 1964-01-08 00:00:00 to just 1964-01-08
I'm using Mode Analytics.

I have a date that looks like this:
1964-01-08 00:00:00

When I use

select typeof(dob)

I get that it's a date type.

Desired Output:
1964-01-08

What I've tried:

DATE(date_parse(CAST(the_date as varchar), '%Y-%m%-%d %H:%i:%s.%f'))

Error: Invalid format: "1964-01-08" is too short

DATE(the_date)

Result: The same

I'm not sure what else to try - does anyone have a solution in mind?

答:
UPDATE: use
DATE_FORMAT(your_date_here, '%Y-%m-%d')</p>


问:
Unable to start Jupyter notebook on VS Code
(Using latest miniconda + VS Code on 64-bit Windows10:) After clean reinstalling VS Code, I can no longer launch jupyter notebook from within it. When I tried to create a new jupyter file for the first time, the Python extension installed ipykernel in my virtual environment "da38" (my main working environment). Then it stays on Connecting to IPython kernel: Connecting to kernel for an unusually long time, and stops with the error message Unable to start session for kernel Python 3.8.5 64-bit ('da38':conda) (images pasted below). I also removed and re-created da38 environment just in case. Used jupyter many times before with no issues until this new VS Code install today, and an identical setup is working on my other computer. Any help is appreciated. Thanks!

答:
I had this same problem. What worked for me is updating ipykernel.

```<code>$ pip install ipykernel --upgrade
</code>```

I also did a few other upgrades just in case.

```<code>$ pip install traitlets --upgrade
$ pip install notebook --upgrade
</code>```

I did not role back to an older version like 'traitlets==4.3.3'.

Body:
I had this same problem. What worked for me is updating ipykernel.

$ pip install ipykernel --upgrade

I also did a few other upgrades just in case.

$ pip install traitlets --upgrade
$ pip install notebook --upgrade

I did not role back to an older version like 'traitlets==4.3.3'.


问:
How to find results that do NOT match a keyword?
Is there any way I can user a NOT or other negation operator before a text search keyword for example,

```<code>NOT program
</code>```

When I do such a search there are 0 records returned.
Please let me know some way to achieve this option.

答:
In Solr you can use the '-' minus sign as a NOT operator, so you would change your query to be

```<code>*:* - program
</code>```

If you are using SolrNet, since that is how your question is tagged, you can do the following

```<code>solr.Query(new SolrQuery("*:*") && !new SolrQuery("program"));
</code>```

Please see Querying in SolrNet for more details.

Updated: Per comment from Mauricio Scheffer

Body:
Is there any way I can user a NOT or other negation operator before a text search keyword for example,

NOT program

When I do such a search there are 0 records returned.
Please let me know some way to achieve this option.

Body:
In Solr you can use the '-' minus sign as a NOT operator, so you would change your query to be

*:* - program

If you are using SolrNet, since that is how your question is tagged, you can do the following

solr.Query(new SolrQuery("*:*") && !new SolrQuery("program"));

Please see Querying in SolrNet for more details.

Updated: Per comment from Mauricio Scheffer


问:
Google Sheets Extracting Digits with Regex
I've been stuck on this for a while now. I want to extract only digits (numeric values) from the cell, but for some reason, it does not extract if it contains a single digit. See below for more details:

String
End Result

$8 - added to cart
8

Formula used: =REGEXEXTRACT(J92,"\d+.?\d+")

The formula would also grab digits that contain decimals. For some reason, this formula works if the string was "$81 - added to cart". Can someone help me fix this so it would work on strings with a single digit?

答:
This regular expression looks for one or more digits, maybe more things, and finally one or more digits.
There are several regex for what you are doing. I recommendend that you use the following:
"\d+(.\d+)?"</p>


问:
Got continuous is not supported error in RandomForestRegressor
I'm just trying to do a simple RandomForestRegressor example. But while testing the accuracy I get this error

```<code>/Users/noppanit/anaconda/lib/python2.7/site-packages/sklearn/metrics/classification.pyc
</code>```

in accuracy_score(y_true, y_pred, normalize, sample_weight)
          177
          178     # Compute accuracy for each possible representation
      --> 179     y_type, y_true, y_pred = _check_targets(y_true, y_pred)
          180     if y_type.startswith('multilabel'):
          181         differing_labels = count_nonzero(y_true - y_pred, axis=1)

```<code>/Users/noppanit/anaconda/lib/python2.7/site-packages/sklearn/metrics/classification.pyc
</code>```

in _check_targets(y_true, y_pred)
           90     if (y_type not in ["binary", "multiclass", "multilabel-indicator",
           91                        "multilabel-sequences"]):
      ---> 92         raise ValueError("{0} is not supported".format(y_type))
           93
           94     if y_type in ["binary", "multiclass"]:

```<code>ValueError: continuous is not supported
</code>```

This is the sample of the data. I can't show the real data.

```<code>target, func_1, func_2, func_2, ... func_200
float, float, float, float, ... float
</code>```

Here's my code.

```<code>import pandas as pd
import numpy as np
from sklearn.preprocessing import Imputer
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor, ExtraTreesRegressor, GradientBoostingRegressor
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
from sklearn import tree

train = pd.read_csv('data.txt', sep='\t')

labels = train.target
train.drop('target', axis=1, inplace=True)
cat = ['cat']
train_cat = pd.get_dummies(train[cat])

train.drop(train[cat], axis=1, inplace=True)
train = np.hstack((train, train_cat))

imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
imp.fit(train)
train = imp.transform(train)

x_train, x_test, y_train, y_test = train_test_split(train, labels.values, test_size = 0.2)

clf = RandomForestRegressor(n_estimators=10)

clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)
accuracy_score(y_test, y_pred) # This is where I get the error.
</code>```

答:
try
tree_clf.score(x_train, y_train)

you can't use a confusion matrix either

Body:
I'm just trying to do a simple RandomForestRegressor example. But while testing the accuracy I get this error

/Users/noppanit/anaconda/lib/python2.7/site-packages/sklearn/metrics/classification.pyc

in accuracy_score(y_true, y_pred, normalize, sample_weight)
          177
          178     # Compute accuracy for each possible representation
      --> 179     y_type, y_true, y_pred = _check_targets(y_true, y_pred)
          180     if y_type.startswith('multilabel'):
          181         differing_labels = count_nonzero(y_true - y_pred, axis=1)

/Users/noppanit/anaconda/lib/python2.7/site-packages/sklearn/metrics/classification.pyc

in _check_targets(y_true, y_pred)
           90     if (y_type not in ["binary", "multiclass", "multilabel-indicator",
           91                        "multilabel-sequences"]):
      ---> 92         raise ValueError("{0} is not supported".format(y_type))
           93
           94     if y_type in ["binary", "multiclass"]:

ValueError: continuous is not supported

This is the sample of the data. I can't show the real data.

target, func_1, func_2, func_2, ... func_200
float, float, float, float, ... float

Here's my code.

import pandas as pd
import numpy as np
from sklearn.preprocessing import Imputer
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor, ExtraTreesRegressor, GradientBoostingRegressor
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
from sklearn import tree

train = pd.read_csv('data.txt', sep='\t')

labels = train.target
train.drop('target', axis=1, inplace=True)
cat = ['cat']
train_cat = pd.get_dummies(train[cat])

train.drop(train[cat], axis=1, inplace=True)
train = np.hstack((train, train_cat))

imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
imp.fit(train)
train = imp.transform(train)

x_train, x_test, y_train, y_test = train_test_split(train, labels.values, test_size = 0.2)

clf = RandomForestRegressor(n_estimators=10)

clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)
accuracy_score(y_test, y_pred) # This is where I get the error.


问:
What does number of nodes mean in ns3 vanet simulation
I have to compare omnet++ and ns3 on basis of vehicular network simulations.

I have a question. In the example vanet-routing-compare.cc in ns3. What does the number of node means??
As i'm importing my own created mobility.tcl file which is obviously generated from Sumo. In omnet++/veins, the amount of vehicles injected per simulation time depends on sumo. However, in ns3, i'm doing it offline.

For example: if my mobility.tcl file looks like this....

```<code>$node_(0) set X_ 1617.74
$node_(0) set Y_ 1819.07
$node_(0) set Z_ 0
$ns_ at 0.0 "$node_(0) setdest 1617.74 1819.07 0.00"
$ns_ at 1.0 "$node_(0) setdest 1619.85 1817.75 2.49"
$node_(1) set X_ 1814.92
$node_(1) set Y_ 2144.86
$node_(1) set Z_ 0
$ns_ at 1.0 "$node_(1) setdest 1814.92 2144.86 0.00"
$ns_ at 2.0 "$node_(0) setdest 1623.52 1815.41 4.36"
$ns_ at 2.0 "$node_(1) setdest 1813.87 2143.14 2.01"
$node_(2) set X_ 1895.04
$node_(2) set Y_ 1319.59
$node_(2) set Z_ 0
$ns_ at 2.0 "$node_(2) setdest 1895.04 1319.59 0.00"
$ns_ at 3.0 "$node_(0) setdest 1629.32 1811.66 6.90"
$ns_ at 3.0 "$node_(1) setdest 1811.51 2139.26 4.54"
$ns_ at 3.0 "$node_(2) setdest 1895.89 1318.47 1.44"
$node_(3) set X_ 1892.25
$node_(3) set Y_ 2045.03
$node_(3) set Z_ 0
$ns_ at 3.0 "$node_(3) setdest 1892.25 2045.03 0.00"
$ns_ at 4.0 "$node_(0) setdest 1636.98 1806.71 9.12"
$ns_ at 4.0 "$node_(1) setdest 1808.22 2133.87 6.32"
$ns_ at 4.0 "$node_(2) setdest 1898.29 1316.5 3.12"
$ns_ at 4.0 "$node_(3) setdest 1893.54 2047.1 2.44"
$node_(4) set X_ 1572.19
$node_(4) set Y_ 997.05
$node_(4) set Z_ 0
$ns_ at 4.0 "$node_(4) setdest 1572.19 997.05 0.00"
$ns_ at 5.0 "$node_(0) setdest 1646.53 1800.55 11.36"
$ns_ at 5.0 "$node_(1) setdest 1804.62 2127.96 6.93"
$ns_ at 5.0 "$node_(2) setdest 1903.35 1315.4 5.20"
$ns_ at 5.0 "$node_(3) setdest 1895.68 2050.55 4.06"
$ns_ at 5.0 "$node_(4) setdest 1573.3 998.36 1.71"
$node_(5) set X_ 2650.52
$node_(5) set Y_ 1706.44
$node_(5) set Z_ 0
$ns_ at 5.0 "$node_(5) setdest 2650.52 1706.44 0.00"
$ns_ at 6.0 "$node_(0) setdest 1658.22 1793.0 13.91"
$ns_ at 6.0 "$node_(1) setdest 1800.76 2121.63 7.41"
$ns_ at 6.0 "$node_(2) setdest 1908.82 1319.34 6.98"
$ns_ at 6.0 "$node_(3) setdest 1899.01 2055.91 6.31"
$ns_ at 6.0 "$node_(4) setdest 1576.02 1001.6 4.24"
$ns_ at 6.0 "$node_(5) setdest 2649.84 1704.07 2.47"
$node_(6) set X_ 1794.89
$node_(6) set Y_ 1434.15
$node_(6) set Z_ 0
$ns_ at 6.0 "$node_(6) setdest 1794.89 1434.15 0.00"
$ns_ at 7.0 "$node_(0) setdest 1670.58 1785.02 14.72"
$ns_ at 7.0 "$node_(1) setdest 1796.82 2115.66 7.18"
$ns_ at 7.0 "$node_(2) setdest 1909.78 1326.39 7.30"
$ns_ at 7.0 "$node_(3) setdest 1903.13 2062.53 7.80"
$ns_ at 7.0 "$node_(4) setdest 1580.05 1006.39 6.26"
$ns_ at 7.0 "$node_(5) setdest 2648.73 1700.24 3.99"
$ns_ at 7.0 "$node_(6) setdest 1794.52 1431.93 2.25"
$node_(7) set X_ 2183.23
$node_(7) set Y_ 1481.54
$node_(7) set Z_ 0
$ns_ at 7.0 "$node_(7) setdest 2183.23 1481.54 0.00"
$ns_ at 8.0 "$node_(0) setdest 1681.82 1777.16 13.72"
$ns_ at 8.0 "$node_(1) setdest 1791.22 2110.52 7.61"
$ns_ at 8.0 "$node_(2) setdest 1905.57 1330.8 6.38"
$ns_ at 8.0 "$node_(3) setdest 1907.43 2069.46 8.15"
$ns_ at 8.0 "$node_(4) setdest 1584.74 1011.97 7.28"
$ns_ at 8.0 "$node_(5) setdest 2647.05 1694.43 6.04"
$ns_ at 8.0 "$node_(6) setdest 1793.84 1427.88 4.11"
$ns_ at 8.0 "$node_(7) setdest 2183.13 1483.64 2.11"
$node_(8) set X_ 2662.12
$node_(8) set Y_ 1746.51
$node_(8) set Z_ 0
$ns_ at 8.0 "$node_(8) setdest 2662.12 1746.51 0.00"
$ns_ at 9.0 "$node_(0) setdest 1693.08 1768.94 13.94"
$ns_ at 9.0 "$node_(1) setdest 1786.38 2106.09 6.56"
$ns_ at 9.0 "$node_(2) setdest 1897.99 1332.11 7.85"
$ns_ at 9.0 "$node_(3) setdest 1911.67 2076.28 8.04"
$ns_ at 9.0 "$node_(4) setdest 1589.62 1017.77 7.58"
$ns_ at 9.0 "$node_(5) setdest 2645.31 1688.4 6.28"
$ns_ at 9.0 "$node_(6) setdest 1792.72 1421.93 6.06"
$ns_ at 9.0 "$node_(7) setdest 2182.97 1487.17 3.53"
$ns_ at 9.0 "$node_(8) setdest 2661.59 1744.67 1.92"
$node_(9) set X_ 2657.83
$node_(9) set Y_ 1720.15
$node_(9) set Z_ 0
$ns_ at 9.0 "$node_(9) setdest 2657.83 1720.15 0.00"
$ns_ at 10.0 "$node_(0) setdest 1704.92 1760.29 14.67"
$ns_ at 10.0 "$node_(1) setdest 1781.22 2101.36 7.00"
$node_(10) set X_ 2445.07
$node_(10) set Y_ 2038.34
$node_(10) set Z_ 0
$ns_ at 10.0 "$node_(10) setdest 2445.07 2038.34 0.00"
$ns_ at 10.0 "$node_(2) setdest 1893.21 1336.25 6.37"
$ns_ at 10.0 "$node_(3) setdest 1916.25 2083.65 8.67"
$ns_ at 10.0 "$node_(4) setdest 1594.33 1023.36 7.32"
$ns_ at 10.0 "$node_(5) setdest 2643.69 1683.41 5.25"
$ns_ at 10.0 "$node_(6) setdest 1790.6 1413.54 8.65"
$ns_ at 10.0 "$node_(7) setdest 2182.7 1493.0 5.83"
$ns_ at 10.0 "$node_(8) setdest 2660.58 1741.17 3.64"
$ns_ at 10.0 "$node_(9) setdest 2658.31 1721.84 1.75"
</code>```

What would be the impact if i select number of nodes 5 or maybe 9??
and simulation time 10 seconds?

答:
From your question: In omnet++/veins, the amount of vehicles injected per simulation time depends on sumo.

Fact: the periodicity of vehicle injection can be customised in route file in case of veins simulation. Check erlangen.rou.xml file in veins project example.

Body:
I have to compare omnet++ and ns3 on basis of vehicular network simulations.

I have a question. In the example vanet-routing-compare.cc in ns3. What does the number of node means??
As i'm importing my own created mobility.tcl file which is obviously generated from Sumo. In omnet++/veins, the amount of vehicles injected per simulation time depends on sumo. However, in ns3, i'm doing it offline.

For example: if my mobility.tcl file looks like this....

$node_(0) set X_ 1617.74
$node_(0) set Y_ 1819.07
$node_(0) set Z_ 0
$ns_ at 0.0 "$node_(0) setdest 1617.74 1819.07 0.00"
$ns_ at 1.0 "$node_(0) setdest 1619.85 1817.75 2.49"
$node_(1) set X_ 1814.92
$node_(1) set Y_ 2144.86
$node_(1) set Z_ 0
$ns_ at 1.0 "$node_(1) setdest 1814.92 2144.86 0.00"
$ns_ at 2.0 "$node_(0) setdest 1623.52 1815.41 4.36"
$ns_ at 2.0 "$node_(1) setdest 1813.87 2143.14 2.01"
$node_(2) set X_ 1895.04
$node_(2) set Y_ 1319.59
$node_(2) set Z_ 0
$ns_ at 2.0 "$node_(2) setdest 1895.04 1319.59 0.00"
$ns_ at 3.0 "$node_(0) setdest 1629.32 1811.66 6.90"
$ns_ at 3.0 "$node_(1) setdest 1811.51 2139.26 4.54"
$ns_ at 3.0 "$node_(2) setdest 1895.89 1318.47 1.44"
$node_(3) set X_ 1892.25
$node_(3) set Y_ 2045.03
$node_(3) set Z_ 0
$ns_ at 3.0 "$node_(3) setdest 1892.25 2045.03 0.00"
$ns_ at 4.0 "$node_(0) setdest 1636.98 1806.71 9.12"
$ns_ at 4.0 "$node_(1) setdest 1808.22 2133.87 6.32"
$ns_ at 4.0 "$node_(2) setdest 1898.29 1316.5 3.12"
$ns_ at 4.0 "$node_(3) setdest 1893.54 2047.1 2.44"
$node_(4) set X_ 1572.19
$node_(4) set Y_ 997.05
$node_(4) set Z_ 0
$ns_ at 4.0 "$node_(4) setdest 1572.19 997.05 0.00"
$ns_ at 5.0 "$node_(0) setdest 1646.53 1800.55 11.36"
$ns_ at 5.0 "$node_(1) setdest 1804.62 2127.96 6.93"
$ns_ at 5.0 "$node_(2) setdest 1903.35 1315.4 5.20"
$ns_ at 5.0 "$node_(3) setdest 1895.68 2050.55 4.06"
$ns_ at 5.0 "$node_(4) setdest 1573.3 998.36 1.71"
$node_(5) set X_ 2650.52
$node_(5) set Y_ 1706.44
$node_(5) set Z_ 0
$ns_ at 5.0 "$node_(5) setdest 2650.52 1706.44 0.00"
$ns_ at 6.0 "$node_(0) setdest 1658.22 1793.0 13.91"
$ns_ at 6.0 "$node_(1) setdest 1800.76 2121.63 7.41"
$ns_ at 6.0 "$node_(2) setdest 1908.82 1319.34 6.98"
$ns_ at 6.0 "$node_(3) setdest 1899.01 2055.91 6.31"
$ns_ at 6.0 "$node_(4) setdest 1576.02 1001.6 4.24"
$ns_ at 6.0 "$node_(5) setdest 2649.84 1704.07 2.47"
$node_(6) set X_ 1794.89
$node_(6) set Y_ 1434.15
$node_(6) set Z_ 0
$ns_ at 6.0 "$node_(6) setdest 1794.89 1434.15 0.00"
$ns_ at 7.0 "$node_(0) setdest 1670.58 1785.02 14.72"
$ns_ at 7.0 "$node_(1) setdest 1796.82 2115.66 7.18"
$ns_ at 7.0 "$node_(2) setdest 1909.78 1326.39 7.30"
$ns_ at 7.0 "$node_(3) setdest 1903.13 2062.53 7.80"
$ns_ at 7.0 "$node_(4) setdest 1580.05 1006.39 6.26"
$ns_ at 7.0 "$node_(5) setdest 2648.73 1700.24 3.99"
$ns_ at 7.0 "$node_(6) setdest 1794.52 1431.93 2.25"
$node_(7) set X_ 2183.23
$node_(7) set Y_ 1481.54
$node_(7) set Z_ 0
$ns_ at 7.0 "$node_(7) setdest 2183.23 1481.54 0.00"
$ns_ at 8.0 "$node_(0) setdest 1681.82 1777.16 13.72"
$ns_ at 8.0 "$node_(1) setdest 1791.22 2110.52 7.61"
$ns_ at 8.0 "$node_(2) setdest 1905.57 1330.8 6.38"
$ns_ at 8.0 "$node_(3) setdest 1907.43 2069.46 8.15"
$ns_ at 8.0 "$node_(4) setdest 1584.74 1011.97 7.28"
$ns_ at 8.0 "$node_(5) setdest 2647.05 1694.43 6.04"
$ns_ at 8.0 "$node_(6) setdest 1793.84 1427.88 4.11"
$ns_ at 8.0 "$node_(7) setdest 2183.13 1483.64 2.11"
$node_(8) set X_ 2662.12
$node_(8) set Y_ 1746.51
$node_(8) set Z_ 0
$ns_ at 8.0 "$node_(8) setdest 2662.12 1746.51 0.00"
$ns_ at 9.0 "$node_(0) setdest 1693.08 1768.94 13.94"
$ns_ at 9.0 "$node_(1) setdest 1786.38 2106.09 6.56"
$ns_ at 9.0 "$node_(2) setdest 1897.99 1332.11 7.85"
$ns_ at 9.0 "$node_(3) setdest 1911.67 2076.28 8.04"
$ns_ at 9.0 "$node_(4) setdest 1589.62 1017.77 7.58"
$ns_ at 9.0 "$node_(5) setdest 2645.31 1688.4 6.28"
$ns_ at 9.0 "$node_(6) setdest 1792.72 1421.93 6.06"
$ns_ at 9.0 "$node_(7) setdest 2182.97 1487.17 3.53"
$ns_ at 9.0 "$node_(8) setdest 2661.59 1744.67 1.92"
$node_(9) set X_ 2657.83
$node_(9) set Y_ 1720.15
$node_(9) set Z_ 0
$ns_ at 9.0 "$node_(9) setdest 2657.83 1720.15 0.00"
$ns_ at 10.0 "$node_(0) setdest 1704.92 1760.29 14.67"
$ns_ at 10.0 "$node_(1) setdest 1781.22 2101.36 7.00"
$node_(10) set X_ 2445.07
$node_(10) set Y_ 2038.34
$node_(10) set Z_ 0
$ns_ at 10.0 "$node_(10) setdest 2445.07 2038.34 0.00"
$ns_ at 10.0 "$node_(2) setdest 1893.21 1336.25 6.37"
$ns_ at 10.0 "$node_(3) setdest 1916.25 2083.65 8.67"
$ns_ at 10.0 "$node_(4) setdest 1594.33 1023.36 7.32"
$ns_ at 10.0 "$node_(5) setdest 2643.69 1683.41 5.25"
$ns_ at 10.0 "$node_(6) setdest 1790.6 1413.54 8.65"
$ns_ at 10.0 "$node_(7) setdest 2182.7 1493.0 5.83"
$ns_ at 10.0 "$node_(8) setdest 2660.58 1741.17 3.64"
$ns_ at 10.0 "$node_(9) setdest 2658.31 1721.84 1.75"

What would be the impact if i select number of nodes 5 or maybe 9??
and simulation time 10 seconds?


问:
How to install websockets for Qt 6?
Already referred below old posts, but its solution of installing websockets didn't work in my Ubuntu 21.10.

Project ERROR: Unknown module(s) in QT: websockets

Project ERROR: Unknown module(s) in QT: webkitwidgets

This could be probably due to my Qt is 6.2, while the available library is from Qt5, viz. libqt5websockets5-dev.

How to install websocket module properly for the Qt6, to fix below error?

Project ERROR: Unknown module(s) in QT: websockets

答: When installing Qt via Qt Maintenance Tool, just go to Additional Libraries and check QtWebSockets. It is available in Qt 6.2.x versions.

Title: How to install websockets for Qt 6?


问:
How do I import a Postman HTTP POST into Azure Logic Apps HTTP action?
I have a HTTP POST set up in Postman that is working correctly. I also have an Azure Logic App that I need to invoke that HTTP POST instead of Postman. I see in Azure Logic Apps you can have an HTTP POST like so:

In Postman, it will give you the HTTP code snippet. I have tried different formats but I can't seem to get the POST to work like it does in Postman.

My Postman POST has authentication and form-data in the body which show up in the HTTP code snippet but when I paste that into the Body of the HTTP request in the logic app, the request fails.

Any ideas of what I'm doing wrong?

答:
There's no importer ready to use. You need to convert whatever you have on Postman into this connector.

You should add headers (Authorization and Content Type)

Authorization: Bearer ey1230218312 (replace with valid token)

Content-Type : application/x-www-form-urlencoded

Body: name=abc&age=30


问:
Duplicate Worksheet but keep values only in google sheets
I have a google sheets doc linked to another sheets document via IMPORTRANGE.

I wish to have a duplicate which mantains Values only without the link data, since i am lookin to update the data and make like monthly reports based on that.

Is there a way to duplicate the sheets via script or another function or either break the links but mantain the values?

答:
Make the copy and enable the IMPORTRANGE(s).

Then select the entire sheet by clicking the blank rectangle just above the left-hand row numbers and to the left of the top column letters. With the sheet selected, click Ctrl-C to copy to clipboard.

With the full-sheet selection still active, hit Ctrl-V for "Paste Special." Look for a clipboard icon to appear lower-right on the visible screen area. Click it and choose "Paste values only."


问:
How do I cycle through random fonts in Conky via LUA?
This question here seems to tangentially touch upon it but I cannot get it to work. Here is my LUA file:

```<code>function conky_myeval()
   local myTable = { " Old London :normal:size=7", "Ethnocentric :normal:size=7"}
   var1 = myTable[ math.random( #myTable)]
   return var1
end
</code>```

and the related conky part:

```<code>${font ${lua conky_myeval}} Hello World!
</code>```

Thank you for any assistance and I apologize if this has been asked before; The most similar I found I posted above.

答:
I've found it easier to have a lua script pass conky a string that can be parsed by a lua_parse object that then generates the intended object rather than trying to pass a value to the intended object.

In the case of random fonts, I'd do something like the following, which worked when tested.

Lua file:

```<code>function conky_myfont()
   local myTable = {"DejaVu Serif:normal:size=12", "MuseJazz Text:normal:size=12"}
   var1 = myTable[ math.random( #myTable)]
   return "${font "..var1.."}"
end
</code>```

Conky part:

```<code>${lua_parse conky_myfont}Hello World!${font}
</code>```

Body:
This question here seems to tangentially touch upon it but I cannot get it to work. Here is my LUA file:

function conky_myeval()
   local myTable = { " Old London :normal:size=7", "Ethnocentric :normal:size=7"}
   var1 = myTable[ math.random( #myTable)]
   return var1
end

and the related conky part:

${font ${lua conky_myeval}} Hello World!

Thank you for any assistance and I apologize if this has been asked before; The most similar I found I posted above.

Body:
I've found it easier to have a lua script pass conky a string that can be parsed by a lua_parse object that then generates the intended object rather than trying to pass a value to the intended object.

In the case of random fonts, I'd do something like the following, which worked when tested.

Lua file:

function conky_myfont()
   local myTable = {"DejaVu Serif:normal:size=12", "MuseJazz Text:normal:size=12"}
   var1 = myTable[ math.random( #myTable)]
   return "${font "..var1.."}"
end

Conky part:

${lua_parse conky_myfont}Hello World!${font}


问:
Return non-zero exit code when raising a scrapy.exceptions.UsageError exception
I have a Scrapy script which looks like this:

main.py

```<code>import os
import argparse
import datetime
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from spiders.mySpider import MySpider

parser = argparse.ArgumentParser(description='My Scrapper')
parser.add_argument('-v',
                    '--verbose',
                    help='Verbose mode',
                    action='store_true')
parser.add_argument('-t',
                    '--type',
                    help='Type',
                    type=str)

args = parser.parse_args()

if args.type != 'expected':
    parser.error("Wrong type")

if __name__ == "__main__":
    settings = get_project_settings()
    settings['LOG_ENABLED'] = args.verbose
    process = CrawlerProcess(settings=settings)
    process.crawl(MySpider, type_arg=args.type)
    process.start()
</code>```

mySpider.py

```<code>from scrapy import Spider
from scrapy.http import Request, FormRequest
import scrapy.exceptions as ScrapyExceptions

class MySpider(Spider):
    name = 'MyScrapper'
    allowed_domains = ['www.webtoscrape.com']
    start_urls = ['http://www.webtoscrape.com/path/to/page.html']

    def parse(self, response):
        # ...
        # Some logic
        # ...

        if condition:
            raise ScrapyExceptions.UsageError(reason="Wrong argument")
</code>```

When I raise a parser.error() on the main.py file, my process returns a non-zero exit code as expected. However, when I raise a scrapy.exceptions.UsageError() on the mySpider.py file, I receive a 0 exit code, so the Jenkins pipeline step I run my script on thinks it has succeded and continues with the pipeline execution. I run my script with a python3 main.py --type my_type command.

Why the script execution doesn't notice that the usage error raised on the mySpider.py module should return a non-zero exit code?

答:
After several hours of trying approaches I found this thread. The problem is that Scrapy does not use a non-zero exit code when a scrape fails. I managed to fix this behaviour by using the Crawler stats collection.

main.py

```<code>if __name__ == "__main__":
    settings = get_project_settings()
    settings['LOG_ENABLED'] = args.verbose
    process = CrawlerProcess(settings=settings)
    process.crawl(MySpider, type_arg=args.type)
    crawler = list(process.crawlers)[0]
    process.start()

    failed = crawler.stats.get_value('custom/failed_job')
    if failed:
        sys.exit(1)
</code>```

mySpider.py

```<code>class MySpider(Spider):
    name = 'MyScrapper'
    allowed_domains = ['www.webtoscrape.com']
    start_urls = ['http://www.webtoscrape.com/path/to/page.html']

    def parse(self, response):
        # ...
        # Some logic
        # ...

        if condition:
            self.crawler.stats.set_value('custom/failed_job', 'True')
            raise ScrapyExceptions.UsageError(reason="Wrong argument")
</code>```

Body:
I have a Scrapy script which looks like this:

main.py

import os
import argparse
import datetime
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from spiders.mySpider import MySpider

parser = argparse.ArgumentParser(description='My Scrapper')
parser.add_argument('-v',
                    '--verbose',
                    help='Verbose mode',
                    action='store_true')
parser.add_argument('-t',
                    '--type',
                    help='Type',
                    type=str)

args = parser.parse_args()

if args.type != 'expected':
    parser.error("Wrong type")

if __name__ == "__main__":
    settings = get_project_settings()
    settings['LOG_ENABLED'] = args.verbose
    process = CrawlerProcess(settings=settings)
    process.crawl(MySpider, type_arg=args.type)
    process.start()

mySpider.py

from scrapy import Spider
from scrapy.http import Request, FormRequest
import scrapy.exceptions as ScrapyExceptions

class MySpider(Spider):
    name = 'MyScrapper'
    allowed_domains = ['www.webtoscrape.com']
    start_urls = ['http://www.webtoscrape.com/path/to/page.html']

    def parse(self, response):
        # ...
        # Some logic
        # ...

        if condition:
            raise ScrapyExceptions.UsageError(reason="Wrong argument")

When I raise a parser.error() on the main.py file, my process returns a non-zero exit code as expected. However, when I raise a scrapy.exceptions.UsageError() on the mySpider.py file, I receive a 0 exit code, so the Jenkins pipeline step I run my script on thinks it has succeded and continues with the pipeline execution. I run my script with a python3 main.py --type my_type command.

Why the script execution doesn't notice that the usage error raised on the mySpider.py module should return a non-zero exit code?

Body:
After several hours of trying approaches I found this thread. The problem is that Scrapy does not use a non-zero exit code when a scrape fails. I managed to fix this behaviour by using the Crawler stats collection.

main.py

if __name__ == "__main__":
    settings = get_project_settings()
    settings['LOG_ENABLED'] = args.verbose
    process = CrawlerProcess(settings=settings)
    process.crawl(MySpider, type_arg=args.type)
    crawler = list(process.crawlers)[0]
    process.start()

    failed = crawler.stats.get_value('custom/failed_job')
    if failed:
        sys.exit(1)

mySpider.py

class MySpider(Spider):
    name = 'MyScrapper'
    allowed_domains = ['www.webtoscrape.com']
    start_urls = ['http://www.webtoscrape.com/path/to/page.html']

    def parse(self, response):
        # ...
        # Some logic
        # ...

        if condition:
            self.crawler.stats.set_value('custom/failed_job', 'True')
            raise ScrapyExceptions.UsageError(reason="Wrong argument")


问:
How to fix error with TypeScript interface?
I have a TypeScript question.

I set in state that either a certain interface or an empty object will get there. I take information for the component from this state. But this component swears that there cannot be an empty object in the state because of the interface. Tell me, please, how to configure so that TypeScript does not swear and the error disappears. Thanks!

```<code>const OneNews: FC<NewsObjectInterface> = ({image, title, createdAt, preview, description}) => {

    return (
        <>
            <Header/>
            <div className="single-blog one-news">
                <div className="single-blog-img">
                    <img src={image} alt={`Image for ${title}`}/>
                </div>
                <div className="blog-meta">
                 <span className="date-type">
                      <i className="bi bi-calendar"></i>{createdAt}
                 </span>
                </div>
                <div className="blog-text">
                    <h4>{title}</h4>
                    <p>{preview}</p>
                    <p>{description}</p>
                </div>
            </div>
            <Footer/>
        </>
    )
}

export default OneNews;

export interface NewsObjectInterface {
    createdAt: string,
    description: string,
    id: string,
    image: string,
    preview: string,
    title: string,
}

const [oneNewsData, setOneNewsData] = useState<NewsObjectInterface | {}>({});

<Route path="/one-news"
                   element={<OneNews title={oneNewsData.title} preview={oneNewsData.preview} image={oneNewsData.image} id={oneNewsData.id} createdAt={oneNewsData.createdAt} description={oneNewsData.description}/>}/>
        </Routes>
</code>```

答:
Change your interface like this (mind the ? symbol):

```<code>export interface NewsObjectInterface {
    createdAt?: string,
    description?: string,
    id?: string,
    image?: string,
    preview?: string,
    title?: string,
}
</code>```

This should be enough.

Body:
I have a TypeScript question.

I set in state that either a certain interface or an empty object will get there. I take information for the component from this state. But this component swears that there cannot be an empty object in the state because of the interface. Tell me, please, how to configure so that TypeScript does not swear and the error disappears. Thanks!

const OneNews: FC<NewsObjectInterface> = ({image, title, createdAt, preview, description}) => {

    return (
        <>

                    <img src={image} alt={`Image for ${title}`}/>

                      {createdAt}

{title}

{preview}

{description}

        </>
    )
}

export default OneNews;

export interface NewsObjectInterface {
    createdAt: string,
    description: string,
    id: string,
    image: string,
    preview: string,
    title: string,
}

const [oneNewsData, setOneNewsData] = useState<NewsObjectInterface | {}>({});

<Route path="/one-news"
                   element={<OneNews title={oneNewsData.title} preview={oneNewsData.preview} image={oneNewsData.image} id={oneNewsData.id} createdAt={oneNewsData.createdAt} description={oneNewsData.description}/>}/>
        </Routes>

Body:
Change your interface like this (mind the ? symbol):

export interface NewsObjectInterface {
    createdAt?: string,
    description?: string,
    id?: string,
    image?: string,
    preview?: string,
    title?: string,
}

This should be enough.


问:
VSCODE - How to select python version thought remote ssh?
How can I execute python 3.9 using remote ssh through vscode?

When I connect to the server, it only run as 2.6

My code:

```<code>from platform import python_version

print("Current Python Version-", python_version())
</code>```

output:

```<code>[Running] python -u "/root/python/projetos.py"
('Current Python Version-', '2.6.6')
</code>```

Is there any way to select the python version through vscode? I've tried to change at Linux level (using alternative command), but don't work.

What I need is vscode to call python3.9 command instead of python command :

```<code>[root@quickstart ~]# python --version
Python 2.6.6
[root@quickstart ~]# python3.9 --version
Python 3.9.10
[root@quickstart ~]#
</code>```

答:
I've find out.

Need to install python vscode extension on remote ssh server.

When connected to the SSH Server, in extensions (Ctrl + shift + x), look for python and so, install in SSH:

After install, type Ctrl + shift + p and look for Python: select interpreter.

And here will show all python interpreters paths installed on the server.

Body:
How can I execute python 3.9 using remote ssh through vscode?

When I connect to the server, it only run as 2.6

My code:

from platform import python_version

print("Current Python Version-", python_version())

output:

[Running] python -u "/root/python/projetos.py"
('Current Python Version-', '2.6.6')

Is there any way to select the python version through vscode? I've tried to change at Linux level (using alternative command), but don't work.

What I need is vscode to call python3.9 command instead of python command :

[root@quickstart ~]# python --version
Python 2.6.6
[root@quickstart ~]# python3.9 --version
Python 3.9.10
[root@quickstart ~]#


答:
You have declared your state to be of type:

```<code>NewsObjectInterface | {}
</code>```

Which means you either have an object full of your expected properties, or you have an empty object. And when you do oneNewsData.title Typescript enforces that both sides of that union must have that property. And an empty object has no properties.

It seems like you need a temporary value while the real value loads. In this case I would recommend you change the type of your state to:

```<code>useState<NewsObjectInterface | null>(null);
</code>```

Now the default value is null. Something else may set a NewsObjectInterface in state later.

And then you simply check for null before you use the state value:

```<code><Route path="/one-news"
  element={
    oneNewsData && <OneNews // check oneNewsData before use
      title={oneNewsData.title}
      preview={oneNewsData.preview}
      image={oneNewsData.image}
      id={oneNewsData.id}
      createdAt={oneNewsData.createdAt}
      description={oneNewsData.description}
    />
  }
/>
</code>```

Title: How to fix error with TypeScript interface?

Body:
You have declared your state to be of type:

NewsObjectInterface | {}

Which means you either have an object full of your expected properties, or you have an empty object. And when you do oneNewsData.title Typescript enforces that both sides of that union must have that property. And an empty object has no properties.

It seems like you need a temporary value while the real value loads. In this case I would recommend you change the type of your state to:

useState<NewsObjectInterface | null>(null);

Now the default value is null. Something else may set a NewsObjectInterface in state later.

And then you simply check for null before you use the state value:

<Route path="/one-news"
  element={
    oneNewsData && <OneNews // check oneNewsData before use
      title={oneNewsData.title}
      preview={oneNewsData.preview}
      image={oneNewsData.image}
      id={oneNewsData.id}
      createdAt={oneNewsData.createdAt}
      description={oneNewsData.description}
    />
  }
/>


问:
How can I replace comma instead of some phrases?
I have a string of characters that starts with a space and has \r\n,I want to delete the first space and delete \r\n then replace it with a comma after the word if there is a space?

My String : "\r\n                        ram\r\ncomputer\r\n" ....

I want the following mode to change? laptop,computer,ram

答:
Use Trim() to remove the space at the beginning (and/or end) and then Replace() to replace the space between words with commas.

https://learn.microsoft.com/en-us/dotnet/api/system.string.trim?view=net-6.0

https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=net-6.0

```<code>string myString = " laptop computer ram";
string newString = myString.Trim().Replace(' ', ',');
</code>```

Body:
Use Trim() to remove the space at the beginning (and/or end) and then Replace() to replace the space between words with commas.

https://learn.microsoft.com/en-us/dotnet/api/system.string.trim?view=net-6.0

https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=net-6.0

string myString = " laptop computer ram";
string newString = myString.Trim().Replace(' ', ',');


问:
Cannot Install Microsoft.Extenstions.Logging Nuget Package, on .Net Framework 4.6, Visual Studio 2015
I am trying to install the Nuget package: Microsoft.Extenstions.Logging, on my ASP.Net MVC 5 projecton, .Net 4.6, Visual Studio 2015, and keep getting this error:

Attempting to gather dependency information for package
  'Microsoft.Extensions.Configuration.2.0.0' with respect to project
  'ProjectName.web', targeting '.NETFramework,Version=v4.6.1' Gathering
  dependency information took 271.03 ms Attempting to resolve
  dependencies for package 'Microsoft.Extensions.Configuration.2.0.0'
  with DependencyBehavior 'Lowest' Resolving dependency information took
  0 ms Resolving actions to install package
  'Microsoft.Extensions.Configuration.2.0.0' Resolved actions to install
  package 'Microsoft.Extensions.Configuration.2.0.0' Retrieving package
  'Microsoft.Extensions.Configuration 2.0.0' from 'nuget.org'.   GET
  https://api.nuget.org/v3-flatcontainer/microsoft.extensions.configuration/2.0.0/microsoft.extensions.configuration.2.0.0.nupkg
  OK
  https://api.nuget.org/v3-flatcontainer/microsoft.extensions.configuration/2.0.0/microsoft.extensions.configuration.2.0.0.nupkg
  259ms Installing Microsoft.Extensions.Configuration 2.0.0. Install
  failed. Rolling back... Package
  'Microsoft.Extensions.Configuration.2.0.0' does not exist in project
  'ProjectName.web' Package 'Microsoft.Extensions.Configuration.2.0.0' does
  not exist in folder 'C:\Git\ProjectName\packages' Executing nuget actions
  took 1.27 sec Could not install package
  'Microsoft.Extensions.Configuration 2.0.0'. You are trying to install
  this package into a project that targets
  '.NETFramework,Version=v4.6.1', but the package does not contain any
  assembly references or content files that are compatible with that
  framework. For more information, contact the package author.
  ========== Finished ========== Time Elapsed: 00:00:05.6980685

Here is another link to this problem, on Github: issue

But does not provide any solution/workaround to fix this...

答:
I used this approach and it worked for me!

While in Visual Studio, Navigate to Tools > NuGet Package Manager > Package Manager Settings > General

Click on "Clear All NuGet Cache(s)"

Wait for process to complete and click Ok

Now retry installation of packages, should work ok :)


问:
select * only return one value
I want select multiple (all) values from table Account.

```<code>string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();
</code>```

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

答: The line reader.Read() will get the next row, so you can use while(reader.Read()) to iterate over the rows.

Title: select * only return one value

Body:
I want select multiple (all) values from table Account.

string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.


问:
Destructuring/list assignment with the `has` declarator
[I ran into the issues that prompted this question and my previous question at the same time, but decided the two questions deserve to be separate.]

The docs describe using destructuring assignment with my and our variables, but don't mention whether it can be used with has variables.  But Raku is consistent enough that I decided to try, and it appears to work:

```<code>class C { has $.a; has $.b }
class D { has ($.a, $.b) }
C.new: :a<foo>;  # OUTPUT: «C.new(a => "foo", b => Any)»
D.new: :a<foo>;  # OUTPUT: «D.new(a => "foo", b => Any)»
</code>```

However, this form seems to break attribute defaults:

```<code>class C { has $.a; has $.b = 42 }
class D { has ($.a, $.b = 42) }
C.new: :a<foo>;  # OUTPUT: «C.new(a => "foo", b => 42)»
D.new: :a<foo>;  # OUTPUT: «C.new(a => "foo", b => Any)»
</code>```

Additionally, flipping the position of the default provides an error message that might provide some insight into what is going on (though not enough for me to understand if the above behavior is correct).

```<code>class D { has ($.a = 42, $.b) }
# OUTPUT:
===SORRY!=== Error while compiling:
Cannot put required parameter $.b after optional parameters
</code>```

So, a few questions: is destructuring assignment even supposed to work with has?  If so, is the behavior with default values correct/is there a way to assign default values when using destucturing assignment?

(I really hope that destructuring assignment is supported with has and can be made to work with default values; even though it might seem like a niche feature for someone using classes for true OO, it's very handy for someone writing more functional code who wants to use a class as a slightly-more-typesafe Hash with fixed keys.  Being able to write things like class User { has (Str $.first-name, Str $.last-name, Int $.age) } is very helpful for that sort of code)

答:
This is currently a known bug in Rakudo.  The intended behavior is for has to support list assignment, which would make syntax very much like that shown in the question work.

I am not sure if the supported syntax will be:

class D { has ($.a, $.b = 42) }
D.new: :a<foo>;  # OUTPUT: «D.new(a => "foo", b => 42)»
```
<p>or</p>
<pre class="lang-raku prettyprint-override"><code>class D { has ($.a, $.b) = (Any, 42) }
D.new: :a<foo>;  # OUTPUT: «D.new(a => "foo", b => 42)»
</code>```

but, either way, there will be a way to use a single has to declare multiple attributes while also providing default values for those attributes.

The current expectation is that this bug will get resolved sometime after the RakuAST branch is merged.

Body:
[I ran into the issues that prompted this question and my previous question at the same time, but decided the two questions deserve to be separate.]

The docs describe using destructuring assignment with my and our variables, but don't mention whether it can be used with has variables.  But Raku is consistent enough that I decided to try, and it appears to work:

class C { has $.a; has $.b }
class D { has ($.a, $.b) }
C.new: :a<foo>;  # OUTPUT: «C.new(a => "foo", b => Any)»
D.new: :a<foo>;  # OUTPUT: «D.new(a => "foo", b => Any)»

However, this form seems to break attribute defaults:

class C { has $.a; has $.b = 42 }
class D { has ($.a, $.b = 42) }
C.new: :a<foo>;  # OUTPUT: «C.new(a => "foo", b => 42)»
D.new: :a<foo>;  # OUTPUT: «C.new(a => "foo", b => Any)»

Additionally, flipping the position of the default provides an error message that might provide some insight into what is going on (though not enough for me to understand if the above behavior is correct).

class D { has ($.a = 42, $.b) }
# OUTPUT:
===SORRY!=== Error while compiling:
Cannot put required parameter $.b after optional parameters

So, a few questions: is destructuring assignment even supposed to work with has?  If so, is the behavior with default values correct/is there a way to assign default values when using destucturing assignment?

(I really hope that destructuring assignment is supported with has and can be made to work with default values; even though it might seem like a niche feature for someone using classes for true OO, it's very handy for someone writing more functional code who wants to use a class as a slightly-more-typesafe Hash with fixed keys.  Being able to write things like class User { has (Str $.first-name, Str $.last-name, Int $.age) } is very helpful for that sort of code)

Body:
This is currently a known bug in Rakudo.  The intended behavior is for has to support list assignment, which would make syntax very much like that shown in the question work.

I am not sure if the supported syntax will be:

class D { has ($.a, $.b = 42) }
D.new: :a<foo>;  # OUTPUT: «D.new(a => "foo", b => 42)»

or

class D { has ($.a, $.b) = (Any, 42) }
D.new: :a<foo>;  # OUTPUT: «D.new(a => "foo", b => 42)»

but, either way, there will be a way to use a single has to declare multiple attributes while also providing default values for those attributes.

The current expectation is that this bug will get resolved sometime after the RakuAST branch is merged.


问:
Qlikview - show first and last selected value in list
I need to display first and last selected value in list. I have listbox and when I pick date I got this result in list

I want to get in one box min value selected but when I use minString(Data) I got 22/2022 instead 303/202. And for max I need to get 306/2022.

Can anyone help please?

答:
To get the Qlik engine to ignore the selected values you need to set analysis.

Firstly, you should be using a max() not a maxstring(). Max() will evaluate the maximum numerical value. Maxstring() will evaluate the maximum ascii values of the string (I think, anyone can correct me).

Secondly, the value 306/2022 in that list is grey which means it is no longer included in the dataset used for the visualisations being displayed. The white values are the values that are included, this is why min(Date) is returing 22/2022. 22/2022 is the minimum available (white) value in that list. 303/2022 is the minimum value of the excluded values in grey.

If you want to be able to reference the values even when the selections have caused it to be excluded (turned them grey) you need to modify your max() to max({1}).

{1} means look at all the data not just the selected data.

```<code>max({1} Date)
</code>```

will return 306/2022 no matter what the selections are.

If you want to return 303/2022. The minimum of the excluded values and have that change dynamically when making other selections let me know and I can show you but I will require you to explain why you would want to that before I try figure it out :)

Body:
To get the Qlik engine to ignore the selected values you need to set analysis.

Firstly, you should be using a max() not a maxstring(). Max() will evaluate the maximum numerical value. Maxstring() will evaluate the maximum ascii values of the string (I think, anyone can correct me).

Secondly, the value 306/2022 in that list is grey which means it is no longer included in the dataset used for the visualisations being displayed. The white values are the values that are included, this is why min(Date) is returing 22/2022. 22/2022 is the minimum available (white) value in that list. 303/2022 is the minimum value of the excluded values in grey.

If you want to be able to reference the values even when the selections have caused it to be excluded (turned them grey) you need to modify your max() to max({1}).

{1} means look at all the data not just the selected data.

max({1} Date)

will return 306/2022 no matter what the selections are.

If you want to return 303/2022. The minimum of the excluded values and have that change dynamically when making other selections let me know and I can show you but I will require you to explain why you would want to that before I try figure it out :)


问:
how to download large files without memory issues in java
When I am trying to download a large file which is of 260MB from server, I get this error: java.lang.OutOfMemoryError: Java heap space. I am sure my heap size is less than 252MB. Is there any way I can download large files without increasing heap size?

How I can download large files without getting this issue? My code is given below:

```<code>String path= "C:/temp.zip";
response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
byte[] buf = new byte[1024];
try {

             File file = new File(path);
             long length = file.length();
             BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
             ServletOutputStream out = response.getOutputStream();

             while ((in != null) && ((length = in.read(buf)) != -1)) {
             out.write(buf, 0, (int) length);
             }
             in.close();
             out.close();
</code>```

答: There's nothing wrong (in regard to memory usage) with the code you're show. Either the servlet container is configured to buffer the entire response (look at the web.xml configuration), or the memory is being leaked elsewhere.

Body:
When I am trying to download a large file which is of 260MB from server, I get this error: java.lang.OutOfMemoryError: Java heap space. I am sure my heap size is less than 252MB. Is there any way I can download large files without increasing heap size?

How I can download large files without getting this issue? My code is given below:

String path= "C:/temp.zip";
response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
byte[] buf = new byte[1024];
try {

             File file = new File(path);
             long length = file.length();
             BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
             ServletOutputStream out = response.getOutputStream();

             while ((in != null) && ((length = in.read(buf)) != -1)) {
             out.write(buf, 0, (int) length);
             }
             in.close();
             out.close();


问:
Trying to bind a complex file name in a DBI insert place holder, but special characters get mangled
Guys I don't know if this is a bind problem, character set problem or something I haven't considered. Here's the challenge - the file system was written by some cd ripping software but the problem is more generic, I need to be able to insert any legal filename from a Linux OS into a database, this set of titles is just a test case.

I tied to make this as clear as I could:

    find(\&process, $_);< populates @fnames with File::Find:name
    my $count = scalar @fnames;
    print "File count $count\n";
```
<p>So I use File:Find to fill the array with the file name strings, some are really problematic..</p>
```    $stm = $dbh_sms->prepare(qq{
    INSERT INTO $table (path) VALUES (?)
    });
    foreach $fname(@fnames){
    print "File:$fname\n";
    $stm->execute("$fname");
    }
```
<p>Now here's what I see printed, compared to what comes back out of MariaDb, just a few examples showing the problem:</p>
<p>File:/test1/music/THE DOOBIE BROTHERS - BEST OF THE DOOBIES/02 - THE DOOBIE BROTHERS - LONG TRAIN RUNNIN´.mp3</p>
<p>A bunch of these titles have the back ticks, they are problem #1 - here's how they come back out of a select against the table after I populate it:</p>
<p>| /test1/music/THE DOOBIE BROTHERS - BEST OF THE DOOBIES/02 - THE DOOBIE BROTHERS - LONG TRAIN RUNNINÂ´.mp3</p>
<p>This character is also a problem:</p>
<p>File:/test1/music/Blue Öyster Cult - Workshop Of The Telescopes/01 - Blue Öyster Cult - Don't Fear The Reaper.mp3</p>
<p>From the database:</p>
<p>/test1/music/Blue Ãyster Cult - Workshop Of The Telescopes/01 - Blue Ãyster Cult - Don't Fear The Reaper.mp3</p>
<p>And one more, but far from the last of the problematic strings:</p>
<p>File:/test1/music/Better Than Ezra - Deluxe/03 - Better Than Ezra - Southern Gürl.mp3</p>
<p>Comes out as:</p>
<p>/test1/music/Better Than Ezra - Deluxe/03 - Better Than Ezra - Southern GÃ¼rl.mp3</p>
<p>I though this was a character set problem, so I added this to the connect string:</p>
```    { RaiseError => 1, mysql_enable_utf8mb4 => 1 }
```
<p>I've also tried:</p>
```    $dbh_sms->do('SET NAMES utf8mb4');
```

Is that a hex C2 being added to the string? (Edit: it's an octal 303, hex c3) I've also tried changing the column to varbinary and still see the same results. Anyone have a clue why this is happening? I'm at a loss....

TIA

Edit - I dumped the table with OD to find out what is actually getting inserted since I was of the belief that with a placeholder, a bind variable would be written without interpolation, basically a binary transfer. To save my eyes, I just did a handful of records concentrating on what I thought was a 'back tick' from the above example, which is an octal 264, AKA "Acute accent - spacing acute".

It is in the table, but preceded by 303 202 and 302, which are a couple of those 'A' characters with the icing on top and a "low quote" character in between. Which contradicts my prior understanding about the utility of place holders and bind variables.

So I am more confused now than before.

答:
I found the problem, it was in the perl character encoding:

```<code>    $fname = decode("UTF-8", $fname);
</code>```

was all I needed.

Body:
Guys I don't know if this is a bind problem, character set problem or something I haven't considered. Here's the challenge - the file system was written by some cd ripping software but the problem is more generic, I need to be able to insert any legal filename from a Linux OS into a database, this set of titles is just a test case.

I tied to make this as clear as I could:

    find(\&process, $_);< populates @fnames with File::Find:name
    my $count = scalar @fnames;
    print "File count $count\n";

So I use File:Find to fill the array with the file name strings, some are really problematic..

    $stm = $dbh_sms->prepare(qq{
    INSERT INTO $table (path) VALUES (?)
    });
    foreach $fname(@fnames){
    print "File:$fname\n";
    $stm->execute("$fname");
    }

Now here's what I see printed, compared to what comes back out of MariaDb, just a few examples showing the problem:

File:/test1/music/THE DOOBIE BROTHERS - BEST OF THE DOOBIES/02 - THE DOOBIE BROTHERS - LONG TRAIN RUNNIN´.mp3

A bunch of these titles have the back ticks, they are problem #1 - here's how they come back out of a select against the table after I populate it:

| /test1/music/THE DOOBIE BROTHERS - BEST OF THE DOOBIES/02 - THE DOOBIE BROTHERS - LONG TRAIN RUNNINÂ´.mp3

This character is also a problem:

File:/test1/music/Blue Öyster Cult - Workshop Of The Telescopes/01 - Blue Öyster Cult - Don't Fear The Reaper.mp3

From the database:

/test1/music/Blue Ãyster Cult - Workshop Of The Telescopes/01 - Blue Ãyster Cult - Don't Fear The Reaper.mp3

And one more, but far from the last of the problematic strings:

File:/test1/music/Better Than Ezra - Deluxe/03 - Better Than Ezra - Southern Gürl.mp3

Comes out as:

/test1/music/Better Than Ezra - Deluxe/03 - Better Than Ezra - Southern GÃ¼rl.mp3

I though this was a character set problem, so I added this to the connect string:

    { RaiseError => 1, mysql_enable_utf8mb4 => 1 }

I've also tried:

    $dbh_sms->do('SET NAMES utf8mb4');

Is that a hex C2 being added to the string? (Edit: it's an octal 303, hex c3) I've also tried changing the column to varbinary and still see the same results. Anyone have a clue why this is happening? I'm at a loss....

TIA

Edit - I dumped the table with OD to find out what is actually getting inserted since I was of the belief that with a placeholder, a bind variable would be written without interpolation, basically a binary transfer. To save my eyes, I just did a handful of records concentrating on what I thought was a 'back tick' from the above example, which is an octal 264, AKA "Acute accent - spacing acute".

It is in the table, but preceded by 303 202 and 302, which are a couple of those 'A' characters with the icing on top and a "low quote" character in between. Which contradicts my prior understanding about the utility of place holders and bind variables.

So I am more confused now than before.

Body:
I found the problem, it was in the perl character encoding:

    $fname = decode("UTF-8", $fname);

was all I needed.


问:
Flutter: How to catch "Scheme not starting with alphabetic character (at character 1)"
I have a text field where I can paste text. I  use this to paste URL's from the internet.
If I accidentally paste a large chunk of code from my clipboard instead of normal text or URL's, it gives me the following error:
Scheme not starting with alphabetic character (at character 1).

How can I catch this error so that the user has a good experience?

[EDIT]

There is a button with a clipboard icon that the user can tap. Here is where the error happens once this button is tapped by the user:

```<code>onTap: () async {
    if (linkTextController.text.trim() == "") {
        try {
            ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
            linkTextController.text = data!.text.toString();
        } catch (error) {
            print(error);
        }
    } else {
        linkTextController.text = "";
    }
    setState(() {});
},
</code>```

答:
Try handling the onChanged event of the TextField using official document - Handle changes to a text field

UPDATE

You might want to use hasStrings() first, given here, because the official documentation for ClipboardData class clearly states that:<br /

The system clipboard can contain data of various media types. This data structure currently supports only plain text data, in the text property.

Body:
I have a text field where I can paste text. I  use this to paste URL's from the internet.
If I accidentally paste a large chunk of code from my clipboard instead of normal text or URL's, it gives me the following error:
Scheme not starting with alphabetic character (at character 1).

How can I catch this error so that the user has a good experience?

[EDIT]

There is a button with a clipboard icon that the user can tap. Here is where the error happens once this button is tapped by the user:

onTap: () async {
    if (linkTextController.text.trim() == "") {
        try {
            ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
            linkTextController.text = data!.text.toString();
        } catch (error) {
            print(error);
        }
    } else {
        linkTextController.text = "";
    }
    setState(() {});
},


问:
SwiftUI: Combining Custom Text
With the SwiftUI built-in Text we are able to concatenate multiple Text views if we want to create a rich Text

like this:

```<code>Text("hello").foregroundColor(.white) + Text("world").foregroundColor(.pink)
</code>```

However, if I have a custom Text:

```<code>struct MyText: View {

  let label: String

  var body: some View {
      Text(self.label)
         .foregroundColor(.myAppColor)
  }
}
</code>```

and then combine:

```<code>MyText(label: "hello") + MyText(label: "world")
</code>```

the compiler outputs the following error:

```<code>Referencing operator function '+' on 'FloatingPoint' requires that 'MyText' conform to 'FloatingPoint'
</code>```

I tried casting MyText to Text but the compiler doesn't like that either.

How do I go about achieving this in a slick manner?

答:
This is a custom feature of Text, you can, however, mimick some of the behaviour. See the following example:

```<code>import SwiftUI

struct MyText: View {

    private let configurations: [Configuration]

    init(_ title: String, foregroundColor: Color = .black) {
        self.configurations = [
            .init(title: title,
                  foregroundColor: foregroundColor)
        ]
    }

    private init(configurations: [Configuration]) {
        self.configurations = configurations
    }

    private struct Configuration: Identifiable {
        let id = UUID()
        let title: String
        let foregroundColor: Color
    }

    var body: some View {
        HStack {
            ForEach(configurations, content: Render.init)
        }
    }

    static func + (lhs: Self, rhs: Self) -> Self {
        let configurations = lhs.configurations + rhs.configurations
        return MyText(configurations: configurations)
    }

    private struct Render: View {
        let configuration: Configuration
        var body: some View {
            Text(configuration.title)
                .foregroundColor(configuration.foregroundColor)
        }
    }
}

struct MyText_Previews: PreviewProvider {
    static var previews: some View {
        MyText("hej") + MyText("Yo", foregroundColor: .red)
    }
}
</code>```

This is much more a proof of concept, than an advice to do this practice however.

Title: SwiftUI: Combining Custom Text

Body:
With the SwiftUI built-in Text we are able to concatenate multiple Text views if we want to create a rich Text

like this:

Text("hello").foregroundColor(.white) + Text("world").foregroundColor(.pink)

However, if I have a custom Text:

struct MyText: View {

  let label: String

  var body: some View {
      Text(self.label)
         .foregroundColor(.myAppColor)
  }
}

and then combine:

MyText(label: "hello") + MyText(label: "world")

the compiler outputs the following error:

Referencing operator function '+' on 'FloatingPoint' requires that 'MyText' conform to 'FloatingPoint'

I tried casting MyText to Text but the compiler doesn't like that either.

How do I go about achieving this in a slick manner?

Body:
This is a custom feature of Text, you can, however, mimick some of the behaviour. See the following example:

import SwiftUI

struct MyText: View {

    private let configurations: [Configuration]

    init(_ title: String, foregroundColor: Color = .black) {
        self.configurations = [
            .init(title: title,
                  foregroundColor: foregroundColor)
        ]
    }

    private init(configurations: [Configuration]) {
        self.configurations = configurations
    }

    private struct Configuration: Identifiable {
        let id = UUID()
        let title: String
        let foregroundColor: Color
    }

    var body: some View {
        HStack {
            ForEach(configurations, content: Render.init)
        }
    }

    static func + (lhs: Self, rhs: Self) -> Self {
        let configurations = lhs.configurations + rhs.configurations
        return MyText(configurations: configurations)
    }

    private struct Render: View {
        let configuration: Configuration
        var body: some View {
            Text(configuration.title)
                .foregroundColor(configuration.foregroundColor)
        }
    }
}

struct MyText_Previews: PreviewProvider {
    static var previews: some View {
        MyText("hej") + MyText("Yo", foregroundColor: .red)
    }
}

This is much more a proof of concept, than an advice to do this practice however.