问:
How to fix the Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path: C:Users\mukes\AppData\Local\Android\Sdk error?
I am trying to use expo to create a react native app. This is my first time using expo. When I tried to run expo using android, it gives me back the following error:

```<code>    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    › Opening exp://192.168.0.142:19000 on SM_A536E
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
</code>```

I have set the environment variable on path as ANDROID_HOME pointing to C:Users\mukes\AppData\Local\Android\Sdk.

I tried to use Android because the normal way of running it using the app doesn't seem to work on my laptop either. When I try to use tunnel, I am met with this error instead:

```<code>    Error starting ngrok: The system cannot find the path specified.
</code>```

Could someone please tell me what I'm doing wrong? I have already spent like 2 days with this problem. Any help is very much appreciated. Thanks.

Body:
I am trying to use expo to create a react native app. This is my first time using expo. When I tried to run expo using android, it gives me back the following error:

    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    › Opening exp://192.168.0.142:19000 on SM_A536E
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk
    Failed to resolve the Android SDK path. ANDROID_HOME is set to a non-existing path:
    C:Users\mukes\AppData\Local\Android\Sdk

I have set the environment variable on path as ANDROID_HOME pointing to C:Users\mukes\AppData\Local\Android\Sdk.

I tried to use Android because the normal way of running it using the app doesn't seem to work on my laptop either. When I try to use tunnel, I am met with this error instead:

    Error starting ngrok: The system cannot find the path specified.

Could someone please tell me what I'm doing wrong? I have already spent like 2 days with this problem. Any help is very much appreciated. Thanks.


来源: stackexchange

问:
How can I make reservation control?
```<code>CREATE TABLE member(
    member_id number(11) NOT NULL PRIMARY KEY,
    member_name varchar2(255) NOT NULL,
    member_surname varchar2(255) NOT NULL,
    gender varchar2(30) NOT NULL,
    birthdate DATE,
    phone varchar2(11),
    mail varchar2(255) NOT NULL,
    member_password varchar2(255) NOT NULL,
    address varchar2(255) not null,
    status number(1),
    role_id number(10) NOT NULL
);
</code>```
```<code>CREATE TABLE reservation(
    reservation_id number(10) NOT NULL PRIMARY KEY,
    member_id number(11) NOT NULL,
    item_id number(11) NOT NULL,
    start_date DATE,
    end_date DATE,
    status number(1),
    isReserved number(1) DEFAULT 0
);
</code>```
```<code>CREATE TABLE item(
    item_id number(11) NOT NULL PRIMARY KEY,
    member_id number(11) ,
    publish_date DATE,
    is_occupied NUMBER(1) NOT NULL,
    publisher_id number(11) NOT NULL

);
</code>```

MY TRIGGER WORKS FOR NOW ;

```<code>CREATE OR REPLACE TRIGGER PreInsertreservation
BEFORE INSERT ON reservation
FOR EACH ROW
BEGIN

    SELECT status INTO :NEW.status
    FROM member
    WHERE member_id = :NEW.member_id;

    IF :NEW.status != 1 THEN
        RAISE_APPLICATION_ERROR(-20001, 'Error: Member has an inactive status MEMBER . STATUS = 0 ');
    END IF;

    SELECT member_id INTO :NEW.member_id
    FROM item
    WHERE item.member_id = :NEW.member_id;

    IF :NEW.member_id IS NOT NULL THEN
        RAISE_APPLICATION_ERROR(-20001, 'Error: MEMBER NOT NULL ');
    END IF;

    IF :new.start_date >= :new.end_date OR (:new.end_date - :new.start_date)>15 THEN
        RAISE_APPLICATION_ERROR(-20001, 'Error: Start date must be before end date');
    END IF;

    SELECT isReserved INTO :New.isReserved
    FROM reservation
    Where reservation_id=:NEW.reservation_id;

    IF :NEW.isReserved!=0 THEN
        RAISE_APPLICATION_ERROR(-200001,'Error : The item is already taken another member');
    END IF;
END;
</code>```

If the user reserves an item, the is reserved field will be 1. However, if another user wants to reserve that item and it should not be done between the same dates. Also, if the item is reserved and the person who reserved the item has given up on purchasing the item, after 15 days, the reserved part is 0 again and I need to make it bookable by other users.

ContentLicense: CC BY-SA 4.0

Title: How can I make reservation control?

Body:
CREATE TABLE member(
    member_id number(11) NOT NULL PRIMARY KEY,
    member_name varchar2(255) NOT NULL,
    member_surname varchar2(255) NOT NULL,
    gender varchar2(30) NOT NULL,
    birthdate DATE,
    phone varchar2(11),
    mail varchar2(255) NOT NULL,
    member_password varchar2(255) NOT NULL,
    address varchar2(255) not null,
    status number(1),
    role_id number(10) NOT NULL
);

CREATE TABLE reservation(
    reservation_id number(10) NOT NULL PRIMARY KEY,
    member_id number(11) NOT NULL,
    item_id number(11) NOT NULL,
    start_date DATE,
    end_date DATE,
    status number(1),
    isReserved number(1) DEFAULT 0
);

CREATE TABLE item(
    item_id number(11) NOT NULL PRIMARY KEY,
    member_id number(11) ,
    publish_date DATE,
    is_occupied NUMBER(1) NOT NULL,
    publisher_id number(11) NOT NULL

);

MY TRIGGER WORKS FOR NOW ;

CREATE OR REPLACE TRIGGER PreInsertreservation
BEFORE INSERT ON reservation
FOR EACH ROW
BEGIN

    SELECT status INTO :NEW.status
    FROM member
    WHERE member_id = :NEW.member_id;

    IF :NEW.status != 1 THEN
        RAISE_APPLICATION_ERROR(-20001, 'Error: Member has an inactive status MEMBER . STATUS = 0 ');
    END IF;

    SELECT member_id INTO :NEW.member_id
    FROM item
    WHERE item.member_id = :NEW.member_id;

    IF :NEW.member_id IS NOT NULL THEN
        RAISE_APPLICATION_ERROR(-20001, 'Error: MEMBER NOT NULL ');
    END IF;

    IF :new.start_date >= :new.end_date OR (:new.end_date - :new.start_date)>15 THEN
        RAISE_APPLICATION_ERROR(-20001, 'Error: Start date must be before end date');
    END IF;

    SELECT isReserved INTO :New.isReserved
    FROM reservation
    Where reservation_id=:NEW.reservation_id;

    IF :NEW.isReserved!=0 THEN
        RAISE_APPLICATION_ERROR(-200001,'Error : The item is already taken another member');
    END IF;
END;

If the user reserves an item, the is reserved field will be 1. However, if another user wants to reserve that item and it should not be done between the same dates. Also, if the item is reserved and the person who reserved the item has given up on purchasing the item, after 15 days, the reserved part is 0 again and I need to make it bookable by other users.


问:
MongoDB (mongoose) Nested Object(s) Search against elements in array
I have a collection of cards with some 21000 documents like the one below - each card document can have multiple versions (refer to the "sub_cat" field which is an array for the versions and relevant details). I also have the unique version IDs combined into a single string in the field named "versionsAll" at the end.

```<code>    {
    "_id":"f63b9c2cd8a77c57015b7d8ada75eb51",
    "name":"Bulbasaur",
    "category":"Pokemon",
    "set_name":"Topsun",
    "card_number":"1",
    "releaseYear":{"$numberInt":"1995"},
    "language":"Japanese",
    "sub_cat": [
        {"card_id":"67127cb5-38cc-4f6d-95da-19a0416fc2f1",
         "image":"<image link here>",
         "sub_category":"Blue Back",
         "last_sold":{"$date":{"$numberLong":"1666656000000"}}}
        ],
    "releaseYear_search":"1995",
    "datecreated":{"$date":{"$numberLong":"1670976000000"}},
    "lastmodified":{"$date":{"$numberLong":"1670976000000"}},
    "featured":false,
    "is_deleted":false,
    "popularity":{"$numberInt":"59"},
    "versionsAll":"67127cb5-38cc-4f6d-95da-19a0416fc2f1"
}
</code>```

I need to query the cards collection to get cards in return for specified version IDs supplied in an array. I have tried using $elemMatch, $in, with the "sub_cat" array and regex with the "versionsAll" field but either way returns me all 21k cards and not just the ones I'm looking for. The same query formats do however work on mongodb atlas.

Here is my API written in nodejs express making use of the mongoose library:

Using Regex

```<code>router.get('/popularSales', (req, res) => {
  salesModel.find({}, {card_id: true, psa_window: true, bgs_window: true, cgc_window: true}).sort({psa_window: -1}).limit(20)
  .then(versionsAll => {
    versionsArr = []
    versionsAll.map(version => versionsArr.push(version.card_id))
    regex = versionsArr.map(function (version) {return new RegExp(("^" + version + "$", "i"))})

    cardModel.find({versionsAll: {$in: regex}})
    .then(cards => {
      console.log(versionsAll.length, cards.length)
      return res.status(200).json({
        error: false
      })
    })
    .catch(error => {
      return res.status(200).json({
        error: true,
        message: error.message
      })
    })

  })
  .catch(e => {
    return res.status(200).json({
      error: true,
      message: e.message
    })
  })
})
</code>```

Using $elemMatch and $in

```<code>router.get('/popularSales', (req, res) => {
  salesModel.find({}, {card_id: true, psa_window: true, bgs_window: true, cgc_window: true}).sort({psa_window: -1}).limit(20)
  .then(versionsAll => {
    versionsArr = []
    versionsAll.map(version => versionsArr.push(version.card_id))

    cardModel.find({"sub_cat": {$elemMatch: {"card_id": {$in: versionsArr}}}})
    .then(cards => {
      console.log(versionsAll.length, cards.length)
      return res.status(200).json({
        error: false
      })
    })
    .catch(error => {
      return res.status(200).json({
        error: true,
        message: error.message
      })
    })

  })
  .catch(e => {
    return res.status(200).json({
      error: true,
      message: e.message
    })
  })
})
</code>```

Body:
I have a collection of cards with some 21000 documents like the one below - each card document can have multiple versions (refer to the "sub_cat" field which is an array for the versions and relevant details). I also have the unique version IDs combined into a single string in the field named "versionsAll" at the end.

    {
    "_id":"f63b9c2cd8a77c57015b7d8ada75eb51",
    "name":"Bulbasaur",
    "category":"Pokemon",
    "set_name":"Topsun",
    "card_number":"1",
    "releaseYear":{"$numberInt":"1995"},
    "language":"Japanese",
    "sub_cat": [
        {"card_id":"67127cb5-38cc-4f6d-95da-19a0416fc2f1",
         "image":"<image link here>",
         "sub_category":"Blue Back",
         "last_sold":{"$date":{"$numberLong":"1666656000000"}}}
        ],
    "releaseYear_search":"1995",
    "datecreated":{"$date":{"$numberLong":"1670976000000"}},
    "lastmodified":{"$date":{"$numberLong":"1670976000000"}},
    "featured":false,
    "is_deleted":false,
    "popularity":{"$numberInt":"59"},
    "versionsAll":"67127cb5-38cc-4f6d-95da-19a0416fc2f1"
}

I need to query the cards collection to get cards in return for specified version IDs supplied in an array. I have tried using $elemMatch, $in, with the "sub_cat" array and regex with the "versionsAll" field but either way returns me all 21k cards and not just the ones I'm looking for. The same query formats do however work on mongodb atlas.

Here is my API written in nodejs express making use of the mongoose library:

Using Regex

router.get('/popularSales', (req, res) => {
  salesModel.find({}, {card_id: true, psa_window: true, bgs_window: true, cgc_window: true}).sort({psa_window: -1}).limit(20)
  .then(versionsAll => {
    versionsArr = []
    versionsAll.map(version => versionsArr.push(version.card_id))
    regex = versionsArr.map(function (version) {return new RegExp(("^" + version + "$", "i"))})

    cardModel.find({versionsAll: {$in: regex}})
    .then(cards => {
      console.log(versionsAll.length, cards.length)
      return res.status(200).json({
        error: false
      })
    })
    .catch(error => {
      return res.status(200).json({
        error: true,
        message: error.message
      })
    })

  })
  .catch(e => {
    return res.status(200).json({
      error: true,
      message: e.message
    })
  })
})

Using $elemMatch and $in

router.get('/popularSales', (req, res) => {
  salesModel.find({}, {card_id: true, psa_window: true, bgs_window: true, cgc_window: true}).sort({psa_window: -1}).limit(20)
  .then(versionsAll => {
    versionsArr = []
    versionsAll.map(version => versionsArr.push(version.card_id))

    cardModel.find({"sub_cat": {$elemMatch: {"card_id": {$in: versionsArr}}}})
    .then(cards => {
      console.log(versionsAll.length, cards.length)
      return res.status(200).json({
        error: false
      })
    })
    .catch(error => {
      return res.status(200).json({
        error: true,
        message: error.message
      })
    })

  })
  .catch(e => {
    return res.status(200).json({
      error: true,
      message: e.message
    })
  })
})


问:
I'm using Flutter HtmlWidget for displaying Vimeo video but the issue is for android devices i'm not getting fullscreen button
-------------- Original With issue --------------

```<code>Padding(
    padding: const EdgeInsets.symmetric(horizontal: 10.0),
    child: HtmlWidget('<p> <iframe src="https://player.vimeo.com/video/638758046" height="200" frameborder="0" allow="autoplay; fullscreen"></iframe> </p>',
                      webView: true,
                    ),
                  );
</code>```

anybody has any solution for android devices please help me out in this issue.Also this same is working fine with iOs devices in iOs devices i'm getting the fullscreen button i don't know what is the issue is with android

-------------- Tried an solution --------------

```<code>Padding(
    padding: const EdgeInsets.symmetric(horizontal: 10.0),
    child: HtmlWidget('<p> <iframe src="https://player.vimeo.com/video/638758046" height="200" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe> </p>',
                      webView: true,
                    ),
                  );
</code>```

I also tried to put allow full screen in Iframe but it did not helped me with it.

Body:
-------------- Original With issue --------------

Padding(
    padding: const EdgeInsets.symmetric(horizontal: 10.0),
    child: HtmlWidget('

',
                      webView: true,
                    ),
                  );

anybody has any solution for android devices please help me out in this issue.Also this same is working fine with iOs devices in iOs devices i'm getting the fullscreen button i don't know what is the issue is with android

-------------- Tried an solution --------------

Padding(
    padding: const EdgeInsets.symmetric(horizontal: 10.0),
    child: HtmlWidget('

',
                      webView: true,
                    ),
                  );

I also tried to put allow full screen in Iframe but it did not helped me with it.


问:
How to define an interface for different packages that must be used as trait in php
I have a model in my project called Employee and it has a hierarchical structure(each employee may has some superior or inferior employees).

So I use a package that implement this hierarchical structure by utilizing nested set model.

The Employee model must use this package as trait(NodeTrait).
But it may be needed to change the algorithm and so the package I currently use, in the future.

What's the best way to decouple this model from the package I use for implementing hierarchical structure?

This is current code:

```<code>class Employee
{
    use NodeTrait;

    public function addChild(Employee $child){
        $this->appendNode($child);
    }

}
</code>```

In this code appendNode is a method of NodeTrait but I want to write a code that doesnt depend on NodeTrait methods, instead have an interface with some methods such as addChild and call those methods in methods of Employee class.

Body:
I have a model in my project called Employee and it has a hierarchical structure(each employee may has some superior or inferior employees).

So I use a package that implement this hierarchical structure by utilizing nested set model.

The Employee model must use this package as trait(NodeTrait).
But it may be needed to change the algorithm and so the package I currently use, in the future.

What's the best way to decouple this model from the package I use for implementing hierarchical structure?

This is current code:

class Employee
{
    use NodeTrait;

    public function addChild(Employee $child){
        $this->appendNode($child);
    }

}

In this code appendNode is a method of NodeTrait but I want to write a code that doesnt depend on NodeTrait methods, instead have an interface with some methods such as addChild and call those methods in methods of Employee class.


问:
Swipe back tab routing in Ionic Angular with infinite sub routes
We have a case where tabs can lead into infinite routing. On a detail page of an article you can navigate to a company and from there again to a detail page of articles from that company and so on. This results in infinite number of deep routes.

You can see an example of what I mean when using the GitHub Mobile App. Navigate to a repository and click on issues, then on any issue and from there click the repository again. Now repeat this. Swipe back and back button still works, but infinite.

With standalone components, it gets a little easier to add these detail pages to the stack of a tab navigation. But I could not find a solution to have this like infinite stacked so the “back button” will always appear and swipe back will always work.

Navigating would be like that I think:

/tabs/all-articles/article/<id>

/tabs/all-articles/article/<id>/company/<id>

/tabs/all-articles/article/<id>/company/<id>/article/<id>

/tabs/all-articles/article/<id>/company/<id>/article/<id>/.......

Or like this:

/tabs/all-articles/article/<id>

/tabs/all-articles/company/<id>

...

Or ideally (but that would destroy stack based navigation and swipe back):

/tabs/all-articles/

/article/<id>

/company/<id>

...

But both do not work. The Angular router is unable to get any further than /tabs/all-articles/article/<id>.

REPL: https://stackblitz.com/edit/angular-jczzhd


问:
Why is my background picture being pushed down when I add margin-auto?
I have a background picture, I'm trying to get the login form down the page by putting the margin auto but it drags down the image as well.

Here is my code:

.container {
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  height:110vh;

}
.login-form {
  width: 500px;
  padding: 32px;
  background-color: #fff;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
  border-radius: 4px;
  margin-top:3%;
  margin-bottom:auto;
  margin-left:auto;
  margin-right:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div className="container" style={{ backgroundImage: `url(${cancer})` }}>
  {isLoading ? <div>loggin you in!</div> : null}
  <form onSubmit={onSubmit} className="login-form">
    <div>
      <em>
        <div>{formErrors.username}</div>
        <div>{formErrors.password}</div>
      </em>
    </div>
    <label>
      Username:
      <input type="text" value={credentials.username} onChange={onChange} name="username" id="name-input"
        placeholder="Username" />
    </label>
    <label>
      Password:
      <input type="password" value={credentials.password} onChange={onChange} name="password" id="password-input"
        placeholder="password" />
    </label>
    <div className="login-button-container">
      <button className="login-button" disabled={disabled}>
        Login
      </button>
    </div>
  </form>
</div></code>```

Body:
I have a background picture, I'm trying to get the login form down the page by putting the margin auto but it drags down the image as well.

Here is my code:

.container {
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  height:110vh;

}
.login-form {
  width: 500px;
  padding: 32px;
  background-color: #fff;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
  border-radius: 4px;
  margin-top:3%;
  margin-bottom:auto;
  margin-left:auto;
  margin-right:auto;
}

<div className="container" style={{ backgroundImage: `url(${cancer})` }}>
  {isLoading ?
loggin you in!
 : null}
  <form onSubmit={onSubmit} className="login-form">

{formErrors.username}

{formErrors.password}

      Username:
      <input type="text" value={credentials.username} onChange={onChange} name="username" id="name-input"
        placeholder="Username" />

      Password:
      <input type="password" value={credentials.password} onChange={onChange} name="password" id="password-input"
        placeholder="password" />

      <button className="login-button" disabled={disabled}>
        Login
      </button>

  </form>


问:
unable to install strain openstack package in linux ubuntu
after installing all prerequietsed/environment when i am trying to install Repositary Strain Package Showing this error: 'strain': not a valid cloud name. Must be one of ['folsom','folsom-proposed','grizzly','grizzly-proposed', 'havana', 'havana-proposed', 'icehouse', 'icehouse-proposed', 'juno', 'juno-proposed', 'octa', 'octa-proposed', 'newton', 'newton-proposed',

i have try to install that package removing and recreating another VM and follow the instruction page -- openstack, but still same issue their.

i want the points which i need to check which is responsible for giving following error.


问:
How to prepend to move a line comment to the middle of field declaration with JavaParser

What I want to do

I am trying to add a comment on the generated field declaration by Lombok like this:

@lombok.Generated
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SomeController.class);
```
<p>To tell Parasoft Jtest to suppress the reporting of findings, I added a comment like this with JavaParser:</p>
<pre class="lang-java prettyprint-override"><code>/* parasoft suppress item * class ClassName line 21 */
@lombok.Generated
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SomeController.class);
</code>```

What I tried

To add this comment, I wrote a Java program with JavaParser like this:

public static void main(String[] args) throws IOException {
    Log.setAdapter(new Log.StandardOutStandardErrorAdapter());

    Path inPath = Paths.get("/path/to/input/source");
    SourceRoot sourceRoot = new SourceRoot(inPath);
    List<ParseResult<CompilationUnit>> p = sourceRoot.tryToParseParallelized();

    Iterator<ParseResult<CompilationUnit>> it = p.iterator();
    while (it.hasNext()) {
        ParseResult<CompilationUnit> pr = it.next();
        pr.getResult().ifPresent(cu -> {
            cu.accept(new ModifierVisitor<Void>() {
                @Override
                public Visitable visit(FieldDeclaration n, Void arg) {
                    List<MarkerAnnotationExpr> list = n.findAll(MarkerAnnotationExpr.class);
                    Iterator<MarkerAnnotationExpr> it = list.iterator();
                    while (it.hasNext()) {
                        MarkerAnnotationExpr ann = it.next();
                        if (ann.getNameAsString().equals("lombok.Generated") || ann.getNameAsString().equals("Generated")) {
                            // Suppress all findings at the line of field declaration
                            n.setBlockComment(String.format(" parasoft suppress item * class %s line %d ", "ClassName", n.getEnd().get().line));
                        }
                    }
                    return super.visit(n, arg);
                }
            }, null);
        });
    }
    Path outPath = Paths.get("/path/to/output/source");
    sourceRoot.saveAll(outPath);
}
```
<h2>Problem</h2>
<p>I have successfully added the comment to the target fields.
But on the same file, all line comments on field declarations move to the middle of the field declaration like this:</p>
<h4>Input</h4>
<pre class="lang-java prettyprint-override"><code>@Autowired
HttpSession session; // line comment
</code>```

Output

@Autowired
HttpSession // line comment
session;
```

Because of this, the line number from Node#getEnd().get().line changes after the addition of the parasoft suppress comment.
It makes the parasoft suppress comment doesn't work properly.

Question

How can I prepend to move a line comment to the middle of the field declaration with JavaParser ModifierVisitor?

Body:
What I want to do

I am trying to add a comment on the generated field declaration by Lombok like this:

@lombok.Generated
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SomeController.class);

To tell Parasoft Jtest to suppress the reporting of findings, I added a comment like this with JavaParser:

/* parasoft suppress item * class ClassName line 21 */
@lombok.Generated
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SomeController.class);

What I tried

To add this comment, I wrote a Java program with JavaParser like this:

public static void main(String[] args) throws IOException {
    Log.setAdapter(new Log.StandardOutStandardErrorAdapter());

    Path inPath = Paths.get("/path/to/input/source");
    SourceRoot sourceRoot = new SourceRoot(inPath);
    List<ParseResult<CompilationUnit>> p = sourceRoot.tryToParseParallelized();

    Iterator<ParseResult<CompilationUnit>> it = p.iterator();
    while (it.hasNext()) {
        ParseResult<CompilationUnit> pr = it.next();
        pr.getResult().ifPresent(cu -> {
            cu.accept(new ModifierVisitor<Void>() {
                @Override
                public Visitable visit(FieldDeclaration n, Void arg) {
                    List<MarkerAnnotationExpr> list = n.findAll(MarkerAnnotationExpr.class);
                    Iterator<MarkerAnnotationExpr> it = list.iterator();
                    while (it.hasNext()) {
                        MarkerAnnotationExpr ann = it.next();
                        if (ann.getNameAsString().equals("lombok.Generated") || ann.getNameAsString().equals("Generated")) {
                            // Suppress all findings at the line of field declaration
                            n.setBlockComment(String.format(" parasoft suppress item * class %s line %d ", "ClassName", n.getEnd().get().line));
                        }
                    }
                    return super.visit(n, arg);
                }
            }, null);
        });
    }
    Path outPath = Paths.get("/path/to/output/source");
    sourceRoot.saveAll(outPath);
}

Problem

I have successfully added the comment to the target fields.
But on the same file, all line comments on field declarations move to the middle of the field declaration like this:

Input

@Autowired
HttpSession session; // line comment

Output

@Autowired
HttpSession // line comment
session;

Because of this, the line number from Node#getEnd().get().line changes after the addition of the parasoft suppress comment.
It makes the parasoft suppress comment doesn't work properly.

Question

How can I prepend to move a line comment to the middle of the field declaration with JavaParser ModifierVisitor?


问:
How do i define a custom file path in c?
I'm trying to make it so a file name which is created using character arrays and strcat is created in a folder which is also created using character arrays and strcat. However, when I try to define the file path in the fopen() function, it refuses to compile.

```<code>#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

char spaceadder (char array[100]) {
  int i, count = -1;
  for(i = 0; array[i] != '\0'; i++) {
    count++;
  }
  array[count + 1] = ' ';
  array[count + 2] = '\0';

  return array;
}

int main(void) {
  char make[50], model[50], reg[100], folderName[100], fileName[100];
  FILE *fp;

  printf("Reg: ");
  scanf("%s", reg);
  printf("Enter the Make and Model of the Vehicle: ");
  scanf("%s %s", make, model);

  strcpy(folderName, make);
  spaceadder(folderName);
  strcat(folderName, model);
  spaceadder(folderName);
  strcat(folderName, reg);

  mkdir(folderName, 0777);

  strcpy(fileName, "AD ");
  strcat(fileName, reg);

  fp = fopen(folderName\\fileName, "w");
  fclose(fp);

  return 0;
}
</code>```

Body:
I'm trying to make it so a file name which is created using character arrays and strcat is created in a folder which is also created using character arrays and strcat. However, when I try to define the file path in the fopen() function, it refuses to compile.

#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

char spaceadder (char array[100]) {
  int i, count = -1;
  for(i = 0; array[i] != '\0'; i++) {
    count++;
  }
  array[count + 1] = ' ';
  array[count + 2] = '\0';

  return array;
}

int main(void) {
  char make[50], model[50], reg[100], folderName[100], fileName[100];
  FILE *fp;

  printf("Reg: ");
  scanf("%s", reg);
  printf("Enter the Make and Model of the Vehicle: ");
  scanf("%s %s", make, model);

  strcpy(folderName, make);
  spaceadder(folderName);
  strcat(folderName, model);
  spaceadder(folderName);
  strcat(folderName, reg);

  mkdir(folderName, 0777);

  strcpy(fileName, "AD ");
  strcat(fileName, reg);

  fp = fopen(folderName\\fileName, "w");
  fclose(fp);

  return 0;
}


问:
How can I detect which MIME type in a DataTransfer is canonical?
I'm implementing copy-paste in my application's WYSIWYG editor. The application listens for the Element.paste event. The event's .clipboardData is a DataTransfer object. In general, the clipboard data contains multiple MIME types, such as text/plain and text/html. My application then has to decide which of those types to use when pasting.

Most applications populate the clipboard with multiple MIME types to be "helpful". Two important examples:

When copying webpage text from Chrome (or any browser), it puts it on the clipboard as a text/html fragment, as expected. But it also puts it on the clipboard in text/plain format, in case the pasting application cannot handle HTML.

When copying text from Visual Studio Code, it puts it on the clipboard as a text/plain fragment, as expected. But it also puts it on the clipboard in text/html format, with inline CSS that shows code highlighting.

(You can test this behavior using this clipboard inspector I made.)

When pasting the copied webpage text, my application should use the canonical text/html data; it should ignore the "helpful" text/plain data that has been generated from it. But when pasting the copied text from Visual Studio Code, my application should use the canonical text/plain data; it should ignore the "helpful" text/html data that has been generated from it.

However, there seems to be no way for my application to distinguish between these two cases:

"The text/html data is canonical. I've also generated some text/plain for you, in case you want that instead."

"The text/plain data is canonical. I've also generated some text/html for you, in case you want that instead."

I expected there would be a way for the copying application to express which type is canonical, and which ones are fallbacks. Is there not?

I thought perhaps that this would be expressed by the DataTransfer.types array, with the canonical item first. But it seems that the order is always ["text/plain", "text/html"].

I can see that Visual Studio Code also puts data on the clipboard with a "vscode-editor-data" type. My application can detect that, and use it as a special case, where it should prefer the text/plain data. But this is only a fix for VS Code, and not for all applications.

What method should I use to detect which MIME type is canonical when handling a paste event? Or is that information just lost?


问:
how can I take public DNS of EC2 instance and use it in Jenkins pipeline?
I am using Terraform with Jenkins pipeline to create EC2 instances, in one of the EC2 I am deploying the Petclinic Application via user data and in the second EC2, I am deploying MySQL database. There is one more requirement to do a health check on the Petclinic application if it is running or not. Without the pipeline, I can send a GET request and see if it is up or not. Since EC2 public DNS is dynamic I cannot add a static URL to the GET request. The question is how can I do it dynamically and add this stage to the Jenkins Pipeline?</p>


问:
Is there an equivalent to string / list slicing in C++, like in Python?
I'm learning C++ whilst being fairly good at Python. Is there a slicing equivalent in C++ like in Python?

```<code># Python

person = "Jimmy"
print(person[1:-1]) # imm
</code>```
```<code>// c++

#include <iostream>
#include <string>

using namespace std;

int main(){
    string name = "Jimmy";
    cout << name[1:-1] << endl; // imm
}
</code>```

Thanks

Here is the error:

`

```<code>random.cpp: In function 'int main()':
random.cpp:8:19: error: expected ']' before ':' token
     cout << name[1:-1] << endl; // imm
                   ^
random.cpp:8:19: error: expected ';' before ':' token
</code>```

`

Body:
I'm learning C++ whilst being fairly good at Python. Is there a slicing equivalent in C++ like in Python?

# Python

person = "Jimmy"
print(person[1:-1]) # imm

// c++

#include <iostream>
#include <string>

using namespace std;

int main(){
    string name = "Jimmy";
    cout << name[1:-1] << endl; // imm
}

Thanks

Here is the error:

`

random.cpp: In function 'int main()':
random.cpp:8:19: error: expected ']' before ':' token
     cout << name[1:-1] << endl; // imm
                   ^
random.cpp:8:19: error: expected ';' before ':' token

`


问:
How to fix the filter reset when selecting the number of products on the page in woocometrce?
When selecting how many products to display on the page, the parameters that are in the URL are reset (respectively reset and the product filter)
enter image description here
How can this be fixed?</p>
```<code>        $per_page   = filter_input(INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT) ?? 12;
        $options    = [12, 24, 48];
        ?>

        <div class="frow align-items-center justify-content-between archive-pagination-wrapper">
            <form method="get" class="woocommerce-perpage frow-16">
                <label for="woocommerce-perpage-select" class="item">
                    <?= _loc('Товаров на странице') ?>
                </label>

                <select name="perpage" id="woocommerce-perpage-select">
                    <?php foreach($options as $option): ?>
                        <option value="<?= $option ?>" <?= $option == $per_page ? 'selected' : '' ?>><?= $option ?></option>
                    <?php endforeach; ?>
                </select>
            </form>

            <div class="woocommerce-paginator">
                <?php woocommerce_pagination(); ?>
            </div>
        </div>

</code>```

Body:
When selecting how many products to display on the page, the parameters that are in the URL are reset (respectively reset and the product filter)
enter image description here
How can this be fixed?

        $per_page   = filter_input(INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT) ?? 12;
        $options    = [12, 24, 48];
        ?>

            <form method="get" class="woocommerce-perpage frow-16">

                    <?= _loc('Товаров на странице') ?>

                <select name="perpage" id="woocommerce-perpage-select">
                    <?php foreach($options as $option): ?>
                        <option value="<?= $option ?>" <?= $option == $per_page ? 'selected' : '' ?>><?= $option ?></option>
                    <?php endforeach; ?>
                </select>
            </form>

                <?php woocommerce_pagination(); ?>


问:
Implement micro service with micro front end using ASP.NET MVC
I have a huge application which was developed in vb.net.

Our goal to convert this application to C# micro services, but in incremental manner.

So what ever new functionality that we are going to add to the existing application, we are planning to create them as a separate Micro Service with micro front end UI.

Since these are small api's with UI, I am trying to understand whether we can implement this API + UI in a single ASP.NET MVC project as a web component.

I tried 2 options:

Created an ASP.NET MVC application and added angular to same project. Is this better way to mix MVC and Angular in a single project?

I tried creating a sample ASP.NET MVC application with razor ui. But didn't understand how I can use this as a microfrontend component.

I am good in ASP.NET MVC and C#, but not that great in Angular. So planning to create microfrontend component in ASP.NET MVC razor.

Is it possible to do this? As I have to use this micro ui component in vb.net, I need this to be generated as js file to use further.


问:
Flutter App: Firebase Credentials viewable in Source Code (apk / web) = unsecure database?
Setting:
I have connected firebase with my flutter app.

Problem:
Even if I have set up the security rules to only allow authenticated requests, the google services info.json file can easily be obtained by extracting the APK file or see it in the Web Version inside the user side HTML.

What would stop an intruder from setting up their own app, register firebase with my credentials and authenticate themselves and making any changes they want to my database?

Question:
If that's the case, how can I prevent it / obfuscate the firebase credentials?


问:
Traceback: KeyError: 'twitter' python
I am having an issue when running my code. I am trying to connect to the Twitter API and retrieve the keys from a dictionary that is in a config.ini file. The Traceback that I get is:

```<code>  File "c:\Users\Dino\Projects\TwitterNLP\twitter_api.py", line 20, in <module>
    api_key = config['twitter']['api_key']
  File "C:\Users\Dino\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 963, in __getitem__
    raise KeyError(key)
KeyError: 'twitter'
</code>```
```<code>import tweepy
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
api_key = config['twitter']['api_key']
api_key_secret = config['twitter']['api_key_secret']
access_token = config['twitter']['access_token']
access_token_secret = config['twitter']['access_token_secret']
auth = tweepy.OAuthHandler(api_key, api_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
print(api.me().name)
</code>```

My config file:

```<code>[twitter]

api_key =
api_key_secret =

access_token =
access_token_secret =
</code>```

So my question is, why is this traceback occuring and how do I fix it?

Title: Traceback: KeyError: 'twitter' python

Body:
I am having an issue when running my code. I am trying to connect to the Twitter API and retrieve the keys from a dictionary that is in a config.ini file. The Traceback that I get is:

  File "c:\Users\Dino\Projects\TwitterNLP\twitter_api.py", line 20, in <module>
    api_key = config['twitter']['api_key']
  File "C:\Users\Dino\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 963, in __getitem__
    raise KeyError(key)
KeyError: 'twitter'

import tweepy
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
api_key = config['twitter']['api_key']
api_key_secret = config['twitter']['api_key_secret']
access_token = config['twitter']['access_token']
access_token_secret = config['twitter']['access_token_secret']
auth = tweepy.OAuthHandler(api_key, api_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
print(api.me().name)

My config file:

[twitter]

api_key =
api_key_secret =

access_token =
access_token_secret =

So my question is, why is this traceback occuring and how do I fix it?


问:
relational algebra expression and the sql query

Use the following query to compute a new table.

section_and_time =
    π course_id, sec_id, semester, year, day, start_hr, start_min, end_hr, end_min
        (section ⨝ time_slot)
```
<p>Using only section_and_time, write a relational algebra expression that returns a relation of overlapping courses of the form</p>
<pre class="lang-none prettyprint-override"><code>(course_id_1, sec_id_1, semester_1, year_1, course_id_2, sec_id_2, semester_2, year_2)
</code>```

Your table cannot contain duplicates. For example, a result containing

(BIO-101,  1, fall, 2022, MATH-101, 2, fall, 2022)
(MATH-101, 2, fall, 2022, BIO-101,  1, fall, 2022)
```
<p>is incorrect.</p>
</blockquote>
<p>I've tried the following SQL query:</p>
```SELECT S1.course_id, S1.sec_id, S1.semester, S1.year, S2.course_id, S2.sec_id, S2.semester, S2.year
FROM section_and_time S1, section_and_time S2
WHERE (S1.course_id != S2.course_id)
AND NOT (S1.end_hr < S2.start_hr AND S1.end_min < S2.start_min)
```

But the joining of two section_and_time tables causes the joining to occur with every column. How can I do it so that 1 course_id will join with every course_id in the table?

Body:
Use the following query to compute a new table.

section_and_time =
    π course_id, sec_id, semester, year, day, start_hr, start_min, end_hr, end_min
        (section ⨝ time_slot)

Using only section_and_time, write a relational algebra expression that returns a relation of overlapping courses of the form

(course_id_1, sec_id_1, semester_1, year_1, course_id_2, sec_id_2, semester_2, year_2)

Your table cannot contain duplicates. For example, a result containing

(BIO-101,  1, fall, 2022, MATH-101, 2, fall, 2022)
(MATH-101, 2, fall, 2022, BIO-101,  1, fall, 2022)

is incorrect.

I've tried the following SQL query:

SELECT S1.course_id, S1.sec_id, S1.semester, S1.year, S2.course_id, S2.sec_id, S2.semester, S2.year
FROM section_and_time S1, section_and_time S2
WHERE (S1.course_id != S2.course_id)
AND NOT (S1.end_hr < S2.start_hr AND S1.end_min < S2.start_min)

But the joining of two section_and_time tables causes the joining to occur with every column. How can I do it so that 1 course_id will join with every course_id in the table?


问:
How to change default radio button selection from local pickup to shipping cost in woocommerce
In woocommerce cart page, how to change default radio button selection from local pickup to shipping costs. I am using transdirect plugin for shipping calculation. I need shipping cost as default selection.

Cart page

I have tried editing woocommerce/template/cart/cart-shipping.php file


问:
MySQL to ObjectDB Migration
A maven JEE project using JSF, JPA (EclipseLink 2.3) is using MySQL comminity edition as the database. With the size of the database exceeding 20GB, there are database related peformance issues. As a solution, I am going to use ObjectDB.

I am doing to use two persistence units for each database and migrate objects. Will it work? If not, is there any other recommendation? I tired the web to search, but could not find any totorial explaining how to do it ?

Title: MySQL to ObjectDB Migration


问:
Dial in another participant inTwilio
After joining a conference call I am trying to dial in another participant to the conference call. I have 2 functions /ConnectConfrenceCall and /conference (see below the functions)

When getting the callback from /Confrencecall it enters /confrence. I get the below logs as if it is suppose to call but I never get a call. I dont see any outgoing cal in my logs.Anyway to debug this?

//ConnectConfrenceCall

```<code>
exports.handler = function (context, event, callback) {
  console.log("in confrencecalll");
  let conferenceName = "My Conference";
  let twiml = new Twilio.twiml.VoiceResponse();

  twiml.say("Please wait while we dial you into the call.");
  twiml.dial().conference(
    {
      statusCallback: `https://${context.DOMAIN_NAME}/conference`,
      statusCallbackEvent: "join",
    },
    conferenceName
  );

  callback(null, twiml);
};
</code>```

/confrence

```<code>exports.handler = function(context, event, callback) {
  console.log("in confrence");

  let toPhoneNumber = "+xxxxxx";
  let fromNumber = "+xxxxx";

  const twilioClient = context.getTwilioClient();

  if (
    (event.StatusCallbackEvent == "participant-join") &
    (event.SequenceNumber == "1")
  ) {
    console.log("in confrence IN!"+event.ConferenceSid);

    twilioClient.conferences(event.ConferenceSid)
          .participants
          .create({
            label: 'customer',
            earlyMedia: true,
            beep: 'onEnter',
            record: true,
            from: fromNumber,
            to: toPhoneNumber
          })
          .then(participant => console.log(participant.callSid));

  }else{
    console.log("in confrence else");
    return callback(null, twilioClient);
  }
   console.log("in confrence end");
  return callback(null, 'success');
};

</code>```

Logs

```<code>Execution started...
2022-12-18 14:07:13 UTC
In confrencecalll
2022-12-18 14:07:13 UTC
Execution ended in 94.03ms using 102MB
2022-12-18 14:07:17 UTC
Execution started...
2022-12-18 14:07:17 UTC
In confrence
2022-12-18 14:07:17 UTC
In confrence IN!CFc5xxxxxxxx
2022-12-18 14:07:17 UTC
In confrence end
2022-12-18 14:07:17 UTC
Execution ended in 144.57ms using 105MB```
```

Title: Dial in another participant inTwilio

Body:
After joining a conference call I am trying to dial in another participant to the conference call. I have 2 functions /ConnectConfrenceCall and /conference (see below the functions)

When getting the callback from /Confrencecall it enters /confrence. I get the below logs as if it is suppose to call but I never get a call. I dont see any outgoing cal in my logs.Anyway to debug this?

//ConnectConfrenceCall

exports.handler = function (context, event, callback) {
  console.log("in confrencecalll");
  let conferenceName = "My Conference";
  let twiml = new Twilio.twiml.VoiceResponse();

  twiml.say("Please wait while we dial you into the call.");
  twiml.dial().conference(
    {
      statusCallback: `https://${context.DOMAIN_NAME}/conference`,
      statusCallbackEvent: "join",
    },
    conferenceName
  );

  callback(null, twiml);
};

/confrence

exports.handler = function(context, event, callback) {
  console.log("in confrence");

  let toPhoneNumber = "+xxxxxx";
  let fromNumber = "+xxxxx";

  const twilioClient = context.getTwilioClient();

  if (
    (event.StatusCallbackEvent == "participant-join") &
    (event.SequenceNumber == "1")
  ) {
    console.log("in confrence IN!"+event.ConferenceSid);

    twilioClient.conferences(event.ConferenceSid)
          .participants
          .create({
            label: 'customer',
            earlyMedia: true,
            beep: 'onEnter',
            record: true,
            from: fromNumber,
            to: toPhoneNumber
          })
          .then(participant => console.log(participant.callSid));

  }else{
    console.log("in confrence else");
    return callback(null, twilioClient);
  }
   console.log("in confrence end");
  return callback(null, 'success');
};

Logs

Execution started...
2022-12-18 14:07:13 UTC
In confrencecalll
2022-12-18 14:07:13 UTC
Execution ended in 94.03ms using 102MB
2022-12-18 14:07:17 UTC
Execution started...
2022-12-18 14:07:17 UTC
In confrence
2022-12-18 14:07:17 UTC
In confrence IN!CFc5xxxxxxxx
2022-12-18 14:07:17 UTC
In confrence end
2022-12-18 14:07:17 UTC
Execution ended in 144.57ms using 105MB```


问:
Calling async function within Tornado overriden methods
I am trying to call async functions in tornado overriden methods.
Initially, the function generate() is syncronous, but that seems to block the entire program, including on_connection_close method

```<code>class Reader:

    def __init__(self, topic, group_id):
        self.topic = topic
        self.consumer = AIOKafkaConsumer(topic, bootstrap_servers="kafka:9092",
                                         group_id=group_id)

    async def read(self, sender):
        print("enter read...")
        #it seems the code below is blocking
        await self.consumer.start()
        async for message in self.consumer:
            sender(json.dumps(consumed_message))
            await self.consumer.commit()
</code>```
```<code>
class SampleSockeHandler(tornado.websocket.WebSocketHandler):

    def on_connection_close(self):
        self.app.close()

    def on_message(self, message):
        generate(message)
        #await generate(message)

    async def generate(self, message):

        await self.reader.read(message)

</code>```

print("enter read...") is only executed once in the first read() call. In the subsequent read() calls, it does not print anymore.
Now when I comment out all the code below it i.e

```<code>await self.consumer.start()
        async for message in self.consumer:
            sender(json.dumps(consumed_message))
            await self.consumer.commit()

</code>```

it works again

How do I fix this problem? Shouldn't it be an async call?

```<code>
async def main():

    app = Application()

    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    asyncio.run(main())
</code>```

Body:
I am trying to call async functions in tornado overriden methods.
Initially, the function generate() is syncronous, but that seems to block the entire program, including on_connection_close method

class Reader:

    def __init__(self, topic, group_id):
        self.topic = topic
        self.consumer = AIOKafkaConsumer(topic, bootstrap_servers="kafka:9092",
                                         group_id=group_id)

    async def read(self, sender):
        print("enter read...")
        #it seems the code below is blocking
        await self.consumer.start()
        async for message in self.consumer:
            sender(json.dumps(consumed_message))
            await self.consumer.commit()

class SampleSockeHandler(tornado.websocket.WebSocketHandler):

    def on_connection_close(self):
        self.app.close()

    def on_message(self, message):
        generate(message)
        #await generate(message)

    async def generate(self, message):

        await self.reader.read(message)

print("enter read...") is only executed once in the first read() call. In the subsequent read() calls, it does not print anymore.
Now when I comment out all the code below it i.e

await self.consumer.start()
        async for message in self.consumer:
            sender(json.dumps(consumed_message))
            await self.consumer.commit()

it works again

How do I fix this problem? Shouldn't it be an async call?

async def main():

    app = Application()

    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    asyncio.run(main())


问:
Can I useMemo's dependency list to avoid writing logic to update useRef using useEffect
Say I have a code that's written like this to update a value when there's a change to the lastUpdate state.

```<code>const [lastUpdate, setLastUpdate] = useState(Date.now());
const valueRef = useRef(expensiveFunction());
useEffect(()=>{
  valueRef.current = expensiveFunction();
}, [lastUpdate])
return { value: valueRef.current }
</code>```

I was thinking the following code should be equivalent (and it seems to be, but I want to confirm if there's anything that I may miss as there's no documentation I found that describes the following to be an appropriate replacement.  Though it is more concise

```<code>const [lastUpdate, setLastUpdate] = useState(Date.now());
const value = useMemo(()=>expensiveFunction(), [lastUpdate]);
return { value: valueRef.current }
</code>```

Body:
Say I have a code that's written like this to update a value when there's a change to the lastUpdate state.

const [lastUpdate, setLastUpdate] = useState(Date.now());
const valueRef = useRef(expensiveFunction());
useEffect(()=>{
  valueRef.current = expensiveFunction();
}, [lastUpdate])
return { value: valueRef.current }

I was thinking the following code should be equivalent (and it seems to be, but I want to confirm if there's anything that I may miss as there's no documentation I found that describes the following to be an appropriate replacement.  Though it is more concise

const [lastUpdate, setLastUpdate] = useState(Date.now());
const value = useMemo(()=>expensiveFunction(), [lastUpdate]);
return { value: valueRef.current }


问:
Strapi admin page not loading after deploy
After deploying my strapi app to heroku, the admin panel is not loading after logging in. There's a loading circle for a second and then a blank page appears. On localhost everything works fine.
After login, when I open the console I get this error:

```<code>TypeError: (0 , s.default) is not a function
</code>```

The API works fine. I'm using MongoDB for the database.

Here's my package.json file:

{
  "name": "czarogrod-backend-strapi",
  "private": true,
  "version": "0.1.0",
  "description": "A Strapi application",
  "scripts": {
    "develop": "strapi develop",
    "start": "strapi start",
    "build": "strapi build",
    "strapi": "strapi"
  },
  "dependencies": {
    "cloudinary": "^1.32.0",
    "react-query": "^3.39.2",
    "strapi": "^3.6.8",
    "strapi-admin": "^3.6.8",
    "strapi-connector-mongoose": "^3.6.8",
    "strapi-plugin-content-manager": "^3.6.8",
    "strapi-plugin-content-type-builder": "^3.6.8",
    "strapi-plugin-email": "^3.6.8",
    "strapi-plugin-upload": "^3.6.8",
    "strapi-plugin-users-permissions": "^3.6.8",
    "strapi-provider-upload-cloudinary": "^3.6.8",
    "strapi-utils": "^3.6.8",
    "video-react": "0.16.0",
    "webpack": "^4.46.0"
  },
  "author": {
    "name": "A Strapi developer"
  },
  "strapi": {
    "uuid": "2474ae8d-dfcf-46d2-9167-e53366ff5737"
  },
  "engines": {
    "node": "16.x",
    "npm": ">=6.0.0"
  },
  "license": "MIT"
}
```
<p>Here's <code>config/server.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = ({ env }) => ({
  host: env("HOST", "0.0.0.0"),
  port: env.int("PORT", 1337),
  admin: {
    autoopen: false,
    auth: {
      secret: env("ADMIN_JWT_SECRET", "7c50c2e280dc173164bccb85852308f7"),
    },
  },
});
</code>```

Here's config/database.js:

module.exports = ({ env }) => ({
  defaultConnection: "default",
  connections: {
    default: {
      connector: "mongoose",
      settings: {
        uri: env("DATABASE_URI"),
      },
      options: {
        ssl: true,
      },
    },
  },
});
```

config/env/production/database.js looks the same.

My env variables are the same as in production.

Thank you for any help in advance

Body:
After deploying my strapi app to heroku, the admin panel is not loading after logging in. There's a loading circle for a second and then a blank page appears. On localhost everything works fine.
After login, when I open the console I get this error:

TypeError: (0 , s.default) is not a function

The API works fine. I'm using MongoDB for the database.

Here's my package.json file:

{
  "name": "czarogrod-backend-strapi",
  "private": true,
  "version": "0.1.0",
  "description": "A Strapi application",
  "scripts": {
    "develop": "strapi develop",
    "start": "strapi start",
    "build": "strapi build",
    "strapi": "strapi"
  },
  "dependencies": {
    "cloudinary": "^1.32.0",
    "react-query": "^3.39.2",
    "strapi": "^3.6.8",
    "strapi-admin": "^3.6.8",
    "strapi-connector-mongoose": "^3.6.8",
    "strapi-plugin-content-manager": "^3.6.8",
    "strapi-plugin-content-type-builder": "^3.6.8",
    "strapi-plugin-email": "^3.6.8",
    "strapi-plugin-upload": "^3.6.8",
    "strapi-plugin-users-permissions": "^3.6.8",
    "strapi-provider-upload-cloudinary": "^3.6.8",
    "strapi-utils": "^3.6.8",
    "video-react": "0.16.0",
    "webpack": "^4.46.0"
  },
  "author": {
    "name": "A Strapi developer"
  },
  "strapi": {
    "uuid": "2474ae8d-dfcf-46d2-9167-e53366ff5737"
  },
  "engines": {
    "node": "16.x",
    "npm": ">=6.0.0"
  },
  "license": "MIT"
}

Here's config/server.js:

module.exports = ({ env }) => ({
  host: env("HOST", "0.0.0.0"),
  port: env.int("PORT", 1337),
  admin: {
    autoopen: false,
    auth: {
      secret: env("ADMIN_JWT_SECRET", "7c50c2e280dc173164bccb85852308f7"),
    },
  },
});

Here's config/database.js:

module.exports = ({ env }) => ({
  defaultConnection: "default",
  connections: {
    default: {
      connector: "mongoose",
      settings: {
        uri: env("DATABASE_URI"),
      },
      options: {
        ssl: true,
      },
    },
  },
});

config/env/production/database.js looks the same.

My env variables are the same as in production.

Thank you for any help in advance


问:
React Route V6 Get Navigation history
Using React Router V6, how do I get the user's navigation history?

I'm almost certain this is a duplicate but I cannot seem to find anything on React Router's Documentation, their Github and even here mentioning how I should find where the user has been in my app. My only other option is use the browser history but its not perfect for my use case.

EDIT
The use case is analytics and the ability to navigate to the last point of interest, for instance if the user visits a product, the  login page then, the add address page then I'd want the next page they access be the product which is now 2 pages down the stack.

Title: React Route V6 Get Navigation history


问:
How to get data with two columns as first table's object attribute with KNEX JS
I have two tables like this:

bo_orders table:

bo_order_items table:

I'm using knex.js to get data from database. I want to get orders with products in the same JSON object like this:

```<code>[
    {
        id: 4,
        branch_id: 2,
        order_note: "Kolay gelsin.",
        order_total_price: 2712,
        item_count: 7,
        order_status: "PENDING",
        rejection_message: "",
        created_at: "2022-12-18T13:21:10.000Z",
        updated_at: "2022-12-18T13:21:10.000Z",
        products: [
            {
                id: 10,
                order_id: 4,
                product_id: 30,
                product_price: 860,
                product_quantity: 2,
                created_at: "2022-12-18T13:21:10.000Z",
                updated_at: "2022-12-18T13:21:10.000Z",
            },
            {
                id: 11,
                order_id: 4,
                product_id: 34,
                product_price: 860,
                product_quantity: 1,
                created_at: "2022-12-18T13:21:10.000Z",
                updated_at: "2022-12-18T13:21:10.000Z",
            },
            {
                id: 12,
                order_id: 4,
                product_id: 35,
                product_price: 33,
                product_quantity: 4,
                created_at: "2022-12-18T13:21:10.000Z",
                updated_at: "2022-12-18T13:21:10.000Z",
            },
        ],
    },
    {
        id: 5,
        branch_id: 2,
        order_note: "",
        order_total_price: 1720,
        item_count: 2,
        order_status: "PENDING",
        rejection_message: "",
        created_at: "2022-12-18T13:37:44.000Z",
        updated_at: "2022-12-18T13:37:44.000Z",
        products: [
            {
                id: 13,
                order_id: 5,
                product_id: 42,
                product_price: 860,
                product_quantity: 1,
                created_at: "2022-12-18T13:37:44.000Z",
                updated_at: "2022-12-18T13:37:44.000Z",
            },
            {
                id: 14,
                order_id: 5,
                product_id: 39,
                product_price: 860,
                product_quantity: 1,
                created_at: "2022-12-18T13:37:44.000Z",
                updated_at: "2022-12-18T13:37:44.000Z",
            },
        ],
    },
];
</code>```

How i can write a knex.js query to get result like this? I tried some ways to do it but one of these are worked.

```<code>const orders = await db("bo_orders")
            .select("*")
            .leftOuterJoin("bo_order_items", "bo_order_items.order_id", "=", "bo_orders.id")
            .groupBy("products");
</code>```

Thanks!

Body:
I have two tables like this:

bo_orders table:

bo_order_items table:

I'm using knex.js to get data from database. I want to get orders with products in the same JSON object like this:

[
    {
        id: 4,
        branch_id: 2,
        order_note: "Kolay gelsin.",
        order_total_price: 2712,
        item_count: 7,
        order_status: "PENDING",
        rejection_message: "",
        created_at: "2022-12-18T13:21:10.000Z",
        updated_at: "2022-12-18T13:21:10.000Z",
        products: [
            {
                id: 10,
                order_id: 4,
                product_id: 30,
                product_price: 860,
                product_quantity: 2,
                created_at: "2022-12-18T13:21:10.000Z",
                updated_at: "2022-12-18T13:21:10.000Z",
            },
            {
                id: 11,
                order_id: 4,
                product_id: 34,
                product_price: 860,
                product_quantity: 1,
                created_at: "2022-12-18T13:21:10.000Z",
                updated_at: "2022-12-18T13:21:10.000Z",
            },
            {
                id: 12,
                order_id: 4,
                product_id: 35,
                product_price: 33,
                product_quantity: 4,
                created_at: "2022-12-18T13:21:10.000Z",
                updated_at: "2022-12-18T13:21:10.000Z",
            },
        ],
    },
    {
        id: 5,
        branch_id: 2,
        order_note: "",
        order_total_price: 1720,
        item_count: 2,
        order_status: "PENDING",
        rejection_message: "",
        created_at: "2022-12-18T13:37:44.000Z",
        updated_at: "2022-12-18T13:37:44.000Z",
        products: [
            {
                id: 13,
                order_id: 5,
                product_id: 42,
                product_price: 860,
                product_quantity: 1,
                created_at: "2022-12-18T13:37:44.000Z",
                updated_at: "2022-12-18T13:37:44.000Z",
            },
            {
                id: 14,
                order_id: 5,
                product_id: 39,
                product_price: 860,
                product_quantity: 1,
                created_at: "2022-12-18T13:37:44.000Z",
                updated_at: "2022-12-18T13:37:44.000Z",
            },
        ],
    },
];

How i can write a knex.js query to get result like this? I tried some ways to do it but one of these are worked.

const orders = await db("bo_orders")
            .select("*")
            .leftOuterJoin("bo_order_items", "bo_order_items.order_id", "=", "bo_orders.id")
            .groupBy("products");

Thanks!


问:
What is the right way to reconnect automatically in mongodb when using mongoose v6
I am using mongoose v6 for mongodb, and wish to reconnect automatically if my connection to db server gets disconnected. I am aware MongoDB has auto reconnect by default, but this happens only a certain no of times, and I wish to make this to keep trying till it connects successfully. I have shared my mongoose connection code below. Thank you.

mongoose.connect(process.env.DB_URL as string)
  .then(() => console.log('Connected to MongoDB'))
  .catch((err: any) => {
    console.log({ mongoErr: err })
  })

export const testDB  = mongoose.connection.useDb(TEST_DB as string)
export const userDB = mongoose.connection.useDb(USER_DB as string)```


问:
Downgrade SQL query from MYSQL 8 to an eqivalent of MYSQL 5.7
I have been testing this query on my localhost using MYSQL 8 but my hosting provider only offers MYSQL 5.7. I have been trying to find a way that I can write the same code in the older version of MYSQL.

```<code>SELECT SUM(COUNT(application.email)*temembers.referral_bonus) OVER() AS total_count FROM application
            LEFT JOIN members ON members.re_link=application.aff_code
            WHERE application.re_status='1' AND MONTH(application.completed_paydate)='$month'
</code>```

This is the other query while using OVER(PARTITION BY)

```<code>SELECT aff_members.app_full_name, COUNT(application.email) AS NumberOfRe, SUM(COUNT(application.email)*members.re_bonus) OVER(PARTITION BY application.aff_code) AS total_count FROM application
        LEFT JOIN members ON members.re_link=application.aff_code
        WHERE application.re_status='1' AND MONTH(application.completed_paydate)<='$last_month'
        GROUP BY app_email
</code>```

I have tried to find an alternative for combining rows using OVER(), but I have not found any for MYSQL 5.7.

Body:
I have been testing this query on my localhost using MYSQL 8 but my hosting provider only offers MYSQL 5.7. I have been trying to find a way that I can write the same code in the older version of MYSQL.

SELECT SUM(COUNT(application.email)*temembers.referral_bonus) OVER() AS total_count FROM application
            LEFT JOIN members ON members.re_link=application.aff_code
            WHERE application.re_status='1' AND MONTH(application.completed_paydate)='$month'

This is the other query while using OVER(PARTITION BY)

SELECT aff_members.app_full_name, COUNT(application.email) AS NumberOfRe, SUM(COUNT(application.email)*members.re_bonus) OVER(PARTITION BY application.aff_code) AS total_count FROM application
        LEFT JOIN members ON members.re_link=application.aff_code
        WHERE application.re_status='1' AND MONTH(application.completed_paydate)<='$last_month'
        GROUP BY app_email

I have tried to find an alternative for combining rows using OVER(), but I have not found any for MYSQL 5.7.


问:
Taggit django tags separated by a comma
I need to split string containing tags seperated by a comma to use in TaggIt, django.
However when using split() :

```<code>if request.method == 'POST':
    ...
    tags = request.POST.get('tags_hidden').split(',')
    my_object.tags.add(tag for  tag in tags)
    ...
</code>```

I run into an error:
Cannot add <generator object view_name.<locals>.<genexpr> at 0x7f3165109fc0> (<class 'generator'>). Expected <class 'django.db.models.base.ModelBase'> or str.

I found out the solution for this can be simply changing the code to:

```<code>if request.method == 'POST':
    ...
    tags = request.POST.get('tags_hidden').split(',')
    for tag in tags:
        excercise.tags.add(tag)
    ...
</code>```

Why can't an inline expression be used here? Is there any other way I can use inline? Isn't both ways leads to iterate over list which contains only str types?

Title: Taggit django tags separated by a comma

Body:
I need to split string containing tags seperated by a comma to use in TaggIt, django.
However when using split() :

if request.method == 'POST':
    ...
    tags = request.POST.get('tags_hidden').split(',')
    my_object.tags.add(tag for  tag in tags)
    ...

I run into an error:
Cannot add <generator object view_name.<locals>.<genexpr> at 0x7f3165109fc0> (<class 'generator'>). Expected <class 'django.db.models.base.ModelBase'> or str.

I found out the solution for this can be simply changing the code to:

if request.method == 'POST':
    ...
    tags = request.POST.get('tags_hidden').split(',')
    for tag in tags:
        excercise.tags.add(tag)
    ...

Why can't an inline expression be used here? Is there any other way I can use inline? Isn't both ways leads to iterate over list which contains only str types?


问:
Why am I unable to generate a Firebase app check token on an iOS simulator in an Expo project?
I am trying to generate a Firebase app check token on an iOS simulator in an Expo project and am encountering the following error:

```<code>"error": {
    "code": 403,
    "message": "App attestation failed.",
    "status": "PERMISSION_DENIED"
}
</code>```

I have taken the following steps:

Went into Firebase -> Settings -> App Check and created a debug token in Manage debug tokens.
Added the debug token to my eas.json file like this:

```<code>"env": {
        "FIREBASE_APP_CHECK_DEBUG_TOKEN": "***********",
        "FIRAAppCheckDebugToken": "********",
        "FIREBASE_APP_CHECK_DEBUG": "true"
      }
</code>```

Installed and imported the @react-native-firebase/app-check package in my project.
Called the "activate" like this:

```<code>useEffect(() => {
  appCheck().activate("ignored", true);
}, []);
</code>```

When i try a fetch request to my local firebase backend using appCheckTokenResponse = await appCheck().getToken(); and adding to headers "X-Firebase-AppCheck": appCheckTokenResponse.token i receive "PERMISSION_DENIED" because no token is generated.

Any help?

Body:
I am trying to generate a Firebase app check token on an iOS simulator in an Expo project and am encountering the following error:

"error": {
    "code": 403,
    "message": "App attestation failed.",
    "status": "PERMISSION_DENIED"
}

I have taken the following steps:

Went into Firebase -> Settings -> App Check and created a debug token in Manage debug tokens.
Added the debug token to my eas.json file like this:

"env": {
        "FIREBASE_APP_CHECK_DEBUG_TOKEN": "***********",
        "FIRAAppCheckDebugToken": "********",
        "FIREBASE_APP_CHECK_DEBUG": "true"
      }

Installed and imported the @react-native-firebase/app-check package in my project.
Called the "activate" like this:

useEffect(() => {
  appCheck().activate("ignored", true);
}, []);

When i try a fetch request to my local firebase backend using appCheckTokenResponse = await appCheck().getToken(); and adding to headers "X-Firebase-AppCheck": appCheckTokenResponse.token i receive "PERMISSION_DENIED" because no token is generated.

Any help?


问:
Swagger UI with custom layout?
Is there any possibility to create a custom layout for Swagger UI in Angular? The layout of a single long expandable list is not particularly useful. I'm looking for a way to change the structure of this component completely.</p>

Title: Swagger UI with custom layout?


问:
nginx : how to split error directive. error_page away from default.conf with same virtual host
i am working on nginx:1.21-alpine image , i want to create a custom error pages and everything is going well but i want to make the

```<code>error_page 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 421 422 423 424 425 426 428 429 431 451 500 501 502 503 504 505 506 507 508 510 511 /error.html;
location = /error.html {
    ssi on;
    internal;
    auth_basic off;
    root /usr/share/nginx/html;
    }
</code>```

away from the default.conf as another department will add it

but i am working in same virtual host

so i used include
in nginx.conf

```<code>
    include /etc/nginx/conf.d/*;

</code>```

and i put it without server in error.conf file

i got this

"location" directive is not allowed here in /etc/nginx/conf.d/error.conf:2

so i add it into server block , but default.conf overwrite it , after changing error.conf to a.conf it overwrites default.conf ,

what can i do to make them work together completing each others

as the configurations in deafault.conf and only error directive in error.conf

Body:
i am working on nginx:1.21-alpine image , i want to create a custom error pages and everything is going well but i want to make the

error_page 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 421 422 423 424 425 426 428 429 431 451 500 501 502 503 504 505 506 507 508 510 511 /error.html;
location = /error.html {
    ssi on;
    internal;
    auth_basic off;
    root /usr/share/nginx/html;
    }

away from the default.conf as another department will add it

but i am working in same virtual host

so i used include
in nginx.conf

    include /etc/nginx/conf.d/*;

and i put it without server in error.conf file

i got this

"location" directive is not allowed here in /etc/nginx/conf.d/error.conf:2

so i add it into server block , but default.conf overwrite it , after changing error.conf to a.conf it overwrites default.conf ,

what can i do to make them work together completing each others

as the configurations in deafault.conf and only error directive in error.conf


问:
Uncaught (in promise) TypeError: map is not a function
```<code>const initializeBoard = () => {
    const initialBoard = [];

  stores.map((store) => initialBoard.push({lable: store.shop}));
//   stores.map(function(value, _key) {
//     initialBoard.push({lable: value.shop});
// });
  return initialBoard;
}
const nestedMenuitems = ref([

    {
        label: 'Shipments',
        icon: 'pi pi-fw pi-envelope',
        items: initializeBoard()
    },

]);
onMounted(() => {
    ApiService.getStores().then((data) => {
        stores.value = data;
        //return  stores.map((store) => store.push({lable: store.shop}));

        console.log(stores);

//         stores.value.map(function(value, _key) {

//             list.push({lable: value.shop});

//      console.log(value.shop);
//    });
    //    stores.value.forEach((store) => { return {

    //  }});

    });

});
</code>```

i trying to fetch data to pass value   (items: initializeBoard()) this line.this will be show
items: [
{
label: 'Tracker',

```<code>        },
        {
            label: 'Map',

        },
        {
            label: 'Manage',

        }
    ]
</code>```

this format.but i get a error in.Uncaught (in promise) TypeError: map is not a function
this line (  stores.map((store) => initialBoard.push({lable: store.shop}));)
how to solve this?

Body:
const initializeBoard = () => {
    const initialBoard = [];

  stores.map((store) => initialBoard.push({lable: store.shop}));
//   stores.map(function(value, _key) {
//     initialBoard.push({lable: value.shop});
// });
  return initialBoard;
}
const nestedMenuitems = ref([

    {
        label: 'Shipments',
        icon: 'pi pi-fw pi-envelope',
        items: initializeBoard()
    },

]);
onMounted(() => {
    ApiService.getStores().then((data) => {
        stores.value = data;
        //return  stores.map((store) => store.push({lable: store.shop}));

        console.log(stores);

//         stores.value.map(function(value, _key) {

//             list.push({lable: value.shop});

//      console.log(value.shop);
//    });
    //    stores.value.forEach((store) => { return {

    //  }});

    });

});

i trying to fetch data to pass value   (items: initializeBoard()) this line.this will be show
items: [
{
label: 'Tracker',

        },
        {
            label: 'Map',

        },
        {
            label: 'Manage',

        }
    ]

this format.but i get a error in.Uncaught (in promise) TypeError: map is not a function
this line (  stores.map((store) => initialBoard.push({lable: store.shop}));)
how to solve this?


问:
Bootstrap 5 Offcanvas nav - combine 2 seperate navs
I'm trying to combine a top navigation and main navigation into a single mobile navigation using Bootstrap's offcanvas component.

I can get this to work using a standard Bootstrap nav with data-target=".navbar-toggle", but i'm struggling using offcanvas.


问:
How can I make a code to solve this peg and balls game?
There are four pegs and four balls (numbered 1, 2, 3, 4) which can be
stacked on the pegs. Each peg has a height of four, i.e. it can support a stack of all four balls.

We will denote a stack, running from the bottom to the top, by a sequence of digits running left (bottom) to right (top). I.g: 1234 is the stack with the balls in order and 1 on the bottom. An empty stack will be denoted by the digit O. The current state of the game will be shown by giving each peg's stack.

A valid move in the game consists of moving the top ball from a peg's stack and placing it on top at a (possibly empty) stack on another peg: Given a start position, the object of the garne is to make the minimum number of moves to get to a given end position.

For example:
Suppose the starting configuration has a single ball on each peg: 1 2 3 4. There are 12 possible
moves as each ball is on top of a stack and can be moved to any of the other pegs.
The balls on the left-most two pegs could be swapped over by the following sequence of moves:
1 2 3 4 --> 0 2 31 4 --> 2 0 31 4 --> 2 1 3 4; i.e. by stacking ball 1 on top of ball 3,
then moving ball 2 to its final position ahead of ball 1 being moved.

We could move from 1 2 3 4 to 2 3 4 1 using an equivalent swap sequence several times to
swap 1 & 2, then 3 & 1, then 4 & 1. This takes 9 moves.

1 2 3 4 --> 12 0 3 4 --> 12 3 0 4 --> 12 3 4 0 --> 1 32 4 0 --› 0 32 4 1 --> 2 3 4 1
requires only 6 moves.

Write a program to determine the minimum number of moves required to get
between two game states.
The program should first input four numbers showing the initial state of the game. The
next line of input will contain another four numbers giving the end state of the game.
You should output the minimum number of moves required to get from the start to
the end state.

```<code>def calc(init,final):
    c = 0
    for x in range(0,4):
        for z in range(0,4):
            if final[x][0] == init[z][-1] and z != x and (final[x][0] != 0 or init[z][-1] != 0):
                if init[x][0] == "0":
                    init[x][0] = init[z][-1]
                    init[z][-1] = "0"
                    c += 1
                else:
                    init[x].append(init[z][-1])
                    c += 1

    for m in range(0,4):
        for n in range(0,4):
            for o in range(0,len(init[n])):
                for p in range(0, len(final[m])):
                    if final[m][p] == init[n][o] and (m != n or p != o):
                        init[m].append(init[n][o])
                        init[n].pop()
                        c +=1

    return c

#init and final are 2D arrays, which for example would hold the initial 0 32 4 1 as [[0],[3,2],[4],[1]]
</code>```

I created this code but it doesn't work properly/ only for a few possibilities.

Body:
There are four pegs and four balls (numbered 1, 2, 3, 4) which can be
stacked on the pegs. Each peg has a height of four, i.e. it can support a stack of all four balls.

We will denote a stack, running from the bottom to the top, by a sequence of digits running left (bottom) to right (top). I.g: 1234 is the stack with the balls in order and 1 on the bottom. An empty stack will be denoted by the digit O. The current state of the game will be shown by giving each peg's stack.

A valid move in the game consists of moving the top ball from a peg's stack and placing it on top at a (possibly empty) stack on another peg: Given a start position, the object of the garne is to make the minimum number of moves to get to a given end position.

For example:
Suppose the starting configuration has a single ball on each peg: 1 2 3 4. There are 12 possible
moves as each ball is on top of a stack and can be moved to any of the other pegs.
The balls on the left-most two pegs could be swapped over by the following sequence of moves:
1 2 3 4 --> 0 2 31 4 --> 2 0 31 4 --> 2 1 3 4; i.e. by stacking ball 1 on top of ball 3,
then moving ball 2 to its final position ahead of ball 1 being moved.

We could move from 1 2 3 4 to 2 3 4 1 using an equivalent swap sequence several times to
swap 1 & 2, then 3 & 1, then 4 & 1. This takes 9 moves.

1 2 3 4 --> 12 0 3 4 --> 12 3 0 4 --> 12 3 4 0 --> 1 32 4 0 --› 0 32 4 1 --> 2 3 4 1
requires only 6 moves.

Write a program to determine the minimum number of moves required to get
between two game states.
The program should first input four numbers showing the initial state of the game. The
next line of input will contain another four numbers giving the end state of the game.
You should output the minimum number of moves required to get from the start to
the end state.

def calc(init,final):
    c = 0
    for x in range(0,4):
        for z in range(0,4):
            if final[x][0] == init[z][-1] and z != x and (final[x][0] != 0 or init[z][-1] != 0):
                if init[x][0] == "0":
                    init[x][0] = init[z][-1]
                    init[z][-1] = "0"
                    c += 1
                else:
                    init[x].append(init[z][-1])
                    c += 1

    for m in range(0,4):
        for n in range(0,4):
            for o in range(0,len(init[n])):
                for p in range(0, len(final[m])):
                    if final[m][p] == init[n][o] and (m != n or p != o):
                        init[m].append(init[n][o])
                        init[n].pop()
                        c +=1

    return c

#init and final are 2D arrays, which for example would hold the initial 0 32 4 1 as [[0],[3,2],[4],[1]]

I created this code but it doesn't work properly/ only for a few possibilities.


问:
How to use a video trace file in Omnet++?
I am trying to simulate a video transmission in D2D networks using Simulte in Omnet++.

How to use a video trace file for streaming a video?

What should be the format of the trace file? Specifically I intend to simulate a SVC video.

I tried using a video trace file having the following attributes:
time  Frame-type (I/P/B)   Size (in bytes)

However I am getting the following error: "Total UDP packet size exceeded 65535 bytes".


问:
QGIS relation_aggregate() not working as expected
I have ski resorts in one layer (aa_winterSports ) and ski runs in another (aa_piste ).  I have a one to many relation between the layers call winterSport_piste  which is linked on winterSports_id  in both layers.  I have a calculated field in aa_piste  called  pisteLength .  I am now trying to add a calculated field in  winterSports  layer called  meanPisteLength  which should take all the pistes for a specific resort and calculate the mean with this;

```<code>relation_aggregate('winterSports_lift', 'mean', 'pisteLength')
</code>```

I get expression is invalid.  pisteLength  not found.

No idea what I am doing wrong.

Body:
I have ski resorts in one layer (aa_winterSports ) and ski runs in another (aa_piste ).  I have a one to many relation between the layers call winterSport_piste  which is linked on winterSports_id  in both layers.  I have a calculated field in aa_piste  called  pisteLength .  I am now trying to add a calculated field in  winterSports  layer called  meanPisteLength  which should take all the pistes for a specific resort and calculate the mean with this;

relation_aggregate('winterSports_lift', 'mean', 'pisteLength')

I get expression is invalid.  pisteLength  not found.

No idea what I am doing wrong.


问:
Get "LUA_ERROR" "webkit203" when trying to render a page containing a video by Splash
I use Scrapy + Splash to scrape data from news sites.
For one of them though (Farhikhtegan Daily), while I have managed to render text/image-only pages, but those pages containing a specific type of video cannot be rendered due to an error ("webkit203").

Details:

The lua-script that I usually expect to work is:

```<code>function main(splash, args)
  assert(splash:go(args.url))
  assert(splash:wait(2))
  return splash:html()
end
</code>```

For instance this page from the above-mentioned site renders perfectly with this script, but this one (which contains that specific type of video element) doesn't, and I get this error:

{
"error": 400,
"type": "ScriptError",
"description": "Error happened while executing Lua script",
"info": {
"source": "[string "function main(splash, args)\r..."]",
"line_number": 2,
"error": "webkit203",
"type": "LUA_ERROR",
"message": "Lua error: [string "function main(splash, args)\r..."]:2: webkit203"
}
}

I have tried many variations of the script, including enabling/disabling these Splash attributes:

js_enabled
images_enabled
webgl_enabled
html5_media_enabled
media_source_enabled
plugins_enabled
private_mode_enabled

also desperately tried deleting the video element altogether by adding a js function to the script as follows:

```<code>function main(splash, args)
  local rm = splash:jsfunc([[
    function () {
      var vids = document.getElementsByClassName('videodiv');
      vids[0].remove();
      return true;
    }
  ]])
  assert(splash:go(args.url))
  assert(splash:wait(2))
  return splash:html(),
  }
end
</code>```

which of course didn't make a change.
All the above efforts lead to the same error quoted above.

So, is there anything that I might have missed?

Thanks for your help.

Body:
I use Scrapy + Splash to scrape data from news sites.
For one of them though (Farhikhtegan Daily), while I have managed to render text/image-only pages, but those pages containing a specific type of video cannot be rendered due to an error ("webkit203").

Details:

The lua-script that I usually expect to work is:

function main(splash, args)
  assert(splash:go(args.url))
  assert(splash:wait(2))
  return splash:html()
end

For instance this page from the above-mentioned site renders perfectly with this script, but this one (which contains that specific type of video element) doesn't, and I get this error:

{
"error": 400,
"type": "ScriptError",
"description": "Error happened while executing Lua script",
"info": {
"source": "[string "function main(splash, args)\r..."]",
"line_number": 2,
"error": "webkit203",
"type": "LUA_ERROR",
"message": "Lua error: [string "function main(splash, args)\r..."]:2: webkit203"
}
}

I have tried many variations of the script, including enabling/disabling these Splash attributes:

js_enabled
images_enabled
webgl_enabled
html5_media_enabled
media_source_enabled
plugins_enabled
private_mode_enabled

also desperately tried deleting the video element altogether by adding a js function to the script as follows:

function main(splash, args)
  local rm = splash:jsfunc([[
    function () {
      var vids = document.getElementsByClassName('videodiv');
      vids[0].remove();
      return true;
    }
  ]])
  assert(splash:go(args.url))
  assert(splash:wait(2))
  return splash:html(),
  }
end

which of course didn't make a change.
All the above efforts lead to the same error quoted above.

So, is there anything that I might have missed?

Thanks for your help.


问:
Python regex match discrepency on pattern position
I need to extract repository and organization from the pattern [organization/repository] using Python > 3.9.

It gives :

import re
pattern = re.compile(r"\[(.+?)\/(.+?)\]")
```
<p>If I test it over <code>"[aurelienpierre/wp-scholar] Error on activation (Issue #1)"</code>, it works:</p>
<pre class="lang-py prettyprint-override"><code>pattern.match("[aurelienpierre/wp-scholar] Error on activation (Issue #1)")
<re.Match object; span=(0, 27), match='[aurelienpierre/wp-scholar]'>
</code>```

But if the pattern is not at the beginning of the string, it doesn't match anything :

pattern.match("Re: [aurelienpierre/wp-scholar] Error on activation (Issue #1)")
None
```

I'm lost on why it behaves like that, it works in Regex101.

Body:
I need to extract repository and organization from the pattern [organization/repository] using Python > 3.9.

It gives :

import re
pattern = re.compile(r"\[(.+?)\/(.+?)\]")

If I test it over "[aurelienpierre/wp-scholar] Error on activation (Issue #1)", it works:

pattern.match("[aurelienpierre/wp-scholar] Error on activation (Issue #1)")
<re.Match object; span=(0, 27), match='[aurelienpierre/wp-scholar]'>

But if the pattern is not at the beginning of the string, it doesn't match anything :

pattern.match("Re: [aurelienpierre/wp-scholar] Error on activation (Issue #1)")
None

I'm lost on why it behaves like that, it works in Regex101.


问:
xonix game in unity, fill polygon
I am making xonix -ike game (from 1984) in unity. so I have the player and enemies and I made the board from tilemaps, and the trail of my player is made by line renderer.
right now, I am in the part of the filling the polygon made by the tail of the player ( the line renderer).
I have 2 options:

the line encloses a polygon with itself.

the line encloses a polygon with the already closed area.

how can I take all the tiles of a closed area I only know the borders of, and fill it with a specific tile? (checking if enemies are on this area is not a problem) and I already know how to detect that the player enclosed a polygon.

thank you for your help.

I tried to implement the Floddfill algorithm from wikipedia but I'm not running with pixels and precise locations , so I have a lot of difficulty to translate it to my game.

Title: xonix game in unity, fill polygon


问:
Getting a error while make components in angular
I'm facing an error. When ever I make a new component and try to open it in localhost, it doesn't show it.

I made few components both manually by using commands but it doesn't work.

The error which i m getting is that app.component is not a module.

Here is the code.

app.module.ts:

```<code>import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { RecipesComponent } from './recipes/recipes.component';
import { RecipeListComponent } from './recipes/recipe-list/recipe-list.component';
import { RecipeDetailsComponent } from './recipes/recipe-details/recipe-details.component';
@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    RecipesComponent,
    RecipeListComponent,
    RecipeDetailsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.component.ts :

```<code><app-header></app-header>
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <app-recipes></app-recipes>
      <app-shopping-list></app-shopping-list>
    </div>

  </div>

</div>
</code>```

Body:
I'm facing an error. When ever I make a new component and try to open it in localhost, it doesn't show it.

I made few components both manually by using commands but it doesn't work.

The error which i m getting is that app.component is not a module.

Here is the code.

app.module.ts:

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { RecipesComponent } from './recipes/recipes.component';
import { RecipeListComponent } from './recipes/recipe-list/recipe-list.component';
import { RecipeDetailsComponent } from './recipes/recipe-details/recipe-details.component';
@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    RecipesComponent,
    RecipeListComponent,
    RecipeDetailsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts :

<app-header></app-header>

      <app-recipes></app-recipes>
      <app-shopping-list></app-shopping-list>


问:
Kotlin DialogFragment() Inflater and access to dialog elements
I created dialogFragment:

```<code>package com.intorry.intorry11
...

class ProductDialog : DialogFragment() {

    private lateinit var increaseBTN : Button
    private lateinit var decreaseBTN : Button

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(
            com.intorry.intorry11.R.layout.fragment_product_dialog,//?????
            container
        )
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        increaseBTN=view.findViewById(R.id.increase)//it doesn't work  ?????
        decreaseBTN=view.findViewById(com.intorry.intorry11.R.id.decrease)
</code>```

Could someone explain why my code (inflater and views) doesn't work without path "com.intorry.intorry11". The normal fragments works only the problem is in dialogFragment.

Body:
I created dialogFragment:

package com.intorry.intorry11
...

class ProductDialog : DialogFragment() {

    private lateinit var increaseBTN : Button
    private lateinit var decreaseBTN : Button

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(
            com.intorry.intorry11.R.layout.fragment_product_dialog,//?????
            container
        )
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        increaseBTN=view.findViewById(R.id.increase)//it doesn't work  ?????
        decreaseBTN=view.findViewById(com.intorry.intorry11.R.id.decrease)

Could someone explain why my code (inflater and views) doesn't work without path "com.intorry.intorry11". The normal fragments works only the problem is in dialogFragment.