答:
Because columns A and B are both lists, you can just add them together to get the total elements.  Then use Counter in a dictionary comprehension to get the count of each letter, and divide each count by the total number of unique letters (determined by the length of the set).

```<code>from collections import Counter

# Sample data.
df = pd.DataFrame({
    'A': [['a', 'b', 'c'], ['c', 'b', 'e', 'a'], ['a', 'b', 'd', 'e'], ['a', 'b', 'c']],
    'B': [['a', 'b'], ['b', 'e', 'a'], ['a', 'b', 'c'], ['a', 'd', 'c']]
})

# Solution.
>>> df.assign(
    Distinct_Values_with_scoring=
    df['A']
    .add(df['B'])
    .apply(lambda x: {k: v / len(set(x)) for k, v in Counter(x).items()})
)
              A          B                       Distinct_Values_with_scoring
0     [a, b, c]     [a, b]  {'a': 0.6666666666666666, 'b': 0.6666666666666...
1  [c, b, e, a]  [b, e, a]          {'c': 0.25, 'b': 0.5, 'e': 0.5, 'a': 0.5}
2  [a, b, d, e]  [a, b, c]  {'a': 0.4, 'b': 0.4, 'd': 0.2, 'e': 0.2, 'c': ...
3     [a, b, c]  [a, d, c]         {'a': 0.5, 'b': 0.25, 'c': 0.5, 'd': 0.25}
</code>```

Body:
Because columns A and B are both lists, you can just add them together to get the total elements.  Then use Counter in a dictionary comprehension to get the count of each letter, and divide each count by the total number of unique letters (determined by the length of the set).

from collections import Counter

# Sample data.
df = pd.DataFrame({
    'A': [['a', 'b', 'c'], ['c', 'b', 'e', 'a'], ['a', 'b', 'd', 'e'], ['a', 'b', 'c']],
    'B': [['a', 'b'], ['b', 'e', 'a'], ['a', 'b', 'c'], ['a', 'd', 'c']]
})

# Solution.
>>> df.assign(
    Distinct_Values_with_scoring=
    df['A']
    .add(df['B'])
    .apply(lambda x: {k: v / len(set(x)) for k, v in Counter(x).items()})
)
              A          B                       Distinct_Values_with_scoring
0     [a, b, c]     [a, b]  {'a': 0.6666666666666666, 'b': 0.6666666666666...
1  [c, b, e, a]  [b, e, a]          {'c': 0.25, 'b': 0.5, 'e': 0.5, 'a': 0.5}
2  [a, b, d, e]  [a, b, c]  {'a': 0.4, 'b': 0.4, 'd': 0.2, 'e': 0.2, 'c': ...
3     [a, b, c]  [a, d, c]         {'a': 0.5, 'b': 0.25, 'c': 0.5, 'd': 0.25}


来源: stackexchange

问:
Redirect at @ResponseBody?
I have something for ajax login through spring security:

```<code>@RequestMapping(value="/entry.html", method=RequestMethod.GET)
public String getEntry(){
    return isAuthenticated()? "redirect:/logout.jsp":"entry";
}

@RequestMapping(value="/postLogout.html", method=RequestMethod.GET)
public @ResponseBody String getPostLogout(){
    return "{success:true, logout:true, session:false}";
}
</code>```

The flow is that when receive a call to /entry.html, it will check and choose to

redirect to /logout.jsp => handled by spring security and then redirect to /postLogout.html => response JSON

resolve to view entry, which is a jsp contain only a json string

I would like to know if I can use @ResponseBody in getEntry() without using an jsp to write just a json value?

答:
The easiest way to return JSON from Spring is through Jackson.

I'd create a custom return Object:

```<code>public class MyReturnObject{
private boolean success;
private boolean session;
private boolean logout;
// + getters and setters
// + 3-arg constructor
}
</code>```

and write the controller method like this:

```<code>@RequestMapping(value="/postLogout.html", method=RequestMethod.GET)
@ResponseBody
public MyreturnObject getPostLogout(){
    return new ReturnObject(true,true,false);
}
</code>```

Spring+Jackson will take care of serializing the Object to JSON and setting the correct mime type. See this previous answer of mine for a full working version.

ContentLicense: CC BY-SA 3.0

Title: Redirect at @ResponseBody?

Body:
I have something for ajax login through spring security:

@RequestMapping(value="/entry.html", method=RequestMethod.GET)
public String getEntry(){
    return isAuthenticated()? "redirect:/logout.jsp":"entry";
}

@RequestMapping(value="/postLogout.html", method=RequestMethod.GET)
public @ResponseBody String getPostLogout(){
    return "{success:true, logout:true, session:false}";
}

The flow is that when receive a call to /entry.html, it will check and choose to

redirect to /logout.jsp => handled by spring security and then redirect to /postLogout.html => response JSON

resolve to view entry, which is a jsp contain only a json string

I would like to know if I can use @ResponseBody in getEntry() without using an jsp to write just a json value?

Body:
The easiest way to return JSON from Spring is through Jackson.

I'd create a custom return Object:

public class MyReturnObject{
private boolean success;
private boolean session;
private boolean logout;
// + getters and setters
// + 3-arg constructor
}

and write the controller method like this:

@RequestMapping(value="/postLogout.html", method=RequestMethod.GET)
@ResponseBody
public MyreturnObject getPostLogout(){
    return new ReturnObject(true,true,false);
}

Spring+Jackson will take care of serializing the Object to JSON and setting the correct mime type. See this previous answer of mine for a full working version.


问:
Mongo aggregation query to filter records with minimum amount and number of records for one user
I am trying to filter records with condition of each user having minimum number of 7 transaction in a month and each transaction being greater than 1000. I have the below json after 2nd stage of pipeline after filtering out kind of transaction i want, getting month out of date and using groupby to get count of transaction by each user in a month. I am not able to apply the above condition to get the required data after that.

Sample Json:

```<code>{
    "_id" : {
        "month" : 2,
        "sender" : "123dd3"
    },
    "data" : [
        {
            "name" : "name1",
            "amount" : 1000,
            "sender" : {
              "id" : "123455",
                "name" : "send 02",
                "phone" : "1234567"
            },
            "service" : "109",
            "createdAt" : "2020-02-07T16:24:56.047+06:30",
            "month" : 2
        },
        {
            "name" : "name1",
            "amount" : 10400,
            "sender" : {
              "id" : "123455",
                "name" : "send 02",
                "phone" : "1234567"
            },
            "service" : "109",
            "createdAt" : "2020-02-07T16:25:22.019+06:30",
            "month" : 2
        },
        {
            "name" : "name1",
            "amount" : 10400,
            "sender" : {
              "id" : "123455",
                "name" : "send 02",
                "phone" : "1234567"
            },
            "service" : "109",
            "createdAt" : "2020-02-07T16:26:16.703+06:30",
            "month" : 2
        }
    ],
    "count" : 3
}
</code>```

My Query:

```<code>[{
    $match: {
        service: '109'
    }
}, {
    $addFields: {
        "month": {
            "$month": "$createdAt"
        }
    }
}, {
    $group: {
        _id: {
            'month': '$month',
            'sender': '$sender.id'
        },
        data: {
            $push: '$$ROOT'
        },
        count: {
            $sum: 1
        }
    }
}, {
    $project: {
        '_id': 1,
        'data': 1,
        'count': 1,
        'cond': {
            $cond: [{
                $gte: ["$data.amount", 1000]
            }, true, false]
        }
    }
}]
</code>```

I am not able to get the required condition right, as there are multiple records under data and i need to apply this condition to each one of them and with number of transaction being greater than equal to 7.

答:
You have to $filter your data array first and then run $size to see if there's more than 7 items

```<code>{
    $project: {
        '_id': 1,
        'data': 1,
        'count': 1,
        'cond': {
            $gte: [
                { $size: { $filter: { input: "$data", cond: { $gte: [ "$$this.amount", 1000 ] } } } },
                7
            ]
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to filter records with condition of each user having minimum number of 7 transaction in a month and each transaction being greater than 1000. I have the below json after 2nd stage of pipeline after filtering out kind of transaction i want, getting month out of date and using groupby to get count of transaction by each user in a month. I am not able to apply the above condition to get the required data after that.

Sample Json:

{
    "_id" : {
        "month" : 2,
        "sender" : "123dd3"
    },
    "data" : [
        {
            "name" : "name1",
            "amount" : 1000,
            "sender" : {
              "id" : "123455",
                "name" : "send 02",
                "phone" : "1234567"
            },
            "service" : "109",
            "createdAt" : "2020-02-07T16:24:56.047+06:30",
            "month" : 2
        },
        {
            "name" : "name1",
            "amount" : 10400,
            "sender" : {
              "id" : "123455",
                "name" : "send 02",
                "phone" : "1234567"
            },
            "service" : "109",
            "createdAt" : "2020-02-07T16:25:22.019+06:30",
            "month" : 2
        },
        {
            "name" : "name1",
            "amount" : 10400,
            "sender" : {
              "id" : "123455",
                "name" : "send 02",
                "phone" : "1234567"
            },
            "service" : "109",
            "createdAt" : "2020-02-07T16:26:16.703+06:30",
            "month" : 2
        }
    ],
    "count" : 3
}

My Query:

[{
    $match: {
        service: '109'
    }
}, {
    $addFields: {
        "month": {
            "$month": "$createdAt"
        }
    }
}, {
    $group: {
        _id: {
            'month': '$month',
            'sender': '$sender.id'
        },
        data: {
            $push: '$$ROOT'
        },
        count: {
            $sum: 1
        }
    }
}, {
    $project: {
        '_id': 1,
        'data': 1,
        'count': 1,
        'cond': {
            $cond: [{
                $gte: ["$data.amount", 1000]
            }, true, false]
        }
    }
}]

I am not able to get the required condition right, as there are multiple records under data and i need to apply this condition to each one of them and with number of transaction being greater than equal to 7.

Body:
You have to $filter your data array first and then run $size to see if there's more than 7 items

{
    $project: {
        '_id': 1,
        'data': 1,
        'count': 1,
        'cond': {
            $gte: [
                { $size: { $filter: { input: "$data", cond: { $gte: [ "$$this.amount", 1000 ] } } } },
                7
            ]
        }
    }
}


问:
Can I replace the atomic with a volatile in an one-reader/one-writer queue?
Let us consider the following one-reader/one-writer queue implemented with a linked list.

struct queue {
  queue() {
    tail = head = &reserved;
    n = 0;
  }
  void push(item *it) {
     tail->next = it;
     tail = it;
     n++;
  }
  item* pop() {
     while (n == used);
     ++used;
     head = head->next;
     return head;
  }

  item reserved;
  item *tail, *head;

  int used = 0;
  std::atomic <int> n;
}
```

<p>Now I find that using <code>volatile int n</code> could make my writer run faster, while I'm not sure whether it guarantees that <code>head = head->next</code> can always read the correct value.</p>

<p>UPDATED: What if adding an atomic operation between <code>tail->next</code>, <code>n++</code>, i.e.,</p>

<pre class="lang-cpp prettyprint-override"><code>void push(item *it) {
   tail->next = it;
   tail = it;
   a.store(0, std::memory_order_release);
   a.load(std::memory_order_acquire);
   n++;
}
</code>```

in which a is never accessed by the reader? Will this guarantees the order of tail->next = it and head = head->next? (Still, it runs faster than using atomic n)

答:
The volatile keyword in C++ is not a construct to give variable read/write a guarantee to be so ordered as it looks in the code, in multi-threaded environments. So, in your code with the atomic template wrapped counter being made bare with the volatile keyword alone, increasing of the counter observed by a consumer thread does not guarantee that item::next has also been updated.

To achieve maximum performance with the guarantee, I think at least you have to insert a write barrier between updating head->next and the incremenet to the counter, e.g. by n.fetch_add(1, std::memory_order_release), and a read barrier just before fetching tail->next, like n.load(std::memory_order_acquire). I don't know CPU-arch specific details, though.

Body:
Let us consider the following one-reader/one-writer queue implemented with a linked list.

struct queue {
  queue() {
    tail = head = &reserved;
    n = 0;
  }
  void push(item *it) {
     tail->next = it;
     tail = it;
     n++;
  }
  item* pop() {
     while (n == used);
     ++used;
     head = head->next;
     return head;
  }

  item reserved;
  item *tail, *head;

  int used = 0;
  std::atomic <int> n;
}

Now I find that using volatile int n could make my writer run faster, while I'm not sure whether it guarantees that head = head->next can always read the correct value.

UPDATED: What if adding an atomic operation between tail->next, n++, i.e.,

void push(item *it) {
   tail->next = it;
   tail = it;
   a.store(0, std::memory_order_release);
   a.load(std::memory_order_acquire);
   n++;
}

in which a is never accessed by the reader? Will this guarantees the order of tail->next = it and head = head->next? (Still, it runs faster than using atomic n)


问:
MediaStreamRecorder can't record more than an hour?
I am creating a video conference which takes 1 hour. And it can't save because Payload Too Large

Here is my code:

```<code>const data = [];
multiStreamRecorder.ondataavailable = function (blob) {
    data.push(blob);

    var fileName = getFileName('webm');
    var scheduleId = $('#stop-recording').data('id');
    var fileObject = new File([data[0]], fileName, {
        type: data[0].type
    });
    var objectUrl = URL.createObjectURL(data[0]);

    var formData = new FormData();
        formData.append('video_blob', fileObject);
        formData.append('video_filename', fileObject.name);
        formData.append('schedule_id', scheduleId);

    $.ajax({
        url: '{{ url('/') }}/store',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(response) {
            //
        }
    });
};
multiMediaRecorder.start();
</code>```

I need to record the entire conference.

答:
The "payload too large" error comes from your server, not from the MediaRecorder API.

You probably have ways to raise that limit in your server's configs.

Alternatively, you could send the final file by chunks, but that's probably sub-optimal.

Unrelated note:

sending the blobURI is useless, this URI will only be valid for the context that did create it.

Body:
I am creating a video conference which takes 1 hour. And it can't save because Payload Too Large

Here is my code:

const data = [];
multiStreamRecorder.ondataavailable = function (blob) {
    data.push(blob);

    var fileName = getFileName('webm');
    var scheduleId = $('#stop-recording').data('id');
    var fileObject = new File([data[0]], fileName, {
        type: data[0].type
    });
    var objectUrl = URL.createObjectURL(data[0]);

    var formData = new FormData();
        formData.append('video_blob', fileObject);
        formData.append('video_filename', fileObject.name);
        formData.append('schedule_id', scheduleId);

    $.ajax({
        url: '{{ url('/') }}/store',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(response) {
            //
        }
    });
};
multiMediaRecorder.start();

I need to record the entire conference.


问:
i want to add the following from a list but the result only concatinates

Sample value of n is 5

```<code>    n = input("Enter a No: ")
    n = "{0}+{0}{0}+{0}{0}{0}".format(n)
    n = n.split("+")
    a=n[0]
    b=n[1]
    c=n[2]
    n = (a + b + c)
    print(n)

</code>```

Expected Result : 615

答:
You just have to add 1 extra line in your code and it should be running.

You need to convert all the elements in your list to int for performing addition.

Try this :

```<code>n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")

n = list(map(int, n))

a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)

</code>```

Body:
Sample value of n is 5

    n = input("Enter a No: ")
    n = "{0}+{0}{0}+{0}{0}{0}".format(n)
    n = n.split("+")
    a=n[0]
    b=n[1]
    c=n[2]
    n = (a + b + c)
    print(n)

Expected Result : 615

Body:
You just have to add 1 extra line in your code and it should be running.

You need to convert all the elements in your list to int for performing addition.

Try this :

n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")

n = list(map(int, n))

a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)


问:
React Native - launchPackager.command cant be opened
I am having trouble building react native ios project.

Error message:

```<code>"launchPackage command" can't be opened because it is from an unidentified developer.
</code>```

Any idea how to fix this?

答:
on MacOS Catalina and above
Go to

System Preferences

Security & Privacy

Choose tab "Privacy"

Select "Developer Tools" on left pane

Check "Terminal" to allow terminal to run software locally which does not meet system's  security policy . (please be aware of potential implications of this action and make sure that you know what you are doing )

Body:
I am having trouble building react native ios project.

Error message:

"launchPackage command" can't be opened because it is from an unidentified developer.

Any idea how to fix this?


问:
Django authenticate always returns None no matter what
I have been trying to add registration/login/logout functionality. The user registration appears to be working fine, as the created user shows up in Django admin and appears in the database. However, whenever I try to implement the login functionality, it never works. I think I've narrowed down the problem to authenticate().

I have tried everything, and no matter what I do, the authenticate() function always returns None. The usernames and passwords I give are clearly being stored, and yet it doesn't seem to be getting the password correctly, since printing out raw_password = form.cleaned_data.get('password1') in the login_user view gives None.

How can I get the login functionality to work?

In urls.py

```<code>urlpatterns = [
    path('register', views.register_user, name='register'),
    path('login', views.login_user, name='login'),
    path('logout', views.logout_user, name='logout'),
]
</code>```

In views.py

```<code>def register_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)

        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            print(f'User is: {user}')
            login(request, user)
            return redirect('/')

    else:
        form = UserCreationForm(request.POST)

    context = {
        'form': form
    }
    return render(request, 'register.html', context)

def login_user(request):
    if request.method == 'POST':
        form = AuthenticationForm(request=request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            print(f'User is: {user}')
            print(f'username is: {username}')
            print(f'password is: {raw_password}')
            if user is not None:
                if user.is_active:
                    login(request, user)
                    print(f'You are now logged in as {username}')
                    messages.info(request, f"You are now logged in as {username}")
                    return redirect('/')
    else:
        form = AuthenticationForm()

    return render(request = request,
                    template_name = "login.html",
                    context={"form":form})

def logout_user(request):
    logout(request)
    return redirect('/')
</code>```

In register.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration</title>
</head>
<body>
    <h2>Register</h2>
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Register</button>
    </form>
</body>
</html>
</code>```

In login.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Log in</title>
</head>
<body>
    <h2>Log in</h2>
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Log in</button>
    </form>
</body>
</html>
</code>```

The register_user and logout_user views seem to be working fine. In the register_user view, I made it so it automatically logs the user after registration. Oddly, logging in works in this scenario. However, logging in doesn't work for the login_user view, for the reasons mentioned above.

答: raw_password = form.cleaned_data.get('password1') here you must get password itself not password1.

Body:
I have been trying to add registration/login/logout functionality. The user registration appears to be working fine, as the created user shows up in Django admin and appears in the database. However, whenever I try to implement the login functionality, it never works. I think I've narrowed down the problem to authenticate().

I have tried everything, and no matter what I do, the authenticate() function always returns None. The usernames and passwords I give are clearly being stored, and yet it doesn't seem to be getting the password correctly, since printing out raw_password = form.cleaned_data.get('password1') in the login_user view gives None.

How can I get the login functionality to work?

In urls.py

urlpatterns = [
    path('register', views.register_user, name='register'),
    path('login', views.login_user, name='login'),
    path('logout', views.logout_user, name='logout'),
]

In views.py

def register_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)

        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            print(f'User is: {user}')
            login(request, user)
            return redirect('/')

    else:
        form = UserCreationForm(request.POST)

    context = {
        'form': form
    }
    return render(request, 'register.html', context)

def login_user(request):
    if request.method == 'POST':
        form = AuthenticationForm(request=request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            print(f'User is: {user}')
            print(f'username is: {username}')
            print(f'password is: {raw_password}')
            if user is not None:
                if user.is_active:
                    login(request, user)
                    print(f'You are now logged in as {username}')
                    messages.info(request, f"You are now logged in as {username}")
                    return redirect('/')
    else:
        form = AuthenticationForm()

    return render(request = request,
                    template_name = "login.html",
                    context={"form":form})

def logout_user(request):
    logout(request)
    return redirect('/')

In register.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration</title>

Register

    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Register</button>
    </form>

In login.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Log in</title>

Log in

    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Log in</button>
    </form>

The register_user and logout_user views seem to be working fine. In the register_user view, I made it so it automatically logs the user after registration. Oddly, logging in works in this scenario. However, logging in doesn't work for the login_user view, for the reasons mentioned above.


问:
Xrm.Page.getControl() not working in Dynamics 365 Sales Hub
Xrm.Page.getControl("webResource1").getObject() is working fine in Sales Dynamics 365, while it's not working in Sales Hub.

The counterpart is to use formContext, but how to call a script in a web resource from another web resource.

Eg.
Xrm.Page.getControl("webResource1").getObject().contentWindow.function1() is working fine in Sales, but not in Unified UI.

答:
There’s another design change causing this null when using formContext.getControl("WebResourceName").getObject() because Sales hub or UCI form tab having web resource is not rendered yet unless it’s clicked/navigated.

Similar topic in Dynamics community thread

GitHub issue


问:
Prompting an input in bash script should executes an bash function
I would like to get an output based on the input we provided. For Example,

if I selected 1 it should take the 1st element in the array and the output should be My name is test

if I selected 2 it should take the 2nd element in the array and the output should be My name is test1

similarly, if I select all the output should be My name is test
My name is test1
My name is test2
My name is test3

```<code> a=("test" "test1" "test2" "test3")

testfunction() {
        echo My name is $a
}

echo "Enter a number"
select number in "test" "test1" "test2" "tes3" "all"; do
    case "$number" in
        test)
            testfunction "${a[0]}"; break;;
        test1)
            testfunction "${a[1]}"; break;;
        test2)
            testfunction "${a[2]}"; break;;
        test3)
            testfunction "${a[3]}"; break;;
        all)
            testfunction "${a[@]}"; break;;
    esac
done
</code>```

Can someone please help me with this?

答:
As pointed out by other answers, you should use $1 in your testfunction().
Additionally, you can use a for loop to get your desired output when you select all as your input.

```<code>a=("test" "test1" "test2" "test3")

testfunction() {
        echo My name is $1
}

echo "Enter a number"
select number in "test" "test1" "test2" "test3" "all"; do
    case "$number" in
        test)
            testfunction "${a[0]}"; break;;
        test1)
            testfunction "${a[1]}"; break;;
        test2)
            testfunction "${a[2]}"; break;;
        test3)
            testfunction "${a[3]}"; break;;
        all)
            for i in "${a[@]}"; do testfunction "${i}"; done
            break;;
    esac
done
</code>```

Body:
I would like to get an output based on the input we provided. For Example,

if I selected 1 it should take the 1st element in the array and the output should be My name is test

if I selected 2 it should take the 2nd element in the array and the output should be My name is test1

similarly, if I select all the output should be My name is test
My name is test1
My name is test2
My name is test3

 a=("test" "test1" "test2" "test3")

testfunction() {
        echo My name is $a
}

echo "Enter a number"
select number in "test" "test1" "test2" "tes3" "all"; do
    case "$number" in
        test)
            testfunction "${a[0]}"; break;;
        test1)
            testfunction "${a[1]}"; break;;
        test2)
            testfunction "${a[2]}"; break;;
        test3)
            testfunction "${a[3]}"; break;;
        all)
            testfunction "${a[@]}"; break;;
    esac
done

Can someone please help me with this?

Body:
As pointed out by other answers, you should use $1 in your testfunction().
Additionally, you can use a for loop to get your desired output when you select all as your input.

a=("test" "test1" "test2" "test3")

testfunction() {
        echo My name is $1
}

echo "Enter a number"
select number in "test" "test1" "test2" "test3" "all"; do
    case "$number" in
        test)
            testfunction "${a[0]}"; break;;
        test1)
            testfunction "${a[1]}"; break;;
        test2)
            testfunction "${a[2]}"; break;;
        test3)
            testfunction "${a[3]}"; break;;
        all)
            for i in "${a[@]}"; do testfunction "${i}"; done
            break;;
    esac
done


问:
java.lang.ClassNotFoundException - Eclipse with OpenCV
When I run my below code I get the below error, but it worked before and I am not sure what Eclipse got and is not good anymore

Error: Unable to initialize main class src.convolution
Caused by: java.lang.NoClassDefFoundError: org/opencv/core/Mat

```<code>package src;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class convolution {
   public static void main( String[] args ) {

      try {
         int kernelSize = 9;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

         Mat source = Imgcodecs.imread("C:/Users/B & B/Desktop/ProcIMG/grayscale.jpg", Imgcodecs.IMREAD_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());

         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F){
            {
               put(0,0,-3);
               put(0,1,-3);
               put(0,2,-3);

               put(1,0-3);
               put(1,1,0);
               put(1,2,-3);

               put(2,0,5);
               put(2,1,5);
               put(2,2,5);
            }
         };

         Imgproc.filter2D(source, destination, -1, kernel);
         Imgcodecs.imwrite("C:/Users/B & B/Desktop/ProcIMG/output.jpg", destination);

      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
   }
}
</code>```

答:
It could be .classpath issue. Try following steps

Delete Project from Eclipse don't delete content from disk.

remove .classpath and .project files

re-import project in Eclipse

Body:
When I run my below code I get the below error, but it worked before and I am not sure what Eclipse got and is not good anymore

Error: Unable to initialize main class src.convolution
Caused by: java.lang.NoClassDefFoundError: org/opencv/core/Mat

package src;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class convolution {
   public static void main( String[] args ) {

      try {
         int kernelSize = 9;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

         Mat source = Imgcodecs.imread("C:/Users/B & B/Desktop/ProcIMG/grayscale.jpg", Imgcodecs.IMREAD_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());

         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F){
            {
               put(0,0,-3);
               put(0,1,-3);
               put(0,2,-3);

               put(1,0-3);
               put(1,1,0);
               put(1,2,-3);

               put(2,0,5);
               put(2,1,5);
               put(2,2,5);
            }
         };

         Imgproc.filter2D(source, destination, -1, kernel);
         Imgcodecs.imwrite("C:/Users/B & B/Desktop/ProcIMG/output.jpg", destination);

      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
   }
}


问:
How "ORDER BY" ordered if they are same value?
Let's say there's table:

```<code>name | score
A      100
B      98
C      99
D      99
E      99
F      98
</code>```

and request sql = 'select * from table order by score desc'

I know order's gonna be 100, 99, 99, 99, 98, 98 but there are several values in 99 and 98.

I'm using MyIsam and want to make sure the order in the 99 and 98 is not changed even though I delete some element.
 For example, if the order was C->D->E and I delete D, then I expect to be C->E but no E->C.
Is there any logic it works when there's same order value?

答:
```<code>SELECT * FROM table ORDER BY score DESC
</code>```

Above query ordering the data only by the score.
If you want to order the data by another field as you mentioned, you have the add that field also to the query as below. You have mentions that you want to order by name in acceding order (C > D >E). So I used ORDER BY ASC. Below query will give you the output that you requested.

```<code>SELECT * FROM table ORDER BY score DESC,name ASC
</code>```

Body:
Let's say there's table:

name | score
A      100
B      98
C      99
D      99
E      99
F      98

and request sql = 'select * from table order by score desc'

I know order's gonna be 100, 99, 99, 99, 98, 98 but there are several values in 99 and 98.

I'm using MyIsam and want to make sure the order in the 99 and 98 is not changed even though I delete some element.
 For example, if the order was C->D->E and I delete D, then I expect to be C->E but no E->C.
Is there any logic it works when there's same order value?

Body:
SELECT * FROM table ORDER BY score DESC

Above query ordering the data only by the score.
If you want to order the data by another field as you mentioned, you have the add that field also to the query as below. You have mentions that you want to order by name in acceding order (C > D >E). So I used ORDER BY ASC. Below query will give you the output that you requested.

SELECT * FROM table ORDER BY score DESC,name ASC


问:
Why the loop becomes infinite?
How to get out of an infinite loop?

```<code>unsigned char half_limit = 130;

for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}
</code>```

Help, please.

Thank you!

答:
I suggest you take a look at this post:

What is an unsigned char?

Or you could try this approach:

```<code>#include <stdio.h>
#include <stdlib.h>

int main(){
        int half_limit = 130;
        int i;
        for (i = 0; i < 2 * half_limit; ++i){
                printf("%d\n", i);
        }
        return 0;
}
</code>```

Title: Why the loop becomes infinite?

Body:
How to get out of an infinite loop?

unsigned char half_limit = 130;

for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}

Help, please.

Thank you!

Body:
I suggest you take a look at this post:

What is an unsigned char?

Or you could try this approach:

#include <stdio.h>
#include <stdlib.h>

int main(){
        int half_limit = 130;
        int i;
        for (i = 0; i < 2 * half_limit; ++i){
                printf("%d\n", i);
        }
        return 0;
}


问:
How to change state value in const mode?
I am a beginner in React-Native.
I tried to change the state value.
But it seems different with "class" mode. Now I am using "const" mode.
In const mode, how can I change the state value?</p>

```<code>import React from "react";
import {
   View,
   Text,
   Image,
   TouchableOpacity
} from "react-native";

const Product = props => {
    this.state = {
        checkIconURL : require('../../assets/ic_check_circle.png')
    }
    set = () => {
        this.setState({ checkIconURL : require('../../assets/empty.png') })  //But this lines gives err.
    }

    return (
        <View>
            <Text style={{ fontSize: 16}}>Everyday</Text>
            <TouchableOpacity onPress = {this.set}>
                <Image source = {this.state.checkIconURL} style={{width: 30, height: 30}} />
            </TouchableOpacity>
        </View>
    )
}
</code>```

答:
state is not available in function components, this.state and this.setState() can only be used in class component, u have to use useState hook from react to use the state...</p>

```<code>import React ,{ useState } from "react";
import {
    View,
    Text,
    Image,
    TouchableOpacity
} from "react-native";

const Product = props => {
   const initialState = require('../../assets/ic_check_circle.png');
   const [iconUrl, setIconUrl ]  = useState(initialState);

   const set = () => {
       const emptyImageUrl = require('../../assets/empty.png')
          setIconUrl(emptyImageUrl);
    }

   return (
       <View>
           <Text style={{ fontSize: 16}}>Everyday</Text>
               <TouchableOpacity onPress = {set}>
                   <Image source = {iconUrl} style={{width:
                       30, height: 30}} />
               </TouchableOpacity>
       </View>
    )
}

</code>```

Body:
I am a beginner in React-Native.
I tried to change the state value.
But it seems different with "class" mode. Now I am using "const" mode.
In const mode, how can I change the state value?

import React from "react";
import {
   View,
   Text,
   Image,
   TouchableOpacity
} from "react-native";

const Product = props => {
    this.state = {
        checkIconURL : require('../../assets/ic_check_circle.png')
    }
    set = () => {
        this.setState({ checkIconURL : require('../../assets/empty.png') })  //But this lines gives err.
    }

    return (
        <View>
            <Text style={{ fontSize: 16}}>Everyday</Text>
            <TouchableOpacity onPress = {this.set}>
                <Image source = {this.state.checkIconURL} style={{width: 30, height: 30}} />
            </TouchableOpacity>
        </View>
    )
}

Body:
state is not available in function components, this.state and this.setState() can only be used in class component, u have to use useState hook from react to use the state...

import React ,{ useState } from "react";
import {
    View,
    Text,
    Image,
    TouchableOpacity
} from "react-native";

const Product = props => {
   const initialState = require('../../assets/ic_check_circle.png');
   const [iconUrl, setIconUrl ]  = useState(initialState);

   const set = () => {
       const emptyImageUrl = require('../../assets/empty.png')
          setIconUrl(emptyImageUrl);
    }

   return (
       <View>
           <Text style={{ fontSize: 16}}>Everyday</Text>
               <TouchableOpacity onPress = {set}>
                   <Image source = {iconUrl} style={{width:
                       30, height: 30}} />
               </TouchableOpacity>
       </View>
    )
}


问:
Understanding what fc1000_softmax output from tensorflow CNN classification means
I am using python 3.6.10 and tensorflow 1.5 on a cpu. I have trained a cnn and saved it as a .onnx file. I am now trying to make a binary classification of my images using the code below:

import onnx
import warnings
from onnx_tf.backend import prepare
import numpy as np
from numpy import array
from IPython.display import display
from PIL import Image

warnings.filterwarnings('ignore')
onnx_model = onnx.load("trainednet.onnx")  # load onnx model
tf_rep = prepare(onnx_model) # Import the ONNX model to Tensorflow

img = Image.open('Im025.jpg').resize((224, 224))
img = array(img).reshape(1,3, 224,224)

classification = tf_rep.run(img)
print(classification)
```

The print(classification) gives me an output like this:

Outputs(fc1000_softmax=array([[9.9967182e-01, 3.2823894e-04]], dtype=float32))

What does this output mean and how can I use it to understand what tensorflow classified my image as?

答:
Yes exactly, so after you model is not perfect (ie the model doesn't have 100% of accuracy). You should test on more images of class two and you will see the second number will be higher .

You should run it on a test set or refer to the metrics of the trained model.

Body:
I am using python 3.6.10 and tensorflow 1.5 on a cpu. I have trained a cnn and saved it as a .onnx file. I am now trying to make a binary classification of my images using the code below:

import onnx
import warnings
from onnx_tf.backend import prepare
import numpy as np
from numpy import array
from IPython.display import display
from PIL import Image

warnings.filterwarnings('ignore')
onnx_model = onnx.load("trainednet.onnx")  # load onnx model
tf_rep = prepare(onnx_model) # Import the ONNX model to Tensorflow

img = Image.open('Im025.jpg').resize((224, 224))
img = array(img).reshape(1,3, 224,224)

classification = tf_rep.run(img)
print(classification)

The print(classification) gives me an output like this:

Outputs(fc1000_softmax=array([[9.9967182e-01, 3.2823894e-04]], dtype=float32))

What does this output mean and how can I use it to understand what tensorflow classified my image as?


问:
How to make greedy regex for heading text? [as against tailing text]
Consider the following text:

```<code><bla><bla text><bla>
</code>```

I want to get the regex to match exactly the middle <bla text>. I tried \<.*?text.*?\> but it is capturing the string right from the start, since it starts with '<'.

Thanks a lot.

答:
What do you think about

```<code>\<[^>]*text[^>]*?\>
</code>```

Just not capture any character using ., capture anything but > using [^>]* before and after your "text".

See here on Regexr

Body:
Consider the following text:

<bla><bla text><bla>

I want to get the regex to match exactly the middle <bla text>. I tried \<.*?text.*?\> but it is capturing the string right from the start, since it starts with '<'.

Thanks a lot.

Body:
What do you think about

\<[^>]*text[^>]*?\>

Just not capture any character using ., capture anything but > using [^>]* before and after your "text".

See here on Regexr


问:
Why can't imshow show a matrix full of ones properly?
Here is a simple re-producable code:

import numpy as np
import matplotlib.pyplot as plt

plt.figure()
img = np.ones((3,3))
plt.imshow(img)
plt.figure()
plt.imshow(np.array([1,1,1,1,0,1,1,1,1]).reshape(3,3))
```

<p>It will give you images like below:</p>

<p><img src="https://i.stack.imgur.com/NZBOS.png" alt="image of matrix 1"></p>

<p><img src="https://i.stack.imgur.com/zPq6c.png" alt="image of matrix 2"></p>

<p>Even if you use</p>

<pre class="lang-py prettyprint-override"><code>plt.imshow(img.astype(float)) or
plt.imshow(img*255)
</code>```

it is still the same image.

I just need Matplotlib to give me the first image as a yellow image just like the second image does.

答:
Explicitly use the vmin and vmax parameters of imshow:

When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. vmin, vmax are ignored if the norm parameter is used.

import numpy as np
import matplotlib.pyplot as plt

plt.figure()
img = np.ones((3, 3))
plt.imshow(img, vmin=0, vmax=1)
plt.figure()
plt.imshow(np.array([1, 1, 1, 1, 0, 1, 1, 1, 1]).reshape(3, 3))
plt.show()
```

<p>For the second example, the data range is <code>[0 ... 1]</code>, so the colors are scaled with respect to that range by default. But, for the first example, the desired data range of <code>[0 ... 1]</code> can't be extracted from the data itself (all ones), such that you have to provide that information explicitly.</p>

<p>Hope that helps!</p>

<pre class="lang-none prettyprint-override"><code>----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
Matplotlib:  3.2.0rc3
NumPy:       1.18.1
----------------------------------------
</code>```

Body:
Here is a simple re-producable code:

import numpy as np
import matplotlib.pyplot as plt

plt.figure()
img = np.ones((3,3))
plt.imshow(img)
plt.figure()
plt.imshow(np.array([1,1,1,1,0,1,1,1,1]).reshape(3,3))

It will give you images like below:

Even if you use

plt.imshow(img.astype(float)) or
plt.imshow(img*255)

it is still the same image.

I just need Matplotlib to give me the first image as a yellow image just like the second image does.

Body:
Explicitly use the vmin and vmax parameters of imshow:

When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. vmin, vmax are ignored if the norm parameter is used.

import numpy as np
import matplotlib.pyplot as plt

plt.figure()
img = np.ones((3, 3))
plt.imshow(img, vmin=0, vmax=1)
plt.figure()
plt.imshow(np.array([1, 1, 1, 1, 0, 1, 1, 1, 1]).reshape(3, 3))
plt.show()

For the second example, the data range is [0 ... 1], so the colors are scaled with respect to that range by default. But, for the first example, the desired data range of [0 ... 1] can't be extracted from the data itself (all ones), such that you have to provide that information explicitly.

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
Matplotlib:  3.2.0rc3
NumPy:       1.18.1
----------------------------------------


问:
Referencing two collections documents to each other in MongoDB
Is it possible to reference 2 documents to each other using ref and if it is possible, is it recommended and is it good practice ? Like this :

FirstDocumentId Collection's Model :

```<code>const FirstDocumentId = mongoose.model(
    'FirstDocumentId',
    new mongoose.Schema({
        coolField: String,
        secondDocumentId: {type: Mongoose.Schema.Types.ObjectId, ref: 'secondDocumentId'}
    })
);
</code>```

SecondDocumentId Collection's Model :

```<code>const SecondDocumentId = mongoose.model(
    'SecondDocumentId',
    new mongoose.Schema({
        someField: String,
        firstDocumentId: {type: Mongoose.Schema.Types.ObjectId, ref: 'firstDocumentId'}
    })
);
</code>```

The point of this is to create a 1 to 1 relationship and being able to access both documents easily.

I know I can just reference 1, without referencing the second to the first, but I thought it would be simpler to modify them both.

答:
Yes you can reference a collection to another collection like the way you're doing, ideally that's how relationships between two collections are maintained in MongoDB, but you need to understand as MongoDB is schema free, there is no direct way to create/update/delete documents in second collection by creating/updating/deleting relative documents in first collection(Collections & their docs are independent - operations are atomic at document level). As there is no direct way - You've to write application logic or some kind of batch job or MongoDB-stitch to achieve reference maintainance.

But then if you ask why to maintain ?  - As you might be familiar with JOINS in SQL, this is the way, we can do reads very well using references.

So how ? - MongoDB has aggregation framework which is way powerful to query database, In aggregation there is an operator called $lookup which is helpful to do JOINS. For that you've maintain references. You can also check $graphLookup.

Do I've to use ref's ? - So as I've already talked about $lookup is a helpful operator - So by using that you doesn't need to mention ref for those fields. If you're using mongo shell or any client like robo3T or mongo compass or any native driver like mongodb driver for node.js you can use native $lookup. Even you can use lookup while using mongoose but mongoose claims they've .populate() which is very powerful compared to native $lookup, to use that you'll use ref. Apart from that there is no use of it, Even having the same models you can use $lookup with mongoose instead of using populate.

Reference fields - So you're not restricted to _id fields, you can actually reference any field but the values & types should match in both of the collections, that way it could be easy while querying else you need to convert one to another while querying every time, So be careful on writes.

Do I need to maintain reference in both collections - Not necessarily needed, it seems to easy or ok at first but when your collection does grow eventually it would be a hefty task to maintain references - You might need to write/delete/update in two collections every time, where indexes needs to build, document size/collection size can grow, So it would be better to maintain reference based on your query needs. Check this document on data design : data-modeling.

Body:
Is it possible to reference 2 documents to each other using ref and if it is possible, is it recommended and is it good practice ? Like this :

FirstDocumentId Collection's Model :

const FirstDocumentId = mongoose.model(
    'FirstDocumentId',
    new mongoose.Schema({
        coolField: String,
        secondDocumentId: {type: Mongoose.Schema.Types.ObjectId, ref: 'secondDocumentId'}
    })
);

SecondDocumentId Collection's Model :

const SecondDocumentId = mongoose.model(
    'SecondDocumentId',
    new mongoose.Schema({
        someField: String,
        firstDocumentId: {type: Mongoose.Schema.Types.ObjectId, ref: 'firstDocumentId'}
    })
);

The point of this is to create a 1 to 1 relationship and being able to access both documents easily.

I know I can just reference 1, without referencing the second to the first, but I thought it would be simpler to modify them both.


问:
IE not showing PDFs with caching disabled
I've been asked to implement a security requirement that we instruct browsers not to cache sensitive data. This is all fine for the ASPX content using the standard instructions:

```<code>        Response.Expires = -1;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();
</code>```

However when I set these headers for PDF downloads, IE8 won't show the PDF (haven't tried other IE versions yet, kinda moot, I need it working on all of them, even IEfreaking6). Seems to work in firefox 4 beta, but I haven't double checked that it's definitely not caching it. Here is the abridged version of the code I'm using to serve the PDFs:

```<code>        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.Buffer = true;

        //This stops the PDFs from being viewed :(
        //Response.Expires = -1;
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //Response.Cache.SetNoStore();

        Response.ContentType = mime;
        Response.AddHeader("Content-Disposition", disposition);

        Response.BinaryWrite(file);

        Response.End();
</code>```

Where in the case of PDFs the mime type is set to:

```<code>       private const string mimeTypePDF = "application/pdf";
</code>```

The disposition is set to:

```<code>       var disposition = String.Format("{0};filename=\"{1}\"", SendInline ? "inline" : "attachment", Path.GetFileName(filename));
</code>```

I'm going to play-around a bit more, maybe forcing them to download as mimetype "application/octet-stream" might work, but that would stop the nice open PDF's in a new browser window from working.

Has anyone had any success with preventing IE from caching PDFs from the server side and successfully displaying them?

Just to give a clear example about what happens. In one scenario user's can select a bunch of reports from a list, these are compiled into a PDF and the PDF is shown in a new browser window. With the caching enabled the browser window opens, but remains resolutely blank.

答:
I also believe it's a bug in Internet Explorer. I was setting the cache-control header to no-cache and having the same problem. Also note that in Internet Options > Advanced > Security there's a 'Do not save encrypted pages to disk' option that could affect it.

Removal of the cache-control header from the response sorted out my issue. I also then tried checking the above mentioned option, and it seemed to work even better for me. Iinstead of storing the PDF in %LocalAppData%\Microsoft\Windows\Temporary Internet Files, it actually caused IE8 to issue a dialog allowing me to choose where to save it (which is actually what I wanted in my case).

ContentLicense: CC BY-SA 2.5

Body:
I've been asked to implement a security requirement that we instruct browsers not to cache sensitive data. This is all fine for the ASPX content using the standard instructions:

        Response.Expires = -1;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();

However when I set these headers for PDF downloads, IE8 won't show the PDF (haven't tried other IE versions yet, kinda moot, I need it working on all of them, even IEfreaking6). Seems to work in firefox 4 beta, but I haven't double checked that it's definitely not caching it. Here is the abridged version of the code I'm using to serve the PDFs:

        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.Buffer = true;

        //This stops the PDFs from being viewed :(
        //Response.Expires = -1;
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //Response.Cache.SetNoStore();

        Response.ContentType = mime;
        Response.AddHeader("Content-Disposition", disposition);

        Response.BinaryWrite(file);

        Response.End();

Where in the case of PDFs the mime type is set to:

       private const string mimeTypePDF = "application/pdf";

The disposition is set to:

       var disposition = String.Format("{0};filename=\"{1}\"", SendInline ? "inline" : "attachment", Path.GetFileName(filename));

I'm going to play-around a bit more, maybe forcing them to download as mimetype "application/octet-stream" might work, but that would stop the nice open PDF's in a new browser window from working.

Has anyone had any success with preventing IE from caching PDFs from the server side and successfully displaying them?

Just to give a clear example about what happens. In one scenario user's can select a bunch of reports from a list, these are compiled into a PDF and the PDF is shown in a new browser window. With the caching enabled the browser window opens, but remains resolutely blank.


问:
How do I register all Vue components at once in a laravel project?
I'm a begginer so I'm sorry if I have some misunderstandings.

I have a laravel project genereted by laradock.
I wanted to use Vue.js and its components, and I editted app.js.

app.js

window.Vue = require('vue');
Vue.component('my-comp', require('./components/my-comp.vue').default);

const app = new Vue({
    el: '#app',
});
```

<p>that correctly works.
Considering adding more components in the future, I replaced the code like this:</p>

<pre class="lang-js prettyprint-override"><code>const allDirents = fs.readdirSync(dirPath, { withFileTypes: true });
const fileNames = allDirents.filter(dirent => dirent.isFile()).map(({ name }) => name);
fileNames.forEach(filename => {
    Vue.component(filename.replace('.vue', ''), require(dirPath + filename).default);
})
</code>```

But it didn't work.
npm run dev returns the message "Compiled successfully", but when I open a browser, browser's console outputs such messages:

```<code>Uncaught TypeError: fs.readdirSync is not a function
    at Module../resources/js/app.js (app.js:73618)
</code>```

Can't I use Node.js's File System module In a laravel project?
I just want to know how do I get all file name in app.js in the project.
I know it will go well if I register components one by one as follows:

Vue.component('my-comp1', require('./components/my-comp1.vue').default);
Vue.component('my-comp2', require('./components/my-comp2.vue').default);
...
```

But I think it's little tedious and not smart, so I'd rather not.

Does anyone have ideas or solutions?

thanks.

答:
You can try this in your app.js:</p>

```<code>import Vue from 'vue'
import exampleComponent from  './components/ExampleComponent.vue'
import booking  from './components/Booking.vue'
import inquiry from './components/Inquiry'

const app = new Vue({
    el: '#app',
    components:{
        exampleComponent,
        booking,
        inquiry
    }
});
</code>```

Body:
I'm a begginer so I'm sorry if I have some misunderstandings.

I have a laravel project genereted by laradock.
I wanted to use Vue.js and its components, and I editted app.js.

app.js

window.Vue = require('vue');
Vue.component('my-comp', require('./components/my-comp.vue').default);

const app = new Vue({
    el: '#app',
});

that correctly works.
Considering adding more components in the future, I replaced the code like this:

const allDirents = fs.readdirSync(dirPath, { withFileTypes: true });
const fileNames = allDirents.filter(dirent => dirent.isFile()).map(({ name }) => name);
fileNames.forEach(filename => {
    Vue.component(filename.replace('.vue', ''), require(dirPath + filename).default);
})

But it didn't work.
npm run dev returns the message "Compiled successfully", but when I open a browser, browser's console outputs such messages:

Uncaught TypeError: fs.readdirSync is not a function
    at Module../resources/js/app.js (app.js:73618)

Can't I use Node.js's File System module In a laravel project?
I just want to know how do I get all file name in app.js in the project.
I know it will go well if I register components one by one as follows:

Vue.component('my-comp1', require('./components/my-comp1.vue').default);
Vue.component('my-comp2', require('./components/my-comp2.vue').default);
...

But I think it's little tedious and not smart, so I'd rather not.

Does anyone have ideas or solutions?

thanks.

Body:
You can try this in your app.js:

import Vue from 'vue'
import exampleComponent from  './components/ExampleComponent.vue'
import booking  from './components/Booking.vue'
import inquiry from './components/Inquiry'

const app = new Vue({
    el: '#app',
    components:{
        exampleComponent,
        booking,
        inquiry
    }
});


问:
Type-safe configuration read/write library for Java?
Is there a good configuration library for Java which will allow me to read settings in a type-safe way? For example by taking my crafted IConfiguration interface with getters and setters declared and allowing me to read/write configuration via it.

It's a bit boring to read settings using properties.getProperty("group.setting") and then cast it to needed type. Apache commons configuration allows to use something like config.getDouble("number"), but "number" here is a string again and I would like to be able to do something like double value = config.GetNumber().

答:
My Config4J library (which is mature and well-documented but not widely known) provides most of what you want.

In particular, Config4J provides type-safe "lookup" (that is, "get") operations for built-in types such as string, boolean, int, float, and durations (such as "500 milliseconds" or "2.5 days"). A duration string is automatically converted to an integer value denoting (your choice of) milliseconds or seconds.

The library also provides building blocks so you can perform type-safe lookups on strings of the form "<float> <units>" (for example, "2 cm" and "10.5 meters" for distances) or "<units> <float>" (for example, "$0.99" or "£10.00" for money).

The library also provides a trivial-to-use schema validator (in case that is of interest to you).

The way Config4J fails to meet your stated requirements is that the "insert" (that is, "put") functionality of the library works only in terms of strings. So you would have to convert an int/boolean/float/int-denoting-duration/whatever value into a string and then "insert" that into the Config4J object. However, that -to-string conversion is not usually a burdensome task.

After inserting some name=value pairs into the Config4J object, you can then call dump() to serialise the entire object into a string that you can then write back to a configuration file.

Reading Chapters 2 and 3 of the "Getting Started Guide" (PDF, HTML) should give you an a good-enough overview of Config4J to decide if it fits your needs. You might also want to look at the "simple-encapsulation" demo, which is supplied in the source-code download (compressed tar, zip).


问:
How to evenly distributed margin with flex?

I want to display the UI as the picture, and I use a loop to creat the div , so I think flex is the most convince way to do it . each row displays four elements and I want set the margin(top left right bottom) of each flex-item the same 10px. I tried justify-content:space-between / space-around. and neither of these is what I want.

class App extends Component {
  constructor() {
    super();
    this.arr = [1, 2, 3, 4, 5];
  }

  createDiv = () => {
    // return  div className="child" />
  };

  render() {
    return (

        {this.arr.map((item, index) => (

        ))}

    );
  }
}

```

<pre class="lang-css prettyprint-override"><code>.contianer{
   /* width: calc(100%-20px); */
  display:flex;
  flex-flow: row wrap;
  background-color: gray;
  justify-content: space-between
  /* flex:1; */
}

.child{
  background-color: yellow;
  width: calc((100% - 50px) / 4);
  height: 100px;
  margin: 10px 5px

}
</code>```

online demo : https://stackblitz.com/edit/react-fapbff

so it's there a way to achive what I want?

答:
If you need it with flex layout you can use align-item and height for vertical space.

see below css

```<code> .contianer{

  display:flex;
  flex-flow: row wrap;
  background-color: gray;
  justify-content: space-between;
  align-items: space-between;
  height: 230px;
  padding:10px 0 0 10px

}

.child{
  background-color: yellow;
  width: calc((100% - 40px) / 4);
  height: 100px;

}

</code>```

but for full control about layout you can use grid layout.

Body:
I want to display the UI as the picture, and I use a loop to creat the div , so I think flex is the most convince way to do it . each row displays four elements and I want set the margin(top left right bottom) of each flex-item the same 10px. I tried justify-content:space-between / space-around. and neither of these is what I want.

class App extends Component {
  constructor() {
    super();
    this.arr = [1, 2, 3, 4, 5];
  }

  createDiv = () => {
    // return  div className="child" />
  };

  render() {
    return (

        {this.arr.map((item, index) => (

        ))}

    );
  }
}

.contianer{
   /* width: calc(100%-20px); */
  display:flex;
  flex-flow: row wrap;
  background-color: gray;
  justify-content: space-between
  /* flex:1; */
}

.child{
  background-color: yellow;
  width: calc((100% - 50px) / 4);
  height: 100px;
  margin: 10px 5px

}

online demo : https://stackblitz.com/edit/react-fapbff

so it's there a way to achive what I want?

Body:
If you need it with flex layout you can use align-item and height for vertical space.

see below css

 .contianer{

  display:flex;
  flex-flow: row wrap;
  background-color: gray;
  justify-content: space-between;
  align-items: space-between;
  height: 230px;
  padding:10px 0 0 10px

}

.child{
  background-color: yellow;
  width: calc((100% - 40px) / 4);
  height: 100px;

}

but for full control about layout you can use grid layout.


问:
How can i transpose csv data using java spark
I am using java spark and i want to know if there is anyway i can transform the sample data given below

```<code>Incremental Cost Number | Approver Names
---------------------------------------------------------------------------------
S703401                  |Ryan P Cassidy|Christopher J Mattingly|Frank E
                         LaSota|Ryan P Cassidy|Anthony L Locricchio|Jason Monte
</code>```

into something like this.

```<code>Incremental Cost Number| Approver Names
-------------------------------------------
S703401                | Ryan P Cassidy
S703401                | Christopher J Mattingly
S703401                | Frank E LaSota
S703401                | Ryan P Cassidy
S703401                | Anthony L Locricchio
S703401                | Jason Monte
</code>```

Also the file i am importing is a comma separated csv file, just that a particular column contains multiple values are separated by pipeline symbol. And similarly if i have multiple values of Incremental Cost Number.

答:
You can do Something like below, if you have multiple columns</p>

```<code>  import org.apache.spark.sql.functions._

   val df = Seq(("S703401","Ryan P Cassidy|Christopher J Mattingly|Frank E
   LaSota|Ryan P Cassidy|Anthony L Locricchio|Jason
   Monte","xyz|mnp|abc")).toDF("Incremental Cost Number","Approver
   Names","3rd Column")

  df.withColumn("Approver Names", explode(split(col("Approver Names"), "\\|")))
  .withColumn("3rd Column", explode(split(col("3rd Column"), "\\|")))
  .show()

   +-----------------------+--------------------+-----------+
   |Incremental Cost Number|      Approver Names| 3rd Column|
   +-----------------------+--------------------+-----------+
   |                S703401|Ryan P Cassidy|Ch...|xyz|mnp|abc|
   +-----------------------+--------------------+-----------+

   +-----------------------+--------------------+----------+
   |Incremental Cost Number|      Approver Names|3rd Column|
   +-----------------------+--------------------+----------+
   |                S703401|      Ryan P Cassidy|       xyz|
   |                S703401|      Ryan P Cassidy|       mnp|
   |                S703401|      Ryan P Cassidy|       abc|
   |                S703401|Christopher J Mat...|       xyz|
   |                S703401|Christopher J Mat...|       mnp|
   |                S703401|Christopher J Mat...|       abc|
   |                S703401|      Frank E LaSota|       xyz|
   |                S703401|      Frank E LaSota|       mnp|
   |                S703401|      Frank E LaSota|       abc|
   |                S703401|      Ryan P Cassidy|       xyz|
   |                S703401|      Ryan P Cassidy|       mnp|
   |                S703401|      Ryan P Cassidy|       abc|
   |                S703401|Anthony L Locricchio|       xyz|
   |                S703401|Anthony L Locricchio|       mnp|
   |                S703401|Anthony L Locricchio|       abc|
   |                S703401|         Jason Monte|       xyz|
   |                S703401|         Jason Monte|       mnp|
   |                S703401|         Jason Monte|       abc|
   +-----------------------+--------------------+----------+
</code>```

Body:
I am using java spark and i want to know if there is anyway i can transform the sample data given below

Incremental Cost Number | Approver Names
---------------------------------------------------------------------------------
S703401                  |Ryan P Cassidy|Christopher J Mattingly|Frank E
                         LaSota|Ryan P Cassidy|Anthony L Locricchio|Jason Monte

into something like this.

Incremental Cost Number| Approver Names
-------------------------------------------
S703401                | Ryan P Cassidy
S703401                | Christopher J Mattingly
S703401                | Frank E LaSota
S703401                | Ryan P Cassidy
S703401                | Anthony L Locricchio
S703401                | Jason Monte

Also the file i am importing is a comma separated csv file, just that a particular column contains multiple values are separated by pipeline symbol. And similarly if i have multiple values of Incremental Cost Number.

Body:
You can do Something like below, if you have multiple columns

  import org.apache.spark.sql.functions._

   val df = Seq(("S703401","Ryan P Cassidy|Christopher J Mattingly|Frank E
   LaSota|Ryan P Cassidy|Anthony L Locricchio|Jason
   Monte","xyz|mnp|abc")).toDF("Incremental Cost Number","Approver
   Names","3rd Column")

  df.withColumn("Approver Names", explode(split(col("Approver Names"), "\\|")))
  .withColumn("3rd Column", explode(split(col("3rd Column"), "\\|")))
  .show()

   +-----------------------+--------------------+-----------+
   |Incremental Cost Number|      Approver Names| 3rd Column|
   +-----------------------+--------------------+-----------+
   |                S703401|Ryan P Cassidy|Ch...|xyz|mnp|abc|
   +-----------------------+--------------------+-----------+

   +-----------------------+--------------------+----------+
   |Incremental Cost Number|      Approver Names|3rd Column|
   +-----------------------+--------------------+----------+
   |                S703401|      Ryan P Cassidy|       xyz|
   |                S703401|      Ryan P Cassidy|       mnp|
   |                S703401|      Ryan P Cassidy|       abc|
   |                S703401|Christopher J Mat...|       xyz|
   |                S703401|Christopher J Mat...|       mnp|
   |                S703401|Christopher J Mat...|       abc|
   |                S703401|      Frank E LaSota|       xyz|
   |                S703401|      Frank E LaSota|       mnp|
   |                S703401|      Frank E LaSota|       abc|
   |                S703401|      Ryan P Cassidy|       xyz|
   |                S703401|      Ryan P Cassidy|       mnp|
   |                S703401|      Ryan P Cassidy|       abc|
   |                S703401|Anthony L Locricchio|       xyz|
   |                S703401|Anthony L Locricchio|       mnp|
   |                S703401|Anthony L Locricchio|       abc|
   |                S703401|         Jason Monte|       xyz|
   |                S703401|         Jason Monte|       mnp|
   |                S703401|         Jason Monte|       abc|
   +-----------------------+--------------------+----------+


问:
Cannot resolve parameter 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider apiDescriptionsProvider
We use swagger for explore api and one time we turned off razor.

And this led to problem with swagger

Original error:

```<code>An unhandled exception occurred while processing the request.
DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'
  on type 'Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator' can be invoked with the available services and parameters:
Cannot resolve parameter 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider apiDescriptionsProvider'
  of constructor 'Void .ctor(Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider, Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory, Microsoft.Extensions.Options.IOptions`1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions])'.
Cannot resolve parameter 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider apiDescriptionsProvider'
of constructor 'Void .ctor(Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider, Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory, Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions)'.
Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable<Parameter> parameters)
</code>```

答:
I used AddMvc() and it got resolved

For example:

```<code>services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
</code>```

Body:
We use swagger for explore api and one time we turned off razor.

And this led to problem with swagger

Original error:

An unhandled exception occurred while processing the request.
DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'
  on type 'Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator' can be invoked with the available services and parameters:
Cannot resolve parameter 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider apiDescriptionsProvider'
  of constructor 'Void .ctor(Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider, Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory, Microsoft.Extensions.Options.IOptions`1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions])'.
Cannot resolve parameter 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider apiDescriptionsProvider'
of constructor 'Void .ctor(Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider, Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory, Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions)'.
Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable<Parameter> parameters)

Body:
I used AddMvc() and it got resolved

For example:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);


问:
(android studio) can't change the "Webpage not available" page in webview
I'm trying to display my own "no internet" page in my app.
I think something might be wrong with my code, I've been following this tutorial but for some reason, my code keeps displaying the default "Webpage not available" screen.</p>

```<code>public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webView.loadUrl("https://www.kasumushi.com/");

        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");

            }
        });
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        }else {
            super.onBackPressed();
        }
    }

}
</code>```

答:
would you please check the below procedure and try to retest your problem.</p>

```<code>                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    Toast.makeText(MainActivity.this, "Error! " + description, Toast.LENGTH_SHORT).show();
                    //Clear WebView
                    try {
                        view.stopLoading();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        view.clearView();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (view.canGoBack()) {
                        view.goBack();
                    }
                    String ErrorPagePath = "file:///android_asset/htmls/error.html";
                    view.loadUrl(ErrorPagePath);

                    super.onReceivedError(view, errorCode, description, failingUrl);
                }
            });
</code>```

Body:
I'm trying to display my own "no internet" page in my app.
I think something might be wrong with my code, I've been following this tutorial but for some reason, my code keeps displaying the default "Webpage not available" screen.

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webView.loadUrl("https://www.kasumushi.com/");

        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");

            }
        });
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        }else {
            super.onBackPressed();
        }
    }

}

Body:
would you please check the below procedure and try to retest your problem.

                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    Toast.makeText(MainActivity.this, "Error! " + description, Toast.LENGTH_SHORT).show();
                    //Clear WebView
                    try {
                        view.stopLoading();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        view.clearView();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (view.canGoBack()) {
                        view.goBack();
                    }
                    String ErrorPagePath = "file:///android_asset/htmls/error.html";
                    view.loadUrl(ErrorPagePath);

                    super.onReceivedError(view, errorCode, description, failingUrl);
                }
            });


问:
Extracting the encoded representations of an image in PyTorch?
I have a template autoencoder neural net model made in PyTorch that I'm using on the Omniglot dataset. I'd like to extract the encoded representations of the image, but I'm unsure how.</p>

```<code># Load data
mean = 0.5
std = 0.5
batch_size = 128
img_transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((mean,), (std,))
])
dataset = Omniglot('.', download=True, transform=img_transform)
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)

# Define Autoencoder
class Autoencoder(nn.Module):

    def __init__(self, n=64):
        super(Autoencoder, self).__init__()
        self.encoder = nn.Sequential(
            nn.Linear(105*105, 256, bias=True),
            nn.ReLU(True),
            nn.Linear(256, 64, bias=True),
            nn.ReLU(True),
            nn.Linear(64, n, bias=True),
            nn.ReLU(True)
        )
        self.decoder = nn.Sequential(
            nn.Linear(n, 64, bias=True),
            nn.ReLU(True),
            nn.Linear(64, 256, bias=True),
            nn.ReLU(True),
            nn.Linear(256, 105*105, bias=True),
            nn.Tanh()
        )

    def forward(self, x):
        x = self.encoder(x)
        x = self.decoder(x)
        return x

def train(num_epochs, dataloader, model, criterion, optimizer):
    for epoch in range(num_epochs):
        for data in dataloader:
            img, label = data
            img = img.view(img.size(0), -1)
            img = Variable(img).cuda()
            output = model(img)
            loss = criterion(output, img)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
    return model

# Train model
num_epochs = 25
learning_rate = 1e-3
model = Autoencoder().cuda()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
trained_model = train(num_epochs, dataloader, model, criterion, optimizer)
</code>```

答:
You can simply return the encoded output in the forward function as follows:

```<code>class Autoencoder(nn.Module):
...
    def forward(self, x):
        x = self.encoder(x)
        encoded_x = x
        x = self.decoder(x)
        return x, encoded_x
</code>```

Modify the training function a little bit:

```<code>output, encoded_output = model(img)
</code>```

OR you can simply call encoder:

```<code>encoded_output = model.encoder(img)
</code>```

Body:
I have a template autoencoder neural net model made in PyTorch that I'm using on the Omniglot dataset. I'd like to extract the encoded representations of the image, but I'm unsure how.

# Load data
mean = 0.5
std = 0.5
batch_size = 128
img_transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((mean,), (std,))
])
dataset = Omniglot('.', download=True, transform=img_transform)
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)

# Define Autoencoder
class Autoencoder(nn.Module):

    def __init__(self, n=64):
        super(Autoencoder, self).__init__()
        self.encoder = nn.Sequential(
            nn.Linear(105*105, 256, bias=True),
            nn.ReLU(True),
            nn.Linear(256, 64, bias=True),
            nn.ReLU(True),
            nn.Linear(64, n, bias=True),
            nn.ReLU(True)
        )
        self.decoder = nn.Sequential(
            nn.Linear(n, 64, bias=True),
            nn.ReLU(True),
            nn.Linear(64, 256, bias=True),
            nn.ReLU(True),
            nn.Linear(256, 105*105, bias=True),
            nn.Tanh()
        )

    def forward(self, x):
        x = self.encoder(x)
        x = self.decoder(x)
        return x

def train(num_epochs, dataloader, model, criterion, optimizer):
    for epoch in range(num_epochs):
        for data in dataloader:
            img, label = data
            img = img.view(img.size(0), -1)
            img = Variable(img).cuda()
            output = model(img)
            loss = criterion(output, img)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
    return model

# Train model
num_epochs = 25
learning_rate = 1e-3
model = Autoencoder().cuda()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
trained_model = train(num_epochs, dataloader, model, criterion, optimizer)

Body:
You can simply return the encoded output in the forward function as follows:

class Autoencoder(nn.Module):
...
    def forward(self, x):
        x = self.encoder(x)
        encoded_x = x
        x = self.decoder(x)
        return x, encoded_x

Modify the training function a little bit:

output, encoded_output = model(img)

OR you can simply call encoder:

encoded_output = model.encoder(img)


问:
Why I've gotten "Uncaught TypeError: Cannot read property 'counter' of undefined" despite I'm using arrow function for SetTimeout?
The following small count down application cause Uncaught TypeError: Cannot read property 'counter' of undefined at the timing of evaluation of this.counter.

```<code><template>
  <v-app>
    <v-content>
      Redirect after {{counter}} sec.
    </v-content>
  </v-app>
</template>

<script>
/* eslint-disable no-console */
export default {
  name: 'App',

  components: {
  },
  mounted() {
    this.countdown();
  },
  created() {
  },
  methods: {
    countdown: () => {
      setTimeout(() => {
        if (--this.counter <=0){
          location.href=this.$redirectURL;
        } else {
          this.countdown();
        }
      }, 1*1000);
    }
  },

  data: () => ({
    counter: 5,
  }),
};
</script>
</code>```

Uncaught TypeError: Cannot read property 'counter' of undefined as follows:

I have no idea why coutner is evaluated as undefined despite I'm using arrow function, which means the scope of "this pointer" must be lexical. Thank you for your suggestions!

答:
The countdown function is an arrow function, which means that the this inside it is inherited from the outer scope. The same is true for the setTimeout callback. So, here:

```<code>export default {
  // ...
  methods: {
    countdown: () => {
      setTimeout(() => {
        if (--this.counter <=0){
          location.href=this.$redirectURL;
        } else {
          this.countdown();
        }
      }, 1*1000);
    }
  },
  // ...
}
</code>```

this refers to the this at the top level of the module, which is undefined in your setup.

You want this to refer to the current instance instead: when calling countdown, it should capture the new this value (of the instance), rather than inheriting the this of the outer scope. So, change:

```<code>countdown: () => {
</code>```

to

```<code>countdown() {
</code>```

or to

```<code>countdown: function() {
</code>```

Body:
The following small count down application cause Uncaught TypeError: Cannot read property 'counter' of undefined at the timing of evaluation of this.counter.

<template>
  <v-app>
    <v-content>
      Redirect after {{counter}} sec.
    </v-content>
  </v-app>
</template>

Uncaught TypeError: Cannot read property 'counter' of undefined as follows:

I have no idea why coutner is evaluated as undefined despite I'm using arrow function, which means the scope of "this pointer" must be lexical. Thank you for your suggestions!

Body:
The countdown function is an arrow function, which means that the this inside it is inherited from the outer scope. The same is true for the setTimeout callback. So, here:

export default {
  // ...
  methods: {
    countdown: () => {
      setTimeout(() => {
        if (--this.counter <=0){
          location.href=this.$redirectURL;
        } else {
          this.countdown();
        }
      }, 1*1000);
    }
  },
  // ...
}

this refers to the this at the top level of the module, which is undefined in your setup.

You want this to refer to the current instance instead: when calling countdown, it should capture the new this value (of the instance), rather than inheriting the this of the outer scope. So, change:

countdown: () => {

to

countdown() {

or to

countdown: function() {


问:
What is the right way to get an NSString object from an NSArray, keeping Memory Managment in mind?
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

```<code>NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];
</code>```

Now I want to get an object from this NSArray at index 2.

```<code>NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?
</code>```

OR I should first alloc nameString and then assign value to it ?

答:
NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];
and getting value in NSString from any of index wont affect memory ...no need to allocate here.
The collected NSString need not required to be retained until you are passing its ownership to another controller/object.

Body:
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];

Now I want to get an object from this NSArray at index 2.

NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?

OR I should first alloc nameString and then assign value to it ?


问:
Build Fails: `npm rebuild node-sass --force`
Using n to switch Node versions.
I've ran yarn, npm rebuild node-sass --force many many times. And still fails. Getting this error:

Node Sass could not find a binding for your current environment

```<code>This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass --force` to build the binding for your current environment.
</code>```

Anyone have any idea how to fix?

Also..
When running this command..

```<code>npm rebuild node-sass --force
</code>```

I get..

```<code>npm WARN using --force I sure hope you know what you are doing.
</code>```

Doens't seem like it is doing anything..

答:
I have tried all options like:

```<code>npm rebuild --force
npm rebuild node-sass --force
npm rebuild node-sass &
</code>```

also did try to install through Python &
updated VS Project links, but nothing worked..

EXCEPT running it manually:

```<code>node node_modules/node-sass/scripts/install.js
</code>```

Body:
Using n to switch Node versions.
I've ran yarn, npm rebuild node-sass --force many many times. And still fails. Getting this error:

Node Sass could not find a binding for your current environment

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass --force` to build the binding for your current environment.

Anyone have any idea how to fix?

Also..
When running this command..

npm rebuild node-sass --force

I get..

npm WARN using --force I sure hope you know what you are doing.

Doens't seem like it is doing anything..

Body:
I have tried all options like:

npm rebuild --force
npm rebuild node-sass --force
npm rebuild node-sass &

also did try to install through Python &
updated VS Project links, but nothing worked..

EXCEPT running it manually:

node node_modules/node-sass/scripts/install.js


问:
How to check only specific s3 bucket exists using boto3
I am trying to list a specific bucket in my aws account. But I have used list_buckets() method which returns all the buckets. Purpose is to check if this bucket exists or not

I could have used head_bucket() method, but it doesn't return anything in return (according to boto3 documentation)

I am using mistral workflows to get this bucket (still calling boto3 methtods) not python

But somehow, is there a boto3 method to check if the s3 bucket exists or not?

I need to get the return and compare it accordingly to check if the bucket exists. So if that condition satisfies, it only triggers the next task in mistral stackstorm workflow.

In case you need I will put the workflow as well.

```<code>check_if_exists:
        action: aws_boto3.boto3action
        input:
          action_name: "list_buckets"
          region: <% $.bucket_region %>
          service: "s3"
        publish:
          return_code: <% task(check_if_exists).result.result.Buckets.select($.Name) %>
        on-success:
           - task_one
        on-error:
          - fail
</code>```

答:
You could use one of the get_bucket_*() operations, such as get_bucket_location().

However, this will only function correctly if you have permission to run this operation on the bucket and if the bucket belongs to the same account as your IAM credentials.

Body:
I am trying to list a specific bucket in my aws account. But I have used list_buckets() method which returns all the buckets. Purpose is to check if this bucket exists or not

I could have used head_bucket() method, but it doesn't return anything in return (according to boto3 documentation)

I am using mistral workflows to get this bucket (still calling boto3 methtods) not python

But somehow, is there a boto3 method to check if the s3 bucket exists or not?

I need to get the return and compare it accordingly to check if the bucket exists. So if that condition satisfies, it only triggers the next task in mistral stackstorm workflow.

In case you need I will put the workflow as well.

check_if_exists:
        action: aws_boto3.boto3action
        input:
          action_name: "list_buckets"
          region: <% $.bucket_region %>
          service: "s3"
        publish:
          return_code: <% task(check_if_exists).result.result.Buckets.select($.Name) %>
        on-success:
           - task_one
        on-error:
          - fail


问:
Get total [checkbox] value
HTML:

```<code><input type="checkbox" name="product[book]" value="10" /> book
<input type="checkbox" name="product[plane]" value="20" /> plane
</code>```

PHP:

```
<code>
foreach ($_POST['product'] as $name => $value) {
    echo $value;
}
</code>
```

How to get the total (sum) value if the user select two fields (book & plane)

答:
```<code>$pTotal = 0;
foreach ($_POST['product'] as $pVal)
{
  $pTotal += intval($pVal,10);
}
</code>```

Make sure you're explicit about the format type.  Without checking, I would expect the values coming in to be strings, not integers... which will give you all sorts of headaches if you're trying to add them up.  : )

Title: Get total [checkbox] value

Body:
HTML:

<input type="checkbox" name="product[book]" value="10" /> book
<input type="checkbox" name="product[plane]" value="20" /> plane

PHP:

foreach ($_POST['product'] as $name => $value) {
    echo $value;
}

How to get the total (sum) value if the user select two fields (book & plane)

Body:
$pTotal = 0;
foreach ($_POST['product'] as $pVal)
{
  $pTotal += intval($pVal,10);
}

Make sure you're explicit about the format type.  Without checking, I would expect the values coming in to be strings, not integers... which will give you all sorts of headaches if you're trying to add them up.  : )


问:
How to update core-js to core-js@3 dependency?
While I was trying to install and setup react native, the precaution observed about the core-js version as update your core-js@... to core-js@3 But don't know how to update my core-js.

```<code>$ sudo react-native init AwesomeProject121
Password:
This will walk you through creating a new React Native project in /Users/amarnr1989/AwesomeProject121
Using yarn v1.13.0
Installing react-native...
yarn add v1.13.0
info No lockfile found.
[1/4]   Resolving packages...
warning react-native > create-react-class > fbjs > core-js@1.2.7: core-js@<2.6.5 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.
[2/4]   Fetching packages...
[----------------------------------------------------------------------------------------------------------------------------------------------------------] 0/601internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module '/Users/amarnr1989/AwesomeProject121/node_modules/react-native/package.json'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at checkNodeVersion (/usr/local/lib/node_modules/react-native-cli/index.js:306:21)
    at run (/usr/local/lib/node_modules/react-native-cli/index.js:300:3)
    at createProject (/usr/local/lib/node_modules/react-native-cli/index.js:249:3)
    at init (/usr/local/lib/node_modules/react-native-cli/index.js:200:5)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:153:7)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
</code>```

Please Suggest

答:
For npm </p>

```<code> npm install --save core-js@^3
</code>```

<p>for yarn </p>

```<code>yarn add core-js@^3
</code>```

Body:
While I was trying to install and setup react native, the precaution observed about the core-js version as update your core-js@... to core-js@3 But don't know how to update my core-js.

$ sudo react-native init AwesomeProject121
Password:
This will walk you through creating a new React Native project in /Users/amarnr1989/AwesomeProject121
Using yarn v1.13.0
Installing react-native...
yarn add v1.13.0
info No lockfile found.
[1/4]   Resolving packages...
warning react-native > create-react-class > fbjs > core-js@1.2.7: core-js@<2.6.5 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.
[2/4]   Fetching packages...
[----------------------------------------------------------------------------------------------------------------------------------------------------------] 0/601internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module '/Users/amarnr1989/AwesomeProject121/node_modules/react-native/package.json'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at checkNodeVersion (/usr/local/lib/node_modules/react-native-cli/index.js:306:21)
    at run (/usr/local/lib/node_modules/react-native-cli/index.js:300:3)
    at createProject (/usr/local/lib/node_modules/react-native-cli/index.js:249:3)
    at init (/usr/local/lib/node_modules/react-native-cli/index.js:200:5)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:153:7)
    at Module._compile (internal/modules/cjs/loader.js:701:30)

Please Suggest

Body:
For npm

 npm install --save core-js@^3

for yarn

yarn add core-js@^3