问:
Trying to filter a JSON in order to retrieve the parent based on characteristics of the children
Based on the bellow JSON im trying to extract the "DrugReleaseId" for a child that holds the PickNrRangeBegin==558 and PickNrRangeEnd==559.

```<code>"Data":[
  {
     "DrugReleaseId":"8a7bb731-8802-11ec-8ba3-00505699a442",
     "Filters":[
        {
           "BulkBatch2LotIds":null,
           "DrugCodeId":"1",
           "DrugDescription":"Druggy - 10mg 28 tablets",
           "PickNrRangeBegin":558,
           "PickNrRangeEnd":559,
           "Quantity":null,
           "TemporaryUnavailable":null,
           "LotIds":[
              "ed65aa20-e3b7-11eb-8b9b-00505699a442"
           ]
        },
        {
           "BulkBatch2LotIds":null,
           "DrugCodeId":"2",
           "DrugDescription":"Placebo - 10mg 28 tablets",
           "PickNrRangeBegin":25505,
           "PickNrRangeEnd":25506,
           "Quantity":null,
           "TemporaryUnavailable":null,
           "LotIds":[
              "98025036-e92c-11eb-8b9b-00505699a442"
           ]
        }
     ],
     "DepotId":"01",
     "LotId":"b7179175-e92c-11eb-8b9b-00505699a442",
     "LabelGroupId":null,
     "CreatedByUserId":"8509960e-8181-4428-89bd-367c0be29a9a",
     "CreatedUtcDateTime":"Mon Feb 07 2022 00:00:00",
     "Status":0,
     "ProcessedByUserId":null,
     "ProcessedUtcDateTime":null
  }
</code>```

I've only got to $..Data.[?(@.PickNrRangeBegin=='558') && ?(@.PickNrRangeBegin=='559')] but this will return all the contained elements:

```<code>"BulkBatch2LotIds": null,
"DrugCodeId": "1",
"DrugDescription": "BAY123456 - 10mg 28 tablets",
"PickNrRangeBegin": 558,
"PickNrRangeEnd": 559,
"Quantity": null,
"TemporaryUnavailable": null,
"LotIds": [
  "ed65aa20-e3b7-11eb-8b9b-00505699a442"
</code>```

答:
You'd need to apply the filter expression to the Data object itself, not its children.  You'd think this should be...

```<code>$..Data[?(@.Filters[*].PickNrRangeBegin == 558 && @.Filters[*].PickNrRangeEnd == 559)].DrugReleaseId
</code>```

... but that still doesn't quite work.

Here's a simpler expression that also "ought" to work:

```<code>$..Data[?(@..PickNrRangeBegin == 558 && @..PickNrRangeEnd == 559)].DrugReleaseId
</code>```

I think the fact that these aren't working is a weakness of the particular jsonpath parser implementations.  I just tried this last expression on https://jsonpath.herokuapp.com/, which tries 4 different implementations.  The Gatling parser actually gets the correct answer!  But Jayway finds no result, and the other two throw errors.  Sigh.

Body:
Based on the bellow JSON im trying to extract the "DrugReleaseId" for a child that holds the PickNrRangeBegin==558 and PickNrRangeEnd==559.

"Data":[
  {
     "DrugReleaseId":"8a7bb731-8802-11ec-8ba3-00505699a442",
     "Filters":[
        {
           "BulkBatch2LotIds":null,
           "DrugCodeId":"1",
           "DrugDescription":"Druggy - 10mg 28 tablets",
           "PickNrRangeBegin":558,
           "PickNrRangeEnd":559,
           "Quantity":null,
           "TemporaryUnavailable":null,
           "LotIds":[
              "ed65aa20-e3b7-11eb-8b9b-00505699a442"
           ]
        },
        {
           "BulkBatch2LotIds":null,
           "DrugCodeId":"2",
           "DrugDescription":"Placebo - 10mg 28 tablets",
           "PickNrRangeBegin":25505,
           "PickNrRangeEnd":25506,
           "Quantity":null,
           "TemporaryUnavailable":null,
           "LotIds":[
              "98025036-e92c-11eb-8b9b-00505699a442"
           ]
        }
     ],
     "DepotId":"01",
     "LotId":"b7179175-e92c-11eb-8b9b-00505699a442",
     "LabelGroupId":null,
     "CreatedByUserId":"8509960e-8181-4428-89bd-367c0be29a9a",
     "CreatedUtcDateTime":"Mon Feb 07 2022 00:00:00",
     "Status":0,
     "ProcessedByUserId":null,
     "ProcessedUtcDateTime":null
  }

I've only got to $..Data.[?(@.PickNrRangeBegin=='558') && ?(@.PickNrRangeBegin=='559')] but this will return all the contained elements:

"BulkBatch2LotIds": null,
"DrugCodeId": "1",
"DrugDescription": "BAY123456 - 10mg 28 tablets",
"PickNrRangeBegin": 558,
"PickNrRangeEnd": 559,
"Quantity": null,
"TemporaryUnavailable": null,
"LotIds": [
  "ed65aa20-e3b7-11eb-8b9b-00505699a442"

Body:
You'd need to apply the filter expression to the Data object itself, not its children.  You'd think this should be...

$..Data[?(@.Filters[*].PickNrRangeBegin == 558 && @.Filters[*].PickNrRangeEnd == 559)].DrugReleaseId

... but that still doesn't quite work.

Here's a simpler expression that also "ought" to work:

$..Data[?(@..PickNrRangeBegin == 558 && @..PickNrRangeEnd == 559)].DrugReleaseId

I think the fact that these aren't working is a weakness of the particular jsonpath parser implementations.  I just tried this last expression on https://jsonpath.herokuapp.com/, which tries 4 different implementations.  The Gatling parser actually gets the correct answer!  But Jayway finds no result, and the other two throw errors.  Sigh.


来源: stackexchange

问:
How can we get all usernames list only not user objects with django ORM
I want to know that how can we get list of required field data from django models. In my case i want to get all usernames from users models.

```<code>receivers = User.objects.all()
</code>```

this return all users objects. I want to get usernames directly. Something like below:

```<code>receivers = User.objects.all(username)
output:
["ahmed","dummy","hamza","sentence"]
</code>```

in sql query looks like below:

```<code>SELECT username from USER
</code>```

答:
```<code>receivers = User.objects.all().values_list('username')
</code>```

It will return list of all usernames.

ContentLicense: CC BY-SA 4.0

Body:
I want to know that how can we get list of required field data from django models. In my case i want to get all usernames from users models.

receivers = User.objects.all()

this return all users objects. I want to get usernames directly. Something like below:

receivers = User.objects.all(username)
output:
["ahmed","dummy","hamza","sentence"]

in sql query looks like below:

SELECT username from USER

Body:
receivers = User.objects.all().values_list('username')

It will return list of all usernames.


问:
SharedPreferences behaviour on Update/Uninstall
I am using shared preferences to store the number of times my application has been launched. Only on the first launch i display an Welcome message telling the user about the new features and changes in that version.

But as i absorbed on reinstalling the app or upgrading the application i am not able to remove the previous shared preferences. i would like to get the dialog when i reinstall the software or upgrade it too.

AppLauncher

```<code>public class AppLauncher {
    static long launch_count = 0;
    private static boolean isLaunch = false;

    public static void app_launched(Context mContext) {
        System.out.println("I m in AppLauncher");
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) {
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter

        launch_count = prefs.getLong("launch_count", 0);
        editor.putLong("launch_count", launch_count);

        System.out.println("launch_count=" + launch_count);
        if (launch_count == 0 || launch_count == 1) {
            // showLaunchDialog(mContext);
            isLaunch = true;
        }
        if (isLaunch == true) {
            showLaunchDialog(mContext);
            isLaunch = false;
        }
        editor.commit();
    }

    public static void showLaunchDialog(Context mcontext) {
        final Dialog dialog = new Dialog(mcontext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.whatsnew);

        Button dismisButton = (Button) dialog.findViewById(R.id.dismisButtom);
        System.out.println("inside dialog_started");
        dismisButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
</code>```

答: Instead of saving a boolean save the version number of the app. If the current app's version  number is higher (updated), show your dialog and update the number.

ContentLicense: CC BY-SA 3.0

Body:
I am using shared preferences to store the number of times my application has been launched. Only on the first launch i display an Welcome message telling the user about the new features and changes in that version.

But as i absorbed on reinstalling the app or upgrading the application i am not able to remove the previous shared preferences. i would like to get the dialog when i reinstall the software or upgrade it too.

AppLauncher

public class AppLauncher {
    static long launch_count = 0;
    private static boolean isLaunch = false;

    public static void app_launched(Context mContext) {
        System.out.println("I m in AppLauncher");
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) {
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter

        launch_count = prefs.getLong("launch_count", 0);
        editor.putLong("launch_count", launch_count);

        System.out.println("launch_count=" + launch_count);
        if (launch_count == 0 || launch_count == 1) {
            // showLaunchDialog(mContext);
            isLaunch = true;
        }
        if (isLaunch == true) {
            showLaunchDialog(mContext);
            isLaunch = false;
        }
        editor.commit();
    }

    public static void showLaunchDialog(Context mcontext) {
        final Dialog dialog = new Dialog(mcontext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.whatsnew);

        Button dismisButton = (Button) dialog.findViewById(R.id.dismisButtom);
        System.out.println("inside dialog_started");
        dismisButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}


问:
Zoom in and out of image on click using event listeners
I would like to create a function that takes in an array of images, checks whether an image has been clicked. If an image is clicked Zooms into the image, if the same image is clicked again, it would zoom out of the image.

This is what I have written

```<code>let imagesArr = document.querySelectorAll('img')
let isZoomed = false;
function rotateImage (e,isZoomed) {
    isZoomed = false ?
    e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1.5)";
            event.stopImmediatePropagation();
        })
    }) : e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1)";
            event.stopImmediatePropagation();
        })
    })
    isZoomed = true;
}
rotateImage(imagesArr,isZoomed);
</code>```

I an trying to check whether the image is already zoomed (true, false) and zoom/zoom out based on this condition. Not getting an error, but my function does not work (nothing happens when I click an image)

答: You can add event listener in image that you want to zoom on click, and then in event listener you can add style property to for that perticular image!</p>

Body:
I would like to create a function that takes in an array of images, checks whether an image has been clicked. If an image is clicked Zooms into the image, if the same image is clicked again, it would zoom out of the image.

This is what I have written

let imagesArr = document.querySelectorAll('img')
let isZoomed = false;
function rotateImage (e,isZoomed) {
    isZoomed = false ?
    e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1.5)";
            event.stopImmediatePropagation();
        })
    }) : e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1)";
            event.stopImmediatePropagation();
        })
    })
    isZoomed = true;
}
rotateImage(imagesArr,isZoomed);

I an trying to check whether the image is already zoomed (true, false) and zoom/zoom out based on this condition. Not getting an error, but my function does not work (nothing happens when I click an image)


问:
How to use soft constraints in Z3-Python to express 'abstract' biases in SAT search: such as 'I prefer half of the literals to be true and half false'
I previously asked in How to bias Z3's (Python) SAT solving towards a criteria, such as 'preferring' to have more negated literals, whether there was a way in Z3 (Python) to 'bias' the SAT search towards a 'criteria'?

In that post, we learnt 'simple biases' such as I would like Z3 to obtain a model, but not any model: if possible, give me a model that has a great amount of negated literals.

This was performed using a new solver (Optimize instead of Solver) and soft constraints (add_soft instead of add). Concretely, for each literal lit_n and an optimized solver o_solver, this was added: o_solver.add_soft(Not(lit_n)); or, equivalently: o_solver.add_soft(Or(Not(lit1), Not(lit2), ...).

However, I would like to express a 'little more complicated biases'. Concretely: if possible: I prefer models with the half of literals to True and the half to False.

Is there any way I can express this and similar 'biases' using the Optimize tool?

答:
Here’s a simple idea that might help. Count the number of positive literals and subtract from the count of negative ones. Take the absolute value of the difference and minimize it using the optimizer.

That should find the solution with as close a count of positive and negative literals, satisfying your “about half” soft constraint.

Here's a simple example. Let's say you have six literals and you want to satisfy their disjunction. The idiomatic solution would be:

from z3 import *

a, b, c, d, e, f = Bools("a b c d e f")

s = Solver()
s.add(Or(a, b, c, d, e, f))

print(s.check())
print(s.model())
```
<p>If you run this, you'll get:</p>
<pre class="lang-py prettyprint-override"><code>sat
[f = False,
 b = False,
 a = True,
 c = False,
 d = False,
 e = False]
</code>```

So, z3 simply made a True and all others False. But you wanted to have roughly the same count of positive and negative literals. So, let's encode that:

from z3 import *

a, b, c, d, e, f = Bools("a b c d e f")

s = Optimize()
s.add(Or(a, b, c, d, e, f))

def count(ref, xs):
    s = 0
    for x in xs:
        s += If(x == ref, 1, 0)
    return s

def sabs(x):
    return If(x > 0, x, -x)

lits = [a, b, c, d, e, f]
posCount = count(True,  lits)
negCount = count(False, lits)
s.minimize(sabs(posCount - negCount))

print(s.check())
print(s.model())
```
<p>Note how we "symbolically" count the negative and positive literals and ask z3 to minimize the absolute value of the difference. If you run this, you'll get:</p>
<pre class="lang-py prettyprint-override"><code>sat
[a = True,
 b = False,
 c = False,
 d = True,
 e = False,
 f = True]
</code>```

With 3 positive and 3 negative literals. If you had 7 literals to start with, it'd have found a 4-3 split. If you prefer more positive literals than negatives, you can additionally add a soft constraint of the form:

s.add_soft(posCount >= negCount)
```

to bias the solver that way. Hope this gets you started..

Body:
Here’s a simple idea that might help. Count the number of positive literals and subtract from the count of negative ones. Take the absolute value of the difference and minimize it using the optimizer.

That should find the solution with as close a count of positive and negative literals, satisfying your “about half” soft constraint.

Here's a simple example. Let's say you have six literals and you want to satisfy their disjunction. The idiomatic solution would be:

from z3 import *

a, b, c, d, e, f = Bools("a b c d e f")

s = Solver()
s.add(Or(a, b, c, d, e, f))

print(s.check())
print(s.model())

If you run this, you'll get:

sat
[f = False,
 b = False,
 a = True,
 c = False,
 d = False,
 e = False]

So, z3 simply made a True and all others False. But you wanted to have roughly the same count of positive and negative literals. So, let's encode that:

from z3 import *

a, b, c, d, e, f = Bools("a b c d e f")

s = Optimize()
s.add(Or(a, b, c, d, e, f))

def count(ref, xs):
    s = 0
    for x in xs:
        s += If(x == ref, 1, 0)
    return s

def sabs(x):
    return If(x > 0, x, -x)

lits = [a, b, c, d, e, f]
posCount = count(True,  lits)
negCount = count(False, lits)
s.minimize(sabs(posCount - negCount))

print(s.check())
print(s.model())

Note how we "symbolically" count the negative and positive literals and ask z3 to minimize the absolute value of the difference. If you run this, you'll get:

sat
[a = True,
 b = False,
 c = False,
 d = True,
 e = False,
 f = True]

With 3 positive and 3 negative literals. If you had 7 literals to start with, it'd have found a 4-3 split. If you prefer more positive literals than negatives, you can additionally add a soft constraint of the form:

s.add_soft(posCount >= negCount)

to bias the solver that way. Hope this gets you started..


问:
How to run a scoped function before all pytest fixtures of that scope?
I saw this question, asking the same about doing things before tests.

I need to do things before fixtures.

For example, I am setting up a dockerized environment, which I have to clean before building. To make things more complicated, I am using this plugin which defines fixtures I can't control or change, and I need something that comes before all fixtures (and does docker-compose down and other cleanup).

For example, when pytest starts, run the common per-session pre-step, then the fixtures, then the per-module pre-step, then the fixtures, and so on.

Is this a supported hook in pytest?

I couldn't find a relevant doc.

答:
As @MrBean Bremen stated, pytest_sessionstart does the trick.

An annoying problem with that, is I can't use fixtures inside (naturally), with Argument(s) {'fixture_name'} are declared in the hookimpl but can not be found in the hookspec

I tried to fix that with pytest-dependency, but it doesn't seem to work on fixtures, only on tests.

I am left with the hacky workaround to extract required data for sessionstart to functions, and call them in sessionstart as well as in similarly named fixtures.

It works, but it is ugly.

Would accept a cleaner solution over this one


问:
round() mode ROUND_HALF_DOWN with PHP 5.2.17
I need to simulate ROUND_HALF_DOWN mode in PHP 5.2.17 - I cannot upgrade the server's PHP version. Any ideas how to achieve this?

The basic idea is that 1.895 becomes 1.89, not 1.90 like it usually does with round().

EDIT:
This function seems to do the trick:

```<code>function nav_round($v, $prec = 2) {
    // Seems to fix a bug with the ceil function
    $v = explode('.',$v);
    $v = implode('.',$v);
    // The actual calculation
    $v = $v * pow(10,$prec) - 0.5;
    $a = ceil($v) * pow(10,-$prec);
    return number_format( $a, 2, '.', '' );
}
</code>```

答:
You can use the preg_replace for this:</p>

```<code>$string = '1.895';
$pattern = '/(\d+).(\d+)/e';
$replacement = "'\\1'.'.'.((substr($string, -1) > 5) ?  (substr('\\2',0,2) + 1)  :  substr('\\2',0,2))";
echo preg_replace($pattern, $replacement, $string);
</code>```

Body:
I need to simulate ROUND_HALF_DOWN mode in PHP 5.2.17 - I cannot upgrade the server's PHP version. Any ideas how to achieve this?

The basic idea is that 1.895 becomes 1.89, not 1.90 like it usually does with round().

EDIT:
This function seems to do the trick:

function nav_round($v, $prec = 2) {
    // Seems to fix a bug with the ceil function
    $v = explode('.',$v);
    $v = implode('.',$v);
    // The actual calculation
    $v = $v * pow(10,$prec) - 0.5;
    $a = ceil($v) * pow(10,-$prec);
    return number_format( $a, 2, '.', '' );
}

Body:
You can use the preg_replace for this:

$string = '1.895';
$pattern = '/(\d+).(\d+)/e';
$replacement = "'\\1'.'.'.((substr($string, -1) > 5) ?  (substr('\\2',0,2) + 1)  :  substr('\\2',0,2))";
echo preg_replace($pattern, $replacement, $string);


问:
Restart .NET AnyCPU exe with different bitness
I have a .NET exe compiled for "AnyCPU", so it can theoretically run in both 32-bit and 64-bit mode (on a 64-bit operating system). Since my exe strongly interacts with MS Office, I need to run it with the same bitness as the installed Office version. (Please take this requirement as granted, I will gladly provide details in the comments, if you are interested.)

Now, I have thought up a solution for this, but it seems more complicated than necessary:

Compile two versions: MyExe32.exe and MyExe64.exe, targeting x86 and x64, respectively, instead of AnyCPU.

Create a launcher application Launcher.exe, which determines the bitness of the locally installed Office version (I know how to do that) and then starts MyExe32.exe or MyExe64.exe.

This would work, but I'd rather have a single, simple MyExe.exe with something like the following pseudo-code during start-up:

```<code>if (Environment.Is64BitProcess && IsOffice32BitInstalled)
{
    // restart myself in a 32-bit process instead of a 64-bit process
    ???  // <-- this is where I need help
}
</code>```

Is that possible? If yes, how?

Notes: I know about the CorFlags utility, but I'd rather have a solution that does not require modifying the exe itself at runtime.

答:
Apparently I don't have reputation enough to post comments, so posting this as an answer instead.

If, as you say, you're deploying to an internal network, I'd recommend using a launcher anwyay.

That way users can have a single network shortcut to the launcher, that doesn't move around. The launcher can determine which bitness is required, and which is the latest release, and launch the EXE for that release.

If you allow users to go directly at the EXE, you will either encounter problems with users having the EXE opened, so you can't overwrite it, or have to create new user shortcuts for every release.

Body:
I have a .NET exe compiled for "AnyCPU", so it can theoretically run in both 32-bit and 64-bit mode (on a 64-bit operating system). Since my exe strongly interacts with MS Office, I need to run it with the same bitness as the installed Office version. (Please take this requirement as granted, I will gladly provide details in the comments, if you are interested.)

Now, I have thought up a solution for this, but it seems more complicated than necessary:

Compile two versions: MyExe32.exe and MyExe64.exe, targeting x86 and x64, respectively, instead of AnyCPU.

Create a launcher application Launcher.exe, which determines the bitness of the locally installed Office version (I know how to do that) and then starts MyExe32.exe or MyExe64.exe.

This would work, but I'd rather have a single, simple MyExe.exe with something like the following pseudo-code during start-up:

if (Environment.Is64BitProcess && IsOffice32BitInstalled)
{
    // restart myself in a 32-bit process instead of a 64-bit process
    ???  // <-- this is where I need help
}

Is that possible? If yes, how?

Notes: I know about the CorFlags utility, but I'd rather have a solution that does not require modifying the exe itself at runtime.


问:
How to display Splash screen in reactjs
I have two codes for Splash.jsx and one for homepage.jsx. All I want is to display the Splash screen once the Homepage is not in use, but I have no idea how to integrate the splash screen with the Homepage and set the timer, so the splash screen is displayed once I don't use Homepage. It would be great to help me out with showing the splash screen once the Homepage is not in use.
Homepage.jsx

```<code>import React from 'react';

import Card from '../Card/Card'
import img2 from '../../Assets/AutoLoan.png'
import img3 from '../../Assets/KYC.png'
import img4 from '../../Assets/VIsa.png'
import './Homepage.css'

import {
  Swiper,
  SwiperSlide
}
from 'swiper/react';
import 'swiper/css';
import { Navigation } from 'swiper';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
import { Link } from 'react-router-dom';

 const Homepage= () => {
   return (
     <div>

     <div className="background">

         <div className="welcome__heading">
                <h1>Welcome!!</h1>
              </div>
              <div className= "customer__support">
           <h2>We are here for customer service.</h2>
            </div >
            <div className="swiper_container">
               <Swiper
                modules={[Navigation]}
                navigation
              spaceBetween={10}
              slidesPerView={3}
              onSwiper={(swiper) => console.log(swiper)}
                onSlideChange={() => console.log('slide change')}
                loop={true}
              >
           <SwiperSlide>
             <Link to="AutoLoan">
               <Card imgsrc={img2} alt="AutoLoan" title="Auto Loan" />
             </Link>
           </SwiperSlide>
           <SwiperSlide>
             <Link to="KYC">
               <Card imgsrc={img3} alt="KYC" title="KYC Form" />
             </Link>
           </SwiperSlide>
           <SwiperSlide>
             <Link to="Debit">
               <Card imgsrc={img4} alt="Visa" title="Visa Debit Card" />
             </Link>
           </SwiperSlide>
            </Swiper>
            </div>
            <div ClassName="button">

                <Link to = "Location">
                <button className = "btn1">
                  <i className = "fa fa-map"></i>
              </button>
              </Link>
              <Link to = "Calculator">

              <button className = "btn2">
               <i className = "fa fa-calculator"></i>
              </button>
         </Link>
         </div>
       </div>
       </div>

          );

}

export default Homepage
</code>```

Splash.jsx

```<code>import React from 'react';
import './Splash.css'
import img2 from '../../Assets/Header.png'
import img8 from '../../Assets/hand.svg'

const Splash = () => {

    return (
        <div>
            <div className="bg2">
            <div className="header__body">
            <div className="header__left">
                <div className="header__left__image">
                    <img src = {img2} alt="Header"/>
                </div>
                <h1 >Laxmi Bank</h1>
               </div>
            <div className="header__right">
            <h1 >23℃/11:00AM</h1>
                    </div>

        </div>

            </div>
            <div className="splash">
                <h1>TAP HERE</h1>

            <div className= "blink">
                <img src = {img8} alt = "taphand" />

             </div>
        </div>
        </div>
    );
};

export default Splash;
</code>```

The splash screen should appear after 2 sec of not using Homepage, and once we tap on the splash screen the Homepage should appear again and once it is idle the splash screen should appear and vice versa. and I have no idea how to set the timer and control this component. So, it would be good if someone would help me out.

答:
You need to create a idle timer to trigger after inactivity of the
user in Homepage

When setTimeout triggers the callback it will mount the Splash

Once Splash is mounted, click on the Link tag says TAP HERE back to redirect to home

Homepage -
(path = "/home")

```<code>import React,{ useEffect } from "react";
import { useNavigate } from "react-router-dom";

const Homepage= () => {
  let navigate = useNavigate();

  useEffect(() => {
    //Idle timer

    let timerId;

    const resetTimer = () => {
      clearTimeout(timerId);
      timerId = setTimeout(() => {
        navigate("/splash");
      }, 30 * 1000); //30 sec idle time
    };

    document.addEventListener("keydown", resetTimer);
    document.addEventListener("mousemove", resetTimer);
    return () => {
      clearTimeout(timerId);
      document.removeEventListener("keydown", resetTimer);
      document.removeEventListener("mousemove", resetTimer);
    };
  }, []);
}
</code>```

Splash - (path = "/splash")

```<code>const Splash = () => {
  return <div>
    ...
    <Link to='/home'>TAP HERE</Link>
  </div>
}
</code>```

Title: How to display Splash screen in reactjs

Body:
I have two codes for Splash.jsx and one for homepage.jsx. All I want is to display the Splash screen once the Homepage is not in use, but I have no idea how to integrate the splash screen with the Homepage and set the timer, so the splash screen is displayed once I don't use Homepage. It would be great to help me out with showing the splash screen once the Homepage is not in use.
Homepage.jsx

import React from 'react';

import Card from '../Card/Card'
import img2 from '../../Assets/AutoLoan.png'
import img3 from '../../Assets/KYC.png'
import img4 from '../../Assets/VIsa.png'
import './Homepage.css'

import {
  Swiper,
  SwiperSlide
}
from 'swiper/react';
import 'swiper/css';
import { Navigation } from 'swiper';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
import { Link } from 'react-router-dom';

 const Homepage= () => {
   return (

Welcome!!

We are here for customer service.

               <Swiper
                modules={[Navigation]}
                navigation
              spaceBetween={10}
              slidesPerView={3}
              onSwiper={(swiper) => console.log(swiper)}
                onSlideChange={() => console.log('slide change')}
                loop={true}
              >
           <SwiperSlide>
             <Link to="AutoLoan">
               <Card imgsrc={img2} alt="AutoLoan" title="Auto Loan" />
             </Link>
           </SwiperSlide>
           <SwiperSlide>
             <Link to="KYC">
               <Card imgsrc={img3} alt="KYC" title="KYC Form" />
             </Link>
           </SwiperSlide>
           <SwiperSlide>
             <Link to="Debit">
               <Card imgsrc={img4} alt="Visa" title="Visa Debit Card" />
             </Link>
           </SwiperSlide>
            </Swiper>

                <Link to = "Location">
                <button className = "btn1">

              </button>
              </Link>
              <Link to = "Calculator">

              <button className = "btn2">

              </button>
         </Link>

          );

}

export default Homepage

Splash.jsx

import React from 'react';
import './Splash.css'
import img2 from '../../Assets/Header.png'
import img8 from '../../Assets/hand.svg'

const Splash = () => {

    return (

Laxmi Bank

23℃/11:00AM

TAP HERE

    );
};

export default Splash;

The splash screen should appear after 2 sec of not using Homepage, and once we tap on the splash screen the Homepage should appear again and once it is idle the splash screen should appear and vice versa. and I have no idea how to set the timer and control this component. So, it would be good if someone would help me out.

Body:
You need to create a idle timer to trigger after inactivity of the
user in Homepage

When setTimeout triggers the callback it will mount the Splash

Once Splash is mounted, click on the Link tag says TAP HERE back to redirect to home

Homepage -
(path = "/home")

import React,{ useEffect } from "react";
import { useNavigate } from "react-router-dom";

const Homepage= () => {
  let navigate = useNavigate();

  useEffect(() => {
    //Idle timer

    let timerId;

    const resetTimer = () => {
      clearTimeout(timerId);
      timerId = setTimeout(() => {
        navigate("/splash");
      }, 30 * 1000); //30 sec idle time
    };

    document.addEventListener("keydown", resetTimer);
    document.addEventListener("mousemove", resetTimer);
    return () => {
      clearTimeout(timerId);
      document.removeEventListener("keydown", resetTimer);
      document.removeEventListener("mousemove", resetTimer);
    };
  }, []);
}

Splash - (path = "/splash")

const Splash = () => {
  return <div>
    ...
    <Link to='/home'>TAP HERE</Link>
  </div>
}


问:
How can I make this Python Match function faster?
I need to test around 100 million HTML documents to see if they meet certain criteria. I am doing this by checking whether certain strings exist in the text after stripping the HTML tags.

I have made a list of these strings as follows:

```<code>simpleToParse = []
simpleToParse.append('"Subject" "act=dispBoardWrite"'.lower())
simpleToParse.append('"dispMemberSignUpForm"'.lower())
simpleToParse.append('"Help get things started by asking a question"'.lower())
simpleToParse.append('"Recent questions and answers"'.lower())
...
...
...
</code>```

I have around 200 of these strings.
So, for this

```<code>simpleToParse.append('"Subject" "act=dispBoardWrite"'.lower())
</code>```

If the document contains the words subject and act=dispBoardWrite, it will be considered a match. ANY of the items matching from the main simpleToParse list will be considered a match. In essence,

sometext AND sometext

OR

sometext

OR

sometext AND sometext AND sometext

...

...

...

Here is the function I am using

```<code>def check(strippedHTML):
    if any(all(x in strippedHTML.lower() for x in re.findall(r'"(.+?)"',y)) for y in simpleToParse):
        return True
    return False
</code>```

Problem is, this function above is taking anywhere from 2-30 seconds per document depending on the length of the document.

I have an 8C/16T Ryzen 5800x but it would still take me weeks to do this. Any help would be appreciated. Thanks.

答:
I assume the problem is CPU-bound, so to benefit from parallelism you have to use multiprocessing.

Also, do not use a regex if you are not matching regular expressions.

Here is a proposal :

import concurrent.futures

rules = tuple(
    tuple(term.lower() for term in rule)
    for rule in (
        ["subject", "act=dispBoardWrite"],
        ["dispMemberSignUpForm"],
        ["Help get things started by asking a question"],
        ["Recent questions and answers"],
        # ["is creating a new copy of the input"],
    )
)

def check_rule(rule, text):
    return all(term in text for term in rule)

def check_all_rules(filepath):
    with open(filepath, "rt") as file:
        file_content = file.read()

    with concurrent.futures.ProcessPoolExecutor(max_workers=None) as executor:
        # create all futures, one per rule, and get their result as soon as available
        for future in concurrent.futures.as_completed(executor.submit(check_rule, rule, file_content)
                                                      for rule in rules):
            # cf https://stackoverflow.com/q/16276423/11384184
            if future.result() is True:
                # we have one match, no need to search for more
                executor.shutdown(wait=False, cancel_futures=True)  # Python>=3.9
                break
            else:
                # continue searching for a match
                continue
        else:  # the iterator is exhausted, no rule matched
            return False
        # the iterator was interrupted, there was a match
        return True

def check_all_files():
    filepaths = (
        "so70674556.html",
    )
    for filepath in filepaths:
        print(filepath, check_all_rules(filepath))

check_all_files()
```

It will iterate over all the files (in my example just an HTML dump of this page), for each it will create a ProcessPoolExecutor to handle the parallelism, feed it the tasks (one per rule to match), and get the results as they complete. As soon as there is a match, all tasks gets cancelled and it moves to the next file.

I think it will be much faster than your single-threaded regex matching.

If it was not sufficient though, you should provide in your question an example of a real file to process, and an example of the 200 rules to match against.

Body:
I need to test around 100 million HTML documents to see if they meet certain criteria. I am doing this by checking whether certain strings exist in the text after stripping the HTML tags.

I have made a list of these strings as follows:

simpleToParse = []
simpleToParse.append('"Subject" "act=dispBoardWrite"'.lower())
simpleToParse.append('"dispMemberSignUpForm"'.lower())
simpleToParse.append('"Help get things started by asking a question"'.lower())
simpleToParse.append('"Recent questions and answers"'.lower())
...
...
...

I have around 200 of these strings.
So, for this

simpleToParse.append('"Subject" "act=dispBoardWrite"'.lower())

If the document contains the words subject and act=dispBoardWrite, it will be considered a match. ANY of the items matching from the main simpleToParse list will be considered a match. In essence,

sometext AND sometext

OR

sometext

OR

sometext AND sometext AND sometext

...

...

...

Here is the function I am using

def check(strippedHTML):
    if any(all(x in strippedHTML.lower() for x in re.findall(r'"(.+?)"',y)) for y in simpleToParse):
        return True
    return False

Problem is, this function above is taking anywhere from 2-30 seconds per document depending on the length of the document.

I have an 8C/16T Ryzen 5800x but it would still take me weeks to do this. Any help would be appreciated. Thanks.

Body:
I assume the problem is CPU-bound, so to benefit from parallelism you have to use multiprocessing.

Also, do not use a regex if you are not matching regular expressions.

Here is a proposal :

import concurrent.futures

rules = tuple(
    tuple(term.lower() for term in rule)
    for rule in (
        ["subject", "act=dispBoardWrite"],
        ["dispMemberSignUpForm"],
        ["Help get things started by asking a question"],
        ["Recent questions and answers"],
        # ["is creating a new copy of the input"],
    )
)

def check_rule(rule, text):
    return all(term in text for term in rule)

def check_all_rules(filepath):
    with open(filepath, "rt") as file:
        file_content = file.read()

    with concurrent.futures.ProcessPoolExecutor(max_workers=None) as executor:
        # create all futures, one per rule, and get their result as soon as available
        for future in concurrent.futures.as_completed(executor.submit(check_rule, rule, file_content)
                                                      for rule in rules):
            # cf https://stackoverflow.com/q/16276423/11384184
            if future.result() is True:
                # we have one match, no need to search for more
                executor.shutdown(wait=False, cancel_futures=True)  # Python>=3.9
                break
            else:
                # continue searching for a match
                continue
        else:  # the iterator is exhausted, no rule matched
            return False
        # the iterator was interrupted, there was a match
        return True

def check_all_files():
    filepaths = (
        "so70674556.html",
    )
    for filepath in filepaths:
        print(filepath, check_all_rules(filepath))

check_all_files()

It will iterate over all the files (in my example just an HTML dump of this page), for each it will create a ProcessPoolExecutor to handle the parallelism, feed it the tasks (one per rule to match), and get the results as they complete. As soon as there is a match, all tasks gets cancelled and it moves to the next file.

I think it will be much faster than your single-threaded regex matching.

If it was not sufficient though, you should provide in your question an example of a real file to process, and an example of the 200 rules to match against.


问:
Iterate through dict with nested lists with nested dicts ... and so on
I'm using creopyson to read a 3D model's bill of materials. The data that creopyson returns is a nested dict with lists. The BOM is structured in a parent -> child structure where there can be multiple children (organized in a list). Each child is a dict containing the child's info. Ideally, I'd like to iterate through each dict entry no matter its position in the 'master' dict. Then I'll insert each entry into a tree view as a structured BOM based on its position in the dict or by its root level (key->seq_path).

Here's a sample of the raw output dict from creopyson:

```<code>{'has_simprep': False, 'children': {'children': [{'file': 'COUPLERLARGE_SIDE_UPPERPLATE.PRT', 'seq_path': 'root.1'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.2'}, {'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.3'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.4'}, {'file': 'MOUNTBLOCK.PRT', 'seq_path': 'root.5'}, {'file': 'SLIDERPLATE.PRT', 'seq_path': 'root.6'}, {'file': 'STATICHOOK_BACKING.PRT', 'seq_path': 'root.7'}, {'file': 'PIVOTMECH.PRT', 'seq_path': 'root.8'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.9'}, {'children': [{'file': 'SLIDINGPLATE.PRT', 'seq_path': 'root.10.1'}, {'file': 'HOOK.PRT', 'seq_path': 'root.10.2'}, {'file': 'HOOK_BACKING.PRT', 'seq_path': 'root.10.3'}, {'file': 'HOOK.PRT', 'seq_path': 'root.10.4'}, {'file': 'SHOOK_BACKPLATE.PRT', 'seq_path': 'root.10.5'}, {'file': 'CYLINDERCLEVIS.PRT', 'seq_path': 'root.10.6'}], 'file': 'SLIDINGHOOK.ASM', 'seq_path': 'root.10'}, {'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.11'}], 'file': 'bigcoupler_ref.asm', 'seq_path': 'root'},
'generic': '', 'file': 'bigcoupler_ref.asm'}
</code>```

Here's a sample of the output from creopyson using pprint to indent:

```<code>{   'children': {   'children': [   {   'file': 'COUPLERLARGE_SIDE_UPPERPLATE.PRT',
                                        'seq_path': 'root.1'},
                                    {   'file': 'SPRING_REF.PRT',
                                        'seq_path': 'root.2'},
                                    {   'file': 'CYLINDER_REF.PRT',
                                        'seq_path': 'root.3'},
                                    {   'file': 'SPRING_REF.PRT',
                                        'seq_path': 'root.4'},
                                    {   'file': 'MOUNTBLOCK.PRT',
                                        'seq_path': 'root.5'},
                                    {   'file': 'SLIDERPLATE.PRT',
                                        'seq_path': 'root.6'},
                                    {   'file': 'STATICHOOK_BACKING.PRT',
                                        'seq_path': 'root.7'},
                                    {   'file': 'PIVOTMECH.PRT',
                                        'seq_path': 'root.8'},
                                    {   'file': 'SPRING_REF.PRT',
                                        'seq_path': 'root.9'},
                                    {   'children': [   {   'file': 'SLIDINGPLATE.PRT',
                                                            'seq_path': 'root.10.1'},
                                                        {   'file': 'HOOK.PRT',
                                                            'seq_path': 'root.10.2'},
                                                        {   'file': 'HOOK_BACKING.PRT',
                                                            'seq_path': 'root.10.3'},
                                                        {   'file': 'HOOK.PRT',
                                                            'seq_path': 'root.10.4'},
                                                        {   'file': 'SHOOK_BACKPLATE.PRT',
                                                            'seq_path': 'root.10.5'},
                                                        {   'file': 'CYLINDERCLEVIS.PRT',
                                                            'seq_path': 'root.10.6'}],
                                        'file': 'SLIDINGHOOK.ASM',
                                        'seq_path': 'root.10'},
                                    {   'file': 'CYLINDER_REF.PRT',
                                        'seq_path': 'root.11'}],
                    'file': 'bigcoupler_ref.asm',
                    'seq_path': 'root'},
    'file': 'bigcoupler_ref.asm',
    'generic': '',
    'has_simprep': False}
</code>```

答:
You can define this generator:

```<code>def nested_entries(d):
    if "children" in d:
        for child in d["children"]:
            yield from nested_entries(child)
    else:
        yield d
</code>```

It is a bit odd that your top-level dict has a "children" key which does not have a list as value, like is the case at deeper levels. The above function assumes that "children" keys have lists as values, so call it with the "children" value of the top-level object:

```<code>d = {'has_simprep': False, 'children': {'children': [{'file': 'COUPLERLARGE_SIDE_UPPERPLATE.PRT', 'seq_path': 'root.1'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.2'}, {'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.3'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.4'}, {'file': 'MOUNTBLOCK.PRT', 'seq_path': 'root.5'}, {'file': 'SLIDERPLATE.PRT', 'seq_path': 'root.6'}, {'file': 'STATICHOOK_BACKING.PRT', 'seq_path': 'root.7'}, {'file': 'PIVOTMECH.PRT', 'seq_path': 'root.8'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.9'}, {'children': [{'file': 'SLIDINGPLATE.PRT', 'seq_path': 'root.10.1'}, {'file': 'HOOK.PRT', 'seq_path': 'root.10.2'}, {'file': 'HOOK_BACKING.PRT', 'seq_path': 'root.10.3'}, {'file': 'HOOK.PRT', 'seq_path': 'root.10.4'}, {'file': 'SHOOK_BACKPLATE.PRT', 'seq_path': 'root.10.5'}, {'file': 'CYLINDERCLEVIS.PRT', 'seq_path': 'root.10.6'}], 'file': 'SLIDINGHOOK.ASM', 'seq_path': 'root.10'}, {'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.11'}], 'file': 'bigcoupler_ref.asm', 'seq_path': 'root'},
'generic': '', 'file': 'bigcoupler_ref.asm'}

for item in nested_entries(d["children"]):
    print(item)
</code>```

This outputs:

```<code>{'file': 'COUPLERLARGE_SIDE_UPPERPLATE.PRT', 'seq_path': 'root.1'}
{'file': 'SPRING_REF.PRT', 'seq_path': 'root.2'}
{'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.3'}
{'file': 'SPRING_REF.PRT', 'seq_path': 'root.4'}
{'file': 'MOUNTBLOCK.PRT', 'seq_path': 'root.5'}
{'file': 'SLIDERPLATE.PRT', 'seq_path': 'root.6'}
{'file': 'STATICHOOK_BACKING.PRT', 'seq_path': 'root.7'}
{'file': 'PIVOTMECH.PRT', 'seq_path': 'root.8'}
{'file': 'SPRING_REF.PRT', 'seq_path': 'root.9'}
{'file': 'SLIDINGPLATE.PRT', 'seq_path': 'root.10.1'}
{'file': 'HOOK.PRT', 'seq_path': 'root.10.2'}
{'file': 'HOOK_BACKING.PRT', 'seq_path': 'root.10.3'}
{'file': 'HOOK.PRT', 'seq_path': 'root.10.4'}
{'file': 'SHOOK_BACKPLATE.PRT', 'seq_path': 'root.10.5'}
{'file': 'CYLINDERCLEVIS.PRT', 'seq_path': 'root.10.6'}
{'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.11'}
</code>```

Body:
I'm using creopyson to read a 3D model's bill of materials. The data that creopyson returns is a nested dict with lists. The BOM is structured in a parent -> child structure where there can be multiple children (organized in a list). Each child is a dict containing the child's info. Ideally, I'd like to iterate through each dict entry no matter its position in the 'master' dict. Then I'll insert each entry into a tree view as a structured BOM based on its position in the dict or by its root level (key->seq_path).

Here's a sample of the raw output dict from creopyson:

{'has_simprep': False, 'children': {'children': [{'file': 'COUPLERLARGE_SIDE_UPPERPLATE.PRT', 'seq_path': 'root.1'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.2'}, {'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.3'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.4'}, {'file': 'MOUNTBLOCK.PRT', 'seq_path': 'root.5'}, {'file': 'SLIDERPLATE.PRT', 'seq_path': 'root.6'}, {'file': 'STATICHOOK_BACKING.PRT', 'seq_path': 'root.7'}, {'file': 'PIVOTMECH.PRT', 'seq_path': 'root.8'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.9'}, {'children': [{'file': 'SLIDINGPLATE.PRT', 'seq_path': 'root.10.1'}, {'file': 'HOOK.PRT', 'seq_path': 'root.10.2'}, {'file': 'HOOK_BACKING.PRT', 'seq_path': 'root.10.3'}, {'file': 'HOOK.PRT', 'seq_path': 'root.10.4'}, {'file': 'SHOOK_BACKPLATE.PRT', 'seq_path': 'root.10.5'}, {'file': 'CYLINDERCLEVIS.PRT', 'seq_path': 'root.10.6'}], 'file': 'SLIDINGHOOK.ASM', 'seq_path': 'root.10'}, {'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.11'}], 'file': 'bigcoupler_ref.asm', 'seq_path': 'root'},
'generic': '', 'file': 'bigcoupler_ref.asm'}

Here's a sample of the output from creopyson using pprint to indent:

{   'children': {   'children': [   {   'file': 'COUPLERLARGE_SIDE_UPPERPLATE.PRT',
                                        'seq_path': 'root.1'},
                                    {   'file': 'SPRING_REF.PRT',
                                        'seq_path': 'root.2'},
                                    {   'file': 'CYLINDER_REF.PRT',
                                        'seq_path': 'root.3'},
                                    {   'file': 'SPRING_REF.PRT',
                                        'seq_path': 'root.4'},
                                    {   'file': 'MOUNTBLOCK.PRT',
                                        'seq_path': 'root.5'},
                                    {   'file': 'SLIDERPLATE.PRT',
                                        'seq_path': 'root.6'},
                                    {   'file': 'STATICHOOK_BACKING.PRT',
                                        'seq_path': 'root.7'},
                                    {   'file': 'PIVOTMECH.PRT',
                                        'seq_path': 'root.8'},
                                    {   'file': 'SPRING_REF.PRT',
                                        'seq_path': 'root.9'},
                                    {   'children': [   {   'file': 'SLIDINGPLATE.PRT',
                                                            'seq_path': 'root.10.1'},
                                                        {   'file': 'HOOK.PRT',
                                                            'seq_path': 'root.10.2'},
                                                        {   'file': 'HOOK_BACKING.PRT',
                                                            'seq_path': 'root.10.3'},
                                                        {   'file': 'HOOK.PRT',
                                                            'seq_path': 'root.10.4'},
                                                        {   'file': 'SHOOK_BACKPLATE.PRT',
                                                            'seq_path': 'root.10.5'},
                                                        {   'file': 'CYLINDERCLEVIS.PRT',
                                                            'seq_path': 'root.10.6'}],
                                        'file': 'SLIDINGHOOK.ASM',
                                        'seq_path': 'root.10'},
                                    {   'file': 'CYLINDER_REF.PRT',
                                        'seq_path': 'root.11'}],
                    'file': 'bigcoupler_ref.asm',
                    'seq_path': 'root'},
    'file': 'bigcoupler_ref.asm',
    'generic': '',
    'has_simprep': False}

Body:
You can define this generator:

def nested_entries(d):
    if "children" in d:
        for child in d["children"]:
            yield from nested_entries(child)
    else:
        yield d

It is a bit odd that your top-level dict has a "children" key which does not have a list as value, like is the case at deeper levels. The above function assumes that "children" keys have lists as values, so call it with the "children" value of the top-level object:

d = {'has_simprep': False, 'children': {'children': [{'file': 'COUPLERLARGE_SIDE_UPPERPLATE.PRT', 'seq_path': 'root.1'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.2'}, {'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.3'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.4'}, {'file': 'MOUNTBLOCK.PRT', 'seq_path': 'root.5'}, {'file': 'SLIDERPLATE.PRT', 'seq_path': 'root.6'}, {'file': 'STATICHOOK_BACKING.PRT', 'seq_path': 'root.7'}, {'file': 'PIVOTMECH.PRT', 'seq_path': 'root.8'}, {'file': 'SPRING_REF.PRT', 'seq_path': 'root.9'}, {'children': [{'file': 'SLIDINGPLATE.PRT', 'seq_path': 'root.10.1'}, {'file': 'HOOK.PRT', 'seq_path': 'root.10.2'}, {'file': 'HOOK_BACKING.PRT', 'seq_path': 'root.10.3'}, {'file': 'HOOK.PRT', 'seq_path': 'root.10.4'}, {'file': 'SHOOK_BACKPLATE.PRT', 'seq_path': 'root.10.5'}, {'file': 'CYLINDERCLEVIS.PRT', 'seq_path': 'root.10.6'}], 'file': 'SLIDINGHOOK.ASM', 'seq_path': 'root.10'}, {'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.11'}], 'file': 'bigcoupler_ref.asm', 'seq_path': 'root'},
'generic': '', 'file': 'bigcoupler_ref.asm'}

for item in nested_entries(d["children"]):
    print(item)

This outputs:

{'file': 'COUPLERLARGE_SIDE_UPPERPLATE.PRT', 'seq_path': 'root.1'}
{'file': 'SPRING_REF.PRT', 'seq_path': 'root.2'}
{'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.3'}
{'file': 'SPRING_REF.PRT', 'seq_path': 'root.4'}
{'file': 'MOUNTBLOCK.PRT', 'seq_path': 'root.5'}
{'file': 'SLIDERPLATE.PRT', 'seq_path': 'root.6'}
{'file': 'STATICHOOK_BACKING.PRT', 'seq_path': 'root.7'}
{'file': 'PIVOTMECH.PRT', 'seq_path': 'root.8'}
{'file': 'SPRING_REF.PRT', 'seq_path': 'root.9'}
{'file': 'SLIDINGPLATE.PRT', 'seq_path': 'root.10.1'}
{'file': 'HOOK.PRT', 'seq_path': 'root.10.2'}
{'file': 'HOOK_BACKING.PRT', 'seq_path': 'root.10.3'}
{'file': 'HOOK.PRT', 'seq_path': 'root.10.4'}
{'file': 'SHOOK_BACKPLATE.PRT', 'seq_path': 'root.10.5'}
{'file': 'CYLINDERCLEVIS.PRT', 'seq_path': 'root.10.6'}
{'file': 'CYLINDER_REF.PRT', 'seq_path': 'root.11'}


问:
Managing Django Factories
Would there be an issue with including a factory in the model class itself? I know it's valid python but I'm not sure it would break anything in Django. My initial testing shows it works fine, but I haven't seen examples online doing it this way.</p>
```<code>class SampleModel(models.Model):
    ....
    class Factory(factory.django.DjangoModelFactory):
        ....

</code>```

答: I believe it won't break anything, but in my opinion, keeping factories together with models doesn't look good. I think it's cleaner to split them and put factories closer to tests rather than the models.</p>

Title: Managing Django Factories

Body:
Would there be an issue with including a factory in the model class itself? I know it's valid python but I'm not sure it would break anything in Django. My initial testing shows it works fine, but I haven't seen examples online doing it this way.

class SampleModel(models.Model):
    ....
    class Factory(factory.django.DjangoModelFactory):
        ....


问:
usage of string tokenizer
i have a string like this..

/home/Abcd/Pradeep/Jack.sh

/home/Abcd/Pradeep/Paul/Kill.sh

I need to take Jack.sh and Kill.sh alone from these strings. there can be many / in the string.

How to do this using strtok ?

答: You don't need strtok for this. Just use strrchr to find the last '/' character. Your filename starts one character after that.

Title: usage of string tokenizer


问:
springboot swagger3 "Failed to load remote configuration."
Spring Boot 2.6.3 with Springdoc.

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.6.5</version>
        </dependency>
```
<p>In <code>applicaton.yaml</code>, when I set the path as /v3/api-docs or remove it, that means use the default path "/v3/api-docs".
The Swagger UI page shows up correctly with the APIs
http://localhost:8080/swagger-ui/index.html</p>
<p>But I want to overite the path as below</p>
```  api-docs.path: /bus/v3/api-docs
```

then Swagger UI displays the "Failed to load remote configuration" error:

答: Perform "Empty cache and hard refresh" in your browser.</p>

Body:
Spring Boot 2.6.3 with Springdoc.

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.6.5</version>
        </dependency>

In applicaton.yaml, when I set the path as /v3/api-docs or remove it, that means use the default path "/v3/api-docs".
The Swagger UI page shows up correctly with the APIs
http://localhost:8080/swagger-ui/index.html

But I want to overite the path as below

  api-docs.path: /bus/v3/api-docs

then Swagger UI displays the "Failed to load remote configuration" error:


问:
Defining two o more functions in karate-config.js
My karate-config.js is:

```<code>function config(){
    return karate.read('classpath:' + env_file());
}

function env_file(){
    var env_file = karate.env;
    if(!env_file){
        env_file = 'local.yml';
    }
    return 'env/' + env_file;
}
</code>```

That was working fine until I upgraded my Java version to 17.

Now I'm getting the following exception:

```<code>org.graalvm.polyglot.PolyglotException: SyntaxError: Unnamed:5:0 Expected ) but found function
</code>```

Is it possible now to define two functions in the same file?

Thanks in advance.

答:
No. It was never supposed to have been supported, I'm surprised it worked.

Also refer: https://github.com/karatelabs/karate#multiple-functions-in-one-file

Body:
My karate-config.js is:

function config(){
    return karate.read('classpath:' + env_file());
}

function env_file(){
    var env_file = karate.env;
    if(!env_file){
        env_file = 'local.yml';
    }
    return 'env/' + env_file;
}

That was working fine until I upgraded my Java version to 17.

Now I'm getting the following exception:

org.graalvm.polyglot.PolyglotException: SyntaxError: Unnamed:5:0 Expected ) but found function

Is it possible now to define two functions in the same file?

Thanks in advance.


问:
Intellij IDEA: "Cannot find declaration to go to" - message in a new javascript project
I'm getting "Cannot find declaration to go to in" message when try to Ctrl + click the path of an imported module

This message shows up if the path contains "@" symbol as a root reference.

This is happening in my new project and there is no such problem in the old project.

How to fix this problem?

答:
Here is the solution:

First of all  invalidate cashes: menu File -> Invalidate Caches

After that set webpack settings

according to https://www.jetbrains.com/help/idea/using-webpack.html#edit_webpack_configuration_file

And also mark \src\ dir as a sources root directory

upd:
And also make sure that value of property "settings.editor.selected.configurable" = "preferences.pluginManager" in file /.idea/workspace.xml :

```<code><component name="PropertiesComponent">
    ...
    <property name="settings.editor.selected.configurable" value="preferences.pluginManager" />
    ...
</component>
</code>```

upd: not sure about this step...

Body:
Here is the solution:

First of all  invalidate cashes: menu File -> Invalidate Caches

After that set webpack settings

according to https://www.jetbrains.com/help/idea/using-webpack.html#edit_webpack_configuration_file

And also mark \src\ dir as a sources root directory

upd:
And also make sure that value of property "settings.editor.selected.configurable" = "preferences.pluginManager" in file /.idea/workspace.xml :

<component name="PropertiesComponent">
    ...
    <property name="settings.editor.selected.configurable" value="preferences.pluginManager" />
    ...
</component>

upd: not sure about this step...


问:
Sending calculated data from one component to another without Services
I want to send the value from one component to another, they are not related so all solutions are saying that I must use shared service to do that. But these services are using templates (if I'm right). Is there a way to do this sharing without services?

I want to send the BMI value from homepage.component.ts to result.component.ts.

homepage.component.ts:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

constructor() { }

myHeight!:number;
myWeight!:number;

bmi!:number;
  ngOnInit(): void {
  }

  onGenerate(  height:string,width:string){

    this.myHeight = +height;
    this.myHeight=Math.pow(this.myHeight/100,2);

    this.myWeight = +width;
    this.bmi=this.myWeight/this.myHeight

console.log(this.bmi); //this is the calculated value to send

  }
}
</code>```

result.component.ts:

```<code>    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-result',
      templateUrl: './result.component.html',
      styleUrls: ['./result.component.css']
    })
    export class ResultComponent implements OnInit {
      constructor() { }

//I want to get the bmi here
      ngOnInit(): void {
      }

    }
</code>```

答:
There are Two ways to communicate between unrelated components in angular:

1 - Through services, you have to understand where to inject it, in your case I think it should be injected in root, so try this with your service ( follow this tutorial to implement your service, just add my code instead of theirs )

```<code>@Injectable({
  providedIn: 'root',
})
</code>```

2 - Through a store ( a lot of boilerplate coding, to use if you have complexe states to keep synchronized through the whole app, by the way the store is basically a service )

Body:
I want to send the value from one component to another, they are not related so all solutions are saying that I must use shared service to do that. But these services are using templates (if I'm right). Is there a way to do this sharing without services?

I want to send the BMI value from homepage.component.ts to result.component.ts.

homepage.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

constructor() { }

myHeight!:number;
myWeight!:number;

bmi!:number;
  ngOnInit(): void {
  }

  onGenerate(  height:string,width:string){

    this.myHeight = +height;
    this.myHeight=Math.pow(this.myHeight/100,2);

    this.myWeight = +width;
    this.bmi=this.myWeight/this.myHeight

console.log(this.bmi); //this is the calculated value to send

  }
}

result.component.ts:

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-result',
      templateUrl: './result.component.html',
      styleUrls: ['./result.component.css']
    })
    export class ResultComponent implements OnInit {
      constructor() { }

//I want to get the bmi here
      ngOnInit(): void {
      }

    }

Body:
There are Two ways to communicate between unrelated components in angular:

1 - Through services, you have to understand where to inject it, in your case I think it should be injected in root, so try this with your service ( follow this tutorial to implement your service, just add my code instead of theirs )

@Injectable({
  providedIn: 'root',
})

2 - Through a store ( a lot of boilerplate coding, to use if you have complexe states to keep synchronized through the whole app, by the way the store is basically a service )


问:
where to put dimensions in Kimball data warehouse
I am creating a data warehouse following Kimball's theory.  So, I am aiming for the greatest amount of dimension table re-use.  In this theory, how should I physically organize the dimension tables?  I have used databases to organize my data marts (i.e., 1 mart per database, with possibly multiple fact tables per mart).  Since a given dimension can be used by multiple marts (and is what I want to aim for), I don't know where I should put my dimension tables.

For example, should I put them all under a certain schema in a certain database (e.g., schema 'Dimension' under database 'Dimensions')?  Or, perhaps, should I incrementally add them to each new database as I build out new data marts?

答:
Traditional data warehouses often use separate databases to create application boundaries based on either workload, domain or security.

As an example, a traditional SQL Server data warehouse might include a staging database, a data warehouse database, and some data mart databases. In this topology, each database operates as a workload and security boundary in the architecture.

You can create a schema for example for HR datamart and load all the related dimensions under it.

```<code>CREATE SCHEMA [HR]; --   name for the data mart HR
CREATE TABLE [HR].[DimEmployee] -- create dimensions related to data mart HR in the HR schema
(       EmployeeSK BIGINT NOT NULL
,       ...
);
</code>```

Body:
Traditional data warehouses often use separate databases to create application boundaries based on either workload, domain or security.

As an example, a traditional SQL Server data warehouse might include a staging database, a data warehouse database, and some data mart databases. In this topology, each database operates as a workload and security boundary in the architecture.

You can create a schema for example for HR datamart and load all the related dimensions under it.

CREATE SCHEMA [HR]; --   name for the data mart HR
CREATE TABLE [HR].[DimEmployee] -- create dimensions related to data mart HR in the HR schema
(       EmployeeSK BIGINT NOT NULL
,       ...
);


问:
Join 2 separate tables (not with CTE)
I need to join 2 separate tables but not with CTEs but on a regular joins. I believe I probably may need to create a view (?)

Does someone know how it can be done? I usually do it with CTEs but here I need a join.

--JOIN TABLE 1 & 2 ON LEFT_OUTER POPO# AND POITM# TO R4PO# AND R4ITM#

```<code>-- Table 1
SELECT  RIGHT(wp.[POPO#], LEN(wp.[POPO#]) - 1) AS 'MATCH_PO',
wp.[POPO#],
wp.[POITM#]

FROM [Repit].[LEVYDTA].[WHSPOHM] wh
LEFT OUTER JOIN [Repit].[LEVYDTA].[WHSPOLM] wp
ON wh.[PHPO#]=wp.[POPO#]
LEFT OUTER JOIN [Repit].[LEVYDTA].[WHSVENM] wv
ON wh.[PHVEN#]=wv.[VNVEN#]
GROUP BY wp.[POPO#], wp.[POITM#]

-- Table2
SELECT [R4PO#], [R4ITM#], MAX([R4ADAT]) AS 'MAX R4ADAT', MAX([R4QTY]) AS 'MAX R4QTY', MAX([R4COD1]) AS 'MAX R4COD1'
FROM [REPIT].[LEVYDTA].[PUR855M]
GROUP BY [R4PO#], [R4ITM#]
</code>```

答:
Your code is all over the place.

Should be something like

```<code>SELECT key1, key2, MatchPo, MaxR4ADAT, MaxR4Qty, MaxR4Cod1
FROM (
       Select wp.[POPO#] as key1,
       wp.[POITM#] as key2,
       RIGHT(wp.[POPO#], LEN(wp.[POPO#]) - 1) as MatchPo
       FROM [Repit].[LEVYDTA].[WHSPOHM] wh
       LEFT OUTER JOIN [Repit].[LEVYDTA].[WHSPOLM] wp
            ON wh.[PHPO#]=wp.[POPO#]
       LEFT OUTER JOIN [Repit].[LEVYDTA].[WHSVENM] wv
            ON wh.[PHVEN#]=wv.[VNVEN#]
       GROUP BY wp.[POPO#], wp.[POITM#] ) as Data1
INNER JOIN
      (SELECT [R4PO#] as key1, [R4ITM#] as key2,
         MAX([R4ADAT]) AS MaxR4ADAT,
         MAX([R4QTY]) AS MaxR4Qty,
         MAX([R4COD1]) AS MaxR4Cod1
       FROM [REPIT].[LEVYDTA].[PUR855M]
       GROUP BY [R4PO#], [R4ITM#]
      ) as Data2
    ON Data1.key1 = Data2.key1 AND Data1.key2 = Data2.key2
</code>```

Title: Join 2 separate tables (not with CTE)

Body:
I need to join 2 separate tables but not with CTEs but on a regular joins. I believe I probably may need to create a view (?)

Does someone know how it can be done? I usually do it with CTEs but here I need a join.

--JOIN TABLE 1 & 2 ON LEFT_OUTER POPO# AND POITM# TO R4PO# AND R4ITM#

-- Table 1
SELECT  RIGHT(wp.[POPO#], LEN(wp.[POPO#]) - 1) AS 'MATCH_PO',
wp.[POPO#],
wp.[POITM#]

FROM [Repit].[LEVYDTA].[WHSPOHM] wh
LEFT OUTER JOIN [Repit].[LEVYDTA].[WHSPOLM] wp
ON wh.[PHPO#]=wp.[POPO#]
LEFT OUTER JOIN [Repit].[LEVYDTA].[WHSVENM] wv
ON wh.[PHVEN#]=wv.[VNVEN#]
GROUP BY wp.[POPO#], wp.[POITM#]

-- Table2
SELECT [R4PO#], [R4ITM#], MAX([R4ADAT]) AS 'MAX R4ADAT', MAX([R4QTY]) AS 'MAX R4QTY', MAX([R4COD1]) AS 'MAX R4COD1'
FROM [REPIT].[LEVYDTA].[PUR855M]
GROUP BY [R4PO#], [R4ITM#]

Body:
Your code is all over the place.

Should be something like

SELECT key1, key2, MatchPo, MaxR4ADAT, MaxR4Qty, MaxR4Cod1
FROM (
       Select wp.[POPO#] as key1,
       wp.[POITM#] as key2,
       RIGHT(wp.[POPO#], LEN(wp.[POPO#]) - 1) as MatchPo
       FROM [Repit].[LEVYDTA].[WHSPOHM] wh
       LEFT OUTER JOIN [Repit].[LEVYDTA].[WHSPOLM] wp
            ON wh.[PHPO#]=wp.[POPO#]
       LEFT OUTER JOIN [Repit].[LEVYDTA].[WHSVENM] wv
            ON wh.[PHVEN#]=wv.[VNVEN#]
       GROUP BY wp.[POPO#], wp.[POITM#] ) as Data1
INNER JOIN
      (SELECT [R4PO#] as key1, [R4ITM#] as key2,
         MAX([R4ADAT]) AS MaxR4ADAT,
         MAX([R4QTY]) AS MaxR4Qty,
         MAX([R4COD1]) AS MaxR4Cod1
       FROM [REPIT].[LEVYDTA].[PUR855M]
       GROUP BY [R4PO#], [R4ITM#]
      ) as Data2
    ON Data1.key1 = Data2.key1 AND Data1.key2 = Data2.key2


问:
How can we get all usernames list only not user objects with django ORM
I want to know that how can we get list of required field data from django models. In my case i want to get all usernames from users models.

```<code>receivers = User.objects.all()
</code>```

this return all users objects. I want to get usernames directly. Something like below:

```<code>receivers = User.objects.all(username)
output:
["ahmed","dummy","hamza","sentence"]
</code>```

in sql query looks like below:

```<code>SELECT username from USER
</code>```

答:
```<code>receivers=User.objects.values_list('username', flat=True)
</code>```

Try this code, you can read more about this in django offical documents

Body:
I want to know that how can we get list of required field data from django models. In my case i want to get all usernames from users models.

receivers = User.objects.all()

this return all users objects. I want to get usernames directly. Something like below:

receivers = User.objects.all(username)
output:
["ahmed","dummy","hamza","sentence"]

in sql query looks like below:

SELECT username from USER

Body:
receivers=User.objects.values_list('username', flat=True)

Try this code, you can read more about this in django offical documents


问:
memset sets some elements to *almost* zero or nan
I have the line memset(C, 0, N*M);, where C is a matrix of doubles. (I am using WSL.)

However if I look in gdb, certain elements in the matrix are set to either -nan(0xffffffffffff8) and others are set to for example 9.0096750001652956e-314.

The first one doesn't give any errors but a += doesn't seem to change anything (or at the very least doesn't seem to make the nan thing disappear), while the second is an issue if the element is not changed or only has += 0, as the comparison if (0 == C[i][j]) then fails.

If I set the values to 0 manually, then these issues do not arise at all.

Is this a WSL thing, or is there something about memset that I do not understand?

答:
You do not fully initialize the matrix: memset() expects a number of bytes. Assuming the matrix layout is linear, either 1D or 2D, you should clear sizeof(double) * N * M bytes.

If your matrix is defined as a 2D array, you could write:

```<code>#define N 10
#define M 20
        double C[N][M];
        memset(C, 0, sizeof C);
</code>```

If the matrix is received as a function argument, you actually get a pointer, so you must be more careful:

```<code>void clear_matrix(double C[N][M]) {
    memset(C, 0, sizeof(*C) * N);
}
</code>```

or possibly more readable:

```<code>void clear_matrix(double C[N][M]) {
    memset(C, 0, sizeof(C[0][0]) * N * M);
}
</code>```

or simply, as suggested by Lundin, but likely to break if the matrix element type changes:

```<code>void clear_matrix(double C[N][M]) {
    memset(C, 0, sizeof(double[N][M]);
}
</code>```

Note however that memset() will clear the matrix data to all bits zero, which sets the double values to +0.0 if the system uses IEEE-754 representation, but is not fully portable. A portable version would use a nested loop and a good compiler will generate the same memset call or inline code if appropriate for the target system:

```<code>#include <stddef.h>

#define N 10
#define M 20

void clear_matrix(double C[N][M]) {
    for (size_t i = 0; i < N; i++) {
        for (size_t j = 0; j < M; j++) {
             C[i][j] = 0.0;
        }
    }
}
</code>```

Body:
You do not fully initialize the matrix: memset() expects a number of bytes. Assuming the matrix layout is linear, either 1D or 2D, you should clear sizeof(double) * N * M bytes.

If your matrix is defined as a 2D array, you could write:

#define N 10
#define M 20
        double C[N][M];
        memset(C, 0, sizeof C);

If the matrix is received as a function argument, you actually get a pointer, so you must be more careful:

void clear_matrix(double C[N][M]) {
    memset(C, 0, sizeof(*C) * N);
}

or possibly more readable:

void clear_matrix(double C[N][M]) {
    memset(C, 0, sizeof(C[0][0]) * N * M);
}

or simply, as suggested by Lundin, but likely to break if the matrix element type changes:

void clear_matrix(double C[N][M]) {
    memset(C, 0, sizeof(double[N][M]);
}

Note however that memset() will clear the matrix data to all bits zero, which sets the double values to +0.0 if the system uses IEEE-754 representation, but is not fully portable. A portable version would use a nested loop and a good compiler will generate the same memset call or inline code if appropriate for the target system:

#include <stddef.h>

#define N 10
#define M 20

void clear_matrix(double C[N][M]) {
    for (size_t i = 0; i < N; i++) {
        for (size_t j = 0; j < M; j++) {
             C[i][j] = 0.0;
        }
    }
}


问:
Error executing ruby script in docker environment
I have a script that is supposed to just check when my elasticsearch instance/container is up and running. But there appears to be some issue with the calls, as I get the error:

TypeError: Failed to open TCP connection to : (no implicit conversion of nil into String)

Here is the ruby code:

class AwaitEs
  def self.call(uri)
    AwaitEs.new(uri).wait

  def initialize(uri)
    @uri = URI.parse("#{uri}/_cluster/health")

  def wait
    status = get_status
    until VALID_STATUS.include? status
      puts 'Still waiting ...'
      sleep 5
      status = get_status

  def get_status
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']

  private

  attr_reader :uri

  VALID_STATUS = %w[yellow green].freeze

AwaitEs.call ARGV[0]
```
<p>The error occurs on the line <code>res = http.request(request)</code>. It appears that there is no host or port information. But when I check <code>uri.host=elasticsearch</code> and <code>uri.port=9200</code>, where <code>elasticsearch</code> is the name of the docker service for ES. When I change the host to <code>localhost</code>, the error disappears, but instead I get Connection refused instead (because the <code>waiter</code> docker does not see the elasticsearch docker on localhost.</p>
<p>The docker container calls the ruby script using a shell script named <code>start.sh</code></p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/sh
for file in `ls ./??_*.rb`; do
  ruby $file `http://elasticsearch:9200`
done
</code>```

The docker-compose.yml:

volumes:
  es_data: {}

services:
  elasticsearch:
    image: elasticsearch:5.4.3
    ports: ['9200:9200', '9300:9300']
    volumes:
      - es_data:/usr/share/elsticsearch/data
  waiter:
    build:
      context: ./waiter/
```
<p>Finally the dockerfile for waiter:</p>
```FROM jruby:9.1.15-alpine
ADD ./ /app/
WORKDIR /app
CMD bash -c "./start.sh"
```

When I run this, I get the error:

答:
You need to reference uri correctly in the get_status method as an instance variable or pass it along with the get_status method.

Change the following:

```<code>def get_status
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']
</code>```

To use an instance variable @uri, like this:

```<code>def get_status
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(@uri.host, @uri.port)
    request = Net::HTTP::Get.new(@uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']
</code>```

Or you can pass it along as a method parameter. In that case, change this:

```<code> def wait
    status = get_status
    until VALID_STATUS.include? status
      puts 'Still waiting ...'
      sleep 5
      status = get_status

  def get_status
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']
</code>```

to this:

```<code> def wait
    status = get_status(@uri)
    until VALID_STATUS.include? status
      puts 'Still waiting ...'
      sleep 5
      status = get_status(@uri)

  def get_status(uri)
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']
</code>```

Body:
I have a script that is supposed to just check when my elasticsearch instance/container is up and running. But there appears to be some issue with the calls, as I get the error:

TypeError: Failed to open TCP connection to : (no implicit conversion of nil into String)

Here is the ruby code:

class AwaitEs
  def self.call(uri)
    AwaitEs.new(uri).wait

  def initialize(uri)
    @uri = URI.parse("#{uri}/_cluster/health")

  def wait
    status = get_status
    until VALID_STATUS.include? status
      puts 'Still waiting ...'
      sleep 5
      status = get_status

  def get_status
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']

  private

  attr_reader :uri

  VALID_STATUS = %w[yellow green].freeze

AwaitEs.call ARGV[0]

The error occurs on the line res = http.request(request). It appears that there is no host or port information. But when I check uri.host=elasticsearch and uri.port=9200, where elasticsearch is the name of the docker service for ES. When I change the host to localhost, the error disappears, but instead I get Connection refused instead (because the waiter docker does not see the elasticsearch docker on localhost.

The docker container calls the ruby script using a shell script named start.sh

#!/bin/sh
for file in `ls ./??_*.rb`; do
  ruby $file `http://elasticsearch:9200`
done

The docker-compose.yml:

volumes:
  es_data: {}

services:
  elasticsearch:
    image: elasticsearch:5.4.3
    ports: ['9200:9200', '9300:9300']
    volumes:
      - es_data:/usr/share/elsticsearch/data
  waiter:
    build:
      context: ./waiter/

Finally the dockerfile for waiter:

FROM jruby:9.1.15-alpine
ADD ./ /app/
WORKDIR /app
CMD bash -c "./start.sh"

When I run this, I get the error:

Body:
You need to reference uri correctly in the get_status method as an instance variable or pass it along with the get_status method.

Change the following:

def get_status
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']

To use an instance variable @uri, like this:

def get_status
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(@uri.host, @uri.port)
    request = Net::HTTP::Get.new(@uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']

Or you can pass it along as a method parameter. In that case, change this:

 def wait
    status = get_status
    until VALID_STATUS.include? status
      puts 'Still waiting ...'
      sleep 5
      status = get_status

  def get_status
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']

to this:

 def wait
    status = get_status(@uri)
    until VALID_STATUS.include? status
      puts 'Still waiting ...'
      sleep 5
      status = get_status(@uri)

  def get_status(uri)
    HEADER = {'Content-Type' => 'application/json' }.freeze
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri, HEADER)

    begin
      res = http.request(request)
    rescue Errno:ECONNREFUSED
      return 'red'
    end

    result = JSON.parse(response.body)
    result['status']


问:
which library is linked when i am using stdio.h,conio.h
see when ever we are going to use any library at that time we include one .h file in our application & at compiling that application we link that library. if  that library is .so then link at run time.

Now my question is in any system when i am including basic header file like stdio.h conio.h string.h at that time which library is going to link with my program.?

Is it static or dynamic.?

how can i install it in ma system.? any documentation for that?

we are not linking that library still does that library automatically link.?

答: libc.so is the standard library (dynamically linked) of linux (currently libc.so.6)


问:
Subset sum problem for a possible closest value to the target sum in Python for a really big list
I know this problem may have been asked by many. My challenge is that my list is long in length (say 100+) and my target may also be big. The recursive algorithm takes 10 minutes to complete. I need any one subset that makes it closest to the target-sum

My Code

```<code>combination_dict = {}

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)

    if s == target:
        print("sum({})={}".format(partial, target))
        return
    if s >= target:
        partial.pop()
        combination_dict[sum(partial)] = partial
        return

    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])

if __name__ == "__main__":
lst = [100, 100, 100, 100, 100, 100, 100] #my actual list is really long len=100(max)
tgt = 434
subset_sum(lst, tgt)
closest_sum = max([i for i in combination_dict.keys()])
print("Closest possible sum={} and the combination is ={}".format(closest_sum, combination_dict[closest_sum]))
</code>```

If my list length is > 20, it is stuck. I understand this has a time complexity of O(2^n)- but can someone please help me get this optimized to get my result in less than 30 seconds.
My list can have floats. And so be the target-sum.

答:
You can use integer linear programming where each variable is a binary that corresponds to a number and represents whether that number is included in the result. It solves two problems, the first approaching the target value from below and the second from above and then takes the best solution. The following is an example implementation using PuLP:

import numpy as np
from pulp import LpMaximize, LpMinimize, LpProblem, lpSum, LpVariable

rng = np.random.default_rng(seed=0)
numbers = rng.integers(1, 10**6, size=10**4)
target = int(numbers.mean() * rng.normal(loc=1, scale=0.1))

indices = range(len(numbers))
variables = LpVariable.dicts("Choice", indices, cat="Binary")

leq_prob = LpProblem('leq', LpMaximize)
geq_prob = LpProblem('geq', LpMinimize)

leq_prob += lpSum([variables[i]*numbers[i] for i in indices]) <= target
leq_prob += lpSum([variables[i]*numbers[i] for i in indices])

geq_prob += lpSum([variables[i]*numbers[i] for i in indices]) >= target
geq_prob += lpSum([variables[i]*numbers[i] for i in indices])

leq_prob.solve()
leq_choices = [numbers[i] for i in indices if variables[i].value() == 1]

if sum(leq_choices) == target:
    solution = leq_choices
else:
    geq_prob.solve()
    geq_choices = [numbers[i] for i in indices if variables[i].value() == 1]

    solution = (
        leq_choices
        if target-sum(leq_choices) <= sum(geq_choices)-target
        else geq_choices
    )

print(f'Solution: {solution}')
print(f'Sum: {sum(solution)} (target: {target})')
```

Body:
I know this problem may have been asked by many. My challenge is that my list is long in length (say 100+) and my target may also be big. The recursive algorithm takes 10 minutes to complete. I need any one subset that makes it closest to the target-sum

My Code

combination_dict = {}

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)

    if s == target:
        print("sum({})={}".format(partial, target))
        return
    if s >= target:
        partial.pop()
        combination_dict[sum(partial)] = partial
        return

    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])

if __name__ == "__main__":
lst = [100, 100, 100, 100, 100, 100, 100] #my actual list is really long len=100(max)
tgt = 434
subset_sum(lst, tgt)
closest_sum = max([i for i in combination_dict.keys()])
print("Closest possible sum={} and the combination is ={}".format(closest_sum, combination_dict[closest_sum]))

If my list length is > 20, it is stuck. I understand this has a time complexity of O(2^n)- but can someone please help me get this optimized to get my result in less than 30 seconds.
My list can have floats. And so be the target-sum.


问:
Using single cell in loop as trigger to to copy multiple ranges VBA
The macro is working with hard coded inputs but I need loops for debugging and future growth.  I don't know the best way to set this up.

Range("b3:b8:) are the cells I would like to loop over.

If cell.value = 1 then

Set var1 = range("a3:aq3")  (* This range always has the same row number as cell in loop*)

Set var2 = range("a9:aq9")  (*This range always 6 greater than row of cell in loop.)

End if

Next cell
Thanks

答:
Have you tried using a for loop?

Eg:

```<code>For Each Cell in Range("B3:B8")
  If Cell.Value = 1 Then
    Set var1 = range("a3:aq3")
  Else
    Set var2 = range("a9:aq9")
  End If
Next Cell
</code>```

Body:
Have you tried using a for loop?

Eg:

For Each Cell in Range("B3:B8")
  If Cell.Value = 1 Then
    Set var1 = range("a3:aq3")
  Else
    Set var2 = range("a9:aq9")
  End If
Next Cell


问:
How to convert images into numpy array quickly?
To train the image classification model I'm loading input data as NumPy array, I deal with thousands of images. Currently, I'm looping through each image and converting it into a NumPy array as shown below.

```<code>import glob
import cv2
import numpy as np

tem_arr_list = []
from time import time
images_list = glob.glob(r'C:\Datasets\catvsdogs\cat\*.jpg')
start = time()
for idx, image_path in enumerate(images_list):
    start = time()
    img = cv2.imread(image_path)
    temp_arr = np.array(cv2.imread(image_path))
#     print(temp_arr.shape)
    tem_arr_list.append(temp_arr)
print("Total time taken {}".format (time() - start))
</code>```

running this method takes a lot of time when data is huge. So I tried using list comprehension as below

```<code>tem_arr_list = [np.array(cv2.imread(image_path)) for image_path in images_list]
</code>```

which is slight quicker than looping but not fastest

I'm looking any other way to reduce the time to do this operation . Any help or suggestion on this will be appreciated.

答:
Use the multiprocessing pool to load data parallely. In my PC the cpus count is 16. I tried loading 100 images and below you could see the time taken.

```<code>import multiprocessing
import cv2
import glob
from time import time

def load_image(image_path):
    return cv2.imread(image_path)

if __name__ == '__main__':
    image_path_list = glob.glob('*.png')

    try:
        cpus = multiprocessing.cpu_count()
    except NotImplementedError:
        cpus = 2   # arbitrary default

    pool = multiprocessing.Pool(processes=cpus)

    start = time()
    images = pool.map(load_image, image_path_list)
    print("Total time taken using multiprocessing pool {} seconds".format (time() - start))

    images = []
    start = time()
    for image_path in image_path_list:
        images.append(load_image(image_path))
    print("Total time taken using for loop {} seconds".format (time() - start))

    start = time()
    images = [load_image(image_path) for image_path in image_path_list]
    print("Total time taken using list comprehension {} seconds".format (time() - start))
</code>```

Output:

```<code>Total time taken using multiprocessing pool 0.2922379970550537 seconds
Total time taken using for loop 1.4935636520385742 seconds
Total time taken using list comprehension 1.4925990104675293 seconds
</code>```

Body:
To train the image classification model I'm loading input data as NumPy array, I deal with thousands of images. Currently, I'm looping through each image and converting it into a NumPy array as shown below.

import glob
import cv2
import numpy as np

tem_arr_list = []
from time import time
images_list = glob.glob(r'C:\Datasets\catvsdogs\cat\*.jpg')
start = time()
for idx, image_path in enumerate(images_list):
    start = time()
    img = cv2.imread(image_path)
    temp_arr = np.array(cv2.imread(image_path))
#     print(temp_arr.shape)
    tem_arr_list.append(temp_arr)
print("Total time taken {}".format (time() - start))

running this method takes a lot of time when data is huge. So I tried using list comprehension as below

tem_arr_list = [np.array(cv2.imread(image_path)) for image_path in images_list]

which is slight quicker than looping but not fastest

I'm looking any other way to reduce the time to do this operation . Any help or suggestion on this will be appreciated.

Body:
Use the multiprocessing pool to load data parallely. In my PC the cpus count is 16. I tried loading 100 images and below you could see the time taken.

import multiprocessing
import cv2
import glob
from time import time

def load_image(image_path):
    return cv2.imread(image_path)

if __name__ == '__main__':
    image_path_list = glob.glob('*.png')

    try:
        cpus = multiprocessing.cpu_count()
    except NotImplementedError:
        cpus = 2   # arbitrary default

    pool = multiprocessing.Pool(processes=cpus)

    start = time()
    images = pool.map(load_image, image_path_list)
    print("Total time taken using multiprocessing pool {} seconds".format (time() - start))

    images = []
    start = time()
    for image_path in image_path_list:
        images.append(load_image(image_path))
    print("Total time taken using for loop {} seconds".format (time() - start))

    start = time()
    images = [load_image(image_path) for image_path in image_path_list]
    print("Total time taken using list comprehension {} seconds".format (time() - start))

Output:

Total time taken using multiprocessing pool 0.2922379970550537 seconds
Total time taken using for loop 1.4935636520385742 seconds
Total time taken using list comprehension 1.4925990104675293 seconds


问:
Solidity version to learn
I am confused about the different solidity versions in each course, 0.4 and 0.5, whereas the current version is 0.8.
The question is should I search to find the course that works with the latest solidity version 0.8? And is Solidity 0.4 or 0.5 outdated?
I can see something about the solidity version modifier, is that practical?</p>

答:
when u will open this link: https://docs.soliditylang.org, it will automatically redirect you to solidity latest version docs.

also, you can read what is updated in solidity newer versions here: https://github.com/ethereum/solidity/releases

If you prefer youtube, then search "solidity tutorials" and filter videos that are uploaded this month. link: youtube/solidity tutorials/uploaded this month

Title: Solidity version to learn


问:
json string format done differently
I have 2 lists - dates and weekdays

```<code>>>> dates
['2022-02-08', '2022-02-09', '2022-02-10', '2022-02-11', '2022-02-12', '2022-02-13', '2022-02-14', '2022-02-15']
>>> weekdays
['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
</code>```

I want to create a json object that looks like this (for eg) for each element in dates.

```<code>myjson = {"label": "Tuesday-2022-02-08", "value": "/inform_date{\"date_list\": \"2022-02-08\"}"}
</code>```

Basically I want to run a loop where myjson looks like what is given above.

```<code>data = []
for i in range(len(dates)):
  myjson = {"label": "{0}-{1}".format(weekdays[i], dates[i]), "value": "/inform_date{\"date_list\": \"{}\"}".format(dates[i])}
  data.append(myjson)
</code>```

but I get an error when I run the above for loop.

What is the correct way to build myjson so that it looks just like shown in the example above?

答:
Your second format string has 'spare' braces which need to be escaped:

myjson = {"label": "{0}-{1}".format(weekdays[i], dates[i]), "value": "/inform_date{{\"date_list\": \"{}\"}}".format(dates[i])}
```

Title: json string format done differently

Body:
I have 2 lists - dates and weekdays

>>> dates
['2022-02-08', '2022-02-09', '2022-02-10', '2022-02-11', '2022-02-12', '2022-02-13', '2022-02-14', '2022-02-15']
>>> weekdays
['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

I want to create a json object that looks like this (for eg) for each element in dates.

myjson = {"label": "Tuesday-2022-02-08", "value": "/inform_date{\"date_list\": \"2022-02-08\"}"}

Basically I want to run a loop where myjson looks like what is given above.

data = []
for i in range(len(dates)):
  myjson = {"label": "{0}-{1}".format(weekdays[i], dates[i]), "value": "/inform_date{\"date_list\": \"{}\"}".format(dates[i])}
  data.append(myjson)

but I get an error when I run the above for loop.

What is the correct way to build myjson so that it looks just like shown in the example above?


问:
gitpython: determine the remote associated to a (tracking) branch
I would like to determine the remote branch, that is associated to the current (tracking branch)

The solution, that I found is working, but it feels strange, that I have to parse the configuration to achieve what I want.

Is there any more elegant solution?

```<code>repo = git.Repo(path)
branch = repo.active_branch
cfg =  branch.config_reader().config
# hand crafting the section name in next line just seems clumsy
remote= cfg.get(f'branch "{branch.name}"', "remote")
</code>```

答:
Perhaps git.Head.tracking_branch() and git.Reference.remote_name can give you what you're looking for?

e.g.

repo = git.Repo(path)
branch = repo.active_branch
remote_name = branch.tracking_branch().remote_name
```

Body:
I would like to determine the remote branch, that is associated to the current (tracking branch)

The solution, that I found is working, but it feels strange, that I have to parse the configuration to achieve what I want.

Is there any more elegant solution?

repo = git.Repo(path)
branch = repo.active_branch
cfg =  branch.config_reader().config
# hand crafting the section name in next line just seems clumsy
remote= cfg.get(f'branch "{branch.name}"', "remote")


问:
how to rearrange bootstrap columns in order on mobile view
how to rearrange bootstrap columns? i have a 2 column layout on desktop view

this is what i have in desktop view

im trying to achieve this layout on mobile view, is this possible?

答:
To enable this you will want to have each div include the following classes:

```<code><div class="col-lg-6 col-xs-12"></div>
</code>```

Look into the bootstrap grid system for more info.

Body:
To enable this you will want to have each div include the following classes:

<div class="col-lg-6 col-xs-12"></div>

Look into the bootstrap grid system for more info.