问:
Laravel 5.4 Assert Mail Sent Not Working
I'm trying to assert mail sent with Laravel 5.4 fakes.

My test code is this:

```<code>public function setUp()
{
    parent::setUp();

    $this->admin = create(User::class, [
        'is_admin' => true,
    ]);

    $this->faker = Factory::create();
}

/** @test */
public function only_super_admin_can_create_admin()
{
    $admin = [
        'name'  => $this->faker->name,
        'email' => $this->faker->email,
    ];

    Mail::fake();

    $this->signIn($this->admin)
         ->post('/admins', $admin)
         ->assertRedirect('/admins');

    Mail::assertSent(NewUser::class, function ($mail) use ($admin) {
        dd($mail);
        // return $mail->hasTo($admin['email']);
    });

    $this->assertDatabaseHas('users', $admin);
}
</code>```

When the $mail is dumped I am getting the following:

```<code>App\Mail\NewUser {#722
  #user: App\Models\User {#726
    #fillable: array:6 [
      0 => "name"
      1 => "email"
      2 => "password"
      3 => "role"
      4 => "is_admin"
      5 => "id"
    ]
    #hidden: array:2 [
      0 => "password"
      1 => "remember_token"
    ]
    #connection: "testing"
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: true
    #attributes: array:7 [
      "name" => "Dave Ortiz"
      "email" => "prosacco.dejuan@gmail.com"
      "password" => "$2y$10$OGiQJJ/HCOIlbAl/t6tbpuz4WLQenLRVZgFPN/0e0P.3Ft9542OW2"
      "is_admin" => true
      "updated_at" => "2017-06-03 11:06:56"
      "created_at" => "2017-06-03 11:06:56"
      "id" => 2
    ]
    #original: array:7 [
      "name" => "Dave Ortiz"
      "email" => "prosacco.dejuan@gmail.com"
      "password" => "$2y$10$OGiQJJ/HCOIlbAl/t6tbpuz4WLQenLRVZgFPN/0e0P.3Ft9542OW2"
      "is_admin" => true
      "updated_at" => "2017-06-03 11:06:56"
      "created_at" => "2017-06-03 11:06:56"
      "id" => 2
    ]
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #events: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #visible: []
    #guarded: array:1 [
      0 => "*"
    ]
    #rememberTokenName: "remember_token"
  }
  #password: "ogDt9X87fM"
  +from: []
  +to: []
  +cc: []
  +bcc: []
  +replyTo: []
  +subject: null
  #markdown: null
  +view: null
  +textView: null
  +viewData: []
  +attachments: []
  +rawAttachments: []
  +callbacks: []
  +connection: null
  +queue: null
  +delay: null
}
</code>```

As you can see, it is showing nothing in the to array which means when I assert that the Mail was sent with hasTo() it fails:

```<code>1) Tests\Feature\SuperAdminTest::only_super_admin_can_create_admin
The expected [App\Mail\NewUser] mailable was not sent.
Failed asserting that false is true.
</code>```

My Controller stores the user as follows:

```<code>public function store(StoreUserRequest $request)
{
    $user = $request->storeUser(null, null, null, true);
    return redirect('/admins');
}
</code>```

The StoreUserRequest method is as follows:

```<code>public function storeUser($name = null, $email = null, $password = null, $admin = false)
{
    $password = $password ?: str_random(10);
    $user = User::create([
                             'name'     => ($name) ?: $this->name,
                             'email'    => ($email) ?: $this->email,
                             'password' => bcrypt($password),
                             'is_admin' => $admin,
                         ]);

    Mail::send(new NewUser($user, $password));

    return $user;
}
</code>```

The actual NewUser mailable is as follows:

```<code>class NewUser extends Mailable
{
    use Queueable, SerializesModels;

    protected $user;

    protected $password;

    /**
     * Create a new message instance.
     *
     * @param $user
     * @param $password
     */
    public function __construct($user, $password)
    {
        $this->user = $user;
        $this->password = $password;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.users.' . strtolower(($this->user->is_admin) ? 'Admin' : 'Client'))
                    ->with('user', $this->user)
                    ->with('password', $this->password)
                    ->to($this->user->email, $this->user->name)
                    ->subject('[' . $this->user->name . '] Your New ' . ($this->user->is_admin ? 'Admin' : 'Client') . ' Account');
    }
}
</code>```

Now what makes this even more weird is when I manually create a user on the app, the email will arrive!

Does anyone have any ideas why this won't work?

答:
You should attach to outside of the mailable, just like in the documentation:

StoreUserRequest

```<code>Mail::to($user->email)->send(new NewUser($user, $password));
</code>```

NewUser

```<code>public function build() {
    $account_type = $this->user->is_admin ? 'Admin' : 'Client';
    return $this->view('emails.users.' . strtolower($account_type)
        ->with([
            'user' => $this->user,
            'password' => $this->password
        ])
        ->subject("[${this->user->name}] Your New ${account_type} Account");
}
</code>```

Body:
I'm trying to assert mail sent with Laravel 5.4 fakes.

My test code is this:

public function setUp()
{
    parent::setUp();

    $this->admin = create(User::class, [
        'is_admin' => true,
    ]);

    $this->faker = Factory::create();
}

/** @test */
public function only_super_admin_can_create_admin()
{
    $admin = [
        'name'  => $this->faker->name,
        'email' => $this->faker->email,
    ];

    Mail::fake();

    $this->signIn($this->admin)
         ->post('/admins', $admin)
         ->assertRedirect('/admins');

    Mail::assertSent(NewUser::class, function ($mail) use ($admin) {
        dd($mail);
        // return $mail->hasTo($admin['email']);
    });

    $this->assertDatabaseHas('users', $admin);
}

When the $mail is dumped I am getting the following:

App\Mail\NewUser {#722
  #user: App\Models\User {#726
    #fillable: array:6 [
      0 => "name"
      1 => "email"
      2 => "password"
      3 => "role"
      4 => "is_admin"
      5 => "id"
    ]
    #hidden: array:2 [
      0 => "password"
      1 => "remember_token"
    ]
    #connection: "testing"
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: true
    #attributes: array:7 [
      "name" => "Dave Ortiz"
      "email" => "prosacco.dejuan@gmail.com"
      "password" => "$2y$10$OGiQJJ/HCOIlbAl/t6tbpuz4WLQenLRVZgFPN/0e0P.3Ft9542OW2"
      "is_admin" => true
      "updated_at" => "2017-06-03 11:06:56"
      "created_at" => "2017-06-03 11:06:56"
      "id" => 2
    ]
    #original: array:7 [
      "name" => "Dave Ortiz"
      "email" => "prosacco.dejuan@gmail.com"
      "password" => "$2y$10$OGiQJJ/HCOIlbAl/t6tbpuz4WLQenLRVZgFPN/0e0P.3Ft9542OW2"
      "is_admin" => true
      "updated_at" => "2017-06-03 11:06:56"
      "created_at" => "2017-06-03 11:06:56"
      "id" => 2
    ]
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #events: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #visible: []
    #guarded: array:1 [
      0 => "*"
    ]
    #rememberTokenName: "remember_token"
  }
  #password: "ogDt9X87fM"
  +from: []
  +to: []
  +cc: []
  +bcc: []
  +replyTo: []
  +subject: null
  #markdown: null
  +view: null
  +textView: null
  +viewData: []
  +attachments: []
  +rawAttachments: []
  +callbacks: []
  +connection: null
  +queue: null
  +delay: null
}

As you can see, it is showing nothing in the to array which means when I assert that the Mail was sent with hasTo() it fails:

1) Tests\Feature\SuperAdminTest::only_super_admin_can_create_admin
The expected [App\Mail\NewUser] mailable was not sent.
Failed asserting that false is true.

My Controller stores the user as follows:

public function store(StoreUserRequest $request)
{
    $user = $request->storeUser(null, null, null, true);
    return redirect('/admins');
}

The StoreUserRequest method is as follows:

public function storeUser($name = null, $email = null, $password = null, $admin = false)
{
    $password = $password ?: str_random(10);
    $user = User::create([
                             'name'     => ($name) ?: $this->name,
                             'email'    => ($email) ?: $this->email,
                             'password' => bcrypt($password),
                             'is_admin' => $admin,
                         ]);

    Mail::send(new NewUser($user, $password));

    return $user;
}

The actual NewUser mailable is as follows:

class NewUser extends Mailable
{
    use Queueable, SerializesModels;

    protected $user;

    protected $password;

    /**
     * Create a new message instance.
     *
     * @param $user
     * @param $password
     */
    public function __construct($user, $password)
    {
        $this->user = $user;
        $this->password = $password;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.users.' . strtolower(($this->user->is_admin) ? 'Admin' : 'Client'))
                    ->with('user', $this->user)
                    ->with('password', $this->password)
                    ->to($this->user->email, $this->user->name)
                    ->subject('[' . $this->user->name . '] Your New ' . ($this->user->is_admin ? 'Admin' : 'Client') . ' Account');
    }
}

Now what makes this even more weird is when I manually create a user on the app, the email will arrive!

Does anyone have any ideas why this won't work?

Body:
You should attach to outside of the mailable, just like in the documentation:

StoreUserRequest

Mail::to($user->email)->send(new NewUser($user, $password));

NewUser

public function build() {
    $account_type = $this->user->is_admin ? 'Admin' : 'Client';
    return $this->view('emails.users.' . strtolower($account_type)
        ->with([
            'user' => $this->user,
            'password' => $this->password
        ])
        ->subject("[${this->user->name}] Your New ${account_type} Account");
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
getting access violation error while accessing allocated memory
I have allocated memory of 100 MB using malloc

```<code>block = (char *)malloc(sizeof(10485760));  // char *block is a global variable
</code>```

and then I assigned value in block to some local variable say localblock

```<code>char *localblock = block;
</code>```

when I tried to access location after 1 MB and copying string in that location im getting access violation error

```<code>int si = 1048576;

for (int i=0; i < si; ++i)
    ++localptr;
</code>```

strcpy(localblock,"random_string"); <--- im getting error here .please help me

答:
```<code>block = (char *)malloc(sizeof(10485760));
</code>```

is allocating only sizeof(int) number of bytes, when you access memory beyond that its will end up accessing invalid memory and program might crash

ContentLicense: CC BY-SA 3.0

Body:
I have allocated memory of 100 MB using malloc

block = (char *)malloc(sizeof(10485760));  // char *block is a global variable

and then I assigned value in block to some local variable say localblock

char *localblock = block;

when I tried to access location after 1 MB and copying string in that location im getting access violation error

int si = 1048576;

for (int i=0; i < si; ++i)
    ++localptr;

strcpy(localblock,"random_string"); <--- im getting error here .please help me

Body:
block = (char *)malloc(sizeof(10485760));

is allocating only sizeof(int) number of bytes, when you access memory beyond that its will end up accessing invalid memory and program might crash


问:
Execute a function whenever a property of an observable changes in Knockout JS
I have a demo application where all the list items are observables. To achieve this I have used the mapping plugin on the array from which the list is created.

```<code>this.allItems = ko.mapping.fromJS([
    {name:"Annabelle"},
    {name:"Vertie"},
    {name:"Charles"},
    {name:"John"}
]);
</code>```

My question is - how to properly implement this kind of behavior in Knockout JS: whenever a property of an observable(any item of the list) changes a sort function is executed:

```<code>    this.sortList = function() {
    this.allItems(this.allItems().sort(function(a, b) { return a.name() > b.name();}).slice(0, 2));
};
</code>```

答:
First, you need to declare a view model class. Then, declare allItems as an observable array, but display to the user a different member, called say sortedItems, which should be a computed field. This computed field will use allItems internally, so KO will notice when allItems gets updated and will re-evaluate sortedItems too.</p>

```<code>function AppViewModel() {
var self = this;

this.allItems = ko.observableArray([
    {name:"Annabelle"},
    {name:"Vertie"},
    {name:"Charles"},
    {name:"John"}
]);

    this.sortedItems = ko.computed(function() {
        return self.allItems().sort(sortFunction);
    }, this);
}
</code>```

Body:
I have a demo application where all the list items are observables. To achieve this I have used the mapping plugin on the array from which the list is created.

this.allItems = ko.mapping.fromJS([
    {name:"Annabelle"},
    {name:"Vertie"},
    {name:"Charles"},
    {name:"John"}
]);

My question is - how to properly implement this kind of behavior in Knockout JS: whenever a property of an observable(any item of the list) changes a sort function is executed:

    this.sortList = function() {
    this.allItems(this.allItems().sort(function(a, b) { return a.name() > b.name();}).slice(0, 2));
};

Body:
First, you need to declare a view model class. Then, declare allItems as an observable array, but display to the user a different member, called say sortedItems, which should be a computed field. This computed field will use allItems internally, so KO will notice when allItems gets updated and will re-evaluate sortedItems too.

function AppViewModel() {
var self = this;

this.allItems = ko.observableArray([
    {name:"Annabelle"},
    {name:"Vertie"},
    {name:"Charles"},
    {name:"John"}
]);

    this.sortedItems = ko.computed(function() {
        return self.allItems().sort(sortFunction);
    }, this);
}


问:
Nested NSArray into UITableView
i have looked everywhere for this, but i am unable to find the exact answer... all have slight variations.

Anyway, i call a json page that returns the following (from the NSLog):

```<code>{
    messages =         {
        1 =             {
            Body = "This is the body of message 1";
            Title = "Message 1";
        };
        2 =             {
            Body = "This is the body of message 2";
            Title = "Message 2";
        };
    };
}
</code>```

I then save the data into a NSDictionary (called messageArray). (the array is a NSMutableArray)

then i do:

```<code>// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    NSLog(@"the message array = %@",messages );

    //this fails
    cell.textLabel.text = [messages objectAtIndex:indexPath.row];

return cell;
</code>```

the returned NSLog (so i am assuming my json array is working correctly):

```<code>the message array = {
1 =     {
    Body = "This is the body of message 1";
    Title = "Message 1";
};
2 =     {
    Body = "This is the body of message 2";
    Title = "Message 2";
};
</code>```

}

I understand that i am not labelling the textlabels.text correctly, but i am not sure how to go about looping through the "messages" array, to display all the "Title" values from the array, to display on my UITableView list.

i am certain i am missing something so simple... but it has eluded me until now. Any links welcome... i will keep searching myself....

答:
This call

```<code>cell.textLabel.text = [messages objectAtIndex:indexPath.row];
</code>```

looks like it is returning a dictionary, and you are trying to stuff it into a test field.  I would confirm that this is a dictionary first, something like:

```<code>NSLog(@"%@",  [messages objectAtIndex:indexPath.row])
</code>```

If that is not a string, that may be your problem.

To get the string you want, you might do something like:

```<code> [[messages objectAtIndex:indexPath.row] valueForKey:@"Title"]
</code>```

ContentLicense: CC BY-SA 2.5

Title: Nested NSArray into UITableView

Body:
i have looked everywhere for this, but i am unable to find the exact answer... all have slight variations.

Anyway, i call a json page that returns the following (from the NSLog):

{
    messages =         {
        1 =             {
            Body = "This is the body of message 1";
            Title = "Message 1";
        };
        2 =             {
            Body = "This is the body of message 2";
            Title = "Message 2";
        };
    };
}

I then save the data into a NSDictionary (called messageArray). (the array is a NSMutableArray)

then i do:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    NSLog(@"the message array = %@",messages );

    //this fails
    cell.textLabel.text = [messages objectAtIndex:indexPath.row];

return cell;

the returned NSLog (so i am assuming my json array is working correctly):

the message array = {
1 =     {
    Body = "This is the body of message 1";
    Title = "Message 1";
};
2 =     {
    Body = "This is the body of message 2";
    Title = "Message 2";
};

}

I understand that i am not labelling the textlabels.text correctly, but i am not sure how to go about looping through the "messages" array, to display all the "Title" values from the array, to display on my UITableView list.

i am certain i am missing something so simple... but it has eluded me until now. Any links welcome... i will keep searching myself....

Body:
This call

cell.textLabel.text = [messages objectAtIndex:indexPath.row];

looks like it is returning a dictionary, and you are trying to stuff it into a test field.  I would confirm that this is a dictionary first, something like:

NSLog(@"%@",  [messages objectAtIndex:indexPath.row])

If that is not a string, that may be your problem.

To get the string you want, you might do something like:

 [[messages objectAtIndex:indexPath.row] valueForKey:@"Title"]


问:
html tables alignment using css
I am trying to get my alignment for tables and a map on an html page.
It looks like this at the moment:

1,2,3 are all tables, using CSS:

```<code>table {float:left;
    border-collapse: collapse;
    width: 20%; margin: 10px
}
</code>```

and 4 is a googlemap using:

```<code>#location{width: 30%;
    float: left;
    margin: 10px;
    margin-top: 30px;
}
</code>```

I would like 3 to go beneath 2, with 4 always on the right:

答: You could simply put 2 and 3 together in a parent container and make that float: left. If the widths of your elements are narrow enough to allow them to be placed in three columns as shown in your question, this should be enough.

Title: html tables alignment using css

Body:
I am trying to get my alignment for tables and a map on an html page.
It looks like this at the moment:

1,2,3 are all tables, using CSS:

table {float:left;
    border-collapse: collapse;
    width: 20%; margin: 10px
}

and 4 is a googlemap using:

#location{width: 30%;
    float: left;
    margin: 10px;
    margin-top: 30px;
}

I would like 3 to go beneath 2, with 4 always on the right:


问:
Update TextBox while in Background Worker
Unable to update textbox value while in background worker,
value to be updated is sum of column("TaxableValue") of a datatable created inside background worker.
No Error message is prompted

On Button Click following event is raised

Private Sub btnCalcTax_Click(sender As Object, e As EventArgs) Handles btnCalcTax.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub
```

<p>I have created a function to calculate TAX.</p>

<pre class="lang-vb prettyprint-override"><code>Public Sub TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
    Dim finalfdtaxcalcdt As New DataTable
    finalfdtaxcalcdt.Columns.Clear()
    finalfdtaxcalcdt.Rows.Clear()
    Dim outlettyp As String = "POS"
    Dim taxcount As New DataTable
    Dim tax As New DataTable
    If finalfdtaxcalcdt.Columns.Count = 0 Then
        finalfdtaxcalcdt.Columns.Add("TaxID")
        finalfdtaxcalcdt.Columns.Add("TaxName")
        finalfdtaxcalcdt.Columns.Add("TaxableValue")
        finalfdtaxcalcdt.Columns.Add("TaxRate")
        finalfdtaxcalcdt.Columns.Add("SalesAmount")
        finalfdtaxcalcdt.Columns.Add("TaxAmount")
        finalfdtaxcalcdt.Columns.Add("SalesID")
        finalfdtaxcalcdt.Columns.Add("PurchaseID")
        finalfdtaxcalcdt.Columns.Add("TaxClassID")
    End If

    For i = 0 To BodyGridView.RowCount - 1
        If IsDBNull(BodyGridView.GetRowCellValue(i, "Particulars")) Then
            Exit Sub
        End If
        If BodyGridView.GetRowCellValue(i, "Particulars") <> "# End of List" Then
            Dim tempdt As New DataTable

            If isinterstate Then
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'TRUE'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'True'", tempdt)
            Else
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'False'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'False'", tempdt)
            End If

            Dim sum As Double = tempdt.Compute("SUM(TaxRate)", String.Empty)

            For j = 0 To tempdt.Rows.Count - 1
                If finalfdtaxcalcdt.Select("TaxID = '" + tempdt.Rows(j).Item(0).ToString + "'").Count = 0 Then
                    finalfdtaxcalcdt.Rows.Add()
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxID") = tempdt.Rows(j).Item("Tax_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxName") = tempdt.Rows(j).Item("TaxName").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate") = tempdt.Rows(j).Item("TaxRate").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount") = Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesID") = tempdt.Rows(j).Item("SalesAc_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxClassID") = tempdt.Rows(j).Item("TaxClassId").ToString
                    'finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("PurchaseID") = tempdt.Rows(j).Item("TaxRate").ToString
                Else
                    Dim index As Integer = finalfdtaxcalcdt.Rows.IndexOf(finalfdtaxcalcdt.Select("TaxId = '" + tempdt.Rows(j).Item(0).ToString + "'").FirstOrDefault())
                    finalfdtaxcalcdt.Rows(index).Item("SalesAmount") = Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) + Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(index).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(index).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(index).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                End If
            Next
        End If
    Next
    '        MsgBox(finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty).ToString + "1")
    '        TaxGridControl.DataSource = finalfdtaxcalcdt
    ''       TaxGridView.Columns("TaxID").Visible = False
    '     TaxGridView.Columns("SalesAmount").Visible = False
    '    TaxGridView.Columns("SalesID").Visible = False
    '   TaxGridView.Columns("PurchaseID").Visible = False
    '  TaxGridView.Columns("TaxClassID").Visible = False
    Dim k As String = finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty)
    TextBox1.Invoke(DirectCast(Sub() TextBox1.Text = k.ToString, MethodInvoker))
End Sub
</code>```

I am unable to update sum of column("TaxableValue") to Textbox1.text

Code For BackgroundWorker_DoWork is

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            TAXCALC()
 End Sub
```

答:
You need to use delegates.

MSDN Control.Invoke Method (Delegate)

Example:

Public Delegate Sub _TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
Public Sub TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
    If BodyGridView.InvokeRequired Then
        BodyGridView.Invoke(New _TAXCALC(AddressOf TAXCALC), itemname, rackrate, discountedrate, billdate)
    Else
        'Your code here'
    End If
End Sub
```

Hope that helps.

Body:
Unable to update textbox value while in background worker,
value to be updated is sum of column("TaxableValue") of a datatable created inside background worker.
No Error message is prompted

On Button Click following event is raised

Private Sub btnCalcTax_Click(sender As Object, e As EventArgs) Handles btnCalcTax.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub

I have created a function to calculate TAX.

Public Sub TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
    Dim finalfdtaxcalcdt As New DataTable
    finalfdtaxcalcdt.Columns.Clear()
    finalfdtaxcalcdt.Rows.Clear()
    Dim outlettyp As String = "POS"
    Dim taxcount As New DataTable
    Dim tax As New DataTable
    If finalfdtaxcalcdt.Columns.Count = 0 Then
        finalfdtaxcalcdt.Columns.Add("TaxID")
        finalfdtaxcalcdt.Columns.Add("TaxName")
        finalfdtaxcalcdt.Columns.Add("TaxableValue")
        finalfdtaxcalcdt.Columns.Add("TaxRate")
        finalfdtaxcalcdt.Columns.Add("SalesAmount")
        finalfdtaxcalcdt.Columns.Add("TaxAmount")
        finalfdtaxcalcdt.Columns.Add("SalesID")
        finalfdtaxcalcdt.Columns.Add("PurchaseID")
        finalfdtaxcalcdt.Columns.Add("TaxClassID")
    End If

    For i = 0 To BodyGridView.RowCount - 1
        If IsDBNull(BodyGridView.GetRowCellValue(i, "Particulars")) Then
            Exit Sub
        End If
        If BodyGridView.GetRowCellValue(i, "Particulars") <> "# End of List" Then
            Dim tempdt As New DataTable

            If isinterstate Then
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'TRUE'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'True'", tempdt)
            Else
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'False'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'False'", tempdt)
            End If

            Dim sum As Double = tempdt.Compute("SUM(TaxRate)", String.Empty)

            For j = 0 To tempdt.Rows.Count - 1
                If finalfdtaxcalcdt.Select("TaxID = '" + tempdt.Rows(j).Item(0).ToString + "'").Count = 0 Then
                    finalfdtaxcalcdt.Rows.Add()
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxID") = tempdt.Rows(j).Item("Tax_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxName") = tempdt.Rows(j).Item("TaxName").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate") = tempdt.Rows(j).Item("TaxRate").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount") = Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesID") = tempdt.Rows(j).Item("SalesAc_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxClassID") = tempdt.Rows(j).Item("TaxClassId").ToString
                    'finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("PurchaseID") = tempdt.Rows(j).Item("TaxRate").ToString
                Else
                    Dim index As Integer = finalfdtaxcalcdt.Rows.IndexOf(finalfdtaxcalcdt.Select("TaxId = '" + tempdt.Rows(j).Item(0).ToString + "'").FirstOrDefault())
                    finalfdtaxcalcdt.Rows(index).Item("SalesAmount") = Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) + Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(index).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(index).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(index).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                End If
            Next
        End If
    Next
    '        MsgBox(finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty).ToString + "1")
    '        TaxGridControl.DataSource = finalfdtaxcalcdt
    ''       TaxGridView.Columns("TaxID").Visible = False
    '     TaxGridView.Columns("SalesAmount").Visible = False
    '    TaxGridView.Columns("SalesID").Visible = False
    '   TaxGridView.Columns("PurchaseID").Visible = False
    '  TaxGridView.Columns("TaxClassID").Visible = False
    Dim k As String = finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty)
    TextBox1.Invoke(DirectCast(Sub() TextBox1.Text = k.ToString, MethodInvoker))
End Sub

I am unable to update sum of column("TaxableValue") to Textbox1.text

Code For BackgroundWorker_DoWork is

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            TAXCALC()
 End Sub

Body:
You need to use delegates.

MSDN Control.Invoke Method (Delegate)

Example:

Public Delegate Sub _TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
Public Sub TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
    If BodyGridView.InvokeRequired Then
        BodyGridView.Invoke(New _TAXCALC(AddressOf TAXCALC), itemname, rackrate, discountedrate, billdate)
    Else
        'Your code here'
    End If
End Sub

Hope that helps.


问:
Xamarin Studio: Rebuild project error with error : The "DebugType" parameter is not supported by the "XamlCTask" task
I have managed to rebuild the project by remove the line DebugType = "$(DebugType)" in the xml file below. What does this line really do and why it can fix my problem. I have the error because I pulling the new code from source tree.

```<code><Target Name="XamlC">
    <XamlCTask
        Assembly = "$(IntermediateOutputPath)$(TargetFileName)"
        ReferencePath = "@(ReferencePath)"
        Verbosity = "2"
        OptimizeIL = "true"
        DebugSymbols = "$(DebugSymbols)"
        />
</Target>
</code>```

答:
I solved this problem by simply restarting Visual Studio and doing a rebuild in the solution.

I did nothing, and the project worked.

Following this thought, in your case, restarting Xamarin Studio should resolve.

Body:
I have managed to rebuild the project by remove the line DebugType = "$(DebugType)" in the xml file below. What does this line really do and why it can fix my problem. I have the error because I pulling the new code from source tree.

<Target Name="XamlC">
    <XamlCTask
        Assembly = "$(IntermediateOutputPath)$(TargetFileName)"
        ReferencePath = "@(ReferencePath)"
        Verbosity = "2"
        OptimizeIL = "true"
        DebugSymbols = "$(DebugSymbols)"
        />
</Target>


问:
Efficient implementation of multi-dimensional arrays in Java?
As far as I understand (from answers such as this), java has no native multi-dimensional continuous memory arrays (unlike C#, for example).

While the jagged array syntax (arrays of arrays) might be good for most applications, I would still like to know what's the best practice if you do want the raw efficiency of a continuous-memory array (avoiding unneeded memory reads)

I could of course use a single-dimensional array that maps to a 2D one, but I prefer something more structured.

答:
Let's say you have a 2D array int[][] a = new int[height][width], so by convention you have the indices a[y][x]. Depending on how you represent the data and how you access them, the performance varies in a factor of 20 :

The code:

```<code>public class ObjectArrayPerformance {
    public int width;
    public int height;
    public int m[];

    public ObjectArrayPerformance(int w, int h) {
            this.width = w;
            this.height = h;
            this.m = new int[w * h];
    }

    public int get(int x, int y) {
            return this.m[y * width + x];
    }

    public void set(int x, int y, int value) {
            this.m[y * width + x] = value;
    }

    public static void main (String[] args) {
            int w = 1000, h = 2000, passes = 400;

            int matrix[][] = new int[h][];

            for (int i = 0; i < h; ++i) {
                    matrix[i] = new int[w];
            }

            long start;
            long duration;

            System.out.println("duration[ms]\tmethod");

            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int y = 0; y < h; y++) {
                        for (int x = 0; x < w; x++) {
                                    matrix[y][x] = matrix[y][x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\t2D array, loop on x then y");

            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int x = 0; x < w; x++) {
                            for (int y = 0; y < h; y++) {
                                    matrix[y][x] = matrix[y][x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\t2D array, loop on y then x");

            //

            ObjectArrayPerformance mt = new ObjectArrayPerformance(w, h);
            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int x = 0; x < w; x++) {
                            for (int y = 0; y < h; y++) {
                                    mt.set(x, y, mt.get(x, y) + 1);
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\tmapped 1D array, access trough getter/setter");

            //

            ObjectArrayPerformance mt2 = new ObjectArrayPerformance(w, h);
            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int x = 0; x < w; x++) {
                            for (int y = 0; y < h; y++) {
                                    mt2.m[y * w + x] = mt2.m[y * w + x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\tmapped 1D array, access through computed indexes, loop y then x");

            ObjectArrayPerformance mt3 = new ObjectArrayPerformance(w, h);
            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int y = 0; y < h; y++) {
                        for (int x = 0; x < w; x++) {
                                    mt3.m[y * w + x] = mt3.m[y * w + x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\tmapped 1D array, access through computed indexes, loop x then y");

            ObjectArrayPerformance mt4 = new ObjectArrayPerformance(w, h);
            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int y = 0; y < h; y++) {
                        int yIndex = y * w;
                        for (int x = 0; x < w; x++) {
                                    mt4.m[yIndex + x] = mt4.m[yIndex + x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\tmapped 1D array, access through computed indexes, loop x then y, yIndex optimized");
    }
}
</code>```

We can conclude that linear access performance depends more on the way you process the array (lines then columns or the reverse?: performance gain = x10, much due to CPU caches) than the structure of the array itself (1D vs 2D : performance gain = x2).

If random access, the performance differences should be much lower, because the CPU caches have less effect.

Body:
Let's say you have a 2D array int[][] a = new int[height][width], so by convention you have the indices a[y][x]. Depending on how you represent the data and how you access them, the performance varies in a factor of 20 :

The code:

public class ObjectArrayPerformance {
    public int width;
    public int height;
    public int m[];

    public ObjectArrayPerformance(int w, int h) {
            this.width = w;
            this.height = h;
            this.m = new int[w * h];
    }

    public int get(int x, int y) {
            return this.m[y * width + x];
    }

    public void set(int x, int y, int value) {
            this.m[y * width + x] = value;
    }

    public static void main (String[] args) {
            int w = 1000, h = 2000, passes = 400;

            int matrix[][] = new int[h][];

            for (int i = 0; i < h; ++i) {
                    matrix[i] = new int[w];
            }

            long start;
            long duration;

            System.out.println("duration[ms]\tmethod");

            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int y = 0; y < h; y++) {
                        for (int x = 0; x < w; x++) {
                                    matrix[y][x] = matrix[y][x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\t2D array, loop on x then y");

            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int x = 0; x < w; x++) {
                            for (int y = 0; y < h; y++) {
                                    matrix[y][x] = matrix[y][x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\t2D array, loop on y then x");

            //

            ObjectArrayPerformance mt = new ObjectArrayPerformance(w, h);
            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int x = 0; x < w; x++) {
                            for (int y = 0; y < h; y++) {
                                    mt.set(x, y, mt.get(x, y) + 1);
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\tmapped 1D array, access trough getter/setter");

            //

            ObjectArrayPerformance mt2 = new ObjectArrayPerformance(w, h);
            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int x = 0; x < w; x++) {
                            for (int y = 0; y < h; y++) {
                                    mt2.m[y * w + x] = mt2.m[y * w + x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\tmapped 1D array, access through computed indexes, loop y then x");

            ObjectArrayPerformance mt3 = new ObjectArrayPerformance(w, h);
            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int y = 0; y < h; y++) {
                        for (int x = 0; x < w; x++) {
                                    mt3.m[y * w + x] = mt3.m[y * w + x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\tmapped 1D array, access through computed indexes, loop x then y");

            ObjectArrayPerformance mt4 = new ObjectArrayPerformance(w, h);
            start = System.currentTimeMillis();
            for (int z = 0; z < passes; z++) {
                    for (int y = 0; y < h; y++) {
                        int yIndex = y * w;
                        for (int x = 0; x < w; x++) {
                                    mt4.m[yIndex + x] = mt4.m[yIndex + x] + 1;
                            }
                    }
            }
            duration = System.currentTimeMillis() - start;
            System.out.println(duration+"\tmapped 1D array, access through computed indexes, loop x then y, yIndex optimized");
    }
}

We can conclude that linear access performance depends more on the way you process the array (lines then columns or the reverse?: performance gain = x10, much due to CPU caches) than the structure of the array itself (1D vs 2D : performance gain = x2).

If random access, the performance differences should be much lower, because the CPU caches have less effect.


问:
How to fix Slow Rendering (Android vitals)
I have an app that is listed as in the bottom 25% in the new Google Play Console - Android vitals section for Slow Rendering. I am concerned of this because of such articles that seem to say Google Play may penalize your app in the Play Store rankings if you fall in the bottom 25%.

However, it seems impossible to improve this metric for my app. It plays music and has a SeekBar and TextView which is updated every 250ms as any music player would. I made the minimum basic program to demonstrate:

```<code>public class MainActivity extends AppCompatActivity {

    int count;
    SeekBar seekBar;
    TextView textView;

    Runnable runnable =
            new Runnable() {
                @Override
                public void run() {
                    textView.setText(Integer.toString(count));
                    seekBar.setProgress(count);
                    ++count;
                    seekBar.postDelayed(runnable, 250);
                }
            };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        seekBar = (SeekBar) findViewById(R.id.seek);
        textView = (TextView) findViewById(R.id.text);
        seekBar.post(runnable);
    }
}
</code>```

Full project here: https://github.com/svenoaks/SlowRendering.git

When I run this program on hardware similar to the Nexus devices, I get these results for a

adb shell dumpsys gfxinfo com.example.xyz.slowrendering command:

```<code>Stats since: 19222191084749ns
Total frames rendered: 308
Janky frames: 290 (94.16%)
90th percentile: 32ms
95th percentile: 36ms
99th percentile: 44ms
Number Missed Vsync: 2
Number High input latency: 0
Number Slow UI thread: 139
Number Slow bitmap uploads: 0
Number Slow issue draw commands: 283
</code>```

This would mean almost all my frames taking >16ms to render, I guess due to the periodic nature of the updating. All other music player apps I have tested also have this Slow Rendering problem as far as I can see. I fear Google's algorithm ruining my app ranking, is there any way I can improve my score?

答:
The TextView in your layout is causing the problem. Because it has layout width of wrap_content, which said that it's width has to be equals to the width of the content (the text in this example). Therefore, every time you call TextView.setText an expensive measure/layout pass has to occur. Simple setting the layout_width to match_parent will solve the issue.

Here are two images what is taken from systrace, it demonstrate the work run on the UI thread in 1 frame. The top one is done with layout_width=wrap_content and the bottom one is with layout_width=match_parent.

Two following methods that i have tested will improve the frame rate:

If you post the runnable in shorter span like 16ms (seekBar.postDelayed(runnable, 16)), you get this smooth 60fps:

P/s: I am not sure why yet.

Use some other way to update the count value instead of inside the Runnable. Use View.postOnAnimation(Runnable) to reschedule the Runnable. The result is 60FPS for the sample project.

EDIT:
two Runnable that uses postOnAnimation(Runnable)

```<code>Runnable runnable =
  new Runnable() {
    @Override
    public void run() {
      textView.setText(Integer.toString(count));
      seekBar.setProgress(count);
      seekBar.postOnAnimation(this);
    }
  };

Runnable updateCount = new Runnable() {
    @Override public void run() {
      ++count;
      seekBar.postDelayed(this, 250);
    }
  };
</code>```

Body:
I have an app that is listed as in the bottom 25% in the new Google Play Console - Android vitals section for Slow Rendering. I am concerned of this because of such articles that seem to say Google Play may penalize your app in the Play Store rankings if you fall in the bottom 25%.

However, it seems impossible to improve this metric for my app. It plays music and has a SeekBar and TextView which is updated every 250ms as any music player would. I made the minimum basic program to demonstrate:

public class MainActivity extends AppCompatActivity {

    int count;
    SeekBar seekBar;
    TextView textView;

    Runnable runnable =
            new Runnable() {
                @Override
                public void run() {
                    textView.setText(Integer.toString(count));
                    seekBar.setProgress(count);
                    ++count;
                    seekBar.postDelayed(runnable, 250);
                }
            };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        seekBar = (SeekBar) findViewById(R.id.seek);
        textView = (TextView) findViewById(R.id.text);
        seekBar.post(runnable);
    }
}

Full project here: https://github.com/svenoaks/SlowRendering.git

When I run this program on hardware similar to the Nexus devices, I get these results for a

adb shell dumpsys gfxinfo com.example.xyz.slowrendering command:

Stats since: 19222191084749ns
Total frames rendered: 308
Janky frames: 290 (94.16%)
90th percentile: 32ms
95th percentile: 36ms
99th percentile: 44ms
Number Missed Vsync: 2
Number High input latency: 0
Number Slow UI thread: 139
Number Slow bitmap uploads: 0
Number Slow issue draw commands: 283

This would mean almost all my frames taking >16ms to render, I guess due to the periodic nature of the updating. All other music player apps I have tested also have this Slow Rendering problem as far as I can see. I fear Google's algorithm ruining my app ranking, is there any way I can improve my score?

Body:
The TextView in your layout is causing the problem. Because it has layout width of wrap_content, which said that it's width has to be equals to the width of the content (the text in this example). Therefore, every time you call TextView.setText an expensive measure/layout pass has to occur. Simple setting the layout_width to match_parent will solve the issue.

Here are two images what is taken from systrace, it demonstrate the work run on the UI thread in 1 frame. The top one is done with layout_width=wrap_content and the bottom one is with layout_width=match_parent.

Two following methods that i have tested will improve the frame rate:

If you post the runnable in shorter span like 16ms (seekBar.postDelayed(runnable, 16)), you get this smooth 60fps:

P/s: I am not sure why yet.

Use some other way to update the count value instead of inside the Runnable. Use View.postOnAnimation(Runnable) to reschedule the Runnable. The result is 60FPS for the sample project.

EDIT:
two Runnable that uses postOnAnimation(Runnable)

Runnable runnable =
  new Runnable() {
    @Override
    public void run() {
      textView.setText(Integer.toString(count));
      seekBar.setProgress(count);
      seekBar.postOnAnimation(this);
    }
  };

Runnable updateCount = new Runnable() {
    @Override public void run() {
      ++count;
      seekBar.postDelayed(this, 250);
    }
  };


问:
C# Group by list by specific element to result a list of lists
I have a list of objects. Every object has these components: index, countNr, descA, descB.

How I can group by (maybe LINQ) this list by countNr value?

Like:

List = {(1,3,a1,b1), (2,2,a2,b2), (3,2,a3,b3), (4,1,a4,b4), (5,1,a5,b5), (6,1,a6,b6), (7,1,a7,b7)}

I want now to have another newList of lists, where the position in this list is indicating the countNr number, like:

```<code>newList = {{(7,1,a7,b7), (6,1,a6,b6), (5,1,a5,b5), (4,1,a4,b4)},  {(3,2,a3,b3), (2,2,a2,b2)},  {(1,3,a1,b1)}}
</code>```

答:
newList = list.OrderBy(z => z.countNr).ThenByDescending(y => y.index).ToList()

is probably what you want. I think it may generate your sample output based on your sample input.

Or a complete code sample:

```<code>class Bob
{
    public int index;
    public int countNr;
    public string descA;
    public string descB;

    public Bob(int index, int countNr, string descA, string descB)
    {
        this.index = index;
        this.countNr = countNr;
        this.descA = descA;
        this.descB = descB;
    }

    public override string ToString()
    {
        return $"{index} - {countNr} - {descA} - {descB}";
    }
}

class Program
{
    static void Main(string[] args)
    {
        var list = new List<Bob>
        {
            new Bob(1, 3, "a1", "b1"),
            new Bob(2, 2, "a2", "b2"),
            new Bob(3, 2, "a3", "b3"),
            new Bob(4, 1, "a4", "b4"),
            new Bob(5, 1, "a5", "b5"),
            new Bob(6, 1, "a6", "b6"),
            new Bob(7, 1, "a7", "b7")
        };

        var newList = list.OrderBy(z => z.countNr).ThenByDescending(y => y.index).ToList();

        newList.ForEach(Console.WriteLine);

        Console.ReadLine();
    }
}
</code>```

which gives:

```<code>7 - 1 - a7 - b7
6 - 1 - a6 - b6
5 - 1 - a5 - b5
4 - 1 - a4 - b4
3 - 2 - a3 - b3
2 - 2 - a2 - b2
1 - 3 - a1 - b1
</code>```

Body:
I have a list of objects. Every object has these components: index, countNr, descA, descB.

How I can group by (maybe LINQ) this list by countNr value?

Like:

List = {(1,3,a1,b1), (2,2,a2,b2), (3,2,a3,b3), (4,1,a4,b4), (5,1,a5,b5), (6,1,a6,b6), (7,1,a7,b7)}

I want now to have another newList of lists, where the position in this list is indicating the countNr number, like:

newList = {{(7,1,a7,b7), (6,1,a6,b6), (5,1,a5,b5), (4,1,a4,b4)},  {(3,2,a3,b3), (2,2,a2,b2)},  {(1,3,a1,b1)}}

Body:
newList = list.OrderBy(z => z.countNr).ThenByDescending(y => y.index).ToList()

is probably what you want. I think it may generate your sample output based on your sample input.

Or a complete code sample:

class Bob
{
    public int index;
    public int countNr;
    public string descA;
    public string descB;

    public Bob(int index, int countNr, string descA, string descB)
    {
        this.index = index;
        this.countNr = countNr;
        this.descA = descA;
        this.descB = descB;
    }

    public override string ToString()
    {
        return $"{index} - {countNr} - {descA} - {descB}";
    }
}

class Program
{
    static void Main(string[] args)
    {
        var list = new List<Bob>
        {
            new Bob(1, 3, "a1", "b1"),
            new Bob(2, 2, "a2", "b2"),
            new Bob(3, 2, "a3", "b3"),
            new Bob(4, 1, "a4", "b4"),
            new Bob(5, 1, "a5", "b5"),
            new Bob(6, 1, "a6", "b6"),
            new Bob(7, 1, "a7", "b7")
        };

        var newList = list.OrderBy(z => z.countNr).ThenByDescending(y => y.index).ToList();

        newList.ForEach(Console.WriteLine);

        Console.ReadLine();
    }
}

which gives:

7 - 1 - a7 - b7
6 - 1 - a6 - b6
5 - 1 - a5 - b5
4 - 1 - a4 - b4
3 - 2 - a3 - b3
2 - 2 - a2 - b2
1 - 3 - a1 - b1


问:
How to install GPflow on PyCharm if I have anaconda?
I tried download the package and python setup.py develop. However this directly installs GPflow under anaconda. Plus this isn't really working anaconda and gives error

```<code>/Users/Chu/anaconda/bin/python /Users/Chu/Documents/dssg/dssg.py
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg/dssg.py", line 4, in <module>
    import GPflow
  File "/Users/Chu/Documents/GPflow-master/GPflow/__init__.py", line 18, in <module>
    from . import (likelihoods, kernels, ekernels, param, model, gpmc, sgpmc, priors, gpr, svgp, vgp, sgpr, gplvm, tf_wraps,
  File "/Users/Chu/Documents/GPflow-master/GPflow/likelihoods.py", line 17, in <module>
    from . import densities, transforms
  File "/Users/Chu/Documents/GPflow-master/GPflow/transforms.py", line 18, in <module>
    from . import tf_wraps as tfw
  File "/Users/Chu/Documents/GPflow-master/GPflow/tf_wraps.py", line 36, in <module>
    _custom_op_module = tf.load_op_library(os.path.join(os.path.dirname(__file__), 'tfops', 'matpackops.so'))
  File "/Users/Chu/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/load_library.py", line 64, in load_op_library
    None, None, error_msg, error_code)
tensorflow.python.framework.errors_impl.NotFoundError: dlopen(/Users/Chu/Documents/GPflow-master/GPflow/tfops/matpackops.so, 6): image not found
</code>```

So I think I should try install it under library? Here are some other captures:

答:
I have the same issue even if when I try to install it outside Pycharm. I looked into the reported issue in Github, and the problem was solved for someone else when he built TensorFlow from scratch uisng gcc5

I dont think you can just simply install GPflow on pycharm. Do it outside and then you can use it. Here is the link where it is reported to be solved:

https://github.com/GPflow/GPflow/issues/192

Body:
I tried download the package and python setup.py develop. However this directly installs GPflow under anaconda. Plus this isn't really working anaconda and gives error

/Users/Chu/anaconda/bin/python /Users/Chu/Documents/dssg/dssg.py
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg/dssg.py", line 4, in <module>
    import GPflow
  File "/Users/Chu/Documents/GPflow-master/GPflow/__init__.py", line 18, in <module>
    from . import (likelihoods, kernels, ekernels, param, model, gpmc, sgpmc, priors, gpr, svgp, vgp, sgpr, gplvm, tf_wraps,
  File "/Users/Chu/Documents/GPflow-master/GPflow/likelihoods.py", line 17, in <module>
    from . import densities, transforms
  File "/Users/Chu/Documents/GPflow-master/GPflow/transforms.py", line 18, in <module>
    from . import tf_wraps as tfw
  File "/Users/Chu/Documents/GPflow-master/GPflow/tf_wraps.py", line 36, in <module>
    _custom_op_module = tf.load_op_library(os.path.join(os.path.dirname(__file__), 'tfops', 'matpackops.so'))
  File "/Users/Chu/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/load_library.py", line 64, in load_op_library
    None, None, error_msg, error_code)
tensorflow.python.framework.errors_impl.NotFoundError: dlopen(/Users/Chu/Documents/GPflow-master/GPflow/tfops/matpackops.so, 6): image not found

So I think I should try install it under library? Here are some other captures:


问:
How can I get a reference of a view from a inflated layout
I have a huge layout for my activity that i set using setContentView(). In that layout I have a TableLayout(named tableLayout in my Activity) that I want to populate. The rows of that TableLayout are customViews in a layout file(let's call that file tablerow_layout.xml). Inside this layout i have some TextViews and ImageView. What I want to do is change the content of the TextView programatically, when I create the row. This is my code:

```<code>LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newRow = layoutInflater.inflate(R.layout.tablerow_layout, null, false);
TextView name = (TextView) newRow. findViewById(R.id.tablerow_name);
name.setText("THIS LINE");
tableLayout.addView(newRow);
</code>```

Unfortunately my app crashes when I try to change the content of the TextView. I know that I could do this using a ListView, but I usually have a small number of rows and the overhead of creating another Adapter for the ListView is preatty big.

As @ρяσѕρєя K suggested I also tried newRow.findViewById(...) instead of findViewById(...) without any difference

答:
Using IntelliJ Amiya's and ρяσѕρєя K's answers it worked for me with this code.

```<code>LayoutInflater inflater = LayoutInflater.from(this);
    LinearLayout linearLayout =
(LinearLayout)findViewById(R.id.profileView);
    ViewGroup viewGroup = linearLayout;

    for (int i = 0; i < NUM_OF_PROFILES; i++){

        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.profile_badge_layout, viewGroup, false);
        linearLayout.addView(layout);

        TextView names = (TextView)layout.findViewById(R.id.profileName);
        ImageView images = (ImageView)layout.findViewById(R.id.profileImage);

        names.setText(""+i);

        viewGroup = layout;
    }
</code>```

Each text had it's own i value. I believe you need to add the view first. Then you can change the values

Body:
I have a huge layout for my activity that i set using setContentView(). In that layout I have a TableLayout(named tableLayout in my Activity) that I want to populate. The rows of that TableLayout are customViews in a layout file(let's call that file tablerow_layout.xml). Inside this layout i have some TextViews and ImageView. What I want to do is change the content of the TextView programatically, when I create the row. This is my code:

LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newRow = layoutInflater.inflate(R.layout.tablerow_layout, null, false);
TextView name = (TextView) newRow. findViewById(R.id.tablerow_name);
name.setText("THIS LINE");
tableLayout.addView(newRow);

Unfortunately my app crashes when I try to change the content of the TextView. I know that I could do this using a ListView, but I usually have a small number of rows and the overhead of creating another Adapter for the ListView is preatty big.

As @ρяσѕρєя K suggested I also tried newRow.findViewById(...) instead of findViewById(...) without any difference

Body:
Using IntelliJ Amiya's and ρяσѕρєя K's answers it worked for me with this code.

LayoutInflater inflater = LayoutInflater.from(this);
    LinearLayout linearLayout =
(LinearLayout)findViewById(R.id.profileView);
    ViewGroup viewGroup = linearLayout;

    for (int i = 0; i < NUM_OF_PROFILES; i++){

        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.profile_badge_layout, viewGroup, false);
        linearLayout.addView(layout);

        TextView names = (TextView)layout.findViewById(R.id.profileName);
        ImageView images = (ImageView)layout.findViewById(R.id.profileImage);

        names.setText(""+i);

        viewGroup = layout;
    }

Each text had it's own i value. I believe you need to add the view first. Then you can change the values


答:
```<code>cell.textLabel.text = [[messages objectAtIndex:indexPath.row] objectForKey:@"Title"];
cell.detailTextLabel.detailLabel = [[messages objectAtIndex:indexPath.row] objectForKey:@"Body"];
</code>```

Title: Nested NSArray into UITableView


问:
add active class on  element when we click on to make menu as highlighted
in menu, when user click on item, i want to hightlight with class,

i have html like this :

```<code><div id="menu_wrapper">
    <ul class="art-hmenu">
        <li id="home"><a href="Home.aspx">Home</a></li>
        <li id="ProjectList"><a href="ProjectList.aspx">Project List</a><ul>
            <li id="ProjectListsub1"><a href="subone.aspx">Sub One</a></li>
            <li id="ProjectListsub2"><a href="subtwo.aspx">Sub Two</a></li>
        </ul>
        </li>
        <li id="ProjectChoices"><a href="">Project Choices</a><ul>
            <li id="ProjectChoicessub1"><a href="StudentChoices.aspx">Student Project Choices</a></li>
            <li id="ProjectChoicessub2"><a href="StaffChoices.aspx">Supervisor Project Choices</a></li>
        </ul>
        </li>
        <li id="ProjectAllocationList"><a href="AllocationList.aspx">Project Allocation List</a></li>
        <li id="SubmitProposal"><a href="">Submit Proposal</a><ul>
            <li id="SubmitProposalsub1"><a href="submit.aspx">New Proposal</a></li>
            <li id="SubmitProposalsub2"><a href="reSubmit.aspx">Re-Submit Proposal</a></li>
        </ul>
        </li>
        <li id="StaffRecords"><a href="StaffRecords.aspx">Staff Records</a><ul>
            <li id="Li1"><a href="addStaff.aspx">Add new Staff</a></li>
        </ul>
        </li>
        <li id="StudentRecords"><a href="StudentRecords.aspx">Student Records</a></li>
    </ul>
</div>
</code>```

when user click on  i want to add class ="active"

what i tired is like this :

```<code>$(document).ready(function () {
            $(".art-hmenu>ul>li").on("click", "a", function (event) {
                debugger;
                $("#menu_wrapper>ul>li.active").removeClass("active");
                $("#menu_wrapper>ul>li>a.active").removeClass("active");
                $(this).addClass("active");
            });
        });
</code>```

but i am not able to add class , on

答:
Add Bootstrap CDN :

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

HTML code

```<code><div class="container">
    <ul class="nav nav-tabs">
        <li id="parentMenuId"><a href="#parentMenu">Parent Menu</a></li>
        <li id="childMenuId"><a href="#childMenu">Child Menu</a></li>
    </ul>

    <div id="parentMenu">
        <center>
            <div class="form-group">
                <h1>parent menu</h1>
            </div>
        </center>
    </div>

    <div id="childMenu">
        <center>
            <h1>child menu</h1>
        </center>
    </div>
</div>
</code>```

jQuery code

```<code>$(document).ready(function() {
    $("#childMenu").hide();
    $("#parentMenuId").addClass("active");

    $("#parentMenuId").click(function() {
        $("#parentMenu").show();
        $("#childMenu").hide();
        $("#parentMenuId").addClass("active");
        $("#childMenuId").removeClass("active");
    });

    $("#childMenuId").click(function() {
        $("#parentMenu").hide();
        $("#childMenu").show();
        $("#parentMenuId").removeClass("active");
        $("#childMenuId").addClass("active");
    });
});
</code>```

Title: add active class on <a> element when we click on to make menu as highlighted

Body:
in menu, when user click on item, i want to hightlight with class,

i have html like this :

Home

Project List

Sub One

Sub Two

Project Choices

Student Project Choices

Supervisor Project Choices

Project Allocation List

Submit Proposal

New Proposal

Re-Submit Proposal

Staff Records

Add new Staff

Student Records

when user click on  i want to add class ="active"

what i tired is like this :

$(document).ready(function () {
            $(".art-hmenu>ul>li").on("click", "a", function (event) {
                debugger;
                $("#menu_wrapper>ul>li.active").removeClass("active");
                $("#menu_wrapper>ul>li>a.active").removeClass("active");
                $(this).addClass("active");
            });
        });

but i am not able to add class , on

Body:
Add Bootstrap CDN :

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

HTML code

<div class="container">
    <ul class="nav nav-tabs">
        <li id="parentMenuId"><a href="#parentMenu">Parent Menu</a></li>
        <li id="childMenuId"><a href="#childMenu">Child Menu</a></li>
    </ul>

    <div id="parentMenu">
        <center>
            <div class="form-group">
                <h1>parent menu</h1>
            </div>
        </center>
    </div>

    <div id="childMenu">
        <center>
            <h1>child menu</h1>
        </center>
    </div>
</div>

jQuery code

$(document).ready(function() {
    $("#childMenu").hide();
    $("#parentMenuId").addClass("active");

    $("#parentMenuId").click(function() {
        $("#parentMenu").show();
        $("#childMenu").hide();
        $("#parentMenuId").addClass("active");
        $("#childMenuId").removeClass("active");
    });

    $("#childMenuId").click(function() {
        $("#parentMenu").hide();
        $("#childMenu").show();
        $("#parentMenuId").removeClass("active");
        $("#childMenuId").addClass("active");
    });
});


问:
SQL Server: Check Upper Case or Lower Case after certain Character
I have data like 'John is my name; Ram is my name; Adam is my name'.

My rule is such that every first letter that comes after ; should be capital letter.

How do I select all values that satisfy the rule?

答:
The other answers show how to transform rows into something that matches your pattern.

If you just want to select the rows that match the pattern you are describing, you can use patindex() or like with a case sensitive collation (or use collate to apply one).

This assumes that in addition to the rule that every letter that follows a semicolon must be a capital letter, that the very first letter should also be capital. If that is not the case, just remove the first clause in the where.

```<code>select *
from t
where patindex('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]%', val collate latin1_general_cs_as) = 1
  and patindex('%; [^ABCDEFGHIJKLMNOPQRSTUVWXYZ]%', val collate latin1_general_cs_as) = 0
</code>```

```<code>select *
from t
where val collate latin1_general_cs_as like '[ABCDEFGHIJKLMNOPQRSTUVWXYZ]%'
  and val collate latin1_general_cs_as not like '%; [^ABCDEFGHIJKLMNOPQRSTUVWXYZ]%'
</code>```

test setup:

```<code>create table t (id int not null identity(1,1),val varchar(256))
insert into t values
 ('John is my name; Ram is my name; Adam is my name')
,('john is my name; ram is my name; adam is my name')
</code>```

rextester demo: http://rextester.com/DBGIS10645

Both of the above return:

```<code>+----+--------------------------------------------------+
| id |                       val                        |
+----+--------------------------------------------------+
|  1 | John is my name; Ram is my name; Adam is my name |
+----+--------------------------------------------------+
</code>```

Body:
The other answers show how to transform rows into something that matches your pattern.

If you just want to select the rows that match the pattern you are describing, you can use patindex() or like with a case sensitive collation (or use collate to apply one).

This assumes that in addition to the rule that every letter that follows a semicolon must be a capital letter, that the very first letter should also be capital. If that is not the case, just remove the first clause in the where.

select *
from t
where patindex('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]%', val collate latin1_general_cs_as) = 1
  and patindex('%; [^ABCDEFGHIJKLMNOPQRSTUVWXYZ]%', val collate latin1_general_cs_as) = 0

select *
from t
where val collate latin1_general_cs_as like '[ABCDEFGHIJKLMNOPQRSTUVWXYZ]%'
  and val collate latin1_general_cs_as not like '%; [^ABCDEFGHIJKLMNOPQRSTUVWXYZ]%'

test setup:

create table t (id int not null identity(1,1),val varchar(256))
insert into t values
 ('John is my name; Ram is my name; Adam is my name')
,('john is my name; ram is my name; adam is my name')

rextester demo: http://rextester.com/DBGIS10645

Both of the above return:

+----+--------------------------------------------------+
| id |                       val                        |
+----+--------------------------------------------------+
|  1 | John is my name; Ram is my name; Adam is my name |
+----+--------------------------------------------------+


问:
How to replace empty numpy array by grayscale image values
EDIT: I have found a workaround, which is assigning it to an array, then use that array to create a numpy array:
a = []

```<code>for i in range(0,width/image_size):
    for j in range(0,height/image_size):
        roi = img[image_size*j:image_size*(j+1),image_size*i:image_size*(i+1)]
        a.append(roi)

arr = np.asarray(a) #HERE
</code>```

ORIGINAL QUESTION:

I have created an empty numpy array of shape (180,28,28), which should hold 180 gray scale images size 28x28.

```<code>height, width = img.shape[:2]
arr = np.empty(((height/image_size)*(width/image_size), 28, 28 )) #arr.shape = (180,28,28)
</code>```

I have multiple image regions size 28x28 that I want to populate into arr

```<code>for i in range(0,width/image_size):
    for j in range(0,height/image_size):
        roi = img[image_size*j:image_size*(j+1),image_size*i:image_size*(i+1)]
        #HERE - how can I set the value in arr to be an (28x28) roi
</code>```

Thank you.

答:
I have found a workaround, which is assigning it to an array, then use that array to create a numpy array:

```<code>a = []

for i in range(0,width/image_size):
    for j in range(0,height/image_size):
        roi = img[image_size*j:image_size*(j+1),image_size*i:image_size*(i+1)]
        a.append(roi)

arr = np.asarray(a)  #assign it to numpy array here
</code>```

However, I'm not sure if there is a better, or more elegant way to do it.

Body:
EDIT: I have found a workaround, which is assigning it to an array, then use that array to create a numpy array:
a = []

for i in range(0,width/image_size):
    for j in range(0,height/image_size):
        roi = img[image_size*j:image_size*(j+1),image_size*i:image_size*(i+1)]
        a.append(roi)

arr = np.asarray(a) #HERE

ORIGINAL QUESTION:

I have created an empty numpy array of shape (180,28,28), which should hold 180 gray scale images size 28x28.

height, width = img.shape[:2]
arr = np.empty(((height/image_size)*(width/image_size), 28, 28 )) #arr.shape = (180,28,28)

I have multiple image regions size 28x28 that I want to populate into arr

for i in range(0,width/image_size):
    for j in range(0,height/image_size):
        roi = img[image_size*j:image_size*(j+1),image_size*i:image_size*(i+1)]
        #HERE - how can I set the value in arr to be an (28x28) roi

Thank you.

Body:
I have found a workaround, which is assigning it to an array, then use that array to create a numpy array:

a = []

for i in range(0,width/image_size):
    for j in range(0,height/image_size):
        roi = img[image_size*j:image_size*(j+1),image_size*i:image_size*(i+1)]
        a.append(roi)

arr = np.asarray(a)  #assign it to numpy array here

However, I'm not sure if there is a better, or more elegant way to do it.


问:
Inserting a pdf BEFORE the bookdown frontpage
I'm writing my thesis with Bookdown in Rmarkdown (and I will export it to PDF format eventually). To hand in my thesis, I am required to include a few scanned documents with handwritten signatures BEFORE the first page of my thesis.

Bookdown is amazing in combining different Rmd files, but I have not managed to include a PDF document BEFORE the title page.

I have tried this:

```<code>bookdown::pdf_book:
  includes:
    in_header: preamble.tex
    before_body: beforebody.tex
</code>```

With in preamble.tex :

```<code>\usepackage{pdfpages}
</code>```

and in beforebody.tex:

```<code>\includepdf[pages={5}, scale=1]{OfficialFrontpages.pdf}
\newpage
</code>```

However, then it first creates the Bookdown titlepage, and only inserts these pages before the Table of Contents. Is there any way to force this document to be included BEFORE the first page of the final PDF document?

Inclusion of these commands as the lines of the first .Rmd files also doesn't work:

```<code>![Caption](OfficialFrontpages.pdf)
\raggedright
\clearpage
</code>```

答:
One strategy is to edit the latex template so that you call your \includepdf is evaluated before \maketitle. It seems like bookdown is using the regular rmarkdown latex template. Let's make a copy and edit it. There are several alternative ways to do this:

You could remove this part altogether:

```<code>$if(title)$
\maketitle
$endif$
</code>```

And then write in your Rmd document:

```<code>\includepdf[pages={5}, scale=1]{OfficialFrontpages.pdf}
\maketitle
</code>```

Or you could move that part, the one that takes care of the before_body:

```<code>$for(include-before)$
$include-before$
$endfor$
</code>```

before \maketitle, and use your current strategy with before_body.

Either way, you'll need to tell knitr to use your custom template:

```<code>bookdown::pdf_book:
  template: mytemplate.tex
</code>```

And you may have to adjust some other parameters since knitr doesn't behave exactly the same when used with custom templates (for instance, you will probably need to redefine the margin size yourself).

Body:
I'm writing my thesis with Bookdown in Rmarkdown (and I will export it to PDF format eventually). To hand in my thesis, I am required to include a few scanned documents with handwritten signatures BEFORE the first page of my thesis.

Bookdown is amazing in combining different Rmd files, but I have not managed to include a PDF document BEFORE the title page.

I have tried this:

bookdown::pdf_book:
  includes:
    in_header: preamble.tex
    before_body: beforebody.tex

With in preamble.tex :

\usepackage{pdfpages}

and in beforebody.tex:

\includepdf[pages={5}, scale=1]{OfficialFrontpages.pdf}
\newpage

However, then it first creates the Bookdown titlepage, and only inserts these pages before the Table of Contents. Is there any way to force this document to be included BEFORE the first page of the final PDF document?

Inclusion of these commands as the lines of the first .Rmd files also doesn't work:

![Caption](OfficialFrontpages.pdf)
\raggedright
\clearpage

Body:
One strategy is to edit the latex template so that you call your \includepdf is evaluated before \maketitle. It seems like bookdown is using the regular rmarkdown latex template. Let's make a copy and edit it. There are several alternative ways to do this:

You could remove this part altogether:

$if(title)$
\maketitle
$endif$

And then write in your Rmd document:

\includepdf[pages={5}, scale=1]{OfficialFrontpages.pdf}
\maketitle

Or you could move that part, the one that takes care of the before_body:

$for(include-before)$
$include-before$
$endfor$

before \maketitle, and use your current strategy with before_body.

Either way, you'll need to tell knitr to use your custom template:

bookdown::pdf_book:
  template: mytemplate.tex

And you may have to adjust some other parameters since knitr doesn't behave exactly the same when used with custom templates (for instance, you will probably need to redefine the margin size yourself).


问:
Foreign keys vs partitioning
Since foreign keys are not supported by partitioned mySQL databases for the moment, I would like to hear some pro's and con's for a read-heavy application that will handle around 1-400 000 rows per table. Unfortunately, I dont have enough experience yet in this area to make the conclusion by myself...

Thanks a lot!

References:

How to handle foreign key while partitioning

Partitioning mySQL tables that has foreign keys?

答:
Well, partition is not a good solution for complicate data model.  If you only have 2 to 3 tables depending on each other, you may be able to do it but it is not pretty.  Each table must have an column that determine the partition.  Then, each table must have a trigger to create the new table, set the foreign key and unique constraint.

For example,
audittransaction<- auditentry

Each audittransactionhas 0 to n auditentry.  table auditentry contains the foreign key of transaction.  Both table have to have column creationDate since it is used for partition both tables.

------ create a trigger to insert audittransaction within the trigger

```<code>create or replace function audittransaction_insert_function()
returns trigger as $$
DECLARE

    tablepartition varchar;
    tablename varchar;
    startbounds timestamp;
    endbounds timestamp;

BEGIN
    tablepartition :=  to_char(date_trunc('month', NEW.whendone), 'YYYYMMDD');
    tablename := 'audittransaction_' || tablepartition ;

    if not exists(select * from information_schema.tables where table_name = tablename) then
        startbounds := date_trunc('month', NEW.whendone);
        endbounds := startbounds + cast('1 months' as interval);
        execute 'create table ' || tablename || ' ( CHECK (whendone >= ' || quote_literal(startbounds) || ' and whendone < ' || quote_literal(endbounds)|| ') ) inherits (audittransaction)';
        execute 'ALTER TABLE '||  tablename ||' ADD CONSTRAINT '||tablename||'_unique_id UNIQUE (id)';
    end if;
    execute 'insert into ' || tablename || ' (id, operationid, whendone, "comment", ticketid ,transactionid, userid )  values (' || quote_literal(NEW.id) || ',' || quote_literal(NEW.operationid) || ',' || quote_literal(NEW.whendone) || ')';
    return null;
END; $$
LANGUAGE plpgsql;

create trigger insert_audittrans
</code>```

----- then, create a trigger for autientry

```<code>create or replace function auditentry_insert_function()
returns trigger as $$
DECLARE
    tablepartition varchar;
    tablename varchar;
    startbounds timestamp;
    endbounds timestamp;

BEGIN
    tablepartition :=  to_char(date_trunc('month', NEW.transactiontimestampgmt), 'YYYYMMDD');
    tablename := 'auditentry_' || tablepartition ;

    if not exists(select * from information_schema.tables where table_name = tablename) then
        startbounds := date_trunc('month', NEW.transactiontimestampgmt);
        endbounds := startbounds + cast('1 months' as interval);
        execute 'create table ' || tablename || ' ( CHECK (transactiontimestampgmt >= ' || quote_literal(startbounds) || ' and transactiontimestampgmt < ' || quote_literal(endbounds)|| ') ) inherits (auditentry)';
        execute 'ALTER TABLE '||  tablename ||' ADD CONSTRAINT '||tablename||'_unique_id UNIQUE (id)';
        execute 'ALTER TABLE ' || tablename ||' ADD CONSTRAINT auditentry FOREIGN KEY (audit_transaction_id) REFERENCES audittransaction_'||tablepartition ||'(id)';
    end if;
    execute 'insert into ' || tablename || ' (id, audit_transaction_id, eventid, transactiontimestampgmt,timestampgmt, acknowledged, resolved, acknowledgedbyusername, acknowledgeddate,  notificationlevel, resolvedbyusername, resolveddate, severity,  parentauditentry_id )  values (' || quote_literal(NEW.id) || ',' || quote_literal(NEW.audit_transaction_id) || ',' || quote_literal(NEW.eventid) || ','||quote_literal(NEW.transactiontimestampgmt)||')';
    return null;
END; $$
LANGUAGE plpgsql;

create trigger insert_auditentry before insert on auditentry for each row execute procedure auditentry_insert_function();
</code>```

Title: Foreign keys vs partitioning

Body:
Well, partition is not a good solution for complicate data model.  If you only have 2 to 3 tables depending on each other, you may be able to do it but it is not pretty.  Each table must have an column that determine the partition.  Then, each table must have a trigger to create the new table, set the foreign key and unique constraint.

For example,
audittransaction<- auditentry

Each audittransactionhas 0 to n auditentry.  table auditentry contains the foreign key of transaction.  Both table have to have column creationDate since it is used for partition both tables.

------ create a trigger to insert audittransaction within the trigger

create or replace function audittransaction_insert_function()
returns trigger as $$
DECLARE

    tablepartition varchar;
    tablename varchar;
    startbounds timestamp;
    endbounds timestamp;

BEGIN
    tablepartition :=  to_char(date_trunc('month', NEW.whendone), 'YYYYMMDD');
    tablename := 'audittransaction_' || tablepartition ;

    if not exists(select * from information_schema.tables where table_name = tablename) then
        startbounds := date_trunc('month', NEW.whendone);
        endbounds := startbounds + cast('1 months' as interval);
        execute 'create table ' || tablename || ' ( CHECK (whendone >= ' || quote_literal(startbounds) || ' and whendone < ' || quote_literal(endbounds)|| ') ) inherits (audittransaction)';
        execute 'ALTER TABLE '||  tablename ||' ADD CONSTRAINT '||tablename||'_unique_id UNIQUE (id)';
    end if;
    execute 'insert into ' || tablename || ' (id, operationid, whendone, "comment", ticketid ,transactionid, userid )  values (' || quote_literal(NEW.id) || ',' || quote_literal(NEW.operationid) || ',' || quote_literal(NEW.whendone) || ')';
    return null;
END; $$
LANGUAGE plpgsql;

create trigger insert_audittrans

----- then, create a trigger for autientry

create or replace function auditentry_insert_function()
returns trigger as $$
DECLARE
    tablepartition varchar;
    tablename varchar;
    startbounds timestamp;
    endbounds timestamp;

BEGIN
    tablepartition :=  to_char(date_trunc('month', NEW.transactiontimestampgmt), 'YYYYMMDD');
    tablename := 'auditentry_' || tablepartition ;

    if not exists(select * from information_schema.tables where table_name = tablename) then
        startbounds := date_trunc('month', NEW.transactiontimestampgmt);
        endbounds := startbounds + cast('1 months' as interval);
        execute 'create table ' || tablename || ' ( CHECK (transactiontimestampgmt >= ' || quote_literal(startbounds) || ' and transactiontimestampgmt < ' || quote_literal(endbounds)|| ') ) inherits (auditentry)';
        execute 'ALTER TABLE '||  tablename ||' ADD CONSTRAINT '||tablename||'_unique_id UNIQUE (id)';
        execute 'ALTER TABLE ' || tablename ||' ADD CONSTRAINT auditentry FOREIGN KEY (audit_transaction_id) REFERENCES audittransaction_'||tablepartition ||'(id)';
    end if;
    execute 'insert into ' || tablename || ' (id, audit_transaction_id, eventid, transactiontimestampgmt,timestampgmt, acknowledged, resolved, acknowledgedbyusername, acknowledgeddate,  notificationlevel, resolvedbyusername, resolveddate, severity,  parentauditentry_id )  values (' || quote_literal(NEW.id) || ',' || quote_literal(NEW.audit_transaction_id) || ',' || quote_literal(NEW.eventid) || ','||quote_literal(NEW.transactiontimestampgmt)||')';
    return null;
END; $$
LANGUAGE plpgsql;

create trigger insert_auditentry before insert on auditentry for each row execute procedure auditentry_insert_function();


问:
Can't INSERT INTO access database
I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.

Code:

```<code>Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader

conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
</code>```

I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database?  I can insert this query by running query directly in Access.

答:
Firstly I would check the database settings.  If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one).  Rather set it up to COPY IF NEWER.

Further, you should ALWAYS use parameterized queries to protect your data.  It is also is less error prone than string concatenated commands ans is much easier to debug.

Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:

```<code>Using con As New OleDbConnection

   con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
                       "Data Source = "
   Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
                              "VALUES " & _
                              "(@code);"

   Dim sql_insert_entry As New OleDbCommand

   con.Open()

   With sql_insert_entry
      .Parameters.AddWithValue("@code", txtCode.Text)
      .CommandText = sql_insert
      .Connection = con
      .ExecuteNonQuery()
   End With

   con.Close()

End Using
</code>```

Title: Can't INSERT INTO access database

Body:
I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.

Code:

Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader

conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()

I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database?  I can insert this query by running query directly in Access.

Body:
Firstly I would check the database settings.  If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one).  Rather set it up to COPY IF NEWER.

Further, you should ALWAYS use parameterized queries to protect your data.  It is also is less error prone than string concatenated commands ans is much easier to debug.

Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:

Using con As New OleDbConnection

   con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
                       "Data Source = "
   Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
                              "VALUES " & _
                              "(@code);"

   Dim sql_insert_entry As New OleDbCommand

   con.Open()

   With sql_insert_entry
      .Parameters.AddWithValue("@code", txtCode.Text)
      .CommandText = sql_insert
      .Connection = con
      .ExecuteNonQuery()
   End With

   con.Close()

End Using


问:
program that determines if array is ascending, descending, or random(C language)
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

```<code>int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}
</code>```

i'd appreciate some guidance.

答:
Well, how about you try this( although it is long )
you keep the data of the original array to another temporary array like this:

```<code>for(int i=0;i<size;i++)
{
  //assuming arr is your array and size is the no. of data//

  arr[i]=temp[i]; //here we store each data of the original to a temporary
}
</code>```

and then ascend the temp array:

```<code>//Selection sorting the temp array in ascending

for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++ )
  {
    if(temp[i]<temp[j])
     {
        swap = temp[i];
        temp[i] = temp[j];
        temp[j] = swap;
     }
  }
}
</code>```

then compare your original array and the ascended temp array, if they are equal, the original array is ascending, if not move to doing the same way with descending(i.e. descend the temp array then then again compare, if they are equal ur original array is descending )

if neither, your array is random

Body:
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}

i'd appreciate some guidance.

Body:
Well, how about you try this( although it is long )
you keep the data of the original array to another temporary array like this:

for(int i=0;i<size;i++)
{
  //assuming arr is your array and size is the no. of data//

  arr[i]=temp[i]; //here we store each data of the original to a temporary
}

and then ascend the temp array:

//Selection sorting the temp array in ascending

for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++ )
  {
    if(temp[i]<temp[j])
     {
        swap = temp[i];
        temp[i] = temp[j];
        temp[j] = swap;
     }
  }
}

then compare your original array and the ascended temp array, if they are equal, the original array is ascending, if not move to doing the same way with descending(i.e. descend the temp array then then again compare, if they are equal ur original array is descending )

if neither, your array is random


问:
Getting python scripts to run in http simple server
I have a simple python script that I want to serve as a website:

```<code>import SimpleHTTPServer
import SocketServer

PORT = 8000

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()
</code>```

I'm in that folder and run

```<code>$ python3 -m http.server
</code>```

then I visit
http://hassbian.local:8000/song.py

The terminal says this and I get the file as a txt file, the script won't execute.

```<code>Serving HTTP on 0.0.0.0 port 8000 ...
192.168.1.115 - - [04/Jun/2017 14:19:59] "GET / HTTP/1.1" 200 -
192.168.1.115 - - [04/Jun/2017 14:20:04] "GET /song.py HTTP/1.1" 200 -
</code>```

Running on a rasberry pi

答:
SimpleHTTPServer doesn't do CGI. If you want CGI you will have to use CGIHTTPServer

This module can run CGI scripts on Unix and Windows systems.

I am not sure if that's what you really want, but invoking a python script in the manner you have shown is CGI. CGI is a really old way of doing things. Running simple web apps with python is now almost exclusively the domain of webapp2 or flask. While more complex apps involving databases are dominated by django.

Body:
I have a simple python script that I want to serve as a website:

import SimpleHTTPServer
import SocketServer

PORT = 8000

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

I'm in that folder and run

$ python3 -m http.server

then I visit
http://hassbian.local:8000/song.py

The terminal says this and I get the file as a txt file, the script won't execute.

Serving HTTP on 0.0.0.0 port 8000 ...
192.168.1.115 - - [04/Jun/2017 14:19:59] "GET / HTTP/1.1" 200 -
192.168.1.115 - - [04/Jun/2017 14:20:04] "GET /song.py HTTP/1.1" 200 -

Running on a rasberry pi


问:
F# - Convert Int option to Int64 option
Is there better way how to do this? :

```<code>let intOption = Some(123)
let longOption = match intOption with
                   | Some x -> Some(int64 x )
                   | None   -> None
</code>```

I need to convert option of int to option of int64.

答:
The function you're looking for is Option.map:

```<code>let longOption = Option.map int64 intOption
</code>```

Title: F# - Convert Int option to Int64 option

Body:
Is there better way how to do this? :

let intOption = Some(123)
let longOption = match intOption with
                   | Some x -> Some(int64 x )
                   | None   -> None

I need to convert option of int to option of int64.

Body:
The function you're looking for is Option.map:

let longOption = Option.map int64 intOption


答:
Option.map does exactly what you need.

```<code>intOption |> Option.map int64
</code>```

Title: F# - Convert Int option to Int64 option

Body:
Option.map does exactly what you need.

intOption |> Option.map int64