问:
How do a merge multiple fields into a single array in an aggregation?
I have data that has user primary keys in "user.pk", and "usertags.user.pk".

```<code>[
  {
    _id: ObjectId("62015250cb18d3cadb32c38e"),
    user: { pk: '7485070525' },
    usertags: [ { user: { pk: '334777488' } } ]
  },
  {
    _id: ObjectId("62015250cb18d3cadb32c38f"),
    user: { pk: '334777488' },
    usertags: [
      { user: { pk: '7485070525' } },
      { user: { pk: '271738610' } },
      { user: { pk: '31961021' } }
    ]
  }
]
</code>```

I am looking to aggregate all this data into a single list of all distinct user primary keys, so the result for the data above would be something like { _id: null, user_pks: [7485070525, 334777488, 271738610, 31961021] }

I tried using the $group aggregation, but I can't figure out how to merge "user.pk", and "usertags.user.pk". Can anyone help me with that?

Edit:
This is the closest I've gotten, which puts users and usertags in separate lists.

```<code>db.collection.aggregate([
  { $unwind: "$usertags" },
  { $group: { _id: null, users: { $push: "$user.pk" }, usertags: {$push: "$usertags.user.pk" } } },
])
</code>```

答:
you can do this:

test it here mongodb playground

```<code>db.collection.aggregate([
  {
    $group: {
      _id: null,
      user_pk: {
        $push: "$user.pk"
      },
      user_sub_pk: {
        $push: "$usertags"
      }
    },

  },
  // flattern array in user_sub_pk
  {
    $set: {
      user_sub_pk: {
        $reduce: {
          input: "$user_sub_pk",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this"
            ],

          },

        },

      },

    },

  },
  {
    $project: {
      user_pks: {
        $concatArrays: [
          "$user_pk",
          "$user_sub_pk.user.pk"
        ],

      },

    },
    // remove duplicate items
    {
    "$project": {
      "user_pks": {
        "$setUnion": [
          "$user_pks",
          []
        ]
      }
    }
  }

  }
])
</code>```

update: refactored by @zrbecker

```<code>db.collection.aggregate([
  {
    $group: {
      _id: null,
      users: {
        $push: "$user.pk"
      },
      usertags: {
        $push: "$usertags.user.pk"
      }
    }
  },
  {
    $project: {
      users: {
        $setUnion: [
          "$users",
          {
            $reduce: {
              input: "$usertags",
              initialValue: [],
              in: {
                $concatArrays: [
                  "$$value",
                  "$$this"
                ]
              }
            }
          }
        ]
      }
    }
  }
])
</code>```

Body:
I have data that has user primary keys in "user.pk", and "usertags.user.pk".

[
  {
    _id: ObjectId("62015250cb18d3cadb32c38e"),
    user: { pk: '7485070525' },
    usertags: [ { user: { pk: '334777488' } } ]
  },
  {
    _id: ObjectId("62015250cb18d3cadb32c38f"),
    user: { pk: '334777488' },
    usertags: [
      { user: { pk: '7485070525' } },
      { user: { pk: '271738610' } },
      { user: { pk: '31961021' } }
    ]
  }
]

I am looking to aggregate all this data into a single list of all distinct user primary keys, so the result for the data above would be something like { _id: null, user_pks: [7485070525, 334777488, 271738610, 31961021] }

I tried using the $group aggregation, but I can't figure out how to merge "user.pk", and "usertags.user.pk". Can anyone help me with that?

Edit:
This is the closest I've gotten, which puts users and usertags in separate lists.

db.collection.aggregate([
  { $unwind: "$usertags" },
  { $group: { _id: null, users: { $push: "$user.pk" }, usertags: {$push: "$usertags.user.pk" } } },
])

Body:
you can do this:

test it here mongodb playground

db.collection.aggregate([
  {
    $group: {
      _id: null,
      user_pk: {
        $push: "$user.pk"
      },
      user_sub_pk: {
        $push: "$usertags"
      }
    },

  },
  // flattern array in user_sub_pk
  {
    $set: {
      user_sub_pk: {
        $reduce: {
          input: "$user_sub_pk",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this"
            ],

          },

        },

      },

    },

  },
  {
    $project: {
      user_pks: {
        $concatArrays: [
          "$user_pk",
          "$user_sub_pk.user.pk"
        ],

      },

    },
    // remove duplicate items
    {
    "$project": {
      "user_pks": {
        "$setUnion": [
          "$user_pks",
          []
        ]
      }
    }
  }

  }
])

update: refactored by @zrbecker

db.collection.aggregate([
  {
    $group: {
      _id: null,
      users: {
        $push: "$user.pk"
      },
      usertags: {
        $push: "$usertags.user.pk"
      }
    }
  },
  {
    $project: {
      users: {
        $setUnion: [
          "$users",
          {
            $reduce: {
              input: "$usertags",
              initialValue: [],
              in: {
                $concatArrays: [
                  "$$value",
                  "$$this"
                ]
              }
            }
          }
        ]
      }
    }
  }
])


来源: stackexchange

问:
Swift: understanding pointers
I'm trying to create a CoreGraphics Context using the following MacOS Quartz API:

CGContext.init?(_ url: CFURL,
                mediaBox: UnsafePointer<CGRect>?,
                _ auxiliaryInfo: CFDictionary?)
```
<p>, but I'm having trouble with the concept of pointers. I can initiate the context thus:</p>
```var mypointer: UnsafeMutablePointer<CGRect>!
mypointer.pointee = myCGRectangle
var writeContext = CGContext.init(outURL, mediaBox: mypointer, nil)
```
<p>But it says that <code>pointee</code> is a get-only property. I've tried:</p>
```var mypointer: UnsafePointer<CGRect>! = UnsafePointer(myCGRectangle)
```

, based on this, but I get cannot convert CGRect to expected type, amongst other errors.

I have looked at several other questions here about pointers, but I can't find anything useful within them.

答:
Typically you do not just create a variable of type UnsafeMutablePointer<CGRect> and pass it to the init(_:mediaBox:_:). You rather pass a rectangle for which PDF will be displayed, e.g.

```<code>var mediaBox = CGRect(x: 0, y: 0, width: 300, height: 500)
...
var writeContext = CGContext(outURL, mediaBox: &mediaBox, nil)

</code>```

(even that is a simplification, as it creates a rectangle directly. Usually you have some rectangle of the view you want to display PDF in, so you will be passing that rectangle.)

You are also allowed to pass nil to the init(_:mediaBox:_:). In which case, as docs say:

If you pass NULL, CGPDFContextCreateWithURL uses a default page size of 8.5 by 11 inches (612 by 792 points).

So if that rectangle fits your needs, just pass nil (simpler).

ContentLicense: CC BY-SA 4.0

Title: Swift: understanding pointers

Body:
I'm trying to create a CoreGraphics Context using the following MacOS Quartz API:

CGContext.init?(_ url: CFURL,
                mediaBox: UnsafePointer<CGRect>?,
                _ auxiliaryInfo: CFDictionary?)

, but I'm having trouble with the concept of pointers. I can initiate the context thus:

var mypointer: UnsafeMutablePointer<CGRect>!
mypointer.pointee = myCGRectangle
var writeContext = CGContext.init(outURL, mediaBox: mypointer, nil)

But it says that pointee is a get-only property. I've tried:

var mypointer: UnsafePointer<CGRect>! = UnsafePointer(myCGRectangle)

, based on this, but I get cannot convert CGRect to expected type, amongst other errors.

I have looked at several other questions here about pointers, but I can't find anything useful within them.

Body:
Typically you do not just create a variable of type UnsafeMutablePointer<CGRect> and pass it to the init(_:mediaBox:_:). You rather pass a rectangle for which PDF will be displayed, e.g.

var mediaBox = CGRect(x: 0, y: 0, width: 300, height: 500)
...
var writeContext = CGContext(outURL, mediaBox: &mediaBox, nil)

(even that is a simplification, as it creates a rectangle directly. Usually you have some rectangle of the view you want to display PDF in, so you will be passing that rectangle.)

You are also allowed to pass nil to the init(_:mediaBox:_:). In which case, as docs say:

If you pass NULL, CGPDFContextCreateWithURL uses a default page size of 8.5 by 11 inches (612 by 792 points).

So if that rectangle fits your needs, just pass nil (simpler).


问:
Pseudo Class Color Change on Hover
I have an accordion where upon hover, the text color changes. Sounds simple enough, but I have an issue with the content within a pseudo class changing color. I feel like I've added the :after:hover class in the to change the color, but it's not working? Any reason why?

There's a more detailed Codepen here.

```<code><div class="task-resources-accordion">
  Title
</div>
<div class="task-resources-accordion-panel">
  <div class="task-resources-accordion-content">
    <p>Content</p>
  </div>
</div>

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

.task-resources-accordion {
  background-color: #eee;
  color: #1e1e1e;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  box-sizing: border-box;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s ease;
  font-size: 18px;
  line-height: 24px;
  letter-spacing: 0;
}

.task-resources-accordion.active,
.task-resources-accordion:hover {
  background-color: #21bfb2;
  color: #fff;
}

.task-resources-accordion:after {
  content: "\2795";
  font-size: 13px;
  float: left;
  margin-right: 10px;
}

.task-resources-accordion:after:hover {
  color: #fff;
}

.task-resources-accordion.active:after {
  content: "\2796";
  color: #fff;
}

.task-resources-accordion-panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: 0.4s ease;
  opacity: 0;
  margin-bottom: 10px;
  border: 1px solid #eaeaea;
}

.task-resources-accordion-panel.show {
  opacity: 1;
  max-height: 1000px;
}

.task-resources-accordion-content {
  padding: 15px;
}

</code>```

答:
Use 1 more colon with after and correct the position of hover like:
task-resources-accordion:hover::after

Title: Pseudo Class Color Change on Hover

Body:
I have an accordion where upon hover, the text color changes. Sounds simple enough, but I have an issue with the content within a pseudo class changing color. I feel like I've added the :after:hover class in the to change the color, but it's not working? Any reason why?

There's a more detailed Codepen here.

  Title

Content

/* Accordions */

.task-resources-accordion {
  background-color: #eee;
  color: #1e1e1e;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  box-sizing: border-box;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s ease;
  font-size: 18px;
  line-height: 24px;
  letter-spacing: 0;
}

.task-resources-accordion.active,
.task-resources-accordion:hover {
  background-color: #21bfb2;
  color: #fff;
}

.task-resources-accordion:after {
  content: "\2795";
  font-size: 13px;
  float: left;
  margin-right: 10px;
}

.task-resources-accordion:after:hover {
  color: #fff;
}

.task-resources-accordion.active:after {
  content: "\2796";
  color: #fff;
}

.task-resources-accordion-panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: 0.4s ease;
  opacity: 0;
  margin-bottom: 10px;
  border: 1px solid #eaeaea;
}

.task-resources-accordion-panel.show {
  opacity: 1;
  max-height: 1000px;
}

.task-resources-accordion-content {
  padding: 15px;
}


问:
October / Wintercms : set default list filter values programatically
I'm using Wintercms (fork of Octobercms) to create a backend application which needs to display some data according to a date range.

I've used the list filters to be able to select custom date range: https://wintercms.com/docs/backend/lists#list-filters

But when we land on the list, I would like to have a default date range selected.
The rule would be: "From 1st of february to 31st of october of the current year":

I haven't found any way of doing so in the documentations nor in internet examples..

答:
Calculate dynamic defaults by adding scope definition in ListFilterExtendScopes event: https://wintercms.com/docs/backend/lists#extend-filter-scopes

Default for daterange scope is array of :afterDate and :beforeDate values:

```<code>        $filter->addScopes([
            'latest' => [
                'label' => 'Latest',
                'type'  => 'daterange',
                'conditions' => 'latest >= \':afterDate\' AND latest <= \':beforeDate\'',
                'yearRange'  => '20',
                'default'    => [
                    0: Carbon::now()->subDays(10),
                    1: Carbon::now()->addDays(10),
                ],
            ],
        ]);
</code>```

Body:
Calculate dynamic defaults by adding scope definition in ListFilterExtendScopes event: https://wintercms.com/docs/backend/lists#extend-filter-scopes

Default for daterange scope is array of :afterDate and :beforeDate values:

        $filter->addScopes([
            'latest' => [
                'label' => 'Latest',
                'type'  => 'daterange',
                'conditions' => 'latest >= \':afterDate\' AND latest <= \':beforeDate\'',
                'yearRange'  => '20',
                'default'    => [
                    0: Carbon::now()->subDays(10),
                    1: Carbon::now()->addDays(10),
                ],
            ],
        ]);


问:
I have a problrm with if statement and while loop and dictionary in python
```<code>men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif r not in men:
        print('Sorry, the number is not found')
    elif r >= 11:
        while r >= 11:
            r = r + 1 == 1
            print('This is invalid number')
mo()
</code>```

I have problem in the elif. What I want is if I write more than 10 characters in the console, then the code will print 'This is invalid number'. But instead the code prints 'Sorry, the number is not found'.

Output:

```<code>Please Enter The Number: 111111111111111
Sorry, the number is not found

Process finished with exit code 0
</code>```

答:
The answer posted by ksohan is correct, but there's a catch. What you want is if the number entered is greater than 10 characters, then console will print 'This is invalid number'. If you want to compare the length of characters then you should first typecast  r  variable to string and then compare its length with 10.

Try this:

```<code>men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif len(str(r)) > 10:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
mo()
</code>```

Body:
men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif r not in men:
        print('Sorry, the number is not found')
    elif r >= 11:
        while r >= 11:
            r = r + 1 == 1
            print('This is invalid number')
mo()

I have problem in the elif. What I want is if I write more than 10 characters in the console, then the code will print 'This is invalid number'. But instead the code prints 'Sorry, the number is not found'.

Output:

Please Enter The Number: 111111111111111
Sorry, the number is not found

Process finished with exit code 0

Body:
The answer posted by ksohan is correct, but there's a catch. What you want is if the number entered is greater than 10 characters, then console will print 'This is invalid number'. If you want to compare the length of characters then you should first typecast  r  variable to string and then compare its length with 10.

Try this:

men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif len(str(r)) > 10:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
mo()


问:
How to wait for an API response for maximum 15 seconds in react
I have an API which sometimes does not return a response because of some dependencies. I need to wait for maximum 15 seconds for the response, if I don't receive any response within 15 seconds, I want to skip it and make the control goes to next line to execute next set of instructions.
This is how I have the API call:

```<code>const fetchData = async () => {
  const response = await getData() // I want to await max 15 seconds here, if not next line should be executed

  const response2 = await getSecondData()
}
</code>```

How can I implement the same in react ?

答:
@steve K deleted this answer, but i think its really cool answer, i prefer to repost it for literature purposes, because its a really great answer

```<code>const promiseTimeout = new Promise((resolve) => (setTimeout(() => resolve(false),  15000)))

const fetchData = async () => {
  const response = await Promise.race([promiseTimeout, getData()]) // I want to await max 15 seconds here, if not next line should be executed

  // You can do a check here if you need to
  if(!response) // do something

  const response2 = await getSecondData()
}
</code>```

Body:
I have an API which sometimes does not return a response because of some dependencies. I need to wait for maximum 15 seconds for the response, if I don't receive any response within 15 seconds, I want to skip it and make the control goes to next line to execute next set of instructions.
This is how I have the API call:

const fetchData = async () => {
  const response = await getData() // I want to await max 15 seconds here, if not next line should be executed

  const response2 = await getSecondData()
}

How can I implement the same in react ?

Body:
@steve K deleted this answer, but i think its really cool answer, i prefer to repost it for literature purposes, because its a really great answer

const promiseTimeout = new Promise((resolve) => (setTimeout(() => resolve(false),  15000)))

const fetchData = async () => {
  const response = await Promise.race([promiseTimeout, getData()]) // I want to await max 15 seconds here, if not next line should be executed

  // You can do a check here if you need to
  if(!response) // do something

  const response2 = await getSecondData()
}


问:
How To Fix UI in Unity
I would like my UI to be like the first picture, but when I expand it, it turns out like the second picture. How can I fix this?

答: Under your UI Canvas go to Canvas>Render Mode> and change from Screen Space Overlay to Screen Space Camera</p>

Title: How To Fix UI in Unity


问:
JavaScript Increment operator weird expression
Why the output of the bellow expression is 2,1?

let a = 1
let b = 2

a = (b+=a -=b)-a

console.log(`${a,b}`)```

Body:
let a = 1
let b = 2
a = (b+=a-=b)-a (*)

a-=b means a = a-b = 1-2 = -1
a = -1
Substitute into (*) => a = (b+=(-1))-a
b+=(-1) means b=b + (-1) = b - 1 = 1

Substitute into (*) => a = (1)-a = 1-(-1) = 2
a=2 b=1


问:
Modal window not appearing on click
I'm new to Bootstrap and jQuery and I'm trying to integrate a modal window in my sales website. I copied the modal code from https://getbootstrap.com/docs/4.3/components/modal/ to get a test visualization of how it would look in my project; the only problem is that whenever I click the modal button nothing appears. I heard that this could be an issue with jQuery not being loaded in my code but I don't know how to do this or if it is an issue to begin with. Here is my code:

html

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="Project2-2.css" type="text/css">

    <title></title>
  </head>
  <body>
    <!-- Small screen -->

    <!-- Header -->
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-6 bg-info">
          <br>
          <a href="#" class="my-auto">Wand Shoe Reviver</a>
        </div>
        <div class="col-sm-6 bg-secondary">
          <br>
          <a href="#" class="iconcont" id="img1cont">
            <img src="/Users/mauriceaugust/Documents/Project 2/2931147_user_face_avatar_account_head_icon.png" class="img-fluid" alt="">
          </a>
          <a href="#" class="iconcont">
            <img src="/Users/mauriceaugust/Documents/Project 2/2561381_search_icon.png" class="img-fluid" alt="">
          </a>
          <a href="#" class="iconcont">
            <img src="/Users/mauriceaugust/Documents/Project 2/2703085_bag_cart_ecommerce_shop_icon.png" class="img-fluid" alt="">
          </a>
        </div>
      </div>
    </div>
    <br>

    <!-- Hero image -->
    <div class="container-fluid heroimage">
      <div class="row">
        <div class="col-sm-12 bg-danger">
          <img class="img-fluid" src="/Users/mauriceaugust/Documents/Project 2/leather-air_jordan_1-2-min_2048x-copy.jpeg" alt="">
          <p id="herotext">To Scrub or Not to Scrub? Read more about this heated debate in the Wizard Circle.</p>
        </div>
      </div>
      </div>
    </div>
    <br>
  <!-- Other img -->
  <div class="container-fluid additionalimage">
    <div class="row">
      <div class="col-sm-12">
        <img class="img-fluid" src="/Users/mauriceaugust/Documents/Project 2/1489e901-49a2-42f5-8f5a-fa2afc73f369.92c49142211f2246ea56c38b805f46f1.jpeg" alt="">
        <p class="additonalimgtext">The Tools of the Trade - Get the ultimate kit now!</p>
      </div>
    </div>
  </div>
  <br>
  <!-- Items to buy -->
  <h1 class="eco-friendlyh1">Cleaners</h1>
  <p class="eco-friendlyp">Eco-friendly, concentrated cleaners for your most calling cleaning needs</p>
  <div class="container-fluid itemstobuycont">
    <div class="row">
      <div class="col-sm-4">
        <img src="/Users/mauriceaugust/Documents/Project 2/Sole-Revive-PDP-1.jpeg" alt="Sole Reviver" class="img-fluid">
        <p>Potion no1 Wipes - </p>
        <p>$10</p>

      </div>
      <div class="col-sm-4">
        <img src="/Users/mauriceaugust/Documents/Project 2/Wipes.jpeg" alt="Cleaning Wipes" class="img-fluid">
      </div>
      <div class="col-sm-4">
        <img src="/Users/mauriceaugust/Documents/Project 2/Cleaningrag.jpeg" alt="Cleaning Rag" class="img-fluid">
      </div>
    </div>

    <div class="row">
      <div class="col-sm-4">
        <img src="/Users/mauriceaugust/Documents/Project 2/pwtw-bleach-1.jpeg" alt="Bleach" class="img-fluid">
      </div>
      <div class="col-sm-4">
        <img src="/Users/mauriceaugust/Documents/Project 2/Detergent.jpeg" alt="Detergent" class="img-fluid">
      </div>
      <div class="col-sm-4">
        <img src="/Users/mauriceaugust/Documents/Project 2/sneaker-laundry-bag.jpeg" alt="Laundry-Bag" class="img-fluid">
      </div>
    </div>
  </div>

  <!-- Test modal -->

  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
  <br>
  <br>
  <br>
  <br>
  <br>

  <!-- Footer -->
  <div class="container-fluid footercontainer">
    <div class="row">

    </div>
  </div>

    <script type="text/javascript" src="project2-2.js">
    </script> -->
  </body>
</html>
</code>```

CSS

```<code>@font-face {
  src: url("/Users/mauriceaugust/Downloads/vampire-calligraphy-font/VampireCalligraphy-GgoA.ttf");
  font-family: vampire;
}

*{
  box-sizing: border-box;
  --primary-color: #fe7e6d;
  --secondary-color: #4C0070;
  --main-font: "GTWalsheim","Arial";
  font-family: var(--main-font);
}
html, body{
  height: 100%;
}

/* Header */
.container-fluid{
  border: solid black;
  height: 10%;
}
.align-middle{
  border: solid black;
}
.row{
  height: 100%;
}
.my-auto{
  border: solid black;
  color: white;
  font-size: 1.3em;
}
.col-sm-6{
  height: 100%;

}
.iconcont{
  display: inline-block;
  width: 30px;
  height: 27px;
  border: solid black;

  margin-left: 6%;

}

.iconcont img{
  height: 100%;
  width: 100%;
}

#img1cont{
  margin-left: 120px;
}

/* Hero image */
.heroimage, .additionalimage{
  height: 40%;
}
.col-sm-12{
  height: 100%;
}
.col-sm-12 img{
  height: 100%;
  width: 100%;
}
#herotext, .additonalimgtext{
  position: absolute;
  border: solid black;
  top: 0%;
  background-color: white;
  width: 40%;
  left: 30%;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
  padding: 1%;
}

/* Items to buy*/
.itemstobuycont{
  height: 60%;
}
.itemstobuycont .row{
  border: solid red;
  height: 50%;
}
.eco-friendlyh1, .eco-friendlyp{
  text-align: center;
}
.col-sm-4{
  border: solid black;
  text-align:center;
}
.col-sm-4 p{
  font-size: 0.5em;
  border: solid black;
  display: inline-block;
}
/* Footer */
.footercontainer{
  height: 20%;
}
</code>```

答:
You have imported only the CSS of Bootstrap 4.

The modal uses also Javascript.

Therefore, you need to import the JS of Bootstrap 4 along with jQuery and Popper.

Add the following lines to your code, before the import of your project's js file.

```<code><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</code>```

Title: Modal window not appearing on click

Body:
I'm new to Bootstrap and jQuery and I'm trying to integrate a modal window in my sales website. I copied the modal code from https://getbootstrap.com/docs/4.3/components/modal/ to get a test visualization of how it would look in my project; the only problem is that whenever I click the modal button nothing appears. I heard that this could be an issue with jQuery not being loaded in my code but I don't know how to do this or if it is an issue to begin with. Here is my code:

html

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="Project2-2.css" type="text/css">

    <title></title>

          Wand Shoe Reviver

To Scrub or Not to Scrub? Read more about this heated debate in the Wizard Circle.

The Tools of the Trade - Get the ultimate kit now!

Cleaners

Eco-friendly, concentrated cleaners for your most calling cleaning needs

Potion no1 Wipes -

$10

  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>

Modal title

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
          </button>

          ...

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>

     -->

CSS

@font-face {
  src: url("/Users/mauriceaugust/Downloads/vampire-calligraphy-font/VampireCalligraphy-GgoA.ttf");
  font-family: vampire;
}

*{
  box-sizing: border-box;
  --primary-color: #fe7e6d;
  --secondary-color: #4C0070;
  --main-font: "GTWalsheim","Arial";
  font-family: var(--main-font);
}
html, body{
  height: 100%;
}

/* Header */
.container-fluid{
  border: solid black;
  height: 10%;
}
.align-middle{
  border: solid black;
}
.row{
  height: 100%;
}
.my-auto{
  border: solid black;
  color: white;
  font-size: 1.3em;
}
.col-sm-6{
  height: 100%;

}
.iconcont{
  display: inline-block;
  width: 30px;
  height: 27px;
  border: solid black;

  margin-left: 6%;

}

.iconcont img{
  height: 100%;
  width: 100%;
}

#img1cont{
  margin-left: 120px;
}

/* Hero image */
.heroimage, .additionalimage{
  height: 40%;
}
.col-sm-12{
  height: 100%;
}
.col-sm-12 img{
  height: 100%;
  width: 100%;
}
#herotext, .additonalimgtext{
  position: absolute;
  border: solid black;
  top: 0%;
  background-color: white;
  width: 40%;
  left: 30%;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
  padding: 1%;
}

/* Items to buy*/
.itemstobuycont{
  height: 60%;
}
.itemstobuycont .row{
  border: solid red;
  height: 50%;
}
.eco-friendlyh1, .eco-friendlyp{
  text-align: center;
}
.col-sm-4{
  border: solid black;
  text-align:center;
}
.col-sm-4 p{
  font-size: 0.5em;
  border: solid black;
  display: inline-block;
}
/* Footer */
.footercontainer{
  height: 20%;
}

Body:
You have imported only the CSS of Bootstrap 4.

The modal uses also Javascript.

Therefore, you need to import the JS of Bootstrap 4 along with jQuery and Popper.

Add the following lines to your code, before the import of your project's js file.

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>


问:
MySQL: SyntaxError: Unexpected identifier
I just installed MySQL on my computer and when I try to create a database from the MySQL shell, I get this error:

```<code>MySQL  JS > CREATE DATABASE databasename;
SyntaxError: Unexpected identifier
</code>```

Does anyone know why this is happening? Is there a problem with the installation of MySQL?

答:
After using \connect root@localhost code, I am still getting the following error, even after putting in my password:
MySQL Error 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (10061)</p>

Body:
I just installed MySQL on my computer and when I try to create a database from the MySQL shell, I get this error:

MySQL  JS > CREATE DATABASE databasename;
SyntaxError: Unexpected identifier

Does anyone know why this is happening? Is there a problem with the installation of MySQL?


问:
Error trying to remove a namespace from an XML in Mule 4
I see the error like "Trying to write END_DOCUMENT when document has no root" while I replace all the payload env and xmlns with "".

It throws error :

```<code>Message               : "Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document, while writing Xml.
Trace:
  at main (Unknown)" evaluating expression: "payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")".
Element               : map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload)
Element DSL           : <set-payload value="#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]" doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc"></set-payload>
Error type            : MULE:EXPRESSION
FlowStack             : at map_requestFlow(map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload))

  (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
</code>```

Mule flow :

```<code><flow name="map_requestFlow" doc:id="21d0d652-3766-47ed-95aa-a451f62c5776" >
        <http:listener doc:name="Listener" doc:id="7312114b-2857-40b3-98cd-f52b628b3a28" config-ref="HTTP_Listener_config" path="/map"/>
        <set-payload value='#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]' doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc" />
        <logger level="INFO" doc:name="Logger" doc:id="21051f39-bb9f-412c-af73-f65051317757" message="#[payload]"/>
</flow>
</code>```

Input payload : https://github.com/Manikandan99/Map_request/blob/main/soap_request.xml

Expected output : https://github.com/Manikandan99/Map_request/blob/main/soap_response.xml

I am trying to replace payload using

```<code>#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]
</code>```

Please assist me to resolve this issue.

答:
Try the below transformation in DataWeave.</p>
```<code>%dw 2.0
output application/xml
---

  "Envelope" @("xmlns:env": "http://schemas.xmlsoap.org/soap/envelope/", "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd": "http://www.w3.org/2001/XMLSchema"): {
    "Body": {
      rateResponse: payload.Envelope.Body.rateResponse
    }
  }

</code>```

Body:
I see the error like "Trying to write END_DOCUMENT when document has no root" while I replace all the payload env and xmlns with "".

It throws error :

Message               : "Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document, while writing Xml.
Trace:
  at main (Unknown)" evaluating expression: "payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")".
Element               : map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload)
Element DSL           : <set-payload value="#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]" doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc"></set-payload>
Error type            : MULE:EXPRESSION
FlowStack             : at map_requestFlow(map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload))

  (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)

Mule flow :

<flow name="map_requestFlow" doc:id="21d0d652-3766-47ed-95aa-a451f62c5776" >
        <http:listener doc:name="Listener" doc:id="7312114b-2857-40b3-98cd-f52b628b3a28" config-ref="HTTP_Listener_config" path="/map"/>
        <set-payload value='#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]' doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc" />
        <logger level="INFO" doc:name="Logger" doc:id="21051f39-bb9f-412c-af73-f65051317757" message="#[payload]"/>
</flow>

Input payload : https://github.com/Manikandan99/Map_request/blob/main/soap_request.xml

Expected output : https://github.com/Manikandan99/Map_request/blob/main/soap_response.xml

I am trying to replace payload using

#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]

Please assist me to resolve this issue.

Body:
Try the below transformation in DataWeave.

%dw 2.0
output application/xml
---

  "Envelope" @("xmlns:env": "http://schemas.xmlsoap.org/soap/envelope/", "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd": "http://www.w3.org/2001/XMLSchema"): {
    "Body": {
      rateResponse: payload.Envelope.Body.rateResponse
    }
  }


问:
action.devices.traits.TransportControl question
Trying to implement the action.devices.commands.mediaClosedCaptioningOn command for the TransportControl trait..   I have included 'CAPTION_CONTROL' in the transportControlSupportedCommands array I send on the SYNC intent for the device, but when I actually ask Assistant to turn on subtitles on the device it replies "That device cannot play video" and my code never actually gets an EXECUTE Intent from Assistant.

I've also successfully implemented the mediaShuffle command but noticed that when I issue it, Assistant responds with "Music will shuffle after the current item" when my device actually plays videos.

Anyone have any clue how I tell Assistant that my device plays video?  I can't seem to find it in the documentation for TransportControl -- is it under a different trait maybe?

Edit 10/13/2020:

As requested, the complete SYNC response I'm currently sending for this device:

```<code>{
    "requestId": "11724082196092058876",
    "payload": {
        "agentUserId": "xxxxxx",
        "devices": [
            {
                "id": "10.0.6.252",
                "type": "action.devices.types.STREAMING_STICK",
                "traits": [
                    "action.devices.traits.TransportControl",
                    "action.devices.traits.Volume",
                    "action.devices.traits.MediaState"
                ],
                "name": {
                    "name": "Bedroom Stick"
                },
                "willReportState": true,
                "roomHint": "bedroom",
                "attributes": {
                    "transportControlSupportedCommands": [
                        "NEXT",
                        "PREVIOUS",
                        "PAUSE",
                        "STOP",
                        "RESUME",
                        "CAPTION_CONTROL",
                        "SEEK_TO_POSITION",
                        "SEEK_RELATIVE",
                        "SET_REPEAT",
                        "SHUFFLE"
                    ],
                    "volumeMaxLevel": 100,
                    "volumeCanMuteAndUnmute": true,
                    "levelStepSize": 10,
                    "commandOnlyVolume": false,
                    "volumeDefaultPercentage": 100,
                    "supportActivityState": false,
                    "supportPlaybackState": true
                }
            }
        ]
    }
}
</code>```

Exact assistant queries that produce this issue include "OK Google, turn on subtitles on Bedroom Stick" (Response: "That device can't play videos.") and "OK Google, shuffle on Bedroom Stick." (Response: "Alright, music will start shuffling after this track.")

答:
There are certain changes you need to make to your sync response that you have posted which might make your device function properly .

In the sync response I do see that you are making use of a STREAMING_STICK as your device type. If you go through the documentation you will see that this device has the following required traits :

action.devices.traits.AppSelector

action.devices.traits.MediaState

action.devices.traits.TransportControl

action.devices.traits.Volume

Your sync response is missing the AppSelector trait.

It would be good to add the deviceInfo attribute at the end of the sync response.

More information about how to work around with Streaming stick can be found here :

https://developers.google.com/assistant/smarthome/guides/streamingstick#response

Body:
Trying to implement the action.devices.commands.mediaClosedCaptioningOn command for the TransportControl trait..   I have included 'CAPTION_CONTROL' in the transportControlSupportedCommands array I send on the SYNC intent for the device, but when I actually ask Assistant to turn on subtitles on the device it replies "That device cannot play video" and my code never actually gets an EXECUTE Intent from Assistant.

I've also successfully implemented the mediaShuffle command but noticed that when I issue it, Assistant responds with "Music will shuffle after the current item" when my device actually plays videos.

Anyone have any clue how I tell Assistant that my device plays video?  I can't seem to find it in the documentation for TransportControl -- is it under a different trait maybe?

Edit 10/13/2020:

As requested, the complete SYNC response I'm currently sending for this device:

{
    "requestId": "11724082196092058876",
    "payload": {
        "agentUserId": "xxxxxx",
        "devices": [
            {
                "id": "10.0.6.252",
                "type": "action.devices.types.STREAMING_STICK",
                "traits": [
                    "action.devices.traits.TransportControl",
                    "action.devices.traits.Volume",
                    "action.devices.traits.MediaState"
                ],
                "name": {
                    "name": "Bedroom Stick"
                },
                "willReportState": true,
                "roomHint": "bedroom",
                "attributes": {
                    "transportControlSupportedCommands": [
                        "NEXT",
                        "PREVIOUS",
                        "PAUSE",
                        "STOP",
                        "RESUME",
                        "CAPTION_CONTROL",
                        "SEEK_TO_POSITION",
                        "SEEK_RELATIVE",
                        "SET_REPEAT",
                        "SHUFFLE"
                    ],
                    "volumeMaxLevel": 100,
                    "volumeCanMuteAndUnmute": true,
                    "levelStepSize": 10,
                    "commandOnlyVolume": false,
                    "volumeDefaultPercentage": 100,
                    "supportActivityState": false,
                    "supportPlaybackState": true
                }
            }
        ]
    }
}

Exact assistant queries that produce this issue include "OK Google, turn on subtitles on Bedroom Stick" (Response: "That device can't play videos.") and "OK Google, shuffle on Bedroom Stick." (Response: "Alright, music will start shuffling after this track.")


问:
Writing and editing a PHP config file from a HTML form?
Hi just looking for some direction, I have a HTML form which has several fields and basically what I am wanting to do is save the data entered from the form to a PHP config file and also have the ability to edit the saved data by accessing and submitting the form again. I would prefer to do this without the use of a database.

So here's an example:

```<code><form method="post" name="config_form">
<div id="field">
<label>Keywords</label>
<br />
<input type="text" name="keyword">
</div>

<br />

<select name="color">
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>

</form>
</code>```

So the user enters 'computer' as the keyword and selects the color 'blue'. I want to then save this data into my config.php file as variables allowing my other website pages to access this data. Should this all be in an array as well?

```<code><?php
//config file
$keyword = "computer";
$color = "blue";

?>
</code>```

Also when I go back access the form again can I make it so the fields are prefilled with the data from the config.php file?

Any help would be much appreciated thank you!

答:
You can include your configuration file in your main php script file:

```<code>// main.php
<? php include("config.php"); ?>
</code>```

and build the form with something like this:

```<code>// main.php
<?php
?>
    <form method="post" name="config_form">
        <div id="field">
            <label>Keywords</label>
            <br />
            <input type="text" name="keyword">
        </div>

        <br />

        <select name="color">
            <option value="green" <? if ($color == "green") echo "SELECTED"; ?> >Green</option>
            <option value="orange" <? if ($color == "orange") echo "SELECTED"; ?> >Orange</option>
            <option value="blue" <? if ($color == "blue") echo "SELECTED"; ?> >Blue</option>
            <option value="red" <? if ($color == "red") echo "SELECTED"; ?> >Red</option>
        </select>

</form>
<?
?>
</code>```

finally you can save the form data in your config.php file using fopen() and fwrite() functions on form submit:

```<code>$key = $_POST["key"];
$color = $_POST["color"];

if ($key != '' && $color != '') {
    $f = fopen('config.php', 'w') or die("can't open file");
    fwrite($f, '<?php $keyword=' . $key . ';$color=' . $color . ';?>');
    fclose($f);
} else { // write default values or show an error message }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi just looking for some direction, I have a HTML form which has several fields and basically what I am wanting to do is save the data entered from the form to a PHP config file and also have the ability to edit the saved data by accessing and submitting the form again. I would prefer to do this without the use of a database.

So here's an example:

<form method="post" name="config_form">

Keywords

<input type="text" name="keyword">

<select name="color">
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>

</form>

So the user enters 'computer' as the keyword and selects the color 'blue'. I want to then save this data into my config.php file as variables allowing my other website pages to access this data. Should this all be in an array as well?

<?php
//config file
$keyword = "computer";
$color = "blue";

?>

Also when I go back access the form again can I make it so the fields are prefilled with the data from the config.php file?

Any help would be much appreciated thank you!

Body:
You can include your configuration file in your main php script file:

// main.php
<? php include("config.php"); ?>

and build the form with something like this:

// main.php
<?php
?>
    <form method="post" name="config_form">
        <div id="field">
            <label>Keywords</label>
            <br />
            <input type="text" name="keyword">
        </div>

        <br />

        <select name="color">
            <option value="green" <? if ($color == "green") echo "SELECTED"; ?> >Green</option>
            <option value="orange" <? if ($color == "orange") echo "SELECTED"; ?> >Orange</option>
            <option value="blue" <? if ($color == "blue") echo "SELECTED"; ?> >Blue</option>
            <option value="red" <? if ($color == "red") echo "SELECTED"; ?> >Red</option>
        </select>

</form>
<?
?>

finally you can save the form data in your config.php file using fopen() and fwrite() functions on form submit:

$key = $_POST["key"];
$color = $_POST["color"];

if ($key != '' && $color != '') {
    $f = fopen('config.php', 'w') or die("can't open file");
    fwrite($f, '<?php $keyword=' . $key . ';$color=' . $color . ';?>');
    fclose($f);
} else { // write default values or show an error message }


问:
How can I show "empty" if data is not there?
Because of this

```<code><v-card-subtitle class="py-0 my-0">{{ vc_rule.url }}</v-card-subtitle>
</code>```

where this.vc_rule could be empty or null. Sometimes, I got this error on my console.

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading 'url')

Instead of getting this error, how can I tell Vue.js to show "empty" if data is not there?

I envision something like this :

Hint: ?

```<code><v-card-subtitle class="py-0 my-0">{{ vc_rule?.url }}</v-card-subtitle>
</code>```

答:
Try with Logical_OR -> ||

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      vc_rule: null
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">

<div id="app">
  <v-app>
    <v-card>
      <v-card-subtitle class="py-0 my-0">{{ vc_rule?.url || 'empty' }}</v-card-subtitle>
    </v-card>
  </v-app>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script></code>```

Body:
Because of this

<v-card-subtitle class="py-0 my-0">{{ vc_rule.url }}</v-card-subtitle>

where this.vc_rule could be empty or null. Sometimes, I got this error on my console.

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading 'url')

Instead of getting this error, how can I tell Vue.js to show "empty" if data is not there?

I envision something like this :

Hint: ?

<v-card-subtitle class="py-0 my-0">{{ vc_rule?.url }}</v-card-subtitle>

Body:
Try with Logical_OR -> ||

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      vc_rule: null
    }
  }
})

<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">

<div id="app">
  <v-app>
    <v-card>
      <v-card-subtitle class="py-0 my-0">{{ vc_rule?.url || 'empty' }}</v-card-subtitle>
    </v-card>
  </v-app>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>


问:
Handling Frame Rate and Video Scale in RTSP gstreamer python client
We have a RTSP stream running. this is the gstreamer pipeline we use to run the stream.

```<code>./test-launch "nvarguscamerasrc
! video/x-raw(memory:NVMM), width=(int)1280, height=(int)960, framerate=(fraction)30/1, format=(string)NV12
! nvvidconv
! nvv4l2h264enc maxperf-enable=1 poc-type=2 preset-level=1 bitrate=40000000
! rtph264pay name=pay0 pt=96 config-interval=1"
</code>```

I want to read the stream with 10 FPS and video scale of width 640 height 480 after that the received frames are passed for the Object detection.

this is the pipeline I am using to read the stream.

```<code>"rtspsrc location=rtsp://127.0.0.1:8554/test max-rtcp-rtp-time-diff=-1 udp-buffer-size=2147483647 buffer-mode=2 " \
"! decodebin " \
"! autovideoconvert " \
"! nvjpegenc " \
"! appsink name=sink emit-signals=True"
</code>```

I am able to get frames with appsink callback with above approach, but whenever I try to use videoscale and videorate plugins to the existing pipeline I am not getting any output with the appsink callback.

I even used this approach to get the frames but this didn't work either. I am not getting any error but I don't receive any frames on the the appsink callback.

```<code>rtspsrc location=rtsp://127.0.0.1:8554/test
! rtph264depay ! h264parse ! nvv4l2decoder
! videoconvert ! videoscale ! videorate ! video/x-raw,framerate=15/1 ! appsink …
</code>```

when I try to execute the gstreamer in python application I am getting this error I suspect the reason for not being able to change the video size is due to this missing plugin but I am able to continue without this plugin as long as I am not changing the video size and frame rate.

```<code>dlopen failed for /usr/lib/aarch64-linux-gnu/libv4l/plugins-wrapped/libv4l2_nvvidconv.so:
/usr/lib/aarch64-linux-gnu/libv4l/plugins-wrapped/libv4l2_nvvidconv.so:
cannot open shared object file: No such file or directory
</code>```

答:
Your problem may be that nvv4l2decoder outputs into NVMM memory, but videoconvert can't read from NVMM memory. Try nvvidconv instead of both videoconvert and videoscale:</p>
```<code>rtspsrc location=rtsp://127.0.0.1:8554/test ! rtph264depay ! h264parse ! nvv4l2decoder ! nvvidconv ! video/x-raw,width=640,height=480 ! videorate ! video/x-raw,framerate=15/1 ! appsink
</code>```

Body:
We have a RTSP stream running. this is the gstreamer pipeline we use to run the stream.

./test-launch "nvarguscamerasrc
! video/x-raw(memory:NVMM), width=(int)1280, height=(int)960, framerate=(fraction)30/1, format=(string)NV12
! nvvidconv
! nvv4l2h264enc maxperf-enable=1 poc-type=2 preset-level=1 bitrate=40000000
! rtph264pay name=pay0 pt=96 config-interval=1"

I want to read the stream with 10 FPS and video scale of width 640 height 480 after that the received frames are passed for the Object detection.

this is the pipeline I am using to read the stream.

"rtspsrc location=rtsp://127.0.0.1:8554/test max-rtcp-rtp-time-diff=-1 udp-buffer-size=2147483647 buffer-mode=2 " \
"! decodebin " \
"! autovideoconvert " \
"! nvjpegenc " \
"! appsink name=sink emit-signals=True"

I am able to get frames with appsink callback with above approach, but whenever I try to use videoscale and videorate plugins to the existing pipeline I am not getting any output with the appsink callback.

I even used this approach to get the frames but this didn't work either. I am not getting any error but I don't receive any frames on the the appsink callback.

rtspsrc location=rtsp://127.0.0.1:8554/test
! rtph264depay ! h264parse ! nvv4l2decoder
! videoconvert ! videoscale ! videorate ! video/x-raw,framerate=15/1 ! appsink …

when I try to execute the gstreamer in python application I am getting this error I suspect the reason for not being able to change the video size is due to this missing plugin but I am able to continue without this plugin as long as I am not changing the video size and frame rate.

dlopen failed for /usr/lib/aarch64-linux-gnu/libv4l/plugins-wrapped/libv4l2_nvvidconv.so:
/usr/lib/aarch64-linux-gnu/libv4l/plugins-wrapped/libv4l2_nvvidconv.so:
cannot open shared object file: No such file or directory

Body:
Your problem may be that nvv4l2decoder outputs into NVMM memory, but videoconvert can't read from NVMM memory. Try nvvidconv instead of both videoconvert and videoscale:

rtspsrc location=rtsp://127.0.0.1:8554/test ! rtph264depay ! h264parse ! nvv4l2decoder ! nvvidconv ! video/x-raw,width=640,height=480 ! videorate ! video/x-raw,framerate=15/1 ! appsink


答:
The isoreg function is working perfectly. You are fitting a monotonically increasing regression line to the data and ignoring the fluctuations, your data first increases a little and then has a slow downward trend. In this situation, isoreg eventually sticks to a constant mean value which is the best possible solution.

Try truncating the data (subt in my code) when the downward trending starts, you will get to see what is happening.

```<code>t <- 1:189
iPod <- data$iPod
plot(t, iPod, type='l')

subt <- 1:85
# also try 1:25

isoreg <- isoreg(subt, iPod[subt])
lines(subt, isoreg$yf, col='red')
</code>```

In the next two plots, you can see how it works when you ignore some downward trending parts.

Title: Isotonic Regression on R is giving me a visual model that is clearly incorrect

Body:
I'm trying to use Isotonic Regression to estimate the trend for a data set. This form of regression is not meant to be a good estimator for the trend, it's simply an exercise given as part of a Homework problem in an Introduction to Time Series class that I'm taking. In the problem, I have a series of time points, t, with a corresponding series of data points, "iPod." I'm trying to do isotonic regression on this time series with the code below:

data <- read.csv("C:/Users/******/Downloads/iPod.csv", header=TRUE)
t <- c(1:189)
iPod <- data$iPod
plot(t, iPod, type='l')

isoreg <- isoreg(t, iPod)
plot(t, iPod, type='l')
lines(t, isoreg$yf, col='red')

When I run it, however, I get

Clearly something is wrong with it, and I'm not sure what. Any idea what's going on, and how to fix my code?

Edit: I've included a dput() output below:

    dput(data)
structure(list(Month = c("2004-01", "2004-02", "2004-03", "2004-04",
"2004-05", "2004-06", "2004-07", "2004-08", "2004-09", "2004-10",
"2004-11", "2004-12", "2005-01", "2005-02", "2005-03", "2005-04",
"2005-05", "2005-06", "2005-07", "2005-08", "2005-09", "2005-10",
"2005-11", "2005-12", "2006-01", "2006-02", "2006-03", "2006-04",
"2006-05", "2006-06", "2006-07", "2006-08", "2006-09", "2006-10",
"2006-11", "2006-12", "2007-01", "2007-02", "2007-03", "2007-04",
"2007-05", "2007-06", "2007-07", "2007-08", "2007-09", "2007-10",
"2007-11", "2007-12", "2008-01", "2008-02", "2008-03", "2008-04",
"2008-05", "2008-06", "2008-07", "2008-08", "2008-09", "2008-10",
"2008-11", "2008-12", "2009-01", "2009-02", "2009-03", "2009-04",
"2009-05", "2009-06", "2009-07", "2009-08", "2009-09", "2009-10",
"2009-11", "2009-12", "2010-01", "2010-02", "2010-03", "2010-04",
"2010-05", "2010-06", "2010-07", "2010-08", "2010-09", "2010-10",
"2010-11", "2010-12", "2011-01", "2011-02", "2011-03", "2011-04",
"2011-05", "2011-06", "2011-07", "2011-08", "2011-09", "2011-10",
"2011-11", "2011-12", "2012-01", "2012-02", "2012-03", "2012-04",
"2012-05", "2012-06", "2012-07", "2012-08", "2012-09", "2012-10",
"2012-11", "2012-12", "2013-01", "2013-02", "2013-03", "2013-04",
"2013-05", "2013-06", "2013-07", "2013-08", "2013-09", "2013-10",
"2013-11", "2013-12", "2014-01", "2014-02", "2014-03", "2014-04",
"2014-05", "2014-06", "2014-07", "2014-08", "2014-09", "2014-10",
"2014-11", "2014-12", "2015-01", "2015-02", "2015-03", "2015-04",
"2015-05", "2015-06", "2015-07", "2015-08", "2015-09", "2015-10",
"2015-11", "2015-12", "2016-01", "2016-02", "2016-03", "2016-04",
"2016-05", "2016-06", "2016-07", "2016-08", "2016-09", "2016-10",
"2016-11", "2016-12", "2017-01", "2017-02", "2017-03", "2017-04",
"2017-05", "2017-06", "2017-07", "2017-08", "2017-09", "2017-10",
"2017-11", "2017-12", "2018-01", "2018-02", "2018-03", "2018-04",
"2018-05", "2018-06", "2018-07", "2018-08", "2018-09", "2018-10",
"2018-11", "2018-12", "2019-01", "2019-02", "2019-03", "2019-04",
"2019-05", "2019-06", "2019-07", "2019-08", "2019-09"), iPod = c(17L,
14L, 15L, 13L, 15L, 17L, 25L, 24L, 23L, 26L, 33L, 53L, 41L, 40L,
36L, 33L, 36L, 39L, 38L, 36L, 62L, 60L, 71L, 100L, 65L, 52L,
46L, 42L, 43L, 45L, 44L, 41L, 48L, 45L, 57L, 85L, 54L, 43L, 37L,
35L, 36L, 39L, 38L, 35L, 60L, 45L, 55L, 76L, 52L, 43L, 40L, 37L,
38L, 40L, 43L, 40L, 46L, 40L, 51L, 69L, 50L, 44L, 44L, 38L, 39L,
44L, 41L, 39L, 43L, 37L, 47L, 66L, 48L, 41L, 38L, 41L, 41L, 43L,
44L, 41L, 48L, 40L, 47L, 61L, 50L, 43L, 40L, 39L, 38L, 40L, 38L,
35L, 31L, 36L, 43L, 51L, 38L, 32L, 31L, 29L, 29L, 30L, 29L, 27L,
31L, 29L, 32L, 39L, 25L, 23L, 23L, 20L, 20L, 22L, 20L, 18L, 20L,
15L, 19L, 22L, 15L, 14L, 13L, 11L, 12L, 12L, 12L, 11L, 12L, 10L,
12L, 15L, 10L, 9L, 8L, 8L, 8L, 9L, 9L, 9L, 8L, 7L, 9L, 10L, 7L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 5L, 5L, 6L, 7L, 5L, 4L, 4L, 4L, 4L,
4L, 5L, 4L, 4L, 4L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
2L, 3L, 4L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 2L, 2L)), class =
"data.frame", row.names = c(NA,
-189L))

Body:
The isoreg function is working perfectly. You are fitting a monotonically increasing regression line to the data and ignoring the fluctuations, your data first increases a little and then has a slow downward trend. In this situation, isoreg eventually sticks to a constant mean value which is the best possible solution.

Try truncating the data (subt in my code) when the downward trending starts, you will get to see what is happening.

t <- 1:189
iPod <- data$iPod
plot(t, iPod, type='l')

subt <- 1:85
# also try 1:25

isoreg <- isoreg(subt, iPod[subt])
lines(subt, isoreg$yf, col='red')

In the next two plots, you can see how it works when you ignore some downward trending parts.


问:
Unexpected result when using list.append(). What am I doing wrong?
I can't understand the following two examples of behaviour of list.append() in Python:

```<code>list_1 = ['A', 'B']
list_2 = ['C', 'D']

copy_l1 = list_1
copy_l1.append(list_2)
</code>```

Example

```<code>print(copy_l1)
</code>```

result: ['A', 'B', ['C', 'D']]

expected: ['A', 'B', 'C', 'D'].

I kind of understand this, but how to get the expected result?

Example

```<code>print(list_1)
</code>```

result: ['A', 'B', ['C', 'D']]

expected: ['A', 'B'].

This is the most puzzling for me. Why does copy_l1.append(list_2) also affect list_1? Due to my backgound in C, this looks to me like I'm working on pointers, but I gather that should not be the case. What means?

答:
Use .extend() rather than .append() to concatenate lists.

```<code>copy_l1.extend(list_2)
</code>```

You didn't make a copy of list_1, both variables refer to the same list. Use

```<code>copy_l1 = list_1.copy()
</code>```

to make a shallow copy of list_1.

Body:
I can't understand the following two examples of behaviour of list.append() in Python:

list_1 = ['A', 'B']
list_2 = ['C', 'D']

copy_l1 = list_1
copy_l1.append(list_2)

Example

print(copy_l1)

result: ['A', 'B', ['C', 'D']]

expected: ['A', 'B', 'C', 'D'].

I kind of understand this, but how to get the expected result?

Example

print(list_1)

result: ['A', 'B', ['C', 'D']]

expected: ['A', 'B'].

This is the most puzzling for me. Why does copy_l1.append(list_2) also affect list_1? Due to my backgound in C, this looks to me like I'm working on pointers, but I gather that should not be the case. What means?

Body:
Use .extend() rather than .append() to concatenate lists.

copy_l1.extend(list_2)

You didn't make a copy of list_1, both variables refer to the same list. Use

copy_l1 = list_1.copy()

to make a shallow copy of list_1.


问:
QESeal LTV validation
I had issues some months ago with signed PDFs and LTV. Acrobat Reader showed that the signature is LTV enabled and after some months it started to say otherwise, the signature is not LTV enabled and will expire in around 1 year after the signing.

Now I'm working on an a new implementation and just wanna make sure that the LTV won't disappear this time. I got some tips about using the DSS library also to validate my signatures. Adobe says this time also that the signature is LTV enabled. The DSS validator is complaining about one thing: The signed attribute: 'signing-certificate' is absent! I have checked and it's right because there is no signing-certificate attribute in the ASN1 structure but there is signing certificate V2. I tried to also add the signing-certificate attribute but then I got some other issues. I may have done this the wrong way though. Is there a need for having both? Should/can I ignore this warning? How can one be sure about the LTV? Is there some other way for validation?

答:
First off, the term "LTV enabled" is not as well defined as one might wish for. As has been mentioned a number of times here on stack overflow (e.g. here, here, or here), Adobe Acrobat displays that a given signature is "LTV enabled" if during validation it observed that it did not need to access remote sources to retrieve information it required for validation.

Thus, whether or not Adobe Acrobat considers your signature LTV enabled, depends on the (closed!) algorithms of the Adobe signature validation code and the configuration of the signature validation in Adobe Acrobat.

Both these factors are subject to change!

In essence, therefore, you cannot be "sure about the LTV"!

Nonetheless, you can try your best to provide as much relevant validation related information and fix it in time. This improves your chances that your signatures are and will continue to be considered LTV enabled by Adobe Acrobat.

Now concerning your questions:

signing-certificate ... signing-certificate V2 ... Is there a need for having both?

To begin with, these attributes are not required by Adobe Acrobat validation routines. (Not yet, that is.) So this is not (yet?) relevant for your objective.

If you are interested nonetheless - no. If your signature algorithm relies on SHA-1 for hashing (which it of course should not!), you should use the plain signing-certificate attribute (in CMS called ESSCertID). If it relies on a different, more advanced algorithm, you should use the newer signing-certificate-V2 attribute (in CMS called ESSCertIDv2) and use the same hash algorithm as in your signature algorithm.

Only if your signatures will also be verified by older (well, ancient) software that supports ESSCertID but not yet ESSCertIDv2, you might consider adding both attributes.

In the context at hand, by the way, eSig DSS does support both ESSCertID and ESSCertIDv2. Thus, if it says that the signing attribute is missing, that means that there is something fishy about the signing-attribute V2 you saw in your signature...

Should/can I ignore this warning?

In respect to Adobe's "LTV enabled" profile, you currently can ignore the warning for now. And whether or not Adobe will start requiring that attribute by default in the future and (if yes) how exactly, is hard to tell.

How can one be sure about the LTV? Is there some other way for validation?

As mentioned above, you can not be sure about the "LTV enabled" status of your signatures.

Considering the screen shot you shared, though, it mentions that your PDF signature reached only a BASELINE-T equivalent level. In particular, you did not reach a BASELINE-LT equivalent, let alone a BASELINE-LTA equivalent here. Thus, as far as ETSI conform validation goes, the required revocation information were not all found in your PDF.

Adobe's validation rules (currently) are very lax in comparison with the ETSI rules, so it might display "LTV enabled" nonetheless. Unless you want to improve your signatures to BASELINE-LT at least, though, using eSignature DSS won't help you as validation tool...

Title: QESeal LTV validation


问:
Execution failed for task ':app:compileDebugKotlin'. error in Flutter after upgrading to 2.10 version
I upgraded my flutter version to 2.10 and it is giving me this errror while compiling -

```<code>Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/518a28e11257a17211a8fb8a5067b186/jetified-kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/6168eafaded8ddacbc73df91bd758ffe/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/6c0671fbb7722afc42898b4178b11de7/jetified-kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/91667e970d35cee0f38e121291f325a1/jetified-kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/af48bf569b5523ddd7a06285f676a1ca/jetified-kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/b560d76b568ab2e29107d94002f1a070/jetified-kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/d0224631d7841d16cd3b5d2fab11c793/jetified-kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/e0583c70716c2ce3cdb07beee79fcae0/jetified-window-java-1.0.0-beta04-api.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

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

BUILD FAILED in 14s
┌─ Flutter Fix ───────────────────────────────────────────────────────────────────────────────────┐
│ [!] Your project requires a newer version of the Kotlin Gradle plugin.                          │
│ Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then    │
│ update                                                                                │
│ C:\Users\Hp\Desktop\Programming\Flutter\flutter_application_notifications\android\build.gradle: │
│ ext.kotlin_version = '<latest-version>'                                                         │
└─────────────────────────────────────────────────────────────────────────────────────────────────┘
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
</code>```

And I am being honest here, I never have experienced bug free upgradation in Flutter till now, except when they made little changes. Literally. Can someone tell me why is this happening and please give a solution for the above error.

答:
Just go to:
your flutter app\android\build.gradle:

and initialize

ext.kotlin_version = '1.6.10'

That's it

Body:
I upgraded my flutter version to 2.10 and it is giving me this errror while compiling -

Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/518a28e11257a17211a8fb8a5067b186/jetified-kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/6168eafaded8ddacbc73df91bd758ffe/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/6c0671fbb7722afc42898b4178b11de7/jetified-kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/91667e970d35cee0f38e121291f325a1/jetified-kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/af48bf569b5523ddd7a06285f676a1ca/jetified-kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/b560d76b568ab2e29107d94002f1a070/jetified-kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/d0224631d7841d16cd3b5d2fab11c793/jetified-kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/e0583c70716c2ce3cdb07beee79fcae0/jetified-window-java-1.0.0-beta04-api.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

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

BUILD FAILED in 14s
┌─ Flutter Fix ───────────────────────────────────────────────────────────────────────────────────┐
│ [!] Your project requires a newer version of the Kotlin Gradle plugin.                          │
│ Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then    │
│ update                                                                                │
│ C:\Users\Hp\Desktop\Programming\Flutter\flutter_application_notifications\android\build.gradle: │
│ ext.kotlin_version = '<latest-version>'                                                         │
└─────────────────────────────────────────────────────────────────────────────────────────────────┘
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

And I am being honest here, I never have experienced bug free upgradation in Flutter till now, except when they made little changes. Literally. Can someone tell me why is this happening and please give a solution for the above error.


问:
Uppaal - How to force a transition when a condition becomes true?
I would like to be able to force a transition as soon as a condition becomes true.

For example in this Example, I would like to force the transition from the system next from the state S0 to S1 as soon as the global variable a becomes 5. The guard is not enough because a can still be incremented once it reach 5 before the transition is fired. I really need the transition to be triggered and then continue to increment a.

Is there a simple way to do it? I tried by adding invariant in the state but it is creating deadlocks.

答: You can simply add invariant a<=5 in the S0 state.


问:
how to get the http header in asynchronous request mode using ASIHHTTP
I hope to display the download file size by reading http header.

I know there is way do this:

```<code>ASIHTTPRequest request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous]; NSString poweredBy = [[request responseHeaders] objectForKey:@"X-Powered-By"];
NSString *contentType = [[request responseHeaders] objectForKey:@"Content-Type"];
</code>```

but this is Synchronous mode, in Asynchronous mode it can be done as below:

```<code>(void)requestFinished:(ASIHTTPRequest *)request { unsigned long long contentLength = [request contentLength]; }
</code>```

but 'requestFinished' is at the end of download.
Is there an event to get the http header info at the beginning of download?

Thank

interdev

答:
```<code>- (void)requestDidReceiveResponseHeader:(ASIHTTPRequest *)request
{
unsigned long long contentLength = [request contentLength];
NSLog(@"request Bytes = %llu", contentLength);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I hope to display the download file size by reading http header.

I know there is way do this:

ASIHTTPRequest request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous]; NSString poweredBy = [[request responseHeaders] objectForKey:@"X-Powered-By"];
NSString *contentType = [[request responseHeaders] objectForKey:@"Content-Type"];

but this is Synchronous mode, in Asynchronous mode it can be done as below:

(void)requestFinished:(ASIHTTPRequest *)request { unsigned long long contentLength = [request contentLength]; }

but 'requestFinished' is at the end of download.
Is there an event to get the http header info at the beginning of download?

Thank

interdev


问:
How to add a condition to a specific time to a bar
how can I adjust the code below to only highlight the bar if the condition are met with consider to the time?

//@version=5
indicator("", "", true)

bgcolor(dayofweek==5 and time==1400 and close > 1 ? color.new(color.green, 40):na)

If I remove time it works like a charm

bgcolor(dayofweek==5 and close > 1 ? color.new(color.green, 40):na)

答:
Hey CC from TV here and the reason why is because time is a timestamp and the way pinescript is coded, it won't ever equal that amount but an easy workaround would be the following (tested and it works)

```<code>bgcolor(dayofweek == 5 and time >= 1400 and close > 1 ? color.new(color.green, 40) : na)
</code>```

EDIT: To address your original question and your comment, here is another way to write it:

```<code>bgcolor(dayofweek == 5 and time(timeframe.period, "1400-1400:23456") and close > 1 ? color.new(color.green, 40) : na)
</code>```

Body:
Hey CC from TV here and the reason why is because time is a timestamp and the way pinescript is coded, it won't ever equal that amount but an easy workaround would be the following (tested and it works)

bgcolor(dayofweek == 5 and time >= 1400 and close > 1 ? color.new(color.green, 40) : na)

EDIT: To address your original question and your comment, here is another way to write it:

bgcolor(dayofweek == 5 and time(timeframe.period, "1400-1400:23456") and close > 1 ? color.new(color.green, 40) : na)


问:
How to implement the startsWith function of a trie in python
I have the following implementation of a trie in python.

I want to implement the startsWith function that will return a list of all words that start with the prefix.

Currently it return tue or false. Im not sure how to get a list of words in my implementation. I believe I need some sort of dfs, but not sure how to implement it

```<code>class TrieNode:
    def __init__(self):
        self.children = {}
        self.end_of_word = False

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        current = self.root
        for char in word:
            if char not in cur.children:
                current.children[char] = TrieNode()
            current = current.children[char]
        current.end_of_word = True

    def search(self, word):
        current = self.root
        for char in word:
            if char not in current.children:
                return False
            current = current.children[char]
        return current.end_of_word

    def startsWith(self, prefix):
        current = self.root
        for char in prefix:
            if char not in current.children:
                return False
            current = current.children[char]
        return True

    def remove(self, word):
        current = self.root
        if self.search(word):
            for char in word:
                current = current.children[char]
            current.end_of_word = False

# Your Trie object will be instantiated and called as such:
obj = Trie()
obj.insert('apple')
obj.insert('applegate')
obj.insert('apply')
obj.insert('application')

print(obj.search('applegate'))
obj.remove('applegate')
print(obj.search('applegate'))

print(obj.startsWith('app')) -> should return a list of all words that start with 'app'

</code>```

答:
You need something like:

```<code>def all_children_iterator(self, prefix: str) -> Iterator[str]:
    # returns all children of the current node with prefix prepended
    if self.end_of_word:
         yield prefix
    for char, child in self.children.items():
         yield from child.all_children_iterator(prefix + char)
</code>```

Then instead of returning True, you return list(current.all_children_iterator(''))

This code could be made slightly more efficient by using a list to hold the letters and judiciously appending and popping them.  But that makes the basic idea a little bit harder to understand.

Body:
I have the following implementation of a trie in python.

I want to implement the startsWith function that will return a list of all words that start with the prefix.

Currently it return tue or false. Im not sure how to get a list of words in my implementation. I believe I need some sort of dfs, but not sure how to implement it

class TrieNode:
    def __init__(self):
        self.children = {}
        self.end_of_word = False

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        current = self.root
        for char in word:
            if char not in cur.children:
                current.children[char] = TrieNode()
            current = current.children[char]
        current.end_of_word = True

    def search(self, word):
        current = self.root
        for char in word:
            if char not in current.children:
                return False
            current = current.children[char]
        return current.end_of_word

    def startsWith(self, prefix):
        current = self.root
        for char in prefix:
            if char not in current.children:
                return False
            current = current.children[char]
        return True

    def remove(self, word):
        current = self.root
        if self.search(word):
            for char in word:
                current = current.children[char]
            current.end_of_word = False

# Your Trie object will be instantiated and called as such:
obj = Trie()
obj.insert('apple')
obj.insert('applegate')
obj.insert('apply')
obj.insert('application')

print(obj.search('applegate'))
obj.remove('applegate')
print(obj.search('applegate'))

print(obj.startsWith('app')) -> should return a list of all words that start with 'app'

Body:
You need something like:

def all_children_iterator(self, prefix: str) -> Iterator[str]:
    # returns all children of the current node with prefix prepended
    if self.end_of_word:
         yield prefix
    for char, child in self.children.items():
         yield from child.all_children_iterator(prefix + char)

Then instead of returning True, you return list(current.all_children_iterator(''))

This code could be made slightly more efficient by using a list to hold the letters and judiciously appending and popping them.  But that makes the basic idea a little bit harder to understand.


问:
Android listview with header layout
I am rephrasing my question. Please bear with me.

I have a Cursor, which has carNum and tasks needs to be done on that. So carNum repeats in table. Right now I am using SimpleCursorAdapter and displaying all the info as a listitem. What I would like to do is set carNum as a header of a list and tasks need to be done as listitems. In addition to this, I would like to make header it's own layout so that I can display carNum and some info about it. So now where should I start ?

How should I get distinct carNum from Cursor and make that as header ? And then get listitem for that ?

Here is the .java

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

 String empid;
 ListView list;
 Cursor cursor = null;
 TextView text;
 private  DbAdapter_Assignment assignment;

@Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.listlayout);
         empid = getIntent().getExtras().getString("EmpID");
         getData(empid);
}

   public void getData(final String empid)
   {
        assignment =  new DbAdapter_Assignment(getBaseContext());
       assignment.open();

    cursor = assignment.getAcceptedTasks(empid);
    startManagingCursor(cursor);

    text = (TextView) findViewById(R.id.employeename);
    text.setText(getEmployeeName(empid) + " has "+ Integer.toString  (cursor.getCount()) + " tasks assigned." );
    list = (ListView) findViewById(R.id.mytasklist);
    list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, View v, int arg2,
                long arg3) {
        }
   });

    SimpleCursorAdapter adapter = new SimpleCursorAdapter (this, R.layout.mytaskslayout, cursor, new String[] {"A","B", "C", "D", "E", "F"}, new int[] {R.id.a, R.id.b, R.id.c, R.id.d, R.id.e, R.id.f});
    list.setAdapter(adapter);
</code>```

答:
extend SimpleCursorAdapter

Build list of header indexes in the constructor

```<code>    c.moveToFirst();
    int headerIndex = -1;
    String headerValue = null;
    do {
         headerIndex++;
         String header = c.getString(getColumnClass());
         if (!header.equalsIgnoreCase(headerValue)) {
                    mHeaderIndexes.add(headerIndex);
                    headerValue = header;
                    headerIndex++;
          }
    }while (c.moveToNext());
    c.moveToFirst();
    mDataCount = c.getCount()+mHeaderIndexes.size();

</code>```

Override methods

```<code>@Override
    public int getCount() {
        return mDataCount;
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderIndexes.contains(position)) {
            return TYPE_HEADER_ROW;
        }
        return TYPE_ROW;
    }

    @Override
    public Object getItem(int position) {
        if (mHeaderIndexes.contains(position)) {
            // for header row need return first row with data for this group
            getCursor().moveToPosition(position-mHeaderIndexes.indexOf(position));
        }
        else {
            for (int i = 0; i < mHeaderIndexes.size(); i++) {
                if (mHeaderIndexes.get(i) > position) {
                    // need move back by number of headers before position
                    getCursor().moveToPosition(position - i);
                    break;
                }
            }
            if (position>mHeaderIndexes.get(mHeaderIndexes.size()-1)) {
                // if position is in the last group (position >last group header position)
                // move back by number of headers
                getCursor().moveToPosition(position - mHeaderIndexes.size());
            }
        }
        return getCursor();
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public boolean isEnabled(int position) {
        return !mHeaderIndexes.contains(position);
    }
</code>```

Implement getView()

```<code>    public View getView(int position, View convertView, ViewGroup parent) {
        int type = getItemViewType(position);
        Cursor cursor = (Cursor) getItem(position);

        View view = convertView;
        if (type==TYPE_HEADER_ROW) {
            boolean isHeader = view!=null && view.findViewById(R.id.title)!=null;
            if (!isHeader) {
                view = mInflater.inflate(R.layout.row_my_header, null);
            }
            TextView header = view.findViewById(R.id.title);
            header.setText(...);
        }
        else {
            if (view==null) {
                view = mInflater.inflate(R.layout.row_my_data, null);
            }
    // fill data row
         }
    return view;
    }

</code>```

Title: Android listview with header layout

Body:
I am rephrasing my question. Please bear with me.

I have a Cursor, which has carNum and tasks needs to be done on that. So carNum repeats in table. Right now I am using SimpleCursorAdapter and displaying all the info as a listitem. What I would like to do is set carNum as a header of a list and tasks need to be done as listitems. In addition to this, I would like to make header it's own layout so that I can display carNum and some info about it. So now where should I start ?

How should I get distinct carNum from Cursor and make that as header ? And then get listitem for that ?

Here is the .java

public class MyTask extends Activity{

 String empid;
 ListView list;
 Cursor cursor = null;
 TextView text;
 private  DbAdapter_Assignment assignment;

@Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.listlayout);
         empid = getIntent().getExtras().getString("EmpID");
         getData(empid);
}

   public void getData(final String empid)
   {
        assignment =  new DbAdapter_Assignment(getBaseContext());
       assignment.open();

    cursor = assignment.getAcceptedTasks(empid);
    startManagingCursor(cursor);

    text = (TextView) findViewById(R.id.employeename);
    text.setText(getEmployeeName(empid) + " has "+ Integer.toString  (cursor.getCount()) + " tasks assigned." );
    list = (ListView) findViewById(R.id.mytasklist);
    list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, View v, int arg2,
                long arg3) {
        }
   });

    SimpleCursorAdapter adapter = new SimpleCursorAdapter (this, R.layout.mytaskslayout, cursor, new String[] {"A","B", "C", "D", "E", "F"}, new int[] {R.id.a, R.id.b, R.id.c, R.id.d, R.id.e, R.id.f});
    list.setAdapter(adapter);

Body:
extend SimpleCursorAdapter

Build list of header indexes in the constructor

    c.moveToFirst();
    int headerIndex = -1;
    String headerValue = null;
    do {
         headerIndex++;
         String header = c.getString(getColumnClass());
         if (!header.equalsIgnoreCase(headerValue)) {
                    mHeaderIndexes.add(headerIndex);
                    headerValue = header;
                    headerIndex++;
          }
    }while (c.moveToNext());
    c.moveToFirst();
    mDataCount = c.getCount()+mHeaderIndexes.size();

Override methods

@Override
    public int getCount() {
        return mDataCount;
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderIndexes.contains(position)) {
            return TYPE_HEADER_ROW;
        }
        return TYPE_ROW;
    }

    @Override
    public Object getItem(int position) {
        if (mHeaderIndexes.contains(position)) {
            // for header row need return first row with data for this group
            getCursor().moveToPosition(position-mHeaderIndexes.indexOf(position));
        }
        else {
            for (int i = 0; i < mHeaderIndexes.size(); i++) {
                if (mHeaderIndexes.get(i) > position) {
                    // need move back by number of headers before position
                    getCursor().moveToPosition(position - i);
                    break;
                }
            }
            if (position>mHeaderIndexes.get(mHeaderIndexes.size()-1)) {
                // if position is in the last group (position >last group header position)
                // move back by number of headers
                getCursor().moveToPosition(position - mHeaderIndexes.size());
            }
        }
        return getCursor();
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public boolean isEnabled(int position) {
        return !mHeaderIndexes.contains(position);
    }

Implement getView()

    public View getView(int position, View convertView, ViewGroup parent) {
        int type = getItemViewType(position);
        Cursor cursor = (Cursor) getItem(position);

        View view = convertView;
        if (type==TYPE_HEADER_ROW) {
            boolean isHeader = view!=null && view.findViewById(R.id.title)!=null;
            if (!isHeader) {
                view = mInflater.inflate(R.layout.row_my_header, null);
            }
            TextView header = view.findViewById(R.id.title);
            header.setText(...);
        }
        else {
            if (view==null) {
                view = mInflater.inflate(R.layout.row_my_data, null);
            }
    // fill data row
         }
    return view;
    }


问:
How to get array with intersected elements?
I have an array, that contains another arrays with string id's. I need to get an array with string ids, that are exists in all arrays of parent.

Here is example:

```<code>const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

//some magic. Maybe use lodash instersection func

console.log(result) => ['test2']
</code>```

Important note! I don't know, how much arrays of elements in parent array, thats the problem that i cant understand how to use lodash intersection function:(

答:
```<code>const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

let common = parentArray.reduce((p,c) => p.filter(e => c.includes(e)));

// ['test2']
</code>```

Body:
I have an array, that contains another arrays with string id's. I need to get an array with string ids, that are exists in all arrays of parent.

Here is example:

const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

//some magic. Maybe use lodash instersection func

console.log(result) => ['test2']

Important note! I don't know, how much arrays of elements in parent array, thats the problem that i cant understand how to use lodash intersection function:(


问:
How to get select value on form in php?
I want to get a selected value on the form.

Suppose If I select category "car" from sub-category "nissan".
I want this value on php.

Not value 1 and 1 because I do not recognise what value is selected.
I want name or unique value in my php file.

This is php file on the same page:

```<code><?php

if(isset($_POST['select1'])){
    $select1 = $_POST['select1'];
}

if(isset($_POST['select2'])){
 $select2 = $_POST['select2'];
}

?>

 <html>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
 </script>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<select name="select1" id="select1">
 <option value=""></option>
 <option value="1">car</option>
 <option value="2">phone</option>
 <option value="3">tv</option>
</select>

<select name="select2" id="select2">
 <option value=""></option>
 <option value="1">toyota</option>
 <option value="1">nissan</option>
 <option value="1">bmw</option>
 <option value="2">Iphone</option>
 <option value="2">LG</option>
 <option value="2">Samsung</option>
 <option value="3">Philips</option>
 <option value="3">Samsung</option>
</select>
</form>
</html>

<script>
 $("#select1").change(function() {
  if ($(this).data('options') == undefined) {
  /*Taking an array of all options-2 and kind of embedding it on the select1*/
  $(this).data('options', $('#select2 option').clone());
  }
  var id = $(this).val();
  var options = $(this).data('options').filter('[value=' + id + ']');
  $('#select2').html(options);
 });
</script>
</code>```

Any idea or suggestions would be welcome
Thank You.

答:
You can remove the value property from all your options if you want to receive the text on the server instead. Try this

// get all categories and sub categories
let categories = {};
$('#select2 option[data-category]').each(function(i, element){
    let category = $(this).data('category');

    // add category
    if( categories[category] == undefined ) categories[category] = [];
    // add sub category to category
    categories[category].push(element.textContent);
    // remove the option from the DOM
    element.remove();
});

// append related sub categories to #select 2
$("#select1").change(function() {
    let subs = categories[this.value] ?? []; // sub categories for selected category
    $('#select2').html('<option></option>').append(subs.map(txt => `<option>${txt}</option>`));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
    <select name="select1" id="select1">
        <option></option>
        <option>car</option>
        <option>phone</option>
        <option>tv</option>
    </select>
    <select name="select2" id="select2">
        <option></option>
        <option data-category="car">toyota</option>
        <option data-category="car">nissan</option>
        <option data-category="car">bmw</option>
        <option data-category="phone">Iphone</option>
        <option data-category="phone">LG</option>
        <option data-category="phone">Samsung</option>
        <option data-category="tv">Philips</option>
        <option data-category="tv">Samsung</option>
    </select>
</form></code>```

Title: How to get select value on form in php?

Body:
I want to get a selected value on the form.

Suppose If I select category "car" from sub-category "nissan".
I want this value on php.

Not value 1 and 1 because I do not recognise what value is selected.
I want name or unique value in my php file.

This is php file on the same page:

<?php

if(isset($_POST['select1'])){
    $select1 = $_POST['select1'];
}

if(isset($_POST['select2'])){
 $select2 = $_POST['select2'];
}

?>

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<select name="select1" id="select1">
 <option value=""></option>
 <option value="1">car</option>
 <option value="2">phone</option>
 <option value="3">tv</option>
</select>

<select name="select2" id="select2">
 <option value=""></option>
 <option value="1">toyota</option>
 <option value="1">nissan</option>
 <option value="1">bmw</option>
 <option value="2">Iphone</option>
 <option value="2">LG</option>
 <option value="2">Samsung</option>
 <option value="3">Philips</option>
 <option value="3">Samsung</option>
</select>
</form>

Any idea or suggestions would be welcome
Thank You.

Body:
You can remove the value property from all your options if you want to receive the text on the server instead. Try this

// get all categories and sub categories
let categories = {};
$('#select2 option[data-category]').each(function(i, element){
    let category = $(this).data('category');

    // add category
    if( categories[category] == undefined ) categories[category] = [];
    // add sub category to category
    categories[category].push(element.textContent);
    // remove the option from the DOM
    element.remove();
});

// append related sub categories to #select 2
$("#select1").change(function() {
    let subs = categories[this.value] ?? []; // sub categories for selected category
    $('#select2').html('<option></option>').append(subs.map(txt => `<option>${txt}</option>`));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
    <select name="select1" id="select1">
        <option></option>
        <option>car</option>
        <option>phone</option>
        <option>tv</option>
    </select>
    <select name="select2" id="select2">
        <option></option>
        <option data-category="car">toyota</option>
        <option data-category="car">nissan</option>
        <option data-category="car">bmw</option>
        <option data-category="phone">Iphone</option>
        <option data-category="phone">LG</option>
        <option data-category="phone">Samsung</option>
        <option data-category="tv">Philips</option>
        <option data-category="tv">Samsung</option>
    </select>
</form>