问:
TemplateDoesNotExist at/
here is my site url http://webtrick.heliohost.org/
my template directory settings:

```<code>TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__) , 'templates').replace('\\','/')
)
</code>```

view.py

```<code>from django.http import HttpResponse
from django.template import Template , Context
from django.shortcuts import render_to_response
def index(request):
        return render_to_response('index.html')
</code>```

url.py

```<code>from django.conf.urls.defaults import patterns, include, url
from webtrickster.views import index
urlpatterns = patterns('',
    url(r'^$', index)
)
</code>```

i don't know what's wrong with this code
any help appreciated

答:
I encountered the same error. After checking TEMPLATE_DIR and INSTALLED_APPS a thousand times I noticed a small typo in one .html template:

```<code>{% extends "my_app/base.html " %}
</code>```

should have been

```<code>{% extends "my_app/base.html" %}
</code>```

(notice the white space in the first command)

Title: TemplateDoesNotExist at/

Body:
here is my site url http://webtrick.heliohost.org/
my template directory settings:

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__) , 'templates').replace('\\','/')
)

view.py

from django.http import HttpResponse
from django.template import Template , Context
from django.shortcuts import render_to_response
def index(request):
        return render_to_response('index.html')

url.py

from django.conf.urls.defaults import patterns, include, url
from webtrickster.views import index
urlpatterns = patterns('',
    url(r'^$', index)
)

i don't know what's wrong with this code
any help appreciated

Body:
I encountered the same error. After checking TEMPLATE_DIR and INSTALLED_APPS a thousand times I noticed a small typo in one .html template:

{% extends "my_app/base.html " %}

should have been

{% extends "my_app/base.html" %}

(notice the white space in the first command)


来源: stackexchange

问:
Push object data into an array based on another object data value in javascript
I would like to push the values based on another value dynamically into an Array Here is my example:

```<code>const searchData = [
  {
    name: 'Name1',
    value: 'value1',
    class: 'class1',
  },
  {
    name: 'Name1',
    value: 'value2',
    class: 'class2',
  },
];

const data = [
  {
    ID: 'ID1',
    staff: [{ value1: 'hello1', value2: 'hallo1' }],
  },
  {
    ID: 'ID2',
    staff: [{ value1: 'hello2', value2: 'hallo2' }],
  },
];

const array = [];

data.foreach(dataElem => {
  dataElem.staff.foreach(staffElem => {
    searchData.foreach(searchElem => {
      array.push(staffElem[searchElem.value]); // all are undefined -> why?
    )}
  )}
})
</code>```

I don't know why I getting undefined instead of the real values.

答:
Your code has syntax error logic is right
Compare this with above one</p>
```<code>data.forEach(dataElem => {
  dataElem.staff.forEach(staffElem => {
    searchData.forEach(searchElem => {
      array.push(staffElem[searchElem.value])
    })
  })
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to push the values based on another value dynamically into an Array Here is my example:

const searchData = [
  {
    name: 'Name1',
    value: 'value1',
    class: 'class1',
  },
  {
    name: 'Name1',
    value: 'value2',
    class: 'class2',
  },
];

const data = [
  {
    ID: 'ID1',
    staff: [{ value1: 'hello1', value2: 'hallo1' }],
  },
  {
    ID: 'ID2',
    staff: [{ value1: 'hello2', value2: 'hallo2' }],
  },
];

const array = [];

data.foreach(dataElem => {
  dataElem.staff.foreach(staffElem => {
    searchData.foreach(searchElem => {
      array.push(staffElem[searchElem.value]); // all are undefined -> why?
    )}
  )}
})

I don't know why I getting undefined instead of the real values.

Body:
Your code has syntax error logic is right
Compare this with above one

data.forEach(dataElem => {
  dataElem.staff.forEach(staffElem => {
    searchData.forEach(searchElem => {
      array.push(staffElem[searchElem.value])
    })
  })
})


问:
Will using Parallel.ForEach benefit in ObjectContext.Add
I am using Entity Framework with the generic repository pattern. I have used the following method to add an object.

```<code>public int Add<TEntity>(TEntity entity) where TEntity : class
{
   DataContext.AddObject(GetEntityName<TEntity>(), entity);
   return SaveChanges();
}
</code>```

I am also thinking of extending this to support multiple entities.

```<code>public int Add<TEntity>(TEntity[] collection) where TEntity : class
{
   foreach (TEntity item in collection)
   {
     DataContext.AddObject(GetEntityName<TEntity>(), item);
   }

   return SaveChanges();
}
</code>```

Will there be an actual benefit in using Parallel.ForEach instead of the foreach loop in the above scenario?

Also because I haven't called SaveChanges() until the end of the loop, if there is lets say a primary key violation, will it be thrown inside the loop or when SaveChanges() is called? Will I be able to rollback the changes?

答:
ObjectContext is not thread safe. Here's the remark on MSDN

The ObjectContext class is not thread safe. The integrity of data
  objects in an ObjectContext cannot be ensured in multithreaded
  scenarios.

So better not use Parallel.ForEach.

ContentLicense: CC BY-SA 3.0

Body:
I am using Entity Framework with the generic repository pattern. I have used the following method to add an object.

public int Add<TEntity>(TEntity entity) where TEntity : class
{
   DataContext.AddObject(GetEntityName<TEntity>(), entity);
   return SaveChanges();
}

I am also thinking of extending this to support multiple entities.

public int Add<TEntity>(TEntity[] collection) where TEntity : class
{
   foreach (TEntity item in collection)
   {
     DataContext.AddObject(GetEntityName<TEntity>(), item);
   }

   return SaveChanges();
}

Will there be an actual benefit in using Parallel.ForEach instead of the foreach loop in the above scenario?

Also because I haven't called SaveChanges() until the end of the loop, if there is lets say a primary key violation, will it be thrown inside the loop or when SaveChanges() is called? Will I be able to rollback the changes?


问:
Count Number of Good Nodes
problem statement

I am having trouble understanding what is wrong with my code and understanding the constraint below.

My pseudocode:

Traverse the tree Level Order and construct the array representation (input is actually given as a single root, but they use array representation to show the full tree)

iterate over this array representation, skipping null nodes

for each node, let's call it X, iterate upwards until we reach the root checking to see if at any point in the path, parentNode > nodeX, meaning, nodeX is not a good node.

increment counter if the node is good

Constraints:

The number of nodes in the binary tree is in the range [1, 10^5].

Each node's value is between [-10^4, 10^4]

First of all:
My confusion on the constraint is that, the automated tests are giving input such as [2,4,4,4,null,1,3,null,null,5,null,null,null,null,5,4,4] and if we follow the rules that childs are at c1 = 2k+1 and c2 = 2k+2 and parent = (k-1)//2 then  this means that there are nodes with value null

Secondly:
For the input above, my code outputs 8, the expected value is 6, but when I draw the tree from the array, I also think the answer should be 8!

tree of input

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def goodNodes(self, root: TreeNode) -> int:

        arrRepresentation = []

        queue = []

        queue.append(root)

        # while queue not empty
        while queue:
            # remove node
            node = queue.pop(0)
            if node is None:
                arrRepresentation.append(None)

            else:
                arrRepresentation.append(node.val)

            if node is not None:
                # add left to queue
                queue.append(node.left)

                # add right to queue
                queue.append(node.right)

        print(arrRepresentation)
        goodNodeCounter = 1

        # iterate over array representation of binary tree
        for k in range(len(arrRepresentation)-1, 0, -1):
            child = arrRepresentation[k]
            if child is None:
                continue
            isGoodNode = self._isGoodNode(k, arrRepresentation)
            print('is good: ' + str(isGoodNode))

            if isGoodNode:
                goodNodeCounter += 1

        return goodNodeCounter

    def _isGoodNode(self, k, arrRepresentation):

        child = arrRepresentation[k]
        print('child: '+str(child))
        # calculate index of parent
        parentIndex = (k-1)//2

        isGood = True
        # if we have not reached root node
        while parentIndex >= 0:
            parent = arrRepresentation[parentIndex]
            print('parent: '+ str(parent))
            # calculate index of parent
            parentIndex = (parentIndex-1)//2

            if parent is None:
                continue

            if parent > child:
                isGood = False
                break

        return isGood

```

答:
Since you wanted to solve with breadth first search:

```<code>from collections import deque

class Solution:
    def goodNodes(self,root:TreeNode)->int:
        if not root:
            return 0
        queue=deque()
        # run bfs  with track of max_val till its parent node
        queue.append((root,-inf))
        res=0
        while queue:
            current,max_val=queue.popleft()
            if current.val>=max_val:
                res+=1
            if current.left:
                queue.append((current.left,max(max_val,current.val)))

            if current.right:
                queue.append((current.right,max(max_val,current.val)))
        return res
</code>```

I added the node and its max_value till its parent node. I could not add a global max_value, because look at this tree:

For the first 3 nodes, you would have this [3,1,4] and if you were keeping the max_val globally, max_val would be 4.

Now next node would be 3, leaf node on the left. Since max_node is 4, 3<4 would be incorrect so 3 would not be considered as good node. So instead, I keep track of max_val of each node till its parent node

Title: Count Number of Good Nodes

Body:
Since you wanted to solve with breadth first search:

from collections import deque

class Solution:
    def goodNodes(self,root:TreeNode)->int:
        if not root:
            return 0
        queue=deque()
        # run bfs  with track of max_val till its parent node
        queue.append((root,-inf))
        res=0
        while queue:
            current,max_val=queue.popleft()
            if current.val>=max_val:
                res+=1
            if current.left:
                queue.append((current.left,max(max_val,current.val)))

            if current.right:
                queue.append((current.right,max(max_val,current.val)))
        return res

I added the node and its max_value till its parent node. I could not add a global max_value, because look at this tree:

For the first 3 nodes, you would have this [3,1,4] and if you were keeping the max_val globally, max_val would be 4.

Now next node would be 3, leaf node on the left. Since max_node is 4, 3<4 would be incorrect so 3 would not be considered as good node. So instead, I keep track of max_val of each node till its parent node


问:
iptables: how to drop packets by their first bytes
I want all packets whose content starts with "\x18\x00" to be dropped.
And so, I wrote the following config:

```<code>iptables -N LIMIT
iptables -I INPUT -j LIMIT
iptables -A LIMIT -p udp -m string --string "\x18\x00" --algo kmp -j DROP
</code>```

But iptables turns my bytes into a string and no packets are dropped.

答:
I add "$" before my bytes string,like this:</p>
```<code>iptables -N LIMIT
iptables -I INPUT -j LIMIT
iptables -A LIMIT -p udp -m string --string $"\x18\x00" --algo kmp -j DROP
</code>```

Body:
I want all packets whose content starts with "\x18\x00" to be dropped.
And so, I wrote the following config:

iptables -N LIMIT
iptables -I INPUT -j LIMIT
iptables -A LIMIT -p udp -m string --string "\x18\x00" --algo kmp -j DROP

But iptables turns my bytes into a string and no packets are dropped.

Body:
I add "$" before my bytes string,like this:

iptables -N LIMIT
iptables -I INPUT -j LIMIT
iptables -A LIMIT -p udp -m string --string $"\x18\x00" --algo kmp -j DROP


问:
Is it necessary to put space after $this keyword in OOP PHP according to PSRs?
I studied PSR-2 and PSR-12 documentations completely but didn't find any explanation regarding whether to put any space after $this keyword.

My exact question is which one of following styles is more correct according to PSRs:

```<code>return $this->name;
</code>```

or

```<code>return $this -> name;
</code>```

sample codes to compare would be as below:

```<code>class Car
{
    public $name;
    public function getName()
    {
        return $this->name; // I've always seen this style (no spaces)
    }
}
</code>```

in comparison with:

```<code>class Car
{
    public $name;
    public function getName()
    {
        return $this -> name; // Includes spaces
    }
}
</code>```

Are both correct? If so, is there a reason to use one over the other?

答:
There are no explicit rules for this in the standards mentioned, and no examples using $this in particular, but there are plenty of other examples of using the -> operator, and they consistently show it with no spaces around.

For instance, under "Method and Function Calls" (PSR-2 §4.6 / PSR-12 §4.7):

```<code>$foo->bar($arg1);
</code>```

and

```<code>$foo->bar(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
);
</code>```

This doesn't mean that the standard requires that style, but it's a small piece of evidence that this is what most PHP developers would naturally expect.

Body:
I studied PSR-2 and PSR-12 documentations completely but didn't find any explanation regarding whether to put any space after $this keyword.

My exact question is which one of following styles is more correct according to PSRs:

return $this->name;

or

return $this -> name;

sample codes to compare would be as below:

class Car
{
    public $name;
    public function getName()
    {
        return $this->name; // I've always seen this style (no spaces)
    }
}

in comparison with:

class Car
{
    public $name;
    public function getName()
    {
        return $this -> name; // Includes spaces
    }
}

Are both correct? If so, is there a reason to use one over the other?

Body:
There are no explicit rules for this in the standards mentioned, and no examples using $this in particular, but there are plenty of other examples of using the -> operator, and they consistently show it with no spaces around.

For instance, under "Method and Function Calls" (PSR-2 §4.6 / PSR-12 §4.7):

$foo->bar($arg1);

and

$foo->bar(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
);

This doesn't mean that the standard requires that style, but it's a small piece of evidence that this is what most PHP developers would naturally expect.


问:
@selector() in Swift?
I'm trying to create an NSTimer in Swift but I'm having some trouble.

```<code>NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)
</code>```

test() is a function in the same class.

I get an error in the editor:

Could not find an overload for 'init' that accepts the supplied
  arguments

When I change selector: test() to selector: nil the error disappears.

I've tried:

selector: test()

selector: test

selector: Selector(test())

But nothing works and I can't find a solution in the references.

答:
As many have stated selectors are an objective c way of dynamically calling methods that has been carried over to Swift, it some case we are still stuck with it, like UIKit, probable because they where working on SwiftUI to replace it but some api have more swift like version like Swift Timer, for example you can use

```<code>class func scheduledTimer(withTimeInterval interval: TimeInterval,
                                            repeats: Bool,
                                              block: @escaping (Timer) -> Void) -> Timer
</code>```

Instead, you can then call it like

```<code>Timer.scheduledTimer(withTimeInterval: 1,
                              repeats: true ) {
    ... your test code here
}
</code>```

or

```<code>Timer.scheduledTimer(withTimeInterval: 1,
                              repeats: true,
                              block: test)
</code>```

where the method test takes a Timer argument, or if you want test to take an named argument

```<code>Timer.scheduledTimer(withTimeInterval: 1,
                              repeats: true,
                              block: test(timer:))
</code>```

you should also be using Timer not NSTimer as NSTimer is the old objective-c name

Title: @selector() in Swift?

Body:
I'm trying to create an NSTimer in Swift but I'm having some trouble.

NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)

test() is a function in the same class.

I get an error in the editor:

Could not find an overload for 'init' that accepts the supplied
  arguments

When I change selector: test() to selector: nil the error disappears.

I've tried:

selector: test()

selector: test

selector: Selector(test())

But nothing works and I can't find a solution in the references.

Body:
As many have stated selectors are an objective c way of dynamically calling methods that has been carried over to Swift, it some case we are still stuck with it, like UIKit, probable because they where working on SwiftUI to replace it but some api have more swift like version like Swift Timer, for example you can use

class func scheduledTimer(withTimeInterval interval: TimeInterval,
                                            repeats: Bool,
                                              block: @escaping (Timer) -> Void) -> Timer

Instead, you can then call it like

Timer.scheduledTimer(withTimeInterval: 1,
                              repeats: true ) {
    ... your test code here
}

or

Timer.scheduledTimer(withTimeInterval: 1,
                              repeats: true,
                              block: test)

where the method test takes a Timer argument, or if you want test to take an named argument

Timer.scheduledTimer(withTimeInterval: 1,
                              repeats: true,
                              block: test(timer:))

you should also be using Timer not NSTimer as NSTimer is the old objective-c name


问:
create spinner options from json data / array
1. My question: How do I take my JSON data and parse it into an array that I can use in my spinner.

Below is my json data:

```<code>[["Mike Test 1"],["Mike Test 2"],["hello world"],["TEST MIKE 4"],["TEST MIKE 6"],["aliens,crazy stuff"],["Alien"],["american flags,flags"]]
</code>```

My script calls a function that gets the data. I know that is working because I have toasted the return value. It should then loop through and assign the values to a new array that is used in the spinner.

Below is my java:

```<code>  Spinner areaspinner;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    JSONArray jsonArray;

    try {
    //SETTINGS AND METHOD THAT GETS THE DATA
        String spinnerContentType = "styles";
        String spinnerURL = "getStyles.php";
        String spinner_data =  DataCall.getJSON(spinnerURL,spinnerContentType);

     //NEW JSONArray OBJECT
        jsonArray = new JSONArray(spinner_data);

        final String[] array_spinner = new String[jsonArray.length()];

        int show_total = jsonArray.length();
        //CHECK HOW MANY ITEMS ARE RETURNED
        Toast.makeText(flash_tattoo.this, show_total + "test", Toast.LENGTH_LONG).show();

        for (int i=0; i<jsonArray.length(); i++)
        {
            //LOOP AND ASSIGN TO ARRAY
            String styleValue = jsonArray.getJSONArray(0).getString(i);
            array_spinner[i] = styleValue;

        }
        ArrayAdapter<String> adapter =
            new ArrayAdapter<String> (this,
                    android.R.layout.simple_spinner_item,array_spinner);

        adapter.setDropDownViewResource(R.layout.spinner_layout);
        areaspinner.setAdapter(adapter);

    }catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

This is my spinner layout:

```<code><?xml version="1.0" encoding="utf-8"?>

<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/text1"
  style="?android:attr/spinnerDropDownItemStyle"
  android:singleLine="true"
  android:layout_width="fill_parent"
  android:layout_height="?android:attr/listPreferredItemHeight"
  android:textColor="#e70909"
/>
</code>```

答:
To me it looks like areaspinner is null.

To add a spinner you have something like this in your main.xml.

```<code><Spinner android:id="@+id/mySpinner"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:prompt="@string/mySpinnerText" />
</code>```

Then in onCreate()

```<code>Spinner sp = (Spinner) findViewById(R.id.mySpinner);
        ArrayAdapter<String> adapter =
                new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, array_spinner);
        adapter.setDropDownViewResource(R.layout.spinner_layout);
        sp.setAdapter(adapter);
</code>```

Body:
1. My question: How do I take my JSON data and parse it into an array that I can use in my spinner.

Below is my json data:

[["Mike Test 1"],["Mike Test 2"],["hello world"],["TEST MIKE 4"],["TEST MIKE 6"],["aliens,crazy stuff"],["Alien"],["american flags,flags"]]

My script calls a function that gets the data. I know that is working because I have toasted the return value. It should then loop through and assign the values to a new array that is used in the spinner.

Below is my java:

  Spinner areaspinner;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    JSONArray jsonArray;

    try {
    //SETTINGS AND METHOD THAT GETS THE DATA
        String spinnerContentType = "styles";
        String spinnerURL = "getStyles.php";
        String spinner_data =  DataCall.getJSON(spinnerURL,spinnerContentType);

     //NEW JSONArray OBJECT
        jsonArray = new JSONArray(spinner_data);

        final String[] array_spinner = new String[jsonArray.length()];

        int show_total = jsonArray.length();
        //CHECK HOW MANY ITEMS ARE RETURNED
        Toast.makeText(flash_tattoo.this, show_total + "test", Toast.LENGTH_LONG).show();

        for (int i=0; i<jsonArray.length(); i++)
        {
            //LOOP AND ASSIGN TO ARRAY
            String styleValue = jsonArray.getJSONArray(0).getString(i);
            array_spinner[i] = styleValue;

        }
        ArrayAdapter<String> adapter =
            new ArrayAdapter<String> (this,
                    android.R.layout.simple_spinner_item,array_spinner);

        adapter.setDropDownViewResource(R.layout.spinner_layout);
        areaspinner.setAdapter(adapter);

    }catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

This is my spinner layout:

<?xml version="1.0" encoding="utf-8"?>

<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/text1"
  style="?android:attr/spinnerDropDownItemStyle"
  android:singleLine="true"
  android:layout_width="fill_parent"
  android:layout_height="?android:attr/listPreferredItemHeight"
  android:textColor="#e70909"
/>

Body:
To me it looks like areaspinner is null.

To add a spinner you have something like this in your main.xml.

<Spinner android:id="@+id/mySpinner"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:prompt="@string/mySpinnerText" />

Then in onCreate()

Spinner sp = (Spinner) findViewById(R.id.mySpinner);
        ArrayAdapter<String> adapter =
                new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, array_spinner);
        adapter.setDropDownViewResource(R.layout.spinner_layout);
        sp.setAdapter(adapter);


问:
How to list users and its permissions with AWS CLI?
I run this command: aws iam list-users, and I get a list of users but not permissions (meaning if someone is root, or s3fullaccess and so for) are listed.

I run this other command: aws iam list-user-policies --user-name xxxxx, and I get this result below empty:

```<code>{
    "PolicyNames": []
}
</code>```

Which command or what combination of commands I need to display all users plus their respective permissions?, thanks.

答:
Kindly run below one liner bash script regarding to list all users with their policies, groups,attached polices.</p>
```<code>aws iam list-users |grep -i username > list_users ; cat list_users |awk '{print $NF}' |tr '\"' ' ' |tr '\,' ' '|while read user; do echo "\n\n--------------Getting information for user $user-----------\n\n" ; aws iam list-user-policies --user-name $user --output yaml; aws iam list-groups-for-user  --user-name $user --output yaml;aws iam  list-attached-user-policies --user-name $user --output yaml ;done ;echo;echo
</code>```

Body:
I run this command: aws iam list-users, and I get a list of users but not permissions (meaning if someone is root, or s3fullaccess and so for) are listed.

I run this other command: aws iam list-user-policies --user-name xxxxx, and I get this result below empty:

{
    "PolicyNames": []
}

Which command or what combination of commands I need to display all users plus their respective permissions?, thanks.

Body:
Kindly run below one liner bash script regarding to list all users with their policies, groups,attached polices.

aws iam list-users |grep -i username > list_users ; cat list_users |awk '{print $NF}' |tr '\"' ' ' |tr '\,' ' '|while read user; do echo "\n\n--------------Getting information for user $user-----------\n\n" ; aws iam list-user-policies --user-name $user --output yaml; aws iam list-groups-for-user  --user-name $user --output yaml;aws iam  list-attached-user-policies --user-name $user --output yaml ;done ;echo;echo


问:
change color using JavaScript (DOM)
```<code> const box = document.getElementsByClassName('box');
 let colorAsString = '#FEC6F0';
 let colorAsNumber = #FEC6F0;
    Array.from(box).forEach((element) =>{
        element.style.backgroundColor = colorAsString;
        element.style.backgroundColor = colorAsNumber;
    });
</code>```

I stored a hex-color value in string as well as a number and pass the variable as a value for css property.
Why this code not work can you explain me...!

答:
It's working

```<code><html>
 <body>
     <p id="p">
       on click change my color
     </p>
    <script>
      onclick = function(){
         document.getElementById("p").style.color = "#fff";

        document.getElementById("p").style.background = "#000";
      }
    </script>
  </body>
  </html>
</code>```

Title: change color using JavaScript (DOM)

Body:
 const box = document.getElementsByClassName('box');
 let colorAsString = '#FEC6F0';
 let colorAsNumber = #FEC6F0;
    Array.from(box).forEach((element) =>{
        element.style.backgroundColor = colorAsString;
        element.style.backgroundColor = colorAsNumber;
    });

I stored a hex-color value in string as well as a number and pass the variable as a value for css property.
Why this code not work can you explain me...!

Body:
It's working

<html>
 <body>
     <p id="p">
       on click change my color
     </p>
    <script>
      onclick = function(){
         document.getElementById("p").style.color = "#fff";

        document.getElementById("p").style.background = "#000";
      }
    </script>
  </body>
  </html>


问:
create a notification/alert at a specific time html css angular
i created a notification box that it shows me an alert when i create a notification from the date which i create this notification.

but i want now to add a new feature "start from" or something else, to be this notification active in this time.

For Example: i created the notification in 14:00 but it should appears automatically at 14:30.

how can i do it ? which technic should i do to make it?

thanks for your suggestion.

答:
look into setTimeout(). It lets you execute a function after an interval in milliseconds. For example:

```<code>setTimeout(function(){
// show notification after half an hour
}, 30 * 60 * 1000)
</code>```

Body:
look into setTimeout(). It lets you execute a function after an interval in milliseconds. For example:

setTimeout(function(){
// show notification after half an hour
}, 30 * 60 * 1000)


问:
PathFinding Algorithm: How to handle changing Weights Efficiently
So, I have a simple pathfinding algorithm which precalculates the shortest route to several target endpoints, each of which has a different weight.  This is somewhat equivalent to having one endpoint with a node between it and each endpoint, though the edges there have different weights.  The algorithm it uses is a simple spreading algorithm, which in 1d looks this this (| means wall, - means space):

5 - - - 3 | - - - 2 - - - - 2

5 4 - - 3 | - - - 2 - - - - 2 : Handled distance 5 nodes

5 4 3 - 3 | - - - 2 - - - - 2 : Handled distance 4 nodes

5 4 3 2 3 | - - - 2 - - - - 2 : Handled distance 3 nodes

5 4 3 2 3 | - - 1 2 1 - - 1 2 : Handled distance 2 nodes

Done.  Any remaining rooms are unreachable.

So, let's suppose I have a precalculated pathfinding solution like this one, where only the 5 is a target:

- - - - | 5 4 3 2 1 -

If I change the wall to a room.  Recomputing is simple.  Just re-handle all distance nodes (but ignore the ones which already exist).  However, I am not able to figure out an efficient way to handle what to do if the 4 became a wall.  Clearly the result is this:

- - - - | 5 | - - - -

However, in a 2d solution I'm not sure how to efficiently deal with 4.  It is easily possible to store that 4 depends on 5 and thus needs recaculation, but how do I determine its new dependency and values safely? I'd rather avoid recalculating the entire array.

One solution, which is better than nothing, is (roughly) to only recalculate array elements with a manhattan distance of 5 from the 5, and to maintain source information.
This would basically mean reapplying the algorithm to a selected area But can I do better?

答:
Hmmm.  One solution I've come up with is this:
Keep a list of nodes that are reachable most quickly from each node.  If a node becomes a wall, check which node it was reachable from and grab the corresponding list.  Then Recheck all those nodes using the standard algorithm.  When reaching a node where the new distance is smaller, mark it as being in need of retesting.

Take all the neighbors of the marked nodes which are unmarked and reapply the algorithm on them, ignoring any marked nodes that this technique hits.  If the reapplied algorithm increases the value of a marked node, use the new value.

OwnerDisplayName: Brian

ContentLicense: CC BY-SA 2.5


问:
Django : How i can logged in by email instead of username
I want to make the email be set in the frontend of the django application.

I have go and create this class to make the authentification based on the email

```<code>class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
</code>```

Then I have go and define the path of this class in the settings.py

Everything is good without error and I logged in by typing the email. But in the frontend, the label is still "Username". How can I modify it?

Here it's the Html code form login page:

```<code><form method="POST">
            {% csrf_token %} <!--this protect our form against certeain attacks ,added security django rquires-->
            <fieldset class="form-group">
              {{ form|crispy}}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Login</button>
                <small class="test-muted ml-2">
                   <a class="ml-2" href="{% url 'password_reset' %}">Forgot Password?</a>
                </small>
            </div>
            <!--- put div for a link if he is already have account--->
            <div class="border-top pt-3">
                <small class="test-muted">Need an account? <a class="ml-2" href="{% url 'register' %}">Sign Up</a></small>
                <!--it a bootstrap -->
            </div>
        </form>
</code>```

Edited:
This is the view code:

```<code>def login_view(request):

    context = {}
    user = request.user
    destination = get_redirect_if_exists(request)

    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            password = form.cleaned_data["password"]
            user = authenticate(request, email=email, password=password)
            if user == None:
                attempt = request.session.get("attempt") or 0
                request.session['attempt'] = attempt + 1
                return render(request, 'pages/login.html')
            else:
                login(request, user)
                destination = get_redirect_if_exists(request)
                if destination:
                    return redirect(destination)
                return redirect("home")
    return render(request, 'pages/login.html')
</code>```

and this is the login form code:

```<code>class LoginForm(UserCreationForm):
    email = forms.CharField(label='email')
    password = forms.CharField(label='password')
</code>```

答:
Probably you should change form</p>
```<code>urlpatterns = [
   path('login/', LoginView.as_view(authentication_form=YourForm), name='login'),
]

class YourForm(AuthenticationForm):
    username = forms.CharField(widget=TextInput(attrs={'class':'validate','placeholder': 'Username or Email'}))
    password = forms.CharField(widget=PasswordInput(attrs={'placeholder':'Password'})
</code>```

Body:
I want to make the email be set in the frontend of the django application.

I have go and create this class to make the authentification based on the email

class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

Then I have go and define the path of this class in the settings.py

Everything is good without error and I logged in by typing the email. But in the frontend, the label is still "Username". How can I modify it?

Here it's the Html code form login page:

<form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
              {{ form|crispy}}
            </fieldset>

                <button class="btn btn-outline-info" type="submit">Login</button>

                   Forgot Password?

                Need an account? Sign Up

        </form>

Edited:
This is the view code:

def login_view(request):

    context = {}
    user = request.user
    destination = get_redirect_if_exists(request)

    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            password = form.cleaned_data["password"]
            user = authenticate(request, email=email, password=password)
            if user == None:
                attempt = request.session.get("attempt") or 0
                request.session['attempt'] = attempt + 1
                return render(request, 'pages/login.html')
            else:
                login(request, user)
                destination = get_redirect_if_exists(request)
                if destination:
                    return redirect(destination)
                return redirect("home")
    return render(request, 'pages/login.html')

and this is the login form code:

class LoginForm(UserCreationForm):
    email = forms.CharField(label='email')
    password = forms.CharField(label='password')

Body:
Probably you should change form

urlpatterns = [
   path('login/', LoginView.as_view(authentication_form=YourForm), name='login'),
]

class YourForm(AuthenticationForm):
    username = forms.CharField(widget=TextInput(attrs={'class':'validate','placeholder': 'Username or Email'}))
    password = forms.CharField(widget=PasswordInput(attrs={'placeholder':'Password'})


问:
How to create slugs in Laravel?
I'm trying to develop an e-com website in Laravel 5 (Since it required lot of customization, I decided not to use Magento or OpenCart).

The problem I'm facing is to creating category and product URLs from slugs.

For example, one URL can be:

http://somewebsite.com/products/lenovo-yoga-500

But I want to make URL like:

http://somewebsite.com/lenovo-yoga-500

I tried to create a route like:

```<code>Route::get('{slug}', 'BaseController@route');
</code>```

and in the route() method, I tried:

```<code>function route($route){
    $product = Product::where(array('slug' => $slug))->first();

    if(isset($product))
    .....
    else
    .....
</code>```

but first of all, the value is not getting passed to variable '$slug' and secondly I want to redirect the request to another route after checking the condition.

答:
You must use this Route

```<code>Route::get('/sample/show/{sample : slug}',[SampleController::class]);
</code>```

Enter the model of the controller and set the value of getRouteKeyName equal to slug such as:

```<code>public function getRouteKeyName(){return 'slug';}
</code>```

Custom Keys & Scoping

When implicitly binding multiple Eloquent models in a single route definition, you may wish to scope the second Eloquent model such that it must be a child of the previous Eloquent model. For example, consider this route definition that retrieves a blog post by slug for a specific user:

```<code>use App\Models\Post;
use App\Models\User;

Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {    return $post;});
</code>```

Title: How to create slugs in Laravel?

Body:
I'm trying to develop an e-com website in Laravel 5 (Since it required lot of customization, I decided not to use Magento or OpenCart).

The problem I'm facing is to creating category and product URLs from slugs.

For example, one URL can be:

http://somewebsite.com/products/lenovo-yoga-500

But I want to make URL like:

http://somewebsite.com/lenovo-yoga-500

I tried to create a route like:

Route::get('{slug}', 'BaseController@route');

and in the route() method, I tried:

function route($route){
    $product = Product::where(array('slug' => $slug))->first();

    if(isset($product))
    .....
    else
    .....

but first of all, the value is not getting passed to variable '$slug' and secondly I want to redirect the request to another route after checking the condition.

Body:
You must use this Route

Route::get('/sample/show/{sample : slug}',[SampleController::class]);

Enter the model of the controller and set the value of getRouteKeyName equal to slug such as:

public function getRouteKeyName(){return 'slug';}

Custom Keys & Scoping

When implicitly binding multiple Eloquent models in a single route definition, you may wish to scope the second Eloquent model such that it must be a child of the previous Eloquent model. For example, consider this route definition that retrieves a blog post by slug for a specific user:

use App\Models\Post;
use App\Models\User;

Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {    return $post;});


问:
Including classes and jars from a local war file with maven
I have a War file that has dependencies and class files that I need in it that I am trying to include in my project with Maven. Inside the War file, there is a WEB-INF that contains those libs and classes. I have tried everything that I know to try to get this going, but my knowledge of Maven is limited.

I have tried simply listing the War as a dependency and following the process described here to install the third-party library, but when I do that Maven says it can't find my packages that I need when I try to install.

I have tried overlaying the War as described here with no luck.

I have tried maven-warpath-plugin but didn't really have any luck either.

Should any of these tools solve my problem? Is how I am trying to solve the problem possible in this way? Or am I completely off base?

Here are the important parts of my pom.xml from using the maven-warpath-plugin:

```<code><build>
    ...
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.appfuse</groupId>
                <artifactId>maven-warpath-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <extensions>true</extensions>
                <executions>
                    <execution>
                        <goals>
                            <goal>add-classes</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
         </plugins>
    </pluginManagement>
    ...
</build>
<repositories>
    <repository>
        <id>data-local</id>
        <name>data</name>
        <url>file://${project.basedir}/o</url>
    </repository>
</repositories>
<dependencies>
...
    <dependency>
        <groupId>my.local.dep</groupId>
        <artifactId>MyLocalDep</artifactId>
        <version>1.1.1.1</version>
        <type>war</type>
    </dependency>
    <dependency>
        <groupId>my.local.dep</groupId>
        <artifactId>MyLocalDep</artifactId>
        <version>1.1.1.1</version>
        <type>warpath</type>
    </dependency>
</dependencies>
</code>```

答:
Unpack the war in a separate clean step first and add the unpacked jars as system dependency in the main step.

Idea is from here: https://stackoverflow.com/a/6120395/503025

Body:
I have a War file that has dependencies and class files that I need in it that I am trying to include in my project with Maven. Inside the War file, there is a WEB-INF that contains those libs and classes. I have tried everything that I know to try to get this going, but my knowledge of Maven is limited.

I have tried simply listing the War as a dependency and following the process described here to install the third-party library, but when I do that Maven says it can't find my packages that I need when I try to install.

I have tried overlaying the War as described here with no luck.

I have tried maven-warpath-plugin but didn't really have any luck either.

Should any of these tools solve my problem? Is how I am trying to solve the problem possible in this way? Or am I completely off base?

Here are the important parts of my pom.xml from using the maven-warpath-plugin:

<build>
    ...
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.appfuse</groupId>
                <artifactId>maven-warpath-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <extensions>true</extensions>
                <executions>
                    <execution>
                        <goals>
                            <goal>add-classes</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
         </plugins>
    </pluginManagement>
    ...
</build>
<repositories>
    <repository>
        <id>data-local</id>
        <name>data</name>
        <url>file://${project.basedir}/o</url>
    </repository>
</repositories>
<dependencies>
...
    <dependency>
        <groupId>my.local.dep</groupId>
        <artifactId>MyLocalDep</artifactId>
        <version>1.1.1.1</version>
        <type>war</type>
    </dependency>
    <dependency>
        <groupId>my.local.dep</groupId>
        <artifactId>MyLocalDep</artifactId>
        <version>1.1.1.1</version>
        <type>warpath</type>
    </dependency>
</dependencies>


问:
SQL SELECT - order dates with wrong format
I was tasked with ordering some entries in our web application. Current solution made by some other guy 10 years ago, is that there is a select on db and then it iterates and make table.

Problem is, that date is in dd-mm-yyyy format and in varchar data.

And not really sure, if I am brave enought to make changes to the database.

So is there some way to order it anyway within a select, some way to order it by the end meaby? Or only way without making some gruesome function in code is to change the db?

答:
You can use STR_TO_DATE function, but this will work only for small tables(maybe thousands of records), on large data sets you will face performance problems:

```<code>SELECT *
FROM (
  SELECT '01-5-2013' AS Date
  UNION ALL
  SELECT '02-6-2013' AS Date
  UNION ALL
  SELECT '01-6-2013' AS Date
) AS t1
ORDER BY STR_TO_DATE(Date,'%d-%m-%Y')
</code>```

Long term solution should be conversion of that column to proper date type.

Body:
You can use STR_TO_DATE function, but this will work only for small tables(maybe thousands of records), on large data sets you will face performance problems:

SELECT *
FROM (
  SELECT '01-5-2013' AS Date
  UNION ALL
  SELECT '02-6-2013' AS Date
  UNION ALL
  SELECT '01-6-2013' AS Date
) AS t1
ORDER BY STR_TO_DATE(Date,'%d-%m-%Y')

Long term solution should be conversion of that column to proper date type.


答:
You can use the STR_TO_DATE() function for this.  Try

```<code>ORDER BY STR_TO_DATE(varcharDateColumn, '%d-%m-%Y')
</code>```

It converts your character-string dates to the DATE datatype where ordering works without trouble.

As of MySQL 5.7 or later, you can add a so-called generated column to your table without touching the other data.

```<code>     ALTER TABLE tbl
      ADD COLUMN goodDate
              AS (STR_TO_DATE(varcharDateColumn, '%m-%d-%Y'))
          STORED;
</code>```

You can even put an index on that column if you need to use it for searrching.

```<code>ALTER TABLE t1 ADD INDEX goodDate(goodDate);
</code>```

Title: SQL SELECT - order dates with wrong format

Body:
I was tasked with ordering some entries in our web application. Current solution made by some other guy 10 years ago, is that there is a select on db and then it iterates and make table.

Problem is, that date is in dd-mm-yyyy format and in varchar data.

And not really sure, if I am brave enought to make changes to the database.

So is there some way to order it anyway within a select, some way to order it by the end meaby? Or only way without making some gruesome function in code is to change the db?

Body:
You can use the STR_TO_DATE() function for this.  Try

ORDER BY STR_TO_DATE(varcharDateColumn, '%d-%m-%Y')

It converts your character-string dates to the DATE datatype where ordering works without trouble.

As of MySQL 5.7 or later, you can add a so-called generated column to your table without touching the other data.

     ALTER TABLE tbl
      ADD COLUMN goodDate
              AS (STR_TO_DATE(varcharDateColumn, '%m-%d-%Y'))
          STORED;

You can even put an index on that column if you need to use it for searrching.

ALTER TABLE t1 ADD INDEX goodDate(goodDate);


问:
Why does Mongoose have both schemas and models?
The two types of objects seem to be so close to one another that having both feels redundant. What is the point of having both schemas and models?

答:
Schema basically models your data (where you provide datatypes for your fields) and can do some validations on your data. It mainly deals with the structure of your collection.

Whereas the model is a wrapper around your schema to provide you with CRUD methods on collections. It mainly deals with adding/querying the database.

Having both schema and model could appear redundant when compared to other frameworks like Django (which provides only a Model) or SQL (where we create only Schemas and write SQL queries and there is no concept of model). But, this is just the way Mongoose implements it.


问:
Is there a "next" equivalent in map()
When using for example a for loop I can use next to skip a certain item:

```<code>    if (i == 5) next
    print (i)
</code>```

Is there a similar way to do this in a map() or more specifically in a pmap()?

```<code>a <- c(1,2,3)
b <- c(1,1,1)
c <- c(2,2,2)

mapped <- pmap(list(a,b,c),
               function(a,b,c){
                # if (a == 2) next
                print( a + b - c)
               })
</code>```

Thank you for your help!

########## Edit for formatting of my follow up question to Konrad:
Is there any way to avoid getting a NULL element in the list when using if (a != 2)?

```<code>a <- c(1,2,3)
b <- c(1,1,1)
c <- c(2,2,2)

mapped <- pmap(list(a,b,c),
               function(a,b,c){
                 if(a != 2){
                 a + b - c
                 }
               })

str(mapped)
</code>```

returns

```<code>#List of 3
 #$ : num 0
 #$ : NULL
 #$ : num 2
</code>```

But for my solution I would need

```<code>#List of 2
 #$ num 0
 #$ num 2
</code>```

答:
No, the design of map and pmap is that they apply the function to every element.  If you want to skip one, then skip it on the input:

library(purrr)
a <- c(1,2,3)
b <- c(1,1,1)
c <- c(2,2,2)
keep <- a != 2

mapped <- pmap(list(a[keep], b[keep], c[keep]),
               function(a,b,c){
                 a + b - c
               })

str(mapped)
#> List of 2
#>  $ : num 0
#>  $ : num 2
```
<p><sup>Created on 2022-02-08 by the reprex package (v2.0.1.9000)</sup></p>
<p>You can also use <code>purrr</code> functions to do the initial filtering, for example</p>
```list(a,b,c) %>%
map(~ .[a != 2]) %>%
pmap(function(a,b,c){
       a + b - c
     })
```

Title: Is there a "next" equivalent in map()

Body:
When using for example a for loop I can use next to skip a certain item:

    if (i == 5) next
    print (i)

Is there a similar way to do this in a map() or more specifically in a pmap()?

a <- c(1,2,3)
b <- c(1,1,1)
c <- c(2,2,2)

mapped <- pmap(list(a,b,c),
               function(a,b,c){
                # if (a == 2) next
                print( a + b - c)
               })

Thank you for your help!

########## Edit for formatting of my follow up question to Konrad:
Is there any way to avoid getting a NULL element in the list when using if (a != 2)?

a <- c(1,2,3)
b <- c(1,1,1)
c <- c(2,2,2)

mapped <- pmap(list(a,b,c),
               function(a,b,c){
                 if(a != 2){
                 a + b - c
                 }
               })

str(mapped)

returns

#List of 3
 #$ : num 0
 #$ : NULL
 #$ : num 2

But for my solution I would need

#List of 2
 #$ num 0
 #$ num 2

Body:
No, the design of map and pmap is that they apply the function to every element.  If you want to skip one, then skip it on the input:

library(purrr)
a <- c(1,2,3)
b <- c(1,1,1)
c <- c(2,2,2)
keep <- a != 2

mapped <- pmap(list(a[keep], b[keep], c[keep]),
               function(a,b,c){
                 a + b - c
               })

str(mapped)
#> List of 2
#>  $ : num 0
#>  $ : num 2

Created on 2022-02-08 by the reprex package (v2.0.1.9000)

You can also use purrr functions to do the initial filtering, for example

list(a,b,c) %>%
map(~ .[a != 2]) %>%
pmap(function(a,b,c){
       a + b - c
     })


问:
Why does my python script work on desktop but not in programes
So I tried making my first ever script, for some reason the script works fine while im still on desktop, but when I enter a video game (In my example GTA V) the script doesn't input mouse movement, clicks or keyboard. Ive found some solutions online but non work for me... Any help?</p>
```<code>from pydirectinput import *
import pyautogui
import pydirectinput
import time
import keyboard
import random
import win32api, win32con
import sys

while True:
   riba3 = pyautogui.locateCenterOnScreen('riba3.png', confidence=0.5)
   riba2 = pyautogui.locateCenterOnScreen('riba2.png', confidence=0.5)
   riba1 = pyautogui.locateCenterOnScreen('riba1.png', confidence=0.5)
   if riba3:
      pyautogui.moveTo(riba3)
      pyautogui.click(clicks=3, interval=1)

   elif riba2:
       pyautogui.moveTo(riba2)
       pyautogui.click(clicks=3, interval=1)

   elif riba1:
       pyautogui.moveTo(riba1)
       pyautogui.click(clicks=3, interval=1)

</code>```

答: Make sure the terminal you are using to run python file has admin access. I was stuck with the same problem but running the command prompt in admin mode and then launching the py file solved my problem.</p>

Body:
So I tried making my first ever script, for some reason the script works fine while im still on desktop, but when I enter a video game (In my example GTA V) the script doesn't input mouse movement, clicks or keyboard. Ive found some solutions online but non work for me... Any help?

from pydirectinput import *
import pyautogui
import pydirectinput
import time
import keyboard
import random
import win32api, win32con
import sys

while True:
   riba3 = pyautogui.locateCenterOnScreen('riba3.png', confidence=0.5)
   riba2 = pyautogui.locateCenterOnScreen('riba2.png', confidence=0.5)
   riba1 = pyautogui.locateCenterOnScreen('riba1.png', confidence=0.5)
   if riba3:
      pyautogui.moveTo(riba3)
      pyautogui.click(clicks=3, interval=1)

   elif riba2:
       pyautogui.moveTo(riba2)
       pyautogui.click(clicks=3, interval=1)

   elif riba1:
       pyautogui.moveTo(riba1)
       pyautogui.click(clicks=3, interval=1)


问:
FFMPEG : How to swap audio tracks and output the same file
I have a video file with 4 tracks of audio. I need to swap track 1:2 with track 3:4

Here is what i'm trying to achieve

```<code>Input file: 1:2:3:4
Outputfile: 3:4:2:1
</code>```

So simply swapping the audio tracks, here is what i tried:

```<code>ffmpeg -i "test.mxf" -filter_complex "[a:0]amerge=inputs=1[ch1] ;[a:1]amerge=inputs=1[ch2];[a:2]amerge=inputs=1[ch3];[a:3]amerge=inputs=1[ch4]" -map 1:v -map [ch3] -map [ch4] -map [ch1] -map [ch2] -c:v copy -c:a aac -b:a 128k -ar 48000 -ac 2 "out.mxf"
</code>```

Extracting them as separate channels and then mapping them back into the output.

I'm getting error: Invalid input file index: 1

Heres the output log from ffmpeg

```<code>ffmpeg -i "test.mxf" -filter_complex "[a:0]amerge=inputs=1[ch1] ;[a:1]amerge=inputs=1[ch2];[a:2]amerge=inputs=1[ch3];[a:3]amerge=inputs=1[ch4]" -map 1:v -map [ch3] -map [ch4] -map [ch1] -map [ch2] -c:v copy -c:a aac -b:a 128k -ar 48000 -ac 2 "out.mxf"
ffmpeg version 4.3.1-2020-10-01-full_build-www.gyan.dev Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 10.2.0 (Rev3, Built by MSYS2 project)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-lzma --enable-libsnappy --enable-zlib --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libdav1d --enable-libzvbi --enable-librav1e --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --enable-libaom --enable-libopenjpeg --enable-libvpx --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Guessed Channel Layout for Input Stream #0.1 : mono
Guessed Channel Layout for Input Stream #0.2 : mono
Guessed Channel Layout for Input Stream #0.3 : mono
Guessed Channel Layout for Input Stream #0.4 : mono
Input #0, mxf, from 'test.mxf':
  Metadata:
    operational_pattern_ul: 060e2b34.04010101.0d010201.01010900
    uid             : 50a83ad4-88be-11ec-9d91-d0817add6884
    generation_uid  : 50a83ad5-88be-11ec-be21-d0817add6884
    company_name    : Adobe Inc.
    product_name    : Premiere Pro
    product_version : 22.1.2
    application_platform: Mac OS X
    product_uid     : 0c3919fe-46e8-11e5-a151-feff819cdc9f
    modification_date: 2022-02-08T09:05:52.000000Z
    material_package_umid: 0x060A2B340101010501010D111300000050C9F301189605A21036D0817ADD6884
    timecode        : 10:00:00:00
  Duration: 00:01:41.04, start: 0.000000, bitrate: 55052 kb/s
    Stream #0:0: Video: mpeg2video (4:2:2), yuv422p(tv, unknown/bt709/bt709, top first), 1920x1080 [SAR 1:1 DAR 16:9], 50000 kb/s, 25 fps, 25 tbr, 25 tbn, 50 tbc
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 1
    Side data:
      cpb: bitrate max/min/avg: 50000000/0/0 buffer size: 17825792 vbv_delay: N/A
    Stream #0:1: Audio: pcm_s24le, 48000 Hz, mono, s32 (24 bit), 1152 kb/s
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 2
    Stream #0:2: Audio: pcm_s24le, 48000 Hz, mono, s32 (24 bit), 1152 kb/s
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 3
    Stream #0:3: Audio: pcm_s24le, 48000 Hz, mono, s32 (24 bit), 1152 kb/s
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 4
    Stream #0:4: Audio: pcm_s24le, 48000 Hz, mono, s32 (24 bit), 1152 kb/s
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 5
Invalid input file index: 1.
</code>```

答:
Figured it out, i was using the wrong index for the video, also added the audio codec in the below solution.

```<code>ffmpeg -i "test.mxf" -filter_complex "[a:0]amerge=inputs=1[ch1] ;[a:1]amerge=inputs=1[ch2];[a:2]amerge=inputs=1[ch3];[a:3]amerge=inputs=1[ch4]" -map 0:v -map [ch3] -map [ch4] -map [ch1] -map [ch2] -c:v copy -c:a pcm_s24le "out.mxf"
</code>```

This works for me, if anybody has a better solution kindly share

Body:
I have a video file with 4 tracks of audio. I need to swap track 1:2 with track 3:4

Here is what i'm trying to achieve

Input file: 1:2:3:4
Outputfile: 3:4:2:1

So simply swapping the audio tracks, here is what i tried:

ffmpeg -i "test.mxf" -filter_complex "[a:0]amerge=inputs=1[ch1] ;[a:1]amerge=inputs=1[ch2];[a:2]amerge=inputs=1[ch3];[a:3]amerge=inputs=1[ch4]" -map 1:v -map [ch3] -map [ch4] -map [ch1] -map [ch2] -c:v copy -c:a aac -b:a 128k -ar 48000 -ac 2 "out.mxf"

Extracting them as separate channels and then mapping them back into the output.

I'm getting error: Invalid input file index: 1

Heres the output log from ffmpeg

ffmpeg -i "test.mxf" -filter_complex "[a:0]amerge=inputs=1[ch1] ;[a:1]amerge=inputs=1[ch2];[a:2]amerge=inputs=1[ch3];[a:3]amerge=inputs=1[ch4]" -map 1:v -map [ch3] -map [ch4] -map [ch1] -map [ch2] -c:v copy -c:a aac -b:a 128k -ar 48000 -ac 2 "out.mxf"
ffmpeg version 4.3.1-2020-10-01-full_build-www.gyan.dev Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 10.2.0 (Rev3, Built by MSYS2 project)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-lzma --enable-libsnappy --enable-zlib --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libdav1d --enable-libzvbi --enable-librav1e --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --enable-libaom --enable-libopenjpeg --enable-libvpx --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Guessed Channel Layout for Input Stream #0.1 : mono
Guessed Channel Layout for Input Stream #0.2 : mono
Guessed Channel Layout for Input Stream #0.3 : mono
Guessed Channel Layout for Input Stream #0.4 : mono
Input #0, mxf, from 'test.mxf':
  Metadata:
    operational_pattern_ul: 060e2b34.04010101.0d010201.01010900
    uid             : 50a83ad4-88be-11ec-9d91-d0817add6884
    generation_uid  : 50a83ad5-88be-11ec-be21-d0817add6884
    company_name    : Adobe Inc.
    product_name    : Premiere Pro
    product_version : 22.1.2
    application_platform: Mac OS X
    product_uid     : 0c3919fe-46e8-11e5-a151-feff819cdc9f
    modification_date: 2022-02-08T09:05:52.000000Z
    material_package_umid: 0x060A2B340101010501010D111300000050C9F301189605A21036D0817ADD6884
    timecode        : 10:00:00:00
  Duration: 00:01:41.04, start: 0.000000, bitrate: 55052 kb/s
    Stream #0:0: Video: mpeg2video (4:2:2), yuv422p(tv, unknown/bt709/bt709, top first), 1920x1080 [SAR 1:1 DAR 16:9], 50000 kb/s, 25 fps, 25 tbr, 25 tbn, 50 tbc
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 1
    Side data:
      cpb: bitrate max/min/avg: 50000000/0/0 buffer size: 17825792 vbv_delay: N/A
    Stream #0:1: Audio: pcm_s24le, 48000 Hz, mono, s32 (24 bit), 1152 kb/s
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 2
    Stream #0:2: Audio: pcm_s24le, 48000 Hz, mono, s32 (24 bit), 1152 kb/s
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 3
    Stream #0:3: Audio: pcm_s24le, 48000 Hz, mono, s32 (24 bit), 1152 kb/s
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 4
    Stream #0:4: Audio: pcm_s24le, 48000 Hz, mono, s32 (24 bit), 1152 kb/s
    Metadata:
      file_package_umid: 0x060A2B340101010501010D12131248EF50C9F301189605A2B55DD0817ADD6884
      file_package_name: Source Package
      track_name      : Track 5
Invalid input file index: 1.

Body:
Figured it out, i was using the wrong index for the video, also added the audio codec in the below solution.

ffmpeg -i "test.mxf" -filter_complex "[a:0]amerge=inputs=1[ch1] ;[a:1]amerge=inputs=1[ch2];[a:2]amerge=inputs=1[ch3];[a:3]amerge=inputs=1[ch4]" -map 0:v -map [ch3] -map [ch4] -map [ch1] -map [ch2] -c:v copy -c:a pcm_s24le "out.mxf"

This works for me, if anybody has a better solution kindly share


问:
Why am I getting a type error in this LeetCode solution?
For my solution in Leetcode, I am getting the following error. The question is : https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

Error :

```<code>Line 15: error: incompatible types: boolean cannot be converted to List<Boolean>
                return result.add(false);
                                 ^
Line 18: error: incompatible types: boolean cannot be converted to List<Boolean>
                return result.add(true);
                                 ^
2 errors
</code>```

My code:

```<code>class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {

    List<Boolean> result = new ArrayList<Boolean>();
    int max = 0;

    for(int i=0; i<candies.length; i++) {
        if(candies[i] > max) {
            candies[i] = max;
        }
    }

    for(int i=0; i<candies.length; i++) {
        if(candies[i] + extraCandies > max) {
            return result.add(false);
        }
        else {
            return result.add(true);
        }
    }

    return result;
}
}
</code>```

答: You should remove the return before the result.add(...). Otherwise, you try to return the value you just added to the list, instead of returning the list itself like you want.

Body:
For my solution in Leetcode, I am getting the following error. The question is : https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

Error :

Line 15: error: incompatible types: boolean cannot be converted to List<Boolean>
                return result.add(false);
                                 ^
Line 18: error: incompatible types: boolean cannot be converted to List<Boolean>
                return result.add(true);
                                 ^
2 errors

My code:

class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {

    List<Boolean> result = new ArrayList<Boolean>();
    int max = 0;

    for(int i=0; i<candies.length; i++) {
        if(candies[i] > max) {
            candies[i] = max;
        }
    }

    for(int i=0; i<candies.length; i++) {
        if(candies[i] + extraCandies > max) {
            return result.add(false);
        }
        else {
            return result.add(true);
        }
    }

    return result;
}
}


问:
No such Module 'Flutter' : Xcode 13
I am trying to run my app on iphone device and constantly running into this error. I followed some answer to this error on stenter code hereack like removing the pod file and recreating it. Pasting the podfile for better understanding.-------------------------------------------------------------------</p>
```<code># Uncomment this line to define a global platform for your project
platform :ios, '12.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
    end
  end
end
</code>```

答:
config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"

Try Removing this line and follow this link

Xcode 12, building for iOS Simulator, but linking in an object file built for iOS, for architecture 'arm64'

Posted By Thomas Ward

Title: No such Module 'Flutter' : Xcode 13

Body:
I am trying to run my app on iphone device and constantly running into this error. I followed some answer to this error on stenter code hereack like removing the pod file and recreating it. Pasting the podfile for better understanding.-------------------------------------------------------------------

# Uncomment this line to define a global platform for your project
platform :ios, '12.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
    end
  end
end


问:
How to make dynamic value array change value on element change
I am trying to make 3 Men's Morris game. I created the game but there is little error or problem. When drag a ball to box its value pushed to Array but again drag the same ball to other box it pushed a new value to Array if the same ball match pattern it says user won without inserting other balls to game. Could there be a method to remove only the current ball value from Array. And could be any method to make the other player bot to auto play against like in tic tac toe.
Here is my JavaScript :

```<code>let goalBoxes = document.querySelectorAll(".goal");
let user1 = [ ];
let user2 = [ ];

// Possible Win patterns
let pattern = [
  [1, 2, 3], // first row
  [4, 5, 6], // second row
  [7, 8, 9], // third row
  [1, 4, 7], // first column
  [2, 5, 8], // second column
  [3, 6, 9], // third column
  [1, 5, 9], // diagonal 1
  [3, 5, 7] // diagonal 2
];

// Check if anyone win or not
function checkWinner(user) {
  let won = false;
  pattern.forEach((row) => {
    if (
      user.indexOf(row[0]) > -1 &&
      user.indexOf(row[1]) > -1 &&
      user.indexOf(row[2]) > -1
    ) {
      return (won = true);
    }
  });
  return won;
}

function dragStart(event) {
  event.dataTransfer.setData(".", event.target.id);
}

function onDrop(event) {
  const id = event.dataTransfer.getData(".");
  const dragElem = document.getElementById(id);
  const patternIndex = event.target.getAttribute("data-index");
  event.target.appendChild(dragElem);

  // Adding pattern values
  if (event.target.firstChild.className == "ball") {
    user1.push(parseInt(patternIndex));
  } else {
    user2.push(parseInt(patternIndex));
  }

  // Checking for Winner
  checkWinner(user1);
  checkWinner(user2);

  // Showing message on the screen
  if (checkWinner(user1) == true) {
    alert("User1 have won");
  } else if (checkWinner(user2) == true) {
    alert("User2 have won");
  }
}

goalBoxes.forEach((goal) => {
  goal.addEventListener("dragover", (event) => {
    event.preventDefault();
  });
});

</code>```

This is my codepen if want more details https://codepen.io/ghulamshabeer/pen/qBVavEg

答:
If I make a dynamic Array whose values are changing then push those Arrays to main Array then you can overcome this problem.

```<code>let goalBoxes = document.querySelectorAll(".goal");
let user1 = [ ];
let user2 = [ ];
let ball1 = [ ];
let ball2 = [ ];
let ball3 = [ ];
let ball4 = [ ];
let ball5 = [ ];
let ball6 = [ ];

// Adding pattern values
  if (event.target.firstChild.className == "ball") {
    if (event.target.firstChild.id == "ball1") {
      ball1 = [];
      ball1.push(parseInt(patternIndex));
    } else if (event.target.firstChild.id == "ball2") {
     ball2 = [];
      ball2.push(parseInt(patternIndex));
    } else if(event.target.firstChild.id=="ball3"){
      ball3 = [];
      ball3.push(parseInt(patternIndex));
    }
  } else {
    if (event.target.id == "ball4") {
      ball4 = [];
      ball4.push(parseInt(patternIndex));;
    } else if (event.target.id == "ball5") {
      ball5 = [];
      ball5.push(parseInt(patternIndex));;
    } else(event.target.firstChild.id== " ball6") {
      ball6 = [];
      ball6.push(parseInt(patternIndex));;
    }

  }

 let user1pattern =[...ball1,...ball2,...ball3];
 let user2pattern =[...ball4,...ball5,...ball6];

  user1 = [...user1pattern];
  user2 = [...user2pattern];
</code>```

Body:
I am trying to make 3 Men's Morris game. I created the game but there is little error or problem. When drag a ball to box its value pushed to Array but again drag the same ball to other box it pushed a new value to Array if the same ball match pattern it says user won without inserting other balls to game. Could there be a method to remove only the current ball value from Array. And could be any method to make the other player bot to auto play against like in tic tac toe.
Here is my JavaScript :

let goalBoxes = document.querySelectorAll(".goal");
let user1 = [ ];
let user2 = [ ];

// Possible Win patterns
let pattern = [
  [1, 2, 3], // first row
  [4, 5, 6], // second row
  [7, 8, 9], // third row
  [1, 4, 7], // first column
  [2, 5, 8], // second column
  [3, 6, 9], // third column
  [1, 5, 9], // diagonal 1
  [3, 5, 7] // diagonal 2
];

// Check if anyone win or not
function checkWinner(user) {
  let won = false;
  pattern.forEach((row) => {
    if (
      user.indexOf(row[0]) > -1 &&
      user.indexOf(row[1]) > -1 &&
      user.indexOf(row[2]) > -1
    ) {
      return (won = true);
    }
  });
  return won;
}

function dragStart(event) {
  event.dataTransfer.setData(".", event.target.id);
}

function onDrop(event) {
  const id = event.dataTransfer.getData(".");
  const dragElem = document.getElementById(id);
  const patternIndex = event.target.getAttribute("data-index");
  event.target.appendChild(dragElem);

  // Adding pattern values
  if (event.target.firstChild.className == "ball") {
    user1.push(parseInt(patternIndex));
  } else {
    user2.push(parseInt(patternIndex));
  }

  // Checking for Winner
  checkWinner(user1);
  checkWinner(user2);

  // Showing message on the screen
  if (checkWinner(user1) == true) {
    alert("User1 have won");
  } else if (checkWinner(user2) == true) {
    alert("User2 have won");
  }
}

goalBoxes.forEach((goal) => {
  goal.addEventListener("dragover", (event) => {
    event.preventDefault();
  });
});

This is my codepen if want more details https://codepen.io/ghulamshabeer/pen/qBVavEg

Body:
If I make a dynamic Array whose values are changing then push those Arrays to main Array then you can overcome this problem.

let goalBoxes = document.querySelectorAll(".goal");
let user1 = [ ];
let user2 = [ ];
let ball1 = [ ];
let ball2 = [ ];
let ball3 = [ ];
let ball4 = [ ];
let ball5 = [ ];
let ball6 = [ ];

// Adding pattern values
  if (event.target.firstChild.className == "ball") {
    if (event.target.firstChild.id == "ball1") {
      ball1 = [];
      ball1.push(parseInt(patternIndex));
    } else if (event.target.firstChild.id == "ball2") {
     ball2 = [];
      ball2.push(parseInt(patternIndex));
    } else if(event.target.firstChild.id=="ball3"){
      ball3 = [];
      ball3.push(parseInt(patternIndex));
    }
  } else {
    if (event.target.id == "ball4") {
      ball4 = [];
      ball4.push(parseInt(patternIndex));;
    } else if (event.target.id == "ball5") {
      ball5 = [];
      ball5.push(parseInt(patternIndex));;
    } else(event.target.firstChild.id== " ball6") {
      ball6 = [];
      ball6.push(parseInt(patternIndex));;
    }

  }

 let user1pattern =[...ball1,...ball2,...ball3];
 let user2pattern =[...ball4,...ball5,...ball6];

  user1 = [...user1pattern];
  user2 = [...user2pattern];


问:
Is it possible to run a single test in MiniTest?
I can run all tests in a single file with:

```<code>rake test TEST=path/to/test_file.rb
</code>```

However, if I want to run just one test in that file, how would I do it?

I'm looking for similar functionality to:

```<code>rspec path/to/test_file.rb -l 25
</code>```

答:
Install gem minitest-focus and use the keyword focus on test/spec like below to run only the specific test.

```<code>focus
def test
end

focus
it "test" do
end

</code>```

This would not need any command line argument to be passed.

Body:
I can run all tests in a single file with:

rake test TEST=path/to/test_file.rb

However, if I want to run just one test in that file, how would I do it?

I'm looking for similar functionality to:

rspec path/to/test_file.rb -l 25

Body:
Install gem minitest-focus and use the keyword focus on test/spec like below to run only the specific test.

focus
def test
end

focus
it "test" do
end

This would not need any command line argument to be passed.


问:
In R , is there any avaiable funcation like IFERROR formula in EXCEL
In R , is there any available function like IFERROR formula in EXCEL ?
I want to calculate moving average using 4 nearest figures, but if the figures less than 4 in the group then using normal average.
Detail refer to below code, the IF_ERROR is just i wished function and can't work</p>
```<code>library(tidyverse)
library(TTR)
test_data <- data.frame(category=c('a','a','a','b','b','b','b','b','b'),
             amount=c(1,2,3,4,5,6,7,8,9))

test_data %>% group_by(category) %>% mutate(avg_amount=IF_ERROR(TTR::runMedian(amount,4),
                                                                median(amount),
                                                                TTR::runMedian(amount,4))
</code>```

答:
In general, input should only generate errors in exceptional circumstances. It can be computationally expensive to catch and handle errors where a simple if statement will suffice. The key here is realising that runMedian throws an error if the group size is less than 4. Remember we can check the group size inside mutate by using n(), so all you need do is:

test_data %>%
  group_by(category) %>%
  mutate(avg_amount = if(n() > 3) TTR::runMedian(amount, 4) else median(amount))
#> # A tibble: 9 x 3
#> # Groups:   category [2]
#>   category amount avg_amount
#>   <chr>     <dbl>      <dbl>
#> 1 a             1        2
#> 2 a             2        2
#> 3 a             3        2
#> 4 b             4       NA
#> 5 b             5       NA
#> 6 b             6       NA
#> 7 b             7        5.5
#> 8 b             8        6.5
#> 9 b             9        7.5
```
<p>Additionally, if you want to replace the NA values from the beginning of the running median, you could use <code>ifelse</code>:</p>
<pre class="lang-r prettyprint-override"><code>test_data %>%
  group_by(category) %>%
  mutate(avg_amount = if(n() > 3) TTR::runMedian(amount, 4) else median(amount),
         avg_amount = ifelse(is.na(avg_amount), median(amount), avg_amount))
#> # A tibble: 9 x 3
#> # Groups:   category [2]
#>   category amount avg_amount
#>   <chr>     <dbl>      <dbl>
#> 1 a             1        2
#> 2 a             2        2
#> 3 a             3        2
#> 4 b             4        6.5
#> 5 b             5        6.5
#> 6 b             6        6.5
#> 7 b             7        5.5
#> 8 b             8        6.5
#> 9 b             9        7.5
</code>```

Body:
In R , is there any available function like IFERROR formula in EXCEL ?
I want to calculate moving average using 4 nearest figures, but if the figures less than 4 in the group then using normal average.
Detail refer to below code, the IF_ERROR is just i wished function and can't work

library(tidyverse)
library(TTR)
test_data <- data.frame(category=c('a','a','a','b','b','b','b','b','b'),
             amount=c(1,2,3,4,5,6,7,8,9))

test_data %>% group_by(category) %>% mutate(avg_amount=IF_ERROR(TTR::runMedian(amount,4),
                                                                median(amount),
                                                                TTR::runMedian(amount,4))

Body:
In general, input should only generate errors in exceptional circumstances. It can be computationally expensive to catch and handle errors where a simple if statement will suffice. The key here is realising that runMedian throws an error if the group size is less than 4. Remember we can check the group size inside mutate by using n(), so all you need do is:

test_data %>%
  group_by(category) %>%
  mutate(avg_amount = if(n() > 3) TTR::runMedian(amount, 4) else median(amount))
#> # A tibble: 9 x 3
#> # Groups:   category [2]
#>   category amount avg_amount
#>   <chr>     <dbl>      <dbl>
#> 1 a             1        2
#> 2 a             2        2
#> 3 a             3        2
#> 4 b             4       NA
#> 5 b             5       NA
#> 6 b             6       NA
#> 7 b             7        5.5
#> 8 b             8        6.5
#> 9 b             9        7.5

Additionally, if you want to replace the NA values from the beginning of the running median, you could use ifelse:

test_data %>%
  group_by(category) %>%
  mutate(avg_amount = if(n() > 3) TTR::runMedian(amount, 4) else median(amount),
         avg_amount = ifelse(is.na(avg_amount), median(amount), avg_amount))
#> # A tibble: 9 x 3
#> # Groups:   category [2]
#>   category amount avg_amount
#>   <chr>     <dbl>      <dbl>
#> 1 a             1        2
#> 2 a             2        2
#> 3 a             3        2
#> 4 b             4        6.5
#> 5 b             5        6.5
#> 6 b             6        6.5
#> 7 b             7        5.5
#> 8 b             8        6.5
#> 9 b             9        7.5


问:
Update local packages and hot reload to project
Hi I have a local package that I import in a project

Project pubspec.yaml:

```<code>dependencies:
  my_local_package:
    path: ../my_local_package
</code>```

I have both the my_local_package and project open in 2 tabs in android studio. I want to update the my_local_package and press hot reload and receive the updates.

Update my_local_package -> Press Hot reload in main_project -> Updates received

How can I do this?

答:
hot reload need sometimes full reload
https://docs.flutter.dev/development/tools/hot-reload#special-cases</p>

Body:
Hi I have a local package that I import in a project

Project pubspec.yaml:

dependencies:
  my_local_package:
    path: ../my_local_package

I have both the my_local_package and project open in 2 tabs in android studio. I want to update the my_local_package and press hot reload and receive the updates.

Update my_local_package -> Press Hot reload in main_project -> Updates received

How can I do this?


问:
Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView in Kotlin
Dear team I am trying to use com.google.android.material.bottomnavigation.BottomNavigationView on my Kotlin application. While running the application, My application got crash, I got the below error,

```<code>FATAL EXCEPTION: main
    Process: com.demo.myapp, PID: 25273
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.demo.myapp/com.demo.myapp.ui.main.view.MainActivity}: android.view.InflateException: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3827)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4003)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8595)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
     Caused by: android.view.InflateException: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
     Caused by: android.view.InflateException: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:852)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1004)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
        at com.demo.myapp.ui.main.view.MainActivity.onCreate(MainActivity.kt:11)
        at android.app.Activity.performCreate(Activity.java:8207)
        at android.app.Activity.performCreate(Activity.java:8191)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3800)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4003)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8595)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
</code>```

Here is my code,

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:viewBindingIgnore="true"
    tools:context=".ui.main.view.MainActivity"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/container_main"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/White"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toTopOf="@+id/view_navigation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/view_navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:labelVisibilityMode="labeled"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/nav_menu"
        style="@style/BottomNavigationMenu"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

themes.xml

```<code><resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.MyApp" parent="Theme.AppCompat.Light.NoActionBar">
        <!--<item name="android:fontFamily">@font/poppins_regular</item>-->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="BottomNavigationMenu" parent="Widget.MaterialComponents.BottomNavigationView">
        <item name="android:background">@color/White</item>
        <item name="itemIconTint">@color/menu_text_color_selector</item>
        <item name="itemTextColor">@color/menu_text_color_selector</item>
        <item name="itemTextAppearanceActive">@style/MyBottomNavigationView.TextAppearance</item>
        <item name="itemTextAppearanceInactive">@style/MyBottomNavigationView.TextAppearance</item>
    </style>

    <style name="MyBottomNavigationView.TextAppearance" parent="TextAppearance.MaterialComponents.Caption">
        <item name="android:textSize">11sp</item>
    </style>

</resources>
</code>```

build.gradle (app)

```<code>dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
</code>```

答:
Try changing your app's theme... something like this:

```<code><style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.NoActionBar">
</code>```

I think the conflict is causing the crash.

Body:
Dear team I am trying to use com.google.android.material.bottomnavigation.BottomNavigationView on my Kotlin application. While running the application, My application got crash, I got the below error,

FATAL EXCEPTION: main
    Process: com.demo.myapp, PID: 25273
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.demo.myapp/com.demo.myapp.ui.main.view.MainActivity}: android.view.InflateException: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3827)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4003)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8595)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
     Caused by: android.view.InflateException: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
     Caused by: android.view.InflateException: Binary XML file line #23 in com.demo.myapp:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:852)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1004)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
        at com.demo.myapp.ui.main.view.MainActivity.onCreate(MainActivity.kt:11)
        at android.app.Activity.performCreate(Activity.java:8207)
        at android.app.Activity.performCreate(Activity.java:8191)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3800)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4003)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8595)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

Here is my code,

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:viewBindingIgnore="true"
    tools:context=".ui.main.view.MainActivity"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/container_main"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/White"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toTopOf="@+id/view_navigation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/view_navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:labelVisibilityMode="labeled"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/nav_menu"
        style="@style/BottomNavigationMenu"/>

</androidx.constraintlayout.widget.ConstraintLayout>

themes.xml

<resources xmlns:tools="http://schemas.android.com/tools">

</resources>

build.gradle (app)

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

Body:
Try changing your app's theme... something like this:

<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.NoActionBar">

I think the conflict is causing the crash.