问:
LLVM 6 Trunk Build on Ubuntu 16.04 not building lld
I am building LLVM 6 on Ubuntu 16.04. I want lld too. But no matter what I do, lld doesn't build/install.

Followed the following instruction from here. Still sifting through first and second :)

Read the documentation.

Read the documentation.

Remember that you were warned twice about reading the documentation.

In particular, the relative paths specified are important.

Checkout LLVM:

```<code>cd where-you-want-llvm-to-live
svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm
</code>```

Checkout Clang:

```<code>cd where-you-want-llvm-to-live
cd llvm/tools
svn co http://llvm.org/svn/llvm-project/cfe/trunk clang
</code>```

Checkout Extra Clang Tools [Optional]:

```<code>cd where-you-want-llvm-to-live
cd llvm/tools/clang/tools
svn co http://llvm.org/svn/llvm-project/clang-tools-extra/trunk extra
</code>```

Checkout LLD linker [Optional]:

```<code>cd where-you-want-llvm-to-live
cd llvm/tools
svn co http://llvm.org/svn/llvm-project/lld/trunk lld
</code>```

Didn't download the other optional packages. Since svn download was not working properly (svn: E000104: Error running context: Connection reset by peer), I downloaded respective zip for LLVM, Clang, clang-extra and lld from their github mirrors. Since, I didn't use svn some renaming of the folders had to be done (for e.g. clang-tools-extra-master to just extra).

Then execute the following, after cding into the parent folder of the llvm source folder,

```<code>$ mkdir build; cd build
$ cmake ../llvm
$ make
</code>```

After waiting for +8 hours, I get all the programs (clang, lli, llc etc.) except lld. I am expecting it to appear in the folder build/bin.

I have also tried the option cmake -DLLVM_ENABLE_PROJECTS=llvm/tools/lld ../llvm. (The form -DLLVM_ENABLE_PROJECTS=lld doesn't work and I found this place discussing about the same ENABLE issue.)

I have already tried things with some tweaking three times. Since it takes so much time to compile, I decided to take your help.

A separate issue: While building, linking phase takes 12 GB RAM + 8.8 GB swap space on my laptop!! Does LLVM building really require >20 GB of ram ? (I had closed all other foreground apps, especially firefox)

Please let me know if any more information is needed.

答:
First of all, I think that the LLVM_ENABLE_PROJECTS option is useful if you use a "flat" source directory layout. In your case, if you performed the checkouts as you wrote, then it's not of much use.

Moreover, what @PaulR wrote about using ninja is a very good suggestion. It's faster and very useful when restarting builds and it spawns as many separate compilation jobs concurrently as it can depending on the nproc without having to specify it explicitly.

For faster build and shorter link times, I'd also suggest enabling a shared libs enabled build using the BUILD_SHARED_LIBS option.

Some general good advice can be found here, which can be summarized as:

use clang to build clang (a bootstrapped or second-stage build).

use the gold linker instead ld for faster linking times.

prefer a build producing shared libraries.

You can skip point 1 for now (although you could install an initial llvm/clang from the system package manager)

Lastly, you could limit the compilation for the specific target backend you currently require using the LLVM_TARGETS_TO_BUILD option.

I've built trunk recently (including lld) with this cmake configuration:

```<code>CC=gcc CXX=g++ \
cmake -G Ninja \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=On \
  -DBUILD_SHARED_LIBS=On \

  -DLLVM_ENABLE_ASSERTIONS=On \
  -DLLVM_TARGETS_TO_BUILD="X86" \
  -DLLVM_ENABLE_SPHINX=Off \
  -DLLVM_ENABLE_THREADS=On \
  -DLLVM_INSTALL_UTILS=On \

  -DCMAKE_BUILD_TYPE=Debug \
  [path-to-source-root-dir]
</code>```

You can add the following flags if you need to build libcxx:

```<code>[...]
-DLLVM_ENABLE_LIBCXX=On \
-DLIBCXX_ENABLE_EXCEPTIONS=On \
-DLIBCXX_ENABLE_RTTI=On \
[...]
</code>```

For a bootstrapped build using another llvm/clang and libc++ you can augment the above command as (having that clang in your $PATH environment variable):

```<code>LLVM_TOOLCHAIN_LIB_DIR=$(llvm-config --libdir)

LD_FLAGS=""
LD_FLAGS="${LD_FLAGS} -Wl,-L ${LLVM_TOOLCHAIN_LIB_DIR}"
LD_FLAGS="${LD_FLAGS} -Wl,-rpath-link ${LLVM_TOOLCHAIN_LIB_DIR}"
LD_FLAGS="${LD_FLAGS} -lc++ -lc++abi"

CXX_FLAGS=""
CXX_FLAGS="${CXX_FLAGS} -stdlib=libc++ -pthread"

CC=clang CXX=clang++ \
cmake -G Ninja \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=On \
  -DBUILD_SHARED_LIBS=On \
  -DLLVM_ENABLE_LIBCXX=On \
  -DLLVM_ENABLE_ASSERTIONS=On \
  -DLLVM_TARGETS_TO_BUILD="X86" \
  -DLLVM_ENABLE_SPHINX=Off \
  -DLLVM_ENABLE_THREADS=On \
  -DLLVM_INSTALL_UTILS=On \
  -DLIBCXX_ENABLE_EXCEPTIONS=On \
  -DLIBCXX_ENABLE_RTTI=On \
  -DCMAKE_BUILD_TYPE=Debug \
  -DCMAKE_CXX_FLAGS="${CXX_FLAGS}" \
  -DCMAKE_SHARED_LINKER_FLAGS="${LD_FLAGS}" \
  -DCMAKE_MODULE_LINKER_FLAGS="${LD_FLAGS}" \
  -DCMAKE_EXE_LINKER_FLAGS="${LD_FLAGS}" \
  -DCMAKE_POLICY_DEFAULT_CMP0056=NEW \
  -DCMAKE_POLICY_DEFAULT_CMP0058=NEW \
  [path-to-source-root-dir]
</code>```

Moreover, another relevant SO question of interest can be found here.

As you wrote, reading the documentation, experimenting and reading the documentation again is the way to go.

Body:
I am building LLVM 6 on Ubuntu 16.04. I want lld too. But no matter what I do, lld doesn't build/install.

Followed the following instruction from here. Still sifting through first and second :)

Read the documentation.

Read the documentation.

Remember that you were warned twice about reading the documentation.

In particular, the relative paths specified are important.

Checkout LLVM:

cd where-you-want-llvm-to-live
svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm

Checkout Clang:

cd where-you-want-llvm-to-live
cd llvm/tools
svn co http://llvm.org/svn/llvm-project/cfe/trunk clang

Checkout Extra Clang Tools [Optional]:

cd where-you-want-llvm-to-live
cd llvm/tools/clang/tools
svn co http://llvm.org/svn/llvm-project/clang-tools-extra/trunk extra

Checkout LLD linker [Optional]:

cd where-you-want-llvm-to-live
cd llvm/tools
svn co http://llvm.org/svn/llvm-project/lld/trunk lld

Didn't download the other optional packages. Since svn download was not working properly (svn: E000104: Error running context: Connection reset by peer), I downloaded respective zip for LLVM, Clang, clang-extra and lld from their github mirrors. Since, I didn't use svn some renaming of the folders had to be done (for e.g. clang-tools-extra-master to just extra).

Then execute the following, after cding into the parent folder of the llvm source folder,

$ mkdir build; cd build
$ cmake ../llvm
$ make

After waiting for +8 hours, I get all the programs (clang, lli, llc etc.) except lld. I am expecting it to appear in the folder build/bin.

I have also tried the option cmake -DLLVM_ENABLE_PROJECTS=llvm/tools/lld ../llvm. (The form -DLLVM_ENABLE_PROJECTS=lld doesn't work and I found this place discussing about the same ENABLE issue.)

I have already tried things with some tweaking three times. Since it takes so much time to compile, I decided to take your help.

A separate issue: While building, linking phase takes 12 GB RAM + 8.8 GB swap space on my laptop!! Does LLVM building really require >20 GB of ram ? (I had closed all other foreground apps, especially firefox)

Please let me know if any more information is needed.

Body:
First of all, I think that the LLVM_ENABLE_PROJECTS option is useful if you use a "flat" source directory layout. In your case, if you performed the checkouts as you wrote, then it's not of much use.

Moreover, what @PaulR wrote about using ninja is a very good suggestion. It's faster and very useful when restarting builds and it spawns as many separate compilation jobs concurrently as it can depending on the nproc without having to specify it explicitly.

For faster build and shorter link times, I'd also suggest enabling a shared libs enabled build using the BUILD_SHARED_LIBS option.

Some general good advice can be found here, which can be summarized as:

use clang to build clang (a bootstrapped or second-stage build).

use the gold linker instead ld for faster linking times.

prefer a build producing shared libraries.

You can skip point 1 for now (although you could install an initial llvm/clang from the system package manager)

Lastly, you could limit the compilation for the specific target backend you currently require using the LLVM_TARGETS_TO_BUILD option.

I've built trunk recently (including lld) with this cmake configuration:

CC=gcc CXX=g++ \
cmake -G Ninja \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=On \
  -DBUILD_SHARED_LIBS=On \

  -DLLVM_ENABLE_ASSERTIONS=On \
  -DLLVM_TARGETS_TO_BUILD="X86" \
  -DLLVM_ENABLE_SPHINX=Off \
  -DLLVM_ENABLE_THREADS=On \
  -DLLVM_INSTALL_UTILS=On \

  -DCMAKE_BUILD_TYPE=Debug \
  [path-to-source-root-dir]

You can add the following flags if you need to build libcxx:

[...]
-DLLVM_ENABLE_LIBCXX=On \
-DLIBCXX_ENABLE_EXCEPTIONS=On \
-DLIBCXX_ENABLE_RTTI=On \
[...]

For a bootstrapped build using another llvm/clang and libc++ you can augment the above command as (having that clang in your $PATH environment variable):

LLVM_TOOLCHAIN_LIB_DIR=$(llvm-config --libdir)

LD_FLAGS=""
LD_FLAGS="${LD_FLAGS} -Wl,-L ${LLVM_TOOLCHAIN_LIB_DIR}"
LD_FLAGS="${LD_FLAGS} -Wl,-rpath-link ${LLVM_TOOLCHAIN_LIB_DIR}"
LD_FLAGS="${LD_FLAGS} -lc++ -lc++abi"

CXX_FLAGS=""
CXX_FLAGS="${CXX_FLAGS} -stdlib=libc++ -pthread"

CC=clang CXX=clang++ \
cmake -G Ninja \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=On \
  -DBUILD_SHARED_LIBS=On \
  -DLLVM_ENABLE_LIBCXX=On \
  -DLLVM_ENABLE_ASSERTIONS=On \
  -DLLVM_TARGETS_TO_BUILD="X86" \
  -DLLVM_ENABLE_SPHINX=Off \
  -DLLVM_ENABLE_THREADS=On \
  -DLLVM_INSTALL_UTILS=On \
  -DLIBCXX_ENABLE_EXCEPTIONS=On \
  -DLIBCXX_ENABLE_RTTI=On \
  -DCMAKE_BUILD_TYPE=Debug \
  -DCMAKE_CXX_FLAGS="${CXX_FLAGS}" \
  -DCMAKE_SHARED_LINKER_FLAGS="${LD_FLAGS}" \
  -DCMAKE_MODULE_LINKER_FLAGS="${LD_FLAGS}" \
  -DCMAKE_EXE_LINKER_FLAGS="${LD_FLAGS}" \
  -DCMAKE_POLICY_DEFAULT_CMP0056=NEW \
  -DCMAKE_POLICY_DEFAULT_CMP0058=NEW \
  [path-to-source-root-dir]

Moreover, another relevant SO question of interest can be found here.

As you wrote, reading the documentation, experimenting and reading the documentation again is the way to go.


来源: stackexchange

问:
How to show result in HTML once promises are finished
I want to show the result in HTML once the promises are finished. Currently, this is how I do it:

```<code>promoBuyNGetNData = [];//class variable

ngOnInit() {
      Promise.all(this.checkPromoBuyNGetN()).then(values => {
        this.promoBuyNGetNData = values;
      });
}

checkPromoBuyNGetN() {
   var result = [];
   for (let p of this.invoiceProduct) {
      result.push(this.promotionSvc.checkPromoBuyNGetN(this.username, p));
   }
   return result;
}
</code>```

Then, in the HTML I write this:

```<code><tr *ngFor="let p of promoBuyNGetNData">
        <td class="name">{{p.productGet}}</td>
        <td class="quantity">{{p.getN}}</td>
        <td class="price">Rp. {{p.price}},00</td>
</tr>
</code>```

However, in the HTML it only shows an empty row. How can I fix this?

答:
Thanks to @manikant comment, I should write it like this:</p>

```<code><tr *ngFor="let p of promoBuyNGetNData[0]">
        <td class="name">{{p.productGet}}</td>
        <td class="quantity">{{p.getN}}</td>
        <td class="price">Rp. {{p.price}},00</td>
        <td class="delete"><ion-icon *ngIf = "isShowInvoice === false" title="delete" name="trash"></ion-icon></td>
</tr>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to show the result in HTML once the promises are finished. Currently, this is how I do it:

promoBuyNGetNData = [];//class variable

ngOnInit() {
      Promise.all(this.checkPromoBuyNGetN()).then(values => {
        this.promoBuyNGetNData = values;
      });
}

checkPromoBuyNGetN() {
   var result = [];
   for (let p of this.invoiceProduct) {
      result.push(this.promotionSvc.checkPromoBuyNGetN(this.username, p));
   }
   return result;
}

Then, in the HTML I write this:

        {{p.productGet}}
        {{p.getN}}
        Rp. {{p.price}},00

However, in the HTML it only shows an empty row. How can I fix this?

Body:
Thanks to @manikant comment, I should write it like this:

<tr *ngFor="let p of promoBuyNGetNData[0]">
        <td class="name">{{p.productGet}}</td>
        <td class="quantity">{{p.getN}}</td>
        <td class="price">Rp. {{p.price}},00</td>
        <td class="delete"><ion-icon *ngIf = "isShowInvoice === false" title="delete" name="trash"></ion-icon></td>
</tr>


问:
How can I constrain T to support DataContractJsonSerializer, and not implement ISerializable everywhere?
I'm working on this extension method and am trying to constrain T so that the method doesn't apply to EVERY object... just the ones that the DataContractJsonSerializer works well with</p>

```<code>public static string ToJSONString(this object obj)
    {
        using (var stream = new MemoryStream())
        {
            var ser = new DataContractJsonSerializer(obj.GetType());

            ser.WriteObject(stream, obj);

            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }
</code>```

答: The options available inside generics are... Limited. One workaround is to use reflection (typically in a static ctor on a generic type) to check with reflection, but tbh this may be overkill. Could you perhaps add where T : class, new() which may go a long way to limit it to "entity"/DTO types.

ContentLicense: CC BY-SA 2.5

Body:
I'm working on this extension method and am trying to constrain T so that the method doesn't apply to EVERY object... just the ones that the DataContractJsonSerializer works well with

public static string ToJSONString(this object obj)
    {
        using (var stream = new MemoryStream())
        {
            var ser = new DataContractJsonSerializer(obj.GetType());

            ser.WriteObject(stream, obj);

            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }


问:
Unit testing a bash script calling mount partition
I have a bash script that calls linux mount.

I want to unit test that script. I'm currently using shunit2.

One thing that I tried was to create a file mount and tried to use this one to respond 0 or -1 or +1 depending on what I wanted to test.

It obviously didn't work :)

Is there a way to make it work? Any suggestions?

答:
I would create a mock for the mount command this way:</p>

```<code>mount() {
  return $DESIRED_MOUNT_RETURN_CODE
}

setUp() {
  export DESIRED_MOUNT_RETURN_CODE=0 # default
}

testMountSucceeds() {
  . $script_under_test > /dev/null
  ...
}

testMountFails() {
  export DESIRED_MOUNT_RETURN_CODE=1
  . $script_under_test > /dev/null
  ...
}

. shunit2
</code>```

Body:
I would create a mock for the mount command this way:

mount() {
  return $DESIRED_MOUNT_RETURN_CODE
}

setUp() {
  export DESIRED_MOUNT_RETURN_CODE=0 # default
}

testMountSucceeds() {
  . $script_under_test > /dev/null
  ...
}

testMountFails() {
  export DESIRED_MOUNT_RETURN_CODE=1
  . $script_under_test > /dev/null
  ...
}

. shunit2


问:
How to vectorize vectors of points
I have a bunch of points (i.e. (x,y)) and I would like to isolate the ones that outside a unit circle. The condition is simple, one needs to to perform this inequality for all points </p>

```<code>(x^2 + y^2) <= 1
</code>```

<p>In my case, x and y are vectors. I need to vectorize this problem. I can solve it through looping but I need to avoid this approach. Any suggestions? Something like this </p>

```<code>if (x.^2 + y.^2) <= 1
    inside the circle
else
    outside the circle
end
</code>```

答:
Perhaps something like:

```<code>x_in = x(x.^2 + y.^ <= 1);
y_in = y(x.^2 + y.^2 <= 1);
</code>```

Builds x_in and y_in as the subset of x and y, for which that condition holds.

Title: How to vectorize vectors of points

Body:
I have a bunch of points (i.e. (x,y)) and I would like to isolate the ones that outside a unit circle. The condition is simple, one needs to to perform this inequality for all points

(x^2 + y^2) <= 1

In my case, x and y are vectors. I need to vectorize this problem. I can solve it through looping but I need to avoid this approach. Any suggestions? Something like this

if (x.^2 + y.^2) <= 1
    inside the circle
else
    outside the circle
end

Body:
Perhaps something like:

x_in = x(x.^2 + y.^ <= 1);
y_in = y(x.^2 + y.^2 <= 1);

Builds x_in and y_in as the subset of x and y, for which that condition holds.


问:
How to find out if two numbers are relatively prime?
I'm trying to write a method that will calculate if two numbers are relatively prime for an assignment. I'm primarily looking for answers on where to start. I know there is a method gcd() that will do a lot of it for me, but the assignment is pretty much making me do it without gcd or arrays.

I kind of have it started, because I know that I will have to use the % operator in a for loop.

```<code>public static boolean relativeNumber(int input4, int input5){
    for(int i = 1; i <= input4; i++)
</code>```

Obviously this method is only going to return true or false because the main function is only going to print a specific line depending on if the two numbers are relatively prime or not.

I'm thinking I will probably have to write two for loops, both for input4, and input5, and possibly some kind of if statement with a logical && operand, but I'm not sure.

答:
Swift 4 code for @williem-van-onsem answer;

```<code>func gcd(a: Int, b: Int) -> Int {
    var b = b
    var a = a
    var t: Int!

    while(b != 0){
        t = a;
        a = b;
        b = t%b;
    }
    return a
}

func relativelyPrime(a : Int, b: Int) -> Bool{
    return gcd(a: a, b: b) == 1
}
</code>```

Usage;

```<code>print(relativelyPrime(a: 2, b: 4)) // false
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a method that will calculate if two numbers are relatively prime for an assignment. I'm primarily looking for answers on where to start. I know there is a method gcd() that will do a lot of it for me, but the assignment is pretty much making me do it without gcd or arrays.

I kind of have it started, because I know that I will have to use the % operator in a for loop.

public static boolean relativeNumber(int input4, int input5){
    for(int i = 1; i <= input4; i++)

Obviously this method is only going to return true or false because the main function is only going to print a specific line depending on if the two numbers are relatively prime or not.

I'm thinking I will probably have to write two for loops, both for input4, and input5, and possibly some kind of if statement with a logical && operand, but I'm not sure.

Body:
Swift 4 code for @williem-van-onsem answer;

func gcd(a: Int, b: Int) -> Int {
    var b = b
    var a = a
    var t: Int!

    while(b != 0){
        t = a;
        a = b;
        b = t%b;
    }
    return a
}

func relativelyPrime(a : Int, b: Int) -> Bool{
    return gcd(a: a, b: b) == 1
}

Usage;

print(relativelyPrime(a: 2, b: 4)) // false


问:
Focus on input and remove focus using Jquery
I'm tying to check if the input has focus to add color to the back ground However when I remove the mouse and focus on another input it doesn't remove the focus anymore
it actually stays with the focus! how can I remove the backgound from the first one!

```<code>Fullname: <input type="text" name="name"><br>
Email: <input type="text" name="email">
</code>```

How can I check that the class test exists

I'm tying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

```<code>$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
});
</code>```

I would approcialte it if you can test this for me or let me know what's going wrong on the above code!?

答:
For better way you can use CSS:

```<code>input:focus {
    background-color: yellow;
}
</code>```

but with using jquery:

```<code>$('input[type="text"]').focus(function() {
    $(this).css("background-color", "#cccccc");
});

$('input[type="text"]').blur(function() {
    $(this).css("background-color", "#fff");
});
</code>```

Body:
I'm tying to check if the input has focus to add color to the back ground However when I remove the mouse and focus on another input it doesn't remove the focus anymore
it actually stays with the focus! how can I remove the backgound from the first one!

Fullname: <input type="text" name="name">

Email: <input type="text" name="email">

How can I check that the class test exists

I'm tying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
});

I would approcialte it if you can test this for me or let me know what's going wrong on the above code!?

Body:
For better way you can use CSS:

input:focus {
    background-color: yellow;
}

but with using jquery:

$('input[type="text"]').focus(function() {
    $(this).css("background-color", "#cccccc");
});

$('input[type="text"]').blur(function() {
    $(this).css("background-color", "#fff");
});


问:
Getting nameof what an element references in a foreach
I am trying to get the nameof a variable being passed through a foreach loop.

```<code>string[] printThis = {"doesntMatter"};
string[] andThis = {"doesntMatter"};
string[][] arrayOfArrays = {printThis, andThis};

foreach(string element in arrayOfArrays)
{
    string theNameOfTheElement = nameOf(element);
    Console.WriteLine(theNameOfTheElement + " ");
}
</code>```

Instead of getting the desired result of

```<code>printThis andThis
</code>```

I'm obviously getting just:

```<code>element
</code>```

Is this not allowed? A better way?

答:
nameof operator is a lot simpler than you imply: it gives you the name of the variable/field/type/etc. that you pass to it as parameter. In your case that's an equivalent of "element" string.

There is no way to figure out the variable that was used to set a string[][] element, unless you save that information in a separate array or collection:

```<code>string[][] arrayOfArrays = {printThis, andThis};
string[] namesOfArrays =  {nameof(printThis), nameof(andThis)};
</code>```

A better approach is to make a collection of name-array pairs:

```<code>var arrayOfArrays = {
    new {Name = nameof(printThis), Array=printThis}
,   new {Name = nameof(andThis), Array=andThis}
};
foreach (var p in arrayOfArrays) {
    Console.WriteLine(p.Name);
    ...
}
</code>```

Body:
I am trying to get the nameof a variable being passed through a foreach loop.

string[] printThis = {"doesntMatter"};
string[] andThis = {"doesntMatter"};
string[][] arrayOfArrays = {printThis, andThis};

foreach(string element in arrayOfArrays)
{
    string theNameOfTheElement = nameOf(element);
    Console.WriteLine(theNameOfTheElement + " ");
}

Instead of getting the desired result of

printThis andThis

I'm obviously getting just:

element

Is this not allowed? A better way?

Body:
nameof operator is a lot simpler than you imply: it gives you the name of the variable/field/type/etc. that you pass to it as parameter. In your case that's an equivalent of "element" string.

There is no way to figure out the variable that was used to set a string[][] element, unless you save that information in a separate array or collection:

string[][] arrayOfArrays = {printThis, andThis};
string[] namesOfArrays =  {nameof(printThis), nameof(andThis)};

A better approach is to make a collection of name-array pairs:

var arrayOfArrays = {
    new {Name = nameof(printThis), Array=printThis}
,   new {Name = nameof(andThis), Array=andThis}
};
foreach (var p in arrayOfArrays) {
    Console.WriteLine(p.Name);
    ...
}


问:
Solr 7 Forcing q value
I'm using the Drupal ApacheSolr Multisite Module which due to it's dependency Apache Solr Search config currently only support Solr 5.x. I'm using Solr 7 and have update most of the config. I've got everything working except on /select. I believe this is because the query the module supplies (example shown below) features a "q" value which apparently causes it to fail. Is there a way in the solrconfig.xml to set q equal to "* . *" for all selects? I'd like to avoid code changes to the Drupal module itself if possible for deployment purposes.

Solar REST request example

```<code>http://localhost:8983/solr/drupal_multisite/select?start=0&rows=10&fq=%28hash%3A6qegyq%20OR%20access__all%3A0%29&fq=%28hash%3A6qegyq%29&spellcheck=true&q=test&fl=id%2Centity_id%2Centity_type%2Cbundle%2Cbundle_name%2Clabel%2Css_language%2Cis_comment_count%2Cds_created%2Cds_changed%2Cscore%2Cpath%2Curl%2Cis_uid%2Ctos_name%2Chash%2Csite&mm=1&pf=content%5E2.0&ps=15&hl=true&hl.fl=content&hl.snippets=3&hl.mergeContigious=true&f.content.hl.alternateField=teaser&f.content.hl.maxAlternateFieldLength=256&spellcheck.q=test&qf=content%5E40&qf=label%5E5.0&qf=tags_h1%5E5.0&qf=tags_h2_h3%5E3.0&qf=tags_h4_h5_h6%5E2.0&qf=tags_inline%5E1.0&qf=tos_content_extra%5E0.1&qf=tos_name%5E3.0&qf=ts_comments%5E20&wt=json&json.nl=map
</code>```

solarconfig.xml example

```<code><requestHandler name="/select" class="solr.SearchHandler">
 <lst name="defaults">
  <str name="df">text</str>
  <str name="q">*:*</str>
  <str name="q.alt">*:*</str>
 </lst>
</requestHandler>
</code>```

Thank you for any advice!

答:
It is possible to alter the query from your own drupal module, Apache Solr Search module exposes a hook for this (hook_apachesolr_query_alter()).

```<code>/**
 * Implementation of hook_apachesolr_query_alter().
 *
 * @param DrupalSolrQueryInterface $query
 * @see apachesolr.interface.inc
 */
function yourmodule_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  $query->replaceParam('q', '*:*');
}
</code>```

That being said, if you "got everything working except on /select", your issue could be related to your request dispatcher's handleSelect parameter, an option that affects the behavior of requests such as /select?qt=XXX (read SOLR mm and phrase queries not working after upgrading from SOLR 4 to SOLR 6 if you don't know what I mean).

Title: Solr 7 Forcing q value

Body:
I'm using the Drupal ApacheSolr Multisite Module which due to it's dependency Apache Solr Search config currently only support Solr 5.x. I'm using Solr 7 and have update most of the config. I've got everything working except on /select. I believe this is because the query the module supplies (example shown below) features a "q" value which apparently causes it to fail. Is there a way in the solrconfig.xml to set q equal to "* . *" for all selects? I'd like to avoid code changes to the Drupal module itself if possible for deployment purposes.

Solar REST request example

http://localhost:8983/solr/drupal_multisite/select?start=0&rows=10&fq=%28hash%3A6qegyq%20OR%20access__all%3A0%29&fq=%28hash%3A6qegyq%29&spellcheck=true&q=test&fl=id%2Centity_id%2Centity_type%2Cbundle%2Cbundle_name%2Clabel%2Css_language%2Cis_comment_count%2Cds_created%2Cds_changed%2Cscore%2Cpath%2Curl%2Cis_uid%2Ctos_name%2Chash%2Csite&mm=1&pf=content%5E2.0&ps=15&hl=true&hl.fl=content&hl.snippets=3&hl.mergeContigious=true&f.content.hl.alternateField=teaser&f.content.hl.maxAlternateFieldLength=256&spellcheck.q=test&qf=content%5E40&qf=label%5E5.0&qf=tags_h1%5E5.0&qf=tags_h2_h3%5E3.0&qf=tags_h4_h5_h6%5E2.0&qf=tags_inline%5E1.0&qf=tos_content_extra%5E0.1&qf=tos_name%5E3.0&qf=ts_comments%5E20&wt=json&json.nl=map

solarconfig.xml example

<requestHandler name="/select" class="solr.SearchHandler">
 <lst name="defaults">
  <str name="df">text</str>
  <str name="q">*:*</str>
  <str name="q.alt">*:*</str>
 </lst>
</requestHandler>

Thank you for any advice!

Body:
It is possible to alter the query from your own drupal module, Apache Solr Search module exposes a hook for this (hook_apachesolr_query_alter()).

/**
 * Implementation of hook_apachesolr_query_alter().
 *
 * @param DrupalSolrQueryInterface $query
 * @see apachesolr.interface.inc
 */
function yourmodule_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  $query->replaceParam('q', '*:*');
}

That being said, if you "got everything working except on /select", your issue could be related to your request dispatcher's handleSelect parameter, an option that affects the behavior of requests such as /select?qt=XXX (read SOLR mm and phrase queries not working after upgrading from SOLR 4 to SOLR 6 if you don't know what I mean).


问:
Send email after new document is created from template that includes URL from new document
I have some script in Sheets that sends an email after a button is pressed letting me know the sheet is newly created. However, the way I have written the script sends me a link to the template, and not the newly created sheet. I want to have the email created include the URL from the new sheet and not the template. I have the script used below (with some information changed for anonymity):

```<code>function sendemail()  {
MailApp.sendEmail("name@gmail.com", "New Sheet Created",
"The link for the new sheet is

https://docs.google.com/spreadsheets/");
}
</code>```

Thank you for the help, I plan to check back frequently to answer any questions. If I need to clarify anything, please let me know. Thank you!

答:
I think this answer might be what you are looking for:
https://webapps.stackexchange.com/questions/93305/how-to-find-url-of-the-current-sheet</p>

```<code>function getSheetUrl() {
    var SS = SpreadsheetApp.getActiveSpreadsheet();
    var ss = SS.getActiveSheet();
    var url = '';
    url += SS.getUrl();
    url += '#gid=';
    url += ss.getSheetId();
    return url;
}
</code>```

Body:
I have some script in Sheets that sends an email after a button is pressed letting me know the sheet is newly created. However, the way I have written the script sends me a link to the template, and not the newly created sheet. I want to have the email created include the URL from the new sheet and not the template. I have the script used below (with some information changed for anonymity):

function sendemail()  {
MailApp.sendEmail("name@gmail.com", "New Sheet Created",
"The link for the new sheet is

https://docs.google.com/spreadsheets/");
}

Thank you for the help, I plan to check back frequently to answer any questions. If I need to clarify anything, please let me know. Thank you!

Body:
I think this answer might be what you are looking for:
https://webapps.stackexchange.com/questions/93305/how-to-find-url-of-the-current-sheet

function getSheetUrl() {
    var SS = SpreadsheetApp.getActiveSpreadsheet();
    var ss = SS.getActiveSheet();
    var url = '';
    url += SS.getUrl();
    url += '#gid=';
    url += ss.getSheetId();
    return url;
}


问:
Pointer addition and element size
At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

Under: Pointer addition and element size

There is the following code:

```<code>// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]
</code>```

How did "p" in the last line become "4"?

Thanks.

答:
because p is pointer to a type with size 4 bytes. + operator on pointers is actually pointer shift. compiler knows the size of pointed type and shifts it by appropriate value

if you change int to short, p will be shifted by 2 bytes

Title: Pointer addition and element size

Body:
At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

Under: Pointer addition and element size

There is the following code:

// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

How did "p" in the last line become "4"?

Thanks.


问:
Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error
I want to create a docker image. This is my work directory:
Dockerfile.in   test.json   test.py

And this is my Dockerfile:

```<code>COPY ./test.json /home/test.json
COPY ./test.py /home/test.py

RUN python test.py
</code>```

When i launch this command:
docker build -f Dockerfile.in -t 637268723/test:1.0 .

It gives me this error:

```<code>`Step 1/5 : COPY ./test.json /home/test.json
 ---> Using cache
 ---> 6774cd225d60
 Step 2/5 : COPY ./test.py /home/test.py
 COPY failed: stat /var/lib/docker/tmp/docker-builder428014112/test.py:
 no such file or directory`
</code>```

Can anyone help me?

答:
Removing ./ from source path should resolve your issue:

```<code> COPY test.json /home/test.json
 COPY test.py /home/test.py
</code>```

Body:
I want to create a docker image. This is my work directory:
Dockerfile.in   test.json   test.py

And this is my Dockerfile:

COPY ./test.json /home/test.json
COPY ./test.py /home/test.py

RUN python test.py

When i launch this command:
docker build -f Dockerfile.in -t 637268723/test:1.0 .

It gives me this error:

`Step 1/5 : COPY ./test.json /home/test.json
 ---> Using cache
 ---> 6774cd225d60
 Step 2/5 : COPY ./test.py /home/test.py
 COPY failed: stat /var/lib/docker/tmp/docker-builder428014112/test.py:
 no such file or directory`

Can anyone help me?

Body:
Removing ./ from source path should resolve your issue:

 COPY test.json /home/test.json
 COPY test.py /home/test.py


问:
What linkage do constexpr functions have by default?
Do constexpr functions have internal linkage by default or external?

Take for example the following function:

```<code>constexpr int foo() {
    return 0;
}
</code>```

答:
A constexpr specifier used in a function or static member variable (since C++17) declaration implies inline.

from cppreference

Body:
Do constexpr functions have internal linkage by default or external?

Take for example the following function:

constexpr int foo() {
    return 0;
}


问:
How to convert from unicode list to normal list in python/django
How can i convert this list:

```<code>list = [u"[u'book1', u'book2', u'book3']"]into this list:
</code>```

to:

```<code>[u'book1', u'book2', u'book3']
</code>```

I tried this :

```<code>n = ast.literal_eval(list)
</code>```

but i got this error:

ValueError: malformed string

what else can i do to change this list without "u"?

答:
If you know that your list's data is safe you can use eval():

```<code>>>> a = [u"[u'book1', u'book2', u'book3']"]
>>> eval(a[0])
['book1', 'book2', 'book3']
</code>```

Otherwise, the safest option is to use literal_eval from ast module:

```<code>>>> from ast import literal_eval
>>> literal_eval(a[0])
['book1', 'book2', 'book3']
</code>```

Body:
How can i convert this list:

list = [u"[u'book1', u'book2', u'book3']"]into this list:

to:

[u'book1', u'book2', u'book3']

I tried this :

n = ast.literal_eval(list)

but i got this error:

ValueError: malformed string

what else can i do to change this list without "u"?

Body:
If you know that your list's data is safe you can use eval():

>>> a = [u"[u'book1', u'book2', u'book3']"]
>>> eval(a[0])
['book1', 'book2', 'book3']

Otherwise, the safest option is to use literal_eval from ast module:

>>> from ast import literal_eval
>>> literal_eval(a[0])
['book1', 'book2', 'book3']


问:
IONIC/angular is sending origin as file:// in POST and PUT -Getting 403 forbidden Error from API
I am working on IONIC 3/Angular android app. ionic is sending http header origin as file:// for POST and PUT methods of Http calls. It does not add origin to GET method.

The lib i used is '@angular/http'.

We have strict restrictions on the API side. we cannot modify that.

Can any one suggest a solution?

Following is the snippet of http header

```<code>    content-type:application/json
    Host:XXXXXXX
    Origin:file://
    User-Agent:Mozilla/5.0 (Linux; Android 7.1.1; Android SDK built
    for x86 Build/NYC; wv) AppleWebKit/537.36 (KHTML, like Gecko)
    Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36
    X-DevTools-Emulate-Network-Conditions-Client-Id:XXXXX
    X-Requested-With:com.X.X.X
</code>```

I also looked the following POSTs and forums. No luck

https://forum.ionicframework.com/t/native-app-is-sending-header-origin-file-which-causes-problems/62388

SO link but no solution.

Ionic native app is sending header Origin:file:// which causes problems

答:
I'm not sure if this would solve your problem, but I remember running into this issue when I was making an ionic app awhile back. Looking at how I have my app set up, it looks like I used a proxy to make my http calls on my local. I have a file in the root directory called ionic.config.json which is as follows:

```<code>{
  "name": "mobile",
  "app_id": "",
  "type": "ionic-angular",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://your-local-api-address"
    }
  ]
}
</code>```

and then in the file I use to store API info, I have my URL just set to "/api". There definitely is a solution, but it might be that you're trying to do something ionic can't (easily?) do.. like running your live reload while you're trying to run the app on a native device.

UPDATE

Basically what I wrote above, but found this older posted from a guy who says he has a workaround, here's his input

I managed to find a working solution !
  You need to proxy your api server into livereload so that your web app will
  think the api server is actually the same as your livereload server.
  Proxy configuration specs are here : https://github.com/driftyco/ionic-
  cli#advanced-serve-options
  For example, if your api server is on 192.168.0.1:8888, you need to add this
  to your ionic.project :

```<code>"proxies": [
{
  "path": "/api",
  "proxyUrl": "http://192.168.0.1:8888/api"
}
]
</code>```

And then, inside your app, you have to make your api calls like if it was
     local, directly from /api.

Here is the link to the older thread

https://github.com/ionic-team/ionic-cli/issues/89

Body:
I am working on IONIC 3/Angular android app. ionic is sending http header origin as file:// for POST and PUT methods of Http calls. It does not add origin to GET method.

The lib i used is '@angular/http'.

We have strict restrictions on the API side. we cannot modify that.

Can any one suggest a solution?

Following is the snippet of http header

    content-type:application/json
    Host:XXXXXXX
    Origin:file://
    User-Agent:Mozilla/5.0 (Linux; Android 7.1.1; Android SDK built
    for x86 Build/NYC; wv) AppleWebKit/537.36 (KHTML, like Gecko)
    Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36
    X-DevTools-Emulate-Network-Conditions-Client-Id:XXXXX
    X-Requested-With:com.X.X.X

I also looked the following POSTs and forums. No luck

https://forum.ionicframework.com/t/native-app-is-sending-header-origin-file-which-causes-problems/62388

SO link but no solution.

Ionic native app is sending header Origin:file:// which causes problems

Body:
I'm not sure if this would solve your problem, but I remember running into this issue when I was making an ionic app awhile back. Looking at how I have my app set up, it looks like I used a proxy to make my http calls on my local. I have a file in the root directory called ionic.config.json which is as follows:

{
  "name": "mobile",
  "app_id": "",
  "type": "ionic-angular",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://your-local-api-address"
    }
  ]
}

and then in the file I use to store API info, I have my URL just set to "/api". There definitely is a solution, but it might be that you're trying to do something ionic can't (easily?) do.. like running your live reload while you're trying to run the app on a native device.

UPDATE

Basically what I wrote above, but found this older posted from a guy who says he has a workaround, here's his input

I managed to find a working solution !
  You need to proxy your api server into livereload so that your web app will
  think the api server is actually the same as your livereload server.
  Proxy configuration specs are here : https://github.com/driftyco/ionic-
  cli#advanced-serve-options
  For example, if your api server is on 192.168.0.1:8888, you need to add this
  to your ionic.project :

"proxies": [
{
  "path": "/api",
  "proxyUrl": "http://192.168.0.1:8888/api"
}
]

And then, inside your app, you have to make your api calls like if it was
     local, directly from /api.

Here is the link to the older thread

https://github.com/ionic-team/ionic-cli/issues/89


问:
Conditional Styling of Radio Buttons not working(VueJs)

I am trying to make a quiz app. Where on clicking the option, there is an immediate feedback of whether it is the correct answer or not. I am trying to achieve this with CSS and conditional class styling in VueJS.

But the result is different. Let us say option 1, 2 and 3 are wrong answers and option 4 is correct answer. When I click at option 1 or option 2, option 3 is getting selected.

```<code>.gpquiz .incorrect input[type="radio"]:checked ~ label:before {
    content:'\274C';
    text-indent: .9em;
    color: white;
    background-color: maroon;
}

.gpquiz .incorrect input[type="radio"]:checked ~ label {
    background-color: #fff4f4;
</code>```

JSFiddle

答:
There are a few issues here. Firstly, with a radio list you need to bind v-model to one underlying variable so Vue selects the correct option, in your example you are binding your radio buttons to an array index, but you need to do:

```<code><input type="radio" value="1" v-model="selected">
<input type="radio" value="2" v-model="selected">
</code>```

The problem is that you have given each of your radio buttons a value of either true or null based on their correct value, so you need to set the value to something unique, such as index. Also, because you are going to be reusing this piece of code you should wrap it in it's own component and pass the question as a prop so:

```<code>Vue.component('question', {
  template: '#question',
  props: ['question', 'number'],
  methods: {
    hideOption: function() {
      this.disabled = true;
    }
  },
  data() {
    return {
      selected: ''
    }
  }
})
</code>```

Then your markup would be (I've removed some properties for clarity):

```<code><template id="question">
  <div>
    <h5>{{question.instruction}} {{selected}}</h5>
    <h5>{{number}}. {{question.text}}</h5>
    <ul >
      <li v-for="(option, optionindex) in question.options">
        <div :class="{correct: option['correct'],  incorrect: !option['correct']}">
          <input type="radio" @click="hideOption" :value="optionindex" :name="number" v-model="selected">
          <label>{{option.text}}</label>
        </div>
      </li>
    </ul>
  </div>
</template>
</code>```

Then in you main Vue instance you can do:

```<code><div id="app">
  <div class="col-sm-8 gpquiz">
    <question :question="question" :number="index+1" :key="index" v-for="(question, index) in questions"></question>
  </div>
</div>
</code>```

Here's the JSFiddle for that: https://jsfiddle.net/8ocmun6s/

You now have a second problem, your user can select a correct or incorrect answer but your main Vue instance doesn't know anything about what was selected, to do that we need to $emit that event back to the parent and we can do that by using a watcher to watch our selected value and $emit the event when it changes:

```<code>  watch: {
    selected(answer) {
      let correct = this.question.options[answer].correct
      // Emit the question number and whether it was correct back to the parent
      this.$emit('user-selected', this.number, correct)
    }
  },
</code>```

And, we can now listen to that on the component and trigger a method (in this case selectAnswer):

```<code><question :question="question" :number="index+1" :key="index" @user-selected="selectAnswer" v-for="(question, index) in quiz.questions"></question>
</code>```

Now we just need to add that method:

```<code>methods: {
  selectAnswer(number, correct) {
   // use $set here otherwise view won't detect the change
   this.$set(this.userResponses, number-1, correct)
  }
},
</code>```

Now we have an array of true or false answers we can present the result, I'm just going to use a computed:

```<code>computed:{
  correctAnswers(){
    // Return the number of correct answers
    return this.userResponses.filter(x => x).length
  }
},
</code>```

Now we can just show and hide that when the user submits the form, so we can add the following to methods:

```<code>submitAnswers() {
  this.submitted = true;
}
</code>```

And also make sure you declare submitted in data, then you can bind that to the button and add the conditional to your markup, which ends up as:

```<code><div id="app">
  <h1>{{quiz.title}}</h1>
  <hr>
  <div class="col-sm-8 gpquiz" v-if="!submitted">
    <question :question="question" :number="index+1" :key="index" @user-selected="selectAnswer" v-for="(question, index) in quiz.questions"></question>

    <button @click="submitAnswers">
      Submit
    </button>
  </div>
  <h4 v-else>
    You got {{correctAnswers}} out of {{userResponses.length}} Correct!
  </h4>
</div>
</code>```

And here's the final JSFiddle: https://jsfiddle.net/fvk4L326/

Body:
I am trying to make a quiz app. Where on clicking the option, there is an immediate feedback of whether it is the correct answer or not. I am trying to achieve this with CSS and conditional class styling in VueJS.

But the result is different. Let us say option 1, 2 and 3 are wrong answers and option 4 is correct answer. When I click at option 1 or option 2, option 3 is getting selected.

.gpquiz .incorrect input[type="radio"]:checked ~ label:before {
    content:'\274C';
    text-indent: .9em;
    color: white;
    background-color: maroon;
}

.gpquiz .incorrect input[type="radio"]:checked ~ label {
    background-color: #fff4f4;

JSFiddle

Body:
There are a few issues here. Firstly, with a radio list you need to bind v-model to one underlying variable so Vue selects the correct option, in your example you are binding your radio buttons to an array index, but you need to do:

<input type="radio" value="1" v-model="selected">
<input type="radio" value="2" v-model="selected">

The problem is that you have given each of your radio buttons a value of either true or null based on their correct value, so you need to set the value to something unique, such as index. Also, because you are going to be reusing this piece of code you should wrap it in it's own component and pass the question as a prop so:

Vue.component('question', {
  template: '#question',
  props: ['question', 'number'],
  methods: {
    hideOption: function() {
      this.disabled = true;
    }
  },
  data() {
    return {
      selected: ''
    }
  }
})

Then your markup would be (I've removed some properties for clarity):

<template id="question">
  <div>
    <h5>{{question.instruction}} {{selected}}</h5>
    <h5>{{number}}. {{question.text}}</h5>
    <ul >
      <li v-for="(option, optionindex) in question.options">
        <div :class="{correct: option['correct'],  incorrect: !option['correct']}">
          <input type="radio" @click="hideOption" :value="optionindex" :name="number" v-model="selected">
          <label>{{option.text}}</label>
        </div>
      </li>
    </ul>
  </div>
</template>

Then in you main Vue instance you can do:

<div id="app">
  <div class="col-sm-8 gpquiz">
    <question :question="question" :number="index+1" :key="index" v-for="(question, index) in questions"></question>
  </div>
</div>

Here's the JSFiddle for that: https://jsfiddle.net/8ocmun6s/

You now have a second problem, your user can select a correct or incorrect answer but your main Vue instance doesn't know anything about what was selected, to do that we need to $emit that event back to the parent and we can do that by using a watcher to watch our selected value and $emit the event when it changes:

  watch: {
    selected(answer) {
      let correct = this.question.options[answer].correct
      // Emit the question number and whether it was correct back to the parent
      this.$emit('user-selected', this.number, correct)
    }
  },

And, we can now listen to that on the component and trigger a method (in this case selectAnswer):

<question :question="question" :number="index+1" :key="index" @user-selected="selectAnswer" v-for="(question, index) in quiz.questions"></question>

Now we just need to add that method:

methods: {
  selectAnswer(number, correct) {
   // use $set here otherwise view won't detect the change
   this.$set(this.userResponses, number-1, correct)
  }
},

Now we have an array of true or false answers we can present the result, I'm just going to use a computed:

computed:{
  correctAnswers(){
    // Return the number of correct answers
    return this.userResponses.filter(x => x).length
  }
},

Now we can just show and hide that when the user submits the form, so we can add the following to methods:

submitAnswers() {
  this.submitted = true;
}

And also make sure you declare submitted in data, then you can bind that to the button and add the conditional to your markup, which ends up as:

<div id="app">
  <h1>{{quiz.title}}</h1>
  <hr>
  <div class="col-sm-8 gpquiz" v-if="!submitted">
    <question :question="question" :number="index+1" :key="index" @user-selected="selectAnswer" v-for="(question, index) in quiz.questions"></question>

    <button @click="submitAnswers">
      Submit
    </button>
  </div>
  <h4 v-else>
    You got {{correctAnswers}} out of {{userResponses.length}} Correct!
  </h4>
</div>

And here's the final JSFiddle: https://jsfiddle.net/fvk4L326/


问:
Asp.net Core 2.0 MVC CSS that i add doesn't work

I have a problem adding CSS to my site, i have linked the bootstrap.css and the site.css file and it finds and uses them correctly, but if i try to add something to the files it doesn't use it. Here is the code where i am trying to use it to prevent html from overflowing from div:

```<code>@foreach (var article in Model.Articles)
{
    <div class="col-md-12">
        <ul class="list-group article-list">
                <li class="list-group-item">
                    <a asp-action="Details" asp-route-id="@article.Id" asp-route-title="@article.Title.ToFriendlyUrl()">@article.Title</a>
                    <br />
                    <div id="articleIndex">@article.ShortContent ... [<a asp-action="Details" asp-route-id="@article.Id" asp-route-title="@article.Title.ToFriendlyUrl()">Read More</a>]</div>
                    <small>published by @article.Author on @article.PublishDate.ToShortDateString()</small>
                </li>
                @if (User.IsInRole("Administrator") || User.Identity.Name == article.Author)
                {
                    <a href="article/edit/@article.Id" class="btn btn-danger">Edit</a>
                    <a href="article/delete/@article.Id" class="btn btn-danger">Delete</a>
                }
        </ul>
    </div>
}
</code>```

So i added the following to site.css file, but it doesn't use it. I tried adding it to bootstrap.css too and still doesn't properly use it. If i add the css in the html file it does work.

```<code>div#articleIndex {
    word-wrap: break-word !important;
}
</code>```

Why is it now finding my custom added css, but still uses the bootstrap default ones

答:
Find in your project file named Site.css and add your styles there. Make sure that you are following correct load order. Site.css should be loaded after bootstrap.css as latest css overwrites previous.
Last, verify in Chrome development tools (F12) that your Site.css is loaded.</p>

Body:
I have a problem adding CSS to my site, i have linked the bootstrap.css and the site.css file and it finds and uses them correctly, but if i try to add something to the files it doesn't use it. Here is the code where i am trying to use it to prevent html from overflowing from div:

@foreach (var article in Model.Articles)
{

                    @article.Title

@article.ShortContent ... [Read More]

                    published by @article.Author on @article.PublishDate.ToShortDateString()

                @if (User.IsInRole("Administrator") || User.Identity.Name == article.Author)
                {
                    Edit
                    Delete
                }

}

So i added the following to site.css file, but it doesn't use it. I tried adding it to bootstrap.css too and still doesn't properly use it. If i add the css in the html file it does work.

div#articleIndex {
    word-wrap: break-word !important;
}

Why is it now finding my custom added css, but still uses the bootstrap default ones


问:
PHP - isolate first letter from a text
I have a set of articles, in which I want to style the first letter from each article (with CSS).

the articles usually start with a paragrah, like:

```<code><p> bla bla </p>
</code>```

So how could I wrap the first letter from this text within a <span> tag ?

答:
you could add a Php span but might not be as clean
$s = "
 la la
";
$strip = trim(strip_tags($s));
$t = explode(' ', $strip);
$first = $t[0];

// then replace first character with span around it
$replace = preg_replace('/^?/', '$1', $first);

// then replace the first time of that word in the string
$s = preg_replace('/'.$first.'/', $replace, $s, 1);

echo $s;

//not tested

Title: PHP - isolate first letter from a text

Body:
I have a set of articles, in which I want to style the first letter from each article (with CSS).

the articles usually start with a paragrah, like:

 bla bla

So how could I wrap the first letter from this text within a <span> tag ?


问:
delete item in sqlite database with cursor
I have a cursor that filled my database and i would like to delete the elements from this table.

her is the removal code fro my database:

```<code>public void deleteItem(int id){
    SQLiteDatabase database = this.getWritableDatabase();
    database.delete(ContractParaGastos.GASTO, ContractParaGastos.Columnas.MONTO + " = ?", new String[]{String.valueOf(id)});
    database.close();
}
</code>```

And here is the removal code in recyclerviewAdapter:

```<code> viewHolder.button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           databaseHelper.deleteItem(i);
        }
    });
}
</code>```

I add this line in my adapter:

```<code> databaseHelper = new DatabaseHelper(context, ContractParaGastos.GASTO, null, 4);
</code>```

But when i click on the delete button nothing happens. the line is still present in my recyclerview.

Help me please!

答:
Because you didn't initialised the databaseHelper.

Try this code:

```<code>   DatabaseHelper databaseHelper = new DatabaseHelper(this); //in case of activity.
   DatabaseHelper databaseHelper = new DatabaseHelper(getActivity()); //in case of Fragment.
</code>```

Paste this code in onCreate() of Activity or onCreateView() of Fragment.

Thanks and let me know if some need to know more.

Body:
I have a cursor that filled my database and i would like to delete the elements from this table.

her is the removal code fro my database:

public void deleteItem(int id){
    SQLiteDatabase database = this.getWritableDatabase();
    database.delete(ContractParaGastos.GASTO, ContractParaGastos.Columnas.MONTO + " = ?", new String[]{String.valueOf(id)});
    database.close();
}

And here is the removal code in recyclerviewAdapter:

 viewHolder.button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           databaseHelper.deleteItem(i);
        }
    });
}

I add this line in my adapter:

 databaseHelper = new DatabaseHelper(context, ContractParaGastos.GASTO, null, 4);

But when i click on the delete button nothing happens. the line is still present in my recyclerview.

Help me please!

Body:
Because you didn't initialised the databaseHelper.

Try this code:

   DatabaseHelper databaseHelper = new DatabaseHelper(this); //in case of activity.
   DatabaseHelper databaseHelper = new DatabaseHelper(getActivity()); //in case of Fragment.

Paste this code in onCreate() of Activity or onCreateView() of Fragment.

Thanks and let me know if some need to know more.


问:
Printing a Class
Hi I'm trying to print 4 band members details using a class, however I'm only able to print one, ill give samples to give you an understanding below, this is my whole code

```<code>class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)
        return '{} {} \n{} {} {}'.format(paul._firstname, paul._surname,     paul.d, paul.m, paul.y)
        return '{} {} \n{} {} {}'.format(george._firstname,     george._surname, george.d, george.m, george.y)
        return '{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d, ringo.m, ringo.y)

john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._d = '18th'
paul._m = 'June'
paul._y = '1942'

george._firstname = 'George'
george._surname = 'Harrison'
george._d = '25th'
george._m = 'February'
george._y = '1943'

ringo._firstname = 'Ringo'
ringo._surname = 'Starr'
ringo._d = '7th'
ringo._m = 'July'
ringo._y = '1940'

print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y))
print('{} {} \n{} {} {}'.format(paul._firstname, paul._surname, paul.d,     paul.m, paul.y))
print('{} {} \n{} {} {}'.format(george._firstname, george._surname,         george.d, george.m, george.y))
print('{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d,     ringo.m, ringo.y))
</code>```

I receive, the correct output, which is this:

```<code>John Lennon
8th October 1940
Paul McCartney
18th June 1942
George Harrison
25th February 1943
Ringo Starr
7th July 1940
</code>```

I want to be able to type:

```<code>print(john)
print(george)
print(paul)
print(ringo)
</code>```

To get the same output, however when i type this and remove the bottom 4 print lines, i get this

```<code>John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940
</code>```

My understanding up until now is that the __repr__(self) can only read one line of code, which would be john, but that's where my knowledge stops.

ANY help is more than appreciated! if you need more info please ask, I'm quite new to this as I'm in my first year at university so I appreciate your patience and help!:)

答:
You leave a function with a return-statement. Following lines are ignored.
Within a method when accessing the attributes you only use placeholders for the objects itself. Use self instead of real names of objects.

```<code>def __repr__(self):
  return '{} {} \n{} {} {}'.format(
    self._firstname, self._surname, self.d, self.m, self.y)
</code>```

Title: Printing a Class

Body:
Hi I'm trying to print 4 band members details using a class, however I'm only able to print one, ill give samples to give you an understanding below, this is my whole code

class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)
        return '{} {} \n{} {} {}'.format(paul._firstname, paul._surname,     paul.d, paul.m, paul.y)
        return '{} {} \n{} {} {}'.format(george._firstname,     george._surname, george.d, george.m, george.y)
        return '{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d, ringo.m, ringo.y)

john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._d = '18th'
paul._m = 'June'
paul._y = '1942'

george._firstname = 'George'
george._surname = 'Harrison'
george._d = '25th'
george._m = 'February'
george._y = '1943'

ringo._firstname = 'Ringo'
ringo._surname = 'Starr'
ringo._d = '7th'
ringo._m = 'July'
ringo._y = '1940'

print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y))
print('{} {} \n{} {} {}'.format(paul._firstname, paul._surname, paul.d,     paul.m, paul.y))
print('{} {} \n{} {} {}'.format(george._firstname, george._surname,         george.d, george.m, george.y))
print('{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d,     ringo.m, ringo.y))

I receive, the correct output, which is this:

John Lennon
8th October 1940
Paul McCartney
18th June 1942
George Harrison
25th February 1943
Ringo Starr
7th July 1940

I want to be able to type:

print(john)
print(george)
print(paul)
print(ringo)

To get the same output, however when i type this and remove the bottom 4 print lines, i get this

John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940

My understanding up until now is that the __repr__(self) can only read one line of code, which would be john, but that's where my knowledge stops.

ANY help is more than appreciated! if you need more info please ask, I'm quite new to this as I'm in my first year at university so I appreciate your patience and help!:)

Body:
You leave a function with a return-statement. Following lines are ignored.
Within a method when accessing the attributes you only use placeholders for the objects itself. Use self instead of real names of objects.

def __repr__(self):
  return '{} {} \n{} {} {}'.format(
    self._firstname, self._surname, self.d, self.m, self.y)


问:
Create new column using condition on another existing column
I have data like this

```<code>Time    chamber
9       1
10      2
11      3
12      4
13      5
14      6
15      7
16      8
17      9
18      10
19      11
20      12
21      1
22      2
23      3
24      4
</code>```

I want to create a new column using conditions on another existing column (chamber).

It should look something like this

```<code>Time    chamber treatment
9       1       c2t2
10      2       c2t2
11      3       c0t0r
12      4       c2t2r
13      5       c2t2r
14      6       c0t0
15      7       c0t0r
16      8       c0t0r
17      9       c2t2
18      10      c2t2r
19      11      c0t0
20      12      c0t0
21      1       c2t2
22      2       c2t2
23      3       c0t0r
24      4       c2t2r
</code>```

For chambers 1,2,9:   Treatment is c2t2

For chambers 3,7,8:   Treatment is c0t0r.

For chambers 4,5,10:  Treatment is c2t2r

For chambers 6,11,12: Treatment is c0t0.

I have also made a lookup table, but I don't know how to use it:

```<code>lookup_table <- data.frame(row.names = c("1", "2", "3","4", "5", "6","7", "8", "9","10", "11", "12"),
                           new_col = c("C2T2", "C2T2", "C0T0R","C2T2R", "C2T2R", "C0T0","C0T0R", "C0T0R", "C2T2","C2T2R", "C0T0", "C0T0"),
                           stringsAsFactors = FALSE)
</code>```

答:
You can merge your df with the lookup_table. In my experience, if you want to combine different data.frames, merge() is the command I like to use. Do note that there are many different ways and specialised packages you can use for the same purpose!

You need to specify which column you use as the 'matching column' and also that you want to keep all records in df:

```<code>merge(df, lookup_table, all.x = TRUE, by.x = "chamber", by.y = "row.names")
</code>```

Data:

```<code>df <- structure(list(Time = 9:24, chamber = c(1L, 2L, 3L, 4L, 5L, 6L,
                     7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L)),
                    .Names = c("Time", "chamber"), class = "data.frame",
                    row.names = c(NA, -16L))
lookup_table <- structure(list(new_col = c("C2T2", "C2T2", "C0T0R", "C2T2R",
                                          "C2T2R", "C0T0", "C0T0R", "C0T0R",
                                          "C2T2", "C2T2R", "C0T0", "C0T0")),
                                .Names = "new_col",
                                row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), class = "data.frame")
</code>```

Body:
I have data like this

Time    chamber
9       1
10      2
11      3
12      4
13      5
14      6
15      7
16      8
17      9
18      10
19      11
20      12
21      1
22      2
23      3
24      4

I want to create a new column using conditions on another existing column (chamber).

It should look something like this

Time    chamber treatment
9       1       c2t2
10      2       c2t2
11      3       c0t0r
12      4       c2t2r
13      5       c2t2r
14      6       c0t0
15      7       c0t0r
16      8       c0t0r
17      9       c2t2
18      10      c2t2r
19      11      c0t0
20      12      c0t0
21      1       c2t2
22      2       c2t2
23      3       c0t0r
24      4       c2t2r

For chambers 1,2,9:   Treatment is c2t2

For chambers 3,7,8:   Treatment is c0t0r.

For chambers 4,5,10:  Treatment is c2t2r

For chambers 6,11,12: Treatment is c0t0.

I have also made a lookup table, but I don't know how to use it:

lookup_table <- data.frame(row.names = c("1", "2", "3","4", "5", "6","7", "8", "9","10", "11", "12"),
                           new_col = c("C2T2", "C2T2", "C0T0R","C2T2R", "C2T2R", "C0T0","C0T0R", "C0T0R", "C2T2","C2T2R", "C0T0", "C0T0"),
                           stringsAsFactors = FALSE)

Body:
You can merge your df with the lookup_table. In my experience, if you want to combine different data.frames, merge() is the command I like to use. Do note that there are many different ways and specialised packages you can use for the same purpose!

You need to specify which column you use as the 'matching column' and also that you want to keep all records in df:

merge(df, lookup_table, all.x = TRUE, by.x = "chamber", by.y = "row.names")

Data:

df <- structure(list(Time = 9:24, chamber = c(1L, 2L, 3L, 4L, 5L, 6L,
                     7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L)),
                    .Names = c("Time", "chamber"), class = "data.frame",
                    row.names = c(NA, -16L))
lookup_table <- structure(list(new_col = c("C2T2", "C2T2", "C0T0R", "C2T2R",
                                          "C2T2R", "C0T0", "C0T0R", "C0T0R",
                                          "C2T2", "C2T2R", "C0T0", "C0T0")),
                                .Names = "new_col",
                                row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), class = "data.frame")


答:
You are getting malformed string because literal_eval is expecting a string, but you are passing it a list. Look at the outermost delimiters. For a string they should be matched quotes but you have square brackets.

```<code>>>> mylist = [u"[u'book1', u'book2', u'book3']"]
>>> ast.literal_eval(mylist.pop())
[u'book1', u'book2', u'book3']   # in Python 2
['book1', 'book2', 'book3']      # in Python 3
</code>```

Title: How to convert from unicode list to normal list in python/django

Body:
You are getting malformed string because literal_eval is expecting a string, but you are passing it a list. Look at the outermost delimiters. For a string they should be matched quotes but you have square brackets.

>>> mylist = [u"[u'book1', u'book2', u'book3']"]
>>> ast.literal_eval(mylist.pop())
[u'book1', u'book2', u'book3']   # in Python 2
['book1', 'book2', 'book3']      # in Python 3


答:
There is no way to find the name of a variable from by value
With nameof you can get string name of Method, Property, Class, variable ... according to nameof docs

Title: Getting nameof what an element references in a foreach

Body:
I am trying to get the nameof a variable being passed through a foreach loop.

string[] printThis = {"doesntMatter"};
string[] andThis = {"doesntMatter"};
string[][] arrayOfArrays = {printThis, andThis};

foreach(string element in arrayOfArrays)
{
    string theNameOfTheElement = nameOf(element);
    Console.WriteLine(theNameOfTheElement + " ");
}

Instead of getting the desired result of

printThis andThis

I'm obviously getting just:

element

Is this not allowed? A better way?


问:
How to store each web elements in a distinct variable whose index is increments in XPath for each web element
```<code>   String spath = ".//*[@id='container']/div/div[2]/div/div/div[";

   String epath = "]/div[2]";
   for(int i = 1; i < 5; i++) {

      String tpath = spath+i+epath;
      WebElement listpath = h.findElement(By.xpath(tpath));
      String list = listpath.getText();
      System.out.println(list);

    }
</code>```

In this case I have stored all the web elements in the single variable "list", but I need to store each web elements in each distinct variable?

答:
It all depends how you are going to access it later. If order is not important, create a set, which will also de-duplicate your elements, by adding on top:

```<code>Set<String> myElements = new HashSet<>();
</code>```

If order is important, and you will need to access the elements in order, use:

```<code>List<String> myElements = new ListArray<>();
</code>```

To add the elements in the collection you will use:

```<code>myElements.add(list);
</code>```

Instead of printing it.

You can make your collection holding any type, for example you can replace String with WebElement. In that case add the listpath to your collection.

Body:
   String spath = ".//*[@id='container']/div/div[2]/div/div/div[";

   String epath = "]/div[2]";
   for(int i = 1; i < 5; i++) {

      String tpath = spath+i+epath;
      WebElement listpath = h.findElement(By.xpath(tpath));
      String list = listpath.getText();
      System.out.println(list);

    }

In this case I have stored all the web elements in the single variable "list", but I need to store each web elements in each distinct variable?

Body:
It all depends how you are going to access it later. If order is not important, create a set, which will also de-duplicate your elements, by adding on top:

Set<String> myElements = new HashSet<>();

If order is important, and you will need to access the elements in order, use:

List<String> myElements = new ListArray<>();

To add the elements in the collection you will use:

myElements.add(list);

Instead of printing it.

You can make your collection holding any type, for example you can replace String with WebElement. In that case add the listpath to your collection.


问:
How to take out certain elements from a pdb file
I am trying to take out certain columns from a pdb file. I already have taken out all lines that start out with ATOM in my code. For some reason my sub functions are not working and I do not know where or how to call them.
My code is:</p>

```<code>open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
 while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
    push @newlines, $line;
    }
}

my $atomcount = @newlines;
#print "@newlines\n";
#print "$atomcount\n";

##############################################################
#This function will take out the element from each line
#The element is from column 77 and contains one or two letters

sub atomfreq {
    foreach my $record1(@newlines) {
      my $element = substr($record1, 76, 2);
      print "$element\n";
      return;
    }
}

################################################################
#This function will take out the residue name from each line
#The element is from column 18 and contains 3 letters

sub resfreq {
    foreach my $record2(@newlines) {
      my $residue = substr($record2, 17, 3);
      print "$residue\n";
      return;
    }
}
</code>```

答:
As @Ossip already said in this answer you simply need to call your functions:

```<code>sub atomfreq {
    ...
}

sub resfreq {
    ...
}

atomfreq();
resfreq();
</code>```

But I'm not sure whether these functions do what you intended because the comments imply that they should print every $residue and $element from the @newlines array. You've put a return statement inside the for loop which will immediately return from the whole function (and its for loop) so it will print only the first $residue or $element. Because the functions aren't supposed to return anything you can just drop that statement:

```<code>sub atomfreq {
    foreach my $record1(@newlines) {
        my $element = substr($record1, 76, 2);
        print "$element\n";
    }
}

sub resfreq {
    foreach my $record2(@newlines) {
        my $residue = substr($record2, 17, 3);
        print "$residue\n";
    }
}

atomfreq();
resfreq();
</code>```

Body:
I am trying to take out certain columns from a pdb file. I already have taken out all lines that start out with ATOM in my code. For some reason my sub functions are not working and I do not know where or how to call them.
My code is:

open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
 while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
    push @newlines, $line;
    }
}

my $atomcount = @newlines;
#print "@newlines\n";
#print "$atomcount\n";

##############################################################
#This function will take out the element from each line
#The element is from column 77 and contains one or two letters

sub atomfreq {
    foreach my $record1(@newlines) {
      my $element = substr($record1, 76, 2);
      print "$element\n";
      return;
    }
}

################################################################
#This function will take out the residue name from each line
#The element is from column 18 and contains 3 letters

sub resfreq {
    foreach my $record2(@newlines) {
      my $residue = substr($record2, 17, 3);
      print "$residue\n";
      return;
    }
}

Body:
As @Ossip already said in this answer you simply need to call your functions:

sub atomfreq {
    ...
}

sub resfreq {
    ...
}

atomfreq();
resfreq();

But I'm not sure whether these functions do what you intended because the comments imply that they should print every $residue and $element from the @newlines array. You've put a return statement inside the for loop which will immediately return from the whole function (and its for loop) so it will print only the first $residue or $element. Because the functions aren't supposed to return anything you can just drop that statement:

sub atomfreq {
    foreach my $record1(@newlines) {
        my $element = substr($record1, 76, 2);
        print "$element\n";
    }
}

sub resfreq {
    foreach my $record2(@newlines) {
        my $residue = substr($record2, 17, 3);
        print "$residue\n";
    }
}

atomfreq();
resfreq();


问:
Python - Can not solve LP
I have been trying for some time to solve the following linear problem in Python:

```<code>minimize{x1,x2}, such that:
x1+2*x2 = 2
2*x1+3*x2 =2
x1+x2=1
x1>=0
x2>=0
</code>```

I have tried the pulp and linprog libraries (from scipy.optimize import linprog) but I have not got anywhere. The first point is that both these libraries expect me to input some sort of "objective function" to minimize, while I am looking to minimize my variables as such (meaning essentially to verify that I do not have infintely many solutions). However, I tried to minimize the following objective function:

x1 + x2

judging that this is pretty much equal to minimizing x1 and x2 since they are both greater than 0. The second point is that both pulp and linprog seem unable to handle "Infeasible" cases. This means that when both these libraries come in front to an infeasible problem, instead of printing out something relevant (i.e.: "problem can not be solved"), they instead start dropping constraints till they get an answer. For example, the above problem is infeasible, since there are no such numbers x1 and x2 that satisfy all the above equations. Now linprog in this case prints out the following

```<code>message: 'Optimization terminated successfully.'
</code>```

and

```<code>x: array([ 0.,  0.])
</code>```

from which I understand that the solution is x1=0 and x2=0, which is of course incorrect.

My next move is to code everything myself with nested for loops and conditional statements to depict the constraints, but I don't wanna go there yet. Moreover, I am in search of a solution that can be easily generalized, to say 100+ different equations (since I will be doing stuff in n-dimensional spaces of Real Numbers) and 60+ variables (x1, x2 , ... , x60).

答:
This is trivial and i don't get why you did not show any code if you are having problems:

Code:

```<code>import numpy as np
from scipy.optimize import linprog

A_eq = np.array([[1, 2],  # x1+2*x2
                 [2, 3],  # 2*x1+3*x2
                 [1, 1]]) # x1+x2
b_eq = np.array([2,2,1])
c = np.array([1,1])       # min x1 + x2

res = linprog(c, A_eq=A_eq, b_eq=b_eq, method='simplex')
print(res)                                         # fails as expected;
                                                   #   crypted message (for non-experts)

# scipy >= 1.0 !!!
res = linprog(c, A_eq=A_eq, b_eq=b_eq, method='interior-point')
print(res)                                         # warns about problem-status in presolve

res = linprog(c, A_eq=A_eq, b_eq=b_eq, method='interior-point', options={'presolve': False})
print(res)                                         # declares infeasible
                                                   #   turning-off presolve sometimes needed
                                                   #   for more accurate status messages
                                                   #   (which is documented!)
</code>```

Additional info needed:

bounds : sequence, optional

(min, max) pairs for each element in x, defining the bounds on that parameter.
  Use None for one of min or max when there is no bound in that direction. By default bounds are (0, None) (non-negative) If a sequence containing a single tuple is provided, then min and max will be applied to all variables in the problem.

None of these runs will output status=success! (and flags corresponding to some exit-state are set)

Go check what attributes are set. (I'm not showing those as my scipy-install is a bit customized with some private debug-prints)

Now some word of advice:

don't trust scipy.linprog(method='simplex')

if you don't trust me: look up github-issues or search on SO

(i would have deprecated that function a long time ago; if no one is fixing it)

try scipy.linprog(method='interior-point')

if you can live with a non-simplex approach

if you have scipy >= 1.0

Coin's pulp brings, compared to scipy, a very very advanced LP-solver (Clp, favouring Simplex) and using it correctly, it won't output wrong status' messages here for your problems!

Clp is in my opinion the most advanced open-source LP-solver

If you don't have an objective: set the objective vector c to zeros!

And just to be clear

This means that when both these libraries come in front to an infeasible problem, instead of printing out something relevant (i.e.: "problem can not be solved"), they instead start dropping constraints till they get an answer. For example, the above problem is infeasible, since there are no such numbers x1 and x2 that satisfy all the above equations.

No!. No LP-solver, should ever return a successful-solution when the problem is infeasible (that's something else than saying a problem is infeasible!).

Additionally, most LP-solvers support infeasibility-detection (all simplex-type solvers; not all IPM-like solvers, but scipy's) and will return a feasibility-certificate when the problem is infeasible!

Only broken solvers linprog(method='simplex') might be troublesome here.

(The above is valid for problems which are not implying numerical-trouble, which is always possible using finite-memory floating-point math; except for maybe specialized rational-type solvers. This applies even to the most advanced commercial solvers and it's not important for your problem here)

Edit: Approach using Coin's pulp:

```<code>from pulp import *

prob = LpProblem("problem", LpMinimize)
x1 = LpVariable('x1', lowBound=0., upBound=None, cat='Continuous')
x2 = LpVariable('x2', lowBound=0., upBound=None, cat='Continuous')

# The objective function is added to 'prob' first
prob += 1.*x1 +1.*x2, "min x1 + x2"

# Constraints
prob += 1.*x1 + 2.*x2 == 2, "1*x1 + 2*x2 == 2"
prob += 2.*x1 + 3.*x2 == 2, "2*x1 + 3*x2 == 2"
prob += 1.*x1 + 1.*x2 == 1, "1*x1 + 1*x2 == 1"

# Solve
prob.solve()
print("Status:", LpStatus[prob.status])
for v in prob.variables():
    print(v.name, "=", v.varValue)
print("Objective: ", value(prob.objective))
</code>```

Output:

```<code>Status: Infeasible
x1 = 0.0
x2 = 1.0
Objective:  1.0
</code>```

Title: Python - Can not solve LP

Body:
I have been trying for some time to solve the following linear problem in Python:

minimize{x1,x2}, such that:
x1+2*x2 = 2
2*x1+3*x2 =2
x1+x2=1
x1>=0
x2>=0

I have tried the pulp and linprog libraries (from scipy.optimize import linprog) but I have not got anywhere. The first point is that both these libraries expect me to input some sort of "objective function" to minimize, while I am looking to minimize my variables as such (meaning essentially to verify that I do not have infintely many solutions). However, I tried to minimize the following objective function:

x1 + x2

judging that this is pretty much equal to minimizing x1 and x2 since they are both greater than 0. The second point is that both pulp and linprog seem unable to handle "Infeasible" cases. This means that when both these libraries come in front to an infeasible problem, instead of printing out something relevant (i.e.: "problem can not be solved"), they instead start dropping constraints till they get an answer. For example, the above problem is infeasible, since there are no such numbers x1 and x2 that satisfy all the above equations. Now linprog in this case prints out the following

message: 'Optimization terminated successfully.'

and

x: array([ 0.,  0.])

from which I understand that the solution is x1=0 and x2=0, which is of course incorrect.

My next move is to code everything myself with nested for loops and conditional statements to depict the constraints, but I don't wanna go there yet. Moreover, I am in search of a solution that can be easily generalized, to say 100+ different equations (since I will be doing stuff in n-dimensional spaces of Real Numbers) and 60+ variables (x1, x2 , ... , x60).

Body:
This is trivial and i don't get why you did not show any code if you are having problems:

Code:

import numpy as np
from scipy.optimize import linprog

A_eq = np.array([[1, 2],  # x1+2*x2
                 [2, 3],  # 2*x1+3*x2
                 [1, 1]]) # x1+x2
b_eq = np.array([2,2,1])
c = np.array([1,1])       # min x1 + x2

res = linprog(c, A_eq=A_eq, b_eq=b_eq, method='simplex')
print(res)                                         # fails as expected;
                                                   #   crypted message (for non-experts)

# scipy >= 1.0 !!!
res = linprog(c, A_eq=A_eq, b_eq=b_eq, method='interior-point')
print(res)                                         # warns about problem-status in presolve

res = linprog(c, A_eq=A_eq, b_eq=b_eq, method='interior-point', options={'presolve': False})
print(res)                                         # declares infeasible
                                                   #   turning-off presolve sometimes needed
                                                   #   for more accurate status messages
                                                   #   (which is documented!)

Additional info needed:

bounds : sequence, optional

(min, max) pairs for each element in x, defining the bounds on that parameter.
  Use None for one of min or max when there is no bound in that direction. By default bounds are (0, None) (non-negative) If a sequence containing a single tuple is provided, then min and max will be applied to all variables in the problem.

None of these runs will output status=success! (and flags corresponding to some exit-state are set)

Go check what attributes are set. (I'm not showing those as my scipy-install is a bit customized with some private debug-prints)

Now some word of advice:

don't trust scipy.linprog(method='simplex')

if you don't trust me: look up github-issues or search on SO

(i would have deprecated that function a long time ago; if no one is fixing it)

try scipy.linprog(method='interior-point')

if you can live with a non-simplex approach

if you have scipy >= 1.0

Coin's pulp brings, compared to scipy, a very very advanced LP-solver (Clp, favouring Simplex) and using it correctly, it won't output wrong status' messages here for your problems!

Clp is in my opinion the most advanced open-source LP-solver

If you don't have an objective: set the objective vector c to zeros!

And just to be clear

This means that when both these libraries come in front to an infeasible problem, instead of printing out something relevant (i.e.: "problem can not be solved"), they instead start dropping constraints till they get an answer. For example, the above problem is infeasible, since there are no such numbers x1 and x2 that satisfy all the above equations.

No!. No LP-solver, should ever return a successful-solution when the problem is infeasible (that's something else than saying a problem is infeasible!).

Additionally, most LP-solvers support infeasibility-detection (all simplex-type solvers; not all IPM-like solvers, but scipy's) and will return a feasibility-certificate when the problem is infeasible!

Only broken solvers linprog(method='simplex') might be troublesome here.

(The above is valid for problems which are not implying numerical-trouble, which is always possible using finite-memory floating-point math; except for maybe specialized rational-type solvers. This applies even to the most advanced commercial solvers and it's not important for your problem here)

Edit: Approach using Coin's pulp:

from pulp import *

prob = LpProblem("problem", LpMinimize)
x1 = LpVariable('x1', lowBound=0., upBound=None, cat='Continuous')
x2 = LpVariable('x2', lowBound=0., upBound=None, cat='Continuous')

# The objective function is added to 'prob' first
prob += 1.*x1 +1.*x2, "min x1 + x2"

# Constraints
prob += 1.*x1 + 2.*x2 == 2, "1*x1 + 2*x2 == 2"
prob += 2.*x1 + 3.*x2 == 2, "2*x1 + 3*x2 == 2"
prob += 1.*x1 + 1.*x2 == 1, "1*x1 + 1*x2 == 1"

# Solve
prob.solve()
print("Status:", LpStatus[prob.status])
for v in prob.variables():
    print(v.name, "=", v.varValue)
print("Objective: ", value(prob.objective))

Output:

Status: Infeasible
x1 = 0.0
x2 = 1.0
Objective:  1.0


问:
multiplicating big numbers as arrays C++
I'am doing a program that multiples big numbers stored as strings. How can I store every line of multiplication separately in my code below(like multiplication line 1, multiplication line2), so i can add them up like in simple shool mathematic?</p>

```<code>string findCount(string str1, string str2){
    // Before proceeding further, make sure length
    // of str2 is larger.
    if (str1.length() > str2.length())
        swap(str1, str2);

    // Take an empty string for storing result
    string str = "";
    // Calculate lenght of both string
    int n1 = str1.length(), n2 = str2.length();      //n1 is the smaller one

    // Reverse both of strings
    reverse(str1.begin(), str1.end());
    reverse(str2.begin(), str2.end());

    int carry = 0;
    for(int j =0; j<n1; j++){
        for (int i=0; i<n2; i++){
            int multiply = ((str1[j]-'0')*(str2[i]-'0')+carry);
            str.push_back(multiply%10 + '0');

            carry = multiply/10;
        }
    }
    if(carry)
        str.push_back(carry +'0');

    reverse(str.begin(),str.end());
    return str;

}
</code>```

答:
I have modified your function to get what I think is the expected result:

```<code>string findCount(string str1, string str2)
{
    // Before proceeding further, make sure length
    // of str2 is larger.
    if (str1.length() > str2.length())
        swap(str1, str2);

    // Take an empty string for storing result
    string str = "";
    // Calculate lenght of both string
    int n1 = str1.length(), n2 = str2.length();      //n1 is the smaller one

    // Reverse both of strings
    reverse(str1.begin(), str1.end());
    reverse(str2.begin(), str2.end());

    // Itarate small number
    string total;
    for(int j =0; j<n1; j++){

        // Reset carry
        int carry = 0;
        string aux;
        for (int i = 0;i<j;i++)
            aux.push_back('0');
        for (int i=0; i<n2; i++){
            int multiply = ((str1[j]-'0')*(str2[i]-'0')+carry);
            aux.push_back(multiply%10 + '0');
            carry = multiply/10;
        }
        if(carry)
            aux.push_back(carry +'0');

        // Add to toal
        /// Allocate space for result
        if (total.size() < aux.size())
        {
            for (int i = total.size(); i<aux.size(); i++) total.push_back('0');
        }
        // Add
        for (int i = 0;i<aux.size();i++)
        {
            int add = ((total[i] - '0') + (aux[i] - '0'));
            total[i] = (add%10 + '0');
            if (add/10 > 0)
            {
                if (i >= total.size())
                    total.push_back('0');
                total[i+1] = (((total[i+1] - '0') + (add/10)) + '0');
            }
        }

        // Reverse
        reverse(aux.begin(),aux.end());

        // Append
        string aux2 = total;
        reverse(aux2.begin(),aux2.end());
        str += aux;
        str += ("(" + aux2 +")");
        // New line
        str.push_back('\n');
    }
    reverse(total.begin(),total.end());
    str += total;
    return str;
}
</code>```

Your initial code had the problem that you were only carrying at the end of the whole multiplication, not after each n1 digit.

Body:
I'am doing a program that multiples big numbers stored as strings. How can I store every line of multiplication separately in my code below(like multiplication line 1, multiplication line2), so i can add them up like in simple shool mathematic?

string findCount(string str1, string str2){
    // Before proceeding further, make sure length
    // of str2 is larger.
    if (str1.length() > str2.length())
        swap(str1, str2);

    // Take an empty string for storing result
    string str = "";
    // Calculate lenght of both string
    int n1 = str1.length(), n2 = str2.length();      //n1 is the smaller one

    // Reverse both of strings
    reverse(str1.begin(), str1.end());
    reverse(str2.begin(), str2.end());

    int carry = 0;
    for(int j =0; j<n1; j++){
        for (int i=0; i<n2; i++){
            int multiply = ((str1[j]-'0')*(str2[i]-'0')+carry);
            str.push_back(multiply%10 + '0');

            carry = multiply/10;
        }
    }
    if(carry)
        str.push_back(carry +'0');

    reverse(str.begin(),str.end());
    return str;

}

Body:
I have modified your function to get what I think is the expected result:

string findCount(string str1, string str2)
{
    // Before proceeding further, make sure length
    // of str2 is larger.
    if (str1.length() > str2.length())
        swap(str1, str2);

    // Take an empty string for storing result
    string str = "";
    // Calculate lenght of both string
    int n1 = str1.length(), n2 = str2.length();      //n1 is the smaller one

    // Reverse both of strings
    reverse(str1.begin(), str1.end());
    reverse(str2.begin(), str2.end());

    // Itarate small number
    string total;
    for(int j =0; j<n1; j++){

        // Reset carry
        int carry = 0;
        string aux;
        for (int i = 0;i<j;i++)
            aux.push_back('0');
        for (int i=0; i<n2; i++){
            int multiply = ((str1[j]-'0')*(str2[i]-'0')+carry);
            aux.push_back(multiply%10 + '0');
            carry = multiply/10;
        }
        if(carry)
            aux.push_back(carry +'0');

        // Add to toal
        /// Allocate space for result
        if (total.size() < aux.size())
        {
            for (int i = total.size(); i<aux.size(); i++) total.push_back('0');
        }
        // Add
        for (int i = 0;i<aux.size();i++)
        {
            int add = ((total[i] - '0') + (aux[i] - '0'));
            total[i] = (add%10 + '0');
            if (add/10 > 0)
            {
                if (i >= total.size())
                    total.push_back('0');
                total[i+1] = (((total[i+1] - '0') + (add/10)) + '0');
            }
        }

        // Reverse
        reverse(aux.begin(),aux.end());

        // Append
        string aux2 = total;
        reverse(aux2.begin(),aux2.end());
        str += aux;
        str += ("(" + aux2 +")");
        // New line
        str.push_back('\n');
    }
    reverse(total.begin(),total.end());
    str += total;
    return str;
}

Your initial code had the problem that you were only carrying at the end of the whole multiplication, not after each n1 digit.


问:
DoubleClick use Kotlin programmatically face issue val cannot reassigned
I integrate doubleclick to my android app by follow  link

```<code>val adView = PublisherAdView(this)
adView.adSize = AdSize.BANNER
adView.adUnitId = "/6499/example/banner"
</code>```

But I faced error val cannot be reassigned as below, please help me how to fix it

答:
Share for someone face same problem

After researching, I saw adsize only delegate for getAdSize so I use this code instead

```<code>adView!!.setAdSizes(AdSize.BANNER)
</code>```

Body:
I integrate doubleclick to my android app by follow  link

val adView = PublisherAdView(this)
adView.adSize = AdSize.BANNER
adView.adUnitId = "/6499/example/banner"

But I faced error val cannot be reassigned as below, please help me how to fix it

Body:
Share for someone face same problem

After researching, I saw adsize only delegate for getAdSize so I use this code instead

adView!!.setAdSizes(AdSize.BANNER)