问:
Calculations using two pandas dataframes
I have the following two (simplified) dataframes with me:

```<code>df1=
         origin destination  val1  val2
    0      1           A      0.8   0.9
    1      1           B      0.3   0.5
    2      1           c      0.4   0.2
    3      2           A      0.4   0.7
    4      2           B      0.2   0.1
    5      2           c      0.5   0.1
df2=
  org  price
0   1     50
1   2     45
</code>```

what I need to do is to select the price from each origin from df2, multiply it by the sum of val1+val2 in df1 and write it to a csv file.

The calculation for A is as follows:

A => (0.8+0.9)* 50 + (0.4+ 0.7)* 45   = 134.5

here, the values 0.8, 0.9, 0.4 and 0.7 are coming from df1 and they correspond to val1 and val2 of A
where as the values 50 and 45 come from df2 corresponding to origin 1 and 2 respectively.
for B the calculation would be

B => (0.3+0.5)*50 + (0.2+0.1)*45 = 53.5

for C the calculation would be:

C => (0.4+0.2)*50 + (0.5+0.1)*45 = 57

The final CSV file should look like:

A,134.5

B,53.5

C,57
I've written the following python code for that:

```<code># first convert the second table into a python dictionary so that I can refer price value at each origin
df2_dictionary = {}
for ind in df2.index:
    df2_dictionary[df2['org'][ind]] = float(df2['price'][ind])

# now go through df1, add up val1 and val2 and add the result to the result dictionary.
result = {}
for ind in df1.index:
    origin = df1['origin'][ind]
    price = df2_dictionary[origin] # figure out the price from the dictionary.
    r = (df1['val1'][ind] + df1['val2'][ind])*price # this is the needed calculation
    destination = df1['destination'][ind] # store the result in destination
    if(destination in result.keys()):
        result[destination] = result[destination]+r
    else:
        result[destination] = r
f = open("result.csv", "w")
for key in result:
    f.write(key+","+str(result[key])+"\n")
f.close()
</code>```

This is lot of work and doesn't use the pandas inbuilt functions. How do I simplify this? I'm not that worried about efficiency.

答:
Your problem can be solved with map and then groupby:

```<code>df1['total'] = (df1[['val1','val2']].sum(1)
                   .mul(df1['origin']
                            .map(df2.set_index('org').price)
                       )
               )

summary = df1.groupby('destination')['total'].sum()

# save to csv
summary.to_csv('/path/to/file.csv')
</code>```

Output (summary):

```<code>destination
A    134.5
B     53.5
c     57.0
Name: total, dtype: float64
</code>```

Body:
I have the following two (simplified) dataframes with me:

df1=
         origin destination  val1  val2
    0      1           A      0.8   0.9
    1      1           B      0.3   0.5
    2      1           c      0.4   0.2
    3      2           A      0.4   0.7
    4      2           B      0.2   0.1
    5      2           c      0.5   0.1
df2=
  org  price
0   1     50
1   2     45

what I need to do is to select the price from each origin from df2, multiply it by the sum of val1+val2 in df1 and write it to a csv file.

The calculation for A is as follows:

A => (0.8+0.9)* 50 + (0.4+ 0.7)* 45   = 134.5

here, the values 0.8, 0.9, 0.4 and 0.7 are coming from df1 and they correspond to val1 and val2 of A
where as the values 50 and 45 come from df2 corresponding to origin 1 and 2 respectively.
for B the calculation would be

B => (0.3+0.5)*50 + (0.2+0.1)*45 = 53.5

for C the calculation would be:

C => (0.4+0.2)*50 + (0.5+0.1)*45 = 57

The final CSV file should look like:

A,134.5

B,53.5

C,57
I've written the following python code for that:

# first convert the second table into a python dictionary so that I can refer price value at each origin
df2_dictionary = {}
for ind in df2.index:
    df2_dictionary[df2['org'][ind]] = float(df2['price'][ind])

# now go through df1, add up val1 and val2 and add the result to the result dictionary.
result = {}
for ind in df1.index:
    origin = df1['origin'][ind]
    price = df2_dictionary[origin] # figure out the price from the dictionary.
    r = (df1['val1'][ind] + df1['val2'][ind])*price # this is the needed calculation
    destination = df1['destination'][ind] # store the result in destination
    if(destination in result.keys()):
        result[destination] = result[destination]+r
    else:
        result[destination] = r
f = open("result.csv", "w")
for key in result:
    f.write(key+","+str(result[key])+"\n")
f.close()

This is lot of work and doesn't use the pandas inbuilt functions. How do I simplify this? I'm not that worried about efficiency.

Body:
Your problem can be solved with map and then groupby:

df1['total'] = (df1[['val1','val2']].sum(1)
                   .mul(df1['origin']
                            .map(df2.set_index('org').price)
                       )
               )

summary = df1.groupby('destination')['total'].sum()

# save to csv
summary.to_csv('/path/to/file.csv')

Output (summary):

destination
A    134.5
B     53.5
c     57.0
Name: total, dtype: float64


来源: stackexchange

问:
Check if object is all painted
I have a brown sprite, which contains a hole with triangular shape.

I've added a trail renderer (and set its order in layer to appear behind the sprite), so the user can paint the sprite's hole without painting the sprite itself.

My question is: how can it detect when the hole is all painted?

I thought about using a shader to check if there is any black pixel in the screen, but I don't know if it's possible, because the shader won't know in what percentage of the image it is.

答:
One way would be to take a screenshot with the ScreenCapture.CaptureScreenshotAsTexture method and then loop through an array of pixel colors from Texture2D.GetPixels32. You could then check if the array contains 'black' pixels.

I would do it in a coroutine for better performance as doing it every frame may slow down your application. Also what is important when it comes to CaptureScreenshotAsTexture according to unity docs:

To get a reliable output from this method you must make sure it is called once the frame rendering has ended, and not during the rendering process. A simple way of ensuring this is to call it from a coroutine that yields on WaitForEndOfFrame. If you call this method during the rendering process you will get unpredictable and undefined results.

ContentLicense: CC BY-SA 4.0

Title: Check if object is all painted


问:
Can I load XML response after XSLT transformation
I am transforming an XML Response with the XSLT attached in the header with no problem at all. I can access the HTML DOM with Javascript as well. What I want to achieve is to load the original xml AFTER the transformation is completed in the browser. Take in account that I am not getting an XML Response from AJAX but as a Page Load. So far what I have done is to replicate the xml dom inside a hidden div during the transformation but I would prefer a more efficient and elegant solution. Thx in advance.

答:
The solution had to come from the server, instead of using a XML as response now I save the XML Document as a file, with the link to the XSLT, and then redirect to this new xml file. This way I can retrieve the xml from the window.location.href as suggested by Martin Honnen

Then I can load the xml to process with JS and XSLTProcessor to produce the new content on the client. No jQuery or Framewoek needed.

PS. I also change the history URI in case the user needs to refresh the content


问:
IBM BPM 8.5 Multi-instance sequence flow by custom order
Have loan task (see example below)  which is separating by multi-instance loop:

```<code>loans[
   [loanNo:1, dueDate: 2020-10-10],
   [loanNo:2, dueDate: 2020-05-05],
   [loanNo:3, dueDate: 2020-07-07]
]
</code>```

How to make sequence loop to loop by custom order, not by index (0,1,2) but by dueDate so that first element will be closest date 2020-05-05, then 2020-07-07 and etc..

答:
You will have to order your array by dueDate after to pass it to your multi-instance loop.

You could insert in your process a script step before your multi-instance task that do this ordering:

```<code>tw.local.orderedLoans = loans.sort(function(a, b) {
  return a.dueDate.localeCompare(b.dueDate)
});
</code>```

And then pass the tw.local.orderedLoans to the task

Body:
Have loan task (see example below)  which is separating by multi-instance loop:

loans[
   [loanNo:1, dueDate: 2020-10-10],
   [loanNo:2, dueDate: 2020-05-05],
   [loanNo:3, dueDate: 2020-07-07]
]

How to make sequence loop to loop by custom order, not by index (0,1,2) but by dueDate so that first element will be closest date 2020-05-05, then 2020-07-07 and etc..

Body:
You will have to order your array by dueDate after to pass it to your multi-instance loop.

You could insert in your process a script step before your multi-instance task that do this ordering:

tw.local.orderedLoans = loans.sort(function(a, b) {
  return a.dueDate.localeCompare(b.dueDate)
});

And then pass the tw.local.orderedLoans to the task


问:
RFM Analysis - Value keeps changing
Got the following query going.

```<code>SELECT
    customer_id,
    NTILE(5) OVER (ORDER BY MAX(oms_order_date)) AS r_score
FROM
    mdwh.us_raw.l_dmw_order_report
WHERE
    quantity_ordered > 0
    AND customer_id IS NOT NULL
    AND customer_id != ('')
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND extended_amount < 1000 --NO BULK ORDERS
    AND oms_order_date BETWEEN '2020-01-01' AND '2020-01-01'
    AND SUBSTRING(upc,1,6) IN (SELECT item_code FROM item_master_zs WHERE new_division BETWEEN '11' AND '39')
GROUP BY
    customer_id
ORDER BY
    customer_id
</code>```

All I'm doing here is, given some conditions, to give me the unique customer ID, then cluster their latest purchase date into quintiles and provide me with a score in the second column. But everytime I run the query, the r_score value keeps changing? What am I doing wrong..? Here's a snippet of what the table looks like (again, r_score value keeps changing):

答:
The problem with ntile() is that it ensures that the groups are exactly the same size by putting the same value across different groups.

For this reason, I usually do the calculation manually, using rank():

```<code>ceil(rank() over (order by max(oms_order_date)) * 5.0 /
     count(*) over ()
    ) as r_score
</code>```

If you use row_number(), you'll get the equivalent of ntile().

If you want to use ntile(), you can use additional order by keys so the sorting keys are unique.

===================

2/17/20 5:18PM EDIT

Here is the new code I'm using:

```<code>SELECT
    customer_id,
    CEIL(RANK() OVER (ORDER BY MAX(oms_order_date)) * 5 / COUNT(*) OVER ()) AS r_score,
    CEIL(RANK() OVER (ORDER BY COUNT(client_web_order_number)) * 5 / COUNT(*) OVER ()) AS f_score,
    CEIL(RANK() OVER (ORDER BY AVG(extended_amount)) * 5 / COUNT(*) OVER ()) AS m_score,
    (r_score || f_score || m_score) AS rfm_score
FROM
    mdwh.us_raw.l_dmw_order_report t1
WHERE
    quantity_ordered > 0
    AND customer_id IS NOT NULL
    AND customer_id != ('')
    AND oms_order_date IS NOT NULL
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND extended_amount < 1000 --NO BULK ORDERS
    AND oms_order_date BETWEEN '2020-01-01' AND '2020-01-10'
    AND SUBSTRING(upc,1,6) IN (SELECT item_code FROM item_master_zs WHERE new_division BETWEEN '11' AND '39')
GROUP BY
    customer_id
ORDER BY
    customer_id
</code>```

The issue now is that I'm getting some row's with a blank r_score, and the max value is 4 instead of 5..

Title: RFM Analysis - Value keeps changing

Body:
Got the following query going.

SELECT
    customer_id,
    NTILE(5) OVER (ORDER BY MAX(oms_order_date)) AS r_score
FROM
    mdwh.us_raw.l_dmw_order_report
WHERE
    quantity_ordered > 0
    AND customer_id IS NOT NULL
    AND customer_id != ('')
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND extended_amount < 1000 --NO BULK ORDERS
    AND oms_order_date BETWEEN '2020-01-01' AND '2020-01-01'
    AND SUBSTRING(upc,1,6) IN (SELECT item_code FROM item_master_zs WHERE new_division BETWEEN '11' AND '39')
GROUP BY
    customer_id
ORDER BY
    customer_id

All I'm doing here is, given some conditions, to give me the unique customer ID, then cluster their latest purchase date into quintiles and provide me with a score in the second column. But everytime I run the query, the r_score value keeps changing? What am I doing wrong..? Here's a snippet of what the table looks like (again, r_score value keeps changing):

Body:
The problem with ntile() is that it ensures that the groups are exactly the same size by putting the same value across different groups.

For this reason, I usually do the calculation manually, using rank():

ceil(rank() over (order by max(oms_order_date)) * 5.0 /
     count(*) over ()
    ) as r_score

If you use row_number(), you'll get the equivalent of ntile().

If you want to use ntile(), you can use additional order by keys so the sorting keys are unique.

===================

2/17/20 5:18PM EDIT

Here is the new code I'm using:

SELECT
    customer_id,
    CEIL(RANK() OVER (ORDER BY MAX(oms_order_date)) * 5 / COUNT(*) OVER ()) AS r_score,
    CEIL(RANK() OVER (ORDER BY COUNT(client_web_order_number)) * 5 / COUNT(*) OVER ()) AS f_score,
    CEIL(RANK() OVER (ORDER BY AVG(extended_amount)) * 5 / COUNT(*) OVER ()) AS m_score,
    (r_score || f_score || m_score) AS rfm_score
FROM
    mdwh.us_raw.l_dmw_order_report t1
WHERE
    quantity_ordered > 0
    AND customer_id IS NOT NULL
    AND customer_id != ('')
    AND oms_order_date IS NOT NULL
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND extended_amount < 1000 --NO BULK ORDERS
    AND oms_order_date BETWEEN '2020-01-01' AND '2020-01-10'
    AND SUBSTRING(upc,1,6) IN (SELECT item_code FROM item_master_zs WHERE new_division BETWEEN '11' AND '39')
GROUP BY
    customer_id
ORDER BY
    customer_id

The issue now is that I'm getting some row's with a blank r_score, and the max value is 4 instead of 5..


问:
iPhone - Using a static Library?
I created a static library project which generates an "a" file.
I included this "a" file to another project as a static library.

The only way I could use the classes in this static library was to copy all header filed over as well as the "a" file.

Is it possible to avoid copying the header files, and still be able to use and import classes from this static library?

答:
Not really, you have to declare the functions somewhere visible to the caller. Header file is the most convenient way to do it, because it provides an interface. A possible approach is to merge those headers into one .h file, so you provide a single and complete interface with your library.

The only other approach I can think about is declaring the functions in the files where you call them, but this is much more devastating and error prone then including a header file.

ContentLicense: CC BY-SA 3.0

Title: iPhone - Using a static Library?


问:
Postgres jsonb Index Format
I'm trying to find the name for these type of indexes. I looked on Google and Postgres documentation and they have nothing on what Value-> operator does. And how its different from a regular: -> SomeInt.

```<code>CREATE INDEX "someIndex" ON "me-db"."someTable" USING btree ((((jsondata -> 'SomeInt'::text) -> 'HasValue'::text)))
CREATE INDEX "someIndex2" ON "me-db"."someTable" USING btree ((((jsondata -> 'SomeInt'::text) -> 'Value'::text)))
</code>```

What are the names for ->HasValue and ->Value operators? How is ->Value different from ->Field.

答:
Those are called expressional or (more commonly but less correctly) functional indexes.

You are not using ->Value, you are using ->'Value'. Those are different things.  The fist would be looking for a column named "value", and using its contents as the name of the key to look for.  The second uses the literal string 'Value' as the name of the key to look for.

Title: Postgres jsonb Index Format

Body:
I'm trying to find the name for these type of indexes. I looked on Google and Postgres documentation and they have nothing on what Value-> operator does. And how its different from a regular: -> SomeInt.

CREATE INDEX "someIndex" ON "me-db"."someTable" USING btree ((((jsondata -> 'SomeInt'::text) -> 'HasValue'::text)))
CREATE INDEX "someIndex2" ON "me-db"."someTable" USING btree ((((jsondata -> 'SomeInt'::text) -> 'Value'::text)))

What are the names for ->HasValue and ->Value operators? How is ->Value different from ->Field.


问:
Angular Routing not working when adding ID as a parameter in URL
new to Angular here. I have the following in my app.module.ts

```<code>RouterModule.forRoot()
{
...
      {
        path : "posts/:id",
        component: PostprofileComponent
      },
      {
        path : "posts",
        component: PostsComponent
      },
...
}
</code>```

The following is redirecting correctly to PostprofileComponent.

http://localhost:4200/posts/2

However this link does not... it redirects to PostsComponent.

http://localhost:4200/posts?id=2

Shouldn't they behave the same? What am i doing wrong?

答:
The second option is using url query parameters while the first option is using angular routing parameters.

i.e. using this:

```<code>   this.router.navigate(['/posts', '2']);
</code>```

would result in your first route http://localhost:4200/posts/2

and then this:

```<code>this.router.navigate(['/posts'], { queryParams: { id: '2' } });
</code>```

would result in second route http://localhost:4200/posts?id=2

Body:
new to Angular here. I have the following in my app.module.ts

RouterModule.forRoot()
{
...
      {
        path : "posts/:id",
        component: PostprofileComponent
      },
      {
        path : "posts",
        component: PostsComponent
      },
...
}

The following is redirecting correctly to PostprofileComponent.

http://localhost:4200/posts/2

However this link does not... it redirects to PostsComponent.

http://localhost:4200/posts?id=2

Shouldn't they behave the same? What am i doing wrong?

Body:
The second option is using url query parameters while the first option is using angular routing parameters.

i.e. using this:

   this.router.navigate(['/posts', '2']);

would result in your first route http://localhost:4200/posts/2

and then this:

this.router.navigate(['/posts'], { queryParams: { id: '2' } });

would result in second route http://localhost:4200/posts?id=2


问:
dotnet core 2.2 EntityFramework with postgres
I followed the documentation on Postgres C# website.

When I run this code I get:

The entity type 'Bar' requires a primary key to be defined.

POCOs:

```<code>public class Foo
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Name { get; set; }

    [Column(TypeName = "jsonb")]
    public Bar Bar { get; set; }
}

public class Bar
{
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }
}
</code>```

My goal is to avoid using string as a property type of Bar and let the entity framework handle JSON serialize, deserialize. I don't want the Bar to be a separate table. I want it to be a JSON column on Foo.

答:
I ran into this issue with .NET Core 2.1 and MySQL and this is what resolved it for me. I'm not able to update to 3.0 at this time. Adding Ignore was the part that solved my problem.</p>

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Ignore<Bar>();

        modelBuilder.Entity<Foo>()
           .Property(x => x.Bar)
           .HasConversion(
                v => JsonConvert.SerializeObject(v),
                v => JsonConvert.DeserializeObject<Bar>(v))
           .HasColumnType("json");
    }
</code>```

Body:
I followed the documentation on Postgres C# website.

When I run this code I get:

The entity type 'Bar' requires a primary key to be defined.

POCOs:

public class Foo
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Name { get; set; }

    [Column(TypeName = "jsonb")]
    public Bar Bar { get; set; }
}

public class Bar
{
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }
}

My goal is to avoid using string as a property type of Bar and let the entity framework handle JSON serialize, deserialize. I don't want the Bar to be a separate table. I want it to be a JSON column on Foo.

Body:
I ran into this issue with .NET Core 2.1 and MySQL and this is what resolved it for me. I'm not able to update to 3.0 at this time. Adding Ignore was the part that solved my problem.

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Ignore<Bar>();

        modelBuilder.Entity<Foo>()
           .Property(x => x.Bar)
           .HasConversion(
                v => JsonConvert.SerializeObject(v),
                v => JsonConvert.DeserializeObject<Bar>(v))
           .HasColumnType("json");
    }


问:
Visualizing sorting algorithm isn't working
I am trying to create a website which shows different sorting-algorithms by presenting the values of the array as bars and then sorting the array while updating the view.

I've got a method drawArray() which creats the bars and appends them to my content-div.
This method is called after every step of the sorting-algorithm, but it isn't showing the update on the website, instead, it just updates the view, when the sorting-algorithm is finished.

I assume there is an issue with updating the html from within a method or something, but I haven't figured out a way around this problem. Does anybody know how I could show the progress of the sorting?

This is my bubbleSort()-method:

```<code>var bubbleSort = function () {
    var n = array.length;
    do {
        swapped = false;
        for (var i = 0; i < n - 1; i++) {
            if (array[i] > array[i + 1]) {
                var temp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = temp;
                swapped = true;
            }
            drawArray(null, null);
        }
        n = n - 1;
    } while (swapped)
}
</code>```

with the drawArray-method call after each step.

Here is the drawArray()-method:
It could get two variables but this was only for testing, the method would highlight these two divs in a different color, but in the normal case, I just pass null so they appear black.

```<code>var drawArray = function (num1, num2) {
    document.getElementById('content').innerHTML = '';
    for (var i = 0; i < array.length; i++) {
        document.getElementById('content').appendChild(divs[i]);
        if (num1 == array[i]) {
            setDiv(divs[i], array[i], "red");
        } else {
            if (num2 == array[i]) {
                setDiv(divs[i], array[i], "blue");
            } else {
                setDiv(divs[i], array[i], "black");
            }
        }
    }
}
</code>```

This is the setDiv-method which is called inside drawArray(), it basically just changes the height and color of the div:

```<code>var setDiv = function (div, height, farbe) {
   div.setAttribute('style', "color: white; font-family: Arial; height: " +
   height + "px; width: 10px; background-color: " + farbe + "; margin-left: 2px;
   margin-right: 5px; display: inline-block; vertical-align: top;");
}
</code>```

I am thankful for every help :)

EDIT: The problem seems to be that it is working too fast, so I need to delay each step of the sorting-algorithm. How can I do that?

答:
The simplest way is using setTimeount and operation counter. If you want to change array step by step. You can emulate for and while in interval;</p>

```<code>var bubbleSort = function () {
    var n = array.length;
    var timeout = 1000;
    var swapped = false;
    var i = 0;
    var interval = setInterval(function() {
        if (i >= n - 1) {
            n--;
            if (n === 1 || !swapped) {
                clearInterval(interval);
                return;
            }
            swapped = false;
            i = 0;
        }
        if (array[i] > array[i + 1]) {
            var temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
            swapped = true;
        }
        drawArray(null, null);
        i++;
    }, timeout);
}
</code>```

Body:
I am trying to create a website which shows different sorting-algorithms by presenting the values of the array as bars and then sorting the array while updating the view.

I've got a method drawArray() which creats the bars and appends them to my content-div.
This method is called after every step of the sorting-algorithm, but it isn't showing the update on the website, instead, it just updates the view, when the sorting-algorithm is finished.

I assume there is an issue with updating the html from within a method or something, but I haven't figured out a way around this problem. Does anybody know how I could show the progress of the sorting?

This is my bubbleSort()-method:

var bubbleSort = function () {
    var n = array.length;
    do {
        swapped = false;
        for (var i = 0; i < n - 1; i++) {
            if (array[i] > array[i + 1]) {
                var temp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = temp;
                swapped = true;
            }
            drawArray(null, null);
        }
        n = n - 1;
    } while (swapped)
}

with the drawArray-method call after each step.

Here is the drawArray()-method:
It could get two variables but this was only for testing, the method would highlight these two divs in a different color, but in the normal case, I just pass null so they appear black.

var drawArray = function (num1, num2) {
    document.getElementById('content').innerHTML = '';
    for (var i = 0; i < array.length; i++) {
        document.getElementById('content').appendChild(divs[i]);
        if (num1 == array[i]) {
            setDiv(divs[i], array[i], "red");
        } else {
            if (num2 == array[i]) {
                setDiv(divs[i], array[i], "blue");
            } else {
                setDiv(divs[i], array[i], "black");
            }
        }
    }
}

This is the setDiv-method which is called inside drawArray(), it basically just changes the height and color of the div:

var setDiv = function (div, height, farbe) {
   div.setAttribute('style', "color: white; font-family: Arial; height: " +
   height + "px; width: 10px; background-color: " + farbe + "; margin-left: 2px;
   margin-right: 5px; display: inline-block; vertical-align: top;");
}

I am thankful for every help :)

EDIT: The problem seems to be that it is working too fast, so I need to delay each step of the sorting-algorithm. How can I do that?

Body:
The simplest way is using setTimeount and operation counter. If you want to change array step by step. You can emulate for and while in interval;

var bubbleSort = function () {
    var n = array.length;
    var timeout = 1000;
    var swapped = false;
    var i = 0;
    var interval = setInterval(function() {
        if (i >= n - 1) {
            n--;
            if (n === 1 || !swapped) {
                clearInterval(interval);
                return;
            }
            swapped = false;
            i = 0;
        }
        if (array[i] > array[i + 1]) {
            var temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
            swapped = true;
        }
        drawArray(null, null);
        i++;
    }, timeout);
}


问:
Turn off or configure java.util.Logging during Maven build
I want to clean up/unify the log output of a Maven build. Unfortunately, a dependency of a maven plugin uses java.util.Logging (JUL). Simply adding org.slf4j:jul-to-slf4j as an additional dependency to redirect the log output doesn't help. Exclusions also don't work of course, because it's JUL and therefore not a dependency.
Here's my configuration, containing the specific plugin and its dependency:

Configuration

```<code><plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>2.7.11</version>
    <executions>...</executions>
    <configuration>
        <defaultOptions>
            <extraargs>
                <extraarg>-xjc-Xbg</extraarg>
            </extraargs>
        </defaultOptions>
    </configuration>
    <dependencies>
        <!-- This one uses JUL with logging level WARN -->
        <dependency>
            <groupId>org.apache.cxf.xjcplugins</groupId>
            <artifactId>cxf-xjc-boolean</artifactId>
            <version>2.7.0</version>
        </dependency>
    </dependencies>
</plugin>
</code>```

Update

I've managed to turn off/configure JUL itself by adding a logging.properties file with the following content to the project's root folder:

```<code># Turn off any java.util.Loggers (or use SEVERE to see problems)
.level=OFF
</code>```

Additionally, I have to execute Maven with the following parameter (or set it into MAVEN_OPTS):

```<code>mvn clean install -Djava.util.logging.config.file=${basedir}/logging.properties
</code>```

Remaining Question

Is there any way to achieve the same result without extra files and/or JVM parameters (pom.xml only)?

答:
Following configuration for the plugin cxf-codegen-plugin prevented to show DEBUG log entries when building my project with maven:</p>

```<code><configuration>
  <fork>once</fork>
  <additionalJvmArgs>
    -Dorg.apache.cxf.Logger=null
  </additionalJvmArgs>
</configuration>
</code>```

Body:
I want to clean up/unify the log output of a Maven build. Unfortunately, a dependency of a maven plugin uses java.util.Logging (JUL). Simply adding org.slf4j:jul-to-slf4j as an additional dependency to redirect the log output doesn't help. Exclusions also don't work of course, because it's JUL and therefore not a dependency.
Here's my configuration, containing the specific plugin and its dependency:

Configuration

<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>2.7.11</version>
    <executions>...</executions>
    <configuration>
        <defaultOptions>
            <extraargs>
                <extraarg>-xjc-Xbg</extraarg>
            </extraargs>
        </defaultOptions>
    </configuration>
    <dependencies>

        <dependency>
            <groupId>org.apache.cxf.xjcplugins</groupId>
            <artifactId>cxf-xjc-boolean</artifactId>
            <version>2.7.0</version>
        </dependency>
    </dependencies>
</plugin>

Update

I've managed to turn off/configure JUL itself by adding a logging.properties file with the following content to the project's root folder:

# Turn off any java.util.Loggers (or use SEVERE to see problems)
.level=OFF

Additionally, I have to execute Maven with the following parameter (or set it into MAVEN_OPTS):

mvn clean install -Djava.util.logging.config.file=${basedir}/logging.properties

Remaining Question

Is there any way to achieve the same result without extra files and/or JVM parameters (pom.xml only)?

Body:
Following configuration for the plugin cxf-codegen-plugin prevented to show DEBUG log entries when building my project with maven:

<configuration>
  <fork>once</fork>
  <additionalJvmArgs>
    -Dorg.apache.cxf.Logger=null
  </additionalJvmArgs>
</configuration>


问:
Why use spring.factories for Spring Boot auto-configuration instead of annotations?
The documentation states:

Developing auto-configuration and using conditions

If you work in a company that develops shared libraries, or if you work on an open-source or commercial library, you might want to develop your own auto-configuration. Auto-configuration classes can be bundled in external jars and still be picked-up by Spring Boot.

If I have annotations for everything else (even  @AutoConfigureAfter or @AutoConfigureBefore annotations),

Why maintain a properties file to point to a class with an annotation?

答:
all the entries in spring.factories are loaded by below method -

org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelector#loadFactoryNames

```<code>protected Collection<String> loadFactoryNames(Class<?> source) {
        return SpringFactoriesLoader.loadFactoryNames(source, getClass().getClassLoader());
    }
</code>```

SpringFactoriesLoader belongs to the spring-core library see below screen shot

Body:
all the entries in spring.factories are loaded by below method -

org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelector#loadFactoryNames

protected Collection<String> loadFactoryNames(Class<?> source) {
        return SpringFactoriesLoader.loadFactoryNames(source, getClass().getClassLoader());
    }

SpringFactoriesLoader belongs to the spring-core library see below screen shot


问:
How can I get sqlite working on a shared hosting server?
I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.

anyhow, when I run the script below, I am getting ImportError: No module named _sqlite3 and I'm not sure what to do to fix this.

Most online threads mention that sqlite / sqlite3 is included in python 2.6 - so I'm not sure why this isn't working.

```
-jailshell-3.2$ ./pyDropboxValues.py

Traceback (most recent call last):
  File "./pyDropboxValues.py", line 21, in
    import sqlite3
  File "/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py", line 24, in
    from dbapi2 import *
  File "/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in
    from _sqlite3 import *
<b>ImportError: No module named _sqlite3</b>
```

I think I have everything set up right as far as the directory structure.

```
-jailshell-3.2$ find `pwd` -type d

/home/myAccount/opt
/home/myAccount/opt/bin
/home/myAccount/opt/include
/home/myAccount/opt/include/python2.6
/home/myAccount/opt/lib
/home/myAccount/opt/lib/python2.6
/home/myAccount/opt/lib/python2.6/distutils
/home/myAccount/opt/lib/python2.6/distutils/command
/home/myAccount/opt/lib/python2.6/distutils/tests
/home/myAccount/opt/lib/python2.6/compiler
/home/myAccount/opt/lib/python2.6/test
/home/myAccount/opt/lib/python2.6/test/decimaltestdata
/home/myAccount/opt/lib/python2.6/config
/home/myAccount/opt/lib/python2.6/json
/home/myAccount/opt/lib/python2.6/json/tests
/home/myAccount/opt/lib/python2.6/email
/home/myAccount/opt/lib/python2.6/email/test
/home/myAccount/opt/lib/python2.6/email/test/data
/home/myAccount/opt/lib/python2.6/email/mime
/home/myAccount/opt/lib/python2.6/lib2to3
/home/myAccount/opt/lib/python2.6/lib2to3/pgen2
/home/myAccount/opt/lib/python2.6/lib2to3/fixes
/home/myAccount/opt/lib/python2.6/lib2to3/tests
/home/myAccount/opt/lib/python2.6/xml
/home/myAccount/opt/lib/python2.6/xml/parsers
/home/myAccount/opt/lib/python2.6/xml/sax
/home/myAccount/opt/lib/python2.6/xml/etree
/home/myAccount/opt/lib/python2.6/xml/dom
/home/myAccount/opt/lib/python2.6/site-packages
/home/myAccount/opt/lib/python2.6/logging
/home/myAccount/opt/lib/python2.6/lib-dynload
/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/test
/home/myAccount/opt/lib/python2.6/encodings
/home/myAccount/opt/lib/python2.6/wsgiref
/home/myAccount/opt/lib/python2.6/multiprocessing
/home/myAccount/opt/lib/python2.6/multiprocessing/dummy
/home/myAccount/opt/lib/python2.6/curses
/home/myAccount/opt/lib/python2.6/bsddb
/home/myAccount/opt/lib/python2.6/bsddb/test
/home/myAccount/opt/lib/python2.6/idlelib
/home/myAccount/opt/lib/python2.6/idlelib/Icons
/home/myAccount/opt/lib/python2.6/tmp
/home/myAccount/opt/lib/python2.6/lib-old
/home/myAccount/opt/lib/python2.6/lib-tk
/home/myAccount/opt/lib/python2.6/hotshot
/home/myAccount/opt/lib/python2.6/plat-linux2
/home/myAccount/opt/lib/python2.6/ctypes
/home/myAccount/opt/lib/python2.6/ctypes/test
/home/myAccount/opt/lib/python2.6/ctypes/macholib
/home/myAccount/opt/share
/home/myAccount/opt/share/man
/home/myAccount/opt/share/man/man1

```

And finally the contents of the sqlite3 directory:

```
-jailshell-3.2$ find `pwd`

/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.py

```

I feel like I need to add something into the sqlite3 directory - maybe sqlite3.so? But I don't know where to get that.

What am I doing wrong here? Please remember that I'm using a shared host so that means installing / compiling on another server and then copying the files over. Thanks! :)

Update
Just wanted to confirm that the answer from @samplebias did work out very well. I needed to have the dev package installed on the machine I was compiling from to get it to add in sqlite3.so and related files. Also found the link in the answer very helpful. Thanks @samplebias !

答:
Python's build system uses a setup.py file to compile all of the native extensions, including sqlite3. It searches common operating system paths for the sqlite3 include and library dirs. If the sqlite3 development package is not installed Python will skip compiling the _sqlite3.so extension, but the pure Python portion of the sqlite3 package will still be installed.

You would need to have the operating system's sqlite3 development package installed when you compile Python and at runtime: sqlite3-devel on Centos, both libsqlite3-0 and libsqlite3-dev on Ubuntu.

Here's an example of the _sqlite3.so extension linkage on my Ubuntu system:

```<code>% ldd /usr/lib/python2.6/lib-dynload/_sqlite3.so | grep sqlite3
    libsqlite3.so.0 => /usr/lib/libsqlite3.so.0 (0x00007f29ef3be000)
% dpkg -S /usr/lib/libsqlite3.so.0
    libsqlite3-0: /usr/lib/libsqlite3.so.0
</code>```

Body:
I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.

anyhow, when I run the script below, I am getting ImportError: No module named _sqlite3 and I'm not sure what to do to fix this.

Most online threads mention that sqlite / sqlite3 is included in python 2.6 - so I'm not sure why this isn't working.

-jailshell-3.2$ ./pyDropboxValues.py

Traceback (most recent call last):
  File "./pyDropboxValues.py", line 21, in
    import sqlite3
  File "/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py", line 24, in
    from dbapi2 import *
  File "/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in
    from _sqlite3 import *
ImportError: No module named _sqlite3

I think I have everything set up right as far as the directory structure.

-jailshell-3.2$ find `pwd` -type d

/home/myAccount/opt
/home/myAccount/opt/bin
/home/myAccount/opt/include
/home/myAccount/opt/include/python2.6
/home/myAccount/opt/lib
/home/myAccount/opt/lib/python2.6
/home/myAccount/opt/lib/python2.6/distutils
/home/myAccount/opt/lib/python2.6/distutils/command
/home/myAccount/opt/lib/python2.6/distutils/tests
/home/myAccount/opt/lib/python2.6/compiler
/home/myAccount/opt/lib/python2.6/test
/home/myAccount/opt/lib/python2.6/test/decimaltestdata
/home/myAccount/opt/lib/python2.6/config
/home/myAccount/opt/lib/python2.6/json
/home/myAccount/opt/lib/python2.6/json/tests
/home/myAccount/opt/lib/python2.6/email
/home/myAccount/opt/lib/python2.6/email/test
/home/myAccount/opt/lib/python2.6/email/test/data
/home/myAccount/opt/lib/python2.6/email/mime
/home/myAccount/opt/lib/python2.6/lib2to3
/home/myAccount/opt/lib/python2.6/lib2to3/pgen2
/home/myAccount/opt/lib/python2.6/lib2to3/fixes
/home/myAccount/opt/lib/python2.6/lib2to3/tests
/home/myAccount/opt/lib/python2.6/xml
/home/myAccount/opt/lib/python2.6/xml/parsers
/home/myAccount/opt/lib/python2.6/xml/sax
/home/myAccount/opt/lib/python2.6/xml/etree
/home/myAccount/opt/lib/python2.6/xml/dom
/home/myAccount/opt/lib/python2.6/site-packages
/home/myAccount/opt/lib/python2.6/logging
/home/myAccount/opt/lib/python2.6/lib-dynload
/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/test
/home/myAccount/opt/lib/python2.6/encodings
/home/myAccount/opt/lib/python2.6/wsgiref
/home/myAccount/opt/lib/python2.6/multiprocessing
/home/myAccount/opt/lib/python2.6/multiprocessing/dummy
/home/myAccount/opt/lib/python2.6/curses
/home/myAccount/opt/lib/python2.6/bsddb
/home/myAccount/opt/lib/python2.6/bsddb/test
/home/myAccount/opt/lib/python2.6/idlelib
/home/myAccount/opt/lib/python2.6/idlelib/Icons
/home/myAccount/opt/lib/python2.6/tmp
/home/myAccount/opt/lib/python2.6/lib-old
/home/myAccount/opt/lib/python2.6/lib-tk
/home/myAccount/opt/lib/python2.6/hotshot
/home/myAccount/opt/lib/python2.6/plat-linux2
/home/myAccount/opt/lib/python2.6/ctypes
/home/myAccount/opt/lib/python2.6/ctypes/test
/home/myAccount/opt/lib/python2.6/ctypes/macholib
/home/myAccount/opt/share
/home/myAccount/opt/share/man
/home/myAccount/opt/share/man/man1

And finally the contents of the sqlite3 directory:

-jailshell-3.2$ find `pwd`

/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.py

I feel like I need to add something into the sqlite3 directory - maybe sqlite3.so? But I don't know where to get that.

What am I doing wrong here? Please remember that I'm using a shared host so that means installing / compiling on another server and then copying the files over. Thanks! :)

Update
Just wanted to confirm that the answer from @samplebias did work out very well. I needed to have the dev package installed on the machine I was compiling from to get it to add in sqlite3.so and related files. Also found the link in the answer very helpful. Thanks @samplebias !

Body:
Python's build system uses a setup.py file to compile all of the native extensions, including sqlite3. It searches common operating system paths for the sqlite3 include and library dirs. If the sqlite3 development package is not installed Python will skip compiling the _sqlite3.so extension, but the pure Python portion of the sqlite3 package will still be installed.

You would need to have the operating system's sqlite3 development package installed when you compile Python and at runtime: sqlite3-devel on Centos, both libsqlite3-0 and libsqlite3-dev on Ubuntu.

Here's an example of the _sqlite3.so extension linkage on my Ubuntu system:

% ldd /usr/lib/python2.6/lib-dynload/_sqlite3.so | grep sqlite3
    libsqlite3.so.0 => /usr/lib/libsqlite3.so.0 (0x00007f29ef3be000)
% dpkg -S /usr/lib/libsqlite3.so.0
    libsqlite3-0: /usr/lib/libsqlite3.so.0


问:
Documenting a django project (django 2 + drf + drf-access-policy)
I'm documenting a django project that use DRF. I already generated a dynamic API schema using openapi and redoc. Very cool solutions

However, I miss the permissions part in all of this

I have a lot of permissions (permission_classes) in the viewsets and some functions. Do you know any solution to include the permission in the schema, or in a documentation in general?

Going further, how do you document permissions in a APIs in general?

I already have an idea: include the permissions in a custom description in the schema, but it's still dirty

Thanks. José.-

PS: Sorry for the poor english

答:
DRF is in the process of deprecating the use of the coreapi package, however currently there is not easy way within that solution to get security schemas to be added to your documentation.

However there is an alternative https://drf-yasg.readthedocs.io/en/stable/ this tool claims to support extracting these values (but I personally have not used it for that yet).


问:
How to get two-way binding in Blazor with a SELECT Component?
I am trying to write a Blazor component that uses a <select...>, to update the variable passed in from the parent.

I want to click on the drop-down (select/options), choose an option, and have that automatically update the variable in the parent.

I can get it to work if I don't use a component.  But the only way I can get it to work from a component is if I also use a button in the component (see the button in the Component code).  But eventually there will be several components called from the same parent.  It would not be practical to have a separate button for each component.  So the button has to go away.

The @bind uses the "onchange" parameter to the select, so that won't even compile.

I've tried CascadingValue/CascadingParam but that does not update the parent value either (unless I use a button...)

Here is the parent:

```<code>@page "/test"
@page "/test/{param}"

@namespace ComponentTest.Pages

@using System.Web
@using ComponentTest.Pages

<h3>Test Page</h3>

<div class="border col-3">
    <h4>Parent</h4>
    <hr />
    <label for="parentValue">Parent Value</label>
    <input id="parentValue" @bind="@param"/>
</div>
<div class="col-3">&nbsp</div>
<div class="border col-3">
    <h4>Component Select</h4>
    <hr />
    <SelectComponent @bind-Item="@param"/>
</div>

@code {
    [Parameter]
    public string param { get; set; }
}
</code>```

And here is the component:

```<code>@using System.Collections.Generic
@using System.Web

<div class="form-group">
    <p>Component Value = @Item</p>
    <label for="Site" class="font-weight-bold form-check-label">List</label>
    @if (list == null)
    {
        <input id="Item" class="form-control-sm" @bind="@Item" />
    }
    else
    {
        <select id="Item" class="form-control-sm" @bind="@Item">
            @foreach (var l in list)
            {
                @if (Item != null && String.Equals(l, Item, StringComparison.OrdinalIgnoreCase))
                {
                    <option selected value="@l">@l</option>
                }
                else
                {
                    <option value="@l">@l</option>
                }
            }
        </select>
    }
</div>
<button @onclick="UpdateParentsItem" class="btn btn-primary">Update Parent</button>
@code {
    public IEnumerable<string> list = new List<string>()
{
        "Item 1",
        "Item 2",
        "Item 3",
        "Item 4",
        "Item 5"
    };

    [Parameter]
    public string Item { get; set; }

    [Parameter]
    public EventCallback<string> ItemChanged { get; set; }

    private async Task UpdateParentsItem()
    {
        await ItemChanged.InvokeAsync(Item);
    }
}
</code>```

I followed a few groovy examples for implementing events but none that I found actually solved the problem.

答:
I give credit to @enet for the answer but here's my full solution with his(her?) bit included, and with an extra validation check:

Test.razor (Parent)

```<code>@page "/test"
@page "/test/{param}"

<h3>Select Component Test</h3>

<div class="border col-2">
    <h4>Parent</h4>
    <hr />
    <div class="form-group">
        <label for="parentValue">Parent Value</label>
        <input id="parentValue" type="text" class="form-control" @bind="@param" />
    </div>
</div>
<div class="col-3">&nbsp</div>
<div class="border col-2">
    <h4>Component</h4>
    <hr />
    <SelectComponent @bind-Item="@param" />
</div>
<hr />
<ul>Links
    <li><a href="/test/item 1">item 1</a></li>
    <li><a href="/test/ITEM 2">ITEM 2</a></li>
    <li><a href="/test/iTeM 3">iTeM 3</a></li>
    <li><a href="/test/ItEm 4">ItEm 4</a></li>
    <li><a href="/test/item 99">item 99</a></li>
</ul>
@code
{
    [Parameter]
    public string param { get; set; }
}
</code>```

SelectComponent.razor

```<code><!-- Select Component -->
<div class="form-group">
    @if (message != null)
    {
        <p class="text-warning">@message</p>
    }
    <label for="Item" class="form-check-label">Item</label>
    @if (list == null)
    {
        <input id="Item" class="form-control-sm" @bind="@Item" />
    }
    else
    {
        <select id="Item" class="form-control-sm" @bind="@Item">
            @foreach (var l in list)
            {
                <option value="@l">@l</option>
            }
        </select>
    }
</div>
@code {
    private string message;

    public IEnumerable<string> list = new List<string>()
    {
        "Item 1",
        "Item 2",
        "Item 3",
        "Item 4",
        "Item 5"
    };

    private string item { get; set; }

    [Parameter]
    public string Item
    {
        get { return item; }
        set
        {
            if (item != value)  // skip if it's the same string
            {
                if (list == null || list.Count() == 0)
                {
                    item = value;
                }
                else
                {
                    // validate the new item value against my list
                    foreach (var l in list)
                    {
                        if (value != null && String.Equals(l, value, StringComparison.OrdinalIgnoreCase))
                        {
                            item = l;   // match exact case to my list so "selected" option works properly
                            message = null;
                        }
                    }

                    // if there's no match, clear the item
                    if (!String.Equals(item, value, StringComparison.OrdinalIgnoreCase))
                    {
                        item = null;
                        message = "Invalid Item";
                    }
                }

                // make sure there is a parent
                if (ItemChanged.HasDelegate)
                {
                    // this is the magic that updates the parent
                    ItemChanged.InvokeAsync(item);
                }
            }
        }
    }

    [Parameter]
    public EventCallback<string> ItemChanged { get; set; }
}
</code>```

I will use this as a template for several Entity Framework based form validation dropdowns.

Body:
I am trying to write a Blazor component that uses a <select...>, to update the variable passed in from the parent.

I want to click on the drop-down (select/options), choose an option, and have that automatically update the variable in the parent.

I can get it to work if I don't use a component.  But the only way I can get it to work from a component is if I also use a button in the component (see the button in the Component code).  But eventually there will be several components called from the same parent.  It would not be practical to have a separate button for each component.  So the button has to go away.

The @bind uses the "onchange" parameter to the select, so that won't even compile.

I've tried CascadingValue/CascadingParam but that does not update the parent value either (unless I use a button...)

Here is the parent:

@page "/test"
@page "/test/{param}"

@namespace ComponentTest.Pages

@using System.Web
@using ComponentTest.Pages

Test Page

Parent

    Parent Value
    <input id="parentValue" @bind="@param"/>

&nbsp

Component Select

    <SelectComponent @bind-Item="@param"/>

@code {
    [Parameter]
    public string param { get; set; }
}

And here is the component:

@using System.Collections.Generic
@using System.Web

Component Value = @Item

    List
    @if (list == null)
    {
        <input id="Item" class="form-control-sm" @bind="@Item" />
    }
    else
    {
        <select id="Item" class="form-control-sm" @bind="@Item">
            @foreach (var l in list)
            {
                @if (Item != null && String.Equals(l, Item, StringComparison.OrdinalIgnoreCase))
                {
                    <option selected value="@l">@l</option>
                }
                else
                {
                    <option value="@l">@l</option>
                }
            }
        </select>
    }

<button @onclick="UpdateParentsItem" class="btn btn-primary">Update Parent</button>
@code {
    public IEnumerable<string> list = new List<string>()
{
        "Item 1",
        "Item 2",
        "Item 3",
        "Item 4",
        "Item 5"
    };

    [Parameter]
    public string Item { get; set; }

    [Parameter]
    public EventCallback<string> ItemChanged { get; set; }

    private async Task UpdateParentsItem()
    {
        await ItemChanged.InvokeAsync(Item);
    }
}

I followed a few groovy examples for implementing events but none that I found actually solved the problem.

Body:
I give credit to @enet for the answer but here's my full solution with his(her?) bit included, and with an extra validation check:

Test.razor (Parent)

@page "/test"
@page "/test/{param}"

<h3>Select Component Test</h3>

<div class="border col-2">
    <h4>Parent</h4>
    <hr />
    <div class="form-group">
        <label for="parentValue">Parent Value</label>
        <input id="parentValue" type="text" class="form-control" @bind="@param" />
    </div>
</div>
<div class="col-3">&nbsp</div>
<div class="border col-2">
    <h4>Component</h4>
    <hr />
    <SelectComponent @bind-Item="@param" />
</div>
<hr />
<ul>Links
    <li><a href="/test/item 1">item 1</a></li>
    <li><a href="/test/ITEM 2">ITEM 2</a></li>
    <li><a href="/test/iTeM 3">iTeM 3</a></li>
    <li><a href="/test/ItEm 4">ItEm 4</a></li>
    <li><a href="/test/item 99">item 99</a></li>
</ul>
@code
{
    [Parameter]
    public string param { get; set; }
}

SelectComponent.razor

<!-- Select Component -->
<div class="form-group">
    @if (message != null)
    {
        <p class="text-warning">@message</p>
    }
    <label for="Item" class="form-check-label">Item</label>
    @if (list == null)
    {
        <input id="Item" class="form-control-sm" @bind="@Item" />
    }
    else
    {
        <select id="Item" class="form-control-sm" @bind="@Item">
            @foreach (var l in list)
            {
                <option value="@l">@l</option>
            }
        </select>
    }
</div>
@code {
    private string message;

    public IEnumerable<string> list = new List<string>()
    {
        "Item 1",
        "Item 2",
        "Item 3",
        "Item 4",
        "Item 5"
    };

    private string item { get; set; }

    [Parameter]
    public string Item
    {
        get { return item; }
        set
        {
            if (item != value)  // skip if it's the same string
            {
                if (list == null || list.Count() == 0)
                {
                    item = value;
                }
                else
                {
                    // validate the new item value against my list
                    foreach (var l in list)
                    {
                        if (value != null && String.Equals(l, value, StringComparison.OrdinalIgnoreCase))
                        {
                            item = l;   // match exact case to my list so "selected" option works properly
                            message = null;
                        }
                    }

                    // if there's no match, clear the item
                    if (!String.Equals(item, value, StringComparison.OrdinalIgnoreCase))
                    {
                        item = null;
                        message = "Invalid Item";
                    }
                }

                // make sure there is a parent
                if (ItemChanged.HasDelegate)
                {
                    // this is the magic that updates the parent
                    ItemChanged.InvokeAsync(item);
                }
            }
        }
    }

    [Parameter]
    public EventCallback<string> ItemChanged { get; set; }
}

I will use this as a template for several Entity Framework based form validation dropdowns.


问:
iOS 13 Project without Storyboard displays funny
I have this project that is not using storyboards when I run it on my iPhone simulator it is not coming up full screen ?

答: This might be related to issue in launch screen. I also setup the project without storyboard but deleted the LaunchScreen.Storyboard as well and ended up getting the same screen as yours. After I recreated the project but leave the launchScreen file i was able to get the full screen display for my viewcontroller</p>


问:
How to get a string input from stdin that has leading white space in C?
Need a solution to get input string start with spaces?

I know a method to include space in input

```<code>scanf("%[^\n]s", s);
</code>```

But its working only for space between words.
I need a solution for string starts with spaces.
And I also need the starting spaces in the variable

答:
To get a line of user input, use fgets().

```<code>#define S_MAX_LENGTH
char s[S_MAX_LENGTH + 2];
if (fgets(s, sizeof s, stdin)) {
  s[strcspn(s, "\n")] = '\0'; // Should code want to lop off a potential trailing \n
  ....
</code>```

Do not use scanf("%[^\n]s", s); nor gets(s);.  They suffer from buffer overflow and other issues.

Body:
Need a solution to get input string start with spaces?

I know a method to include space in input

scanf("%[^\n]s", s);

But its working only for space between words.
I need a solution for string starts with spaces.
And I also need the starting spaces in the variable

Body:
To get a line of user input, use fgets().

#define S_MAX_LENGTH
char s[S_MAX_LENGTH + 2];
if (fgets(s, sizeof s, stdin)) {
  s[strcspn(s, "\n")] = '\0'; // Should code want to lop off a potential trailing \n
  ....

Do not use scanf("%[^\n]s", s); nor gets(s);.  They suffer from buffer overflow and other issues.


问:
Pressing button causes page to reload rather than run nessasary code?
I have a settings page in my website, the user edits his profile and then hits the update button which when properly working, like on chrome browser, will run certain code in the updateProfileData function. However in the firefox browser the page reloads as soon as I press the update button.

How can I prevent this and instead have the code I want run just like in chrome browser?

$('#update').on('click', event => {
  updateProfileData();
})

function updateProfileData() {
  //none of this will run because the page will instead reload
}

function pickFile() {
  fileButton.click()
}

function pickFile2() {
  fileButton2.click()
}

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  /* bottom: 0px;
  top: 0px; */
  width: 100%;
  height: 100%;
  margin:0px;

  font: Arial;
  font-family: sans-serif;
  font-weight:medium;

  text-align: center;

  /* bellow is to prevent all highlighting on the website. */
  -webkit-user-select: none; /* Chrome/Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+ */
}

/* #mp3Picker {
  color: grey;
} */

/* .middleSignUpDiv .container input {
  background-color: #F5F3F4;
  color: black;

  display: block;
  width: 390px;
  height: 125px;

  margin-left: auto;
  margin-right: auto;
  margin-top: 27px;
  margin-bottom: 17px;

  border-radius: 21px;
  border: none;

  padding-left: 15px;
  font-size: 0.95em;
  outline:none;

  border: solid transparent 2px;
} */

.justify {
  /* background-color: lightblue; */
  margin-top: 5px;
  display: flex;
  justify-content: center;
}

.soundscapeCaption:focus {
  border: solid #E2E2E2 2px;
}

.soundscapeCaption {
  /* margin-left: auto;
  margin-right: auto; */

  display: block;
  margin: 1px;
  padding: 1px;
  padding-left: 20px;
  padding-top: 20px;
  width: 390px;
  height: 115px;
  resize: none;
  background-color: #F5F3F4;
  border-radius: 21px;
  outline: none;
  font-size: 15px;
  border: solid transparent 2px;
}

.imgcontainer {
  display: block;
  position: relative;
  text-align: center;
}

input[type=file] {
  display:none;
}

.imgcontainer img {
  /* display: block; */
  /* vertical-align: middle; */
  object-fit: cover;
}

.middleSignUpDiv input:focus{
  border: solid #E2E2E2 2px;
  /* background-color: #B6B5B5; */
}

.middleSignUpDiv ::placeholder {
  font: Arial;
  font-family: sans-serif;
  /* font-size: 15px; */
  font-weight:medium;
  color: #B6B5B5;
}

/* input[type=text] {
  background-color: #F5F3F4;
  color: #B6B5B5;
} */

button {
  width: 215px;
  height: 55px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 25px;

  font: Arial;
  font-family: sans-serif;
  font-size: 19px;
  font-weight:600;
  color: white;
  background-color: #4152F1;
  border-radius: 7px;
  border: none;
  outline:none;
  cursor: pointer;
}

button:active{
background: blue;
}
button:visited {
   color: #4152F1;
}

/* .disclaimer {
  font: Arial;
  font-family: sans-serif;
  font-size: 12px;
  font-weight:medium;
  color: #CECECE;
  width: 390px;
  margin-left: auto;
  margin-right: auto;
}

.disclaimer em {
  color: #B4B4B4;
  cursor: pointer;
  font: Arial;
  font-family: sans-serif;
  font-size: 12px;
  font-weight:medium;
  font-style: normal
} */

/* Sign Up side */
/* body {
  top: 0px;
  bottom: 0px;

  float:left;
  display:inline-block;
  width: 100%;
  height: 100%;
  background-color: white;
  text-align: center;
} */

.descriptDiv {
  width: 100%;
  text-align: center;
  /* background-color: lightblue; */
}

.topSignUpDiv h1 {
  font: Arial;
  font-family: sans-serif;
  font-size: 40px;
  font-weight:600;
  /* text-align: center; */
  margin-top: 25px;
  margin-bottom: 0px;
}
/* .topSignUpDiv h3 {
  font: Arial;
  font-family: sans-serif;
  font-size: 19px;
  font-weight:400;
  color: white;
  background-color: #4152F1;
  border-radius: 7px;
  padding-top: 10px;
  padding-bottom: 10px;
  margin-top: 10px;
  width: 355px;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 55px;
} */

.disclaimer {
  margin-top: 50px;
  color: grey;
  font: Arial;
  font-family: sans-serif;
  font-size: 15px;
  font-weight:400;
  cursor: pointer;
}

#signout {
  font-weight: 500;
  color: grey;
  margin-top: 30px;
  cursor: pointer;
}

.cancelBtn {
  text-align: center;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  width: 100px;
  /* height: 50px; */
  font: Arial;
  font-family: sans-serif;
  font-size: 20px;
  font-weight:400;
  color: grey;
  cursor: pointer;
  border-radius: 5px;
}

/* .cancelBtn:hover {
} */

.cancelBtn:hover{
  background: #4152F1;
  color: white;
}

.profImg {
  margin-top: 20px;
  height: 150px;
  width: 150px;
  border-radius: 75px;
  border: solid #EFEFEF 1px;
  background-color: #EFEFEF;
  cursor: pointer;
}

.profImg:hover {
  border: solid #4152F1 1.2px;
}

.avatar {
  margin-top: 30px;
  height: 250px;
  width: 65%;
  border-radius: 20px;
  border: solid #EFEFEF 1px;
  background-color: #EFEFEF;
  cursor: pointer;
}

.avatar:hover {
  border: solid #4152F1 1.2px;
}</code>```

Edit profile/Settings

          <input type="file" id="fileButton" value="upload"/>

          <input type="file" id="fileButton2" value="upload"/>

            <textarea placeholder="Bio" class="soundscapeCaption" id="soundscapeCaption" rows="20" cols="50"></textarea>

          <button id="update">Update</button>

        Cancel

Sign out

```

答:
Seems like in Firefox Buttons default to submit. You could set your button type to button or just call event.preventDefault().

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

Body:
I have a settings page in my website, the user edits his profile and then hits the update button which when properly working, like on chrome browser, will run certain code in the updateProfileData function. However in the firefox browser the page reloads as soon as I press the update button.

How can I prevent this and instead have the code I want run just like in chrome browser?

$('#update').on('click', event => {
  updateProfileData();
})

function updateProfileData() {
  //none of this will run because the page will instead reload
}

function pickFile() {
  fileButton.click()
}

function pickFile2() {
  fileButton2.click()
}

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}

html, body {
  /* bottom: 0px;
  top: 0px; */
  width: 100%;
  height: 100%;
  margin:0px;

  font: Arial;
  font-family: sans-serif;
  font-weight:medium;

  text-align: center;

  /* bellow is to prevent all highlighting on the website. */
  -webkit-user-select: none; /* Chrome/Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+ */
}

/* #mp3Picker {
  color: grey;
} */

/* .middleSignUpDiv .container input {
  background-color: #F5F3F4;
  color: black;

  display: block;
  width: 390px;
  height: 125px;

  margin-left: auto;
  margin-right: auto;
  margin-top: 27px;
  margin-bottom: 17px;

  border-radius: 21px;
  border: none;

  padding-left: 15px;
  font-size: 0.95em;
  outline:none;

  border: solid transparent 2px;
} */

.justify {
  /* background-color: lightblue; */
  margin-top: 5px;
  display: flex;
  justify-content: center;
}

.soundscapeCaption:focus {
  border: solid #E2E2E2 2px;
}

.soundscapeCaption {
  /* margin-left: auto;
  margin-right: auto; */

  display: block;
  margin: 1px;
  padding: 1px;
  padding-left: 20px;
  padding-top: 20px;
  width: 390px;
  height: 115px;
  resize: none;
  background-color: #F5F3F4;
  border-radius: 21px;
  outline: none;
  font-size: 15px;
  border: solid transparent 2px;
}

.imgcontainer {
  display: block;
  position: relative;
  text-align: center;
}

input[type=file] {
  display:none;
}

.imgcontainer img {
  /* display: block; */
  /* vertical-align: middle; */
  object-fit: cover;
}

.middleSignUpDiv input:focus{
  border: solid #E2E2E2 2px;
  /* background-color: #B6B5B5; */
}

.middleSignUpDiv ::placeholder {
  font: Arial;
  font-family: sans-serif;
  /* font-size: 15px; */
  font-weight:medium;
  color: #B6B5B5;
}

/* input[type=text] {
  background-color: #F5F3F4;
  color: #B6B5B5;
} */

button {
  width: 215px;
  height: 55px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 25px;

  font: Arial;
  font-family: sans-serif;
  font-size: 19px;
  font-weight:600;
  color: white;
  background-color: #4152F1;
  border-radius: 7px;
  border: none;
  outline:none;
  cursor: pointer;
}

button:active{
background: blue;
}
button:visited {
   color: #4152F1;
}

/* .disclaimer {
  font: Arial;
  font-family: sans-serif;
  font-size: 12px;
  font-weight:medium;
  color: #CECECE;
  width: 390px;
  margin-left: auto;
  margin-right: auto;
}

.disclaimer em {
  color: #B4B4B4;
  cursor: pointer;
  font: Arial;
  font-family: sans-serif;
  font-size: 12px;
  font-weight:medium;
  font-style: normal
} */

/* Sign Up side */
/* body {
  top: 0px;
  bottom: 0px;

  float:left;
  display:inline-block;
  width: 100%;
  height: 100%;
  background-color: white;
  text-align: center;
} */

.descriptDiv {
  width: 100%;
  text-align: center;
  /* background-color: lightblue; */
}

.topSignUpDiv h1 {
  font: Arial;
  font-family: sans-serif;
  font-size: 40px;
  font-weight:600;
  /* text-align: center; */
  margin-top: 25px;
  margin-bottom: 0px;
}
/* .topSignUpDiv h3 {
  font: Arial;
  font-family: sans-serif;
  font-size: 19px;
  font-weight:400;
  color: white;
  background-color: #4152F1;
  border-radius: 7px;
  padding-top: 10px;
  padding-bottom: 10px;
  margin-top: 10px;
  width: 355px;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 55px;
} */

.disclaimer {
  margin-top: 50px;
  color: grey;
  font: Arial;
  font-family: sans-serif;
  font-size: 15px;
  font-weight:400;
  cursor: pointer;
}

#signout {
  font-weight: 500;
  color: grey;
  margin-top: 30px;
  cursor: pointer;
}

.cancelBtn {
  text-align: center;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  width: 100px;
  /* height: 50px; */
  font: Arial;
  font-family: sans-serif;
  font-size: 20px;
  font-weight:400;
  color: grey;
  cursor: pointer;
  border-radius: 5px;
}

/* .cancelBtn:hover {
} */

.cancelBtn:hover{
  background: #4152F1;
  color: white;
}

.profImg {
  margin-top: 20px;
  height: 150px;
  width: 150px;
  border-radius: 75px;
  border: solid #EFEFEF 1px;
  background-color: #EFEFEF;
  cursor: pointer;
}

.profImg:hover {
  border: solid #4152F1 1.2px;
}

.avatar {
  margin-top: 30px;
  height: 250px;
  width: 65%;
  border-radius: 20px;
  border: solid #EFEFEF 1px;
  background-color: #EFEFEF;
  cursor: pointer;
}

.avatar:hover {
  border: solid #4152F1 1.2px;
}

Edit profile/Settings

          <input type="file" id="fileButton" value="upload"/>

          <input type="file" id="fileButton2" value="upload"/>

            <textarea placeholder="Bio" class="soundscapeCaption" id="soundscapeCaption" rows="20" cols="50"></textarea>

          <button id="update">Update</button>

        Cancel

Sign out


问:
Calculating time duration from two time values with no date in R
I am trying to calculate sleep duration, in hours, from two times self-reported in a diary. I have the bed and wake times in 24-hour format (for bedtimes, for instance, "23:00" is 11PM, "0:00" is midnight, "1:00" is 1AM; for wake times, "9:00" is 9AM). I thought the difftime function would be good to extract the sleep duration, but I am running into an issue with some of the cases.

```<code>df$duration2<-difftime(df$Waketime2, df$Bedtime2, units="hours")
</code>```

In running the syntax above, it correctly calculates duration for the cases where the person went to bed at Midnight of later. The problem arises when the bedtime is before midnight - (I think) because it is technically a time on a different day which screws things up. For those cases, this syntax will return a negative number.

```<code>(difftime (8:00, 0:00))
</code>```

would return 8, but

```<code>(difftime (6:45,23:00))
</code>```

would return -16.25.

I do not have data for the date that corresponds to the time, only the time values, but I know that the sequence is such that if one went to bed after midnight it's assumed that the wake time would be on that same day.

Thank you for any help!!

This function makes sense, but it is giving me 0 values for the time difference in hours (at first it showed 0 for all duration in seconds, so that's why I changed it to hours in my code below). I'm also pasting the structure of my bed and wake time variables in hope it helps.

```<code>sleepTime <- function(bed, wake){
  wake <- paste(Sys.Date(), wake)
  tmpbed <- paste(Sys.Date(), bed)
  adjust <- -(difftime(wake, tmpbed) < 0)
  tmpbed <- paste(Sys.Date() + adjust, bed)
  difftime(wake, tmpbed, units="hours")
}

df$Duration2<-sleepTime(df$Bedtime2, df$Waketime2)
df$sTST2
</code>```

```<code>Time differences in hours
  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [67] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[133] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
</code>```

```<code>str(S2trim$Bedtime2)

 'ITime' int [1:436] 23:00:00 NA 23:00:00 21:00:00 22:30:00 21:30:00 00:00:00 22:30:00 23:45:00 22:30:00 ...
</code>```

```<code>str(S2trim$Waketime2)
 'ITime' int [1:436] 06:45:00 06:05:00 07:00:00 10:00:00 06:30:00 05:30:00 07:15:00 07:10:00 NA 05:30:00 ...
</code>```

Body:
I am trying to calculate sleep duration, in hours, from two times self-reported in a diary. I have the bed and wake times in 24-hour format (for bedtimes, for instance, "23:00" is 11PM, "0:00" is midnight, "1:00" is 1AM; for wake times, "9:00" is 9AM). I thought the difftime function would be good to extract the sleep duration, but I am running into an issue with some of the cases.

df$duration2<-difftime(df$Waketime2, df$Bedtime2, units="hours")

In running the syntax above, it correctly calculates duration for the cases where the person went to bed at Midnight of later. The problem arises when the bedtime is before midnight - (I think) because it is technically a time on a different day which screws things up. For those cases, this syntax will return a negative number.

(difftime (8:00, 0:00))

would return 8, but

(difftime (6:45,23:00))

would return -16.25.

I do not have data for the date that corresponds to the time, only the time values, but I know that the sequence is such that if one went to bed after midnight it's assumed that the wake time would be on that same day.

Thank you for any help!!

This function makes sense, but it is giving me 0 values for the time difference in hours (at first it showed 0 for all duration in seconds, so that's why I changed it to hours in my code below). I'm also pasting the structure of my bed and wake time variables in hope it helps.

sleepTime <- function(bed, wake){
  wake <- paste(Sys.Date(), wake)
  tmpbed <- paste(Sys.Date(), bed)
  adjust <- -(difftime(wake, tmpbed) < 0)
  tmpbed <- paste(Sys.Date() + adjust, bed)
  difftime(wake, tmpbed, units="hours")
}

df$Duration2<-sleepTime(df$Bedtime2, df$Waketime2)
df$sTST2

Time differences in hours
  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [67] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[133] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

str(S2trim$Bedtime2)

 'ITime' int [1:436] 23:00:00 NA 23:00:00 21:00:00 22:30:00 21:30:00 00:00:00 22:30:00 23:45:00 22:30:00 ...

str(S2trim$Waketime2)
 'ITime' int [1:436] 06:45:00 06:05:00 07:00:00 10:00:00 06:30:00 05:30:00 07:15:00 07:10:00 NA 05:30:00 ...

Body:
This is a hack but it works. At least it does with the posted input data.

sleepTime <- function(bed, wake){
  wake <- paste(Sys.Date(), wake)
  tmpbed <- paste(Sys.Date(), bed)
  d <- apply(data.frame(tmpbed, wake), 1, function(x) difftime(x[2], x[1], units = "hours"))
  adjust <- -(d < 0)
  tmpbed <- paste(Sys.Date() + adjust, bed)
  apply(data.frame(tmpbed, wake), 1, function(x) difftime(x[2], x[1], units = "hours"))
}

bedtime2 <- c("0:00", "23:00")
waketime2 <- c("8:00", "6:45")
sleepTime(bedtime2, waketime2)
#[1]  8.00 7.75

Another example, with the data in the str outputs posted in the question.

sleepTime(bedtime, waketime)
# [1]  7.750000  6.083333  8.000000 13.000000  8.000000  8.000000
# [7]  7.250000  8.666667  0.250000  7.000000

Data.

bedtime <-
c("23:00:00", NA, "23:00:00", "21:00:00", "22:30:00", "21:30:00",
"00:00:00", "22:30:00", "23:45:00", "22:30:00")

waketime <-
c("06:45:00", "06:05:00", "07:00:00", "10:00:00", "06:30:00",
"05:30:00", "07:15:00", "07:10:00", NA, "05:30:0")


问:
Select columns based on multiple attribute conditions
I am trying to figure how to efficiently select columns using dplyr::select_if. The starwars data set in dplyr 0.70 is a good dataset to use for this:

```<code>> starwars
# A tibble: 87 x 13
                 name height  mass    hair_color  skin_color eye_color birth_year gender homeworld species     films  vehicles starships
                <chr>  <int> <dbl>         <chr>       <chr>     <chr>      <dbl>  <chr>     <chr>   <chr>    <list>    <list>    <list>
 1     Luke Skywalker    172    77         blond        fair      blue       19.0   male  Tatooine   Human <chr [5]> <chr [2]> <chr [2]>
 2              C-3PO    167    75          <NA>        gold    yellow      112.0   <NA>  Tatooine   Droid <chr [6]> <chr [0]> <chr [0]>
 3              R2-D2     96    32          <NA> white, blue       red       33.0   <NA>     Naboo   Droid <chr [7]> <chr [0]> <chr [0]>
 4        Darth Vader    202   136          none       white    yellow       41.9   male  Tatooine   Human <chr [4]> <chr [0]> <chr [1]>
 5        Leia Organa    150    49         brown       light     brown       19.0 female  Alderaan   Human <chr [5]> <chr [1]> <chr [0]>
 6          Owen Lars    178   120   brown, grey       light      blue       52.0   male  Tatooine   Human <chr [3]> <chr [0]> <chr [0]>
 7 Beru Whitesun lars    165    75         brown       light      blue       47.0 female  Tatooine   Human <chr [3]> <chr [0]> <chr [0]>
 8              R5-D4     97    32          <NA>  white, red       red         NA   <NA>  Tatooine   Droid <chr [1]> <chr [0]> <chr [0]>
 9  Biggs Darklighter    183    84         black       light     brown       24.0   male  Tatooine   Human <chr [1]> <chr [0]> <chr [1]>
10     Obi-Wan Kenobi    182    77 auburn, white        fair blue-gray       57.0   male   Stewjon   Human <chr [6]> <chr [1]> <chr [5]>
</code>```

Now say that I would like select columns that are only integers. This works well:

```<code>library(dplyr)

starwars %>%
  select_if(is.numeric)
</code>```

But what should I do if I want to select based on multiple criteria. For example maybe I want both numeric and character columns:

```<code>starwars %>%
  select_if(c(is.numeric, is.character))
</code>```

Or maybe I want all numeric AND the name column:

```<code>starwars %>%
  select_if(name, is.character)
</code>```

Neither of the two examples above work so I am wondering how I might accomplish what I've outlined here.

答:
From version 1.0.0, as mentioned in the news,

select() and rename() use the latest version of the tidyselect interface. Practically, this means that you can now combine selections using Boolean logic (i.e. !, & and |), and use predicate functions (e.g. is.character) to select variables by type (#4680).

### Install development version on GitHub first until CRAN version is available
# install.packages("devtools")
# devtools::install_github("tidyverse/dplyr")
library(dplyr, warn.conflicts = FALSE)

starwars %>%
  as_tibble() %>%
  glimpse()
#> Rows: 87
#> Columns: 14
#> $ name       <chr> "Luke Skywalker", "C-3PO", "R2-D2", "Darth Vader", "Leia...
#> $ height     <int> 172, 167, 96, 202, 150, 178, 165, 97, 183, 182, 188, 180...
#> $ mass       <dbl> 77.0, 75.0, 32.0, 136.0, 49.0, 120.0, 75.0, 32.0, 84.0, ...
#> $ hair_color <chr> "blond", NA, NA, "none", "brown", "brown, grey", "brown"...
#> $ skin_color <chr> "fair", "gold", "white, blue", "white", "light", "light"...
#> $ eye_color  <chr> "blue", "yellow", "red", "yellow", "brown", "blue", "blu...
#> $ birth_year <dbl> 19.0, 112.0, 33.0, 41.9, 19.0, 52.0, 47.0, NA, 24.0, 57....
#> $ sex        <chr> "male", "none", "none", "male", "female", "male", "femal...
#> $ gender     <chr> "masculine", "masculine", "masculine", "masculine", "fem...
#> $ homeworld  <chr> "Tatooine", "Tatooine", "Naboo", "Tatooine", "Alderaan",...
#> $ species    <chr> "Human", "Droid", "Droid", "Human", "Human", "Human", "H...
#> $ films      <list> [<"The Empire Strikes Back", "Revenge of the Sith", "Re...
#> $ vehicles   <list> [<"Snowspeeder", "Imperial Speeder Bike">, <>, <>, <>, ...
#> $ starships  <list> [<"X-wing", "Imperial shuttle">, <>, <>, "TIE Advanced ...
```

<p>To select either numeric or character columns:</p>

<pre class="lang-r prettyprint-override"><code>starwars %>%
  select(is.numeric | is.character) %>%
  glimpse()
#> Rows: 87
#> Columns: 11
#> $ height     <int> 172, 167, 96, 202, 150, 178, 165, 97, 183, 182, 188, 180...
#> $ mass       <dbl> 77.0, 75.0, 32.0, 136.0, 49.0, 120.0, 75.0, 32.0, 84.0, ...
#> $ birth_year <dbl> 19.0, 112.0, 33.0, 41.9, 19.0, 52.0, 47.0, NA, 24.0, 57....
#> $ name       <chr> "Luke Skywalker", "C-3PO", "R2-D2", "Darth Vader", "Leia...
#> $ hair_color <chr> "blond", NA, NA, "none", "brown", "brown, grey", "brown"...
#> $ skin_color <chr> "fair", "gold", "white, blue", "white", "light", "light"...
#> $ eye_color  <chr> "blue", "yellow", "red", "yellow", "brown", "blue", "blu...
#> $ sex        <chr> "male", "none", "none", "male", "female", "male", "femal...
#> $ gender     <chr> "masculine", "masculine", "masculine", "masculine", "fem...
#> $ homeworld  <chr> "Tatooine", "Tatooine", "Naboo", "Tatooine", "Alderaan",...
#> $ species    <chr> "Human", "Droid", "Droid", "Human", "Human", "Human", "H...
</code>```

Or select non-list columns

starwars %>%
  select(!is.list) %>%
  glimpse()
#> Rows: 87
#> Columns: 11
#> $ name       <chr> "Luke Skywalker", "C-3PO", "R2-D2", "Darth Vader", "Leia...
#> $ height     <int> 172, 167, 96, 202, 150, 178, 165, 97, 183, 182, 188, 180...
#> $ mass       <dbl> 77.0, 75.0, 32.0, 136.0, 49.0, 120.0, 75.0, 32.0, 84.0, ...
#> $ hair_color <chr> "blond", NA, NA, "none", "brown", "brown, grey", "brown"...
#> $ skin_color <chr> "fair", "gold", "white, blue", "white", "light", "light"...
#> $ eye_color  <chr> "blue", "yellow", "red", "yellow", "brown", "blue", "blu...
#> $ birth_year <dbl> 19.0, 112.0, 33.0, 41.9, 19.0, 52.0, 47.0, NA, 24.0, 57....
#> $ sex        <chr> "male", "none", "none", "male", "female", "male", "femal...
#> $ gender     <chr> "masculine", "masculine", "masculine", "masculine", "fem...
#> $ homeworld  <chr> "Tatooine", "Tatooine", "Naboo", "Tatooine", "Alderaan",...
#> $ species    <chr> "Human", "Droid", "Droid", "Human", "Human", "Human", "H...
```

<p>To select <code>name</code> & character columns</p>

<pre class="lang-r prettyprint-override"><code>starwars %>%
  select(name | is.character) %>%
  glimpse()
#> Rows: 87
#> Columns: 8
#> $ name       <chr> "Luke Skywalker", "C-3PO", "R2-D2", "Darth Vader", "Leia...
#> $ hair_color <chr> "blond", NA, NA, "none", "brown", "brown, grey", "brown"...
#> $ skin_color <chr> "fair", "gold", "white, blue", "white", "light", "light"...
#> $ eye_color  <chr> "blue", "yellow", "red", "yellow", "brown", "blue", "blu...
#> $ sex        <chr> "male", "none", "none", "male", "female", "male", "femal...
#> $ gender     <chr> "masculine", "masculine", "masculine", "masculine", "fem...
#> $ homeworld  <chr> "Tatooine", "Tatooine", "Naboo", "Tatooine", "Alderaan",...
#> $ species    <chr> "Human", "Droid", "Droid", "Human", "Human", "Human", "H...
</code>```

Created on 2020-02-17 by the reprex package (v0.3.0)

Body:
I am trying to figure how to efficiently select columns using dplyr::select_if. The starwars data set in dplyr 0.70 is a good dataset to use for this:

> starwars
# A tibble: 87 x 13
                 name height  mass    hair_color  skin_color eye_color birth_year gender homeworld species     films  vehicles starships
                <chr>  <int> <dbl>         <chr>       <chr>     <chr>      <dbl>  <chr>     <chr>   <chr>    <list>    <list>    <list>
 1     Luke Skywalker    172    77         blond        fair      blue       19.0   male  Tatooine   Human <chr [5]> <chr [2]> <chr [2]>
 2              C-3PO    167    75          <NA>        gold    yellow      112.0   <NA>  Tatooine   Droid <chr [6]> <chr [0]> <chr [0]>
 3              R2-D2     96    32          <NA> white, blue       red       33.0   <NA>     Naboo   Droid <chr [7]> <chr [0]> <chr [0]>
 4        Darth Vader    202   136          none       white    yellow       41.9   male  Tatooine   Human <chr [4]> <chr [0]> <chr [1]>
 5        Leia Organa    150    49         brown       light     brown       19.0 female  Alderaan   Human <chr [5]> <chr [1]> <chr [0]>
 6          Owen Lars    178   120   brown, grey       light      blue       52.0   male  Tatooine   Human <chr [3]> <chr [0]> <chr [0]>
 7 Beru Whitesun lars    165    75         brown       light      blue       47.0 female  Tatooine   Human <chr [3]> <chr [0]> <chr [0]>
 8              R5-D4     97    32          <NA>  white, red       red         NA   <NA>  Tatooine   Droid <chr [1]> <chr [0]> <chr [0]>
 9  Biggs Darklighter    183    84         black       light     brown       24.0   male  Tatooine   Human <chr [1]> <chr [0]> <chr [1]>
10     Obi-Wan Kenobi    182    77 auburn, white        fair blue-gray       57.0   male   Stewjon   Human <chr [6]> <chr [1]> <chr [5]>

Now say that I would like select columns that are only integers. This works well:

library(dplyr)

starwars %>%
  select_if(is.numeric)

But what should I do if I want to select based on multiple criteria. For example maybe I want both numeric and character columns:

starwars %>%
  select_if(c(is.numeric, is.character))

Or maybe I want all numeric AND the name column:

starwars %>%
  select_if(name, is.character)

Neither of the two examples above work so I am wondering how I might accomplish what I've outlined here.

Body:
From version 1.0.0, as mentioned in the news,

select() and rename() use the latest version of the tidyselect interface. Practically, this means that you can now combine selections using Boolean logic (i.e. !, & and |), and use predicate functions (e.g. is.character) to select variables by type (#4680).

### Install development version on GitHub first until CRAN version is available
# install.packages("devtools")
# devtools::install_github("tidyverse/dplyr")
library(dplyr, warn.conflicts = FALSE)

starwars %>%
  as_tibble() %>%
  glimpse()
#> Rows: 87
#> Columns: 14
#> $ name       <chr> "Luke Skywalker", "C-3PO", "R2-D2", "Darth Vader", "Leia...
#> $ height     <int> 172, 167, 96, 202, 150, 178, 165, 97, 183, 182, 188, 180...
#> $ mass       <dbl> 77.0, 75.0, 32.0, 136.0, 49.0, 120.0, 75.0, 32.0, 84.0, ...
#> $ hair_color <chr> "blond", NA, NA, "none", "brown", "brown, grey", "brown"...
#> $ skin_color <chr> "fair", "gold", "white, blue", "white", "light", "light"...
#> $ eye_color  <chr> "blue", "yellow", "red", "yellow", "brown", "blue", "blu...
#> $ birth_year <dbl> 19.0, 112.0, 33.0, 41.9, 19.0, 52.0, 47.0, NA, 24.0, 57....
#> $ sex        <chr> "male", "none", "none", "male", "female", "male", "femal...
#> $ gender     <chr> "masculine", "masculine", "masculine", "masculine", "fem...
#> $ homeworld  <chr> "Tatooine", "Tatooine", "Naboo", "Tatooine", "Alderaan",...
#> $ species    <chr> "Human", "Droid", "Droid", "Human", "Human", "Human", "H...
#> $ films      <list> [<"The Empire Strikes Back", "Revenge of the Sith", "Re...
#> $ vehicles   <list> [<"Snowspeeder", "Imperial Speeder Bike">, <>, <>, <>, ...
#> $ starships  <list> [<"X-wing", "Imperial shuttle">, <>, <>, "TIE Advanced ...

To select either numeric or character columns:

starwars %>%
  select(is.numeric | is.character) %>%
  glimpse()
#> Rows: 87
#> Columns: 11
#> $ height     <int> 172, 167, 96, 202, 150, 178, 165, 97, 183, 182, 188, 180...
#> $ mass       <dbl> 77.0, 75.0, 32.0, 136.0, 49.0, 120.0, 75.0, 32.0, 84.0, ...
#> $ birth_year <dbl> 19.0, 112.0, 33.0, 41.9, 19.0, 52.0, 47.0, NA, 24.0, 57....
#> $ name       <chr> "Luke Skywalker", "C-3PO", "R2-D2", "Darth Vader", "Leia...
#> $ hair_color <chr> "blond", NA, NA, "none", "brown", "brown, grey", "brown"...
#> $ skin_color <chr> "fair", "gold", "white, blue", "white", "light", "light"...
#> $ eye_color  <chr> "blue", "yellow", "red", "yellow", "brown", "blue", "blu...
#> $ sex        <chr> "male", "none", "none", "male", "female", "male", "femal...
#> $ gender     <chr> "masculine", "masculine", "masculine", "masculine", "fem...
#> $ homeworld  <chr> "Tatooine", "Tatooine", "Naboo", "Tatooine", "Alderaan",...
#> $ species    <chr> "Human", "Droid", "Droid", "Human", "Human", "Human", "H...

Or select non-list columns

starwars %>%
  select(!is.list) %>%
  glimpse()
#> Rows: 87
#> Columns: 11
#> $ name       <chr> "Luke Skywalker", "C-3PO", "R2-D2", "Darth Vader", "Leia...
#> $ height     <int> 172, 167, 96, 202, 150, 178, 165, 97, 183, 182, 188, 180...
#> $ mass       <dbl> 77.0, 75.0, 32.0, 136.0, 49.0, 120.0, 75.0, 32.0, 84.0, ...
#> $ hair_color <chr> "blond", NA, NA, "none", "brown", "brown, grey", "brown"...
#> $ skin_color <chr> "fair", "gold", "white, blue", "white", "light", "light"...
#> $ eye_color  <chr> "blue", "yellow", "red", "yellow", "brown", "blue", "blu...
#> $ birth_year <dbl> 19.0, 112.0, 33.0, 41.9, 19.0, 52.0, 47.0, NA, 24.0, 57....
#> $ sex        <chr> "male", "none", "none", "male", "female", "male", "femal...
#> $ gender     <chr> "masculine", "masculine", "masculine", "masculine", "fem...
#> $ homeworld  <chr> "Tatooine", "Tatooine", "Naboo", "Tatooine", "Alderaan",...
#> $ species    <chr> "Human", "Droid", "Droid", "Human", "Human", "Human", "H...

To select name & character columns

starwars %>%
  select(name | is.character) %>%
  glimpse()
#> Rows: 87
#> Columns: 8
#> $ name       <chr> "Luke Skywalker", "C-3PO", "R2-D2", "Darth Vader", "Leia...
#> $ hair_color <chr> "blond", NA, NA, "none", "brown", "brown, grey", "brown"...
#> $ skin_color <chr> "fair", "gold", "white, blue", "white", "light", "light"...
#> $ eye_color  <chr> "blue", "yellow", "red", "yellow", "brown", "blue", "blu...
#> $ sex        <chr> "male", "none", "none", "male", "female", "male", "femal...
#> $ gender     <chr> "masculine", "masculine", "masculine", "masculine", "fem...
#> $ homeworld  <chr> "Tatooine", "Tatooine", "Naboo", "Tatooine", "Alderaan",...
#> $ species    <chr> "Human", "Droid", "Droid", "Human", "Human", "Human", "H...

Created on 2020-02-17 by the reprex package (v0.3.0)


问:
Unable to resolve deprecation notice with composer
I have asked my hosting provider to switch the operating system on my server from Centos to Ubuntu. Upon downloading all my files from GitHub and running "composer install" I am getting the following error in terminal:

Deprecation Notice: The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence in /usr/share/php/Composer/Downloader/GitDownloader.php:223
  Deprecation Notice: The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence in /usr/share/php/Composer/Downloader/SvnDownloader.php:132

After this composer quits so I need to be able to resolve this not worked around it.

Already tried solutions:

Uninstall and re-install composer.

Upgrade, update, and install commands attempted.

A fresh install of Laravel in case of corruption on Git clone.

答:
How to solve it

Put parenthesis surrounding

```<code>$someString . ($a + $b) . $anotherString
</code>```

What is the error

If you'd write something like this:

```<code>echo "sum: " . $a + $b;
</code>```

PHP would previously interpret it like this:

```<code>echo ("sum: " . $a) + $b;
</code>```

PHP 8 will make it so that it's interpreted like this:

```<code>echo "sum: " . ($a + $b);
</code>```

source: https://stitcher.io/blog/new-in-php-74

Body:
How to solve it

Put parenthesis surrounding

$someString . ($a + $b) . $anotherString

What is the error

If you'd write something like this:

echo "sum: " . $a + $b;

PHP would previously interpret it like this:

echo ("sum: " . $a) + $b;

PHP 8 will make it so that it's interpreted like this:

echo "sum: " . ($a + $b);

source: https://stitcher.io/blog/new-in-php-74


答:
First off, if you're using this for a layout, don't.  Use divs and CSS.

If you're using tabular data, then:

```<code><table>
    <tr>
        <td rowspan="2">A</td>
        <td rowspan="2">B</td>
        <td>C</td>
        <td>D</td>
    </tr>
    <tr>
        <td>C</td>
        <td>D</td>
    </tr>
</table>
</code>```

Title: How do I create this table?

Body:
----------------------------
|     |       |  C   |  D  |
|  A  |   B   |------+-----|
|     |       | E    | F   |
----------------------------

Both A and B need a ROWSPAN of 2. What's the HTML for that?

Body:
First off, if you're using this for a layout, don't.  Use divs and CSS.

If you're using tabular data, then:

<table>
    <tr>
        <td rowspan="2">A</td>
        <td rowspan="2">B</td>
        <td>C</td>
        <td>D</td>
    </tr>
    <tr>
        <td>C</td>
        <td>D</td>
    </tr>
</table>


问:
Why am I getting a Thread 1: fatal error in this function
I am getting the following error on the line basicTop.run(SK...

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

I do not know why I am getting this. I get this error message when I click on the simulator screen.

```<code>class GameScene: SKScene {

    var brickSwitch: SKSpriteNode!
    var basicTop: SKSpriteNode!
    var basicBottom: SKSpriteNode!
    var basicLeft: SKSpriteNode!
    var basicRight: SKSpriteNode!

    override func didMove(to view: SKView) {
        layoutScene()
    }

    func turnBasicTop() {
        basicTop.run(SKAction.rotate(byAngle: .pi/2, duration: 0.25))
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        turnBasicTop()
    }
</code>```

答:
Check whether an optional basicTop contains a value,

```<code>if basicTop != nil {
    basicTop.run(SKAction.rotate(byAngle: .pi/2, duration: 0.25))
}
</code>```

Also, please try to read articles before posting basic questions

https://developer.apple.com/documentation/swift/optional

Body:
I am getting the following error on the line basicTop.run(SK...

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

I do not know why I am getting this. I get this error message when I click on the simulator screen.

class GameScene: SKScene {

    var brickSwitch: SKSpriteNode!
    var basicTop: SKSpriteNode!
    var basicBottom: SKSpriteNode!
    var basicLeft: SKSpriteNode!
    var basicRight: SKSpriteNode!

    override func didMove(to view: SKView) {
        layoutScene()
    }

    func turnBasicTop() {
        basicTop.run(SKAction.rotate(byAngle: .pi/2, duration: 0.25))
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        turnBasicTop()
    }

Body:
Check whether an optional basicTop contains a value,

if basicTop != nil {
    basicTop.run(SKAction.rotate(byAngle: .pi/2, duration: 0.25))
}

Also, please try to read articles before posting basic questions

https://developer.apple.com/documentation/swift/optional


问:
batch copy and suppress all output
I have a batch file where I am copying files from folders to a new destination.

The folder list is generated by the batch file:

```<code>@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
@REM Set defaults
SET BASE_FLDR=.\
SET BLD_TYPE=Release
SET DST_FLDR=SC_APP
@REM Check if base folder specified, if not default to current location
IF NOT [%1] == [] SET BASE_FLDR=%1
@REM Check if build type specified, if not default to Release
IF NOT [%2] == [] SET BLD_TYPE=%2
@REM Display parameters
ECHO Base folder: %BASE_FLDR%
ECHO Build type : %BLD_TYPE%
@REM Does destination folder exist?
IF NOT EXIST %DST_FLDR% MKDIR %DST_FLDR%
@REM Create list of subfolders to search
FOR /F "delims=" %%F IN ('"DIR %BASE_FLDR% /S /B /A:D | FINDSTR /EIC:"%BLD_TYPE%" "') DO (
    @COPY /Y "%%F"\*.DLL "%DST_FLDR%" >NUL
    @COPY /Y "%%F"\*.EXE "%DST_FLDR%" >NUL
)
</code>```

During the copy process I see lots of:

```<code>The system cannot find the file specified.
</code>```

I've tried various things but have not been able to prevent this message from being displayed.

@ doesn't stop it, neither does redirecting the output to NUL, I also tried launching in another CMD, doesn't stop it happening either.

答:
Based upon your self accepted answer, I have decided to post this because you've ignored all of the advice I provided in the comments:

Please note: This is not how I'd perform the task, so it is not provided as an answer per se, more a supplement to your own answer.

```<code>@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

REM Set defaults
SET "BASE_FLDR=."
SET "BLD_TYPE=Release"

REM Check if base folder specified, if not default to current location
IF NOT "%~1" == "" SET "BASE_FLDR=%~1"

REM Check if build type specified, if not default to Release
IF NOT "%~2" == "" SET "BLD_TYPE=%~2"
SET "DST_FLDR=%BASE_FLDR%\sc_app"

REM Display parameters
ECHO Base folder: %BASE_FLDR%
ECHO Build type: %BLD_TYPE%
ECHO Destination folder: %DST_FLDR%
ECHO Please wait

REM Does destination folder exist?
IF NOT EXIST "%DST_FLDR%\" (
    ECHO Creating %DST_FLDR%
    MD "%DST_FLDR%"
)

REM Create list of subfolders to search
ECHO Copying DLL's and EXE's to %DST_FLDR%
FOR /F "DELIMS=" %%F IN ('"DIR /B /S /AD "%BASE_FLDR%" | FINDSTR /EIC:"%BLD_TYPE%""') DO (
    ECHO | SET /P "=."
    COPY /Y "%%F\*.DLL" "%DST_FLDR%" >NUL 2>&1
    COPY /Y "%%F\*.EXE" "%DST_FLDR%" >NUL 2>&1
)
ECHO "Copy complete"
</code>```

Title: batch copy and suppress all output

Body:
I have a batch file where I am copying files from folders to a new destination.

The folder list is generated by the batch file:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
@REM Set defaults
SET BASE_FLDR=.\
SET BLD_TYPE=Release
SET DST_FLDR=SC_APP
@REM Check if base folder specified, if not default to current location
IF NOT [%1] == [] SET BASE_FLDR=%1
@REM Check if build type specified, if not default to Release
IF NOT [%2] == [] SET BLD_TYPE=%2
@REM Display parameters
ECHO Base folder: %BASE_FLDR%
ECHO Build type : %BLD_TYPE%
@REM Does destination folder exist?
IF NOT EXIST %DST_FLDR% MKDIR %DST_FLDR%
@REM Create list of subfolders to search
FOR /F "delims=" %%F IN ('"DIR %BASE_FLDR% /S /B /A:D | FINDSTR /EIC:"%BLD_TYPE%" "') DO (
    @COPY /Y "%%F"\*.DLL "%DST_FLDR%" >NUL
    @COPY /Y "%%F"\*.EXE "%DST_FLDR%" >NUL
)

During the copy process I see lots of:

The system cannot find the file specified.

I've tried various things but have not been able to prevent this message from being displayed.

@ doesn't stop it, neither does redirecting the output to NUL, I also tried launching in another CMD, doesn't stop it happening either.

Body:
Based upon your self accepted answer, I have decided to post this because you've ignored all of the advice I provided in the comments:

Please note: This is not how I'd perform the task, so it is not provided as an answer per se, more a supplement to your own answer.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

REM Set defaults
SET "BASE_FLDR=."
SET "BLD_TYPE=Release"

REM Check if base folder specified, if not default to current location
IF NOT "%~1" == "" SET "BASE_FLDR=%~1"

REM Check if build type specified, if not default to Release
IF NOT "%~2" == "" SET "BLD_TYPE=%~2"
SET "DST_FLDR=%BASE_FLDR%\sc_app"

REM Display parameters
ECHO Base folder: %BASE_FLDR%
ECHO Build type: %BLD_TYPE%
ECHO Destination folder: %DST_FLDR%
ECHO Please wait

REM Does destination folder exist?
IF NOT EXIST "%DST_FLDR%\" (
    ECHO Creating %DST_FLDR%
    MD "%DST_FLDR%"
)

REM Create list of subfolders to search
ECHO Copying DLL's and EXE's to %DST_FLDR%
FOR /F "DELIMS=" %%F IN ('"DIR /B /S /AD "%BASE_FLDR%" | FINDSTR /EIC:"%BLD_TYPE%""') DO (
    ECHO | SET /P "=."
    COPY /Y "%%F\*.DLL" "%DST_FLDR%" >NUL 2>&1
    COPY /Y "%%F\*.EXE" "%DST_FLDR%" >NUL 2>&1
)
ECHO "Copy complete"