问:
OpenCV4 Imshow function opens an empty gray box
When I run the provided code, a imshow() opens a window but it is just an empty gray window. The code executes successfully (doesn't trigger the !image.data check.) The imwrite() function does successfully write the image to a file so I don't think it is a problem with reading the image.

I also tried opening a named window first, and then calling imshow to that window, but that also didn't help.

It seems like there are a few other people having this issue on this site. I browsed the answers and tried the solutions but nothing worked. Also I could not find anyone using opencv 4.0 with c++.

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <string>

using namespace std;
using namespace cv;

int main() {
    Mat image;
    image = imread("./887.jpg");
    if (!image.data)
    {
        cout << "Could not open or find the image" << std::endl;
        return -1;
    }

    imwrite("test.jpg", image);
    waitKey(1);
    imshow("Display window", image);                   // Show our image inside it.
    waitKey(0);

    return 0;
}
```

I expect the image to show up in a window titled "Display window", the window does show up but it is just an empty gray box.

答: Ok, sorry about this. The image I was trying to display is very large, and only visible part was the corner of image which is gray. Once I scaled down the image it appeared just fine. So sorry for wasting everyone's time.</p>

Body:
When I run the provided code, a imshow() opens a window but it is just an empty gray window. The code executes successfully (doesn't trigger the !image.data check.) The imwrite() function does successfully write the image to a file so I don't think it is a problem with reading the image.

I also tried opening a named window first, and then calling imshow to that window, but that also didn't help.

It seems like there are a few other people having this issue on this site. I browsed the answers and tried the solutions but nothing worked. Also I could not find anyone using opencv 4.0 with c++.

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <string>

using namespace std;
using namespace cv;

int main() {
    Mat image;
    image = imread("./887.jpg");
    if (!image.data)
    {
        cout << "Could not open or find the image" << std::endl;
        return -1;
    }

    imwrite("test.jpg", image);
    waitKey(1);
    imshow("Display window", image);                   // Show our image inside it.
    waitKey(0);

    return 0;
}

I expect the image to show up in a window titled "Display window", the window does show up but it is just an empty gray box.


来源: stackexchange

问:
I need to retreive data where the variable = one thing, and also return data whereby the same matches for another variable
I have 3 tables. Product, Extra and Link. The product table contains the original row, and then more rows which are based on the original. Then there are extras attached to the original and each variant, using the link table. Each variant has the extras attached to it as per the Link table, but also all of the extras that are attached to the original. I need to return all extras where the name of the variable = xx, and the output should include all extras attached to the original and the variant.

These are my tables

Product

```<code>Id     ProdName   Basedonvariantid
--------------------------------------------
123    Original   null
456    Product1a  123
789    Product1b  123
012    Product1c  123
987    Original   null
654    Product2a  987
321    Product2b  987
098    Product2c  987
</code>```

Extra

```<code>Id     ExtraName
--------------------------------------------
1      Extra1
2      Extra2
3      Extra3
4      Extra4
5      Extra5
6      Extra6
7      Extra7
8      Extra8
</code>```

Link

```<code>Id     Productid      Extraid
--------------------------------------------
a      123            1
b      123            3
c      123            5
d      456            2
e      789            4
f      012            6
g      987            1
h      987            2
i      987            4
j      654            3
k      321            5
l      098            6
m      098            7
n      098            8
</code>```

I cant work it out. I can do the join but only to return the extra's attached to just the variant, i.e

```<code>select p.prodname, e.extraname
from Product p
join Link l on p.id=l.productid
join Extra e on e.id=l.extraid
where p.prodname in (
'Product1b',
'Product2c'
)
</code>```

In the front end system, it will show that Product1b has all the extras linked to Product1 and Product1b, and it will show that Product2c has all the extras linked to Product2 and Product2c.

How can I write a query that says 'give me all extras for product1b and 2c, and returns the following:

```<code>Prodname      Extraname
--------------------------------------------
Product1b        Extra1
Product1b        Extra3
Product1b        Extra4
Product1b        Extra5
Product2c        Extra1
Product2c        Extra2
Product2c        Extra4
Product2c        Extra6
Product2c        Extra7
Product2c        Extra8
</code>```

答:
You could use an OR in your join condition to the link table. This may not be the most efficient (where a UNION might be more efficient)

```<code>select p.prodname, e.extraname
from Product p
    join Link l on (p.id=l.productid OR p.basedonvariantid = l.productid)
    join Extra e on e.id=l.extraid
where p.prodname in (
    'Product1b',
    'Product2c'
);
</code>```

The UNION version of this would look like:

```<code>select p.prodname, e.extraname
from Product p
join Link l on p.id=l.productid
join Extra e on e.id=l.extraid
where p.prodname in (
'Product1b',
'Product2c'
)
UNION ALL
select p.prodname, e.extraname
from Product p
join Link l on p.basedonvariantid=l.productid
join Extra e on e.id=l.extraid
where p.prodname in (
'Product1b',
'Product2c'
)
</code>```

Both will work as long as the BasedonvariantID never refers to another variant (which itself refers to a main id). If that's the case then you'll have to resort to a recursive query.

ContentLicense: CC BY-SA 4.0

Body:
I have 3 tables. Product, Extra and Link. The product table contains the original row, and then more rows which are based on the original. Then there are extras attached to the original and each variant, using the link table. Each variant has the extras attached to it as per the Link table, but also all of the extras that are attached to the original. I need to return all extras where the name of the variable = xx, and the output should include all extras attached to the original and the variant.

These are my tables

Product

Id     ProdName   Basedonvariantid
--------------------------------------------
123    Original   null
456    Product1a  123
789    Product1b  123
012    Product1c  123
987    Original   null
654    Product2a  987
321    Product2b  987
098    Product2c  987

Extra

Id     ExtraName
--------------------------------------------
1      Extra1
2      Extra2
3      Extra3
4      Extra4
5      Extra5
6      Extra6
7      Extra7
8      Extra8

Link

Id     Productid      Extraid
--------------------------------------------
a      123            1
b      123            3
c      123            5
d      456            2
e      789            4
f      012            6
g      987            1
h      987            2
i      987            4
j      654            3
k      321            5
l      098            6
m      098            7
n      098            8

I cant work it out. I can do the join but only to return the extra's attached to just the variant, i.e

select p.prodname, e.extraname
from Product p
join Link l on p.id=l.productid
join Extra e on e.id=l.extraid
where p.prodname in (
'Product1b',
'Product2c'
)

In the front end system, it will show that Product1b has all the extras linked to Product1 and Product1b, and it will show that Product2c has all the extras linked to Product2 and Product2c.

How can I write a query that says 'give me all extras for product1b and 2c, and returns the following:

Prodname      Extraname
--------------------------------------------
Product1b        Extra1
Product1b        Extra3
Product1b        Extra4
Product1b        Extra5
Product2c        Extra1
Product2c        Extra2
Product2c        Extra4
Product2c        Extra6
Product2c        Extra7
Product2c        Extra8

Body:
You could use an OR in your join condition to the link table. This may not be the most efficient (where a UNION might be more efficient)

select p.prodname, e.extraname
from Product p
    join Link l on (p.id=l.productid OR p.basedonvariantid = l.productid)
    join Extra e on e.id=l.extraid
where p.prodname in (
    'Product1b',
    'Product2c'
);

The UNION version of this would look like:

select p.prodname, e.extraname
from Product p
join Link l on p.id=l.productid
join Extra e on e.id=l.extraid
where p.prodname in (
'Product1b',
'Product2c'
)
UNION ALL
select p.prodname, e.extraname
from Product p
join Link l on p.basedonvariantid=l.productid
join Extra e on e.id=l.extraid
where p.prodname in (
'Product1b',
'Product2c'
)

Both will work as long as the BasedonvariantID never refers to another variant (which itself refers to a main id). If that's the case then you'll have to resort to a recursive query.


问:
Copying tinymce skin's directory using webpack
According to TinyMce's Webpack file-loader documentation, the following snippet will copy TinyMce's skins directory:

```<code>require.context(
  'file?name=[path][name].[ext]&context=node_modules/tinymce!tinymce/skins',
  true,
  /.*/
);
</code>```

I placed this snippet into app/assets/javascript/tinymce.vue right before my include statements for tinymce. Unfortunately, I get the following error thrown by postcss when I attempt to webpack compile:

```<code>% rails webpacker:compile

Webpacker is installed
Using /repos/myapp/config/webpacker.yml file for setting up webpack paths
Compiling…
Compilation failed:
CssSyntaxError: /repos/myapp/js/skins/content/default/content.css:2:1: Unknown word
    at Input.error (/repos/myapp/node_modules/postcss/lib/input.js:130:16)
    at Parser.unknownWord (/repos/myapp/node_modules/postcss/lib/parser.js:563:22)
    at Parser.other (/repos/myapp/node_modules/postcss/lib/parser.js:168:12)
    at Parser.parse (/repos/myapp/node_modules/postcss/lib/parser.js:77:16)
    at parse (/repos/myapp/node_modules/postcss/lib/parse.js:17:12)
    at new LazyResult (/repos/myapp/node_modules/postcss/lib/lazy-result.js:60:16)
    at Processor.<anonymous> (/repos/myapp/node_modules/postcss/lib/processor.js:138:12)
    at Processor.process (/repos/myapp/node_modules/postcss/lib/processor.js:117:23)
    at Function.creator.process (/repos/myapp/node_modules/postcss/lib/postcss.js:148:43)
    at OptimizeCssAssetsWebpackPlugin.processCss (/repos/myapp/node_modules/optimize-css-assets-webpack-plugin/src/index.js:65:21)
    at Object.processor (/repos/myapp/node_modules/optimize-css-assets-webpack-plugin/src/index.js:11:18)
    at each (/repos/myapp/node_modules/last-call-webpack-plugin/src/index.js:150:10)
    at arrayEach (/repos/myapp/node_modules/lodash/_arrayEach.js:15:9)
    at forEach (/repos/myapp/node_modules/lodash/forEach.js:38:10)
    at OptimizeCssAssetsWebpackPlugin.process (/repos/myapp/node_modules/last-call-webpack-plugin/src/index.js:147:5)
    at compilation.hooks.optimizeChunkAssets.tapPromise.chunks (/repos/myapp/node_modules/last-call-webpack-plugin/src/index.js:178:28)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:8:17)
    at AsyncSeriesHook.lazyCompileHook (/repos/myapp/node_modules/tapable/lib/Hook.js:154:20)
    at hooks.additionalAssets.callAsync.err (/repos/myapp/node_modules/webpack/lib/Compilation.js:1311:36)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/repos/myapp/node_modules/tapable/lib/Hook.js:154:20)
    at hooks.optimizeTree.callAsync.err (/repos/myapp/node_modules/webpack/lib/Compilation.js:1307:32)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/repos/myapp/node_modules/tapable/lib/Hook.js:154:20)
    at Compilation.seal (/repos/myapp/node_modules/webpack/lib/Compilation.js:1244:27)
    at hooks.make.callAsync.err (/repos/myapp/node_modules/webpack/lib/Compiler.js:624:17)
    at _done (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:9:1)
    at _err1 (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:32:22)
    at _addModuleChain (/repos/myapp/node_modules/webpack/lib/Compilation.js:1095:12)
    at processModuleDependencies.err (/repos/myapp/node_modules/webpack/lib/Compilation.js:1007:9)
    at processTicksAndRejections (internal/process/next_tick.js:74:9)
</code>```

rails webpacker:compile compiles to public/packs directory and the error message is referencing a directory that doesn't exist. Also of note, line 2 of /node_modules/tinymce/skins/content/default/content.cssis simply part of a comment block in css:

```<code>/**
 * Copyright (c) Tiny Technologies, Inc. All rights reserved.
 * Licensed under the LGPL or a commercial license.
 * For LGPL see License.txt in the project root for license information.
 * For commercial licenses see https://www.tiny.cloud/
 */
</code>```

I think I need to use another loader (e.g style-loader) to compile the css... but I don't quite know how to do that using webpack's inline syntax.

Any help is appreciated!

答:
According to file-loader's documentation, I can specify the output path via outputPath.

As for webpack's style-loader, I learned you can disable other loaders by prefixing the desired the inline syntax with an !.

// copy tinymce's skins directory into public/packs
require.context(
  '!file-loader?name=[path][name].[ext]&context=node_modules/tinymce&outputPath=js!tinymce/skins',
  true,
  /.*/
);
```

Body:
According to TinyMce's Webpack file-loader documentation, the following snippet will copy TinyMce's skins directory:

require.context(
  'file?name=[path][name].[ext]&context=node_modules/tinymce!tinymce/skins',
  true,
  /.*/
);

I placed this snippet into app/assets/javascript/tinymce.vue right before my include statements for tinymce. Unfortunately, I get the following error thrown by postcss when I attempt to webpack compile:

% rails webpacker:compile

Webpacker is installed
Using /repos/myapp/config/webpacker.yml file for setting up webpack paths
Compiling…
Compilation failed:
CssSyntaxError: /repos/myapp/js/skins/content/default/content.css:2:1: Unknown word
    at Input.error (/repos/myapp/node_modules/postcss/lib/input.js:130:16)
    at Parser.unknownWord (/repos/myapp/node_modules/postcss/lib/parser.js:563:22)
    at Parser.other (/repos/myapp/node_modules/postcss/lib/parser.js:168:12)
    at Parser.parse (/repos/myapp/node_modules/postcss/lib/parser.js:77:16)
    at parse (/repos/myapp/node_modules/postcss/lib/parse.js:17:12)
    at new LazyResult (/repos/myapp/node_modules/postcss/lib/lazy-result.js:60:16)
    at Processor.<anonymous> (/repos/myapp/node_modules/postcss/lib/processor.js:138:12)
    at Processor.process (/repos/myapp/node_modules/postcss/lib/processor.js:117:23)
    at Function.creator.process (/repos/myapp/node_modules/postcss/lib/postcss.js:148:43)
    at OptimizeCssAssetsWebpackPlugin.processCss (/repos/myapp/node_modules/optimize-css-assets-webpack-plugin/src/index.js:65:21)
    at Object.processor (/repos/myapp/node_modules/optimize-css-assets-webpack-plugin/src/index.js:11:18)
    at each (/repos/myapp/node_modules/last-call-webpack-plugin/src/index.js:150:10)
    at arrayEach (/repos/myapp/node_modules/lodash/_arrayEach.js:15:9)
    at forEach (/repos/myapp/node_modules/lodash/forEach.js:38:10)
    at OptimizeCssAssetsWebpackPlugin.process (/repos/myapp/node_modules/last-call-webpack-plugin/src/index.js:147:5)
    at compilation.hooks.optimizeChunkAssets.tapPromise.chunks (/repos/myapp/node_modules/last-call-webpack-plugin/src/index.js:178:28)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:8:17)
    at AsyncSeriesHook.lazyCompileHook (/repos/myapp/node_modules/tapable/lib/Hook.js:154:20)
    at hooks.additionalAssets.callAsync.err (/repos/myapp/node_modules/webpack/lib/Compilation.js:1311:36)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/repos/myapp/node_modules/tapable/lib/Hook.js:154:20)
    at hooks.optimizeTree.callAsync.err (/repos/myapp/node_modules/webpack/lib/Compilation.js:1307:32)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/repos/myapp/node_modules/tapable/lib/Hook.js:154:20)
    at Compilation.seal (/repos/myapp/node_modules/webpack/lib/Compilation.js:1244:27)
    at hooks.make.callAsync.err (/repos/myapp/node_modules/webpack/lib/Compiler.js:624:17)
    at _done (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:9:1)
    at _err1 (eval at create (/repos/myapp/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:32:22)
    at _addModuleChain (/repos/myapp/node_modules/webpack/lib/Compilation.js:1095:12)
    at processModuleDependencies.err (/repos/myapp/node_modules/webpack/lib/Compilation.js:1007:9)
    at processTicksAndRejections (internal/process/next_tick.js:74:9)

rails webpacker:compile compiles to public/packs directory and the error message is referencing a directory that doesn't exist. Also of note, line 2 of /node_modules/tinymce/skins/content/default/content.cssis simply part of a comment block in css:

/**
 * Copyright (c) Tiny Technologies, Inc. All rights reserved.
 * Licensed under the LGPL or a commercial license.
 * For LGPL see License.txt in the project root for license information.
 * For commercial licenses see https://www.tiny.cloud/
 */

I think I need to use another loader (e.g style-loader) to compile the css... but I don't quite know how to do that using webpack's inline syntax.

Any help is appreciated!


问:
What is the difference between interface signals and interface ports?
Suppose we have an interface like this:

```<code>interface Memory_i(input Clock);

    Data_t InData;
    Data_t OutData;
    Address_t Address;

    // To memory controller
    modport Master
    (
        input Clock,
        output InData,
        input OutData,
        output Address
    );

    // To memory
    modport Slave
    (
        input Clock,
        input InData,
        output OutData,
        input Address,
    );

endinterface
</code>```

Is there any significant difference between Clock (interface port) and, let us say, InData (interface signal)? I know that these entities are connected differently when an interface is instantiated. But is there something else? I also noticed that interface ports are frequently used for the clock signal. Is there a reason for that?

UPDATE

I simplified my interface and made two examples where I am trying to use clock in two different ways. I got two slightly different RTL circuits, but I cannot not see any fundamental difference between them.

Clock as a port:

```<code>interface CdcSignal_i(input clock);

    logic data;

    // To memory controller
    modport Master
    (
        input clock,
        output data
    );

    // To memory
    modport Slave
    (
        input clock,
        input data
    );

endinterface

module Cdc(
    CdcSignal_i.Slave slave,
    CdcSignal_i.Master master
);

    logic registerS;
    logic registerM;

    always_ff @(posedge slave.clock) begin
        registerS <= slave.data;
    end

    always_ff @(posedge master.clock) begin
        registerM <= registerS;
        master.data <= registerM;
    end

endmodule

module InterfaceTest(
    input logic clock0,
    input logic clock1,
    input logic data0,
    output data1);

    CdcSignal_i signal0(clock0);
    assign signal0.data = data0;

    CdcSignal_i signal1(clock1);
    assign data1 = signal1.data;

    Cdc cdc(signal0, signal1);

endmodule
</code>```

Clock as a signal:

```<code>interface CdcSignal_i();

    logic data;
     logic clock;

    // To memory controller
    modport Master
    (
        input clock,
        output data
    );

    // To memory
    modport Slave
    (
        input clock,
        input data
    );

endinterface

module Cdc(
    CdcSignal_i.Slave slave,
    CdcSignal_i.Master master
);

    logic registerS;
    logic registerM;

    always_ff @(posedge slave.clock) begin
        registerS <= slave.data;
    end

    always_ff @(posedge master.clock) begin
        registerM <= registerS;
        master.data <= registerM;
    end

endmodule

module InterfaceTest(
    input logic clock0,
    input logic clock1,
    input logic data0,
    output data1);

    CdcSignal_i signal0();
    assign signal0.clock = clock0;
    assign signal0.data = data0;

    CdcSignal_i signal1();
    assign signal1.clock = clock1;
    assign data1 = signal1.data;

    Cdc cdc(signal0, signal1);

endmodule
</code>```

答: You typically see a Clock as input port to an interface because that signal is shared among many other interface and module instances. On the other hand, each instance of your interface creates another instance of the signal InData.

Body:
Suppose we have an interface like this:

interface Memory_i(input Clock);

    Data_t InData;
    Data_t OutData;
    Address_t Address;

    // To memory controller
    modport Master
    (
        input Clock,
        output InData,
        input OutData,
        output Address
    );

    // To memory
    modport Slave
    (
        input Clock,
        input InData,
        output OutData,
        input Address,
    );

endinterface

Is there any significant difference between Clock (interface port) and, let us say, InData (interface signal)? I know that these entities are connected differently when an interface is instantiated. But is there something else? I also noticed that interface ports are frequently used for the clock signal. Is there a reason for that?

UPDATE

I simplified my interface and made two examples where I am trying to use clock in two different ways. I got two slightly different RTL circuits, but I cannot not see any fundamental difference between them.

Clock as a port:

interface CdcSignal_i(input clock);

    logic data;

    // To memory controller
    modport Master
    (
        input clock,
        output data
    );

    // To memory
    modport Slave
    (
        input clock,
        input data
    );

endinterface

module Cdc(
    CdcSignal_i.Slave slave,
    CdcSignal_i.Master master
);

    logic registerS;
    logic registerM;

    always_ff @(posedge slave.clock) begin
        registerS <= slave.data;
    end

    always_ff @(posedge master.clock) begin
        registerM <= registerS;
        master.data <= registerM;
    end

endmodule

module InterfaceTest(
    input logic clock0,
    input logic clock1,
    input logic data0,
    output data1);

    CdcSignal_i signal0(clock0);
    assign signal0.data = data0;

    CdcSignal_i signal1(clock1);
    assign data1 = signal1.data;

    Cdc cdc(signal0, signal1);

endmodule

Clock as a signal:

interface CdcSignal_i();

    logic data;
     logic clock;

    // To memory controller
    modport Master
    (
        input clock,
        output data
    );

    // To memory
    modport Slave
    (
        input clock,
        input data
    );

endinterface

module Cdc(
    CdcSignal_i.Slave slave,
    CdcSignal_i.Master master
);

    logic registerS;
    logic registerM;

    always_ff @(posedge slave.clock) begin
        registerS <= slave.data;
    end

    always_ff @(posedge master.clock) begin
        registerM <= registerS;
        master.data <= registerM;
    end

endmodule

module InterfaceTest(
    input logic clock0,
    input logic clock1,
    input logic data0,
    output data1);

    CdcSignal_i signal0();
    assign signal0.clock = clock0;
    assign signal0.data = data0;

    CdcSignal_i signal1();
    assign signal1.clock = clock1;
    assign data1 = signal1.data;

    Cdc cdc(signal0, signal1);

endmodule


问:
Please help me with Queryable.select
How can I fix this error ?

```<code>>     Type arguments for method Queryable.Select<TSource>,<TResult> ....
>     cannot be inferred from the usage.
>     Try specifying the type arguments explicitly.
</code>```

This is my code

```<code>Comments = e.Comments.AsQueryable().Select(CommentViewMode.ViewModel)
</code>```

It shows the red squiggly line on 'Select'

答:
Minnie,

The LINQ Select extension method for IQueryable takes a function as an argument.  The documentation from Microsoft shows the signature and a simple example:

```<code>List<int> range =
    new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Project the square of each int value.
IEnumerable<int> squares =
    range.AsQueryable().Select(x => x * x);
</code>```

So the Select method expects a function that takes an argument of the same type as your queryable enumerates.  In the example above, it is an int.  In the code you provided it will be the type of one of your Comments elements.  I expect you need to write your select like this:

var something = e.Comments.AsQueryable().Select(x => x.SomePropertyOfYourCommentClass)

Title: Please help me with Queryable.select

Body:
How can I fix this error ?

>     Type arguments for method Queryable.Select<TSource>,<TResult> ....
>     cannot be inferred from the usage.
>     Try specifying the type arguments explicitly.

This is my code

Comments = e.Comments.AsQueryable().Select(CommentViewMode.ViewModel)

It shows the red squiggly line on 'Select'

Body:
Minnie,

The LINQ Select extension method for IQueryable takes a function as an argument.  The documentation from Microsoft shows the signature and a simple example:

List<int> range =
    new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Project the square of each int value.
IEnumerable<int> squares =
    range.AsQueryable().Select(x => x * x);

So the Select method expects a function that takes an argument of the same type as your queryable enumerates.  In the example above, it is an int.  In the code you provided it will be the type of one of your Comments elements.  I expect you need to write your select like this:

var something = e.Comments.AsQueryable().Select(x => x.SomePropertyOfYourCommentClass)


问:
Add ODBC user DSN using python ctypes.windll.ODBCCP32.SQLConfigDataSource
I am trying to add new ODBC data source in python and found this code online which seem to work with python 2 (as other people mentioned but I have not tried) but does not work with python 3 (I am using 3.6).  The code runs without error but did not add new DSN to the system (always return 0).

I searched around and found some people mentioning it might be due to the encode issue, so I have tried to change the attribute part to bytes (nul.join(attrib)) with different encoding but none of them works.

Here is part of the code:

ODBC_ADD_DSN = 1        # Add data source, user DSN only
ODBC_CONFIG_DSN = 2     # Configure (edit) data source
ODBC_REMOVE_DSN = 3     # Remove data source
ODBC_ADD_SYS_DSN = 4    # add a system DSN
ODBC_CONFIG_SYS_DSN = 5 # Configure a system DSN
ODBC_REMOVE_SYS_DSN = 6 # remove a system DSN

def add_dsn(name, driver, **kw):
    nul, attrib = '', []
    kw['DSN'] = name
    for attr, val in kw.items():
        attrib.append('%s=%s' % (attr, val))

    return ctypes.windll.ODBCCP32.SQLConfigDataSource(0, ODBC_ADD_DSN, driver, nul.join(attrib))

#
if __name__ == "__main__":
    print (add_dsn('test', 'SQL Server', server='(local)', description = 'Testing'))
```

Can anyone help on how to resolve this issue or provide a solution to add new ODBC data sources using python. Thanks!

答:
To connect to SQL server using python 3 , I use the below statement and can get the data without any errors.

```<code>import pyodbc
import pandas as pd
cnxn = pyodbc.connect(driver='{SQL Server}', server='YourServer', database='YourDBName',
               trusted_connection='yes')
cursor = cnxn.cursor()
</code>```

then you can use pd.read_sql command to retrieve any data.

```<code>print(pd.read_sql("SELECT * FROM [fruits]",cnxn))
</code>```

Output from Database:

```<code>  fruiteater       Fruit1  Fruit2       Fruit3 Fruit4       Fruit5  Fruit6
      Aaron       Orange    Pear        Apple   None         None    None
         Bob        Apple  Orange  Blueberries  Peach        Mango  Banana
      Carter         Pear  Orange        Apple   None         None    None
       David  Blueberries    None         None   None         None    None
     Earnest        Mango  Orange         Pear  Apple  Blueberries    None
       Frank  Raspberries    None         None   None         None    None
</code>```

Body:
I am trying to add new ODBC data source in python and found this code online which seem to work with python 2 (as other people mentioned but I have not tried) but does not work with python 3 (I am using 3.6).  The code runs without error but did not add new DSN to the system (always return 0).

I searched around and found some people mentioning it might be due to the encode issue, so I have tried to change the attribute part to bytes (nul.join(attrib)) with different encoding but none of them works.

Here is part of the code:

ODBC_ADD_DSN = 1        # Add data source, user DSN only
ODBC_CONFIG_DSN = 2     # Configure (edit) data source
ODBC_REMOVE_DSN = 3     # Remove data source
ODBC_ADD_SYS_DSN = 4    # add a system DSN
ODBC_CONFIG_SYS_DSN = 5 # Configure a system DSN
ODBC_REMOVE_SYS_DSN = 6 # remove a system DSN

def add_dsn(name, driver, **kw):
    nul, attrib = '', []
    kw['DSN'] = name
    for attr, val in kw.items():
        attrib.append('%s=%s' % (attr, val))

    return ctypes.windll.ODBCCP32.SQLConfigDataSource(0, ODBC_ADD_DSN, driver, nul.join(attrib))

#
if __name__ == "__main__":
    print (add_dsn('test', 'SQL Server', server='(local)', description = 'Testing'))

Can anyone help on how to resolve this issue or provide a solution to add new ODBC data sources using python. Thanks!

Body:
To connect to SQL server using python 3 , I use the below statement and can get the data without any errors.

import pyodbc
import pandas as pd
cnxn = pyodbc.connect(driver='{SQL Server}', server='YourServer', database='YourDBName',
               trusted_connection='yes')
cursor = cnxn.cursor()

then you can use pd.read_sql command to retrieve any data.

print(pd.read_sql("SELECT * FROM [fruits]",cnxn))

Output from Database:

  fruiteater       Fruit1  Fruit2       Fruit3 Fruit4       Fruit5  Fruit6
      Aaron       Orange    Pear        Apple   None         None    None
         Bob        Apple  Orange  Blueberries  Peach        Mango  Banana
      Carter         Pear  Orange        Apple   None         None    None
       David  Blueberries    None         None   None         None    None
     Earnest        Mango  Orange         Pear  Apple  Blueberries    None
       Frank  Raspberries    None         None   None         None    None


问:
Can we freeze selected neurons in a fully connected layer in keras?
So , I need to freeze only a neuron or two in the fully connected dense layer in keras, so that its weight doesn't change during the course of training. Is there a way to do this in keras ?</p>

答:
You might want define a mask and set the elements of the mask corresponding to the neuron you want to freeze to 0. This way gradient won't propagate and the neuron won't be trained.

Something similar to:
https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/model_pruning


问:
Sylius/FriendsOfSymfony: What is a "token" Grant Type?
The documentation for Sylius's REST API indicates its oAuth authorization system supports three grant types.

```<code>php bin/console sylius:oauth-server:create-client \
    --grant-type="password" \
    --grant-type="refresh_token" \
    --grant-type="token"
</code>```

The password grant type allows you to fetch a token from /api/oauth/v2/token using your admin username and password (assuming that user has the ROLE_API_ACCESS role).

When you fetch this token, it comes down with an access_token and a  refresh_token.

```<code>{
    "access_token":"ODE0NzA2NmU1NGVkNDc5ODNiNjcxZDBhZTA0NGY3MzY4NjBlMTc3ZDk0ZjM3MTIyOTlkMTQzMWU3YjM3ODc5ZQ",
    "expires_in":3600,
    "token_type":"bearer",
    "scope":null,
    "refresh_token":"NjNlNGY1YTQ5NmJhMzZiNzdlY2JmMzQyZDc5MGZkYTA5Mzg4MDc2MmRmZTRmOWE0MmMwNzU4NzBmMGM3YzVmZQ"
}
</code>```

When your token expires, if your client has the refresh_token grant type, you can use the /api/oauth/v2/token endpoint to fetch a new token using the refresh_token parameter/argument.

So what is a token grant type?  When I think about this, I get stuck on "How could you fetch a token from /api/oauth/v2/token if you don't have a token in the first place?" or "If you already HAD a token that hadn't expired why would you need to use token to get a new one?"

So what am I missing?  What is the token grant-type for?

答:
There are several grant types provided by OAuth2.  See them here.  I'm not sure exactly which one is used by sylius when you ask for "token" but I assume authorization code.

```<code>The most common OAuth 2.0 grant types are listed below.

   Authorization Code
   Implicit
   Password
   Client Credentials
   Device Code
   Refresh Token
</code>```

Body:
The documentation for Sylius's REST API indicates its oAuth authorization system supports three grant types.

php bin/console sylius:oauth-server:create-client \
    --grant-type="password" \
    --grant-type="refresh_token" \
    --grant-type="token"

The password grant type allows you to fetch a token from /api/oauth/v2/token using your admin username and password (assuming that user has the ROLE_API_ACCESS role).

When you fetch this token, it comes down with an access_token and a  refresh_token.

{
    "access_token":"ODE0NzA2NmU1NGVkNDc5ODNiNjcxZDBhZTA0NGY3MzY4NjBlMTc3ZDk0ZjM3MTIyOTlkMTQzMWU3YjM3ODc5ZQ",
    "expires_in":3600,
    "token_type":"bearer",
    "scope":null,
    "refresh_token":"NjNlNGY1YTQ5NmJhMzZiNzdlY2JmMzQyZDc5MGZkYTA5Mzg4MDc2MmRmZTRmOWE0MmMwNzU4NzBmMGM3YzVmZQ"
}

When your token expires, if your client has the refresh_token grant type, you can use the /api/oauth/v2/token endpoint to fetch a new token using the refresh_token parameter/argument.

So what is a token grant type?  When I think about this, I get stuck on "How could you fetch a token from /api/oauth/v2/token if you don't have a token in the first place?" or "If you already HAD a token that hadn't expired why would you need to use token to get a new one?"

So what am I missing?  What is the token grant-type for?

Body:
There are several grant types provided by OAuth2.  See them here.  I'm not sure exactly which one is used by sylius when you ask for "token" but I assume authorization code.

The most common OAuth 2.0 grant types are listed below.

   Authorization Code
   Implicit
   Password
   Client Credentials
   Device Code
   Refresh Token


问:
Open graph og:video Meta Tags content
I'm trying to set up a page which can be properly scraped by Facebook when it's shared/liked. The page will have a YouTube video associated with it, so in the content attribute of the og:video tag, should I put the YouTube video embed link or the actual youtube page link for it to appear on Facebook with the little "Preview" button that plays the video in Facebook?

Hope someone can help! Thanks!

答:
        <meta property="og:video" content="http://example.com/awesome.flv" />
        <meta property="og:video:height" content="640" />
        <meta property="og:video:width" content="385" />
        <meta property="og:video:type" content="application/x-shockwave-flash" />
        ...

```

The link of the .flv file.... check out https://developers.facebook.com/docs/opengraph/#types

ContentLicense: CC BY-SA 2.5

Title: Open graph og:video Meta Tags content

Body:
<html xmlns:og="http://ogp.me/ns#">
    <head>
        <!-- ... -->
        <!-- [REQUIRED TAGS] -->
        <meta property="og:video" content="http://example.com/awesome.flv" />
        <meta property="og:video:height" content="640" />
        <meta property="og:video:width" content="385" />
        <meta property="og:video:type" content="application/x-shockwave-flash" />
        ...
    </head>

The link of the .flv file.... check out https://developers.facebook.com/docs/opengraph/#types


问:
Iterating through a list of strings and appending a json returned element for each term in the list
Warning this is very very complex. (I'm an idiot and should probably take a break), Its a confusing title but I'll do my best to explain what I'm running into,

I have this code:

```<code>test_terms = ['spartan', 'forerunner', 'didact']

test_list = []

for term in test_terms:

    search_term = term
    search_service = PyMsCognitiveWebSearch('API_Key', search_term,
                                        custom_params={'title': 'name', 'domain': 'url', 'mkt': 'en-usa', 'description': 'url'})
    result = search_service.search(limit=3, format='json')
    test_list.append(result[term].json)

print(test_list)
</code>```

This works when its outside of the loop and I run simply this:

```<code>search_term = 'spartan'
search_service = PyMsCognitiveWebSearch('API_Key', search_term,
                                        custom_params={'title': 'name', 'domain': 'url', 'mkt': 'en-usa',
                                                       'description': 'url'})
result = search_service.search(limit=3, format='json')
test_list.append(result[0].json)
print(test_list)
</code>```

which gives me:

```<code>[{'id': 'https://api.cognitive.microsoft.com/api/v7/#WebPages.0', 'name': 'Obstacle Course Races | Spartan Race', 'url': 'https://www.spartan.com/', 'isFamilyFriendly': True, 'displayUrl': 'https://www.spartan.com', 'snippet': 'Spartan Race is the global leader in obstacle course races, with the right challenge for anyone - from first-time racers to elite athletes.', 'deepLinks': ... etc, for three more results}]
</code>```

My first instinct wast to do simply for term in range(len(test_terms)):, however this returned a result but instead of the items in the list, I got information on the number 1 through 3.

Next I tried for item, term enumerate(test_terms):

but I got this error:

```<code>TypeError: list indices must be integers or slices, not str
</code>```

Which makes sense, however I'm not sure exactly how to proceed given that the index is a "string" and I've tried enumerating it in two different ways, removing result[term].json and changing it to result.json throws an object error too.

Any help would be great! Also the package specs if it helps.

UPDATE:

result is a web object that is essentially this (via the documentation):

```<code>packaged_results = [WebResult(single_result_json) for single_result_json in json_results.get("webPages", {}).get("value", [])]
</code>```

Link the source code

But its a giant nested list, I wrote it out on a white board, it returns 3 lists consisting of 9 elements, of mixed types, one list and one dictionary. Literally my nightmare.

答:
The way you're using 'term' in your for loop makes 'term' a string (one of ['spartan', 'forerunner', 'didact']). You're looking for an integer to use in "result[term]", so, stick with enumerate, but remember using enumerate the first part of the tuple is the "enumeration" and the second part is the item.</p>

```<code>for i, term in enumerate(test_terms):
    ...
    test_list.append(result[i].json)
</code>```

Body:
Warning this is very very complex. (I'm an idiot and should probably take a break), Its a confusing title but I'll do my best to explain what I'm running into,

I have this code:

test_terms = ['spartan', 'forerunner', 'didact']

test_list = []

for term in test_terms:

    search_term = term
    search_service = PyMsCognitiveWebSearch('API_Key', search_term,
                                        custom_params={'title': 'name', 'domain': 'url', 'mkt': 'en-usa', 'description': 'url'})
    result = search_service.search(limit=3, format='json')
    test_list.append(result[term].json)

print(test_list)

This works when its outside of the loop and I run simply this:

search_term = 'spartan'
search_service = PyMsCognitiveWebSearch('API_Key', search_term,
                                        custom_params={'title': 'name', 'domain': 'url', 'mkt': 'en-usa',
                                                       'description': 'url'})
result = search_service.search(limit=3, format='json')
test_list.append(result[0].json)
print(test_list)

which gives me:

[{'id': 'https://api.cognitive.microsoft.com/api/v7/#WebPages.0', 'name': 'Obstacle Course Races | Spartan Race', 'url': 'https://www.spartan.com/', 'isFamilyFriendly': True, 'displayUrl': 'https://www.spartan.com', 'snippet': 'Spartan Race is the global leader in obstacle course races, with the right challenge for anyone - from first-time racers to elite athletes.', 'deepLinks': ... etc, for three more results}]

My first instinct wast to do simply for term in range(len(test_terms)):, however this returned a result but instead of the items in the list, I got information on the number 1 through 3.

Next I tried for item, term enumerate(test_terms):

but I got this error:

TypeError: list indices must be integers or slices, not str

Which makes sense, however I'm not sure exactly how to proceed given that the index is a "string" and I've tried enumerating it in two different ways, removing result[term].json and changing it to result.json throws an object error too.

Any help would be great! Also the package specs if it helps.

UPDATE:

result is a web object that is essentially this (via the documentation):

packaged_results = [WebResult(single_result_json) for single_result_json in json_results.get("webPages", {}).get("value", [])]

Link the source code

But its a giant nested list, I wrote it out on a white board, it returns 3 lists consisting of 9 elements, of mixed types, one list and one dictionary. Literally my nightmare.

Body:
The way you're using 'term' in your for loop makes 'term' a string (one of ['spartan', 'forerunner', 'didact']). You're looking for an integer to use in "result[term]", so, stick with enumerate, but remember using enumerate the first part of the tuple is the "enumeration" and the second part is the item.

for i, term in enumerate(test_terms):
    ...
    test_list.append(result[i].json)


问:
Is there a way to upload file before custom button click,and then using ajax send it to controller action method?
I am quite new to Telerik Html Kendo. My aim is to upload a file first. Then, invoke the corresponding action method in 'Administration' controller through ajax that should take the uploaded file and other parameters on clicking the 'Submit' button as shown in image below.

Most of Telerik examples show asynchronous upload feature which invokes controller method to upload file. I don't want to do this way.

However, I have tried to upload file with onSelect event of kendo upload. It shows that file gets included however it doesn't upload.

As a result, I am unable to see any info. about uploaded file in onSuccess and onComplete event.
I used formData on 'Submit' button click. However I receive null at the action method all time.

Any correct way of doing this?

Here is my html code for file upload:

```<code><div class="well well-sm" style="width:inherit;text-align: center;float:left;">
            <!--form method="post"-->
                <!--div class="demo-section k-content">
                    <input name="files" id="files" type="file" value="Upload a Data File"/>
                </div-->
            <!--/form-->
            @(Html.Kendo().Upload()
        .Name("files")
        .Multiple(false)
        .Messages(m => m.Select("Please upload a Data File"))
        .HtmlAttributes(new { aria_label = "file" })
        .Events(events => events
                .Complete("onComplete")
                .Select("onSelect")
                .Success("onSuccess")
                .Upload("onUpload")
                .Progress("onProgress"))
        //.Async(a=>a.AutoUpload(false))
        .Validation(v => v.AllowedExtensions(new string[] { ".csv", ".xls", ".xlsx", ".txt" }))
        )
        </div>
</code>```

Here is the javascript code for all the js events I want to invoke.

```<code><script>

   var _files;
        function onSelect(e) {
            var files = e.files;
            alert(files[0].name);
            _files = files[0];
            //file = files[0].name;
                var acceptedFiles = [".xlsx", ".xls", ".txt", ".csv"]
                var isAcceptedFormat = ($.inArray(files[0].extension, acceptedFiles)) != -1

            if (!isAcceptedFormat) {
                e.preventDefault();
                $("#meter_addt_details").addClass("k-state-disabled");
                //$("#submit_btn").addClass("k-state-disabled");
                document.getElementById("submit_btn").disabled = true;
                alert("Please upload correct file. Valid extensions are xls, xlsx,txt,csv");
            }
            else {
/* Here I tried to upload file didn't work out */
                $("#meter_addt_details").removeClass("k-state-disabled");
               // $("#submit_btn").removeClass("k-state-disabled");
                document.getElementById("submit_btn").disabled = false;
                @*
                $("#files").kendoUpload({
                async: {
                    saveUrl: '@Url.Action("ReadMeterFile","Administration")',
                    autoUpload: false
                    }
                }); *@
                $("#files").kendoUpload();
                //$(".k-upload-selected").click();
                @*var upload = $("#files").data("kendoUpload");
                upload.upload(); *@
            }
        }
        @*
        function onUpload(e) {
            $(".k-upload-selected").trigger('click');
            //console.log("Upload :: " + getFileInfo(e));
        }
        function onSuccess(e) {

            console.log(files[0].name);
            _files = e.files[0];
        }
        function onProgress(e) {
            console.log("Upload progress :: " + e.percentComplete);
        }
        function onComplete(e) {
            console.log("Complete");
        }
        function onSubmitButtonClick(e) {

            var formData = new FormData();
            alert(_files.name);
            formData.append('files', _files);
            formData.append('order_num', $("#order").val());
            formData.append('purchase_order', $("#purchase_order").val());
            $.ajax({
                url: '@Url.Action("ReadFile","Administration")',
                data: formData,
                type: 'POST',
                processData: false,
                contentType: false,
                dataType: "json",
                success: function (data) {
                    alert("Good");
                }
            });
        }
    </script>
</code>```

Here is my controller:

```<code>public ActionResult ReadFile(IEnumerable<HttpPostedFileBase> files,string order_num, string purchase_order)
        {
            System.Diagnostics.Debug.WriteLine("File length:"+files.ToList().Capacity);
            foreach(var f in files)
            {
                System.Diagnostics.Debug.WriteLine(f.FileName);
                var fileName = Path.GetFileName(f.FileName);
                var destinationPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);

                f.SaveAs(destinationPath);
            }
            //System.Diagnostics.Debug.WriteLine(file);
            /*
            System.Diagnostics.Debug.WriteLine("File:"+files);
            System.Diagnostics.Debug.WriteLine("Order:"+order_num);
            System.Diagnostics.Debug.WriteLine("Purchase Order:"+purchase_order);
            return Content("");
        }
</code>```

答:
Here is some code I used before for manually uploading from the kendo upload widget. From your question I think what you are looking for is the way to correctly get the info on the controller side.  However, I will add the code I have used which should help you out. (My code uploads a PDF)

```<code>@(Html.Kendo().Upload()
    .Name("pdf-file")
    .Multiple(false)
    .Validation(v => v.AllowedExtensions(new string[] { "pdf" }))
    .Events(ev => ev.Select("pdfSelected"))
)

function pdfSelected(e) {
    if (e.files != null && e.files.length > 0 && e.files[0] != null) {
        var file = e.files[0];

        if (file.validationErrors != null && file.validationErrors.length > 0) {
            return; //These errors will show in the UI
        }

        var formData = new FormData();
        formData.append('PdfFile', file.rawFile);
        formData.append('AdditionalValue', 'Some String');

        $.ajax({
            type: 'post',
            url: '[SOMEURL]',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: pdfUploaded
        });
    }
}

function pdfUploaded(data) {
    //Whatever you want.
}
</code>```

Inside of pdfSelected is the code that actually posts the file.  If you want to do it all at the same time along with other properties, via a submit button. Then instead of performing the upload there.  Do nothing but your validation for the upload or don't implement pdfSelected and wait until submit is clicked to perform the validation(probably better).  Then on your button click

```<code>//Or course check files.length to avoid errors. Not added to keep it short
var files = $('#pdf-file').data('kendoUpload').getFiles();
var file = files[0];
</code>```

Everything from "var formData = new FormData();" down, from the code above remains the same.  Here is the controller code.

```<code>public ActionResult MyAction() {
    string additionalValue = (string) this.Request.Form["AdditionalValue"];
    HttpPostedFileBase file = this.Request.Files["PdfFile"];

    //Do whatever you need to with them.
}
</code>```

The file's rawFile property is what you need not just the file object because that is kendo specific.

Body:
I am quite new to Telerik Html Kendo. My aim is to upload a file first. Then, invoke the corresponding action method in 'Administration' controller through ajax that should take the uploaded file and other parameters on clicking the 'Submit' button as shown in image below.

Most of Telerik examples show asynchronous upload feature which invokes controller method to upload file. I don't want to do this way.

However, I have tried to upload file with onSelect event of kendo upload. It shows that file gets included however it doesn't upload.

As a result, I am unable to see any info. about uploaded file in onSuccess and onComplete event.
I used formData on 'Submit' button click. However I receive null at the action method all time.

Any correct way of doing this?

Here is my html code for file upload:

            @(Html.Kendo().Upload()
        .Name("files")
        .Multiple(false)
        .Messages(m => m.Select("Please upload a Data File"))
        .HtmlAttributes(new { aria_label = "file" })
        .Events(events => events
                .Complete("onComplete")
                .Select("onSelect")
                .Success("onSuccess")
                .Upload("onUpload")
                .Progress("onProgress"))
        //.Async(a=>a.AutoUpload(false))
        .Validation(v => v.AllowedExtensions(new string[] { ".csv", ".xls", ".xlsx", ".txt" }))
        )

Here is the javascript code for all the js events I want to invoke.

Here is my controller:

public ActionResult ReadFile(IEnumerable<HttpPostedFileBase> files,string order_num, string purchase_order)
        {
            System.Diagnostics.Debug.WriteLine("File length:"+files.ToList().Capacity);
            foreach(var f in files)
            {
                System.Diagnostics.Debug.WriteLine(f.FileName);
                var fileName = Path.GetFileName(f.FileName);
                var destinationPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);

                f.SaveAs(destinationPath);
            }
            //System.Diagnostics.Debug.WriteLine(file);
            /*
            System.Diagnostics.Debug.WriteLine("File:"+files);
            System.Diagnostics.Debug.WriteLine("Order:"+order_num);
            System.Diagnostics.Debug.WriteLine("Purchase Order:"+purchase_order);
            return Content("");
        }

Body:
Here is some code I used before for manually uploading from the kendo upload widget. From your question I think what you are looking for is the way to correctly get the info on the controller side.  However, I will add the code I have used which should help you out. (My code uploads a PDF)

@(Html.Kendo().Upload()
    .Name("pdf-file")
    .Multiple(false)
    .Validation(v => v.AllowedExtensions(new string[] { "pdf" }))
    .Events(ev => ev.Select("pdfSelected"))
)

function pdfSelected(e) {
    if (e.files != null && e.files.length > 0 && e.files[0] != null) {
        var file = e.files[0];

        if (file.validationErrors != null && file.validationErrors.length > 0) {
            return; //These errors will show in the UI
        }

        var formData = new FormData();
        formData.append('PdfFile', file.rawFile);
        formData.append('AdditionalValue', 'Some String');

        $.ajax({
            type: 'post',
            url: '[SOMEURL]',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: pdfUploaded
        });
    }
}

function pdfUploaded(data) {
    //Whatever you want.
}

Inside of pdfSelected is the code that actually posts the file.  If you want to do it all at the same time along with other properties, via a submit button. Then instead of performing the upload there.  Do nothing but your validation for the upload or don't implement pdfSelected and wait until submit is clicked to perform the validation(probably better).  Then on your button click

//Or course check files.length to avoid errors. Not added to keep it short
var files = $('#pdf-file').data('kendoUpload').getFiles();
var file = files[0];

Everything from "var formData = new FormData();" down, from the code above remains the same.  Here is the controller code.

public ActionResult MyAction() {
    string additionalValue = (string) this.Request.Form["AdditionalValue"];
    HttpPostedFileBase file = this.Request.Files["PdfFile"];

    //Do whatever you need to with them.
}

The file's rawFile property is what you need not just the file object because that is kendo specific.


问:
Can I close the Bootstrap modal once the link has been clicked?
Right now, I'm using this in a Bootstrap modal to redirect to a site:

```<code><a href="http://www.example.com/" href="_blank">click</a>
</code>```

I want the modal to be closed once the link has been clicked, so I thought adding data-dismiss="modal" to the tag would work, however it causes the modal to close without the link being opened.

Can I combine these and make the modal close after the URL opens?

答:
This worked for me.
click

ContentLicense: CC BY-SA 3.0

Body:
Right now, I'm using this in a Bootstrap modal to redirect to a site:

click

I want the modal to be closed once the link has been clicked, so I thought adding data-dismiss="modal" to the tag would work, however it causes the modal to close without the link being opened.

Can I combine these and make the modal close after the URL opens?

Body:
This worked for me.
<a onclick="location.href='http://www.example.com/';" data-dismiss="modal">click</a>


问:
Where do I find the code that generates text overlays (such as "Out of Stock") on product images on product category webpages?
I can't find the code that generates the following HTML:

```<code><div class="woocommerce">
    <span class="soldout">Out of stock</span>
</div>
</code>```

I've searched in all the files that came with the WooCommerce plugin for the text "soldout".

I downloaded my whole website and searched for "soldout" and could not find it.

I even searched (via a MySQL query "... like '%soldout%'") in the WooCommerce tables and other tables in my WordPress database and could not locate the text "soldout".

I would like to see where this code resides so I can hook into it to add additional custom overlays such as "Preferred".

答:
I found the code.  This is a warning to others that Windows Explorer, even though it has the feature to search in "File contents", should not be used to locate text inside files.

I used Notepad++ to search the files in my downloaded website for "soldout".  Notepad++, unlike Windows Explorer, was able to locate not only the files that contained the text that I was looking for but also the line number where the text was located on in the file.

Body:
I can't find the code that generates the following HTML:

    Out of stock

I've searched in all the files that came with the WooCommerce plugin for the text "soldout".

I downloaded my whole website and searched for "soldout" and could not find it.

I even searched (via a MySQL query "... like '%soldout%'") in the WooCommerce tables and other tables in my WordPress database and could not locate the text "soldout".

I would like to see where this code resides so I can hook into it to add additional custom overlays such as "Preferred".


问:
React - Create grid using bootstrap
I am trying to create a website and trying to create a grid. As I am not good with CSS I am using bootstrap. </p>

<p>However I am not able to figure out how to create grid from an array of images I have such that it's reactive as well. </p>

```<code>import Container from 'react-bootstrap/Container'
import Row from 'react-bootstrap/Row'
import Col from 'react-bootstrap/Col'

import React, { Component } from 'react'

export default class MoviesComponent extends Component {
    componentDidMount() {
        this.props.fetchShows()
    }
    render() {
        // console.log(this.props)
        let popular_movies = this.props.popular_movies
        // const items = popular_movies.length > 0 ? popular_movies.map((item)=> <div key={item.id}>item.title</div>) : "tt"
        return (
            popular_movies.length > 0 ?
            popular_movies.map((movie) => {
                return <Container className="container" key={movie.id}>
                            <Row>
                            <Col><img src= {"http://image.tmdb.org/t/p/w185"+movie.poster_path} alt={movie.title} /></Col>
                            </Row>

                 </Container>
             })
             : <div>Loading...</div>

        )
    }
}
</code>```

答:
You need to wrap your mapped items in a HTML element or React Fragment. As far as Row/Col goes, it seems correct, however strongly suggest avoiding the library, its not maintained. Go for other Bootstrap based flavors.</p>

```<code>return (
  popular_movies.length ?
    <Container className="container">
      <Row>
      {
        popular_movies.map((movie) => <Col xs={1} key={movie.id}>{movie.id}</Col>)
      }
      </Row>
    </Container>
    : <div>Loading...</div>
)
</code>```

Title: React - Create grid using bootstrap

Body:
I am trying to create a website and trying to create a grid. As I am not good with CSS I am using bootstrap.

However I am not able to figure out how to create grid from an array of images I have such that it's reactive as well.

import Container from 'react-bootstrap/Container'
import Row from 'react-bootstrap/Row'
import Col from 'react-bootstrap/Col'

import React, { Component } from 'react'

export default class MoviesComponent extends Component {
    componentDidMount() {
        this.props.fetchShows()
    }
    render() {
        // console.log(this.props)
        let popular_movies = this.props.popular_movies
        // const items = popular_movies.length > 0 ? popular_movies.map((item)=>
item.title
) : "tt"
        return (
            popular_movies.length > 0 ?
            popular_movies.map((movie) => {
                return <Container className="container" key={movie.id}>
                            <Row>
                            <Col></Col>
                            </Row>

                 </Container>
             })
             :
Loading...

        )
    }
}

Body:
You need to wrap your mapped items in a HTML element or React Fragment. As far as Row/Col goes, it seems correct, however strongly suggest avoiding the library, its not maintained. Go for other Bootstrap based flavors.

return (
  popular_movies.length ?
    <Container className="container">
      <Row>
      {
        popular_movies.map((movie) => <Col xs={1} key={movie.id}>{movie.id}</Col>)
      }
      </Row>
    </Container>
    : <div>Loading...</div>
)


问:
Sum of two arrays
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

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

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}
</code>```

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).

答:
Its impossible to first do a[g] when dynamically getting g.

Your first lines in main should be:

```<code>int i,g;
int *a,*b;
printf("Give size of both arrays: ");
scanf("%d",&g);
a = (int *)malloc(g*sizeof(int));
b = (int *)malloc(g*sizeof(int));
</code>```

Title: Sum of two arrays

Body:
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

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

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).

Body:
Its impossible to first do a[g] when dynamically getting g.

Your first lines in main should be:

int i,g;
int *a,*b;
printf("Give size of both arrays: ");
scanf("%d",&g);
a = (int *)malloc(g*sizeof(int));
b = (int *)malloc(g*sizeof(int));


问:
How to summarise (dplyr) user specified variables reactively in flexdashboard/shiny?
I am trying to develop a shiny dashboard app that is able to produce a bar graph for different outcome variables that can be selected by the user.  To do so, I need to subset my data reactively to generate aggregate data frames. I am able to have the code below successfully filter my data reactively, but I am running into trouble when I try to use dplyr::summarise() reactively.

Here is my data

```<code>dput(head(df))

structure(
    list(
      geoid = c(
        "01001020200",
        "01001020300",
        "01001020700",
        "01001020802",
        "01001021000",
        "01001021100"
      ),
      state = c(
        "Alabama",
        "Alabama",
        "Alabama",
        "Alabama",
        "Alabama",
        "Alabama"
      ),
      county = c(
        "Autauga County",
        "Autauga County",
        "Autauga County",
        "Autauga County",
        "Autauga County",
        "Autauga County"
      ),
      ozzone = structure(
        c(1L, 1L, 2L, 1L, 1L, 1L),
        .Label = c("non.oz", "oz"),
        class = "factor"
      ),
      tract_type = c(
        "LICs",
        "Contiguous",
        "LICs",
        "Contiguous",
        "Contiguous",
        "LICs"
      ),
      investment_score_1_low_10_high = c(4,
                                         6, 9, 10, 5, 6),
      socioeconomic_change_flag_1_yes_blank_no = c(0,
                                                   0, 0, 0, 0, 0),
      fips_county = c("01001", "01001", "01001", "01001",
                      "01001", "01001"),
      total_empl = c(51809L, 51809L, 51809L, 51809L,
                     51809L, 51809L),
      total_payroll = c(338395L, 338395L, 338395L,
                        338395L, 338395L, 338395L),
      total_establishments = c(5090L, 5090L,
                               5090L, 5090L, 5090L, 5090L),
      largest_employer = c(72L, 72L, 72L,
                           72L, 72L, 72L),
      largest_employer_bypayroll = c(44L, 44L, 44L,
                                     44L, 44L, 44L),
      trend_employee_change = c(
        2735.60000000046,
        2735.60000000046,
        2735.60000000046,
        2735.60000000046,
        2735.60000000046,
        2735.60000000046
      ),
      trend_payroll_change = c(
        23074.8000000037,
        23074.8000000037,
        23074.8000000037,
        23074.8000000037,
        23074.8000000037,
        23074.8000000037
      ),
      trend_establishment_change = c(
        53.4000000000084,
        53.4000000000084,
        53.4000000000084,
        53.4000000000084,
        53.4000000000084,
        53.4000000000084
      ),
      damage_cost_weather_total = c(20000, 20000, 20000, 20000,
                                    20000, 20000),
      deaths_weather_total = c(0L, 0L, 0L, 0L, 0L, 0L),
      medianrent = c(537, 633, 525, 680, 409, 303),
      vacancyrate = c(
        0.108200455580866,
        0.113652113652114,
        0.0436681222707424,
        0.0512166859791425,
        0.229962546816479,
        0.21030303030303
      ),
      total_pop = c(503, 827, 900, 2989, 740, 813),
      undertwo_percent = c(
        0.391650099403579,
        0.351874244256348,
        0.397777777777778,
        0.17096018735363,
        0.301351351351351,
        0.263222632226322
      ),
      mobility_rate = c(
        0.133702166897188,
        0.0737753882915173,
        0.196514423076923,
        0.172716680111141,
        0.0641304347826087,
        0.0681084570690769
      ),
      unemploy_rate = c(
        0.0176991150442478,
        0.0273203592814371,
        0.109881724532621,
        0.0127906976744186,
        0.0344982078853047,
        0.0281910728269381
      ),
      median_income = c(41287, 46806, 41250, 64439,
                        46607, 36450),
      renter_percent = c(
        0.337653478854025,
        0.310596310596311,
        0.331877729257642,
        0.268110942458949,
        0.328686327077748,
        0.365986394557823
      ),
      blackaa_percent = c(
        0.5451197053407,
        0.264697193500739,
        0.145906432748538,
        0.152916262243007,
        0.258583690987124,
        0.530922930542341
      ),
      hispanic_percent = c(
        0.0105893186003683,
        0.0803545051698671,
        0.0400584795321637,
        0.0137651107385511,
        0.00822603719599428,
        0.00666032350142721
      ),
      transit_score_mean = c(0, 0, 0, 0, 0, 0),
      life_expectancy = c(75.67, 75.67, 75.67, 75.67, 75.67, 75.67),
      trend_life_expectancy = c(5.1, 5.1, 5.1, 5.1, 5.1, 5.1),
      median_monthly_housing_costs = c(885,
                                       885, 885, 885, 885, 885),
      pestilence_2018 = c(2, 2, 2, 2, 2,
                          2),
      total_pop_county = c(6772, 6772, 6772, 6772, 6772, 6772),
      deaths_weather_pop = c(0, 0, 0, 0, 0, 0),
      cost_weather_pop = c(
        2.95333727111636,
        2.95333727111636,
        2.95333727111636,
        2.95333727111636,
        2.95333727111636,
        2.95333727111636
      ),
      Male_HSgrad = c(75, 68, 211, 189, 97,
                      42),
      Male_SomeCollege = c(28, 18, 51, 111, 74, 38),
      Male_AssocDeg = c(4,
                        6, 0, 63, 0, 21),
      Male_BachDeg = c(7, 9, 0, 11, 0, 9),
      Male_GradDeg = c(0,
                       0, 0, 29, 6, 0),
      MaleEduAboveHS = c(114, 101, 262, 403, 177,
                         110),
      Total_Male18.24 = c(145, 123, 285, 455, 202, 110),
      MaleEduHSAbove_pop = c(
        0.786206896551724,
        0.821138211382114,
        0.919298245614035,
        0.885714285714286,
        0.876237623762376,
        1
      ),
      Female_HSgrad = c(11, 60, 87, 156, 23, 83),
      Female_SomeCollege = c(22,
                             25, 13, 47, 54, 65),
      Female_AssocDeg = c(0, 0, 20, 82, 0,
                          0),
      Female_BachDeg = c(5, 26, 0, 19, 0, 11),
      Female_GradDeg = c(5,
                         16, 0, 0, 0, 0),
      FemaleEduAboveHS = c(43, 127, 120, 304,
                           77, 159),
      Total_Female18.24 = c(53, 127, 192, 581, 92, 198),
      FemaleEduHSAbove_pop = c(
        0.811320754716981,
        1,
        0.625,
        0.523235800344234,
        0.83695652173913,
        0.803030303030303
      )
    ),

    row.names = c(NA,
                  6L),
    class = "data.frame"
  )

</code>```

Here is my code

```<code>
#List of potential outcome variables to be plotted
variables <- c("total_empl", "total_payroll", "total_establishments", "largest_employer", "largest_employer_bypayroll", "trend_employee_change", "trend_payroll_change", "trend_establishment_change", "damage_cost_weather_total", "deaths_weather_total", "medianrent", "vacancyrate", "total_pop", "undertwo_percent", "mobility_rate", "unemploy_rate", "median_income", "renter_percent", "blackaa_percent", "hispanic_percent", "median_monthly_housing_costs", "MaleEduAboveHS_pop", "FemaleEduHSAbove_pop")

# Define inputs
selectInput('state_name', label = 'Select a state', choices = lookup)

selectInput('DV', label = 'Outcome Measure', choices = variables)

#Filter data based on the State and outcome measure the user would like to investigate.

bar <- reactive({

  st <- df %>%
        filter(state == input$state_name)

  bp <- st %>%
        group_by(tract_type) %>%
        summarise(Outcome = mean(st[,input$DV]))

  return(bp)
})

bar
</code>```

UPDATE
Right now, this code successfully filters the data by the input$state_name, but there is an issue with the calculation of means. The result is this:

```<code># A tibble: 2 x 2
  tract_type Outcome
  <chr>        <dbl>
1 Contiguous   468296.
2 LICs         468296.
</code>```

As you can see, the means that are calculated are identical.  In fact, these values correspond to the grand average mean for whichever variable is chosen for input$DV.  Therefore, the filtered st data is not being successfully grouped into the two levels of tract_type.

答:
I see what you are trying to do. The difference is that in your reactive part you try to calculate the mean of a string, which won't work. What you want to do is summarise one of the columns in df by providing the name

In the following example, I specify the summarising variable manually. Note that investment_score_1_low_10_high does not have quotes. investment_score_1_low_10_high is what is called a symbol in R.

```<code>st <- df %>%
  filter(state == "Alabama") %>%
  group_by(tract_type) %>%
  summarise(Outcome = mean(investment_score_1_low_10_high))
</code>```

But I think this should work:

```<code>bar <- reactive({
  # Create a symbol from string.
  mean_variable <- sym(input$DV)
  bp <- df %>%
        filter(state == input$state_name) %>%
        group_by(tract_type) %>%
        summarise(Outcome = mean(!! mean_variable, na.rm = TRUE))

  return(bp)
})
</code>```

Extra information about the use of !! and what it does can be found here: Here

And even better with examples Here

Body:
I am trying to develop a shiny dashboard app that is able to produce a bar graph for different outcome variables that can be selected by the user.  To do so, I need to subset my data reactively to generate aggregate data frames. I am able to have the code below successfully filter my data reactively, but I am running into trouble when I try to use dplyr::summarise() reactively.

Here is my data

dput(head(df))

structure(
    list(
      geoid = c(
        "01001020200",
        "01001020300",
        "01001020700",
        "01001020802",
        "01001021000",
        "01001021100"
      ),
      state = c(
        "Alabama",
        "Alabama",
        "Alabama",
        "Alabama",
        "Alabama",
        "Alabama"
      ),
      county = c(
        "Autauga County",
        "Autauga County",
        "Autauga County",
        "Autauga County",
        "Autauga County",
        "Autauga County"
      ),
      ozzone = structure(
        c(1L, 1L, 2L, 1L, 1L, 1L),
        .Label = c("non.oz", "oz"),
        class = "factor"
      ),
      tract_type = c(
        "LICs",
        "Contiguous",
        "LICs",
        "Contiguous",
        "Contiguous",
        "LICs"
      ),
      investment_score_1_low_10_high = c(4,
                                         6, 9, 10, 5, 6),
      socioeconomic_change_flag_1_yes_blank_no = c(0,
                                                   0, 0, 0, 0, 0),
      fips_county = c("01001", "01001", "01001", "01001",
                      "01001", "01001"),
      total_empl = c(51809L, 51809L, 51809L, 51809L,
                     51809L, 51809L),
      total_payroll = c(338395L, 338395L, 338395L,
                        338395L, 338395L, 338395L),
      total_establishments = c(5090L, 5090L,
                               5090L, 5090L, 5090L, 5090L),
      largest_employer = c(72L, 72L, 72L,
                           72L, 72L, 72L),
      largest_employer_bypayroll = c(44L, 44L, 44L,
                                     44L, 44L, 44L),
      trend_employee_change = c(
        2735.60000000046,
        2735.60000000046,
        2735.60000000046,
        2735.60000000046,
        2735.60000000046,
        2735.60000000046
      ),
      trend_payroll_change = c(
        23074.8000000037,
        23074.8000000037,
        23074.8000000037,
        23074.8000000037,
        23074.8000000037,
        23074.8000000037
      ),
      trend_establishment_change = c(
        53.4000000000084,
        53.4000000000084,
        53.4000000000084,
        53.4000000000084,
        53.4000000000084,
        53.4000000000084
      ),
      damage_cost_weather_total = c(20000, 20000, 20000, 20000,
                                    20000, 20000),
      deaths_weather_total = c(0L, 0L, 0L, 0L, 0L, 0L),
      medianrent = c(537, 633, 525, 680, 409, 303),
      vacancyrate = c(
        0.108200455580866,
        0.113652113652114,
        0.0436681222707424,
        0.0512166859791425,
        0.229962546816479,
        0.21030303030303
      ),
      total_pop = c(503, 827, 900, 2989, 740, 813),
      undertwo_percent = c(
        0.391650099403579,
        0.351874244256348,
        0.397777777777778,
        0.17096018735363,
        0.301351351351351,
        0.263222632226322
      ),
      mobility_rate = c(
        0.133702166897188,
        0.0737753882915173,
        0.196514423076923,
        0.172716680111141,
        0.0641304347826087,
        0.0681084570690769
      ),
      unemploy_rate = c(
        0.0176991150442478,
        0.0273203592814371,
        0.109881724532621,
        0.0127906976744186,
        0.0344982078853047,
        0.0281910728269381
      ),
      median_income = c(41287, 46806, 41250, 64439,
                        46607, 36450),
      renter_percent = c(
        0.337653478854025,
        0.310596310596311,
        0.331877729257642,
        0.268110942458949,
        0.328686327077748,
        0.365986394557823
      ),
      blackaa_percent = c(
        0.5451197053407,
        0.264697193500739,
        0.145906432748538,
        0.152916262243007,
        0.258583690987124,
        0.530922930542341
      ),
      hispanic_percent = c(
        0.0105893186003683,
        0.0803545051698671,
        0.0400584795321637,
        0.0137651107385511,
        0.00822603719599428,
        0.00666032350142721
      ),
      transit_score_mean = c(0, 0, 0, 0, 0, 0),
      life_expectancy = c(75.67, 75.67, 75.67, 75.67, 75.67, 75.67),
      trend_life_expectancy = c(5.1, 5.1, 5.1, 5.1, 5.1, 5.1),
      median_monthly_housing_costs = c(885,
                                       885, 885, 885, 885, 885),
      pestilence_2018 = c(2, 2, 2, 2, 2,
                          2),
      total_pop_county = c(6772, 6772, 6772, 6772, 6772, 6772),
      deaths_weather_pop = c(0, 0, 0, 0, 0, 0),
      cost_weather_pop = c(
        2.95333727111636,
        2.95333727111636,
        2.95333727111636,
        2.95333727111636,
        2.95333727111636,
        2.95333727111636
      ),
      Male_HSgrad = c(75, 68, 211, 189, 97,
                      42),
      Male_SomeCollege = c(28, 18, 51, 111, 74, 38),
      Male_AssocDeg = c(4,
                        6, 0, 63, 0, 21),
      Male_BachDeg = c(7, 9, 0, 11, 0, 9),
      Male_GradDeg = c(0,
                       0, 0, 29, 6, 0),
      MaleEduAboveHS = c(114, 101, 262, 403, 177,
                         110),
      Total_Male18.24 = c(145, 123, 285, 455, 202, 110),
      MaleEduHSAbove_pop = c(
        0.786206896551724,
        0.821138211382114,
        0.919298245614035,
        0.885714285714286,
        0.876237623762376,
        1
      ),
      Female_HSgrad = c(11, 60, 87, 156, 23, 83),
      Female_SomeCollege = c(22,
                             25, 13, 47, 54, 65),
      Female_AssocDeg = c(0, 0, 20, 82, 0,
                          0),
      Female_BachDeg = c(5, 26, 0, 19, 0, 11),
      Female_GradDeg = c(5,
                         16, 0, 0, 0, 0),
      FemaleEduAboveHS = c(43, 127, 120, 304,
                           77, 159),
      Total_Female18.24 = c(53, 127, 192, 581, 92, 198),
      FemaleEduHSAbove_pop = c(
        0.811320754716981,
        1,
        0.625,
        0.523235800344234,
        0.83695652173913,
        0.803030303030303
      )
    ),

    row.names = c(NA,
                  6L),
    class = "data.frame"
  )

Here is my code

#List of potential outcome variables to be plotted
variables <- c("total_empl", "total_payroll", "total_establishments", "largest_employer", "largest_employer_bypayroll", "trend_employee_change", "trend_payroll_change", "trend_establishment_change", "damage_cost_weather_total", "deaths_weather_total", "medianrent", "vacancyrate", "total_pop", "undertwo_percent", "mobility_rate", "unemploy_rate", "median_income", "renter_percent", "blackaa_percent", "hispanic_percent", "median_monthly_housing_costs", "MaleEduAboveHS_pop", "FemaleEduHSAbove_pop")

# Define inputs
selectInput('state_name', label = 'Select a state', choices = lookup)

selectInput('DV', label = 'Outcome Measure', choices = variables)

#Filter data based on the State and outcome measure the user would like to investigate.

bar <- reactive({

  st <- df %>%
        filter(state == input$state_name)

  bp <- st %>%
        group_by(tract_type) %>%
        summarise(Outcome = mean(st[,input$DV]))

  return(bp)
})

bar

UPDATE
Right now, this code successfully filters the data by the input$state_name, but there is an issue with the calculation of means. The result is this:

# A tibble: 2 x 2
  tract_type Outcome
  <chr>        <dbl>
1 Contiguous   468296.
2 LICs         468296.

As you can see, the means that are calculated are identical.  In fact, these values correspond to the grand average mean for whichever variable is chosen for input$DV.  Therefore, the filtered st data is not being successfully grouped into the two levels of tract_type.

Body:
I see what you are trying to do. The difference is that in your reactive part you try to calculate the mean of a string, which won't work. What you want to do is summarise one of the columns in df by providing the name

In the following example, I specify the summarising variable manually. Note that investment_score_1_low_10_high does not have quotes. investment_score_1_low_10_high is what is called a symbol in R.

st <- df %>%
  filter(state == "Alabama") %>%
  group_by(tract_type) %>%
  summarise(Outcome = mean(investment_score_1_low_10_high))

But I think this should work:

bar <- reactive({
  # Create a symbol from string.
  mean_variable <- sym(input$DV)
  bp <- df %>%
        filter(state == input$state_name) %>%
        group_by(tract_type) %>%
        summarise(Outcome = mean(!! mean_variable, na.rm = TRUE))

  return(bp)
})

Extra information about the use of !! and what it does can be found here: Here

And even better with examples Here


问:
How to loop through vectors when the lengths of the vectors are changing?
I have two vectors of the same lengths initially. This first is full of protein modification sites I.E. "E123". The second is a unique code for the literature reference to this site. I need to go through these vectors to remove multiple references to the same site from the same paper. That is, if VectorOne[1] == VectorOne[2] && VectorTwo[1] == VectorTwo[2], I need to remove the duplicate. The problem is when I use for loops to loop through the data I am potentially changing the lengths of the vectors meaning that the indices I'm using may no longer be correct.

As soon as I have removed a single element from the vectors the value I am looping to length(primarySite) is too high and the code crashes.

Here is an example of the first 10 values from these two vectors:

```<code>primarySite[1:10]
 [1] ""     ""     "D248" "E241" "E242" "E241" "E242" "D244" "D244" "E241"
sitePMID[1:10]
 [1] 24641686 24055347 23955771 23955771 23955771 23955771 23955771 23955771 23955771 23955771

Desired Output:
primarySite[1:6]
 [1] ""     ""     "D248" "E241" "E242" "D244"
sitePMID[1:6]
 [1] 24641686 24055347 23955771 23955771 23955771 23955771

for(i in 1:length(primarySite)){
      for(j in (i+1):length(primarySite)){
        if(primarySite[i] == primarySite[j] && sitePMID[i] ==
sitePMID[j]){
      primarySite <- primarySite[-j]
      sitePMID <- sitePMID[-j]

    }
  }
}
</code>```

答:
This is easy if we put the vectors in a data frame:

```<code>data = data.frame(primarySite, sitePMID)
deduplicated_data = unique(data)
</code>```

You can find many other ways in the R-FAQ

Body:
I have two vectors of the same lengths initially. This first is full of protein modification sites I.E. "E123". The second is a unique code for the literature reference to this site. I need to go through these vectors to remove multiple references to the same site from the same paper. That is, if VectorOne[1] == VectorOne[2] && VectorTwo[1] == VectorTwo[2], I need to remove the duplicate. The problem is when I use for loops to loop through the data I am potentially changing the lengths of the vectors meaning that the indices I'm using may no longer be correct.

As soon as I have removed a single element from the vectors the value I am looping to length(primarySite) is too high and the code crashes.

Here is an example of the first 10 values from these two vectors:

primarySite[1:10]
 [1] ""     ""     "D248" "E241" "E242" "E241" "E242" "D244" "D244" "E241"
sitePMID[1:10]
 [1] 24641686 24055347 23955771 23955771 23955771 23955771 23955771 23955771 23955771 23955771

Desired Output:
primarySite[1:6]
 [1] ""     ""     "D248" "E241" "E242" "D244"
sitePMID[1:6]
 [1] 24641686 24055347 23955771 23955771 23955771 23955771

for(i in 1:length(primarySite)){
      for(j in (i+1):length(primarySite)){
        if(primarySite[i] == primarySite[j] && sitePMID[i] ==
sitePMID[j]){
      primarySite <- primarySite[-j]
      sitePMID <- sitePMID[-j]

    }
  }
}

Body:
This is easy if we put the vectors in a data frame:

data = data.frame(primarySite, sitePMID)
deduplicated_data = unique(data)

You can find many other ways in the R-FAQ


问:
Is %$var dereferencing a Perl hash?
I'm sending a subroutine a hash, and fetching it with my($arg_ref) = @_;

But what exactly is %$arg_ref? Is %$ dereferencing the hash?

答:
```<code>my %hash = ( fred => 'wilma',
             barney => 'betty');
my $hashref = \%hash;
my $freds_wife = $hashref->{fred};
my %hash_copy = %$hash # or %{$hash} as noted above.
</code>```

Soo, what's the point of the syntax flexibility?  Let's try this:

```<code>my %flintstones = ( fred => { wife => 'wilma',
                              kids => ['pebbles'],
                              pets => ['dino'],
                            }
                    barney => { # etc ... }
                  );
</code>```

Actually for deep data structures like this it's often more convenient to start with a ref:

```<code>my $flintstones = { fred => { wife => 'Wilma',
                               kids => ['Pebbles'],
                               pets => ['Dino'],
                              },
                   };
</code>```

OK, so fred gets a new pet, 'Velociraptor'

```<code>push @{$flintstones->{fred}->{pets}}, 'Velociraptor';
</code>```

How many pets does Fred have?

scalar @ {flintstones->{fred}->{pets} }

Let's feed them ...

```<code>for my $pet ( @ {flintstones->{fred}->{pets} } ) {
    feed($pet)
}
</code>```

and so on.  The curly-bracket soup can look a bit daunting at first, but it becomes quite easy to deal with them in the end, so long as you're consistent in the way that you deal with them.

OwnerDisplayName: Stian S

LastEditorDisplayName: brian d foy

Title: Is %$var dereferencing a Perl hash?

Body:
my %hash = ( fred => 'wilma',
             barney => 'betty');
my $hashref = \%hash;
my $freds_wife = $hashref->{fred};
my %hash_copy = %$hash # or %{$hash} as noted above.

Soo, what's the point of the syntax flexibility?  Let's try this:

my %flintstones = ( fred => { wife => 'wilma',
                              kids => ['pebbles'],
                              pets => ['dino'],
                            }
                    barney => { # etc ... }
                  );

Actually for deep data structures like this it's often more convenient to start with a ref:

my $flintstones = { fred => { wife => 'Wilma',
                               kids => ['Pebbles'],
                               pets => ['Dino'],
                              },
                   };

OK, so fred gets a new pet, 'Velociraptor'

push @{$flintstones->{fred}->{pets}}, 'Velociraptor';

How many pets does Fred have?

scalar @ {flintstones->{fred}->{pets} }

Let's feed them ...

for my $pet ( @ {flintstones->{fred}->{pets} } ) {
    feed($pet)
}

and so on.  The curly-bracket soup can look a bit daunting at first, but it becomes quite easy to deal with them in the end, so long as you're consistent in the way that you deal with them.


问:
Fine tuning regex to extract data between delimeters
I'm using VBA regex and I need to extract only the data between two # delimters (I only need the text with any spaces before and after removed, not the # delimeters).

So far I have this pattern:

^#\s*(.*)\s*#$

The data entered has several rules:

```<code>1. Always start with #
2. After the first # there may be zero or one spaces
3. After captured text there may be zero or one spaces before end of line
4. After captured text there may be zero or one # before end of line
</code>```

So for example:

```<code># this is a test
#this is a test
# this is a test#
# this is a test #
</code>```

In all four cases this is a test should be the only thing returned.

I don't think the pattern is a million miles away however it seems to have difficulty when I add the ending # symbol along with / absence of spaces....

Any assistance is appreciated.

答:
You may fix your current solution using

```<code>^#\s*(.*?)\s*#?$
</code>```

See the regex demo. Two main points: 1) (.*?) must be a lazy dot pattern, 2) #? now has a ? quantifier to match # 1 or 0 times.

However, you may also remove the leading / trailing matches using Replace with

```<code>^#\s*|\s*#?$
</code>```

pattern. Do not forget to set regex .Global = True.

See another regex demo.

Body:
I'm using VBA regex and I need to extract only the data between two # delimters (I only need the text with any spaces before and after removed, not the # delimeters).

So far I have this pattern:

^#\s*(.*)\s*#$

The data entered has several rules:

1. Always start with #
2. After the first # there may be zero or one spaces
3. After captured text there may be zero or one spaces before end of line
4. After captured text there may be zero or one # before end of line

So for example:

# this is a test
#this is a test
# this is a test#
# this is a test #

In all four cases this is a test should be the only thing returned.

I don't think the pattern is a million miles away however it seems to have difficulty when I add the ending # symbol along with / absence of spaces....

Any assistance is appreciated.

Body:
You may fix your current solution using

^#\s*(.*?)\s*#?$

See the regex demo. Two main points: 1) (.*?) must be a lazy dot pattern, 2) #? now has a ? quantifier to match # 1 or 0 times.

However, you may also remove the leading / trailing matches using Replace with

^#\s*|\s*#?$

pattern. Do not forget to set regex .Global = True.

See another regex demo.


问:
Use awk, or sed commands to remove the letters and parenthesis from the rows of a file
I have an input file as below,

```<code>group_velocity: [     0.0000000      0.0000000      0.0000000 ]
group_velocity: [     6.8213667      5.2673206      0.0002496 ]
group_velocity: [    19.0751734     29.0686833      0.0006979 ]
</code>```

Now, I want to use the awk/sed command, such that the output file would look as:

```<code>   0.0000000      0.0000000      0.0000000
   6.8213667      5.2673206      0.0002496
   19.0751734     29.0686833     0.0006979
</code>```

Any help would be appreciated.

Body:
I have an input file as below,

group_velocity: [     0.0000000      0.0000000      0.0000000 ]
group_velocity: [     6.8213667      5.2673206      0.0002496 ]
group_velocity: [    19.0751734     29.0686833      0.0006979 ]

Now, I want to use the awk/sed command, such that the output file would look as:

   0.0000000      0.0000000      0.0000000
   6.8213667      5.2673206      0.0002496
   19.0751734     29.0686833     0.0006979

Any help would be appreciated.

Body:
this works:

echo "group_velocity: [     0.0000000      0.0000000      0.0000000 ]
group_velocity: [     6.8213667      5.2673206      0.0002496 ]
group_velocity: [    19.0751734     29.0686833      0.0006979 ]" | awk '{print $3, $4, $5}'

Regards.


问:
Avoid warning: expected ‘const struct aiocb * const*’ but argument is of type ‘struct aiocb **’
```<code>archives.c: In function ‘fd_writeback_wait’:
archives.c:121:21: warning: passing argument 1 of ‘aio_suspend’ from incompatible pointer type [-Wincompatible-pointer-types]
     r = aio_suspend(&cb, 1, NULL);
                     ^~~
In file included from ../lib/dpkg/fsys.h:28,
                 from ../lib/dpkg/triglib.h:28,
                 from archives.c:57:
/usr/include/aio.h:168:51: note: expected ‘const struct aiocb * const*’ but argument is of type ‘struct aiocb **’
 extern int aio_suspend (const struct aiocb *const __list[], int __nent,
                         ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~
</code>```

Explanations:

Why isn't it legal to convert "pointer to pointer to non-const" to a "pointer to pointer to const"

... or look at the Related questions list on the right hand side of the screen, and take your pick :-).

I think there is no way to avoid this warning, without writing a dangerous type cast to change the const qualifiers, or suppressing the whole category of warnings.

Apparently C++ does better here.  It also has const_cast for clearer casting, which makes sure that you are only changing const qualifiers.

In other words, POSIX defining aio_suspend() to use const like this is arguably rather dangerous.

Have I interpreted this correctly?

If I am wrong, then how can I avoid this warning, but still have the compiler check that I am only casting const qualifiers, and not casting to a completely incompatible type?

I suspect if there are methods, they would not be ones that I would want to use in practice, but I am curious.

The current code I am working on does not explicitly document a required compiler version.

I would be interested in techniques that work in standard C versions.  I would be interested to hear about GCC extensions.  Comments about whether it is recommended or dis-recommended to define function parameters like this are also welcome.

Readers are reminded that C and C++ are different, and not 100% compatible languages.  I acknowledge that switching code bases to C++ could probably provide a solution, but I do not think that solution would be very useful to me.  Thank you.

答:
Here is a way to call the function with appropriate constness:

```<code>struct aiocb cb;
const struct aiocb * cblist[1] = { &cb };
aio_suspend(cblist, 1, NULL);
</code>```

And alternatively:

```<code>struct aiocb cb;
const struct aiocb * cbptr = &cb;
aio_suspend(&cbptr, 1, NULL);
</code>```

Note, the above answer was proposed because you used this syntax:

```<code>r = aio_suspend(&cb, 1, NULL);
</code>```

Passing in the address of cb to something that expects a pointer to pointer means cb was a pointer, so this call only makes sense for a single element array.

Suppose your warning came about because you actually had this:

```<code>struct aiocb *cbv[256];
r = aio_suspend(cbv, 256, NULL);
</code>```

It is easy to remove the warning. Use (void *).

```<code>r = aio_suspend((void *)cbv, 256, NULL);
</code>```

However, it would be better to define the vector to be using pointers to const in the first place.

```<code>const struct aiocb *cbv[256];
r = aio_suspend(cbv, 256, NULL);
</code>```

If each callback instance is indeed modifiable in reality (eg, was allocated by malloc), then just cast away const before modifying.

```<code>struct aiocb *cb = (struct aiocb *)cbv[i];
/* ... modify cb ... */
</code>```

Body:
archives.c: In function ‘fd_writeback_wait’:
archives.c:121:21: warning: passing argument 1 of ‘aio_suspend’ from incompatible pointer type [-Wincompatible-pointer-types]
     r = aio_suspend(&cb, 1, NULL);
                     ^~~
In file included from ../lib/dpkg/fsys.h:28,
                 from ../lib/dpkg/triglib.h:28,
                 from archives.c:57:
/usr/include/aio.h:168:51: note: expected ‘const struct aiocb * const*’ but argument is of type ‘struct aiocb **’
 extern int aio_suspend (const struct aiocb *const __list[], int __nent,
                         ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~

Explanations:

Why isn't it legal to convert "pointer to pointer to non-const" to a "pointer to pointer to const"

... or look at the Related questions list on the right hand side of the screen, and take your pick :-).

I think there is no way to avoid this warning, without writing a dangerous type cast to change the const qualifiers, or suppressing the whole category of warnings.

Apparently C++ does better here.  It also has const_cast for clearer casting, which makes sure that you are only changing const qualifiers.

In other words, POSIX defining aio_suspend() to use const like this is arguably rather dangerous.

Have I interpreted this correctly?

If I am wrong, then how can I avoid this warning, but still have the compiler check that I am only casting const qualifiers, and not casting to a completely incompatible type?

I suspect if there are methods, they would not be ones that I would want to use in practice, but I am curious.

The current code I am working on does not explicitly document a required compiler version.

I would be interested in techniques that work in standard C versions.  I would be interested to hear about GCC extensions.  Comments about whether it is recommended or dis-recommended to define function parameters like this are also welcome.

Readers are reminded that C and C++ are different, and not 100% compatible languages.  I acknowledge that switching code bases to C++ could probably provide a solution, but I do not think that solution would be very useful to me.  Thank you.

Body:
Here is a way to call the function with appropriate constness:

struct aiocb cb;
const struct aiocb * cblist[1] = { &cb };
aio_suspend(cblist, 1, NULL);

And alternatively:

struct aiocb cb;
const struct aiocb * cbptr = &cb;
aio_suspend(&cbptr, 1, NULL);

Note, the above answer was proposed because you used this syntax:

r = aio_suspend(&cb, 1, NULL);

Passing in the address of cb to something that expects a pointer to pointer means cb was a pointer, so this call only makes sense for a single element array.

Suppose your warning came about because you actually had this:

struct aiocb *cbv[256];
r = aio_suspend(cbv, 256, NULL);

It is easy to remove the warning. Use (void *).

r = aio_suspend((void *)cbv, 256, NULL);

However, it would be better to define the vector to be using pointers to const in the first place.

const struct aiocb *cbv[256];
r = aio_suspend(cbv, 256, NULL);

If each callback instance is indeed modifiable in reality (eg, was allocated by malloc), then just cast away const before modifying.

struct aiocb *cb = (struct aiocb *)cbv[i];
/* ... modify cb ... */


问:
Query to list all users of a certain group
How can I use a a search filter to display users of a specific group?

I've tried the following:

```<code>(&
    (objectCategory=user)
    (memberOf=MyCustomGroup)
)
</code>```

and this:

```<code>(&
    (objectCategory=user)
    (memberOf=cn=SingleSignOn,ou=Groups,dc=tis,dc=eg,dc=ddd,DC=com)
)
</code>```

but neither display users of a specific group.

答:
If the DC is Win2k3 SP2 or above, you can use something like:

(&(objectCategory=user)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com))

to get the nested group membership.

Source: https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches

Body:
How can I use a a search filter to display users of a specific group?

I've tried the following:

(&
    (objectCategory=user)
    (memberOf=MyCustomGroup)
)

and this:

(&
    (objectCategory=user)
    (memberOf=cn=SingleSignOn,ou=Groups,dc=tis,dc=eg,dc=ddd,DC=com)
)

but neither display users of a specific group.