问:
Laravel output single row from database
I am a beginner at Laravel, and I am stuck :)

I am building a simple CMS for a costumer with a rather simple website.
I have created a database for all the text throughout the site, which I want to be able to edit. All the CRUD is working, but I can't seem to output the content from the database, with blade, to the actual view, as I get the error that the variable doesnt exist.

I thought I would be doing something like this {{ $text->"insert specific id" }}
My table has strings for id's to identify the respective text-content thoughout the site.

I have a MainController and a TextController, which is the one dealing with the CRUD of the text-elements.

I am probably forgetting a simple thing, but I just can't seem to work it out.

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Text;
use Session;

class TextController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $texts = Text::all();

    return view('texts.index')->withTexts($texts);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text = new Text;
    $text->content = $request->content;
    $text->save();

    return redirect()->route('texts.index');
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $text = Text::find($id);
    return view('texts.edit')->withText($text);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $text = Text::find($id);
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text->content = $request->content;
    $text->save();

    Session::flash('success', 'Teksten blev ændret!');

    return redirect()->route('texts.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}
</code>```

}

I would think that I am missing something in the MainController

```<code><?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use Illuminate\Support\Facades\DB;
use Session;
use App\Text;

class MainController extends Controller
{
public function index(){

    return view('index');
}
</code>```

Could that be?

Thanks in advance!

答:
In controller you have to select data you want to pass to view

```<code>$texts = Text::get(); //or Text::all(); for all results
$text = Text::find($id); //if you want one item get by ID
$text = Text::where('column', 'value')->first(); //first item matching condition
</code>```

//and then pass it to view as second parameter (array) in view function)

```<code>return view('index', ['texts' => $texts, 'text' => $text] /* or compact('texts', 'text') */);
</code>```

//then in view

```<code>@foreach($texts as $t)
{{$t->content}}
@endforeach

or
{{$text->content}}
</code>```

Title: Laravel output single row from database

Body:
I am a beginner at Laravel, and I am stuck :)

I am building a simple CMS for a costumer with a rather simple website.
I have created a database for all the text throughout the site, which I want to be able to edit. All the CRUD is working, but I can't seem to output the content from the database, with blade, to the actual view, as I get the error that the variable doesnt exist.

I thought I would be doing something like this {{ $text->"insert specific id" }}
My table has strings for id's to identify the respective text-content thoughout the site.

I have a MainController and a TextController, which is the one dealing with the CRUD of the text-elements.

I am probably forgetting a simple thing, but I just can't seem to work it out.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Text;
use Session;

class TextController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $texts = Text::all();

    return view('texts.index')->withTexts($texts);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text = new Text;
    $text->content = $request->content;
    $text->save();

    return redirect()->route('texts.index');
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $text = Text::find($id);
    return view('texts.edit')->withText($text);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $text = Text::find($id);
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text->content = $request->content;
    $text->save();

    Session::flash('success', 'Teksten blev ændret!');

    return redirect()->route('texts.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}

}

I would think that I am missing something in the MainController

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use Illuminate\Support\Facades\DB;
use Session;
use App\Text;

class MainController extends Controller
{
public function index(){

    return view('index');
}

Could that be?

Thanks in advance!

Body:
In controller you have to select data you want to pass to view

$texts = Text::get(); //or Text::all(); for all results
$text = Text::find($id); //if you want one item get by ID
$text = Text::where('column', 'value')->first(); //first item matching condition

//and then pass it to view as second parameter (array) in view function)

return view('index', ['texts' => $texts, 'text' => $text] /* or compact('texts', 'text') */);

//then in view

@foreach($texts as $t)
{{$t->content}}
@endforeach

or
{{$text->content}}


来源: stackexchange

问:
Avoid looping to get one particular column of values from Set<Entity> in Java
I have a code snippet in Java as follows:

```<code>Set<BookDO> bookSet = shopDO.getBooks();
    Collection<String> bookCollection = null;
    if (bookSet != null && !bookSet .isEmpty()) {
      bookCollection = new ArrayList<String>();
      for (BookDO book : bookSet) {
        bookCollection .add(book.getName());
      }
    }
</code>```

Finally I want the only Collection of book names to pass it to an API which displays the output.

Is it possible to avoid the for loop to improve performance ?

答:
You should not worry about the performance of the loop construct. There is a JIT, that will optimize things at runtime.

You have a Set of Books, containing n elements. You want to retrieve a property of each set entry; and push that value into a list. That is simply not possible without somehow iterating that whole set! You know, in order to touch every element, you have to, well, touch every element.

Yes, using java8 streams, this could be rewritten in various ways; and you might gain a bit of performance because that will enable the compiler to use the invokedynamic bytecode instruction (which has certain performance advantages).

But in the end: you don't get around iterating over all entries of that collection.

And the real take away is: you are only assuming that you have a performance problem. Don't try to fix something that isn't real; until it becomes a real issue. Of course, if that collections contains many zillions of entries, then you do have a real problem. But then your question is still going in the wrong direction; because if you are doing "hardcore" data crunching; you would have to re-think your complete design to find ways to "scale".

Caveat: if we would be talking quantum computing, and Grover search, then, well, crazy things would be possible. But we aren't.

ContentLicense: CC BY-SA 3.0

Body:
I have a code snippet in Java as follows:

Set<BookDO> bookSet = shopDO.getBooks();
    Collection<String> bookCollection = null;
    if (bookSet != null && !bookSet .isEmpty()) {
      bookCollection = new ArrayList<String>();
      for (BookDO book : bookSet) {
        bookCollection .add(book.getName());
      }
    }

Finally I want the only Collection of book names to pass it to an API which displays the output.

Is it possible to avoid the for loop to improve performance ?


问:
Open a file after it was created in Python
I created two classes. The first class takes an image from the working directory and then covert the image from pdf to jpg using wand. The second class takes the created jpg image and then do further manipulations with the image.

Now When I try to run the first class and then the second class right after that; python crashes because the second class is trying to look for the image but it wont find it until it is created.

My question is how can you run the second class but just after the first class is executed.

class1 = imagecreation('image.jpg')
class2 = transformimage()

答: I found the answer to my question. When you reference classes and you import as a module in a different one; the module will get call when is defined if you do not use if __name__=='__main__':. By putting this code at the end of the code will only execute the module once it is intended to be executed but not when you import the module. This way you can use the modules by themselves and also to import from other modules.


问:
Regex to find matches from a string having multiple square brackets
I have a paragraph like below:

Some wording for testing [!#today] where the [!condition] does not satisfy with this verbiage [!ShowElemIf://Student/FullName;  [[[Text not recognized fully]]]  ;/First Name] But simple tags found having age [!ShowElemIf://Student/Age;xml//Student/DOB/@formatted;y]

I need to find all the placeholders/tags from above which are like: [!tag] using C#. I tried for a regex but it is not able to find the tag having "FullName" word as highlighted in bold above.

List<string> tags = Regex.Matches(
                     sampleText.Replace(Environment.NewLine, ""), @"\[!([^]]+)\] ")
                     .Cast<Match>()
                     .Select(x => x.Groups[1].Value)
                     .ToList();```

Using this RegEx I can find below but not the highlighted one.

today

condition

ShowElemIf://Student/Age;xml//Student/DOB/@formatted;y

答:
You need to use  balancing groups available in .NET regex:

```<code>@"\[!((?:[^][]+|(?<o>\[)|(?<-o>)])*(?(o)(?!)))]"
</code>```

See the regex demo

Details:

\[! - a [! substring

((?:[^][]+|(?<o>\[)|(?<-o>)])*(?(o)(?!))) - Capturing group 1 matching

(?: - a non-capturing group with 3 alternatives:

[^][]+| - 1 or more chars other than [ and ], or

(?<o>\[)| - a [ pushed into "o" group stack, or

(?<-o>)] - a ] is subtracted from the "o" group stack

)*  - zero or more occurrences

(?(o)(?!))) - a conditional construct checking if the "o" group stack is empty. If it is empty, matching goes on, else, no match is returned.

]  - a literal closing ] symbol.

Body:
I have a paragraph like below:

Some wording for testing [!#today] where the [!condition] does not satisfy with this verbiage [!ShowElemIf://Student/FullName;  [[[Text not recognized fully]]]  ;/First Name] But simple tags found having age [!ShowElemIf://Student/Age;xml//Student/DOB/@formatted;y]

I need to find all the placeholders/tags from above which are like: [!tag] using C#. I tried for a regex but it is not able to find the tag having "FullName" word as highlighted in bold above.

List<string> tags = Regex.Matches(
                     sampleText.Replace(Environment.NewLine, ""), @"\[!([^]]+)\] ")
                     .Cast<Match>()
                     .Select(x => x.Groups[1].Value)
                     .ToList();

Using this RegEx I can find below but not the highlighted one.

today

condition

ShowElemIf://Student/Age;xml//Student/DOB/@formatted;y

Body:
You need to use  balancing groups available in .NET regex:

@"\[!((?:[^][]+|(?<o>\[)|(?<-o>)])*(?(o)(?!)))]"

See the <a href="http://regexstorm.net/tester?p=%5c%5b!%28%28%3f%3a%5b%5e%5d%5b%5d%2b%7c%28%3f%3co%3e%5c%5b%29%7c%28%3f%3c-o%3e%29%5d%29*%28%3f%28o%29%28%3f!%29%29%29%5d&i=Some+wording+for+testing+%5b!%23today%5d+where+the+%5b!condition%5d+does+not+satisfy+with+this+verbiage+%5b!ShowElemIf%3a%2f%2fStudent%2fFullName%3b+%5b%5b%5bText+not+recognized+fully%5d%5d%5d+%3b%2fFirst+Name%5d+But+simple+tags+found+having+age+%5b!ShowElemIf%3a%2f%2fStudent%2fAge%3bxml%2f%2fStudent%2fDOB%2f%40formatted%3by%5d" rel="nofollow noreferrer">regex demo

Details:

\[! - a [! substring

((?:[^][]+|(?<o>\[)|(?<-o>)])*(?(o)(?!))) - Capturing group 1 matching

(?: - a non-capturing group with 3 alternatives:

[^][]+| - 1 or more chars other than [ and ], or

(?<o>\[)| - a [ pushed into "o" group stack, or

(?<-o>)] - a ] is subtracted from the "o" group stack

)*  - zero or more occurrences

(?(o)(?!))) - a conditional construct checking if the "o" group stack is empty. If it is empty, matching goes on, else, no match is returned.

]  - a literal closing ] symbol.


问:
Specific dice to reroll in C
I am working on a game of Yahtzee and one part of the game is the user can choose which dice out of 5 they wish to re-roll. I don't really know how to approach this besides writing a ton of if if-else statements, but there has to be a more efficient way to re-roll the specific die/ dice. I wrote out a snippet of what I am trying to accomplish, its not exactly like this in my actual code, but hopefully it is enough to answer the question :)

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

int main(void)
{
    int die1 = 0, die2 = 0, die3 = 0, die4 = 0, die5 = 0;
    int *ptr_die1 = &die1, *ptr_die2 = &die2, *ptr_die3 = &die3, *ptr_die4 = &die4, *ptr_die5 = &die5;
    int choice = 0;
    int die[5] = { 0 };

    for (int i = 0; i < 5; i++)
    {
        die[i] = rand() % 6 + 1;
    }

    printf("Die[1] = %d\n", die[0]);
    printf("Die[2] = %d\n", die[1]);
    printf("Die[3] = %d\n", die[2]);
    printf("Die[4] = %d\n", die[3]);
    printf("Die[5] = %d\n", die[4]);

    choice = printf("Please select which die to reroll\n");
    scanf("%d", &choice);

    printf("%d\n", choice);

    for (int i = 0; i < 5; i++)
    {
        die[choice-1] = rand() % 6 + 1;
    }

    printf("Die[1] = %d\n", die[0]);
    printf("Die[2] = %d\n", die[1]);
    printf("Die[3] = %d\n", die[2]);
    printf("Die[4] = %d\n", die[3]);
    printf("Die[5] = %d\n", die[4]);

    return 0;
}
</code>```

after this I am really lost on how to change the die because the user could want to change just 1, or all 5 or any combination in between...

答:
I don't see any if..else statements in your code above. I will say, in this chunk of code:

```<code>for (int i = 0; i < 5; i++)
{
    die[choice-1] = rand() % 6 + 1;
}
</code>```

You don't need the for loop. You are not using the index, and rand() should work the first time through. I know rand() isn't the best written function, but if you seed it first, it should give you a pseudo-random number.

```<code>#include <time.h>
...
/* initialize random seed: */
srand ( time(NULL) );
...
die[choice-1] = rand() % 6 + 1;
</code>```

Hope this was helpful, if you are still even working on that project!

Title: Specific dice to reroll in C

Body:
I am working on a game of Yahtzee and one part of the game is the user can choose which dice out of 5 they wish to re-roll. I don't really know how to approach this besides writing a ton of if if-else statements, but there has to be a more efficient way to re-roll the specific die/ dice. I wrote out a snippet of what I am trying to accomplish, its not exactly like this in my actual code, but hopefully it is enough to answer the question :)

#include<stdio.h>

int main(void)
{
    int die1 = 0, die2 = 0, die3 = 0, die4 = 0, die5 = 0;
    int *ptr_die1 = &die1, *ptr_die2 = &die2, *ptr_die3 = &die3, *ptr_die4 = &die4, *ptr_die5 = &die5;
    int choice = 0;
    int die[5] = { 0 };

    for (int i = 0; i < 5; i++)
    {
        die[i] = rand() % 6 + 1;
    }

    printf("Die[1] = %d\n", die[0]);
    printf("Die[2] = %d\n", die[1]);
    printf("Die[3] = %d\n", die[2]);
    printf("Die[4] = %d\n", die[3]);
    printf("Die[5] = %d\n", die[4]);

    choice = printf("Please select which die to reroll\n");
    scanf("%d", &choice);

    printf("%d\n", choice);

    for (int i = 0; i < 5; i++)
    {
        die[choice-1] = rand() % 6 + 1;
    }

    printf("Die[1] = %d\n", die[0]);
    printf("Die[2] = %d\n", die[1]);
    printf("Die[3] = %d\n", die[2]);
    printf("Die[4] = %d\n", die[3]);
    printf("Die[5] = %d\n", die[4]);

    return 0;
}

after this I am really lost on how to change the die because the user could want to change just 1, or all 5 or any combination in between...

Body:
I don't see any if..else statements in your code above. I will say, in this chunk of code:

for (int i = 0; i < 5; i++)
{
    die[choice-1] = rand() % 6 + 1;
}

You don't need the for loop. You are not using the index, and rand() should work the first time through. I know rand() isn't the best written function, but if you seed it first, it should give you a pseudo-random number.

#include <time.h>
...
/* initialize random seed: */
srand ( time(NULL) );
...
die[choice-1] = rand() % 6 + 1;

Hope this was helpful, if you are still even working on that project!


问:
Creating and connecting a socket indipendently from the IP version using sockaddr_storage
I'm writing a client that can connect both to an IPv4 and an IPv6 address, making the code as generale as possible.
I used the getaddrinfofunction to which I pass the string of the IP address, and from that I obtain the address family (at this point I know if it's IPv4 or IPv6). Now I need to bind that address and the port to a sockaddr structure. I've read that in order to make it general I should use sockaddr_storage and then using it by casting it to sockaddr, but I don't understand how to fill sockaddr_storage with the address and the port needed for the connection.

Thanks for your attention.

NB. I want it to work on UNIX.

答:
The POSIX specification only says that the sockaddr_storage should be

Large enough to accommodate all supported protocol-specific address structures

Aligned at an appropriate boundary so that pointers to it can be cast as pointers to protocol-specific address structures and used to access the fields of those structures without alignment problems

And

The sockaddr_storage structure shall contain at least the following members:

sa_family_t   ss_family

There's some notes saying that the family structure member for all sockaddr-family structures will be at the same place, but that's about it.

So the I would say that the "best" way to use it is to have special cases for IPv4 and IPv6 that fills in the correct sockaddr_in or sockaddr_in6 structures, then memcpy them into a sockaddr_storage structure that can later be used.


问:
How to remove duplicate record in MongoDB 3.x?
I tried

dropDups: true

but it is not working,
is there any other way to remove duplicates from mongo collection?

And how to assign unique key to particular field?

答:
dropDupes is deprecated after 2.7

You can go for Aggregation and write script to remove dups.
Or else you can get a dump of that collection then remove all documents from that old collection.
after that add unique index to the collection and then restore the collection back.
mongoresore will not add duplicate collections.


问:
Delete row from database with form in the same page
In the same page I have a form that asks the user to confirm whether he wants to delete the data or not, and I have the PHP code. Now, I want to delete a row from database using superglobals, but I can't figure out the problem. It always echos "NOT DELETED". Also If the user chooses not to delete, I would like to perform a redirect to home.php.

```<code><body>

<h2>Are you sure you want to delete the student?</h2>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="YES" />
    <input type="submit" name="submit" value="NO" />
</form>

<?php

$fields = array('id', 'student', 'firstname', 'lastname', 'email');
$student= array();

foreach ($fields as $field) {
$student[$field]="";
}

if(isset($_POST['id'])) {
    $id = htmlspecialchars($_POST['id']);
}
else if(isset($_GET['id'])) {
    $id = htmlspecialchars($_GET['id']);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if(!empty($id)) {

    include "inc_DBConnect.php";

    $SQLString = "DELETE FROM students WHERE id = '$id'";

    $SQLQueryResult = mysqli_query($DBConnection, $SQLString);
    if($SQLQueryResult === FALSE) {
        echo "<p>There was an error retrieving the record.<br />\n</p>";
    } else {
        echo "<p>Student deleted</p>";
    }
} else {
    echo "NOT DELETED";
 }

}

?>
</body>
</code>```

答:
In your code there is no id field there so would not going to get it on POST request.</p>

```<code><body>
<?php
// check this too when your form is submitting
// print_r($_SERVER);
?>
<h2>Are you sure you want to delete the student?</h2>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="hidden" name="id" value="<?php echo $_GET['id']?>" />
    <input type="submit" name="submit" value="YES" />
    <input type="submit" name="submit" value="NO" />
</form>

<?php

$fields = array('id', 'student', 'firstname', 'lastname', 'email');
$student= array();

foreach ($fields as $field) {
$student[$field]="";
}

if(isset($_POST['id'])) {
    $id = htmlspecialchars($_POST['id']);
}
else if(isset($_GET['id'])) {
    $id = htmlspecialchars($_GET['id']);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if(!empty($id)) {

    include "inc_DBConnect.php";

    $SQLString = "DELETE FROM students WHERE id = '$id'";

    $SQLQueryResult = mysqli_query($DBConnection, $SQLString);
    if($SQLQueryResult === FALSE) {
        echo "<p>There was an error retrieving the record.<br />\n</p>";
    }
    else {
        echo "<p>Student deleted</p>";
    }
}
else {
    echo "NOT DELETED";
}
}

?>
</body>
</code>```

Body:
In the same page I have a form that asks the user to confirm whether he wants to delete the data or not, and I have the PHP code. Now, I want to delete a row from database using superglobals, but I can't figure out the problem. It always echos "NOT DELETED". Also If the user chooses not to delete, I would like to perform a redirect to home.php.

Are you sure you want to delete the student?

<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="YES" />
    <input type="submit" name="submit" value="NO" />
</form>

<?php

$fields = array('id', 'student', 'firstname', 'lastname', 'email');
$student= array();

foreach ($fields as $field) {
$student[$field]="";
}

if(isset($_POST['id'])) {
    $id = htmlspecialchars($_POST['id']);
}
else if(isset($_GET['id'])) {
    $id = htmlspecialchars($_GET['id']);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if(!empty($id)) {

    include "inc_DBConnect.php";

    $SQLString = "DELETE FROM students WHERE id = '$id'";

    $SQLQueryResult = mysqli_query($DBConnection, $SQLString);
    if($SQLQueryResult === FALSE) {
        echo "
There was an error retrieving the record.
\n
";
    } else {
        echo "
Student deleted
";
    }
} else {
    echo "NOT DELETED";
 }

}

?>

Body:
In your code there is no id field there so would not going to get it on POST request.

<body>
<?php
// check this too when your form is submitting
// print_r($_SERVER);
?>
<h2>Are you sure you want to delete the student?</h2>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="hidden" name="id" value="<?php echo $_GET['id']?>" />
    <input type="submit" name="submit" value="YES" />
    <input type="submit" name="submit" value="NO" />
</form>

<?php

$fields = array('id', 'student', 'firstname', 'lastname', 'email');
$student= array();

foreach ($fields as $field) {
$student[$field]="";
}

if(isset($_POST['id'])) {
    $id = htmlspecialchars($_POST['id']);
}
else if(isset($_GET['id'])) {
    $id = htmlspecialchars($_GET['id']);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if(!empty($id)) {

    include "inc_DBConnect.php";

    $SQLString = "DELETE FROM students WHERE id = '$id'";

    $SQLQueryResult = mysqli_query($DBConnection, $SQLString);
    if($SQLQueryResult === FALSE) {
        echo "<p>There was an error retrieving the record.<br />\n</p>";
    }
    else {
        echo "<p>Student deleted</p>";
    }
}
else {
    echo "NOT DELETED";
}
}

?>
</body>


问:
How to add scrollbar to celltable
i have small problem i.e. their is one celltable with lot of data it is placed in popup so the popup height is very large so my problem is i want to add a scrollbar to my celltable so the popup height reduced
                    please help me anyone....

note:-i will try set height for table and popup but their is no result & i am write code in java & gwt

答: Have a look at the ScrollPanel.</p>

ContentLicense: CC BY-SA 2.5

Title: How to add scrollbar to celltable

Body: Have a look at the ScrollPanel.


问:
C# Inheritance misconception
Let's say that we have 2 classes. The first one is Person

```<code>    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace People
    {
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }
</code>```

The second one is Teacher

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}
</code>```

And I want to make a teacher object using this syntax Person teacher = new Teacher(); When I make it and I try to refer to the Position property, I can't... Why does this happen? I can instead use this syntax Person teacher = new Teacher() {Position="boss" }; but even though, after that I can't refer to the teacher position using "teacher.Position".

答:
The reason is, the compiler simply does not know the inherited type after you assigned it to a variable explicitly declared as the base type.

The reason for that is, that while the object is still clearly an instance of Teacher the compiler can only be sure that this object is a Person at runtime, thus it will not allow you to access any properties of the Teacher class.

Declaring the variable as var will let the compiler determine the type of that variable based on what was assigned to it.

Title: C# Inheritance misconception

Body:
Let's say that we have 2 classes. The first one is Person

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace People
    {
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }

The second one is Teacher

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}

And I want to make a teacher object using this syntax Person teacher = new Teacher(); When I make it and I try to refer to the Position property, I can't... Why does this happen? I can instead use this syntax Person teacher = new Teacher() {Position="boss" }; but even though, after that I can't refer to the teacher position using "teacher.Position".


答:
Sorry for late update:

No. It is not possible right out of current code (aside of using Java 8 features to hide it)

If shopDO.getBooks(); code is in your hands you have another options :

if Book Name is unique use Map instead of Set with Name as a key.
then you have your Book names right out of it as bookMap.keySet()

if Book Name is not unique you can return from shopDO two collections 1. Set<BookDO> and List<String> of names populated at the same time when you populate first Set

If you cannot modify shopDo code then there is no options.

Title: Avoid looping to get one particular column of values from Set<Entity> in Java


问:
How to create and process a 4D sparse matrix in Python efficiently
I have a 4D sparse matrix of shape (21x21x21x21). Only one of the element will be set to 1. After which, I will vectorize this matrix and determine the non-zero row. The whole process takes about 6 mins to compute which is too long. Is there a way to do this efficiently in Python? </p>

```<code>sparseMatrix = np.zeros((21,21,21,21), dtype = np.int8)
#w,x,y,z can be any random integer from 0 to 20.
w = 3
x = 5
y = 18
z = 16
sparseMatrix[w, x, y, z] = 1
sparseMatrix_vec = np.reshape(sparseMatrix, [-1,1])
sparseMatrix_vec_index = np.nonzero(sparseMatrix_vec)[0][0]
</code>```

答:
If you need (w,x,y,z) to form a unique integer, where each of (w,x,y,z) can vary between 0 and 20, then simply use base 21 representation. The integer you are looking for is:

N = w*(21 ** 0) + x*(21 ** 1) + y*(21 ** 2) + z*(21 ** 3).

Given an integer, you can go back to (w,x,y,z) by using integer division and modulus.

Body:
I have a 4D sparse matrix of shape (21x21x21x21). Only one of the element will be set to 1. After which, I will vectorize this matrix and determine the non-zero row. The whole process takes about 6 mins to compute which is too long. Is there a way to do this efficiently in Python?

sparseMatrix = np.zeros((21,21,21,21), dtype = np.int8)
#w,x,y,z can be any random integer from 0 to 20.
w = 3
x = 5
y = 18
z = 16
sparseMatrix[w, x, y, z] = 1
sparseMatrix_vec = np.reshape(sparseMatrix, [-1,1])
sparseMatrix_vec_index = np.nonzero(sparseMatrix_vec)[0][0]


问:
Android: conerting Image into byteArray
In my project I have an bitmap image. I need to convert this picture to byteArray in order to manipulate some bytes and after that save it as image.

with this code image = BitmapFactory.decodeResource(context.getResources(), R.drawable.tasnim); I have acces to width and height but how can I have access to bytes of this image?

Thanks

答:
AFAIK Most correct way is:</p>

```<code>ByteBuffer copyToBuffer(Bitmap bitmap){
    int size = bitmap.getHeight() * bitmap.getRowBytes();
    ByteBuffer buffer = ByteBuffer.allocateDirect(size);
    bitmap.copyPixelsToBuffer(buffer);
    return buffer;
}
</code>```

Title: Android: conerting Image into byteArray

Body:
AFAIK Most correct way is:

ByteBuffer copyToBuffer(Bitmap bitmap){
    int size = bitmap.getHeight() * bitmap.getRowBytes();
    ByteBuffer buffer = ByteBuffer.allocateDirect(size);
    bitmap.copyPixelsToBuffer(buffer);
    return buffer;
}


问:
Get value of comboboxitem contentcontrol in wpf
I am new to WPF.
I want to know how can i get the selectedtext if the text that i want is placed inside a control inside comboboxitem and not directly inside comboboxitem.
I know this is very basic,but would appreciate if someone could provide me a simple and quick solution

My simple combobox code is as follows:

```<code><ComboBox x:Name="cmdTest">
    <ComboBoxItem>
        <TextBlock Text="RED" Background="RED" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
    </ComboBoxItem>
    <ComboBoxItem>
        <Grid Width="250">
            <TextBlock Text="GREEN" Background="GREEN" Foreground="White" FontFamily="Sans Serif" FontSize="14" Height="15"/>
        </Grid>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock Text="BLUE" Background="Blue" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
    </ComboBoxItem>
</ComboBox>
</code>```

答:
Try this:</p>

```<code>private void cmdTest_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBoxItem item = cmdTest.SelectedItem as ComboBoxItem;
    if (item != null)
    {
        TextBlock txt = item.Content as TextBlock;
        if (txt != null)
            MessageBox.Show(txt.Text + " is selected");
    }
}
</code>```

Body:
I am new to WPF.
I want to know how can i get the selectedtext if the text that i want is placed inside a control inside comboboxitem and not directly inside comboboxitem.
I know this is very basic,but would appreciate if someone could provide me a simple and quick solution

My simple combobox code is as follows:

<ComboBox x:Name="cmdTest">
    <ComboBoxItem>
        <TextBlock Text="RED" Background="RED" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
    </ComboBoxItem>
    <ComboBoxItem>
        <Grid Width="250">
            <TextBlock Text="GREEN" Background="GREEN" Foreground="White" FontFamily="Sans Serif" FontSize="14" Height="15"/>
        </Grid>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock Text="BLUE" Background="Blue" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
    </ComboBoxItem>
</ComboBox>

Body:
Try this:

private void cmdTest_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBoxItem item = cmdTest.SelectedItem as ComboBoxItem;
    if (item != null)
    {
        TextBlock txt = item.Content as TextBlock;
        if (txt != null)
            MessageBox.Show(txt.Text + " is selected");
    }
}


问:
The default ActiveAdmin filter doesn't filter my index table
I have an application where you can fill in metadata of documents. I currently have a problem with the default filtering as it doesn't filter my index table. The filter options are shown on the right side and you can also see the filtering options in the url and params after you choose a filter and hit the button.

```<code>utf8=✓&q%5Buser_id_eq%5D=3&commit=Filter&order=id_desc
</code>```

But somehow the index table doesn't refresh.

The only scope I have is the default:

```<code>  scope :all, default: true
</code>```

EDIT

I think it has something to do with the pagination because If i remove pagination the filters work again.

This is my current index method in my app/admin/DocumentType.rb file:

```<code>def index
  index! do |format|
    @document_types = DocumentType.where(archived_at: nil).page(params[:page])
    file_name = "document_types_#{DateTime.now.strftime('%a_%d_%b_%Y_%H%M%S').downcase}"

    format.xls {
      spreadsheet = DocumentTypesSpreadsheet.new @document_types
      send_data spreadsheet.generate_xls, filename: file_name + ".xls"
    }
  end
end
</code>```

Only document types which are not archived should be displayed in the index therefore i have

```<code>@document_types = DocumentType.where(archived_at: nil).page(params[:page])
</code>```

Now with this my filter don't work. But if I remove this line completely they work again except now it displays also the archived document types. And if I remove the .page(params[:page]) part I get the following error message:

```<code> Collection is not a paginated scope. Set collection.page(params[:page]).per(10) before calling :paginated_collection.
</code>```

答:
Try to update your controller with this

```<code>def index
  index! do |format|
    @document_types = DocumentType.where(archived_at: nil).ransack(params[:q]).result
    file_name = "document_types_#{DateTime.now.strftime('%a_%d_%b_%Y_%H%M%S').downcase}"

    format.xls {
      spreadsheet = DocumentTypesSpreadsheet.new @document_types
      send_data spreadsheet.generate_xls, filename: file_name + ".xls"
    }
  end
end
</code>```

But you need to be sure, you deisplay the records with this condition as well:

```<code>.where(archived_at: nil)
</code>```

because the exported result will be different with displayed

Body:
I have an application where you can fill in metadata of documents. I currently have a problem with the default filtering as it doesn't filter my index table. The filter options are shown on the right side and you can also see the filtering options in the url and params after you choose a filter and hit the button.

utf8=✓&q%5Buser_id_eq%5D=3&commit=Filter&order=id_desc

But somehow the index table doesn't refresh.

The only scope I have is the default:

  scope :all, default: true

EDIT

I think it has something to do with the pagination because If i remove pagination the filters work again.

This is my current index method in my app/admin/DocumentType.rb file:

def index
  index! do |format|
    @document_types = DocumentType.where(archived_at: nil).page(params[:page])
    file_name = "document_types_#{DateTime.now.strftime('%a_%d_%b_%Y_%H%M%S').downcase}"

    format.xls {
      spreadsheet = DocumentTypesSpreadsheet.new @document_types
      send_data spreadsheet.generate_xls, filename: file_name + ".xls"
    }
  end
end

Only document types which are not archived should be displayed in the index therefore i have

@document_types = DocumentType.where(archived_at: nil).page(params[:page])

Now with this my filter don't work. But if I remove this line completely they work again except now it displays also the archived document types. And if I remove the .page(params[:page]) part I get the following error message:

 Collection is not a paginated scope. Set collection.page(params[:page]).per(10) before calling :paginated_collection.

Body:
Try to update your controller with this

def index
  index! do |format|
    @document_types = DocumentType.where(archived_at: nil).ransack(params[:q]).result
    file_name = "document_types_#{DateTime.now.strftime('%a_%d_%b_%Y_%H%M%S').downcase}"

    format.xls {
      spreadsheet = DocumentTypesSpreadsheet.new @document_types
      send_data spreadsheet.generate_xls, filename: file_name + ".xls"
    }
  end
end

But you need to be sure, you deisplay the records with this condition as well:

.where(archived_at: nil)

because the exported result will be different with displayed


问:
jQuery sortable is not a function
I am trying to make an ordered list of items click-and-draggable with the Sortable jQuery UI plugin version 1.8.16. However, I keep getting the error that $("#ol-id ol").sortable is not a function, with 'ol-id' being the id of the list. My code is as follows:

```<code>//Sorting stuff
if($("#li-id li").size()>1) {
    $("#ol-id ol").sortable({
        revert:         true,
        axis:           'y',
        containment:    'parent',
        cursor:         'move',
        handle:         'div.link_div',
        smooth:         false,
        opacity:        0.7,
        tolerance:      'pointer',
        start: function(){
            $("#ol-id").removeClass("bottom_dragged");
        },
        update: function(){
            $("#ol-id ol").sortable({disabled : true});
            $("#saving_indicator").html("saving...")
            $("#saving_indicator").show();
                            //do other stuff...
        }
    })
}
</code>```

Oddly, the error shows up in Firebug as being on the line with update: function(){.

I have verified that this function is called after both the page is loaded and the jQuery UI library is loaded. I am including both jquery-1.6.2.min.js and jquery-ui-1.8.16.custom.min.js in the header. Moreover, I have verified that all id names are correct and match their HTML counterparts.

So if it's not this missing resource-related stuff, what is causing the problem?

EDIT: here is my HTML header:

```<code><link href="/_css/styles.css?mod=1317745564" type="text/css" rel="stylesheet">
<link href="/_javascript/qtip/jquery.qtip.min.css?mod=1315947301" type="text/css" rel="stylesheet">
<script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js">
<script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/start/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/le-frog/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js" type="text/javascript">
<script src="/_javascript/sets.js?mod=1320080042" type="text/javascript"> //Sorting stuff code is here
<script type="text/javascript" src="http://dev.selfcheck.vudat.msu.edu/_javascript/jquery.jsonp.js">
<script type="text/javascript" src="http://dev.selfcheck.vudat.msu.edu/_javascript/jquery.form.js">
<script type="text/javascript" src="http://dev.selfcheck.vudat.msu.edu/_javascript/qtip/jquery.qtip.min.js">
<link href="/_css/ui/ui.core.css?mod=1315947279" type="text/css" rel="stylesheet">
<link href="/_css/ui/ui.theme.css?mod=1315947280" type="text/css" rel="stylesheet">
</code>```

答:
i have found new solution,
just edit acf.php file at line number 551

old

```<code> 'deps'      => array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker', 'underscore', 'select2'),
</code>```

new

```<code> 'deps'      => array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker', 'jquery-ui-sortable', 'underscore', 'select2'),
</code>```

i just added jquery-ui-sortable in array
i hope help someone
thank you.

Title: jQuery sortable is not a function

Body:
I am trying to make an ordered list of items click-and-draggable with the Sortable jQuery UI plugin version 1.8.16. However, I keep getting the error that $("#ol-id ol").sortable is not a function, with 'ol-id' being the id of the list. My code is as follows:

//Sorting stuff
if($("#li-id li").size()>1) {
    $("#ol-id ol").sortable({
        revert:         true,
        axis:           'y',
        containment:    'parent',
        cursor:         'move',
        handle:         'div.link_div',
        smooth:         false,
        opacity:        0.7,
        tolerance:      'pointer',
        start: function(){
            $("#ol-id").removeClass("bottom_dragged");
        },
        update: function(){
            $("#ol-id ol").sortable({disabled : true});
            $("#saving_indicator").html("saving...")
            $("#saving_indicator").show();
                            //do other stuff...
        }
    })
}

Oddly, the error shows up in Firebug as being on the line with update: function(){.

I have verified that this function is called after both the page is loaded and the jQuery UI library is loaded. I am including both jquery-1.6.2.min.js and jquery-ui-1.8.16.custom.min.js in the header. Moreover, I have verified that all id names are correct and match their HTML counterparts.

So if it's not this missing resource-related stuff, what is causing the problem?

EDIT: here is my HTML header:

<link href="/_css/styles.css?mod=1317745564" type="text/css" rel="stylesheet">
<link href="/_javascript/qtip/jquery.qtip.min.css?mod=1315947301" type="text/css" rel="stylesheet">

Body:
i have found new solution,
just edit acf.php file at line number 551

old

 'deps'      => array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker', 'underscore', 'select2'),

new

 'deps'      => array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker', 'jquery-ui-sortable', 'underscore', 'select2'),

i just added jquery-ui-sortable in array
i hope help someone
thank you.


问:
Magento 2 API: How do I list products as a customer or anonymous user
I'm build a mobile app that uses magento 2 REST API. So in this I can add products to cart and even complete an order. But it seems to me that I cant list products or categories as a customer or guest user. As an admin I can do that. This is the error that I get

```<code>{
  "message": "Consumer is not authorized to access %resources",
  "parameters": {
    "resources": "Magento_Catalog::categories"
  }
}
</code>```

Is there a way I can use the "/V1/products" API as a customer or guest?

I guess the only other option I have is to build my own customer API that lists products/categories for anonymous users.

答:
there is a specific settings to allow anonymous user access to hidden rest API endpoints:

Configuration > Services > Magento Web API > Web API Security. Then select Yes from the Allow Anonymous Guest Access menu.

Reference: http://devdocs.magento.com/guides/v2.0/rest/anonymous-api-security.html

Body:
I'm build a mobile app that uses magento 2 REST API. So in this I can add products to cart and even complete an order. But it seems to me that I cant list products or categories as a customer or guest user. As an admin I can do that. This is the error that I get

{
  "message": "Consumer is not authorized to access %resources",
  "parameters": {
    "resources": "Magento_Catalog::categories"
  }
}

Is there a way I can use the "/V1/products" API as a customer or guest?

I guess the only other option I have is to build my own customer API that lists products/categories for anonymous users.


问:
Calculating available bandwidth
I need write a code in C++ in Windows , to calculate available bandwidth.
I'm currently planing to use spruce algorithm.
i wanted to know is there any code available for this algorithm in windows .
or is there any other technique to get the internet bandwidth.</p>

答: thrulay is another network capacity tester, which along with calculating the bandwidth, does the rtt and uses median for summarizing delay which as it's author Stanislav Shalunov in Mean Delay Considered Harmful is right as averages are mostly meaningless if the distribution from which the samples are taken isn't fixed</p>

Title: Calculating available bandwidth


问:
Why doesn't "cp -a" also copy and preserve all git files?
Because of some directory changes, I need to copy my local development directory to a new location. This development directory is using git to sync to a external git repo. Recently there were some new file changes made that was not committed and pushed to that external repo. My wish is to just copy everything to a new directory and continue git'ing where I left of.

In original directory:

```<code>~/original_dir $ git status

On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   .idea/misc.xml
    modified:   ...

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    ../README.md
    ...

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

After doing cp -a ~/original_dir ~/new_dir, I simply get:

```<code>~/new_dir $ git status

fatal: Not a git repository (or any of the parent directories): .git
</code>```

Inspection shows that .git is missing from root directory of copy. This is quite concerning as I have been using cp -a for backups. Which mean that cp -a cannot be trusted to copy everything. (According to man pages, -a is "same as -dR --preserve=all".)

What is the proper cp command to have an exact snapshot of that directory?

NOTE: Using tar -cf old_dir.tar old_dir and then extracting this, does yield an exact directory copy, that can also be used to continue your git operations as you left off.

答:
Thanks to links in OP comments, I think I found two answers.

(1) Apparently my Bash has the dotglob shell option off by default, it need to be on.

```<code>$ shopt
...
dotglob         off
...
</code>```

(2) A very subtle trick is to specify a trailing dot in the copy command, and that the destination directory already exists:

```<code>cp -a old_dir/. new_dir/
</code>```

Second one I still need to test.

Body:
Because of some directory changes, I need to copy my local development directory to a new location. This development directory is using git to sync to a external git repo. Recently there were some new file changes made that was not committed and pushed to that external repo. My wish is to just copy everything to a new directory and continue git'ing where I left of.

In original directory:

~/original_dir $ git status

On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   .idea/misc.xml
    modified:   ...

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    ../README.md
    ...

no changes added to commit (use "git add" and/or "git commit -a")

After doing cp -a ~/original_dir ~/new_dir, I simply get:

~/new_dir $ git status

fatal: Not a git repository (or any of the parent directories): .git

Inspection shows that .git is missing from root directory of copy. This is quite concerning as I have been using cp -a for backups. Which mean that cp -a cannot be trusted to copy everything. (According to man pages, -a is "same as -dR --preserve=all".)

What is the proper cp command to have an exact snapshot of that directory?

NOTE: Using tar -cf old_dir.tar old_dir and then extracting this, does yield an exact directory copy, that can also be used to continue your git operations as you left off.

Body:
Thanks to links in OP comments, I think I found two answers.

(1) Apparently my Bash has the dotglob shell option off by default, it need to be on.

$ shopt
...
dotglob         off
...

(2) A very subtle trick is to specify a trailing dot in the copy command, and that the destination directory already exists:

cp -a old_dir/. new_dir/

Second one I still need to test.


问:
Html.Actionlink not providing both parameters to Controller - nullable int exception
I am trying to pass two parameters into a controller to allow a simple Create process to happen.

My actionlink is:

```<code>Html.ActionLink("New EB", "Create", "Erroneous", new { id = Model.Id, customerId = Model.Customer.Id }, htmlAttributes: null)
</code>```

My Controller is:

```<code>[Route("{customerId}/{id}")]
    public ActionResult Create(int id, int customerId)
    {
        if (customerId == 0)
        {
            return HttpNotFound();
        }

        var customer = _context.Customers.Single(c => c.Id == customerId);

        if (customer == null)
        {
            return HttpNotFound();
        }

        var viewModel = new CreateErroneousBillViewModel
        {
            Id = id,
            CustomerId = customer.Id,
        };

        return View("CreateErroneousBillForm", viewModel);
    }
</code>```

However when clicking on the action link the url onl provides the first id and not the second like such:

```<code>http://localhost:65339/Erroneous/Create/24/
</code>```

Where 24 is the Id of customer

whereas I think it should be providing something like

```<code>http://localhost:65339/Erroneous/Create/24/1
</code>```

Where 1 is the Id

Any help appreciated, have been scratching my head over this for a while now.

Edit:

I have also tried setting absolute values to eliminate null values coming from the model

```<code>Html.ActionLink("New EB", "Create", "Erroneous", new { id = 1, customerId = 24 }, htmlAttributes: null)
</code>```

This also did not work.

答:
We resolved this.

I was making a silly error and changing the wrong ActionLink so the one that we were clicking in the UI turned out to be completely the wrong one.

Doh!

Body:
I am trying to pass two parameters into a controller to allow a simple Create process to happen.

My actionlink is:

Html.ActionLink("New EB", "Create", "Erroneous", new { id = Model.Id, customerId = Model.Customer.Id }, htmlAttributes: null)

My Controller is:

[Route("{customerId}/{id}")]
    public ActionResult Create(int id, int customerId)
    {
        if (customerId == 0)
        {
            return HttpNotFound();
        }

        var customer = _context.Customers.Single(c => c.Id == customerId);

        if (customer == null)
        {
            return HttpNotFound();
        }

        var viewModel = new CreateErroneousBillViewModel
        {
            Id = id,
            CustomerId = customer.Id,
        };

        return View("CreateErroneousBillForm", viewModel);
    }

However when clicking on the action link the url onl provides the first id and not the second like such:

http://localhost:65339/Erroneous/Create/24/

Where 24 is the Id of customer

whereas I think it should be providing something like

http://localhost:65339/Erroneous/Create/24/1

Where 1 is the Id

Any help appreciated, have been scratching my head over this for a while now.

Edit:

I have also tried setting absolute values to eliminate null values coming from the model

Html.ActionLink("New EB", "Create", "Erroneous", new { id = 1, customerId = 24 }, htmlAttributes: null)

This also did not work.


问:
Xcode 8 Shell Script Invocation Error
I'm trying to fix this issue for hours, but it still persists. Tried everything on the forums, nothing helped.
I'm using Cocoapods latest version 1.2.0.beta.1
When I try to build the project, it gives me this:

答: I'm using Carthage, the reason these errors came out was because I changed the target iOS version from iOS 10 to iOS 9, I solved this problem by running carthage update again.

Title: Xcode 8 Shell Script Invocation Error


问:
Shared preference for Multiuser
In my app , to store data I am using SharedPreferences. I am able to add and retrieve data from SharedPreferences. My problem is when I switched to New user,SharedPreferences are not creating for new user. It is always fetching data from owner not from Newuser. How to create SharedPreferences so it should create both owner and Newuser ?

Thanks

答:
use like this.

```<code>   SharedPreferences.Editor editor = getSharedPreferences("first user",         MODE_PRIVATE).edit();
    editor.putString("firstusername", "bcd");
     editor.putInt("password", 12);
       editor.commit();

   //for seconduser.

   SharedPreferences.Editor editor2 = getSharedPreferences("second user", MODE_PRIVATE).edit();
  editor2.putString("secondusername", "abc");
  editor2.putInt("password", 12);

  editor.commit();
</code>```

//for retriving.

```<code>      SharedPreferences prefs = getSharedPreferences("SharedPreferences   prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
   String restoredText = prefs.getString("firstusername", null);
   if (restoredText != null) {
    String name1 = prefs.getString("firstusername", "No name defined");

//    for seconduser retriving
SharedPreferences prefs = getSharedPreferences("SharedPreferences   prefs = getSharedPreferences("secon user", MODE_PRIVATE);
   String restoredText = prefs.getString("secondtusername", null);
   if (restoredText != null) {
    String name2 = prefs.getString("secondtusername", "No name defined");
</code>```

}

Title: Shared preference for Multiuser

Body:
use like this.

   SharedPreferences.Editor editor = getSharedPreferences("first user",         MODE_PRIVATE).edit();
    editor.putString("firstusername", "bcd");
     editor.putInt("password", 12);
       editor.commit();

   //for seconduser.

   SharedPreferences.Editor editor2 = getSharedPreferences("second user", MODE_PRIVATE).edit();
  editor2.putString("secondusername", "abc");
  editor2.putInt("password", 12);

  editor.commit();

//for retriving.

      SharedPreferences prefs = getSharedPreferences("SharedPreferences   prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
   String restoredText = prefs.getString("firstusername", null);
   if (restoredText != null) {
    String name1 = prefs.getString("firstusername", "No name defined");

//    for seconduser retriving
SharedPreferences prefs = getSharedPreferences("SharedPreferences   prefs = getSharedPreferences("secon user", MODE_PRIVATE);
   String restoredText = prefs.getString("secondtusername", null);
   if (restoredText != null) {
    String name2 = prefs.getString("secondtusername", "No name defined");

}


问:
QTableView scrolling stopped after dynamic resizing
I have a QTableView with a custom QSortFilterProxyModel for searching and sorting and a QSqlQueryModel for populating the table.

```<code>void ProxyModel::searchTable(QString name, QString type, QString date, QString time ){
    if(name_ != name)
        name_ = name;
    if(type_ != type)
        type_ = type;
    if(date_ != date)
        date_ = date;
    if(time_ != time)
        time_ = time;
    invalidateFilter();
}
bool ProxyModel::filterAcceptsRow(int source_row,
                                  const QModelIndex &source_parent) const{
    QModelIndex indName = sourceModel()->index(source_row,
                                               0, source_parent);
    QModelIndex indType= sourceModel()->index(source_row,
                                               4, source_parent);
    QModelIndex indDate = sourceModel()->index(source_row,
                                               2, source_parent);
    QModelIndex indTime = sourceModel()->index(source_row,
                                               3, source_parent);
    if(
              sourceModel()->data(indName).toString().toLower().contains(name_.toLower())
            &&sourceModel()->data(indType).toString().toLower().contains(type_.toLower())
            &&sourceModel()->data(indDate).toString().toLower().contains(date_.toLower())
            &&sourceModel()->data(indTime).toString().toLower().contains(time_.toLower())
       )
    {
        emit adjust();
        return true;
    }
    return false;
}
</code>```

After  a successful search, I emit a signal from my proxy model to a slot where it adjusts the table height to fit the size of the rows.
    connect(proxyModel, SIGNAL(adjust()), this, SLOT(dataChanged()));

And when the search button is clicked

connect(ui->searchBtn, &QToolButton::clicked, this, &AllVisitedPlaces::getSearchOptions);

I call the proxy model searchTable method with search parameters

```<code>void AllVisitedPlaces::getSearchOptions()
{
    proxyModel->searchTable(ui->nameLineEdit->text(),
                            ui->typeLineEdit->text(),
                            ui->dateLineEdit->text(),
                            ui->timeLineEdit->text());
     adjustTableSize();
}

void AllVisitedPlaces::dataChanged()
{
    adjustTableSize();
    this->verticalHeader->setSectionResizeMode(QHeaderView::ResizeToContents);

}

void AllVisitedPlaces::adjustTableSize()
{
     QRect rect = ui->table->geometry();
     int height = 0;
     for (int i =0; i < proxyModel->rowCount() ; i++)
         height+= ui->table->rowHeight(i);
     rect.setHeight(18 + ui->table->horizontalHeader()->height() + height);
         ui->table->setGeometry(rect);
         verticalHeader->setSectionResizeMode(QHeaderView::Stretch);
}
</code>```

The problem is, when the table re-sizes , I lose scrolling.
How can I fix that ?

Before re-sizing :

After re-sizing :

答:
Why would you expect scrolling when you've resized the table to fit its contents?

The likely problem is that your Ui is broken in other ways and the table is obscured: it has been resized, but you can't see that because whatever widget the table view sits in doesn't manage the table widget properly. But we can't tell for sure because you didn't minimize your code to provide a complete compileable example of what you're doing. We're talking about <100 lines of code in all - surely it wouldn't be a big deal to just paste such a main.cpp in your question. See e.g. example 1 or example 2.

This is a bad design anyway since you're presuming that the table will fit on screen. Yet it won't: once the resizing works, you'll end up with a vertically huge window that cannot be used as some of its corners will extend past the screen, with no way to reach them to see the contents or to resize the window.

Finally, once you properly use layouts in your Ui design, the setGeometry() call on any widget below top-level is a no-op: it's the layout that controls the child widget geometry. The solution then is not to set the widget's geometry, but to set its minimum size instead.

You're facing an XY Problem: you're dead set on a solution, without telling us what it is that you're trying to achieve and making sure first that what you're after makes sense (as in: that it will actually lead to a usable Ui!).

Body:
I have a QTableView with a custom QSortFilterProxyModel for searching and sorting and a QSqlQueryModel for populating the table.

void ProxyModel::searchTable(QString name, QString type, QString date, QString time ){
    if(name_ != name)
        name_ = name;
    if(type_ != type)
        type_ = type;
    if(date_ != date)
        date_ = date;
    if(time_ != time)
        time_ = time;
    invalidateFilter();
}
bool ProxyModel::filterAcceptsRow(int source_row,
                                  const QModelIndex &source_parent) const{
    QModelIndex indName = sourceModel()->index(source_row,
                                               0, source_parent);
    QModelIndex indType= sourceModel()->index(source_row,
                                               4, source_parent);
    QModelIndex indDate = sourceModel()->index(source_row,
                                               2, source_parent);
    QModelIndex indTime = sourceModel()->index(source_row,
                                               3, source_parent);
    if(
              sourceModel()->data(indName).toString().toLower().contains(name_.toLower())
            &&sourceModel()->data(indType).toString().toLower().contains(type_.toLower())
            &&sourceModel()->data(indDate).toString().toLower().contains(date_.toLower())
            &&sourceModel()->data(indTime).toString().toLower().contains(time_.toLower())
       )
    {
        emit adjust();
        return true;
    }
    return false;
}

After  a successful search, I emit a signal from my proxy model to a slot where it adjusts the table height to fit the size of the rows.
    connect(proxyModel, SIGNAL(adjust()), this, SLOT(dataChanged()));

And when the search button is clicked

connect(ui->searchBtn, &QToolButton::clicked, this, &AllVisitedPlaces::getSearchOptions);

I call the proxy model searchTable method with search parameters

void AllVisitedPlaces::getSearchOptions()
{
    proxyModel->searchTable(ui->nameLineEdit->text(),
                            ui->typeLineEdit->text(),
                            ui->dateLineEdit->text(),
                            ui->timeLineEdit->text());
     adjustTableSize();
}

void AllVisitedPlaces::dataChanged()
{
    adjustTableSize();
    this->verticalHeader->setSectionResizeMode(QHeaderView::ResizeToContents);

}

void AllVisitedPlaces::adjustTableSize()
{
     QRect rect = ui->table->geometry();
     int height = 0;
     for (int i =0; i < proxyModel->rowCount() ; i++)
         height+= ui->table->rowHeight(i);
     rect.setHeight(18 + ui->table->horizontalHeader()->height() + height);
         ui->table->setGeometry(rect);
         verticalHeader->setSectionResizeMode(QHeaderView::Stretch);
}

The problem is, when the table re-sizes , I lose scrolling.
How can I fix that ?

Before re-sizing :

After re-sizing :


问:
Wildcards in counter specifiers in Azure Diagnostic
What I am trying to achieve is similar to what you can see in mongo-azure repo, specifically, I want to write Azure Diagnostic Configuration File in such a way so that I can get all the instances of performance counters, for example

\Processor(*)\% Processor Time

and it doesn't seem to be working - no data is visible in the table in my storage account.

Is it achievable at all with configuration, and if so, how?

UPD: We were able to get this working for a simple single VM (so it is possible!), but for some reason it still doesn't work for VMs in VMSS where Service Fabric Cluster is running

UPD #2: We did upgrade to VS 2015 tools 1.5 and now it magically works. I am not really sure if that was the root cause problem or we screwed up anywhere else.

答:
Is it achievable at all with configuration, and if so, how?

Based on the documentation here, it seems it is not possible. From this link:

Performance counters available for Microsoft Azure

Azure provides a subset of the performance counters available for
  Windows Server, IIS and the ASP.NET stack. The following table lists
  some of the performance counters of particular interest for Azure
  applications.

Table that follows below only includes Processor(_Total).


问:
nginx shows default page instead of my site
i have three virtual machines and Apache on the first and second and nginx on the third here is my virtual hosts on the two Apache:

```<code><virtualHost 192.168.80.140:8080>
ServerName united.com
ServerAlias www.united.com
DocumentRoot /var/www/html/united.com
</VirtualHost>
</code>```

and:

```<code><virtualHost 192.168.80.137:8080>
ServerName united.com
ServerAlias www.united.com
DocumentRoot /var/www/html/united.com
</VirtualHost>
</code>```

and nginx conf:

```<code>user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
worker_connections  1024;
}

http {
   upstream loadbalancedbackend {
           server 192.168.80.140;
           server 192.168.80.137;
     }
server {
     location / {
            proxy pass http://loadbalancedbackend;
          }
     }
}
</code>```

also i set hosts file on my windows host machine:

```<code>192.168.80.150          www.united.com
</code>```

which is the ip of my nginx. so my problem is when i try to www.united.com from the browser it show nginx default page ?

答:
In your apache configuration, you have specified to listen on port 8080 for the virtual hosts, but in your nginx configuration you don't specify port (thus defaulting to port 80 for http). Try to replace </p>

```<code>server 192.168.80.140;
server 192.168.80.137;
</code>```

<p>with </p>

```<code>server 192.168.80.140:8080;
server 192.168.80.137:8080;
</code>```

Body:
i have three virtual machines and Apache on the first and second and nginx on the third here is my virtual hosts on the two Apache:

<virtualHost 192.168.80.140:8080>
ServerName united.com
ServerAlias www.united.com
DocumentRoot /var/www/html/united.com
</VirtualHost>

and:

<virtualHost 192.168.80.137:8080>
ServerName united.com
ServerAlias www.united.com
DocumentRoot /var/www/html/united.com
</VirtualHost>

and nginx conf:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
worker_connections  1024;
}

http {
   upstream loadbalancedbackend {
           server 192.168.80.140;
           server 192.168.80.137;
     }
server {
     location / {
            proxy pass http://loadbalancedbackend;
          }
     }
}

also i set hosts file on my windows host machine:

192.168.80.150          www.united.com

which is the ip of my nginx. so my problem is when i try to www.united.com from the browser it show nginx default page ?

Body:
In your apache configuration, you have specified to listen on port 8080 for the virtual hosts, but in your nginx configuration you don't specify port (thus defaulting to port 80 for http). Try to replace

server 192.168.80.140;
server 192.168.80.137;

with

server 192.168.80.140:8080;
server 192.168.80.137:8080;


问:
How to open windows explorer on selected resource in Eclipse
I was looking for a small plugin for Eclipse that would allow to open windows explorer on currently selected resource from Package Explorer tree.

I know that Aptana Studio provides this functionality via context menu on the resource, but it has tons of other stuff that I am not interested to.

Are there other solutions?

答:
StartExplorer doesn't work under my Ubuntu, but ExploreFS works. You can find it here:

http://junginger.biz/eclipse/

It supports Windows, Mac OS X, and Linux.


问:
How can I change image tintColor in iOS and WatchKit
I have an UIImageView called "theImageView", with UIImage in a single color (transparent background) just like the left black heart below. How can I change the tint color of this image programmatically in iOS 7 or above, as per the tint method used in the iOS 7+ Navigation Bar icons?

Can this method also work in WatchKit for an Apple Watch app?

答:
iOS

Solution for doing it from Interface Builder, set templateImage param in keyPath and choose your tint color from IB

```<code>extension UIImageView {

// make template image with tint color
var templateImage: Bool {
    set {
        if newValue, let image = self.image {
            let newImage = image.withRenderingMode(.alwaysTemplate)
            self.image = newImage
        }
    } get {
        return false
    }
}
</code>```

}

Body:
iOS

Solution for doing it from Interface Builder, set templateImage param in keyPath and choose your tint color from IB

extension UIImageView {

// make template image with tint color
var templateImage: Bool {
    set {
        if newValue, let image = self.image {
            let newImage = image.withRenderingMode(.alwaysTemplate)
            self.image = newImage
        }
    } get {
        return false
    }
}

}

ContentLicense: CC BY-SA 4.0


问:
How Can I See All Laravel Events Being Fired
How can I see all laravel events being fired or search for events that are specific to my use case. I should be able to see a list of events being fired during a single request.</p>

答:
you can install Laravel DebugBar: https://github.com/barryvdh/laravel-debugbar

and then on the config/debugbar.php

```<code>'collectors' => [
    <snip>
    'events' => true,
    <snip>
];
</code>```

you should then see a bar at the bottom page of your app:

Body:
you can install Laravel DebugBar: https://github.com/barryvdh/laravel-debugbar

and then on the config/debugbar.php

'collectors' => [
    <snip>
    'events' => true,
    <snip>
];

you should then see a bar at the bottom page of your app:


问:
vertx.io java + twitter4j - event loop integration
I'm trying to integrate twitter4j with vertx event loop and I don't know if I'm doing it the right way.
I'm new to vertx, although I'm a Node.js developer, so I'm familiar with the event loop/single thread concept.

In my test, I want to subscribe to a twitter stream and publish the stream on the vertx event bus.

I've created an agnostic TwitterAPI class which will transform the twitter stream into an Observable (this will be hooked to vertx later):

```<code>public class TwitterAPI {
    public Observable<Status> getTwitterObservable() {
        return Observable.create(emitter -> {
            final TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
            twitterStream.addListener(new StatusListener(){
                public void onStatus(Status status) {
                    emitter.onNext(status);
                }
                public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
                public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
                public void onException(Exception ex) {
                    emitter.onError(ex);
                }
                @Override
                public void onScrubGeo(long userId, long upToStatusId) {}

                @Override
                public void onStallWarning(StallWarning warning) {}
            });

            //twitterStream.filter("some keyword");
            twitterStream.sample();
        });
    }
}
</code>```

Then I created a TwitterVerticle, which will listen to the above Observable and publish the stream on the event bus, so some other verticles can subscribe to it and process it:

```<code>public class TwitterVerticle extends AbstractVerticle {
    public void start() {
        EventBus eb = this.vertx.eventBus();
        TwitterAPI twitterAPI = new TwitterAPI();
        twitterAPI.getTwitterObservable()
            .map(Status::getText)
            .filter(text -> text.startsWith("my keyword"))
            .subscribe(text -> {
                eb.publish("tweet-feed", text);
            });
    }
}
</code>```

For example, I created another verticle which will listen to "twitter-feed" on event bus and publish it on WebSocket, so you can see the feed in the browser.

Everything is working well at the first look...but...my main question is: I'm not sure twitter4j will play well with the event loop, maybe my integration technique is wrong. Maybe I should make TwitterVerticle a Worker Verticle?

Could somebody take a look and let me know if this is the best way to accomplish such task?

Thanks a lot!

EDIT

Publishing on event bus directly is a better pattern in this case?
Here is the modified code:

```<code>public class TwitterAPI {

    public void publishStreamOnEventBus(Vertx vertx) {
        EventBus eb = vertx.eventBus();
        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

        twitterStream.addListener(new StatusListener(){
            public void onStatus(Status status) {
                eb.publish("tweet-feed", status.getText());
            }
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
            public void onException(Exception ex) {
                //emitter.onError(ex);
            }
            @Override
            public void onScrubGeo(long userId, long upToStatusId) {}

            @Override
            public void onStallWarning(StallWarning warning) {}
        });

        twitterStream.sample();
    }
}

public class Main {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        new TwitterAPI().publishStreamOnEventBus(vertx);

        //vertx.deployVerticle(new TwitterVerticle()/*, new DeploymentOptions().setWorker(true)*/);
        vertx.deployVerticle(new WebServerVerticle());
    }

}
</code>```

答:
First a couple of general recommendations.

1/ If subscribing to an Observable involves invoking blocking APIs, use a blockingScheduler:

```<code>Scheduler blockingScheduler = io.vertx.rx.java.RxHelper.blockingScheduler(vertx);
Observable<String> obs = twitterObservable.subscribeOn(blockingScheduler);
</code>```

2/ Then I assume twitter4j uses its own threads to invoke the StatusListener, so the EventBus#publish call will be made on one of those. To come back to the verticle context use the #observeOn operator:

```<code>Scheduler contextScheduler = io.vertx.rx.java.RxHelper.scheduler(context);
Observable<String> obs = twitterObservable.observeOn(contextScheduler);
</code>```

Combining the two changes:

```<code>public class TwitterVerticle extends AbstractVerticle {
    public void start() {
        EventBus eb = this.vertx.eventBus();
        Scheduler contextScheduler = io.vertx.rx.java.RxHelper.scheduler(context);
        Scheduler blockingScheduler = io.vertx.rx.java.RxHelper.blockingScheduler(vertx);
        TwitterAPI twitterAPI = new TwitterAPI();
        twitterAPI.getTwitterObservable()
            .map(Status::getText)
            .filter(text -> text.startsWith("my keyword"))
            .observeOn(contextScheduler)
            .subscribeOn(blockingScheduler)
            .subscribe(text -> {
                eb.publish("tweet-feed", text);
            });
    }
}
</code>```

All that said, if this the only job of the verticle, I would recommend to get rid of it and simply publish to the event bus. The event bus instance is thread safe and it's perfectly fine to invoke publish from the outside (non Vert.x) world. Actually, this is a good pattern to combine Vert.x code with legacy code.

Body:
I'm trying to integrate twitter4j with vertx event loop and I don't know if I'm doing it the right way.
I'm new to vertx, although I'm a Node.js developer, so I'm familiar with the event loop/single thread concept.

In my test, I want to subscribe to a twitter stream and publish the stream on the vertx event bus.

I've created an agnostic TwitterAPI class which will transform the twitter stream into an Observable (this will be hooked to vertx later):

public class TwitterAPI {
    public Observable<Status> getTwitterObservable() {
        return Observable.create(emitter -> {
            final TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
            twitterStream.addListener(new StatusListener(){
                public void onStatus(Status status) {
                    emitter.onNext(status);
                }
                public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
                public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
                public void onException(Exception ex) {
                    emitter.onError(ex);
                }
                @Override
                public void onScrubGeo(long userId, long upToStatusId) {}

                @Override
                public void onStallWarning(StallWarning warning) {}
            });

            //twitterStream.filter("some keyword");
            twitterStream.sample();
        });
    }
}

Then I created a TwitterVerticle, which will listen to the above Observable and publish the stream on the event bus, so some other verticles can subscribe to it and process it:

public class TwitterVerticle extends AbstractVerticle {
    public void start() {
        EventBus eb = this.vertx.eventBus();
        TwitterAPI twitterAPI = new TwitterAPI();
        twitterAPI.getTwitterObservable()
            .map(Status::getText)
            .filter(text -> text.startsWith("my keyword"))
            .subscribe(text -> {
                eb.publish("tweet-feed", text);
            });
    }
}

For example, I created another verticle which will listen to "twitter-feed" on event bus and publish it on WebSocket, so you can see the feed in the browser.

Everything is working well at the first look...but...my main question is: I'm not sure twitter4j will play well with the event loop, maybe my integration technique is wrong. Maybe I should make TwitterVerticle a Worker Verticle?

Could somebody take a look and let me know if this is the best way to accomplish such task?

Thanks a lot!

EDIT

Publishing on event bus directly is a better pattern in this case?
Here is the modified code:

public class TwitterAPI {

    public void publishStreamOnEventBus(Vertx vertx) {
        EventBus eb = vertx.eventBus();
        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

        twitterStream.addListener(new StatusListener(){
            public void onStatus(Status status) {
                eb.publish("tweet-feed", status.getText());
            }
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
            public void onException(Exception ex) {
                //emitter.onError(ex);
            }
            @Override
            public void onScrubGeo(long userId, long upToStatusId) {}

            @Override
            public void onStallWarning(StallWarning warning) {}
        });

        twitterStream.sample();
    }
}

public class Main {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        new TwitterAPI().publishStreamOnEventBus(vertx);

        //vertx.deployVerticle(new TwitterVerticle()/*, new DeploymentOptions().setWorker(true)*/);
        vertx.deployVerticle(new WebServerVerticle());
    }

}

Body:
First a couple of general recommendations.

1/ If subscribing to an Observable involves invoking blocking APIs, use a blockingScheduler:

Scheduler blockingScheduler = io.vertx.rx.java.RxHelper.blockingScheduler(vertx);
Observable<String> obs = twitterObservable.subscribeOn(blockingScheduler);

2/ Then I assume twitter4j uses its own threads to invoke the StatusListener, so the EventBus#publish call will be made on one of those. To come back to the verticle context use the #observeOn operator:

Scheduler contextScheduler = io.vertx.rx.java.RxHelper.scheduler(context);
Observable<String> obs = twitterObservable.observeOn(contextScheduler);

Combining the two changes:

public class TwitterVerticle extends AbstractVerticle {
    public void start() {
        EventBus eb = this.vertx.eventBus();
        Scheduler contextScheduler = io.vertx.rx.java.RxHelper.scheduler(context);
        Scheduler blockingScheduler = io.vertx.rx.java.RxHelper.blockingScheduler(vertx);
        TwitterAPI twitterAPI = new TwitterAPI();
        twitterAPI.getTwitterObservable()
            .map(Status::getText)
            .filter(text -> text.startsWith("my keyword"))
            .observeOn(contextScheduler)
            .subscribeOn(blockingScheduler)
            .subscribe(text -> {
                eb.publish("tweet-feed", text);
            });
    }
}

All that said, if this the only job of the verticle, I would recommend to get rid of it and simply publish to the event bus. The event bus instance is thread safe and it's perfectly fine to invoke publish from the outside (non Vert.x) world. Actually, this is a good pattern to combine Vert.x code with legacy code.


问:
Remove identical entries that have true value on a column in Excel 2016
I have a table that kinda looks like this:

```<code>WebDocumentId   To remove
675082          0
675082          0
675082          0
675083          0
675083          1
675083          0
675083          0
675083          0
675085          1
675085          0
675087          0
675087          0
675087          1
675087          0
675089          0
675089          0
675089          0
675089          0
</code>```

My aim is to somehow remove all the identical entries for which 1 appears at least once in the 'to remove' column. A simple VLOOKUP on a third column would have worked if 1 was the first value of an id.

Summing up, the final table should look like this:

```<code>WebDocumentId   To remove
675082          0
675082          0
675082          0
675089          0
675089          0
675089          0
675089          0
</code>```

Thanks in advance!

答:
See below. Some important notes about this code:

It's going to be very slow if your list is long. It creates a list
of all items with a '1' in column B and then loops through that list
for every entry in column A.

It doesn't address potential duplicates in column B. In other words
if you have a document that is marked "to remove" twice then it will
check twice which is inefficient.

It doesn't handle blanks in column A.

It deletes the entire row and not just columns A & B. If you have
data in columns C or greater, that data will be deleted. Please use
caution.

```<code>Option Explicit

Sub RemoveEntries()

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    Dim startRow As Long
    startRow = 2

    Dim endRow As Long
    endRow = ws.UsedRange.Rows.Count

    ' make a list of IDs to delete
    Dim rowsToDelete() As String
    Dim arraySize As Long
    arraySize = -1  ' note this isn't zero

    Dim row As Long
    For row = startRow To endRow
        If ws.Cells(row, 2).Value = 1 Then
            arraySize = arraySize + 1
            ReDim Preserve rowsToDelete(arraySize)
            rowsToDelete(arraySize) = ws.Cells(row, 1)
        End If
    Next row

    ' delete the rows
    Dim checkRow As Long
    For row = endRow To startRow Step -1 ' note that we're starting at the bottom
       For checkRow = 0 To UBound(rowsToDelete)
        If ws.Cells(row, 1).Value = rowsToDelete(checkRow) Then
            ws.Rows(row).Delete
            Exit For
        End If
       Next checkRow
    Next row

End Sub
</code>```

Body:
I have a table that kinda looks like this:

WebDocumentId   To remove
675082          0
675082          0
675082          0
675083          0
675083          1
675083          0
675083          0
675083          0
675085          1
675085          0
675087          0
675087          0
675087          1
675087          0
675089          0
675089          0
675089          0
675089          0

My aim is to somehow remove all the identical entries for which 1 appears at least once in the 'to remove' column. A simple VLOOKUP on a third column would have worked if 1 was the first value of an id.

Summing up, the final table should look like this:

WebDocumentId   To remove
675082          0
675082          0
675082          0
675089          0
675089          0
675089          0
675089          0

Thanks in advance!

Body:
See below. Some important notes about this code:

It's going to be very slow if your list is long. It creates a list
of all items with a '1' in column B and then loops through that list
for every entry in column A.

It doesn't address potential duplicates in column B. In other words
if you have a document that is marked "to remove" twice then it will
check twice which is inefficient.

It doesn't handle blanks in column A.

It deletes the entire row and not just columns A & B. If you have
data in columns C or greater, that data will be deleted. Please use
caution.

Option Explicit

Sub RemoveEntries()

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    Dim startRow As Long
    startRow = 2

    Dim endRow As Long
    endRow = ws.UsedRange.Rows.Count

    ' make a list of IDs to delete
    Dim rowsToDelete() As String
    Dim arraySize As Long
    arraySize = -1  ' note this isn't zero

    Dim row As Long
    For row = startRow To endRow
        If ws.Cells(row, 2).Value = 1 Then
            arraySize = arraySize + 1
            ReDim Preserve rowsToDelete(arraySize)
            rowsToDelete(arraySize) = ws.Cells(row, 1)
        End If
    Next row

    ' delete the rows
    Dim checkRow As Long
    For row = endRow To startRow Step -1 ' note that we're starting at the bottom
       For checkRow = 0 To UBound(rowsToDelete)
        If ws.Cells(row, 1).Value = rowsToDelete(checkRow) Then
            ws.Rows(row).Delete
            Exit For
        End If
       Next checkRow
    Next row

End Sub


问:
Dynamic default value for Kendo Grid
I want an auto increment column in my Kendo Grid. This field isn't server side auto increment, because I want the user to see the value and be able to change it.

My current solution is to add a click attribute to Create button and loop over rows to find the highest value and increment it.

But how can I insert this value inside the newly created row? Click event happens before the new row is created.

So there is two possible solution:

Have a variable as default value and update it in my JS code.

Access the newly created row somehow, and update the value.

This is my JS code:

```<code>function createClick(id) {
    var grid = $("#" + id).data('kendoGrid');
    var highestRadif = 0;
    grid.tbody.find('>tr').each(function () {
        var dataItem = grid.dataItem(this);
        var radif = dataItem.SRadifReqR;
        highestRadif = highestRadif < radif ? radif : highestRadif;
    })
    alert(++highestRadif);
}
</code>```

答:
I was able to put a function in the datasource schema for this.</p>

```<code>schema: {
    model: {
        id: "id",
        fields: {
            currencyType: { defaultValue: getDefaultCurrency },
            invoiceDate: { type: "date" }
        }
    }
}

    function getDefaultCurrency() {
        return _.find(vm.currencyTypes, { id: vm.currencyId });
    };
</code>```

Title: Dynamic default value for Kendo Grid

Body:
I want an auto increment column in my Kendo Grid. This field isn't server side auto increment, because I want the user to see the value and be able to change it.

My current solution is to add a click attribute to Create button and loop over rows to find the highest value and increment it.

But how can I insert this value inside the newly created row? Click event happens before the new row is created.

So there is two possible solution:

Have a variable as default value and update it in my JS code.

Access the newly created row somehow, and update the value.

This is my JS code:

function createClick(id) {
    var grid = $("#" + id).data('kendoGrid');
    var highestRadif = 0;
    grid.tbody.find('>tr').each(function () {
        var dataItem = grid.dataItem(this);
        var radif = dataItem.SRadifReqR;
        highestRadif = highestRadif < radif ? radif : highestRadif;
    })
    alert(++highestRadif);
}

Body:
I was able to put a function in the datasource schema for this.

schema: {
    model: {
        id: "id",
        fields: {
            currencyType: { defaultValue: getDefaultCurrency },
            invoiceDate: { type: "date" }
        }
    }
}

    function getDefaultCurrency() {
        return _.find(vm.currencyTypes, { id: vm.currencyId });
    };


问:
C# Inheritance misconception
Let's say that we have 2 classes. The first one is Person

```<code>    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace People
    {
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }
</code>```

The second one is Teacher

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}
</code>```

And I want to make a teacher object using this syntax Person teacher = new Teacher(); When I make it and I try to refer to the Position property, I can't... Why does this happen? I can instead use this syntax Person teacher = new Teacher() {Position="boss" }; but even though, after that I can't refer to the teacher position using "teacher.Position".

答:
The problem is caused by the type of the reference. In the declaration

```<code>Person teacher = new Teacher() { Position="boss" };
</code>```

the right-hand side creates a new object of type Teacher and also initializes the Position property. However, the reference teacher is of type Person. While the object referred to by teacher is actually of type Teacher, the reference itself is of the more general type Person.

Informally speaking, in the above declaration you state that you want to refer teacher to a Person, regardless of whether it is of the more derived type Teacher, so the reference itself does not 'know' that it refers to the more special type Teacher and therefor does not 'know' that there is a Position property.

More technically speaking, this is necessary because at runtime it would be possible to let teacher refer to other objects deriving from Person, say Student or Wizard, which would perhaps also would not have a Position property.

Title: C# Inheritance misconception

Body:
Let's say that we have 2 classes. The first one is Person

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace People
    {
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }

The second one is Teacher

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}

And I want to make a teacher object using this syntax Person teacher = new Teacher(); When I make it and I try to refer to the Position property, I can't... Why does this happen? I can instead use this syntax Person teacher = new Teacher() {Position="boss" }; but even though, after that I can't refer to the teacher position using "teacher.Position".

Body:
The problem is caused by the type of the reference. In the declaration

Person teacher = new Teacher() { Position="boss" };

the right-hand side creates a new object of type Teacher and also initializes the Position property. However, the reference teacher is of type Person. While the object referred to by teacher is actually of type Teacher, the reference itself is of the more general type Person.

Informally speaking, in the above declaration you state that you want to refer teacher to a Person, regardless of whether it is of the more derived type Teacher, so the reference itself does not 'know' that it refers to the more special type Teacher and therefor does not 'know' that there is a Position property.

More technically speaking, this is necessary because at runtime it would be possible to let teacher refer to other objects deriving from Person, say Student or Wizard, which would perhaps also would not have a Position property.