问:
Align TextView leftmost after adding a newline
I'm using SQLite to show buy log from database in my project. I'm appending every row data in StringBuffer and then adding a newline after that. But what I want is that each newline starts from the same position. Like in the picture where the black bar is.

enter image description here

I can't find a way to do this. any help will be appreciated.

Here is my XML code:

```<code><LinearLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="vertical"
    tools:layout_constraintTop_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintBottom_creator="1"
    android:layout_marginStart="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginEnd="8dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="8dp"
    tools:layout_constraintLeft_creator="1"
    android:layout_marginBottom="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:gravity="center">

    <TextView
        android:id="@+id/buyTv"
        android:textSize="15sp"
        android:textColor="#0000FF"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars = "vertical"/>
</LinearLayout>
</code>```

and my java code for this:

```<code>        StringBuffer buffer = new StringBuffer();

        while (cursor.moveToNext()) {

            buffer.append("BuyID: " + cursor.getString(0) + "\n");
            buffer.append("Time: " + cursor.getString(1) + "\n");
            buffer.append("Product Name: " + cursor.getString(2) + "\n");
            buffer.append("Price: " + cursor.getString(3) + "\n");
            buffer.append("Quantity: " + cursor.getString(4) + "\n");
            buffer.append("Total Cost: " + cursor.getString(5) + "\n\n");
        }

        String temp = buffer.toString();

        tv.setText(temp);
        tv.setMovementMethod(new ScrollingMovementMethod());
</code>```

答:
Remove the property of the TextView

```<code>android:gravity="center"
</code>```

or modify it into

```<code>android:gravity="left"
</code>```

in your XML file. This property makes your text align in center.

Body:
I'm using SQLite to show buy log from database in my project. I'm appending every row data in StringBuffer and then adding a newline after that. But what I want is that each newline starts from the same position. Like in the picture where the black bar is.

enter image description here

I can't find a way to do this. any help will be appreciated.

Here is my XML code:

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="vertical"
    tools:layout_constraintTop_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintBottom_creator="1"
    android:layout_marginStart="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginEnd="8dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="8dp"
    tools:layout_constraintLeft_creator="1"
    android:layout_marginBottom="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:gravity="center">

    <TextView
        android:id="@+id/buyTv"
        android:textSize="15sp"
        android:textColor="#0000FF"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars = "vertical"/>
</LinearLayout>

and my java code for this:

        StringBuffer buffer = new StringBuffer();

        while (cursor.moveToNext()) {

            buffer.append("BuyID: " + cursor.getString(0) + "\n");
            buffer.append("Time: " + cursor.getString(1) + "\n");
            buffer.append("Product Name: " + cursor.getString(2) + "\n");
            buffer.append("Price: " + cursor.getString(3) + "\n");
            buffer.append("Quantity: " + cursor.getString(4) + "\n");
            buffer.append("Total Cost: " + cursor.getString(5) + "\n\n");
        }

        String temp = buffer.toString();

        tv.setText(temp);
        tv.setMovementMethod(new ScrollingMovementMethod());

Body:
Remove the property of the TextView

android:gravity="center"

or modify it into

android:gravity="left"

in your XML file. This property makes your text align in center.


来源: stackexchange

问:
WebdriverIO typescript cannot find name $(dollar sign)
I am writing e2e tests using webdriverio and mocha, I am using typescript to code

However, when I compile I get a bunch of error because of the dollar sign $ of browser.execute

example of code:

```<code>injetarTextoPropriedade(seletor) {
    browser.execute(function () {
        $(seletor).each(function () {
            var $this = $(this);
            $this.attr("conteudo", $this.text().trim());
        });
    });
}
</code>```

and then, when I compile, I get the following error:

src/pages/page.ts(42,4): error TS2304: Cannot find name '$'.

Does anyone know how to fix it?

答:
Although OP accepted an answer, I feel other people(like myself) may be looking for another similar issue.

If you the error Cannot find name '$' happens for the webdriverio $ instead of JQuery $, you can work around by declare $ globally.

Add a file and name it global.d.ts and declare const $, $$;

Not pretty though, let me know if you have a better way.

ContentLicense: CC BY-SA 3.0

Body:
I am writing e2e tests using webdriverio and mocha, I am using typescript to code

However, when I compile I get a bunch of error because of the dollar sign $ of browser.execute

example of code:

injetarTextoPropriedade(seletor) {
    browser.execute(function () {
        $(seletor).each(function () {
            var $this = $(this);
            $this.attr("conteudo", $this.text().trim());
        });
    });
}

and then, when I compile, I get the following error:

src/pages/page.ts(42,4): error TS2304: Cannot find name '$'.

Does anyone know how to fix it?


问:
How to initialize a Thread in Kotlin?
In Java it works by accepting an object which implements runnable :

```<code>Thread myThread = new Thread(new myRunnable())
</code>```

where myRunnable is a class implementing Runnable.

But when I tried this in Kotlin, it doesn't seems to work:

```<code>var myThread:Thread = myRunnable:Runnable
</code>```

答:
Please try this code:</p>

```<code>Thread().run { Thread.sleep(3000); }
</code>```

Title: How to initialize a Thread in Kotlin?

Body:
In Java it works by accepting an object which implements runnable :

Thread myThread = new Thread(new myRunnable())

where myRunnable is a class implementing Runnable.

But when I tried this in Kotlin, it doesn't seems to work:

var myThread:Thread = myRunnable:Runnable

Body:
Please try this code:

Thread().run { Thread.sleep(3000); }


问:
Removing strings from another string in java
Lets say I have this list of words:

```<code> String[] stopWords = new String[]{"i","a","and","about","an","are","as","at","be","by","com","for","from","how","in","is","it","not","of","on","or","that","the","this","to","was","what","when","where","who","will","with","the","www"};
</code>```

Than I have text

```<code> String text = "I would like to do a nice novel about nature AND people"
</code>```

Is there method that matches the stopWords and removes them while ignoring case; like this somewhere out there?:

```<code> String noStopWordsText = remove(text, stopWords);
</code>```

Result:

```<code> " would like do nice novel nature people"
</code>```

If you know about regex that wold work great but I would really prefer something like commons solution that is bit more performance oriented.

BTW, right now I'm using this commons method which is lacking proper insensitive case handling:

```<code> private static final String[] stopWords = new String[]{"i", "a", "and", "about", "an", "are", "as", "at", "be", "by", "com", "for", "from", "how", "in", "is", "it", "not", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "the", "www", "I", "A", "AND", "ABOUT", "AN", "ARE", "AS", "AT", "BE", "BY", "COM", "FOR", "FROM", "HOW", "IN", "IS", "IT", "NOT", "OF", "ON", "OR", "THAT", "THE", "THIS", "TO", "WAS", "WHAT", "WHEN", "WHERE", "WHO", "WILL", "WITH", "THE", "WWW"};
 private static final String[] blanksForStopWords = new String[]{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};

 noStopWordsText = StringUtils.replaceEach(text, stopWords, blanksForStopWords);
</code>```

答:
This is a solution that does not use regular expressions. I think it's inferior to my other answer because it is much longer and less clear, but if performance is really, really important then this is O(n) where n is the length of the text.

```<code>Set<String> stopWords = new HashSet<String>();
stopWords.add("a");
stopWords.add("and");
// and so on ...

String sampleText = "I would like to do a nice novel about nature AND people";
StringBuffer clean = new StringBuffer();
int index = 0;

while (index < sampleText.length) {
  // the only word delimiter supported is space, if you want other
  // delimiters you have to do a series of indexOf calls and see which
  // one gives the smallest index, or use regex
  int nextIndex = sampleText.indexOf(" ", index);
  if (nextIndex == -1) {
    nextIndex = sampleText.length - 1;
  }
  String word = sampleText.substring(index, nextIndex);
  if (!stopWords.contains(word.toLowerCase())) {
    clean.append(word);
    if (nextIndex < sampleText.length) {
      // this adds the word delimiter, e.g. the following space
      clean.append(sampleText.substring(nextIndex, nextIndex + 1));
    }
  }
  index = nextIndex + 1;
}

System.out.println("Stop words removed: " + clean.toString());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Lets say I have this list of words:

 String[] stopWords = new String[]{"i","a","and","about","an","are","as","at","be","by","com","for","from","how","in","is","it","not","of","on","or","that","the","this","to","was","what","when","where","who","will","with","the","www"};

Than I have text

 String text = "I would like to do a nice novel about nature AND people"

Is there method that matches the stopWords and removes them while ignoring case; like this somewhere out there?:

 String noStopWordsText = remove(text, stopWords);

Result:

 " would like do nice novel nature people"

If you know about regex that wold work great but I would really prefer something like commons solution that is bit more performance oriented.

BTW, right now I'm using this commons method which is lacking proper insensitive case handling:

 private static final String[] stopWords = new String[]{"i", "a", "and", "about", "an", "are", "as", "at", "be", "by", "com", "for", "from", "how", "in", "is", "it", "not", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "the", "www", "I", "A", "AND", "ABOUT", "AN", "ARE", "AS", "AT", "BE", "BY", "COM", "FOR", "FROM", "HOW", "IN", "IS", "IT", "NOT", "OF", "ON", "OR", "THAT", "THE", "THIS", "TO", "WAS", "WHAT", "WHEN", "WHERE", "WHO", "WILL", "WITH", "THE", "WWW"};
 private static final String[] blanksForStopWords = new String[]{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};

 noStopWordsText = StringUtils.replaceEach(text, stopWords, blanksForStopWords);

Body:
This is a solution that does not use regular expressions. I think it's inferior to my other answer because it is much longer and less clear, but if performance is really, really important then this is O(n) where n is the length of the text.

Set<String> stopWords = new HashSet<String>();
stopWords.add("a");
stopWords.add("and");
// and so on ...

String sampleText = "I would like to do a nice novel about nature AND people";
StringBuffer clean = new StringBuffer();
int index = 0;

while (index < sampleText.length) {
  // the only word delimiter supported is space, if you want other
  // delimiters you have to do a series of indexOf calls and see which
  // one gives the smallest index, or use regex
  int nextIndex = sampleText.indexOf(" ", index);
  if (nextIndex == -1) {
    nextIndex = sampleText.length - 1;
  }
  String word = sampleText.substring(index, nextIndex);
  if (!stopWords.contains(word.toLowerCase())) {
    clean.append(word);
    if (nextIndex < sampleText.length) {
      // this adds the word delimiter, e.g. the following space
      clean.append(sampleText.substring(nextIndex, nextIndex + 1));
    }
  }
  index = nextIndex + 1;
}

System.out.println("Stop words removed: " + clean.toString());


问:
What is happening when calling an enum/enum class with parentheses in C++?
This is maybe a bit weird question, but I really don't know how to phrase it better than this.

I just discovered that I can do the following:

```<code>#include <iostream>

enum class Colour  // also works with plain old enum
{
    Red = 1,
    Green,
    Blue,
    Yellow,
    Black,
    White
};

int main()
{
    Colour c = Colour(15);  // this is the line I don't quite understand

    std::cout << static_cast<int>(c) << std::endl;  // this returns 15

    return 0;
}
</code>```

So now I have integer value 15 in a variable of the type Colour.

What exactly is happening here? Is that some kind of enum "constructor" at work? As far as I know, integer value 15 is not put into enumeration, it is stored just in variable c. Why would something like that be useful, in the first place - to create a value that doesn't exist in enum?

答:
Colour(15) is an expression that creates a temporary (prvalue) instance of the Colour enum, initialized with the value 15.

Colour c = Colour(15); initializes a new variable c of type Colour from the previously-explained expression. It is equivalent to Colour c(15).

Body:
This is maybe a bit weird question, but I really don't know how to phrase it better than this.

I just discovered that I can do the following:

#include <iostream>

enum class Colour  // also works with plain old enum
{
    Red = 1,
    Green,
    Blue,
    Yellow,
    Black,
    White
};

int main()
{
    Colour c = Colour(15);  // this is the line I don't quite understand

    std::cout << static_cast<int>(c) << std::endl;  // this returns 15

    return 0;
}

So now I have integer value 15 in a variable of the type Colour.

What exactly is happening here? Is that some kind of enum "constructor" at work? As far as I know, integer value 15 is not put into enumeration, it is stored just in variable c. Why would something like that be useful, in the first place - to create a value that doesn't exist in enum?


答:
Change the gravity of your textview to start or left like this:

```<code><TextView
    android:width="wrap_content"
    android:width="wrap_content"
    android:layout_gravity="center_horizontal"
    android:id="@+id/buyTv"
    android:textSize="15sp"
    android:textColor="#0000FF"
    android:gravity="left"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars = "vertical"/>
</code>```

Title: Align TextView leftmost after adding a newline

Body:
Change the gravity of your textview to start or left like this:

<TextView
    android:width="wrap_content"
    android:width="wrap_content"
    android:layout_gravity="center_horizontal"
    android:id="@+id/buyTv"
    android:textSize="15sp"
    android:textColor="#0000FF"
    android:gravity="left"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars = "vertical"/>


问:
How to query edge from graph in networkx 2.0 "by name"
I have a directed multi graph. With networkx 2.0 I found that the edges are returned as tuple made of (start_node, end_node, integer), where the integer is generated to distinguish multiple edges between same nodes.

With networks 1.x I could get an edge using:

```<code>edge = G.edge[start_node][end_node]
</code>```

With v2.0 this doesn't work anymore, because "edges" isn't a nested dict anymore. A change to:

```<code>edge = G.edges(start_node, end_node)
</code>```

doesn't work "{ValueError}too many values to unpack (expected 3)", because it misses the integer to identify the single edge within the multi edge. Whether or not multiple edges exist between nodes isn't fixed, same for the number of multi edges.

Does that mean I always have to iterate over edges?

答:
According to the networkx 1.x -> 2.0 migration guide:

Replace any use of G.edge with G.adj. The Graph attribute edge has been removed. The attribute G.adj is G.edge in v1 and will work with both versions.

This migration guide is a fairly quick read, and to my experience is a pretty comprehensive guide to all the things that break going from 1.x to 2.0.

Body:
I have a directed multi graph. With networkx 2.0 I found that the edges are returned as tuple made of (start_node, end_node, integer), where the integer is generated to distinguish multiple edges between same nodes.

With networks 1.x I could get an edge using:

edge = G.edge[start_node][end_node]

With v2.0 this doesn't work anymore, because "edges" isn't a nested dict anymore. A change to:

edge = G.edges(start_node, end_node)

doesn't work "{ValueError}too many values to unpack (expected 3)", because it misses the integer to identify the single edge within the multi edge. Whether or not multiple edges exist between nodes isn't fixed, same for the number of multi edges.

Does that mean I always have to iterate over edges?


问:
Why doing someVar in someArray in an If always give false value
I was just working on something in AngularJS. I noticed that by using the attached style of if condition, I always get a false result. Why so? Am I missing something? I tried to google it but didn't find anything.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(testExt in allowedExtensions){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
  Is Extension Allowed : {{isAllowed}}
</div>
</body>
</html></code>```

I am from .NET background so we use LINQ in that kinda same like that. Is this type of syntax not supported in JS?

EDIT
I know about index of and other ways to find if it is in the array. But I was confused why in operator is not working.

Thank you for your time and help.

答:
As pointy called out, your syntax is simply incorrect. There are two main ways you can do this in JS.

Array.indexOf docs

```<code>var allowedExtensions = [".jpg",".pdf", ".png"];
var testExt = ".jpg";

if (allowedExtensions.indexOf(testExt) > 0){
  $scope.isAllowed = true;
} else {
  $scope.isAllowed = false;
}
</code>```

Array.includes docs

```<code>var allowedExtensions = [".jpg",".pdf", ".png"];
var testExt = ".jpg";

if (allowedExtensions.includes(testExt)){
  $scope.isAllowed = true;
} else {
  $scope.isAllowed = false;
}
</code>```

You'll get better browser support with indexOf, but includes is a newer/cleaner solution.

Side-note, I always find in interesting in programming when someone says "if a is true then b is true, if a is false b is false". Rather than have redundant conditional blocks you could just directly assign the expression, since both expressions (indexOf & includes) return the type Boolean.
e.g.

```<code>$scope.isAllowed = allowedExtensions.includes(testExt);
</code>```

Body:
I was just working on something in AngularJS. I noticed that by using the attached style of if condition, I always get a false result. Why so? Am I missing something? I tried to google it but didn't find anything.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(testExt in allowedExtensions){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}

  Is Extension Allowed : {{isAllowed}}

I am from .NET background so we use LINQ in that kinda same like that. Is this type of syntax not supported in JS?

EDIT
I know about index of and other ways to find if it is in the array. But I was confused why in operator is not working.

Thank you for your time and help.

Body:
As pointy called out, your syntax is simply incorrect. There are two main ways you can do this in JS.

Array.indexOf docs

var allowedExtensions = [".jpg",".pdf", ".png"];
var testExt = ".jpg";

if (allowedExtensions.indexOf(testExt) > 0){
  $scope.isAllowed = true;
} else {
  $scope.isAllowed = false;
}

Array.includes docs

var allowedExtensions = [".jpg",".pdf", ".png"];
var testExt = ".jpg";

if (allowedExtensions.includes(testExt)){
  $scope.isAllowed = true;
} else {
  $scope.isAllowed = false;
}

You'll get better browser support with indexOf, but includes is a newer/cleaner solution.

Side-note, I always find in interesting in programming when someone says "if a is true then b is true, if a is false b is false". Rather than have redundant conditional blocks you could just directly assign the expression, since both expressions (indexOf & includes) return the type Boolean.
e.g.

$scope.isAllowed = allowedExtensions.includes(testExt);


问:
Create a large file with a given size with a pattern in Linux
In Linux how can I create a large file with a given text or hex pattern (Like DEADBEEFDEADBEEFDEADBEEF ....)

I know dd can be used to create large files but it doesn't write desired text or hex pattern

```<code>dd if=/dev/urandom of=/tmp/bigfile bs=blocksize count=size
</code>```

or

```<code>dd if=/dev/zero of=/tmp/bigfile bs=blocksize count=size
</code>```

Quickly create a large file on a Linux system?

How to create a file with a given size in Linux?

答:
If your intention is to achieve a scrambled data and not random.

```<code>shuf folder/* | dd of=target.txt bs=1K count=2048
</code>```

to get a 2MB sample file which you can then shorten or invoke the command above again with different numbers for count

```<code>folder/* will contain files with your patterns
</code>```

Or as an alternative you can have your hexadecimal values stored in a single file in separate lines and use shuf to shuffle them based on your need and fill them

```<code>shuf -n 100 source.txt | dd of=target.txt bs=1K count=2048
</code>```

Or you can just dump it in dd as

```<code>dd if=source.txt of=target.txt bs=1K count=2048
</code>```

Shuffle Documentation

Body:
In Linux how can I create a large file with a given text or hex pattern (Like DEADBEEFDEADBEEFDEADBEEF ....)

I know dd can be used to create large files but it doesn't write desired text or hex pattern

dd if=/dev/urandom of=/tmp/bigfile bs=blocksize count=size

or

dd if=/dev/zero of=/tmp/bigfile bs=blocksize count=size

Quickly create a large file on a Linux system?

How to create a file with a given size in Linux?

Body:
If your intention is to achieve a scrambled data and not random.

shuf folder/* | dd of=target.txt bs=1K count=2048

to get a 2MB sample file which you can then shorten or invoke the command above again with different numbers for count

folder/* will contain files with your patterns

Or as an alternative you can have your hexadecimal values stored in a single file in separate lines and use shuf to shuffle them based on your need and fill them

shuf -n 100 source.txt | dd of=target.txt bs=1K count=2048

Or you can just dump it in dd as

dd if=source.txt of=target.txt bs=1K count=2048

Shuffle Documentation


问:
Need to show parallel all cells of a row in a table

I am trying to have a table that has some  in it and and in this table I have labels that gets data from database and they change in length each time the data bind to it is different the problem is the alignment of these labels in the '' changes too here is a example of what I have.

      Full Name:

   <asp:Label ID="lblFullName" runat="server" Text=""></asp:Label>    Address:
      <asp:Label ID="lblTuition" runat="server" Text=""></asp:Label>

```

This is how it looks spacing in between I am using  to give spacing in between them and now when lets say the FullName have a value that's a big value the Address: gets pushed away further is there a way I could have any value but the spacing for these 2 don't change and I don't want to use the float-right for address I want these to be kind of in the middle of the table

Expected result could be some thing like this:

Any help?

答:
You can accomplish that by breaking your name and address headers up into two separate cells. That will allow you to specify how far apart you want the cells to be, regardless of the length of the data being imported:

td {
  width: 10%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td class="auto-style4">
      </asp:Label>Full Name:
      <asp:Label ID="lblFullName" runat="server" Text="">
    </td>
    <td class="auto-style4">
      </asp:Label>Address:
      <asp:Label ID="lblTuition" runat="server" Text=""></asp:Label>
    </td>
  </tr>
</table></code>```

Body:
I am trying to have a table that has some  in it and and in this table I have labels that gets data from database and they change in length each time the data bind to it is different the problem is the alignment of these labels in the '' changes too here is a example of what I have.

      Full Name:

   <asp:Label ID="lblFullName" runat="server" Text=""></asp:Label>    Address:
      <asp:Label ID="lblTuition" runat="server" Text=""></asp:Label>

This is how it looks spacing in between I am using  to give spacing in between them and now when lets say the FullName have a value that's a big value the Address: gets pushed away further is there a way I could have any value but the spacing for these 2 don't change and I don't want to use the float-right for address I want these to be kind of in the middle of the table

Expected result could be some thing like this:

Any help?

Body:
You can accomplish that by breaking your name and address headers up into two separate cells. That will allow you to specify how far apart you want the cells to be, regardless of the length of the data being imported:

td {
  width: 10%;
}

<table>
  <tr>
    <td class="auto-style4">
      </asp:Label>Full Name:
      <asp:Label ID="lblFullName" runat="server" Text="">
    </td>
    <td class="auto-style4">
      </asp:Label>Address:
      <asp:Label ID="lblTuition" runat="server" Text=""></asp:Label>
    </td>
  </tr>
</table>


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
If you're really interested in the topic, let me first recommend David Gries' "The Science of Programming", a classic introductory work on the topic.

It actually is possible to prove programs correct to some extent.  You can write preconditions and postconditions and then prove that given a state that meets the preconditions, the resulting state after execution will meet the postconditions.

Where it gets tricky, however, is loops.  For these, you additionally need to find a loop invariant and to show correct termination you need to find an upper bound function on the maximum possible number of iterations remaining after each loop.  You also have to be able to show that this decreases by at least one after each iteration through the loop.

Once you have all this for a program, the proof is mechanical.  But unfortunately, there's no way to automatically derive the invariant and bound functions for loops.  Human intuition suffices for trivial cases with small loops, but realistically, complex programs quickly become intractable.

Title: Why can't programs be proven?

OwnerDisplayName: Boojum

LastEditorDisplayName: Boojum


问:
if char equals a letter then execute a code
Please help I cannot run this block of code:</p>

```<code>import java.util.Scanner;

public class Methods_in_java {

    public static void main(String[] args) {
        boolean gameover = true;
        int score = 5000;
        int Levelcomplete = 5;
        int bonus = 100;
        boolean prize = true;
        System.out.println("Please enter your name");
        Scanner lic = new Scanner(System.in);
        String ab = lic.nextLine();
        char fir = Character.toUpperCase(ab.charAt(1));
        if(fir == 'A'){
                prize = true;
        }
        Calculatescore(gameover,score,Levelcomplete,bonus,prize);
    }
    public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
        if(gameover){
            int finalscore = score + (levelcomplete * bonus);
            if (prize){
                finalscore += 1000;
            }
            System.out.println("Your final score is "+ finalscore);
        }
    }
}
</code>```

答:
You have initialized your prize variable as true that will remain always true even its meet if condition or not just change it to false.

and as you were accessing the String's 2nd character using charAt(1), the index starts from 0 and if you try using charAt(0) then you will access 1st character.

Just change your code to:

```<code>public class cn {

    public static void main(String[] args) {
        boolean gameover = true;
        int score = 5000;
        int Levelcomplete = 5;
        int bonus = 100;
        boolean prize=false;
        System.out.println("Please enter your name");
        Scanner lic = new Scanner(System.in);
        String ab = lic.nextLine();
        char fir = Character.toUpperCase(ab.charAt(0));
        if(fir == 'A'){
                prize = true;
        }
        Calculatescore(gameover,score,Levelcomplete,bonus,prize);
    }
    public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
        if(gameover){
            int finalscore = score + (levelcomplete * bonus);
            if (prize){
                finalscore += 1000;
            }
            System.out.println("Your final score is "+ finalscore);
        }
    }
}
</code>```

Body:
Please help I cannot run this block of code:

import java.util.Scanner;

public class Methods_in_java {

    public static void main(String[] args) {
        boolean gameover = true;
        int score = 5000;
        int Levelcomplete = 5;
        int bonus = 100;
        boolean prize = true;
        System.out.println("Please enter your name");
        Scanner lic = new Scanner(System.in);
        String ab = lic.nextLine();
        char fir = Character.toUpperCase(ab.charAt(1));
        if(fir == 'A'){
                prize = true;
        }
        Calculatescore(gameover,score,Levelcomplete,bonus,prize);
    }
    public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
        if(gameover){
            int finalscore = score + (levelcomplete * bonus);
            if (prize){
                finalscore += 1000;
            }
            System.out.println("Your final score is "+ finalscore);
        }
    }
}

Body:
You have initialized your prize variable as true that will remain always true even its meet if condition or not just change it to false.

and as you were accessing the String's 2nd character using charAt(1), the index starts from 0 and if you try using charAt(0) then you will access 1st character.

Just change your code to:

public class cn {

    public static void main(String[] args) {
        boolean gameover = true;
        int score = 5000;
        int Levelcomplete = 5;
        int bonus = 100;
        boolean prize=false;
        System.out.println("Please enter your name");
        Scanner lic = new Scanner(System.in);
        String ab = lic.nextLine();
        char fir = Character.toUpperCase(ab.charAt(0));
        if(fir == 'A'){
                prize = true;
        }
        Calculatescore(gameover,score,Levelcomplete,bonus,prize);
    }
    public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
        if(gameover){
            int finalscore = score + (levelcomplete * bonus);
            if (prize){
                finalscore += 1000;
            }
            System.out.println("Your final score is "+ finalscore);
        }
    }
}


问:
Weak property in a Swift protocol may only be a class or class-bound protocol type
I would like to define a protocol which is used in a Viper architecture to establish a connection between a Viper components using a protocol with a weak property but I get the following error message:

'weak' may only be applied to class and class-bound protocol types,
  not 'Self.ViperViewClass'

```<code>protocol ViperPresenter: class {

    associatedtype ViperViewClass
    weak var view: ViperViewClass! { get set }

}
</code>```

答:
Protocols can't currently require properties to be implemented as weak stored properties.

Although the weak and unowned keywords are currently allowed on property requirements, they have no effect. The following is perfectly legal:

```<code>class C {}

protocol P {
  weak var c: C? { get set }
}

struct S : P {
  var c: C? // strong reference to a C instance, not weak.
}
</code>```

This was filed as a bug, and SE-0186 will make the use of weak and unowned on property requirements in a protocol a warning in Swift 4.1 (in both Swift 3 and 4 modes), and an error in Swift 5.

But even if protocols could require properties to be implemented as weak or unowned stored properties, the compiler would need to know that ViperViewClass is a class type (i.e by saying
 associatedtype ViperViewClass : AnyObject).

Body:
I would like to define a protocol which is used in a Viper architecture to establish a connection between a Viper components using a protocol with a weak property but I get the following error message:

'weak' may only be applied to class and class-bound protocol types,
  not 'Self.ViperViewClass'

protocol ViperPresenter: class {

    associatedtype ViperViewClass
    weak var view: ViperViewClass! { get set }

}

Body:
Protocols can't currently require properties to be implemented as weak stored properties.

Although the weak and unowned keywords are currently allowed on property requirements, they have no effect. The following is perfectly legal:

class C {}

protocol P {
  weak var c: C? { get set }
}

struct S : P {
  var c: C? // strong reference to a C instance, not weak.
}

This was filed as a bug, and SE-0186 will make the use of weak and unowned on property requirements in a protocol a warning in Swift 4.1 (in both Swift 3 and 4 modes), and an error in Swift 5.

But even if protocols could require properties to be implemented as weak or unowned stored properties, the compiler would need to know that ViperViewClass is a class type (i.e by saying
 associatedtype ViperViewClass : AnyObject).


问:
WPF: set ListBoxItem select event in code
Okey, in code (C#) I create some ListBoxItems and add them to a UniformGird that gets put in a Viewbox defined in XAML (and for practical reasons I can't define a ListBox on XAML).

When a ListBoxItem is Selected I need to fire an event that calls a method I have made.

In XAML I would just set an EventSetter that calls the method, but I'm not sure how I can do the same thing in C# code for ListBoxItem.

答:
Hook up an event handler for the Selected or PreviewMouseLeftButtonDown event:

```<code>ListBoxItem lbi = new ListBoxItem();
lbi.PreviewMouseLeftButtonDown += (se, ee) => { MessageBox.Show("do something..."); };
</code>```

Body:
Hook up an event handler for the Selected or PreviewMouseLeftButtonDown event:

ListBoxItem lbi = new ListBoxItem();
lbi.PreviewMouseLeftButtonDown += (se, ee) => { MessageBox.Show("do something..."); };


问:
Dropdown-menu width changes when other
 is added by jQuery
CODE :

```<code><head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script
    src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"
    integrity="sha256-eEa1kEtgK9ZL6h60VXwDsJ2rxYCwfxi40VZ9E0XwoEA="
    crossorigin="anonymous"></script>
</head>
<body>

<div class="dropdown bigdiv">
  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
    <span class="caret"></span></button>
  <ul class="dropdown-menu bigul">
    <li>
        <a href="#" id="open_input">open_input</a>
    </li>

    <ul class="list-group test">
    </ul>
  </ul>
</div>

</body>
<script>
    $(document).ready(function () {
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "Fortran",
        ];

        var ul_text = '    <li class="ui-widget">\n' +
            '<form role="form" style="">\n' +
            '                <div class="input-group input-group-sm" style="">\n' +
            '                  <input type="text" class="form-control" id="tags" placeholder="Enter email">\n' +
            '                </div>\n' +
            '              </form>\n' +
            '    </li>'

        $('#open_input').click(function (e) {
            $('.bigul').append(ul_text)
            $('#tags').autocomplete({
                    search: function(event, ui) {
                        $('.test').empty();
                    },
                    source: availableTags,
                    messages: {
                        noResults: '',
                        results: function() {}
                    }
                }).data('autocomplete')._renderItem = function(ul, item) {
                    return $('<li class="list-group-item"></li>')
                        .data('item.autocomplete', item)
                        .append(item.value)
                        .appendTo($('.test'));
                    };
            e.stopPropagation();
        });
    });
</script>
</code>```

jsfiddle : http://jsfiddle.net/uMqyn/919/

On that code, when I click #open_input, ul.dropdown-menu.bigul's width changes from 160px to 182px. As you can see on , If I click #open_input some
 is added.

Even I gave style="100%" to all elements of var ul_text, it does not works.

Question:

First Question : How can I make width will be the same as initial status? I want it to have the same width - 160px. It's main question.

Second Question : If it is possible, I want to follow width of <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example button. In other words, if width of button is 20px, dropdown-menu and other following
's width will be 20px width also.
But first question is most important to me. Second question is not as important as first one.

答:
The simple solution, modify this line in your javascript:

```<code><input type="text" class="form-control" id="tags" placeholder="Enter email">
</code>```

to

```<code><input type="text" class="form-control" id="tags" placeholder="Enter email" style="width:158px;">
</code>```

You can view it here: http://jsfiddle.net/6ybd6656/

Title: Dropdown-menu width changes when other <li> is added by jQuery

Body:
CODE :

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
    </button>

        open_input

jsfiddle : http://jsfiddle.net/uMqyn/919/

On that code, when I click #open_input, ul.dropdown-menu.bigul's width changes from 160px to 182px. As you can see on , If I click #open_input some
 is added.

Even I gave style="100%" to all elements of var ul_text, it does not works.

Question:

First Question : How can I make width will be the same as initial status? I want it to have the same width - 160px. It's main question.

Second Question : If it is possible, I want to follow width of <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example button. In other words, if width of button is 20px, dropdown-menu and other following
's width will be 20px width also.
But first question is most important to me. Second question is not as important as first one.

Body:
The simple solution, modify this line in your javascript:

<input type="text" class="form-control" id="tags" placeholder="Enter email">

to

<input type="text" class="form-control" id="tags" placeholder="Enter email" style="width:158px;">

You can view it here: http://jsfiddle.net/6ybd6656/


问:
TomcatEmbeddedServletContainerFactory is missing in Spring Boot 2
I have Spring Boot application version 1.5.x, which uses org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory, I'm trying to migrate it to Spring Boot 2, but the app does not compile, although a have a dependency to org.springframework.boot:spring-boot-starter-tomcat. The compiler issues the error below:

```<code>error: package org.springframework.boot.context.embedded.tomcat
</code>```

答:
The class has been removed and replaced by org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
For more info check: Spring-Boot-2.0-Migration-Guide, which says:

In order to support reactive use cases, the embedded containers
  package structure has been refactored quite extensively.
  EmbeddedServletContainer has been renamed to WebServer and the
  org.springframework.boot.context.embedded package has been relocated
  to org.springframework.boot.web.server. Correspondingly,
  EmbeddedServletContainerCustomizer has been renamed to
  WebServerFactoryCustomizer.

For example, if you were customizing the embedded Tomcat container
  using the TomcatEmbeddedServletContainerFactory callback interface,
  you should now use TomcatServletWebServerFactory and if you were using
  an EmbeddedServletContainerCustomizer bean, you should now use a
  WebServerFactoryCustomizer bean.

I had the problem that I needed to sent bigger request, then the default size allowed:

```<code>@Bean
    public TomcatServletWebServerFactory containerFactory() {
        return new TomcatServletWebServerFactory() {
            protected void customizeConnector(Connector connector) {
                int maxSize = 50000000;
                super.customizeConnector(connector);
                connector.setMaxPostSize(maxSize);
                connector.setMaxSavePostSize(maxSize);
                if (connector.getProtocolHandler() instanceof AbstractHttp11Protocol) {

                    ((AbstractHttp11Protocol <?>) connector.getProtocolHandler()).setMaxSwallowSize(maxSize);
                    logger.info("Set MaxSwallowSize "+ maxSize);
                }
            }
        };

    }
</code>```

Body:
I have Spring Boot application version 1.5.x, which uses org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory, I'm trying to migrate it to Spring Boot 2, but the app does not compile, although a have a dependency to org.springframework.boot:spring-boot-starter-tomcat. The compiler issues the error below:

error: package org.springframework.boot.context.embedded.tomcat

Body:
The class has been removed and replaced by org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
For more info check: Spring-Boot-2.0-Migration-Guide, which says:

In order to support reactive use cases, the embedded containers
  package structure has been refactored quite extensively.
  EmbeddedServletContainer has been renamed to WebServer and the
  org.springframework.boot.context.embedded package has been relocated
  to org.springframework.boot.web.server. Correspondingly,
  EmbeddedServletContainerCustomizer has been renamed to
  WebServerFactoryCustomizer.

For example, if you were customizing the embedded Tomcat container
  using the TomcatEmbeddedServletContainerFactory callback interface,
  you should now use TomcatServletWebServerFactory and if you were using
  an EmbeddedServletContainerCustomizer bean, you should now use a
  WebServerFactoryCustomizer bean.

I had the problem that I needed to sent bigger request, then the default size allowed:

@Bean
    public TomcatServletWebServerFactory containerFactory() {
        return new TomcatServletWebServerFactory() {
            protected void customizeConnector(Connector connector) {
                int maxSize = 50000000;
                super.customizeConnector(connector);
                connector.setMaxPostSize(maxSize);
                connector.setMaxSavePostSize(maxSize);
                if (connector.getProtocolHandler() instanceof AbstractHttp11Protocol) {

                    ((AbstractHttp11Protocol <?>) connector.getProtocolHandler()).setMaxSwallowSize(maxSize);
                    logger.info("Set MaxSwallowSize "+ maxSize);
                }
            }
        };

    }

ContentLicense: CC BY-SA 4.0


问:
Facebook Webhook The URL couldn't be validated. Response does not match challenge
I'm setting up comment moderation tool on a client's website, and in order to do that I need to create an app through facebook developer tools and create a webhook in order to be able to moderate comments.

When I try to set up the webhook, this is the error I receive.

The URL couldn't be validated. Response does not match challenge, expected value="716205142", received=""

And here's the code within the fbwebhook.php file:

```<code><?php
    $challenge = $_GET['hub_challenge'];
    $verify_token = $_GET['hub_verify_token'];
    if ($verify_token === 'TpQQFSkEJZbVlXZzCfEx') {
        echo $challenge;
    }

    file_put_contents(
       'log.txt',
       "\n" . file_get_contents('php://input'),
       FILE_APPEND
    );
</code>```

What is really driving me crazy is that this same file works on the staging site, works on other servers, but not on the server where the live site is being hosted.

We are on WPengine,

```<code>createwhimsy.staging.wpengine.com == webhook works

createwhimsy.com == webhook doesn't work (error above)
</code>```

Tried on a digital ocean server == webhook works.

Tried on a different site being hosted on WPengine == webhook doesn't work (same error as above)

If I move the file I get a 404 error, so I know that FB is hitting the file, but it seems like FB isn't sending the right data to be used to verify, or something, not sure. This leads me to believe it's a DNS issue, or something with WPengine's hosting environment.

Any direction or input is much appreciated!

答:
Discovered what is is.

WPengine has a redirect bot in place that will totally mess with facebooks validation post to your site. Just have to request them to disable the bot, and it worked just fine!

Body:
I'm setting up comment moderation tool on a client's website, and in order to do that I need to create an app through facebook developer tools and create a webhook in order to be able to moderate comments.

When I try to set up the webhook, this is the error I receive.

The URL couldn't be validated. Response does not match challenge, expected value="716205142", received=""

And here's the code within the fbwebhook.php file:

<?php
    $challenge = $_GET['hub_challenge'];
    $verify_token = $_GET['hub_verify_token'];
    if ($verify_token === 'TpQQFSkEJZbVlXZzCfEx') {
        echo $challenge;
    }

    file_put_contents(
       'log.txt',
       "\n" . file_get_contents('php://input'),
       FILE_APPEND
    );

What is really driving me crazy is that this same file works on the staging site, works on other servers, but not on the server where the live site is being hosted.

We are on WPengine,

createwhimsy.staging.wpengine.com == webhook works

createwhimsy.com == webhook doesn't work (error above)

Tried on a digital ocean server == webhook works.

Tried on a different site being hosted on WPengine == webhook doesn't work (same error as above)

If I move the file I get a 404 error, so I know that FB is hitting the file, but it seems like FB isn't sending the right data to be used to verify, or something, not sure. This leads me to believe it's a DNS issue, or something with WPengine's hosting environment.

Any direction or input is much appreciated!


问:
PHP - How to re-encode a URI
I think I have the need to take a uri which has been decoded in PHP, and re-encode it.

Here is the situation:

JavaScript passes encoded uri as query string parameter to php script.

PHP script embeds uri as a hidden input value in an html document, responds with the document to a user agent.

JavaScript reads embedded uri and sets location of current document based on value of hidden input.

On Step 2, I am finding that the Uri is fully decoded after reading it in via $_GET.  So when I embed the uri in the hidden input, it becomes un-encoded.  So I would like to run a PHP script which re-encodes the Uri properly ex:

```<code>http://my.example.com/dog walk?is=very great

==>

http://my.example.com/dog%20walk?is=very%20great
</code>```

Is there a pre-built php function for this or should I just write my own?

PLEASE NOTE: urlencode and urldecode are not the answer to get the desired input/output I have in the example above.

Thanks,
Macy

答: Are you looking for : http://fr.php.net/manual/en/function.urlencode.php ?</p>

Title: PHP - How to re-encode a URI

Body:
I think I have the need to take a uri which has been decoded in PHP, and re-encode it.

Here is the situation:

JavaScript passes encoded uri as query string parameter to php script.

PHP script embeds uri as a hidden input value in an html document, responds with the document to a user agent.

JavaScript reads embedded uri and sets location of current document based on value of hidden input.

On Step 2, I am finding that the Uri is fully decoded after reading it in via $_GET.  So when I embed the uri in the hidden input, it becomes un-encoded.  So I would like to run a PHP script which re-encodes the Uri properly ex:

http://my.example.com/dog walk?is=very great

==>

http://my.example.com/dog%20walk?is=very%20great

Is there a pre-built php function for this or should I just write my own?

PLEASE NOTE: urlencode and urldecode are not the answer to get the desired input/output I have in the example above.

Thanks,
Macy


问:
Is PowerBI available with SQL Server 2016(Standard OR Enterprise) edition
Please help me in understand that,

Is PowerBI part of SQL Server 2016(Standard OR Enterprise) edition or PowerBI is separate setup that needs to installed for reports?

Best Regards,
Arayn

答:
This depends on clarification of your question but to summarise the full "suite" if you will..

Power BI itself is a cloud platform as a service.

FREE - You can create Power BI reports & datasets using Power BI Desktop & these can be deployed to the Power BI Service.

There are then 2 paid models. (Pricing)

Per User per Month fee of $9.99

Power BI Premium (This can be obtained 3 ways)

Based on capacity

Part of the SQL Server Enterprise + Software Assurance

Part of an Office 365 Subscription.

Here's a good summary of purchasing Power BI Premium from @Guyinacube

With Power BI Premium you can install the Power BI Report Server

This is a separate installer from SQL Server as is Reporting Services (2016 & 2017).

It behaves and looks very similar to Reporting Services but is a separate install/interface & database

Here is a great reference page for ALL things Power BI


问:
React-Redux-Thunk: actions does not return dispatch
I am using React Native with Redux-thunk middleware.
My problem is dispatch function does not return the object and does not even console.

Here is my actions file:

```<code>function movieSelc(movie) {
    return {
            type: types.MOVIE_SELECT,
            selectedMovie: movie
        };
}

export function selectMovie(m) {
    console.log("this console works!")
  return (dispatch) => {
    console.log("this console never works")
    dispatch(movieSelc(m));
  };
}
</code>```

This is the component(i am not including here const styles to make it a bit  shorter):

```<code>import React, { Component } from 'react';
import { Text, View, TouchableOpacity, Image, } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import * as actions from './../actions';

class ListItem extends Component {
    render() {
        const { movie } = this.props;
        return (

            <View>
                    {
                      movie && movie.map((item, index) =>
                        <View key={index} style={styles.containerStyle}>
                             <Image
                                 source={{ uri: `https://image.tmdb.org/t/p/w342${item.backdrop_path}` }}
                                 style={styles.imgStyle}
                             />

                            <TouchableOpacity
                                 style={{ backgroundColor: 'gray' }}
                                 onPress={() => { actions.selectMovie(item); }}
                            >
                                  <Text style={styles.headStyle}>{item.title}</Text>
                                  <Text>{item.overview}</Text>
                                  <Text style={styles.rateStyle}>
                                    Release Day:{item.release_date}
                                  </Text>
                                  <Text style={styles.rateStyle}>Rating: {item.vote_average}</Text>
                            </TouchableOpacity>
                        </View>)
                    }
            </View>

        );
    }
}
ListItem.propTypes = {
    actions: PropTypes.object.isRequired,
    movies: PropTypes.object.isRequired,
};

function mapStateToProps(state) {
    const { movies } = state;
    return {
        movies,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actions, dispatch)
    };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(ListItem);
</code>```

Please let me know if I need to provide more information. Thank you!

答:
You are calling selectMovie action instead of dispatching it. With the bindActionToProps method, react-redux provide you a way to dispatch actions via props, so the correct code should be:</p>

```<code><TouchableOpacity
style={{ backgroundColor: 'gray' }}
onPress={() => { this.props.actions.selectMovie(item)); }}>
</code>```

Body:
I am using React Native with Redux-thunk middleware.
My problem is dispatch function does not return the object and does not even console.

Here is my actions file:

function movieSelc(movie) {
    return {
            type: types.MOVIE_SELECT,
            selectedMovie: movie
        };
}

export function selectMovie(m) {
    console.log("this console works!")
  return (dispatch) => {
    console.log("this console never works")
    dispatch(movieSelc(m));
  };
}

This is the component(i am not including here const styles to make it a bit  shorter):

import React, { Component } from 'react';
import { Text, View, TouchableOpacity, Image, } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import * as actions from './../actions';

class ListItem extends Component {
    render() {
        const { movie } = this.props;
        return (

            <View>
                    {
                      movie && movie.map((item, index) =>
                        <View key={index} style={styles.containerStyle}>
                             <Image
                                 source={{ uri: `https://image.tmdb.org/t/p/w342${item.backdrop_path}` }}
                                 style={styles.imgStyle}
                             />

                            <TouchableOpacity
                                 style={{ backgroundColor: 'gray' }}
                                 onPress={() => { actions.selectMovie(item); }}
                            >
                                  <Text style={styles.headStyle}>{item.title}</Text>
                                  <Text>{item.overview}</Text>
                                  <Text style={styles.rateStyle}>
                                    Release Day:{item.release_date}
                                  </Text>
                                  <Text style={styles.rateStyle}>Rating: {item.vote_average}</Text>
                            </TouchableOpacity>
                        </View>)
                    }
            </View>

        );
    }
}
ListItem.propTypes = {
    actions: PropTypes.object.isRequired,
    movies: PropTypes.object.isRequired,
};

function mapStateToProps(state) {
    const { movies } = state;
    return {
        movies,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actions, dispatch)
    };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(ListItem);

Please let me know if I need to provide more information. Thank you!

Body:
You are calling selectMovie action instead of dispatching it. With the bindActionToProps method, react-redux provide you a way to dispatch actions via props, so the correct code should be:

<TouchableOpacity
style={{ backgroundColor: 'gray' }}
onPress={() => { this.props.actions.selectMovie(item)); }}>


问:
Is there a way i can detect if a form was submited on a webview?
I have a webview with a thirdparty payment company. I don't want to get the post data i just want to know if the user already submitted to lock the actions in the app so he can't do anything till the process is done. </p>

<p>Accoording the android documentation WebViewCLient doesn't do this on shouldOverrideUrlLoading() with post methods. </p>

答:
I didn't find a way to do exactly this but my work around was overriding shouldInterceptRequest(WebView view, WebResourceRequest request) on web client and then used there request.hasGesture() to know that the request was fired by an user action </p>

```private final WebViewClient webViewClient = new WebViewClient() {
@Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if(request.hasGesture()){
                    //block screen
                }
            }

            return super.shouldInterceptRequest(view, request);
        }
}```

Body:
I have a webview with a thirdparty payment company. I don't want to get the post data i just want to know if the user already submitted to lock the actions in the app so he can't do anything till the process is done.

Accoording the android documentation WebViewCLient doesn't do this on shouldOverrideUrlLoading() with post methods.

Body:
I didn't find a way to do exactly this but my work around was overriding shouldInterceptRequest(WebView view, WebResourceRequest request) on web client and then used there request.hasGesture() to know that the request was fired by an user action

private final WebViewClient webViewClient = new WebViewClient() {
@Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if(request.hasGesture()){
                    //block screen
                }
            }

            return super.shouldInterceptRequest(view, request);
        }
}


问:
Generate SNMP trap with source as Ipv6 address
I have come across simulators which support IPv6 for the host. But i am looking for a simulator where the SNMP trap generator uses the IPv6 address as the source IP or we can externally specify the IPv6 address in the command to generate snmp trap.
Can some one please tell me if you know any simulator which i can use for this.

thanks in advance
-Prateek

答:
This is trivial in MIMIC Simulator, which our company sells.
Here's a sample trap generated within a minute received by our trap receiver:

    % ./trapper --ipv6
    INFO  12/07.11:48:50 - Waiting for traps on port 162 ...
    INFO  12/07.11:57:08 - Received a SNMPv1 TRAP. [5 bytes from 2001::1,161]
    INFO  12/07.11:57:08 - HEADER :
    INFO  12/07.11:57:08 -   community        = public
    INFO  12/07.11:57:08 -   enterprise       = 1.3.6.1.4.1.9.1.46
    INFO  12/07.11:57:08 -   agent_addr       = 0.0.0.0
    INFO  12/07.11:57:08 -   generic_trap     = coldStart(0)
    INFO  12/07.11:57:08 -   specific_trap    = 0
    INFO  12/07.11:57:08 -   time_stamp       = 51692
    INFO  12/07.11:57:08 - MIB :
    INFO  12/07.11:57:08 -   mib              = SNMPv1-TRAPS


答:
It would be helpful if you elaborated more on what your problem is,
do you have a run time error, a compile time error, or it the output just not what you'd expect.

Your problem may be that arrays start at 0 so the first letter is charAt(0).

Actually I believe another user mentioned that the prize variable was initialized to true.  I believe that that is the issue and that answer should be marked correct.

Title: if char equals a letter then execute a code


问:
OmniAuth: Guarding against multiple accounts for the same user
I have a couple of Rails apps I'm looking to integrate with OmniAuth, but there is a conceptual problem I'm having with it that I'd like to figure out first. Consider the following scenario:

Your application, Foo, supports OmniAuth logins via Twitter and Facebook.

Joe comes to your site and logs in via his Twitter account. This creates a new user on Foo and associates it with this new Twitter authorization.

Joe logs out of Foo, and forgets about the site for six months.

Joe returns to Foo, not remembering that he has previously logged in with Twitter.

Joe logs in with Facebook. Since he is not already logged in via his original Twitter authorization, there is no way to detect that he is, in fact, the same Joe, and a new account is created.

Joe discovers his old account, and is now frustrated that his older content is tied to this old account, and that he can't log in with Twitter and Facebook interchangeably.

Since Twitter does not supply Foo with an email address, there is no universal identifier to use for detecting that the two Joes are the same Joe. You could decide to support only providers who give you the user's email address, but this doesn't help if the user has registered with different email addresses on different providers.

The only other solution I can think of is to give the user some way of merging two existing accounts. That's a big headache compared to the relative ease of everything else when using OmniAuth. If this is the only solution, has anyone come across a guide/tutorial showing an example of how this might be done? I'm surprised this issue hasn't gotten more attention given the popularity of OmniAuth.

Thanks!

答:
I also came across this problem today. I think I will handle it the following way:

I will ask the user for their email and a password when signing up, just like in a traditional authentication setup, where I try to get the email from the OmniAuth Service the user has chosen (FB, Twitter,...). So they only have to supply the email if it is not supplied by the auth provider. Then, if the user signs in later with the same provider they used for sign up, they will be logged in straight away. This will probably happen in 99% of all cases.

However, having the email and password of the user I can also handle all kind of cases that could occur (including the one you describe):

The original authentication provider is down or the user deleted their authentication provider account -> Solution: The user can login the traditional way, using their email and password. (Note, that this is an important case that I haven't seen mentioned anywhere on the net yet. People seem to assume that FB, Twitter, etc will be there forever, will never be down and users will never quit their accounts with those services. By not storing the users pw and email you will loose all your user accounts which were generated by a provider if one of these cases ocurrs, as you can't map them to users anymore. To me that is an unacceptable dependency on an external service.)

The user logs in later with a different authentication provider (this is your case) -> Solution: Try to map the user to an existing account using their email, if that fails, display the signup form with a button/link "I have already an account, please log me in" (or similar ;-). If they click that, they have to supply their email and password. Then, if they authenticate successfully, you can simply add that provider to the existing user record, and next time they are logged in straight away, just like with the provider they originally used for signup...

Maybe there are other cases that could occur. Any Feedback?


问:
Adding multiple rows with the same name pandas
I have a quick question.
If I have multiple rows with the same NAME but different quantities is there a pandas function to just add them? </p>

```<code>NAME     QTY
A         2
A         5

A         6

A total = 13?
</code>```

答:
try pivot table.  if your data frame is named df:

```<code>df = pd.pivot_table(df, index=['NAME'],values=['QTY'],aggfunc='sum')
</code>```

Body:
I have a quick question.
If I have multiple rows with the same NAME but different quantities is there a pandas function to just add them?

NAME     QTY
A         2
A         5

A         6

A total = 13?

Body:
try pivot table.  if your data frame is named df:

df = pd.pivot_table(df, index=['NAME'],values=['QTY'],aggfunc='sum')


问:
substitute list of equations into expression
In the following toy problem I'd like to evaluate j(fxxx) but with with the actual numbers for a,b,c that solve produces, is there a way to do that? According to the docs there is subst but it takes three arguments (variables to be substituted, the values, and the expression).

```<code>display2d:false;
i(f) := integrate(f(x),x,0,1);
j(f) := a*f(0)+b*f(1/2)+c*f(1);
f1(x) := 1;
fx(x) := x;
fxx(x) := x^2;
fxxx(x) := x^3;
print(solve([i(f1) = j(f1), i(fx) = j(fx), i(fxx) = j(fxx)],[a,b,c]));
</code>```

Try it online!

答:
Actually I should have finished reading the docs, we can actually still use subst:

```<code>i(f) := integrate(f(x),x,0,1);
j(f) := a*f(0)+b*f(1/2)+c*f(1);
f1(x) := 1;
fx(x) := x;
fxx(x) := x^2;
fxxx(x) := x^3;
jj(g) := subst(solve([i(f1) = j(f1), i(fx) = j(fx), i(fxx) = j(fxx)],[a,b,c]),j(g));
print(jj(g));
print(jj(fxxx)-i(fxxx));
</code>```

Try it online!

Body:
In the following toy problem I'd like to evaluate j(fxxx) but with with the actual numbers for a,b,c that solve produces, is there a way to do that? According to the docs there is subst but it takes three arguments (variables to be substituted, the values, and the expression).

display2d:false;
i(f) := integrate(f(x),x,0,1);
j(f) := a*f(0)+b*f(1/2)+c*f(1);
f1(x) := 1;
fx(x) := x;
fxx(x) := x^2;
fxxx(x) := x^3;
print(solve([i(f1) = j(f1), i(fx) = j(fx), i(fxx) = j(fxx)],[a,b,c]));

Try it online!

Body:
Actually I should have finished reading the docs, we can actually still use subst:

i(f) := integrate(f(x),x,0,1);
j(f) := a*f(0)+b*f(1/2)+c*f(1);
f1(x) := 1;
fx(x) := x;
fxx(x) := x^2;
fxxx(x) := x^3;
jj(g) := subst(solve([i(f1) = j(f1), i(fx) = j(fx), i(fxx) = j(fxx)],[a,b,c]),j(g));
print(jj(g));
print(jj(fxxx)-i(fxxx));

Try it online!


问:
Disable Scrolling on Body
I would like to disable scrolling on the HTML body completely. I have tried the following options:

overflow: hidden; (not working, did not disable scrolling, it just hid the scrollbar)

position: fixed; (this worked, but it scrolled completely to the top, which is unacceptable for this specific application)

I was unable to find any alternatives to these two options, are there any more?

答:
This post was helpful, but just wanted to share a slight alternative that may help others:

Setting max-height instead of height also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;} when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.

Title: Disable Scrolling on Body


问:
Reading 2-D array from a file
I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is : </p>

```<code>import java.util.*;
import java.lang.*;
import java.io.*;

public class appMainNineSix {

    /**
     * @param args
     */
    public static void main(String[] args)
        throws java.io.FileNotFoundException{
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("src/array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int [m][n];
        while (input.next()!=null){
            for (int i=0;i<m;i++){
                for (int j=0;j<n;j++)
                    a[i][j]= input.nextInt();
            }

        }
        //print the input matrix
        System.out.println("The input sorted matrix is : ");
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++)
                System.out.println(a[i][j]);
        }

    }

}
</code>```

答:
Well the problem may be that you've got that pair of nested loops to read the numbers stuck inside that while loop.  Why would you want to re-read the array values after you've read them once? And note that if there's anything in the file after the last number, then you'll fill the array in with whatever .nextInt() returns after end-of-file has been reached!

edit — well .nextInt() should throw an exception I guess when input runs out, so that may not be the problem.

Title: Reading 2-D array from a file

Body:
I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is :

import java.util.*;
import java.lang.*;
import java.io.*;

public class appMainNineSix {

    /**
     * @param args
     */
    public static void main(String[] args)
        throws java.io.FileNotFoundException{
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("src/array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int [m][n];
        while (input.next()!=null){
            for (int i=0;i<m;i++){
                for (int j=0;j<n;j++)
                    a[i][j]= input.nextInt();
            }

        }
        //print the input matrix
        System.out.println("The input sorted matrix is : ");
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++)
                System.out.println(a[i][j]);
        }

    }

}


问:
Rewrite foreach loops into linq query?
I tried to rewrite the following loops in one "elegant" linq query but no success!

```<code>foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }
</code>```

Could anyone suggest a query (if even possible)?

Thanks in advance

答:
You can only convert one of those foreach:</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        var test = Get("yes");
    }

    public static object Get(string value)
    {
        List<Obj1> List1 = new List<Obj1>();
        List1.Add(new Obj1());

        List<Obj2> List2 = new List<Obj2>();
        List2.Add(new Obj2());

        return (from om in List1
                where List2.Any(ol => ol.prop == value)
                select om.prop).FirstOrDefault();
    }
}

public class Obj1
{
    public string prop => "not";
}

public class Obj2
{
    public string prop => "yes";
}
</code>```

Title: Rewrite foreach loops into linq query?

Body:
I tried to rewrite the following loops in one "elegant" linq query but no success!

foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }

Could anyone suggest a query (if even possible)?

Thanks in advance

Body:
You can only convert one of those foreach:

class Program
{
    static void Main(string[] args)
    {
        var test = Get("yes");
    }

    public static object Get(string value)
    {
        List<Obj1> List1 = new List<Obj1>();
        List1.Add(new Obj1());

        List<Obj2> List2 = new List<Obj2>();
        List2.Add(new Obj2());

        return (from om in List1
                where List2.Any(ol => ol.prop == value)
                select om.prop).FirstOrDefault();
    }
}

public class Obj1
{
    public string prop => "not";
}

public class Obj2
{
    public string prop => "yes";
}


问:
What is fundamental difference between item.Axes.GetDescendants() and item.Axes.selectitems() in sitecore
What is fundamental/Performance difference between item.Axes.GetDescendants() and item.Axes.selectitems() in sitecore?

答:
item.Axes.selectitems() selects the items based on query provided.It is always good idea to use item.Axes.selectitems() in sitecore
instead of GetDescendents as Get Descendents always fetch the child items recursively and has huge performance hit if child items are large in size.</p>


问:
C#: loop through array of numbers and put consecutive numbers in one array, and all other numbers else in other array
I have an unsorted array of numbers. Most numbers in this array are consecutive (1, 2, 3, 4, 5,...) but sometimes there's a number in it that's higher than the rest.

```<code>int highestNumber = int.MinValue;
int secondHighestNumber = int.MinValue;

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;

foreach (int number in arr) {
    if (number > highestNumber) {
        secondHighestNumber = highestNumber;
        highestNumber = number;
    }
    else if (number > secondHighestNumber) secondHighestNumber = number;
}
</code>```

When I run the code, it'll tell me 9001 is the highest number and 9000 the second highest. But I want to change it so that I get an array of all the numbers from 1 to 11, with all the consecutive numbers that only have a difference of one, and a second array with all the larger numbers: 1207, 1803, 9000 and 9001.

9000 and 9001 shouldn't be in the first array, because the difference between these numbers and the rest is too high. So the end result should look like this:

```<code>int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] arr2 = new int[] { 1207, 1803, 9000, 9001 };
</code>```

Some background info on what the purpose of this is:

Cient creates articles and each article has an article number that is created by looking up what the highest article number is in the "articles" table so far (e.g. 20), then the number of the new article is that number + 1 (e.g. 21); So an increment per number. However the client wishes to be able to sometimes add articles and input the article number he desires for the article, so let's say for the last article he created he inputted 7000 as article number. If he he then creates another article after that, I have to continue with that list of incrementing numbers. So unless the client changes the value of the next article again, the next new article should have 22 as article number (and not 7001).

Any help would be greatly appreciated as I've been stuck on trying to figure this out for a while now.

答:
```<code>int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, 9000, 9001 };

// Sort the array
Array.Sort(arr);

// Start at the beginning and check if the index matches the actual number.
// Computer begins at 0, so fix that
for (int index=0;index<arr.Length; index++)
{
    if (arr[index] != index+1)
    {
        Console.WriteLine("Next ID is " +(index+1));
        break;
    }
}
</code>```

Body:
I have an unsorted array of numbers. Most numbers in this array are consecutive (1, 2, 3, 4, 5,...) but sometimes there's a number in it that's higher than the rest.

int highestNumber = int.MinValue;
int secondHighestNumber = int.MinValue;

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;

foreach (int number in arr) {
    if (number > highestNumber) {
        secondHighestNumber = highestNumber;
        highestNumber = number;
    }
    else if (number > secondHighestNumber) secondHighestNumber = number;
}

When I run the code, it'll tell me 9001 is the highest number and 9000 the second highest. But I want to change it so that I get an array of all the numbers from 1 to 11, with all the consecutive numbers that only have a difference of one, and a second array with all the larger numbers: 1207, 1803, 9000 and 9001.

9000 and 9001 shouldn't be in the first array, because the difference between these numbers and the rest is too high. So the end result should look like this:

int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] arr2 = new int[] { 1207, 1803, 9000, 9001 };

Some background info on what the purpose of this is:

Cient creates articles and each article has an article number that is created by looking up what the highest article number is in the "articles" table so far (e.g. 20), then the number of the new article is that number + 1 (e.g. 21); So an increment per number. However the client wishes to be able to sometimes add articles and input the article number he desires for the article, so let's say for the last article he created he inputted 7000 as article number. If he he then creates another article after that, I have to continue with that list of incrementing numbers. So unless the client changes the value of the next article again, the next new article should have 22 as article number (and not 7001).

Any help would be greatly appreciated as I've been stuck on trying to figure this out for a while now.


问:
Return HashMap<String, Object> from GraphQL-Java
I tried few variant and had no luck to return a map in GraphQL. So I have the following two objects:

```<code>public class Customer {

    private String name, age;
    // getters & setters
}

public class Person {

   private String type;
   private Map<String, Customer> customers;
   // getters & setters
}
</code>```

My schema looks like this:

```<code>type Customer {
   name: String!
   age:  String!
}

type Person {
  type: String!
  customers: [Customer!] // Here I tried all combination but had no luck, is there a Map type support for GQL?
}
</code>```

Can someone please tell me how to achieve this so that GraphQL magically process this or an alternative approach.

Many thanks!

答:
There is no map type in GraphQL (Discussion on GitHub).

An alternative approach would be to have customers as a List of Customers

```<code>public class Person {
   private String type;
   private List<Customer> customers;
}
</code>```

and include the key for the map inside the Customer class

```<code>public class Customer {
    private String key; // or another meaningful name
    private String name, age;
}
</code>```

Schema would mostly remain the same.

```<code>type Customer {
   key: String! // or another meaningful name
   name: String!
   age: String!
}

type Person {
  type: String!
  customers: [Customer!]!
}
</code>```

Body:
I tried few variant and had no luck to return a map in GraphQL. So I have the following two objects:

public class Customer {

    private String name, age;
    // getters & setters
}

public class Person {

   private String type;
   private Map<String, Customer> customers;
   // getters & setters
}

My schema looks like this:

type Customer {
   name: String!
   age:  String!
}

type Person {
  type: String!
  customers: [Customer!] // Here I tried all combination but had no luck, is there a Map type support for GQL?
}

Can someone please tell me how to achieve this so that GraphQL magically process this or an alternative approach.

Many thanks!

Body:
There is no map type in GraphQL (Discussion on GitHub).

An alternative approach would be to have customers as a List of Customers

public class Person {
   private String type;
   private List<Customer> customers;
}

and include the key for the map inside the Customer class

public class Customer {
    private String key; // or another meaningful name
    private String name, age;
}

Schema would mostly remain the same.

type Customer {
   key: String! // or another meaningful name
   name: String!
   age: String!
}

type Person {
  type: String!
  customers: [Customer!]!
}


问:
Python: Continuing to next iteration in outer loop
I wanted to know if there are any built-in ways to continue to next iteration in outer loop in python.  For example,  consider the code:

```<code>for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            continue
    ...block1...
</code>```

I want this continue statement to exit the jj loop and goto next item in the ii loop.  I can implement this logic in some other way (by setting a flag variable), but is there an easy way to do this, or is this like asking for too much?

答:
We want to find something and then stop the inner iteration. I use a flag system.</p>

```<code>for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False
</code>```

Body:
I wanted to know if there are any built-in ways to continue to next iteration in outer loop in python.  For example,  consider the code:

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            continue
    ...block1...

I want this continue statement to exit the jj loop and goto next item in the ii loop.  I can implement this logic in some other way (by setting a flag variable), but is there an easy way to do this, or is this like asking for too much?

Body:
We want to find something and then stop the inner iteration. I use a flag system.

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False


问:
Supporting multiple instances of a plugin DLL with global data
Context: I converted a legacy standalone engine into a plugin component for a composition tool. Technically, this means that I compiled the engine code base to a C DLL which I invoke from a .NET wrapper using P/Invoke; the wrapper implements an interface defined by the composition tool. This works quite well, but now I receive the request to load multiple instances of the engine, for different projects. Since the engine keeps the project data in a set of global variables, and since the DLL with the engine code base is loaded only once, loading multiple projects means that the project data is overwritten.

I can see a number of solutions, but they all have some disadvantages:

You can create multiple DLLs with the same code, which are seen as different DLLs by Windows, so their code is not shared. Probably this already works if you have multiple copies of the engine DLL with different names. However, the engine is invoked from the wrapper using DllImport attributes and I think the name of the engine DLL needs to be known when compiling the wrapper. Obviously, if I have to compile different versions of the wrapper for each project, this is quite cumbersome.

The engine could run as a separate process. This means that the wrapper would launch a separate process for the engine when it loads a project, and it would use some form of IPC to communicate with this process. While this is a relatively clean solution, it requires some effort to get working, I don't now which IPC technology would be best to set-up this kind of construction. There may also be a significant overhead of the communication: the engine needs to frequently exchange arrays of floating-point numbers.

The engine could be adapted to support multiple projects. This means that the global variables should be put into a project structure, and every reference to the globals should be converted to a corresponding reference that is relative to a particular project. There are about 20-30 global variables, but as you can imagine, these global variables are referenced from all over the code base, so this conversion would need to be done in some automatic manner. A related problem is that you should be able to reference the "current" project structure in all places, but passing this along as an extra argument in each and every function signature is also cumbersome. Does there exist a technique (in C) to consider the current call stack and find the nearest enclosing instance of a relevant data value there?

Can the stackoverflow community give some advice on these (or other) solutions?

答: Use approach #3. Since the code is in C, an easy way to deal with the globals that are spread everywhere is to define a macro for each global that has the same name as the global variable, but the macro expands to something like getSession()->theGlobal where getSession() returns a pinter to a "session-specific" structure that holds all the data for your globals. getSession() would fish the right data structure out of a global map of data structures somehow, perhaps using thread-local storage, or based on process ID, etc.</p>