问:
MVC C# Count Records Based on Condition
I am trying to count and display the number of logs conducted by various users from the Admin section.
Each user has a  UserID and through this, I would like to count and display data from a specific table.
I have made of a stored procedure and passed it to the Controller via a ViewBag but it keeps returning 1 as the total for all values.
 the procedure is Below

```<code>CREATE proc [Usp_GetCallCountByUserID]
@UserID int output
AS
BEGIN
SELECT COUNT (*) FROM Customer Where UserID= @UserID
GROUP BY UserID
set @UserID =@@ROWCOUNT
END
GO
</code>```

Controller:

```<code>     public ActionResult Index()
       {
        con.Open();
        SqlCommand comm = new SqlCommand("Usp_GetCallCountByUserID", con);
        comm.CommandType = CommandType.StoredProcedure;
        comm.Parameters.Add("@UserID", SqlDbType.Int).Direction =
            ParameterDirection.Output;
        SqlDataReader reader;
        reader = comm.ExecuteReader();
        reader.Close();
        ViewBag.CountLog = comm.Parameters["@UserID"].Value.ToString();
        con.Close();

        var callCustomers = db.Registrations;
        return View(callCustomers.ToList());
    }
</code>```

答:
Edit: answer edited after clarification

If I'm right you would do something like this:

```<code>CREATE proc [Usp_GetCallCountByUserID]
  @UserId int
  @TotalCount int output
AS
BEGIN
  SELECT @TotalCount = COUNT(*) FROM Customer WHERE UserId = @UserId
END
</code>```

Please modify calling c# code accordingly. You do not need the GROUP BY clause, if grouping by the same field you are filtering on.

Consideration: IMO a stored procedure is overkill for such a simple task, and does not give any sensible performance improvements, expecially if your application and DB server are always up (both will optimize the query execution, if repeated). When queries are so simple, I'd rather execute a CommandType.Text DbCommand:

```<code>conn.Open();
using (var cmd = conn.CreateCommand())
{
   cmd.CommandType = CommandType.Text;
   cmd.CommandText = "SELECT Count(*) FROM Customer where UserId = @UserId";
   cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = currentUserId;
   using (var reader = cmd.ExecuteReader())
   {
      reader.Read(); // Advance one record
      ViewBag.CountLog = reader.GetInt32(0);
   }
}
</code>```

Finally, since you seem to be using some sort of ORM (Entity Framework?), why not just:

```<code>db.Customers.Count(c => c.UserId == currentUserId);
</code>```

That is pretty much equivalent to the code above.

Title: MVC C# Count Records Based on Condition

Body:
I am trying to count and display the number of logs conducted by various users from the Admin section.
Each user has a  UserID and through this, I would like to count and display data from a specific table.
I have made of a stored procedure and passed it to the Controller via a ViewBag but it keeps returning 1 as the total for all values.
 the procedure is Below

CREATE proc [Usp_GetCallCountByUserID]
@UserID int output
AS
BEGIN
SELECT COUNT (*) FROM Customer Where UserID= @UserID
GROUP BY UserID
set @UserID =@@ROWCOUNT
END
GO

Controller:

     public ActionResult Index()
       {
        con.Open();
        SqlCommand comm = new SqlCommand("Usp_GetCallCountByUserID", con);
        comm.CommandType = CommandType.StoredProcedure;
        comm.Parameters.Add("@UserID", SqlDbType.Int).Direction =
            ParameterDirection.Output;
        SqlDataReader reader;
        reader = comm.ExecuteReader();
        reader.Close();
        ViewBag.CountLog = comm.Parameters["@UserID"].Value.ToString();
        con.Close();

        var callCustomers = db.Registrations;
        return View(callCustomers.ToList());
    }

Body:
Edit: answer edited after clarification

If I'm right you would do something like this:

CREATE proc [Usp_GetCallCountByUserID]
  @UserId int
  @TotalCount int output
AS
BEGIN
  SELECT @TotalCount = COUNT(*) FROM Customer WHERE UserId = @UserId
END

Please modify calling c# code accordingly. You do not need the GROUP BY clause, if grouping by the same field you are filtering on.

Consideration: IMO a stored procedure is overkill for such a simple task, and does not give any sensible performance improvements, expecially if your application and DB server are always up (both will optimize the query execution, if repeated). When queries are so simple, I'd rather execute a CommandType.Text DbCommand:

conn.Open();
using (var cmd = conn.CreateCommand())
{
   cmd.CommandType = CommandType.Text;
   cmd.CommandText = "SELECT Count(*) FROM Customer where UserId = @UserId";
   cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = currentUserId;
   using (var reader = cmd.ExecuteReader())
   {
      reader.Read(); // Advance one record
      ViewBag.CountLog = reader.GetInt32(0);
   }
}

Finally, since you seem to be using some sort of ORM (Entity Framework?), why not just:

db.Customers.Count(c => c.UserId == currentUserId);

That is pretty much equivalent to the code above.


来源: stackexchange

问:
Firefox OS: How launch an APP in code
I want to open an APP when one Alarm is fired. I can fire alarms with Alarm API, but I don't know how I can open the APP when the alarm is fired. Now, when the alarm is fired the APP is opened but in background.

I have Firefox OS 1.1.

答:
You can launch any app, like this:

```<code>let request = navigator.mozApps.mgmt.getAll();

request.onsuccess = function() {
  let apps = request.result;
  apps.forEach(function iterateApp(app) {
    if (app.origin != "origin of the app you want to launch") return;
    app.launch();
  });
};

request.onerror = function() {
  console.log("Error: " + request.error.name);
};
</code>```

Here, 'navigator.mozApps.mgmt.getAll()' returns 'pendingGetAll' object. Inside onsuccess, pendingGetAll.result(here request.result) will be an array of App objects that contains all the apps installed in the current browser or KaiOS phone.

example of app origin: app://contacts.lic.com.

You will get it inside the manifest file of the app(manifest.webapp).

ContentLicense: CC BY-SA 3.0

Title: Firefox OS: How launch an APP in code

Body:
You can launch any app, like this:

let request = navigator.mozApps.mgmt.getAll();

request.onsuccess = function() {
  let apps = request.result;
  apps.forEach(function iterateApp(app) {
    if (app.origin != "origin of the app you want to launch") return;
    app.launch();
  });
};

request.onerror = function() {
  console.log("Error: " + request.error.name);
};

Here, 'navigator.mozApps.mgmt.getAll()' returns 'pendingGetAll' object. Inside onsuccess, pendingGetAll.result(here request.result) will be an array of App objects that contains all the apps installed in the current browser or KaiOS phone.

example of app origin: app://contacts.lic.com.

You will get it inside the manifest file of the app(manifest.webapp).

ContentLicense: CC BY-SA 4.0


问:
Failed gem install: gem require ruby-2.6.1 but the currently ruby-2.6.1

Show messages errors:

```<code>Required ruby-2.6.1 is not installed.
To install do: 'rvm install "ruby-2.6.1"'
</code>```

ruby -v

```<code>ruby 2.6.1p33 (2019-01-30 revision 66950) [x64-mingw32]
</code>```

rails -v

```<code>Rails 5.2.2
</code>```

答:
if you are using rbenv

see if you have it available in your list :

```<code>rbenv install --list | grep 2.6.1
</code>```

if not, fetch it

```<code>cd ~/.rbenv/plugins/ruby-build && git pull && cd -
</code>```

now if you try again

```<code>rbenv install -l | grep 2.6.1
</code>```

so just run the installation command:

```<code>rbenv install 2.6.1
</code>```

```<code>Downloading ruby-2.6.1.tar.bz2...  08:36:17
-> https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.1.tar.bz2
Installing ruby-2.6.1...
Installed ruby-2.6.1 to ~/.rbenv/versions/2.6.1
</code>```

now you can use it for global or local projects. if local :

```<code>rbenv local 2.6.1
</code>```

Body:
Show messages errors:

Required ruby-2.6.1 is not installed.
To install do: 'rvm install "ruby-2.6.1"'

ruby -v

ruby 2.6.1p33 (2019-01-30 revision 66950) [x64-mingw32]

rails -v

Rails 5.2.2

Body:
if you are using rbenv

see if you have it available in your list :

rbenv install --list | grep 2.6.1

if not, fetch it

cd ~/.rbenv/plugins/ruby-build && git pull && cd -

now if you try again

rbenv install -l | grep 2.6.1

so just run the installation command:

rbenv install 2.6.1

Downloading ruby-2.6.1.tar.bz2...  08:36:17
-> https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.1.tar.bz2
Installing ruby-2.6.1...
Installed ruby-2.6.1 to ~/.rbenv/versions/2.6.1

now you can use it for global or local projects. if local :

rbenv local 2.6.1


问:
posting an array using JQuery .post()
so I am rather new to the whole .post() experience with jquery.

I have only experience POSTing input values so far. What I want to do is POST an array.

which is a standard array of a list of numbers. The end goal being: performing a query with these values.

Could somebody explain to me very basically how using JQuery .post() I can post my array?

many thanks,

答:
I guess, without going into great detail, the answer on you question is called JSON.

The process is easy:

Backend (PHP) Array -> encode as JSON
  string -> send that JSON string to the
  browser -> decode the JSON string as
  Javascript Array

Title: posting an array using JQuery .post()


问:
Why this code works well in MySQL but not in SQL Server?
This is a question in Leetcode: https://leetcode.com/problems/delete-duplicate-emails/solution/

Basically the question asks to delete duplicate emails and keep the one that has the minumal index.

My code is the following one, and I firstly ran it in SQL Server mode, and it shows "Internal Error". But it has passed in MySQL mode. Why does this happen? Are there any syntax differences between them shown in this case? Thanks.

```<code>delete from Person
where Id not in (
select temp.minimum from
(select min(Id) as minimum from Person group by Email) as temp
);
</code>```

答:
I tried this on sql server express 10.50.6560 and it seems it works...

```<code>CREATE TABLE PERSON
(
  ID INT NOT NULL
, EMAIL VARCHAR(1000)
)

ALTER TABLE PERSON
ADD CONSTRAINT PK_PERSON
PRIMARY KEY (ID)

INSERT INTO PERSON VALUES(1, 'AAAAA')
INSERT INTO PERSON VALUES(2, 'AAAAA')
INSERT INTO PERSON VALUES(3, 'BBBBB')

DROP TABLE PERSON
</code>```

--Your query

```<code>delete from Person
where Id not in (
select temp.minimum from
(select min(Id) as minimum from Person group by Email) as temp
);
</code>```

It deletes one row...

Hope it helps

Body:
This is a question in Leetcode: https://leetcode.com/problems/delete-duplicate-emails/solution/

Basically the question asks to delete duplicate emails and keep the one that has the minumal index.

My code is the following one, and I firstly ran it in SQL Server mode, and it shows "Internal Error". But it has passed in MySQL mode. Why does this happen? Are there any syntax differences between them shown in this case? Thanks.

delete from Person
where Id not in (
select temp.minimum from
(select min(Id) as minimum from Person group by Email) as temp
);

Body:
I tried this on sql server express 10.50.6560 and it seems it works...

CREATE TABLE PERSON
(
  ID INT NOT NULL
, EMAIL VARCHAR(1000)
)

ALTER TABLE PERSON
ADD CONSTRAINT PK_PERSON
PRIMARY KEY (ID)

INSERT INTO PERSON VALUES(1, 'AAAAA')
INSERT INTO PERSON VALUES(2, 'AAAAA')
INSERT INTO PERSON VALUES(3, 'BBBBB')

DROP TABLE PERSON

--Your query

delete from Person
where Id not in (
select temp.minimum from
(select min(Id) as minimum from Person group by Email) as temp
);

It deletes one row...

Hope it helps


问:
Run python script multiple times as a background process with different configuration
I used php to run python script on Linux via web after running and I get process ID

```<code><!DOCTYPE html>
<html>
   <body>
      <?php
      echo 'Starting the mapping process';
      echo exec('nohup python cloudemir.py '.$_GET[message].' > /dev/null 2>&1 & echo $! &');
     ?>
  </body>
</html>
</code>```

which is then used to kill the process when I don't need it which works fine

```<code><!DOCTYPE html>
<html>
    <body>
        <?php
        $pid=$_GET['pid'];
        echo exec("kill -9 $pid");
        ?>
    </body>
</html>
</code>```

The python script I used is just publishing one message via MQTT every second. The problem is that I can't change the message content.

If the message is Hi, and I run this process, it says "Hi", "Hi"... every second. If I change python script message to Hi2, and run it again I get new process id and new message is Hi2 every second and there is no Hi message any more.

I need it to run separately and to get both messages, and when needed to kill one of them. I need it to be able to run unlimited number of instances of that python sctipt with different configuiration, I don't need to build new scripts.

domain/run.php?message=Hi

domain/run.php?message=Hi2

This should print Hi, Hi2, Hi, Hi2

domain/run.php?message=Hi

domain/run.php?message=Hi2

domain/run.php?message=Hi3

This should print Hi, Hi2, Hi3, Hi, Hi2, Hi3

In both cases it prints only last message

I even tried the same without php, but calling the script from another python script with

```<code>proc = subprocess.Popen("nohup python cloudemir.py "+content+" > /dev/null 2>&1 &", shell=True)
</code>```

But it remains the same, last call overwrites the previous

答:
You should use sys.argv. As an example of the file cloudemir.py:

import sys

print(sys.argv[0])
```

<p>And then you can call it with:</p>

```python cloudemir.py Hi # First time
python cloudemir.py Hi2 # Second time
```

This way the name after cloudemir.py will be inputed as a param to the python program.

Body:
I used php to run python script on Linux via web after running and I get process ID

<!DOCTYPE html>

      <?php
      echo 'Starting the mapping process';
      echo exec('nohup python cloudemir.py '.$_GET[message].' > /dev/null 2>&1 & echo $! &');
     ?>

which is then used to kill the process when I don't need it which works fine

<!DOCTYPE html>

        <?php
        $pid=$_GET['pid'];
        echo exec("kill -9 $pid");
        ?>

The python script I used is just publishing one message via MQTT every second. The problem is that I can't change the message content.

If the message is Hi, and I run this process, it says "Hi", "Hi"... every second. If I change python script message to Hi2, and run it again I get new process id and new message is Hi2 every second and there is no Hi message any more.

I need it to run separately and to get both messages, and when needed to kill one of them. I need it to be able to run unlimited number of instances of that python sctipt with different configuiration, I don't need to build new scripts.

domain/run.php?message=Hi

domain/run.php?message=Hi2

This should print Hi, Hi2, Hi, Hi2

domain/run.php?message=Hi

domain/run.php?message=Hi2

domain/run.php?message=Hi3

This should print Hi, Hi2, Hi3, Hi, Hi2, Hi3

In both cases it prints only last message

I even tried the same without php, but calling the script from another python script with

proc = subprocess.Popen("nohup python cloudemir.py "+content+" > /dev/null 2>&1 &", shell=True)

But it remains the same, last call overwrites the previous

Body:
You should use sys.argv. As an example of the file cloudemir.py:

import sys

print(sys.argv[0])

And then you can call it with:

python cloudemir.py Hi # First time
python cloudemir.py Hi2 # Second time

This way the name after cloudemir.py will be inputed as a param to the python program.


问:
Scrolling issues with webview
Tried too many times but failed , Here is the code that I have tried

```<code><android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:fillViewport="true">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mainweb">
</WebView>

 </android.support.v4.widget.NestedScrollView>
</code>```

On launching the application nested scroll view is working fine but sometimes webview doesn't scroll.

I inserted webview inside nested scroll view to hide toolbar in fragment activities

Any help will be highly appreciate as I am stuck on this problem from past 7 months

答:
You need to add this dependency in build.gradle file

```<code>implementation 'com.github.ksoichiro:android-observablescrollview:1.6.0'
</code>```

In your java class

```<code>ObservableWebView webView;

webView.setScrollViewCallbacks(new ObservableScrollViewCallbacks() {
        @Override
        public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {

        }

        @Override
        public void onDownMotionEvent() {

        }

        @Override
        public void onUpOrCancelMotionEvent(ScrollState scrollState) {

            if (scrollState == ScrollState.UP) {

                ((AppCompatActivity)getActivity()).getSupportActionBar().hide();
                // hide your action bar
            } else if (scrollState == ScrollState.DOWN) {
                ((AppCompatActivity)getActivity()).getSupportActionBar().show();
                // show your action bar
            }

        }
    });
</code>```

Title: Scrolling issues with webview

Body:
Tried too many times but failed , Here is the code that I have tried

<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:fillViewport="true">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mainweb">
</WebView>

 </android.support.v4.widget.NestedScrollView>

On launching the application nested scroll view is working fine but sometimes webview doesn't scroll.

I inserted webview inside nested scroll view to hide toolbar in fragment activities

Any help will be highly appreciate as I am stuck on this problem from past 7 months

Body:
You need to add this dependency in build.gradle file

implementation 'com.github.ksoichiro:android-observablescrollview:1.6.0'

In your java class

ObservableWebView webView;

webView.setScrollViewCallbacks(new ObservableScrollViewCallbacks() {
        @Override
        public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {

        }

        @Override
        public void onDownMotionEvent() {

        }

        @Override
        public void onUpOrCancelMotionEvent(ScrollState scrollState) {

            if (scrollState == ScrollState.UP) {

                ((AppCompatActivity)getActivity()).getSupportActionBar().hide();
                // hide your action bar
            } else if (scrollState == ScrollState.DOWN) {
                ((AppCompatActivity)getActivity()).getSupportActionBar().show();
                // show your action bar
            }

        }
    });


问:
Convert UNIX time string to date in R
I have the following UNIX time string:

"1575824800.169"

If you convert this time you will get: 12/08/2019 17:06
on an online unix converter.

However when trying to convert this in R using the following code:

```<code>as.POSIXct("1575824800.169", format='%d/%m/%Y %H:%M', origin = "1970-01-01")
</code>```

I am returned with the value NA

i'm struggling to see why the above code does not work - i have looked into different answers on here, but have not found one where the unix time string has 3 digits after the period (dot) in the string. Maybe this is the problem?

答:
You don't have a string encoding a date (as implied by using the format argument of as.POSIXct) but a number. If we re-cast the string as a numeric and get rid of the format argument we get the expected result (although we might need to use the tz argument to specify a timezone)

```<code>as.POSIXct(1575824800.169, origin = "1970-01-01")
</code>```

Returns:

```<code>[1] "2019-12-08 18:06:40 CET"
</code>```

Edit:

Adding timezone argument

```<code>as.POSIXct(1575824800.169, origin = "1970-01-01", tz = "UCT")
</code>```

Returns:

```<code>[1] "2019-12-08 17:06:40 UTC"
</code>```

Edit 2:

Regarding converting the string to numeric with as.numeric: As @IceCreamToucan pointed out, it does not matter. Only the "printed" value changes, the internal representation stays the same and therefore the result is still correct

```<code>as.POSIXct(as.numeric("1575824800.169"), origin = "1970-01-01", tz = "UCT")
</code>```

Returns the same:

```<code>[1] "2019-12-08 17:06:40 UTC"
</code>```

Title: Convert UNIX time string to date in R

Body:
I have the following UNIX time string:

"1575824800.169"

If you convert this time you will get: 12/08/2019 17:06
on an online unix converter.

However when trying to convert this in R using the following code:

as.POSIXct("1575824800.169", format='%d/%m/%Y %H:%M', origin = "1970-01-01")

I am returned with the value NA

i'm struggling to see why the above code does not work - i have looked into different answers on here, but have not found one where the unix time string has 3 digits after the period (dot) in the string. Maybe this is the problem?

Body:
You don't have a string encoding a date (as implied by using the format argument of as.POSIXct) but a number. If we re-cast the string as a numeric and get rid of the format argument we get the expected result (although we might need to use the tz argument to specify a timezone)

as.POSIXct(1575824800.169, origin = "1970-01-01")

Returns:

[1] "2019-12-08 18:06:40 CET"

Edit:

Adding timezone argument

as.POSIXct(1575824800.169, origin = "1970-01-01", tz = "UCT")

Returns:

[1] "2019-12-08 17:06:40 UTC"

Edit 2:

Regarding converting the string to numeric with as.numeric: As @IceCreamToucan pointed out, it does not matter. Only the "printed" value changes, the internal representation stays the same and therefore the result is still correct

as.POSIXct(as.numeric("1575824800.169"), origin = "1970-01-01", tz = "UCT")

Returns the same:

[1] "2019-12-08 17:06:40 UTC"


问:
How to filter and append arrays
I have a code that I am using to try and filter out arrays that are missing values as seen here:

```<code>from astropy.table import Table
import numpy as np

data = '/home/myname/data.fits'
data = Table.read(data, format="fits")

ID = np.array(data['id'])
ID.astype(str)

redshift = np.array(data['z'])
redshift.astype(float)

radius = np.array(data['r'])
radius.astype(float)

mag = np.array(data['M'])
mag.astype(float)

def stack(array1, array2, array3, array4):
    #stacks multiple arrays to have corresponding values next to eachother
    stacked_array = [(array1[i], array2[i], array3[i], array4[i]) for i in range(0, array1.size)]
    stacked_array = np.array(stacked_array)
    return(stacked_array)

stacked = stack(ID, redshift, radius, mag)

filtered_array = np.array([])

for i in stacked:
    if not i.any == 'nan':
        np.insert(filtered_array, i[0], axis=0)
</code>```

The last for loop is where i'm having difficulty. I want to insert the rows from my stacked array into my filtered array if it has all of the information (some rows are missing redshift, others are missing magnitude etc...). How would I be able to loop over my stacked array and filter out all of the rows that have all 4 values I want? I keep getting this error currently.

```<code>TypeError: _insert_dispatcher() missing 1 required positional argument: 'values'
</code>```

答:
So something like this?

```<code>a=[[1,2,3,4],[1,"nan",2,3]]
b=[i for i in a if not any(j=='nan' for j in i)]
</code>```

which prints [[1, 2, 3, 4]].

Title: How to filter and append arrays

Body:
I have a code that I am using to try and filter out arrays that are missing values as seen here:

from astropy.table import Table
import numpy as np

data = '/home/myname/data.fits'
data = Table.read(data, format="fits")

ID = np.array(data['id'])
ID.astype(str)

redshift = np.array(data['z'])
redshift.astype(float)

radius = np.array(data['r'])
radius.astype(float)

mag = np.array(data['M'])
mag.astype(float)

def stack(array1, array2, array3, array4):
    #stacks multiple arrays to have corresponding values next to eachother
    stacked_array = [(array1[i], array2[i], array3[i], array4[i]) for i in range(0, array1.size)]
    stacked_array = np.array(stacked_array)
    return(stacked_array)

stacked = stack(ID, redshift, radius, mag)

filtered_array = np.array([])

for i in stacked:
    if not i.any == 'nan':
        np.insert(filtered_array, i[0], axis=0)

The last for loop is where i'm having difficulty. I want to insert the rows from my stacked array into my filtered array if it has all of the information (some rows are missing redshift, others are missing magnitude etc...). How would I be able to loop over my stacked array and filter out all of the rows that have all 4 values I want? I keep getting this error currently.

TypeError: _insert_dispatcher() missing 1 required positional argument: 'values'

Body:
So something like this?

a=[[1,2,3,4],[1,"nan",2,3]]
b=[i for i in a if not any(j=='nan' for j in i)]

which prints [[1, 2, 3, 4]].


问:
Mongodb C# driver Perform string contains query on a property in an embedded document
I have the below simplified model:

```<code>public class Entity
{
    public Guid Id { get; set; }

    public IList<ComponentProperty> Components { get; private set; }

}

public class ComponentProperty
{
    public string PropertyName { get; set; }

    public string Value { get; set; }

}
</code>```

I want to be able to find any entity whose property value string contains the search string, and to that end I wrote the following query, based on recommendation here, which implicitly uses Regex:

```<code>var query = _context.GetCollection<Entity>()
                        .AsQueryable()
                        .Where(t => t.Components.Any(c => c.Value.ToLower() == queryOptions.Filter));
</code>```

This query produces the following json, and (incorrectly) returns 0 rows:

```<code>aggregate([{ "$match" : { "Components" : { "$elemMatch" : { "Value" : /^'green'$/i} } } }])
</code>```

However, the hand-crafted query that produces the correct results is the below:

```<code>aggregate([{ "$match" : { "Components" : { "$elemMatch" : { "Value" :  {$regex: '.*green.*' } } } } }])
</code>```

Perhaps, there is something I have overlooked in my approach using the c# driver, and any pointers will be much appreciated.

答:
change your where clause to this:

.Where(e => e.Components.Any(c => c.Value.ToLower().Contains(queryOptions.Filter)))
```

<p>which produces this aggregation:</p>

<pre class="lang-java prettyprint-override"><code>db.Entity.aggregate([
    {
        "$match": {
            "Components.Value": /green/is
        }
    }
])
</code>```

here's a test program:

using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Collections.Generic;
using System.Linq;

namespace StackOverFlow
{
    public class Ntity : Entity
    {
        public IList<ComponentProperty> Components { get; set; }
    }

    public class ComponentProperty
    {
        public string PropertyName { get; set; }

        public string Value { get; set; }

    }

    public static class Program
    {
        private static void Main()
        {
            new DB("test");

            new Ntity
            {
                Components = new List<ComponentProperty> {
                    new ComponentProperty {
                        PropertyName = "test",
                        Value = "the RED color" }
                }
            }.Save();

            new Ntity
            {
                Components = new List<ComponentProperty> {
                    new ComponentProperty {
                        PropertyName = "test",
                        Value = "the Green color" }
                }
            }.Save();

            var result = DB.Queryable<Ntity>()
                           .Where(e => e.Components.Any(c => c.Value.ToLower().Contains("green")))
                           .ToList();
        }
    }
}```

Body:
I have the below simplified model:

public class Entity
{
    public Guid Id { get; set; }

    public IList<ComponentProperty> Components { get; private set; }

}

public class ComponentProperty
{
    public string PropertyName { get; set; }

    public string Value { get; set; }

}

I want to be able to find any entity whose property value string contains the search string, and to that end I wrote the following query, based on recommendation here, which implicitly uses Regex:

var query = _context.GetCollection<Entity>()
                        .AsQueryable()
                        .Where(t => t.Components.Any(c => c.Value.ToLower() == queryOptions.Filter));

This query produces the following json, and (incorrectly) returns 0 rows:

aggregate([{ "$match" : { "Components" : { "$elemMatch" : { "Value" : /^'green'$/i} } } }])

However, the hand-crafted query that produces the correct results is the below:

aggregate([{ "$match" : { "Components" : { "$elemMatch" : { "Value" :  {$regex: '.*green.*' } } } } }])

Perhaps, there is something I have overlooked in my approach using the c# driver, and any pointers will be much appreciated.

Body:
change your where clause to this:

.Where(e => e.Components.Any(c => c.Value.ToLower().Contains(queryOptions.Filter)))

which produces this aggregation:

db.Entity.aggregate([
    {
        "$match": {
            "Components.Value": /green/is
        }
    }
])

here's a test program:

using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Collections.Generic;
using System.Linq;

namespace StackOverFlow
{
    public class Ntity : Entity
    {
        public IList<ComponentProperty> Components { get; set; }
    }

    public class ComponentProperty
    {
        public string PropertyName { get; set; }

        public string Value { get; set; }

    }

    public static class Program
    {
        private static void Main()
        {
            new DB("test");

            new Ntity
            {
                Components = new List<ComponentProperty> {
                    new ComponentProperty {
                        PropertyName = "test",
                        Value = "the RED color" }
                }
            }.Save();

            new Ntity
            {
                Components = new List<ComponentProperty> {
                    new ComponentProperty {
                        PropertyName = "test",
                        Value = "the Green color" }
                }
            }.Save();

            var result = DB.Queryable<Ntity>()
                           .Where(e => e.Components.Any(c => c.Value.ToLower().Contains("green")))
                           .ToList();
        }
    }
}


问:
Default path of program installed per user on Windows
I'm creating WiX installer for my WPF application on Windows. My goal is to allow users without admin rights to install this program, but in the installer, the default path is currently set to Program Files which causes an Access Denied error.

What is the best practice, what should be the default installation path in per-user installation?. Is %LOCALAPPDATA% OK?

答:
All your Component or ComponentGroup belongs to a Directory

Dictionary.wxs

      <Directory Id="LocalAppDataFolder">
        <Directory Id="LocalAppDataManufacturerFolder" Name="$(var.Manufacturer)">
          <Directory Id="LocalAppDataProductDatabaseFolder" Name="$(var.ProductName)" />
        </Directory>
      </Directory>

      <Directory Id="AppDataFolder">
        <Directory Id="AppDataManufacturerFolder" Name="$(var.Manufacturer)">
          <Directory Id="AppDataProductDatabaseFolder" Name="$(var.ProductName)" />
        </Directory>
      </Directory>
```

<p>Product.wxs</p>

<pre class="lang-xml prettyprint-override"><code><?include .\Dictionary.wxi ?>
...
<ComponentGroup Id="MyCoreComponent" Directory="AppDataProductDatabaseFolder">
...
</code>```

Manufacturer and Productname are just variables you can use your hard coded strings as well

Body:
All your Component or ComponentGroup belongs to a Directory

Dictionary.wxs

      <Directory Id="LocalAppDataFolder">
        <Directory Id="LocalAppDataManufacturerFolder" Name="$(var.Manufacturer)">
          <Directory Id="LocalAppDataProductDatabaseFolder" Name="$(var.ProductName)" />
        </Directory>
      </Directory>

      <Directory Id="AppDataFolder">
        <Directory Id="AppDataManufacturerFolder" Name="$(var.Manufacturer)">
          <Directory Id="AppDataProductDatabaseFolder" Name="$(var.ProductName)" />
        </Directory>
      </Directory>

Product.wxs

<?include .\Dictionary.wxi ?>
...
<ComponentGroup Id="MyCoreComponent" Directory="AppDataProductDatabaseFolder">
...

Manufacturer and Productname are just variables you can use your hard coded strings as well


问:
Executing a Process on Windows using Remote SSH Connection
Hi i am trying to execute a process on a remote windows machine using SSH. I used Renci.SshNet to connect to the remote windows 10 machine, uploaded an executable (whcih works Fine i.e open in fore ground when executed by a user on the machine) however, when i try to execute it over SSH connection it runs in background with no intilization. I dont know about this strange behavior. This is the sample code which i used to run the remote executeable.   </p>

```<code>    public void SshCommandExecutor(string MachineIP, string MachineUserID, string MachineUserPassword, string command)
    {
        SshClient cSSH = new SshClient(MachineIP, 22, MachineUserID, MachineUserPassword);
        cSSH.Connect();
        SshCommand x = cSSH.RunCommand(command);
        cSSH.Disconnect();
        cSSH.Dispose();
        log(x.Result.ToString());

    }
</code>```

答:
I figured it out:

So what i did was i uplaoded the executable file using ssh then i initiated a vnc session on the remote machine and using vncdotool* exeuted the remote process via command line

*https://pypi.org/project/vncdotool/

Body:
Hi i am trying to execute a process on a remote windows machine using SSH. I used Renci.SshNet to connect to the remote windows 10 machine, uploaded an executable (whcih works Fine i.e open in fore ground when executed by a user on the machine) however, when i try to execute it over SSH connection it runs in background with no intilization. I dont know about this strange behavior. This is the sample code which i used to run the remote executeable.

    public void SshCommandExecutor(string MachineIP, string MachineUserID, string MachineUserPassword, string command)
    {
        SshClient cSSH = new SshClient(MachineIP, 22, MachineUserID, MachineUserPassword);
        cSSH.Connect();
        SshCommand x = cSSH.RunCommand(command);
        cSSH.Disconnect();
        cSSH.Dispose();
        log(x.Result.ToString());

    }


问:
Laravel - How to Pass Parameter to return redirect
In my Laravel-5.8, I have:

```<code>public function manager_employee_goal_list($id)
{
    $goal = AppraisalGoal::findOrFail($id);
    $goaldetails = AppraisalGoalDetail::where('appraisal_goal_id', $id)->get();

    return view('appraisal.appraisal_goals.manager_employee_goal_list')
        ->with('goal', $goal)
        ->with('goaldetails', $goaldetails);
}

public function manager_employee_goal_approve(Request $request, $id)
{
    $goal = AppraisalGoal::find($id);
    $goal->is_approved = 3;
    $goal->line_manager_comment = $request->line_manager_comment;
    $goal->save();

    Session::flash('success', 'Goal is approved');

    return redirect()->route('appraisal.appraisal_goals.manager_employee_goal_list');
}
</code>```

view : manager_employee_goal_list

```<code><a class="btn btn-xs btn-info" data-toggle="modal" data-target="#approve{{ $goal->id }}" data-original-title="Approve">
   Approve
</a>

<div class="modal fade" id="approve{{ $goal->id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="{route('appraisal.appraisal_goals.manager_employee_goal_approve',['id'=>$goal->id])}}" method="post">
                {{ csrf_field() }}
                <div class="modal-header">
                    Approve Goal
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <label class="control-label">Comment</label>
                        <textarea rows="2" name="line_manager_comment" class="form-control" placeholder="Enter Comment here" value="{{old('line_manager_comment')}}" required data-validation-required-message="This field is required"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button  type="submit" class="btn btn-success btn-ok">Approve Goal</button>
                </div>
            </form>
        </div>
    </div>
</div>
</code>```

route/web.php

```<code>Route::get('appraisal_goals/manager_employee_goal_list/{id?}', 'Appraisal\AppraisalGoalsController@manager_employee_goal_list')->name('appraisal.appraisal_goals.manager_employee_goal_list');
Route::post('appraisal_goals/manager_employee_goal_approve/{id?}', 'Appraisal\AppraisalGoalsController@manager_employee_goal_approve')->name('appraisal.appraisal_goals.manager_employee_goal_approve');
</code>```

When I submit on the modal form, it saves but couldn't redirect to:

return redirect()->route('appraisal.appraisal_goals.manager_employee_goal_list');

It displays this error

Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal_list(), 0 passed and exactly 1 expected

How do I resolve it?

Thanks

答:
manager_employee_goal_list method expects an ID, all you have to do is to pass that ID, like so:

```<code>return redirect()->route(
        'appraisal.appraisal_goals.manager_employee_goal_list',
        ['id' => $id]
);
</code>```

Also I suggest you to either remove question mark after id in your defined route, or update arguments from your method by making them nullable

```<code>public function manager_employee_goal_list($id = null)
</code>```

and of course you have to adjust code too

Body:
In my Laravel-5.8, I have:

public function manager_employee_goal_list($id)
{
    $goal = AppraisalGoal::findOrFail($id);
    $goaldetails = AppraisalGoalDetail::where('appraisal_goal_id', $id)->get();

    return view('appraisal.appraisal_goals.manager_employee_goal_list')
        ->with('goal', $goal)
        ->with('goaldetails', $goaldetails);
}

public function manager_employee_goal_approve(Request $request, $id)
{
    $goal = AppraisalGoal::find($id);
    $goal->is_approved = 3;
    $goal->line_manager_comment = $request->line_manager_comment;
    $goal->save();

    Session::flash('success', 'Goal is approved');

    return redirect()->route('appraisal.appraisal_goals.manager_employee_goal_list');
}

view : manager_employee_goal_list

id }}" data-original-title="Approve">
   Approve

id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

            <form action="{route('appraisal.appraisal_goals.manager_employee_goal_approve',['id'=>$goal->id])}}" method="post">
                {{ csrf_field() }}

                    Approve Goal

                        Comment
                        <textarea rows="2" name="line_manager_comment" class="form-control" placeholder="Enter Comment here" value="{{old('line_manager_comment')}}" required data-validation-required-message="This field is required"></textarea>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button  type="submit" class="btn btn-success btn-ok">Approve Goal</button>

            </form>

route/web.php

Route::get('appraisal_goals/manager_employee_goal_list/{id?}', 'Appraisal\AppraisalGoalsController@manager_employee_goal_list')->name('appraisal.appraisal_goals.manager_employee_goal_list');
Route::post('appraisal_goals/manager_employee_goal_approve/{id?}', 'Appraisal\AppraisalGoalsController@manager_employee_goal_approve')->name('appraisal.appraisal_goals.manager_employee_goal_approve');

When I submit on the modal form, it saves but couldn't redirect to:

return redirect()->route('appraisal.appraisal_goals.manager_employee_goal_list');

It displays this error

Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal_list(), 0 passed and exactly 1 expected

How do I resolve it?

Thanks

Body:
manager_employee_goal_list method expects an ID, all you have to do is to pass that ID, like so:

return redirect()->route(
        'appraisal.appraisal_goals.manager_employee_goal_list',
        ['id' => $id]
);

Also I suggest you to either remove question mark after id in your defined route, or update arguments from your method by making them nullable

public function manager_employee_goal_list($id = null)

and of course you have to adjust code too


问:
Is it possible to give index to a date and then use jumpToPage to that date?
So this is what I want basicly:

I want every day to be and index so 2020 jan. is 31 days + feb. 21 = 52. When I click on feb 21 I want to jump to page with index 52. Right now Its jump to 52 because of this code:

```<code>controller.jumpToPage(52);
</code>```

答:
You can use DateTime.difference() :

final firstDate = DateTime(2020, 1, 1);
final secondDate = DateTime(2020, 2, 21);
final index = secondDate.difference(firstDate).inDays;
controller.jumpToPage(index) // index : 51
```

Body:
So this is what I want basicly:

I want every day to be and index so 2020 jan. is 31 days + feb. 21 = 52. When I click on feb 21 I want to jump to page with index 52. Right now Its jump to 52 because of this code:

controller.jumpToPage(52);


问:
Can't resolve Android databinding class
While using data binding , I am not able to get class MainActivityBinding  as per Data Binding Guide

My layout name is activity_main.xml.
I am also see Android - DataBinding - How and when the Binding classes will be generated? but it can't help me.

答:
I recently installed android studio 3.5.3 and this issue rised so what i did is.

```<code>1) Clean Project
2) Update Gradle (as notification was coming)
3) Rebuild project
</code>```

hope this helps.

Title: Can't resolve Android databinding class

Body:
I recently installed android studio 3.5.3 and this issue rised so what i did is.

1) Clean Project
2) Update Gradle (as notification was coming)
3) Rebuild project

hope this helps.


问:
setFullScreenIntent does not work second time
I have an application in android and I want to bring an activity to foreground in some cases. I use NotificationManager for this. Here is my code. The problem is, activity is brought to front successfully at first time, but then it does not. Also, this code is run from service.</p>

```<code>Intent notificationIntent = new Intent(context, MainActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

            NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentIntent(contentIntent)
                        .setContentTitle("Bring me front!")
                        .setContentText("Bring me!!! BRING!!!")
                        .setFullScreenIntent(contentIntent, true);

            NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(0, mBuilder.build());
</code>```

答:
I had a similar problem. In my case I missed two things:

USE_FULL_SCREEN_INTENT permission in Manifest.

A password or graphic pattern must be set on your phone settings. UI must be NOT available to the user immediately after you press the unlock button. Then fullscreen activity shows.

Body:
I have an application in android and I want to bring an activity to foreground in some cases. I use NotificationManager for this. Here is my code. The problem is, activity is brought to front successfully at first time, but then it does not. Also, this code is run from service.

Intent notificationIntent = new Intent(context, MainActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

            NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentIntent(contentIntent)
                        .setContentTitle("Bring me front!")
                        .setContentText("Bring me!!! BRING!!!")
                        .setFullScreenIntent(contentIntent, true);

            NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(0, mBuilder.build());


问:
Transpose a dataframe in case of rows contain two values for the same variable in R
I'm dealing with a dataframe that contains a variable named "Marker" which shows two values all the samples I collected.
The dataframe is, for instance, as follows:

```<code>Sample.File Sample.Name Marker value
1            a         a_1    xxx    16
2            a         a_1    xxx    18
3            a         a_1    yyy    16
4            a         a_1    yyy    20
5            a         a_1    zzz     9
6            a         a_1    zzz    13
7            b         b_1    xxx    10
8            b         b_1    xxx    10
9            b         b_1    yyy     6
10           b         b_1    yyy    12
11           b         b_1    zzz    14
12           b         b_1    zzz    14
</code>```

which is provided by the following code:

```<code>data <- data.frame(
   Sample.File = as.factor(c("a", "a", "a", "a", "a", "a", "b", "b", "b", "b",
                             "b", "b")),
   Sample.Name = as.factor(c("a_1", "a_1", "a_1", "a_1", "a_1", "a_1", "b_1",
                             "b_1", "b_1", "b_1", "b_1", "b_1")),
        Marker = as.factor(c("xxx", "xxx", "yyy", "yyy", "zzz", "zzz", "xxx",
                             "xxx", "yyy", "yyy", "zzz", "zzz")),
   value = c(16L, 18L, 16L, 20L, 9L, 13L, 10L, 10L, 6L, 12L, 14L, 14L)
)
</code>```

The new dataframe I'd like to work with is should be achieved by transposing the current data, but maintaining the columns Sample.File and Sample.Name for all the collected samples. Furthermore, I'd like to obtain new variables to be labelled as follows (e.g. xxx & xxx.1, yyy & yyy.1, zzz & zzz.1) for the column labelled as "value".

The table I'd like to achieve looks like the following:

```<code>  Sample.File Sample.Name xxx xxx.1 yyy yyy.1 zzz zzz.1
1           a         a_1  16    18  16    20   9    13
2           b         b_1  10    10   6    12  14    14
</code>```

I'd like to use a code without writing the name of the labels reported into "Marker" column (since I could obtain up to 100 different labels).
I tried to use the following code but I couldn't achieve my goal:

I tried to use the following code but I couldn't achieve my goal:

```<code>library(dplyr)
library(tidyr)
data %>%
  gather(Sample.File, Sample.Name) %>%
  spread(value)

Error: `var` must evaluate to a single number or a column name, not a double vector
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
attributes are not identical across measure variables;
they will be dropped
</code>```

I'd be very grateful if anybody could attend to this matter!

答:
Here is one way to do it. We can create an ID for each Marker and then create a column. After that, we can convert it to wide format.

```<code>library(dplyr)
library(tidyr)

data2 <- data %>%
  group_by_at(vars(-value)) %>%
  mutate(N = row_number() - 1) %>%
  unite(col = "Marker", Marker, N, sep = ".") %>%
  pivot_wider(names_from = "Marker", values_from = "value") %>%
  ungroup()
data2
# # A tibble: 2 x 8
#   Sample.File Sample.Name xxx.0 xxx.1 yyy.0 yyy.1 zzz.0 zzz.1
#   <fct>       <fct>       <int> <int> <int> <int> <int> <int>
# 1 a           a_1            16    18    16    20     9    13
# 2 b           b_1            10    10     6    12    14    14
</code>```

Body:
I'm dealing with a dataframe that contains a variable named "Marker" which shows two values all the samples I collected.
The dataframe is, for instance, as follows:

Sample.File Sample.Name Marker value
1            a         a_1    xxx    16
2            a         a_1    xxx    18
3            a         a_1    yyy    16
4            a         a_1    yyy    20
5            a         a_1    zzz     9
6            a         a_1    zzz    13
7            b         b_1    xxx    10
8            b         b_1    xxx    10
9            b         b_1    yyy     6
10           b         b_1    yyy    12
11           b         b_1    zzz    14
12           b         b_1    zzz    14

which is provided by the following code:

data <- data.frame(
   Sample.File = as.factor(c("a", "a", "a", "a", "a", "a", "b", "b", "b", "b",
                             "b", "b")),
   Sample.Name = as.factor(c("a_1", "a_1", "a_1", "a_1", "a_1", "a_1", "b_1",
                             "b_1", "b_1", "b_1", "b_1", "b_1")),
        Marker = as.factor(c("xxx", "xxx", "yyy", "yyy", "zzz", "zzz", "xxx",
                             "xxx", "yyy", "yyy", "zzz", "zzz")),
   value = c(16L, 18L, 16L, 20L, 9L, 13L, 10L, 10L, 6L, 12L, 14L, 14L)
)

The new dataframe I'd like to work with is should be achieved by transposing the current data, but maintaining the columns Sample.File and Sample.Name for all the collected samples. Furthermore, I'd like to obtain new variables to be labelled as follows (e.g. xxx & xxx.1, yyy & yyy.1, zzz & zzz.1) for the column labelled as "value".

The table I'd like to achieve looks like the following:

  Sample.File Sample.Name xxx xxx.1 yyy yyy.1 zzz zzz.1
1           a         a_1  16    18  16    20   9    13
2           b         b_1  10    10   6    12  14    14

I'd like to use a code without writing the name of the labels reported into "Marker" column (since I could obtain up to 100 different labels).
I tried to use the following code but I couldn't achieve my goal:

I tried to use the following code but I couldn't achieve my goal:

library(dplyr)
library(tidyr)
data %>%
  gather(Sample.File, Sample.Name) %>%
  spread(value)

Error: `var` must evaluate to a single number or a column name, not a double vector
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
attributes are not identical across measure variables;
they will be dropped

I'd be very grateful if anybody could attend to this matter!

Body:
Here is one way to do it. We can create an ID for each Marker and then create a column. After that, we can convert it to wide format.

library(dplyr)
library(tidyr)

data2 <- data %>%
  group_by_at(vars(-value)) %>%
  mutate(N = row_number() - 1) %>%
  unite(col = "Marker", Marker, N, sep = ".") %>%
  pivot_wider(names_from = "Marker", values_from = "value") %>%
  ungroup()
data2
# # A tibble: 2 x 8
#   Sample.File Sample.Name xxx.0 xxx.1 yyy.0 yyy.1 zzz.0 zzz.1
#   <fct>       <fct>       <int> <int> <int> <int> <int> <int>
# 1 a           a_1            16    18    16    20     9    13
# 2 b           b_1            10    10     6    12    14    14


问:
how to record screen in high quality
i am creating a screen recorder for desktop in python. and i have already completed the coding part but when i record the screen why it is not recording in high defination.
problem.........
1> i want to record the screen in high quality what should i do.
2> i am also trying to capute my cursor with the help on cv2.circle() but i want to create the circle with less opacity or more transparent

my code

```<code>import cv2
import numpy as np
import pyautogui
import datetime
import win32api

date=datetime.datetime.now()

SCREEN_SIZE = (960,540) #std res 1366, 768
framerate=12
# define the codec
fourcc = cv2.VideoWriter_fourcc(*'XVID')
filename='E:/project/videos/rec_%s%s%s%s%s%s.avi' %(date.year,date.month,date.day,date.hour,date.minute,date.second)

out = cv2.VideoWriter(filename, fourcc,framerate, SCREEN_SIZE)

while True:

    img = pyautogui.screenshot()

    frame = np.array(img)

    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    _xs,_ys = win32api.GetCursorPos()
    image=cv2.circle(frame,(_xs,_ys),20,(0,255,255,0.3),-1)
    frame = cv2.resize(frame,(960,540)) #resize window

    out.write(frame)

    cv2.imshow('screenshot', frame)

    if cv2.waitKey(1) == ord("q"):
        break

cv2.destroyAllWindows()
out.release()
</code>```

答:
When you use cv2.videowriter, make sure that the framesize is equal to the size of the screen so that the image is not distorted.

In addition, if you need to record the screen, you should make sure that the opencv window does not affect the beauty of the entire desktop.

In my code, I have added a translucent circle. You can change the transparency of the circle as needed.

```<code>from PIL import ImageGrab
import numpy as np
import cv2
import datetime
from pynput import keyboard
import threading
import win32api

flag=False

def transparent_circle(img,center,radius,color,thickness):
    center = tuple(map(int,center))
    rgb = [255*c for c in color[:3]] # convert to 0-255 scale for OpenCV
    alpha = color[-1]
    radius = int(radius)
    if thickness > 0:
        pad = radius + 2 + thickness
    else:
        pad = radius + 3
    roi = slice(center[1]-pad,center[1]+pad),slice(center[0]-pad,center[0]+pad)

    try:
        overlay = img[roi].copy()
        cv2.circle(img,center,radius,rgb, thickness=thickness, lineType=cv2.LINE_AA)
        opacity = alpha
        cv2.addWeighted(src1=img[roi], alpha=opacity, src2=overlay, beta=1. - opacity, gamma=0, dst=img[roi])
    except:
        logger.debug("transparent_circle would have been partially outside of img. Did not draw it.")

def video_record():
    date=datetime.datetime.now()
    filename='path/rec_%s%s%s%s%s%s.avi' %(date.year,date.month,date.day,date.hour,date.minute,date.second)
    p = ImageGrab.grab()
    a, b = p.size
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    video = cv2.VideoWriter(filename, fourcc, 20, (a, b))
    while True:
        im = ImageGrab.grab()
        imm=cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
        _xs,_ys = win32api.GetCursorPos()
        transparent_circle(imm,(_xs,_ys),20,(0,255,255,0.5), -1)
#       cv2.circle(imm,(_xs,_ys),20,(0,255,255,0.3),-1)
        video.write(imm)
        if flag:
            print("Record Over")
            break
    video.release()
def on_press(key):
    global flag
    if key == keyboard.Key.esc:
        flag=True
        print("stop monitor")
        return False

if __name__=='__main__':
    th=threading.Thread(target=video_record)
    th.start()
    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()
</code>```

When you run the code, start recording. When you press the ESC key, stop recording and save the file.

Note: You may need to add some libraries, otherwise there will be an error that the module cannot be found

Title: how to record screen in high quality

Body:
i am creating a screen recorder for desktop in python. and i have already completed the coding part but when i record the screen why it is not recording in high defination.
problem.........
1> i want to record the screen in high quality what should i do.
2> i am also trying to capute my cursor with the help on cv2.circle() but i want to create the circle with less opacity or more transparent

my code

import cv2
import numpy as np
import pyautogui
import datetime
import win32api

date=datetime.datetime.now()

SCREEN_SIZE = (960,540) #std res 1366, 768
framerate=12
# define the codec
fourcc = cv2.VideoWriter_fourcc(*'XVID')
filename='E:/project/videos/rec_%s%s%s%s%s%s.avi' %(date.year,date.month,date.day,date.hour,date.minute,date.second)

out = cv2.VideoWriter(filename, fourcc,framerate, SCREEN_SIZE)

while True:

    img = pyautogui.screenshot()

    frame = np.array(img)

    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    _xs,_ys = win32api.GetCursorPos()
    image=cv2.circle(frame,(_xs,_ys),20,(0,255,255,0.3),-1)
    frame = cv2.resize(frame,(960,540)) #resize window

    out.write(frame)

    cv2.imshow('screenshot', frame)

    if cv2.waitKey(1) == ord("q"):
        break

cv2.destroyAllWindows()
out.release()

Body:
When you use cv2.videowriter, make sure that the framesize is equal to the size of the screen so that the image is not distorted.

In addition, if you need to record the screen, you should make sure that the opencv window does not affect the beauty of the entire desktop.

In my code, I have added a translucent circle. You can change the transparency of the circle as needed.

from PIL import ImageGrab
import numpy as np
import cv2
import datetime
from pynput import keyboard
import threading
import win32api

flag=False

def transparent_circle(img,center,radius,color,thickness):
    center = tuple(map(int,center))
    rgb = [255*c for c in color[:3]] # convert to 0-255 scale for OpenCV
    alpha = color[-1]
    radius = int(radius)
    if thickness > 0:
        pad = radius + 2 + thickness
    else:
        pad = radius + 3
    roi = slice(center[1]-pad,center[1]+pad),slice(center[0]-pad,center[0]+pad)

    try:
        overlay = img[roi].copy()
        cv2.circle(img,center,radius,rgb, thickness=thickness, lineType=cv2.LINE_AA)
        opacity = alpha
        cv2.addWeighted(src1=img[roi], alpha=opacity, src2=overlay, beta=1. - opacity, gamma=0, dst=img[roi])
    except:
        logger.debug("transparent_circle would have been partially outside of img. Did not draw it.")

def video_record():
    date=datetime.datetime.now()
    filename='path/rec_%s%s%s%s%s%s.avi' %(date.year,date.month,date.day,date.hour,date.minute,date.second)
    p = ImageGrab.grab()
    a, b = p.size
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    video = cv2.VideoWriter(filename, fourcc, 20, (a, b))
    while True:
        im = ImageGrab.grab()
        imm=cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
        _xs,_ys = win32api.GetCursorPos()
        transparent_circle(imm,(_xs,_ys),20,(0,255,255,0.5), -1)
#       cv2.circle(imm,(_xs,_ys),20,(0,255,255,0.3),-1)
        video.write(imm)
        if flag:
            print("Record Over")
            break
    video.release()
def on_press(key):
    global flag
    if key == keyboard.Key.esc:
        flag=True
        print("stop monitor")
        return False

if __name__=='__main__':
    th=threading.Thread(target=video_record)
    th.start()
    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()

When you run the code, start recording. When you press the ESC key, stop recording and save the file.

Note: You may need to add some libraries, otherwise there will be an error that the module cannot be found


问:
Edge and HTML Form Validation: how to remove "red square" around the input for elements in invalid status?
On the picture (this is the Edge browser) field named BsMultiSelect have normal bootstrap invalid look (this is in css). The same I expect from "Input sample", but there Edge browser adds its own "red border" (it is not in css!) for elements in invalid state . How to disable this browser behaviour?

Chrome doesn't have such feature, doesn't add any own styles for :invalid elements.

答:
You can remove this outline like this :

```<code>input {
    outline: unset;
}
</code>```

Body:
You can remove this outline like this :

input {
    outline: unset;
}


问:
Variable's value doesn't increment within nested loops (File writing with Python)
I have a code to parse through several text files and extract a given part from each one and write them into another text file. I repeat this process over and over again, extracting the next part of the files and writing them on the other text file.

I'm using the variable cube_i to move from one file to another and the variable layer to move from one part of the text files to another. However, the loops I created don't go further than the cube_i=0 and layer=0. Any suggestions on how I can proceed to increment the value of those variables?

```<code>rgx_start = re.compile(r'Z down')  # Second line before the start of the layer code: "G0Z2 ; Z down"
rgx_end = re.compile(r'Layer #')  # Second line after the end of the layer code: "; Layer #<integer>"
if layer in range(0, (layers_total + 1)):
    final_code.write('; ------------------------------\n')
    label = ';          Layer #{}\n'.format(layer)
    final_code.write(label)
    final_code.write('; ------------------------------\n')
    with open(first_file,'r') as gcode:  # Opening the first file to write the powder drop
        for i, line in enumerate(gcode.readlines()):
            if i in range(powdrop_start, (powdrop_end + 1)):  # Writing the powder drop
                final_code.write(line)
    cube_i = 0 # Reseting the cube_i variable
    if cube_i in range(0, (parts_total + 1)):
        label_cube = ';   PART #{}\n'.format(cube_i)
        final_code.write(label_cube)
        # Opening each text file separately
        with open(f_path, 'r') as gcode:  # f_path contains cube_i
            lines = gcode.readlines()
        start_i = prev_start[cube_i]
        for i, line in enumerate(lines[start_i + 1:]):  # Searching for the beginning of given layer
            if rgx_start.search(line):
                layer_start = start_i + i + 3
                break
        for i, line in enumerate(lines[layer_start + 1:]):  # Searching for the end of given layer
            if rgx_end.search(line):
                layer_end = layer_start + i - 1
                break
        for i, line in enumerate(lines[layer_start:layer_end + 1]):
            final_code.write(line)
        prev_start.append(layer_start)
        prev_end.append(layer_end)
        cube_i = + 1
    if layer == 0: # Writing the zeroth layer footer
        with open(first_file, 'r') as gcode:
            for i, line in enumerate(gcode.readlines()):
                if i == zeroth_ftr:
                    final_code.write(line)
    layer =+ 1
</code>```

答:
There are a couple of for loops in the code which have been incorrectly written as if statements.
The correct code snipped would be :

```<code>rgx_start = re.compile(r'Z down')  # Second line before the start of the layer code: "G0Z2 ; Z down"
rgx_end = re.compile(r'Layer #')  # Second line after the end of the layer code: "; Layer #<integer>"
for layer in range(0, (layers_total + 1)):
    final_code.write('; ------------------------------\n')
    label = ';          Layer #{}\n'.format(layer)
    final_code.write(label)
    final_code.write('; ------------------------------\n')
    with open(first_file,'r') as gcode:  # Opening the first file to write the powder drop
        for i, line in enumerate(gcode.readlines()):
            if i in range(powdrop_start, (powdrop_end + 1)):  # Writing the powder drop
                final_code.write(line)
    cube_i = 0 # Reseting the cube_i variable
    for cube_i in range(0, (parts_total + 1)):
        label_cube = ';   PART #{}\n'.format(cube_i)
        final_code.write(label_cube)
        # Opening each text file separately
        with open(f_path, 'r') as gcode:  # f_path contains cube_i
            lines = gcode.readlines()
        start_i = prev_start[cube_i]
        for i, line in enumerate(lines[start_i + 1:]):  # Searching for the beginning of given layer
            if rgx_start.search(line):
                layer_start = start_i + i + 3
                break
        for i, line in enumerate(lines[layer_start + 1:]):  # Searching for the end of given layer
            if rgx_end.search(line):
                layer_end = layer_start + i - 1
                break
        for i, line in enumerate(lines[layer_start:layer_end + 1]):
            final_code.write(line)
        prev_start.append(layer_start)
        prev_end.append(layer_end)
        cube_i = + 1
    if layer == 0: # Writing the zeroth layer footer
        with open(first_file, 'r') as gcode:
            for i, line in enumerate(gcode.readlines()):
                if i == zeroth_ftr:
                    final_code.write(line)
    layer =+ 1
</code>```

This should work in your case.

Body:
I have a code to parse through several text files and extract a given part from each one and write them into another text file. I repeat this process over and over again, extracting the next part of the files and writing them on the other text file.

I'm using the variable cube_i to move from one file to another and the variable layer to move from one part of the text files to another. However, the loops I created don't go further than the cube_i=0 and layer=0. Any suggestions on how I can proceed to increment the value of those variables?

rgx_start = re.compile(r'Z down')  # Second line before the start of the layer code: "G0Z2 ; Z down"
rgx_end = re.compile(r'Layer #')  # Second line after the end of the layer code: "; Layer #<integer>"
if layer in range(0, (layers_total + 1)):
    final_code.write('; ------------------------------\n')
    label = ';          Layer #{}\n'.format(layer)
    final_code.write(label)
    final_code.write('; ------------------------------\n')
    with open(first_file,'r') as gcode:  # Opening the first file to write the powder drop
        for i, line in enumerate(gcode.readlines()):
            if i in range(powdrop_start, (powdrop_end + 1)):  # Writing the powder drop
                final_code.write(line)
    cube_i = 0 # Reseting the cube_i variable
    if cube_i in range(0, (parts_total + 1)):
        label_cube = ';   PART #{}\n'.format(cube_i)
        final_code.write(label_cube)
        # Opening each text file separately
        with open(f_path, 'r') as gcode:  # f_path contains cube_i
            lines = gcode.readlines()
        start_i = prev_start[cube_i]
        for i, line in enumerate(lines[start_i + 1:]):  # Searching for the beginning of given layer
            if rgx_start.search(line):
                layer_start = start_i + i + 3
                break
        for i, line in enumerate(lines[layer_start + 1:]):  # Searching for the end of given layer
            if rgx_end.search(line):
                layer_end = layer_start + i - 1
                break
        for i, line in enumerate(lines[layer_start:layer_end + 1]):
            final_code.write(line)
        prev_start.append(layer_start)
        prev_end.append(layer_end)
        cube_i = + 1
    if layer == 0: # Writing the zeroth layer footer
        with open(first_file, 'r') as gcode:
            for i, line in enumerate(gcode.readlines()):
                if i == zeroth_ftr:
                    final_code.write(line)
    layer =+ 1

Body:
There are a couple of for loops in the code which have been incorrectly written as if statements.
The correct code snipped would be :

rgx_start = re.compile(r'Z down')  # Second line before the start of the layer code: "G0Z2 ; Z down"
rgx_end = re.compile(r'Layer #')  # Second line after the end of the layer code: "; Layer #<integer>"
for layer in range(0, (layers_total + 1)):
    final_code.write('; ------------------------------\n')
    label = ';          Layer #{}\n'.format(layer)
    final_code.write(label)
    final_code.write('; ------------------------------\n')
    with open(first_file,'r') as gcode:  # Opening the first file to write the powder drop
        for i, line in enumerate(gcode.readlines()):
            if i in range(powdrop_start, (powdrop_end + 1)):  # Writing the powder drop
                final_code.write(line)
    cube_i = 0 # Reseting the cube_i variable
    for cube_i in range(0, (parts_total + 1)):
        label_cube = ';   PART #{}\n'.format(cube_i)
        final_code.write(label_cube)
        # Opening each text file separately
        with open(f_path, 'r') as gcode:  # f_path contains cube_i
            lines = gcode.readlines()
        start_i = prev_start[cube_i]
        for i, line in enumerate(lines[start_i + 1:]):  # Searching for the beginning of given layer
            if rgx_start.search(line):
                layer_start = start_i + i + 3
                break
        for i, line in enumerate(lines[layer_start + 1:]):  # Searching for the end of given layer
            if rgx_end.search(line):
                layer_end = layer_start + i - 1
                break
        for i, line in enumerate(lines[layer_start:layer_end + 1]):
            final_code.write(line)
        prev_start.append(layer_start)
        prev_end.append(layer_end)
        cube_i = + 1
    if layer == 0: # Writing the zeroth layer footer
        with open(first_file, 'r') as gcode:
            for i, line in enumerate(gcode.readlines()):
                if i == zeroth_ftr:
                    final_code.write(line)
    layer =+ 1

This should work in your case.


问:
TypeError: Cannot read property 'length' of undefined at model create
I'm creating a model and a controller to execute some financial transactions, as debit and credits.

When I try 'create' using <model>.create method, its returning me the following error:

```<code>(node:5192) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
    at Transaction._initValues (/Users/username/Documents/Projetos/projectname/node_modules/sequelize/lib/model.js:140:49)
</code>```

The Controller source code is:

```<code>import * as Yup from 'yup';
import Transaction from '../models/Transaction';

class TransactionController {
  async store(req, res) {
    const schema = Yup.object().shape({
      id_user: Yup.number().required(),
      id_category: Yup.number().required(),
      id_wallet: Yup.number(),
      title: Yup.string()
        .min(6)
        .max(32)
        .required(),
      description: Yup.string(),
      amount: Yup.number()
        .round('floor')
        .moreThan(0)
        .positive()
        .required(),
      is_credit: Yup.bool()
        .required()
        .default(true),
    });
    if (!(await schema.isValid(req.body))) {
      return res.status(400).json({
        error:
          'Validation failed, see documentation for insert new transaction',
      });
    }
    const {
      id_user,
      id_category,
      id_wallet,
      title,
      description,
      amount,
      is_credit,
    } = await Transaction.create(req.body).catch(error => {
      console.log('error', error);
    });
    return res.json({
      id_user,
      id_category,
      id_wallet,
      title,
      description,
      amount,
      is_credit,
    });
  }
}

export default new TransactionController();
</code>```

And the model base is:

```<code>class Transaction extends Model {
  static init(sequelize) {
    super.init(
      {
        id_user: Sequelize.INTEGER,
        id_category: Sequelize.INTEGER,
        id_wallet: Sequelize.INTEGER,
        title: Sequelize.STRING,
        description: Sequelize.STRING,
        amount: Sequelize.DECIMAL(10, 2),
        is_credit: Sequelize.BOOLEAN,
      },
      {
        sequelize,
      }
    );
    return this;
  }

  /* static associate(models) {
                  this.belongsTo(models.File, { foreignKey: 'avatar_id', as: 'avatar' });
                } */

  static associate(models) {
    this.belongsTo(models.User, { foreignKey: 'id_user', as: 'id' });
  }
}

export default Transaction;
</code>```

I can't understand what length means, because I'm validating the body with YUP and trying to insert using all values inside the JSON BODY.

Can someone help me, please?

Thanks in advance,

答:
You have to excecute your database.js class before you call your request. For example:

If you are using a file for import routes, have to import database.js and excecute it before excecute the controller.

Body:
I'm creating a model and a controller to execute some financial transactions, as debit and credits.

When I try 'create' using <model>.create method, its returning me the following error:

(node:5192) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
    at Transaction._initValues (/Users/username/Documents/Projetos/projectname/node_modules/sequelize/lib/model.js:140:49)

The Controller source code is:

import * as Yup from 'yup';
import Transaction from '../models/Transaction';

class TransactionController {
  async store(req, res) {
    const schema = Yup.object().shape({
      id_user: Yup.number().required(),
      id_category: Yup.number().required(),
      id_wallet: Yup.number(),
      title: Yup.string()
        .min(6)
        .max(32)
        .required(),
      description: Yup.string(),
      amount: Yup.number()
        .round('floor')
        .moreThan(0)
        .positive()
        .required(),
      is_credit: Yup.bool()
        .required()
        .default(true),
    });
    if (!(await schema.isValid(req.body))) {
      return res.status(400).json({
        error:
          'Validation failed, see documentation for insert new transaction',
      });
    }
    const {
      id_user,
      id_category,
      id_wallet,
      title,
      description,
      amount,
      is_credit,
    } = await Transaction.create(req.body).catch(error => {
      console.log('error', error);
    });
    return res.json({
      id_user,
      id_category,
      id_wallet,
      title,
      description,
      amount,
      is_credit,
    });
  }
}

export default new TransactionController();

And the model base is:

class Transaction extends Model {
  static init(sequelize) {
    super.init(
      {
        id_user: Sequelize.INTEGER,
        id_category: Sequelize.INTEGER,
        id_wallet: Sequelize.INTEGER,
        title: Sequelize.STRING,
        description: Sequelize.STRING,
        amount: Sequelize.DECIMAL(10, 2),
        is_credit: Sequelize.BOOLEAN,
      },
      {
        sequelize,
      }
    );
    return this;
  }

  /* static associate(models) {
                  this.belongsTo(models.File, { foreignKey: 'avatar_id', as: 'avatar' });
                } */

  static associate(models) {
    this.belongsTo(models.User, { foreignKey: 'id_user', as: 'id' });
  }
}

export default Transaction;

I can't understand what length means, because I'm validating the body with YUP and trying to insert using all values inside the JSON BODY.

Can someone help me, please?

Thanks in advance,


问:
How to check if a value in object is a primitive?
So basically i want to check if my data (which is in JSON Format) has a value which is a primitive. So let's take an Example: I get data that looks like this: {name: Artikel, value: {"ArtNr": 1234}} and i want to check if 1234 is primitive or not. I also want to differentiate if the result is an Array with Primitives in it or an Object. Is that possible?

```<code>function isObjectContainingPrimitiveValues(test) {
        let values = Object.values(test);
        for (let i of values) {
            console.log(i);
            return (typeof i === 'string' || typeof i === 'number' || typeof i === 'boolean' || typeof i === null || typeof i === undefined);
        }
    }
</code>```

UPDATE

So with the awesome help of MaxK i have built a isResultContainingPrimitiveValues() Function which checks my data for Primitive/ Primitive Arrays and or Objects. The following part is the trickiest at least with my understanding. The following Example will hopefully help you understand my problems better.

So my let namesSplit = treeNode.name.split('.'); variable splits the data it gets and has as a result of nameSplit : Artikel,Artnr. Next i defined a key variable let key = namesSplit[0]; which has key : Artikel as a result. Than i define a contextEntry variable let contextEntry = exprData.contextEntry.find(_x => _x.name === key); and has contextEntry : {"name":"Artikel","value":{"ArtNr":123}} as a result. Now i want to check: if there's another split namesSplit.length > 1 check isResultContainingPrimitiveValues(). If it is primitive, throw an error, if it is an object -> get values from it and if it is an array -> get values form there. I know it's a lot but from all the confusing stuff i can't seem to think clear, so i appreciate every help i can get.

答:
Array and object types all return a 'typeof' 'object'. so you can check against an object instead of checking against multiple conditions.
So the return statement will be:
return (typeof i === 'object').
Number, string, undefined, null will all return false on the statement above.

Body:
So basically i want to check if my data (which is in JSON Format) has a value which is a primitive. So let's take an Example: I get data that looks like this: {name: Artikel, value: {"ArtNr": 1234}} and i want to check if 1234 is primitive or not. I also want to differentiate if the result is an Array with Primitives in it or an Object. Is that possible?

function isObjectContainingPrimitiveValues(test) {
        let values = Object.values(test);
        for (let i of values) {
            console.log(i);
            return (typeof i === 'string' || typeof i === 'number' || typeof i === 'boolean' || typeof i === null || typeof i === undefined);
        }
    }

UPDATE

So with the awesome help of MaxK i have built a isResultContainingPrimitiveValues() Function which checks my data for Primitive/ Primitive Arrays and or Objects. The following part is the trickiest at least with my understanding. The following Example will hopefully help you understand my problems better.

So my let namesSplit = treeNode.name.split('.'); variable splits the data it gets and has as a result of nameSplit : Artikel,Artnr. Next i defined a key variable let key = namesSplit[0]; which has key : Artikel as a result. Than i define a contextEntry variable let contextEntry = exprData.contextEntry.find(_x => _x.name === key); and has contextEntry : {"name":"Artikel","value":{"ArtNr":123}} as a result. Now i want to check: if there's another split namesSplit.length > 1 check isResultContainingPrimitiveValues(). If it is primitive, throw an error, if it is an object -> get values from it and if it is an array -> get values form there. I know it's a lot but from all the confusing stuff i can't seem to think clear, so i appreciate every help i can get.


问:
check if image exists with fetch (function does not return response)
I have the following function to check if an image (avatar) exists on the server. If so, the avatar is displayed. If not, a default avatar is displayed.

```<code>export const Avatar = props => {

    const userId = props.userId

    const size = props.size ? props.size : 25

    fetch(URL.Avatar + '/' + userId + '_avatar.jpg').then(res => {
        if (res.status === 404) {
            return (
                <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        } else {
            return (
                <Image source={{uri: URL.Avatar + '/' + userId + '_avatar.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        }
    }).catch(err => {
        return (
            <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
                width: size,
                height: size,
                borderRadius: size / 2
            }} />
        )
    })

}
</code>```

However, this function does not work. I get the error "nothing was returned from render", because the function thinks a return-statement (at the end) is missing. However, when I put some console.logs in it, the fetch itself is working. The URLs are correct, because when I put a return at the end with an Image-component, it works.

Anyone knows what the problem could be? Has it anything to do with async?

答:
There's no need to fetch the image yourself before using it, it's redundant. Instead, you can use the onError function of the Image component to identify that the image failed to load. You can save the URL in the component state and change it according to the success/failure status (see the onLoad function to identify that the image was successfully loaded).

Alternatively, you can set a default image that will show while the image is loading via the defaultSource prop to act as a placeholder.

Body:
I have the following function to check if an image (avatar) exists on the server. If so, the avatar is displayed. If not, a default avatar is displayed.

export const Avatar = props => {

    const userId = props.userId

    const size = props.size ? props.size : 25

    fetch(URL.Avatar + '/' + userId + '_avatar.jpg').then(res => {
        if (res.status === 404) {
            return (
                <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        } else {
            return (
                <Image source={{uri: URL.Avatar + '/' + userId + '_avatar.jpg' }} style={{
                    width: size,
                    height: size,
                    borderRadius: size / 2
                }} />
            )
        }
    }).catch(err => {
        return (
            <Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
                width: size,
                height: size,
                borderRadius: size / 2
            }} />
        )
    })

}

However, this function does not work. I get the error "nothing was returned from render", because the function thinks a return-statement (at the end) is missing. However, when I put some console.logs in it, the fetch itself is working. The URLs are correct, because when I put a return at the end with an Image-component, it works.

Anyone knows what the problem could be? Has it anything to do with async?


问:
Check all checkboxes in checkboxlist with one click using c#
I want to have a button that once clicked, it will select all checkboxes in my checklistbox. I've search the possible answers but I always see examples for asp.net and javascript. I am using Windows form in c#. Thank you for any response.</p>

答:
what I did is I put it inside of a tableLayoutPanel, I fixed all the checkboxs in the 3rd column and i added the event:</p>

```<code>private void cbCheckAllCHECKBOXs_CheckedChanged(objects sender, EventArgs e)
{
    if (cbCheeckAllCHECKBOXs.Checked)
    {
        for (int i = 0; i < tlpCHECKBOXsControlPanel.RowCount; i++)
        {
            ((System.Windows.Forms.CheckBox)(tlpCHECKBOXsControlPanel.GetControlFromPosition(3, i))).Checked = true;
        }
    }
}
</code>```

Body:
what I did is I put it inside of a tableLayoutPanel, I fixed all the checkboxs in the 3rd column and i added the event:

private void cbCheckAllCHECKBOXs_CheckedChanged(objects sender, EventArgs e)
{
    if (cbCheeckAllCHECKBOXs.Checked)
    {
        for (int i = 0; i < tlpCHECKBOXsControlPanel.RowCount; i++)
        {
            ((System.Windows.Forms.CheckBox)(tlpCHECKBOXsControlPanel.GetControlFromPosition(3, i))).Checked = true;
        }
    }
}


问:
FLVPlayBack: don't load flv until prompted to
Is it possible to configure FLVPlayback so that it does not auto-load the associated video file, but instead waits for a click on a "play" button to load and then play it? (I'm building a site that will have a player for a rather large video on its front page, and I'd rather not have the video downloaded unless/until the user asks to see it.) I already have autoplay set to false, but I can still see the video getting downloaded in the progress bar. </p>

答:
add an invisible button, with a hit area as big as the video:

```<code>btnPlay.addEventListener(MouseEvent.CLICK, onPlayClick);

function onPlayClick(evt:MouseEvent):void
{
btnPlay.visible = false;
flvPlayer.load("filename.flv");
flvPlayer.play();
}
</code>```

or something like that. the problem is: the FLVPlayback component shows an animated bar with stripes when there is no content assigned to it. if you don´t want to see that, you could set the "skinAutoHide" property to true. after that, there is only one more problem: the user doesn´t see your player, so you should add a play image in the button. if you click on the button, the button disappears and the video starts loading and playing.

ContentLicense: CC BY-SA 2.5

Body:
add an invisible button, with a hit area as big as the video:

btnPlay.addEventListener(MouseEvent.CLICK, onPlayClick);

function onPlayClick(evt:MouseEvent):void
{
btnPlay.visible = false;
flvPlayer.load("filename.flv");
flvPlayer.play();
}

or something like that. the problem is: the FLVPlayback component shows an animated bar with stripes when there is no content assigned to it. if you don´t want to see that, you could set the "skinAutoHide" property to true. after that, there is only one more problem: the user doesn´t see your player, so you should add a play image in the button. if you click on the button, the button disappears and the video starts loading and playing.


问:
Strip a comma and whitespace thats after it from a string
I'm working with a Postcode Finder and some of the address elements i.e County are returning empty at times as a ", "

I'm looking to strip them from the string to return a more readable address format

Example Data is JSON :

```<code>{
"latitude": 53.381130218505859,
"longitude": -1.4663739204406738,
"addresses": [
    "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Crucible Theatre, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Crucible Productions Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Theatres Crucible Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "The City Of Sheffield Theatre Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire"
]
}
</code>```

As you can see there's a lot of commas and spaces directly after with no data in.

How do I go about doing this? My current code is :

```<code>$.ajax(
            {
                type: 'POST',
                url: '/address',
                dataType: 'json',
                data: { _token: token, postcode: postcode},
                success: function( data )
                {
                    $('.addresses').html('');

                    $.each(data, function(k, v)
                    {
                        address = v.replace(/\s+/g, ' ');

                        $('.addresses').append('<option value="">'+ address +'</option>');
                    })
                }
            }
        )
</code>```

答:
You could also do this without the use of regular expressions.

```<code>const address = "The City Of Sheffield Theatre Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire"

const cleanAddress = address.split(", ")
    .filter(section => !!section)
    .join(", ");

// The City Of Sheffield Theatre Trust, 55 Norfolk Street, Sheffield, South Yorkshire
</code>```

This uses the fact that an empty string "" is a falsy value.

Adding this to your code:

```<code>$.ajax({
  type: "POST",
  url: "/address",
  dataType: "json",
  data: { _token: token, postcode: postcode },
  success: function(data) {
    $(".addresses").html("");

    $.each(data, function(k, v) {
     address = v.split(", ")
         .filter(section => !!section)
         .join(", ");

      $(".addresses").append('<option value="">' + address + "</option>");
    });
  }
});
</code>```

Body:
I'm working with a Postcode Finder and some of the address elements i.e County are returning empty at times as a ", "

I'm looking to strip them from the string to return a more readable address format

Example Data is JSON :

{
"latitude": 53.381130218505859,
"longitude": -1.4663739204406738,
"addresses": [
    "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Crucible Theatre, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Crucible Productions Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Theatres Crucible Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "The City Of Sheffield Theatre Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire"
]
}

As you can see there's a lot of commas and spaces directly after with no data in.

How do I go about doing this? My current code is :

$.ajax(
            {
                type: 'POST',
                url: '/address',
                dataType: 'json',
                data: { _token: token, postcode: postcode},
                success: function( data )
                {
                    $('.addresses').html('');

                    $.each(data, function(k, v)
                    {
                        address = v.replace(/\s+/g, ' ');

                        $('.addresses').append('<option value="">'+ address +'</option>');
                    })
                }
            }
        )

Body:
You could also do this without the use of regular expressions.

const address = "The City Of Sheffield Theatre Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire"

const cleanAddress = address.split(", ")
    .filter(section => !!section)
    .join(", ");

// The City Of Sheffield Theatre Trust, 55 Norfolk Street, Sheffield, South Yorkshire

This uses the fact that an empty string "" is a falsy value.

Adding this to your code:

$.ajax({
  type: "POST",
  url: "/address",
  dataType: "json",
  data: { _token: token, postcode: postcode },
  success: function(data) {
    $(".addresses").html("");

    $.each(data, function(k, v) {
     address = v.split(", ")
         .filter(section => !!section)
         .join(", ");

      $(".addresses").append('<option value="">' + address + "</option>");
    });
  }
});


问:
Error in Boto AWS Rekognition
I am trying to compare faces using AWS Rekognitionthrough Python boto3, as instructed in the AWS documentation.

My API call is:

```<code>client = boto3.client('rekognition', aws_access_key_id=key, aws_secret_access_key=secret, region_name=region )

source_bytes = open('source.jpg', 'rb')
target_bytes = open('target.jpg', 'rb')

response = client.compare_faces(
    SourceImage = {
        'Bytes':bytearray(source_bytes.read())
    },
    TargetImage = {
        'Bytes':bytearray(target_bytes.read())
    },
    SimilarityThreshold = SIMILARITY_THRESHOLD
)

source_image.close()
target_image.close()
</code>```

But everytime I run this program,I get the following error:

```<code>botocore.errorfactory.InvalidParameterException: An error occurred (InvalidParameterException) when calling the CompareFaces operation: Request has Invalid Parameters
</code>```

I have specified the secret, key, region, and threshold properly. How can I clear off this error and make the request call work?

答:
For those still looking for answer,

I had the same problem, while, @mohanbabu pointed to official docs for what should go in to compare_faces, what I realised is that compare_faces looks for faces in both SourceImage and TargetImage. I confirmed this by first detecting faces using aws's detect_faces and passing deteced faces to compare_faces.

compare_faces failed almost all the time when face detected by detect_faces was a littile obscure.

So, to summerize if any of your SourceImage or TargetImage is tightly cropped to face AND that face is not instantly obvious, compare_faces will fail.

There can be other reason but this observation worked for me.

ex:

In the above image you can fairly confidently say there is a face in the middle

But,

Now, not so obvious.

This was the reason for me atleast, check both your images and you should know.

Title: Error in Boto AWS Rekognition

Body:
I am trying to compare faces using AWS Rekognitionthrough Python boto3, as instructed in the AWS documentation.

My API call is:

client = boto3.client('rekognition', aws_access_key_id=key, aws_secret_access_key=secret, region_name=region )

source_bytes = open('source.jpg', 'rb')
target_bytes = open('target.jpg', 'rb')

response = client.compare_faces(
    SourceImage = {
        'Bytes':bytearray(source_bytes.read())
    },
    TargetImage = {
        'Bytes':bytearray(target_bytes.read())
    },
    SimilarityThreshold = SIMILARITY_THRESHOLD
)

source_image.close()
target_image.close()

But everytime I run this program,I get the following error:

botocore.errorfactory.InvalidParameterException: An error occurred (InvalidParameterException) when calling the CompareFaces operation: Request has Invalid Parameters

I have specified the secret, key, region, and threshold properly. How can I clear off this error and make the request call work?


问:
Open Stack and Development Stack
i am really confuse about  the main difference between Open Stack and development Stack ?
is it different version  or different platform ?</p>

答:
First of all, let's get the terminology correct.  You are talking about OpenStack (one word) and DevStack (one word).

OpenStack is a suite of services for managing computing and related resources.  You typically use it for managing "cloud computing" resources, consisting of multiple physical compute and storage servers.  Setting up a system like this for production use on "real" hardware takes a lot of time and expertise.

DevStack is a essentially a set of scripts that will set up set up a simple OpenStack test environment running as virtual machines on (typically) a Linux PC with a few GB of RAM and a chunk of free disk space.  The purpose is to allow a developer to set up a tiny cloud for trying things out, and doing service development work.

OpenStack and DevStack are neither different versions or different platforms.  They are different parts of a larger whole.  (You could say that DevStack is part of the OpenStack suite of software.  Development of OpenStack and DevStack are handled by the same umbrella organization under the same governance, etc, etc.)

Title: Open Stack and Development Stack


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答:
You fight someone else's overdesign/feature creep in several ways:

Request feature priority, based on actual user requirements.  Mock up features for alpha and beta testers, and ask if they would trade N months of delay for it.

Aggressively refactor to avoid special-casing.  Break code into layers or modular components whenever appropriate.  Find a balance between "works just fine now" and "easy to extend later".

Notify your management when you disagree with design decisions, prepare to be overruled, and accept the decision.  Don't go over anyone's head or sabotage code.

OwnerDisplayName: ʞɔıu

Title: How do you fight design complexity?

LastEditorDisplayName: philippe

OwnerDisplayName: HUAGHAGUAH


问:
How to rename part of a file
I would to to rename part of a file name, because the structure is hardcoded in getfiles.

I have metabolomics mzML files containing ltQCs, sQCs and samples, but the name of the files have different lenghts (6,6,7).I am trying to run XCMS, but it only picks up ltQCs and sQCs, because the structure is hardcoded to 6. How do I change the structure of the filename see example below:

2020-02-02_B1W1_RP_NEG_P7_A20_001.mzML (structure of 7)
to
2020-02-02_B1W1_RP_NEG_P7A20_001.mzML (structure of 6)

I have higlighted the part that I would like to change. If this is impossible, maybe renaming the ltQCs and sQCs may be easier by adding a letter or number, so I get a structure of 7 and then change the structure in getfiles to 7.

Hope somebody can help, thank you:)

Best

答:
You can change the file names with a regular expression using gsub which removes the penultimate underline

my_regex <- "(_)([[:alnum:]]{3}_[[:alnum:]]{3}[.]mzML)"
my_filename <- "2020-02-02_B1W1_RP_NEG_P7_A20_001.mzML"
gsub(my_regex, "\\2", my_filename)
#> [1] "2020-02-02_B1W1_RP_NEG_P7A20_001.mzML"
```

<p>So you could do something like</p>

```rename_mzMLs <- function(directory)
{
  filenames <- list.files(directory, pattern = ".mzML")
  my_regex <- "(_)([[:alnum:]]{3}_[[:alnum:]]{3}[.]mzML)"
  new_filenames <- gsub(my_regex, "\\2", filenames)
  file.rename(filenames, new_filenames)
}
```

<p>And run it by doing</p>

```rename_mzMLs("C:/path/to/mzML/files/")
```

Obviously, I can't test this since I don't have any mzML files, so ensure you back up your files before running this function!

Title: How to rename part of a file

Body:
You can change the file names with a regular expression using gsub which removes the penultimate underline

my_regex <- "(_)([[:alnum:]]{3}_[[:alnum:]]{3}[.]mzML)"
my_filename <- "2020-02-02_B1W1_RP_NEG_P7_A20_001.mzML"
gsub(my_regex, "\\2", my_filename)
#> [1] "2020-02-02_B1W1_RP_NEG_P7A20_001.mzML"

So you could do something like

rename_mzMLs <- function(directory)
{
  filenames <- list.files(directory, pattern = ".mzML")
  my_regex <- "(_)([[:alnum:]]{3}_[[:alnum:]]{3}[.]mzML)"
  new_filenames <- gsub(my_regex, "\\2", filenames)
  file.rename(filenames, new_filenames)
}

And run it by doing

rename_mzMLs("C:/path/to/mzML/files/")

Obviously, I can't test this since I don't have any mzML files, so ensure you back up your files before running this function!