问:
Laravel Nova 404 when using hasMany
In my Laravel Nova project, I have a Page and a PageTranslation (model and resource). When adding a hasMany to my Resource fields, upon visiting the detail of the Page, I get a 404 error. This is my code

This is my Page Resource

```<code><?php

namespace App\Pages\Resources;

use Illuminate\Http\Request;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\HasMany;

class Page extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = 'App\Pages\Models\Page';

    /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
    public static $title = 'working_title';

    /**
     * @var string
     */
    public static $group = 'Pages';

    /**
     * The columns that should be searched.
     *
     * @var array
     */
    public static $search = [
        'id', 'working_title'
    ];

    /**
     * Eager load translations
     */
    public static $with = ['translations'];

    /**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),

            Text::make('Title', 'working_title')
                ->sortable()
                ->rules('required', 'max:256'),

            HasMany::make('Translations', 'translations', \App\Pages\Resources\PageTranslation::class)

        ];
    }

}
</code>```

This is my PageTranslation Resource

```<code><?php

namespace Codedor\Pages\Resources;

use Illuminate\Http\Request;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;

class PageTranslation extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = 'Codedor\Pages\Models\PageTranslation';

    /**
     * Hide resource from Nova's standard menu.
     * @var bool
     */
    public static $displayInNavigation = false;

    /**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),

            Text::make('Locale')
                ->sortable()
                ->rules('required', 'max:256')
        ];
    }
}
</code>```

答:
It's not related to relationships at all. Make sure you've included the resources in your NovaServiceProvider
Also, to restrict from viewing in the sidebar based on user role, you can do something like:

```<code> public static function availableForNavigation(Request $request)
 {
   return $request->user()->isAdmin();
 }
</code>```

Title: Laravel Nova 404 when using hasMany

Body:
In my Laravel Nova project, I have a Page and a PageTranslation (model and resource). When adding a hasMany to my Resource fields, upon visiting the detail of the Page, I get a 404 error. This is my code

This is my Page Resource

<?php

namespace App\Pages\Resources;

use Illuminate\Http\Request;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\HasMany;

class Page extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = 'App\Pages\Models\Page';

    /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
    public static $title = 'working_title';

    /**
     * @var string
     */
    public static $group = 'Pages';

    /**
     * The columns that should be searched.
     *
     * @var array
     */
    public static $search = [
        'id', 'working_title'
    ];

    /**
     * Eager load translations
     */
    public static $with = ['translations'];

    /**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),

            Text::make('Title', 'working_title')
                ->sortable()
                ->rules('required', 'max:256'),

            HasMany::make('Translations', 'translations', \App\Pages\Resources\PageTranslation::class)

        ];
    }

}

This is my PageTranslation Resource

<?php

namespace Codedor\Pages\Resources;

use Illuminate\Http\Request;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;

class PageTranslation extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = 'Codedor\Pages\Models\PageTranslation';

    /**
     * Hide resource from Nova's standard menu.
     * @var bool
     */
    public static $displayInNavigation = false;

    /**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),

            Text::make('Locale')
                ->sortable()
                ->rules('required', 'max:256')
        ];
    }
}

Body:
It's not related to relationships at all. Make sure you've included the resources in your NovaServiceProvider
Also, to restrict from viewing in the sidebar based on user role, you can do something like:

 public static function availableForNavigation(Request $request)
 {
   return $request->user()->isAdmin();
 }


来源: stackexchange

问:
How can I convert the string [1,2,3,4,5] into an integer array?
```<code>def array = [1,2,3,4,5]
def b = int[array.length]
for(int i = 0; i < b.length; i++){
    b[i] = Integer.parseInt(array[i])
}
</code>```

Should I use Integer.parseInt, Integer.valueOf or other methods?

Should I include a for loop?

答:
Another option: take all numbers from the string as list and then cast them</p>

```<code>"1, 2, 3".findAll(/\d+/) as Integer[]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
def array = [1,2,3,4,5]
def b = int[array.length]
for(int i = 0; i < b.length; i++){
    b[i] = Integer.parseInt(array[i])
}

Should I use Integer.parseInt, Integer.valueOf or other methods?

Should I include a for loop?

Body:
Another option: take all numbers from the string as list and then cast them

"1, 2, 3".findAll(/\d+/) as Integer[]


问:
Different Checksums Values using BlobDownload Client
I am running into a strange issue. I am downloading the same file from my storage account with no problem. However, I am getting different checksum values for each download.  Below is the code I am using. Any reason why that would be? Thanks</p>

```<code>       BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();

    BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient("test");

    String fileName ="blob.iso";
    BlobClient blobClient = containerClient.getBlobClient(fileName);

    blobClient.download("path to file");
</code>```

答:
Based on my test, the checksums just match.

Here is my code:

```<code>    public static void main(String[] args) throws Exception {
        String connectStr = "DefaultEndpointsProtocol=https;AccountName=storagetest789;AccountKey=G3************1w==;EndpointSuffix=core.windows.net";
        BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();
        BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient("pub");
        BlobClient blobClient = containerClient.getBlobClient("azure-cli-2.0.67.msi");
        blobClient.downloadToFile("d:/test/azure-cli-2.0.67.msi",true);
        System.out.println("azure-cli-2.0.67.msi -> " + DigestUtils.md5DigestAsHex(FileUtils.openInputStream(new File("d:/test/azure-cli-2.0.67.msi"))));
    }
</code>```

I ran it twice, and got the following outputs:

```<code>// First time
azure-cli-2.0.67.msi -> 4510dc9ee0dd38bfbf261f6a9e467d34
// Second time
azure-cli-2.0.67.msi -> 4510dc9ee0dd38bfbf261f6a9e467d34
</code>```

I see that you are trying to download an ISO file whose size may be larger. I am not sure if it would be a problem. When the network environment is not good, the downloaded data may be incomplete or incorrect which may cause your problem.

Body:
I am running into a strange issue. I am downloading the same file from my storage account with no problem. However, I am getting different checksum values for each download.  Below is the code I am using. Any reason why that would be? Thanks

       BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();

    BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient("test");

    String fileName ="blob.iso";
    BlobClient blobClient = containerClient.getBlobClient(fileName);

    blobClient.download("path to file");

Body:
Based on my test, the checksums just match.

Here is my code:

    public static void main(String[] args) throws Exception {
        String connectStr = "DefaultEndpointsProtocol=https;AccountName=storagetest789;AccountKey=G3************1w==;EndpointSuffix=core.windows.net";
        BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();
        BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient("pub");
        BlobClient blobClient = containerClient.getBlobClient("azure-cli-2.0.67.msi");
        blobClient.downloadToFile("d:/test/azure-cli-2.0.67.msi",true);
        System.out.println("azure-cli-2.0.67.msi -> " + DigestUtils.md5DigestAsHex(FileUtils.openInputStream(new File("d:/test/azure-cli-2.0.67.msi"))));
    }

I ran it twice, and got the following outputs:

// First time
azure-cli-2.0.67.msi -> 4510dc9ee0dd38bfbf261f6a9e467d34
// Second time
azure-cli-2.0.67.msi -> 4510dc9ee0dd38bfbf261f6a9e467d34

I see that you are trying to download an ISO file whose size may be larger. I am not sure if it would be a problem. When the network environment is not good, the downloaded data may be incomplete or incorrect which may cause your problem.


问:
javascript function needs doubleclick to work
I have these two javascript functions that for some reason I have to click the button twice for them to work. any ideas?

```<code>var shirts = new Array("shirtpink.png","shirtred.png", "shirtblue.png", "shirtyellow.png","shirt.png");

var index = 0;
function changecolor(){
    if (index > 4){
        index = 0;
    }
    var shirtpick = document.getElementById("shirt");
    shirtpick.setAttribute('src',shirts[index]);
    index++;
}
</code>```

other function:

```<code>function changecolorback(){
    index--;
    i++;
    if (index < 0){
        index = 4;
    }
    var shirtback = document.getElementById("shirt");
    shirtback.setAttribute('src',shirts[index]);
}
</code>```

答:
```<code>var shirts = ["shirtpink.png","shirtred.png", "shirtblue.png", "shirtyellow.png","shirt.png"],
    index = 0;

function changecolor(amount){
   index = (index + amount) % shirts.length;
   document.getElementById("shirt").setAttribute('src',shirts[index]);
}
</code>```

The reason was your increments:
You were incrementing after your code executed (in one function, but not in the other, so your changecolorback() should have behaved ok).

You also had i++ which looked redundant, and some variables that were only used once.

I shortened your code (drastically) so you get to these comments without too much scrolling.
Instead of calling changecolorback(), you can now just do changecolor(-1), and the forward method is changecolor(1).

Another advantage is that this will allow you to jump by more than one, or a random amount, which might (or might not) be useful.

EDIT:

JS implements modulus like Java, so negatives still hold their sign. I.e. (-1)%5 === -1

You can overcome this pretty easily by changing (more elegant although not quite equivalent):

```<code>index = Math.abs(index + amount) % shirts.length;
</code>```

or

```<code>index = ((index + amount) % shirts.length + shirts.length ) % shirts.length;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have these two javascript functions that for some reason I have to click the button twice for them to work. any ideas?

var shirts = new Array("shirtpink.png","shirtred.png", "shirtblue.png", "shirtyellow.png","shirt.png");

var index = 0;
function changecolor(){
    if (index > 4){
        index = 0;
    }
    var shirtpick = document.getElementById("shirt");
    shirtpick.setAttribute('src',shirts[index]);
    index++;
}

other function:

function changecolorback(){
    index--;
    i++;
    if (index < 0){
        index = 4;
    }
    var shirtback = document.getElementById("shirt");
    shirtback.setAttribute('src',shirts[index]);
}

Body:
var shirts = ["shirtpink.png","shirtred.png", "shirtblue.png", "shirtyellow.png","shirt.png"],
    index = 0;

function changecolor(amount){
   index = (index + amount) % shirts.length;
   document.getElementById("shirt").setAttribute('src',shirts[index]);
}

The reason was your increments:
You were incrementing after your code executed (in one function, but not in the other, so your changecolorback() should have behaved ok).

You also had i++ which looked redundant, and some variables that were only used once.

I shortened your code (drastically) so you get to these comments without too much scrolling.
Instead of calling changecolorback(), you can now just do changecolor(-1), and the forward method is changecolor(1).

Another advantage is that this will allow you to jump by more than one, or a random amount, which might (or might not) be useful.

EDIT:

JS implements modulus like Java, so negatives still hold their sign. I.e. (-1)%5 === -1

You can overcome this pretty easily by changing (more elegant although not quite equivalent):

index = Math.abs(index + amount) % shirts.length;

or

index = ((index + amount) % shirts.length + shirts.length ) % shirts.length;


问:
React Native gradlew clean commant is not working
i just formatted my PC and reinstalled the envs for react native.

and after i built a empty project getting weird erros.
Than i tryed to run gradlew clean in android folder and even this code is not working.

答:
you must first go to android directory by:

```<code>cd android
</code>```

then use this command:

```<code>./gradlew clean
</code>```

for running again , back to previous directory with:

```<code>cd ..
</code>```

and again there use this:

```<code>react-native run-android
</code>```

Body:
you must first go to android directory by:

cd android

then use this command:

./gradlew clean

for running again , back to previous directory with:

cd ..

and again there use this:

react-native run-android


问:
Send Message to selected user using laravel
I am trying to send message to selected user  unfortunately I am facing error how to fix it ? thanks.

please check error
  https://flareapp.io/share/67OAAVmr#F59

controller

```<code>                public function chataction(REQUEST $request)
                {
                $user = Auth::user();
                $m = $user->Chats()->create([
               'chat_message' => $request->input('message'),
               'from_user_id' =>Auth::user()->id,
               'to_user_id' =>$request->input('id'),
               ]);
               return ['status' => 'Message Sent!'];
                }
</code>```

html view

```<code>          <form action="{{route('chat.action')}}" method="post">
          @csrf
          <input type="hidden" name="id" >
          <div class="input-group">
          <input type="text" id="chatmessage" name="message" placeholder="Type Message ..."
          class="form-control">
          <span class="input-group-append">
          <button type="submit" name="btnsubmit" id="btnsubmit"  class="btn btn-
          primary">Send</button>
          </span>
          </div>
          </form>
</code>```

答:
Change your REQUEST

```<code>use Illuminate\Http\Request;

public function chataction(Request $request)
   {
     $user = Auth::user();
     $m = $user->Chats()->create([
          'chat_message' => $request->input('message'),
          'from_user_id' => Auth::user()->id,
          'to_user_id' => $request->input('id'),
          ]);
         return ['status' => 'Message Sent!'];
   }
</code>```

Change In your Model

use fillable when you are use create method to insert data

```<code>protected $fillable = ['chat_message', 'from_user_id', 'to_user_id'];
</code>```

Body:
I am trying to send message to selected user  unfortunately I am facing error how to fix it ? thanks.

please check error
  https://flareapp.io/share/67OAAVmr#F59

controller

                public function chataction(REQUEST $request)
                {
                $user = Auth::user();
                $m = $user->Chats()->create([
               'chat_message' => $request->input('message'),
               'from_user_id' =>Auth::user()->id,
               'to_user_id' =>$request->input('id'),
               ]);
               return ['status' => 'Message Sent!'];
                }

html view

          <form action="{{route('chat.action')}}" method="post">
          @csrf
          <input type="hidden" name="id" >

          <input type="text" id="chatmessage" name="message" placeholder="Type Message ..."
          class="form-control">

          <button type="submit" name="btnsubmit" id="btnsubmit"  class="btn btn-
          primary">Send</button>

          </form>

Body:
Change your REQUEST

use Illuminate\Http\Request;

public function chataction(Request $request)
   {
     $user = Auth::user();
     $m = $user->Chats()->create([
          'chat_message' => $request->input('message'),
          'from_user_id' => Auth::user()->id,
          'to_user_id' => $request->input('id'),
          ]);
         return ['status' => 'Message Sent!'];
   }

Change In your Model

use fillable when you are use create method to insert data

protected $fillable = ['chat_message', 'from_user_id', 'to_user_id'];


问:
How to change the branching point in Git?
Suppose I have the following structure in my git repo:

```<code>          C'---D'---E'---F'    (dev)
        /
A---B---C---D---E---F       (master)
</code>```

I would like to pull C' into the master branch and change the branching point to C', i.e., I want to turn the above into

```<code>              D'---E'---F'     (dev)
             /
A---B---C---C'---D---E---F  (master)
</code>```

I believe I should use a combination of cherry-picking and rebasing, but I am confused about how to do so exactly.  Which sequence of operations should I perform?

Suggestion after comments for a clearer schema (since same-letter commits in the original were in fact unnecessary)

```<code>          G---H---I---J   (dev)
         /
A---B---C---D---E---F     (master)
</code>```

with the associated expected result :

```<code>              H---I---J    (dev)
             /
A---B---C---G---D---E---F  (master)
</code>```

答:
You would need to do the following:

Take not of the hash-refs of these commits: C, C', D, E, F. Then:

git checkout master

git reset --hard C

git cherry-pick C'

git checkout dev

git rebase -i master (interactive rebase to get rid of C')

git checkout master

git cherry-pick D

git cherry-pick E

git cherry-pick F

Push both branches with --force to finish.

I do not recommend this if you're not comfortable with git but that's how I would go about it if absolutely needed to do it like that.

You can always go this route

```<code>                           D'---E'---F'     (dev)
                          /
A---B---C---D---E---F---C'  (master)
</code>```

and just cherry-pick C' then rebase your dev branch against master. That would be the simplest solution.

Body:
Suppose I have the following structure in my git repo:

          C'---D'---E'---F'    (dev)
        /
A---B---C---D---E---F       (master)

I would like to pull C' into the master branch and change the branching point to C', i.e., I want to turn the above into

              D'---E'---F'     (dev)
             /
A---B---C---C'---D---E---F  (master)

I believe I should use a combination of cherry-picking and rebasing, but I am confused about how to do so exactly.  Which sequence of operations should I perform?

Suggestion after comments for a clearer schema (since same-letter commits in the original were in fact unnecessary)

          G---H---I---J   (dev)
         /
A---B---C---D---E---F     (master)

with the associated expected result :

              H---I---J    (dev)
             /
A---B---C---G---D---E---F  (master)

Body:
You would need to do the following:

Take not of the hash-refs of these commits: C, C', D, E, F. Then:

git checkout master

git reset --hard C

git cherry-pick C'

git checkout dev

git rebase -i master (interactive rebase to get rid of C')

git checkout master

git cherry-pick D

git cherry-pick E

git cherry-pick F

Push both branches with --force to finish.

I do not recommend this if you're not comfortable with git but that's how I would go about it if absolutely needed to do it like that.

You can always go this route

                           D'---E'---F'     (dev)
                          /
A---B---C---D---E---F---C'  (master)

and just cherry-pick C' then rebase your dev branch against master. That would be the simplest solution.


问:
Error: Expected undefined to equal in karma
Test Case File

```<code>describe('homeController', function() {
beforeEach(module('moduleInjectionApp'));

var $controller;
var $rootScope;
beforeEach(inject(function(_$controller_, _$rootScope_) {
    $controller = _$controller_('homeController', {'$scope': scope});
    $rootScope = _$rootScope_;
}));

describe('$scope.ID', function() {
    it('Check the scope object', function() {
        var $scope = {};
        expect($scope.ID).toEqual(5);
    });
  });
});
</code>```

Controller File

```<code> angular.module('moduleInjectionApp').controller('homeController', homeController)
 homeController.$inject = ["$scope", "$rootScope", "$location"];
 function homeController($scope, $rootScope, $location) {
     console.log("entered homeController")
     $scope.ID = 5;
     $rootScope.loginObj = JSON.parse(localStorage.getItem('login_data'));
 }
</code>```

Error

```<code>Error: Expected undefined to equal 5.
        at <Jasmine>
        at UserContext.<anonymous> (WebContent/test/home/homeSpec.js:14:31)
        at <Jasmine>
</code>```

Chrome 75.0.3770 (Windows 10.0.0): Executed 1 of 1 (1 FAILED) (0.036 secs / 0.012 secs)
  TOTAL: 1 FAILED, 0 SUCCESS

答:
Try

```<code>describe('homeController', function() {
    beforeEach(module('moduleInjectionApp'));

    var $controller;

    beforeEach(inject(function(_$controller_){
              $controller = _$controller_;
    }));

    describe('$scope.ID', function() {
        it('Check the scope object', function() {
            var $scope = {};
            var controller = $controller('homeController', { $scope: $scope });
            expect($scope.ID).toEqual(5);
        });
    });
});

</code>```

When you declare var $scope = {};, you will always get $scope.ID as undefined. You need to do

```<code>var $scope = { ID: 5}

</code>```

Anyways, in unit test, you dont create some values and then expect assertions on it. You validate the values which are already defined or have been modified. Here you were trying to declare and then putting expect (which will always pass)

Body:
Test Case File

describe('homeController', function() {
beforeEach(module('moduleInjectionApp'));

var $controller;
var $rootScope;
beforeEach(inject(function(_$controller_, _$rootScope_) {
    $controller = _$controller_('homeController', {'$scope': scope});
    $rootScope = _$rootScope_;
}));

describe('$scope.ID', function() {
    it('Check the scope object', function() {
        var $scope = {};
        expect($scope.ID).toEqual(5);
    });
  });
});

Controller File

 angular.module('moduleInjectionApp').controller('homeController', homeController)
 homeController.$inject = ["$scope", "$rootScope", "$location"];
 function homeController($scope, $rootScope, $location) {
     console.log("entered homeController")
     $scope.ID = 5;
     $rootScope.loginObj = JSON.parse(localStorage.getItem('login_data'));
 }

Error

Error: Expected undefined to equal 5.
        at <Jasmine>
        at UserContext.<anonymous> (WebContent/test/home/homeSpec.js:14:31)
        at <Jasmine>

Chrome 75.0.3770 (Windows 10.0.0): Executed 1 of 1 (1 FAILED) (0.036 secs / 0.012 secs)
  TOTAL: 1 FAILED, 0 SUCCESS

Body:
Try

describe('homeController', function() {
    beforeEach(module('moduleInjectionApp'));

    var $controller;

    beforeEach(inject(function(_$controller_){
              $controller = _$controller_;
    }));

    describe('$scope.ID', function() {
        it('Check the scope object', function() {
            var $scope = {};
            var controller = $controller('homeController', { $scope: $scope });
            expect($scope.ID).toEqual(5);
        });
    });
});

When you declare var $scope = {};, you will always get $scope.ID as undefined. You need to do

var $scope = { ID: 5}

Anyways, in unit test, you dont create some values and then expect assertions on it. You validate the values which are already defined or have been modified. Here you were trying to declare and then putting expect (which will always pass)


问:
Where can i find a dataset of handwritten broken numbers or floats or digits?
I m looking for DATASET of HANDWRITTEN BROKEN NUMBERS or floats or digits which means for example a teacher s handwritten mark of students or anything like these images below

thank you in advance

example

答:
Google recently launched a Dataset search engine, you can type in handwritten digits and check all the options (link to that exact query).

Some options available (besides the well known MNIST):

Pen-Based Recognition of Handwritten Digits (link)

Semeion Handwritten Digits (link)


问:
How to return bool value with navigator.pop?
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.</p>

```<code>final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}
</code>```

答:
```<code>onPressed:() {
  result = false;
  //print(result);
  setState(() {});

  Navigator.pop(context, result);
}
</code>```

or

```<code>onPressed:() {
  setState(() {
    result = false;
    //print(result);
    Navigator.pop(context, result);
  });
}
</code>```

Body:
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.

final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}

Body:
onPressed:() {
  result = false;
  //print(result);
  setState(() {});

  Navigator.pop(context, result);
}

or

onPressed:() {
  setState(() {
    result = false;
    //print(result);
    Navigator.pop(context, result);
  });
}


问:
memcpy / sub list of linked list using pointers
In legacy program I'm working on, there are several structs for linked lists as:

```<code>typedef struct Unit_Cell
{
    short           Type ;
    char            Name[x] ;
    short           X ;
    short           Y ;
    struct Unit_Cell *Next;
} Unit_Cell ;

typedef struct
{
    Unit_Cell    *Start;
    Unit_Cell    *Current;
} List_Cell;
</code>```

I have a pointer to the List_Cell structure, which contains all cells.

List_Cell *FullList; # malloc'ed, with added elements etc etc

For a new development, I need to associate a subset of this full list, to new structures that looks like: (simplified)

```<code>typedef struct Unit_NewElement
{
    char            Name[y];
    int             Value;
    List_Cell      *ListCells;
    struct Unit_NewElement *Next;
} Unit_NewElement;

typedef struct
{
    Unit_NewElement   *Start;
    Unit_NewElement   *Current;
} List_Cell;
</code>```

Creating a new element as:

Unit_NewElement *NewElement; # malloc'ed, with added elements etc etc ...
                           # EXCEPT LIST CELLS !

Looping on the full list of cells, I'm doing calculations to know if the Current cell need to be associated to my element structure.

Basically, we would do something like:

```<code>
# Keeping the last element
Unit_Cell *Temp = NewElement->ListCells->Current;

# Replacing last element
NewElement->ListCells->Current = FullList->Current;

# Setting temp element (which is now our previous), next pointer to the new current
Temp->Next = NewElement->ListCells->Current;

</code>```

But doing so, I'm literally broking the original "FullList" list.
Which I don't want.

I need to be able to add cells from the full list, for every NewElements I need, without impacted the full list itself.

Is memcpy the way to go ?

memcpy(Element->ListCells->Current, FullList->Current, sizeof(Unit_Cell));

How to handle the fact that there is also a pointer in the copied structure ?

And what about copying directly data without memcpy:

*Element->ListCells->Current = *FullList->Current;

Thanks

答:
I think what you need to do in order to get a real copy of a list is a combination of malloc and memcpy, also the copied Next pointer must be overwritten.

Since I dont know how your sublist is created, I suggested something like a given starting cell and the amount of cells to be copied - then you could do sth like this:

```<code>ListCell *copyList(UnitCell *from, int n)
{
   int i = 0;

   if (!from || n <= 0)
      return NULL;

   ListCell *newList = (ListCell*)malloc(sizeof(ListCell));
   newList->Start = NULL;
   newList->Current = NULL;

   while (from && i++ < n)
   {
      if (!newList->Start)
      {
          newList->Start = (UnitCell*)malloc(sizeof(UnitCell));
          memcpy(newList->Start, from, sizeof(UnitCell));
          newList->Current = newList->Start;
      }
      else if (newList->Current)
      {
          newList->Current->Next = (UnitCell*)malloc(sizeof(UnitCell));
          memcpy(newList->Current->Next, from, sizeof(UnitCell));
          newList->Current = newList->Current->Next;
      }

      from = from->Next;
   }

   // Next-pointer of last cell still points to source list cell
   if (newList->Current)
      newList->Current->Next = NULL;

   return newList;
}
</code>```

(I actually did not test this code so there might be some errors left)

Body:
In legacy program I'm working on, there are several structs for linked lists as:

typedef struct Unit_Cell
{
    short           Type ;
    char            Name[x] ;
    short           X ;
    short           Y ;
    struct Unit_Cell *Next;
} Unit_Cell ;

typedef struct
{
    Unit_Cell    *Start;
    Unit_Cell    *Current;
} List_Cell;

I have a pointer to the List_Cell structure, which contains all cells.

List_Cell *FullList; # malloc'ed, with added elements etc etc

For a new development, I need to associate a subset of this full list, to new structures that looks like: (simplified)

typedef struct Unit_NewElement
{
    char            Name[y];
    int             Value;
    List_Cell      *ListCells;
    struct Unit_NewElement *Next;
} Unit_NewElement;

typedef struct
{
    Unit_NewElement   *Start;
    Unit_NewElement   *Current;
} List_Cell;

Creating a new element as:

Unit_NewElement *NewElement; # malloc'ed, with added elements etc etc ...
                           # EXCEPT LIST CELLS !

Looping on the full list of cells, I'm doing calculations to know if the Current cell need to be associated to my element structure.

Basically, we would do something like:

# Keeping the last element
Unit_Cell *Temp = NewElement->ListCells->Current;

# Replacing last element
NewElement->ListCells->Current = FullList->Current;

# Setting temp element (which is now our previous), next pointer to the new current
Temp->Next = NewElement->ListCells->Current;

But doing so, I'm literally broking the original "FullList" list.
Which I don't want.

I need to be able to add cells from the full list, for every NewElements I need, without impacted the full list itself.

Is memcpy the way to go ?

memcpy(Element->ListCells->Current, FullList->Current, sizeof(Unit_Cell));

How to handle the fact that there is also a pointer in the copied structure ?

And what about copying directly data without memcpy:

*Element->ListCells->Current = *FullList->Current;

Thanks

Body:
I think what you need to do in order to get a real copy of a list is a combination of malloc and memcpy, also the copied Next pointer must be overwritten.

Since I dont know how your sublist is created, I suggested something like a given starting cell and the amount of cells to be copied - then you could do sth like this:

ListCell *copyList(UnitCell *from, int n)
{
   int i = 0;

   if (!from || n <= 0)
      return NULL;

   ListCell *newList = (ListCell*)malloc(sizeof(ListCell));
   newList->Start = NULL;
   newList->Current = NULL;

   while (from && i++ < n)
   {
      if (!newList->Start)
      {
          newList->Start = (UnitCell*)malloc(sizeof(UnitCell));
          memcpy(newList->Start, from, sizeof(UnitCell));
          newList->Current = newList->Start;
      }
      else if (newList->Current)
      {
          newList->Current->Next = (UnitCell*)malloc(sizeof(UnitCell));
          memcpy(newList->Current->Next, from, sizeof(UnitCell));
          newList->Current = newList->Current->Next;
      }

      from = from->Next;
   }

   // Next-pointer of last cell still points to source list cell
   if (newList->Current)
      newList->Current->Next = NULL;

   return newList;
}

(I actually did not test this code so there might be some errors left)


问:
making unequal array control
I have an array ,vehicle owners and tools are available, there is no stability in the array there are three car owners,vehicles they own show. in short; I have 3 car owners and I wanted to show on the page which of these three vehicles are ford, male, scania

code it gives me
enter image description here

i want to do
enter image description here

```<code><?php
$vehicles = array(

    array(
     "vehicleowner" =>("john"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

    array(
     "vehicleowner" =>("alex"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

     array(
     "vehicleowner" =>("Robert"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

 );

echo '<table border="1">
<thead>
<tr>
<td>vehicleowner</td>
<td>Ford</td>
<td>Scania</td>
<td>Man</td>
';

foreach($vehicles as $i => $value){
     // echo "```";
    // print_r($value);

    $ford = $value["vehicles"][$i]["id"]==1;

    if($ford){ $fordd = $value["vehicles"][$i]["brand"];}

    $scania = $value["vehicles"][$i]["id"]==2;
    if($scania){ $scaniaa = $value["vehicles"][$i]["brand"];}

    $man = $value["vehicles"][$i]["id"]==3;
    if($man){ $mann = $value["vehicles"][$i]["brand"];}

?>

 <?php echo $value["vehicleowner"]?>
 <?php echo isset($fordd) ? $fordd : '-';?>
 <?php echo isset($scaniaa) ? $scaniaa : '-';?>
 <?php echo isset($mann) ? $mann : '-';?>

<?php } ?>
```

答:
One simple way to do this, based on what you already have, would be

```<code>foreach($vehicles as $i => $value){
  $ford = $scania = $man = '-'; // initialize variables with placeholder value '-'
  foreach($value['vehicles'] as $vehicle) {
    // set variables to brand, if model matches
    if($vehicle['model'] == 'ford') {
      $ford = $vehicle['brand'];
    }
    if($vehicle['model'] == 'scania') {
      $scania = $vehicle['brand'];
    }
    if($vehicle['model'] == 'man') {
      $man = $vehicle['brand'];
    }
  }

?>

 <tr>
 <td><?php echo $value["vehicleowner"]?></td>
 <td><?php echo $ford;?></td>
 <td><?php echo $scania;?></td>
 <td><?php echo $man;?></td>
 <tr>
</code>```

More sophisticated variants using an array instead of individual variables, etc., are of course conceivable.

Title: making unequal array control

Body:
I have an array ,vehicle owners and tools are available, there is no stability in the array there are three car owners,vehicles they own show. in short; I have 3 car owners and I wanted to show on the page which of these three vehicles are ford, male, scania

code it gives me
enter image description here

i want to do
enter image description here

<?php
$vehicles = array(

    array(
     "vehicleowner" =>("john"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

    array(
     "vehicleowner" =>("alex"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

     array(
     "vehicleowner" =>("Robert"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

 );

echo '

vehicleowner
Ford
Scania
Man
';

foreach($vehicles as $i => $value){
     // echo "
";
    // print_r($value);

    $ford = $value["vehicles"][$i]["id"]==1;

    if($ford){ $fordd = $value["vehicles"][$i]["brand"];}

    $scania = $value["vehicles"][$i]["id"]==2;
    if($scania){ $scaniaa = $value["vehicles"][$i]["brand"];}

    $man = $value["vehicles"][$i]["id"]==3;
    if($man){ $mann = $value["vehicles"][$i]["brand"];}

?>

 <?php echo $value["vehicleowner"]?>
 <?php echo isset($fordd) ? $fordd : '-';?>
 <?php echo isset($scaniaa) ? $scaniaa : '-';?>
 <?php echo isset($mann) ? $mann : '-';?>

<?php } ?>

Body:
One simple way to do this, based on what you already have, would be

foreach($vehicles as $i => $value){
  $ford = $scania = $man = '-'; // initialize variables with placeholder value '-'
  foreach($value['vehicles'] as $vehicle) {
    // set variables to brand, if model matches
    if($vehicle['model'] == 'ford') {
      $ford = $vehicle['brand'];
    }
    if($vehicle['model'] == 'scania') {
      $scania = $vehicle['brand'];
    }
    if($vehicle['model'] == 'man') {
      $man = $vehicle['brand'];
    }
  }

?>

 <tr>
 <td><?php echo $value["vehicleowner"]?></td>
 <td><?php echo $ford;?></td>
 <td><?php echo $scania;?></td>
 <td><?php echo $man;?></td>
 <tr>

More sophisticated variants using an array instead of individual variables, etc., are of course conceivable.


问:
Adding variable hours to timestamp in Spark SQL
I have one column Start_Time with a timestamp, and one column Time_Zone_Offset, an integer. How can I add the Time_Zone_Offset to Start_Time as a number of hours?

Example MyTable:

```<code>id  Start_Time            Time_Zone_Offset

1   2020-01-12 00:00:00     1
2   2020-01-12 00:00:00     2
</code>```

Desired output:

```<code>id  Local_Start_Time

1   2020-01-12 01:00:00
2   2020-01-12 02:00:00
</code>```

Attempt:

```<code>SELECT id, Start_time + INTERVAL time_zone_offset HOURS AS Local_Start_Time
FROM MyTable
</code>```

This doesn't seem to work, and I can't use from_utc_timestamp as I don't have the actual timezone details, just the time-zone offset at the time being considered.

答:
Adding an alternative to Benoit's answer using a python UDF: </p>

```<code>from pyspark.sql import SQLContext
from datetime import datetime, timedelta
from pyspark.sql.types import TimestampType

# Defining pyspark function to add hours onto datetime
def addHours(my_datetime, hours):
    # Accounting for NULL (None in python) values
    if (hours is None) or (my_datetime is None):
        adjusted_datetime = None
    else:
        adjusted_datetime = my_datetime + timedelta(hours = hours)
    return adjusted_datetime

# Registering the function as a UDF to use in SQL, and defining the output type as 'TimestampType' (this is important, the default is StringType)
sqlContext.udf.register("add_hours", addHours, TimestampType());
</code>```

<p>followed by: </p>

```<code>SELECT id, add_hours(Start_Time, Time_Zone_Offset) AS Local_Start_Time
FROM MyTable
</code>```

Body:
I have one column Start_Time with a timestamp, and one column Time_Zone_Offset, an integer. How can I add the Time_Zone_Offset to Start_Time as a number of hours?

Example MyTable:

id  Start_Time            Time_Zone_Offset

1   2020-01-12 00:00:00     1
2   2020-01-12 00:00:00     2

Desired output:

id  Local_Start_Time

1   2020-01-12 01:00:00
2   2020-01-12 02:00:00

Attempt:

SELECT id, Start_time + INTERVAL time_zone_offset HOURS AS Local_Start_Time
FROM MyTable

This doesn't seem to work, and I can't use from_utc_timestamp as I don't have the actual timezone details, just the time-zone offset at the time being considered.

Body:
Adding an alternative to Benoit's answer using a python UDF:

from pyspark.sql import SQLContext
from datetime import datetime, timedelta
from pyspark.sql.types import TimestampType

# Defining pyspark function to add hours onto datetime
def addHours(my_datetime, hours):
    # Accounting for NULL (None in python) values
    if (hours is None) or (my_datetime is None):
        adjusted_datetime = None
    else:
        adjusted_datetime = my_datetime + timedelta(hours = hours)
    return adjusted_datetime

# Registering the function as a UDF to use in SQL, and defining the output type as 'TimestampType' (this is important, the default is StringType)
sqlContext.udf.register("add_hours", addHours, TimestampType());

followed by:

SELECT id, add_hours(Start_Time, Time_Zone_Offset) AS Local_Start_Time
FROM MyTable


问:
Multiply each row of one dataframe by all rows of a second dataframe
Am struggling with operation as my datasets are very large and i have provided an example of what i want.

I have two dataframes.

df1 - contains sampling-derived iterations for each parameter of a variable defined as the column name (10,000 rows)

df2 - contains the actual value of each of the variable defined as the column name (4,000 rows)

I want a df3 which is effectively the multiplication of each row of df2 by df1 and would therefore be 4000*10000 rows

As a short example i have provided a minimal example of df1 and df2. I have provided the output that i would be looking at shown in df3.

```<code>df1 <- structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
-2L))

df3 <- structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), intercept = c(3.4, 3.6, 3.7, 3.4, 3.6,
3.7), age = c(3.2, 2, 2.4, 3.6, 2.25, 2.7), male = c(0.07, 0.06,
0.07, 0, 0, 0)), class = "data.frame", row.names = c(NA, -6L))
</code>```

Can somebody point me to an efficient way to do this in R?

答:
You can perform row-wise Kronecker product (from package MGLM) like below

```<code>out <- data.frame(id = rep(df2$id,each=nrow(df1)),
                  t(MGLM::kr(t(df2[-1]),t(df1))))
</code>```

such that

```<code>> out
  id intercept  age male
1  a       3.4 3.20 0.07
2  a       3.6 2.00 0.06
3  a       3.7 2.40 0.07
4  b       3.4 3.60 0.00
5  b       3.6 2.25 0.00
6  b       3.7 2.70 0.00
</code>```

Benchmarking (so far the approach by @Sotos is the winner)

```<code>df1 <- do.call(rbind,replicate(500,structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
                                                            0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
                                                                                -3L)),simplify = F))

df2 <- do.call(rbind,replicate(100,structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
                      intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
                                                                                -2L)),simplify = F))

library(MGLM)
library(purrr)

f_ThomasIsCoding <- function() {
  data.frame(id = rep(df2$id,each=nrow(df1)),
                    t(MGLM::kr(t(df2[-1]),t(df1))))
}

f_tmfmnk_1 <- function() {
  map_dfr(.x = asplit(df2[-1], 1), ~ sweep(df1, 2, FUN = `*`, .x))
}

f_tmfmnk_2 <- function() {
  data.frame(do.call(rbind, lapply(asplit(df2[-1], 1), function(x) sweep(df1, 2, FUN = `*`, x))),
             id = rep(df2$id, each = nrow(df1)))
}

f_RonakShah <- function() {
  new1 <- df1[rep(seq(nrow(df1)), nrow(df2)), ]
  new2 <- df2[rep(seq(nrow(df2)), each = nrow(df1)),]
  out <- cbind(new2[1], new1 * new2[-1])
  rownames(out) <- NULL
  out
}

f_Sotos <- function() {
  data.frame(id = rep(df2$id, each = nrow(df1)),
             mapply(function(x, y)c(outer(x, y, `*`)), df1, df2[-1])
  )
}

bmk <- microbenchmark(times = 20,
               unit = "relative",
               f_ThomasIsCoding(),
               f_tmfmnk_1(),
               f_tmfmnk_2(),
               f_RonakShah(),
               f_Sotos())
</code>```

which gives

```<code>> bmk
Unit: relative
               expr       min        lq      mean    median       uq       max neval
 f_ThomasIsCoding()  1.186124  1.218201  1.197346  1.321731 1.042721  1.077854    20
       f_tmfmnk_1()  7.594520  7.572723  4.539698  7.297610 2.437621  3.446436    20
       f_tmfmnk_2()  9.670286 12.212220  6.583183 11.888061 3.370593  4.088534    20
      f_RonakShah() 28.918724 28.861437 16.707258 27.889563 8.403161 11.668252    20
          f_Sotos()  1.000000  1.000000  1.000000  1.000000 1.000000  1.000000    20
</code>```

Body:
Am struggling with operation as my datasets are very large and i have provided an example of what i want.

I have two dataframes.

df1 - contains sampling-derived iterations for each parameter of a variable defined as the column name (10,000 rows)

df2 - contains the actual value of each of the variable defined as the column name (4,000 rows)

I want a df3 which is effectively the multiplication of each row of df2 by df1 and would therefore be 4000*10000 rows

As a short example i have provided a minimal example of df1 and df2. I have provided the output that i would be looking at shown in df3.

df1 <- structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
-2L))

df3 <- structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), intercept = c(3.4, 3.6, 3.7, 3.4, 3.6,
3.7), age = c(3.2, 2, 2.4, 3.6, 2.25, 2.7), male = c(0.07, 0.06,
0.07, 0, 0, 0)), class = "data.frame", row.names = c(NA, -6L))

Can somebody point me to an efficient way to do this in R?

Body:
You can perform row-wise Kronecker product (from package MGLM) like below

out <- data.frame(id = rep(df2$id,each=nrow(df1)),
                  t(MGLM::kr(t(df2[-1]),t(df1))))

such that

> out
  id intercept  age male
1  a       3.4 3.20 0.07
2  a       3.6 2.00 0.06
3  a       3.7 2.40 0.07
4  b       3.4 3.60 0.00
5  b       3.6 2.25 0.00
6  b       3.7 2.70 0.00

Benchmarking (so far the approach by @Sotos is the winner)

df1 <- do.call(rbind,replicate(500,structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
                                                            0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
                                                                                -3L)),simplify = F))

df2 <- do.call(rbind,replicate(100,structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
                      intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
                                                                                -2L)),simplify = F))

library(MGLM)
library(purrr)

f_ThomasIsCoding <- function() {
  data.frame(id = rep(df2$id,each=nrow(df1)),
                    t(MGLM::kr(t(df2[-1]),t(df1))))
}

f_tmfmnk_1 <- function() {
  map_dfr(.x = asplit(df2[-1], 1), ~ sweep(df1, 2, FUN = `*`, .x))
}

f_tmfmnk_2 <- function() {
  data.frame(do.call(rbind, lapply(asplit(df2[-1], 1), function(x) sweep(df1, 2, FUN = `*`, x))),
             id = rep(df2$id, each = nrow(df1)))
}

f_RonakShah <- function() {
  new1 <- df1[rep(seq(nrow(df1)), nrow(df2)), ]
  new2 <- df2[rep(seq(nrow(df2)), each = nrow(df1)),]
  out <- cbind(new2[1], new1 * new2[-1])
  rownames(out) <- NULL
  out
}

f_Sotos <- function() {
  data.frame(id = rep(df2$id, each = nrow(df1)),
             mapply(function(x, y)c(outer(x, y, `*`)), df1, df2[-1])
  )
}

bmk <- microbenchmark(times = 20,
               unit = "relative",
               f_ThomasIsCoding(),
               f_tmfmnk_1(),
               f_tmfmnk_2(),
               f_RonakShah(),
               f_Sotos())

which gives

> bmk
Unit: relative
               expr       min        lq      mean    median       uq       max neval
 f_ThomasIsCoding()  1.186124  1.218201  1.197346  1.321731 1.042721  1.077854    20
       f_tmfmnk_1()  7.594520  7.572723  4.539698  7.297610 2.437621  3.446436    20
       f_tmfmnk_2()  9.670286 12.212220  6.583183 11.888061 3.370593  4.088534    20
      f_RonakShah() 28.918724 28.861437 16.707258 27.889563 8.403161 11.668252    20
          f_Sotos()  1.000000  1.000000  1.000000  1.000000 1.000000  1.000000    20


问:
Azure Devops + Coverlet + SonarQube shows 0%
Good morning,

Sorry to bother you, I have a problem and I have no leads.

I have a pipeline on Azure DevOps where I use coverlet to generate a code coverage report when I use the command "dotnet test".

Indeed, the report is well generated.

At first, in the "Prepare analysis on SonarQube" step, I set the variable "sonar.cs.opencover.reportsPaths="$(Agent.TempDirectory)/coverage.opencover.xml".

And yet the end in my SonarQube there is 0% code coverage... I don't know what to do or any leads...

Thanks

答:
I did a lot of things to finally managed to get the coverage working but I think that the problem was the "ProjectGUID" missing in each .csproj of my solution making the projects ignored by SonarQube scanner.

I also upgraded from SonarQube 6.2 to 8.1 at the same time which may have solved the problem.

My steps remained unchanged to make this work.


问:
How to use Two Toggle buttons on same page having same function with different css?
I have been trying to hard to add 2 Toggle Buttons having different styles (css) on Menu Bar and footer page. They are to be used for night and dark mode.

However when I use

```<code>onclick="themeToggle()" id="theme-switcher"
</code>```

for both of the buttons, only one of them works.

This is my Toggle Buttons Test Page.

This is the js which is being used :

```<code> var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;

 let onpageLoad = localStorage.getItem("theme") || "";
 if(onpageLoad != null && onpageLoad  == 'dark-mode'){
      tSwitcher.checked = true;
 }
 element.classList.add(onpageLoad);

function themeToggle(){
      if(tSwitcher.checked){
          localStorage.setItem('theme', 'dark-mode');
            element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
            element.classList.remove('dark-mode');
        }
    }

</code>```

This is the code for Two Toggle buttons

```<code>
    <label class="switcher">
    <input type="checkbox" onclick="themeToggle()" id="theme-switcher">
    <div>
    <i class="fas fa-sun"></i>
    <i class="fas fa-arrow-left arrow"></i>
    <i class="fas fa-moon"></i>
    </div>
    </label>

</code>```

```<code>
 <label class="switch" style="padding: 23px 0;">
<input type="checkbox" onclick="themeToggle()" id="theme-switcher">
<div>
    <span></span>
</div>

</code>```

Kindly help me in solving the issue with the code as well.

Thanks for the help.

答:
Because you are using ID in <input type="checkbox" onclick="themeToggle()" id="theme-switcher">, which you repeat in other checkbox. so only first ID in the DOM will be taken.

Change your <input type="checkbox" onclick="themeToggle()" id="theme-switcher">

To

<input type="checkbox" onclick="themeToggle()" class="theme-switcher">

And update the below code

Note: dont repeat ID

```<code>var tSwitcher = document.getElementsByClassName('theme-switcher');
let element = document.body;

let onpageLoad = localStorage.getItem("theme") || "";
if (onpageLoad != null && onpageLoad == 'dark-mode') {
        for(let i = 0; i<tSwitcher.length; i++){
                tSwitcher[i].checked = true;
    }

}

if(onpageLoad) element.classList.add(onpageLoad);
</code>```

So update your themeToggle() to

```<code>  function themeToggle() {
    if (event.target.checked) {
      localStorage.setItem('theme', 'dark-mode');
      element.classList.add('dark-mode');
    } else {
      localStorage.setItem('theme', '');
      element.classList.remove('dark-mode');
    }
  }
</code>```

Body:
I have been trying to hard to add 2 Toggle Buttons having different styles (css) on Menu Bar and footer page. They are to be used for night and dark mode.

However when I use

onclick="themeToggle()" id="theme-switcher"

for both of the buttons, only one of them works.

This is my Toggle Buttons Test Page.

This is the js which is being used :

 var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;

 let onpageLoad = localStorage.getItem("theme") || "";
 if(onpageLoad != null && onpageLoad  == 'dark-mode'){
      tSwitcher.checked = true;
 }
 element.classList.add(onpageLoad);

function themeToggle(){
      if(tSwitcher.checked){
          localStorage.setItem('theme', 'dark-mode');
            element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
            element.classList.remove('dark-mode');
        }
    }

This is the code for Two Toggle buttons

    <input type="checkbox" onclick="themeToggle()" id="theme-switcher">

<input type="checkbox" onclick="themeToggle()" id="theme-switcher">

Kindly help me in solving the issue with the code as well.

Thanks for the help.

Body:
Because you are using ID in <input type="checkbox" onclick="themeToggle()" id="theme-switcher">, which you repeat in other checkbox. so only first ID in the DOM will be taken.

Change your <input type="checkbox" onclick="themeToggle()" id="theme-switcher">

To

<input type="checkbox" onclick="themeToggle()" class="theme-switcher">

And update the below code

Note: dont repeat ID

var tSwitcher = document.getElementsByClassName('theme-switcher');
let element = document.body;

let onpageLoad = localStorage.getItem("theme") || "";
if (onpageLoad != null && onpageLoad == 'dark-mode') {
        for(let i = 0; i<tSwitcher.length; i++){
                tSwitcher[i].checked = true;
    }

}

if(onpageLoad) element.classList.add(onpageLoad);

So update your themeToggle() to

  function themeToggle() {
    if (event.target.checked) {
      localStorage.setItem('theme', 'dark-mode');
      element.classList.add('dark-mode');
    } else {
      localStorage.setItem('theme', '');
      element.classList.remove('dark-mode');
    }
  }


问:
DenseNet: Graph disconnected: cannot obtain value for tensor
I am trying to build up a Densenet but stuck with the following error..
Here is the smallest example to reproduce:

```<code>import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as tfkl

def create_model(input_dim):

    feature_list = list()
    input_x = tfkl.Input(shape=input_dim, name="Inputs")
    feature_list.append(input_x)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv1")(input_x)
    feature_list.append(x)

    x = tfkl.Concatenate(axis=-1, name="Concat1")(feature_list)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv2")(x)
    feature_list.append(x)
    x = tfkl.Concatenate(axis=-1, name="Concat2")(feature_list)

    return tf.keras.Model(inputs=input_x, outputs=x)

z = create_model((128,128,2))
</code>```

The error I get:

```<code>ValueError: Graph disconnected: cannot obtain value for tensor Tensor("Conv2/Identity:0", shape=(None, 128, 128, 16), dtype=float32) at layer "Concat1". The following previous layers were accessed without issue: ['Inputs', 'Conv1']
</code>```

I could not realize what is wrong with this model?

The idea behind using feature_list here is that later I can create a dense block with a variable number of convolution layers, i.e.:

```<code>    for i in range(nb_layers):
          nb_filter += growth_rate
          x = tfkl.Concatenate(axis=-1)(feature_list)
          x = tfkl.Conv2D(nb_filter , kernel_size=(3, 3), padding="same")(x)
          feature_list.append(x)
</code>```

Furthermore, if I comment out the following two lines in create_model function:

```<code>    #feature_list.append(x)
    #x = tfkl.Concatenate(axis=-1, name="Concat2")(feature_list)
</code>```

then the model works without problems (so it means that generally Concatenate works correctly):

```<code>z.summary()
Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
Inputs (InputLayer)             [(None, 128, 128, 2) 0
__________________________________________________________________________________________________
Conv1 (Conv2D)                  (None, 128, 128, 16) 304         Inputs[0][0]
__________________________________________________________________________________________________
Concat1 (Concatenate)           (None, 128, 128, 18) 0           Inputs[0][0]
                                                                 Conv1[0][0]
__________________________________________________________________________________________________
Conv2 (Conv2D)                  (None, 128, 128, 16) 2608        Concat1[0][0]
==================================================================================================
Total params: 2,912
Trainable params: 2,912
Non-trainable params: 0
__________________________________________________________________________________________________
</code>```

答:
I think that's because of the names of your layers, your trying to concatenate an array with layer names that are the same : [input_x, x, x], try this :</p>

```<code>import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as tfkl

def create_model(input_dim):

    feature_list = list()
    input_x = tfkl.Input(shape=input_dim)
    feature_list.append(input_x)
    conv1 = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same")(input_x)
    feature_list.append(conv1)

    concat1 = tfkl.Concatenate(axis=-1)(feature_list)
    conv2 = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same")(concat1)
    feature_list.append(conv2)

    concat2 = tfkl.Concatenate(axis=-1)(feature_list)

    return tf.keras.Model(inputs=input_x, outputs=concat2)

z = create_model((128,128,2))
</code>```

Body:
I am trying to build up a Densenet but stuck with the following error..
Here is the smallest example to reproduce:

import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as tfkl

def create_model(input_dim):

    feature_list = list()
    input_x = tfkl.Input(shape=input_dim, name="Inputs")
    feature_list.append(input_x)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv1")(input_x)
    feature_list.append(x)

    x = tfkl.Concatenate(axis=-1, name="Concat1")(feature_list)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv2")(x)
    feature_list.append(x)
    x = tfkl.Concatenate(axis=-1, name="Concat2")(feature_list)

    return tf.keras.Model(inputs=input_x, outputs=x)

z = create_model((128,128,2))

The error I get:

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("Conv2/Identity:0", shape=(None, 128, 128, 16), dtype=float32) at layer "Concat1". The following previous layers were accessed without issue: ['Inputs', 'Conv1']

I could not realize what is wrong with this model?

The idea behind using feature_list here is that later I can create a dense block with a variable number of convolution layers, i.e.:

    for i in range(nb_layers):
          nb_filter += growth_rate
          x = tfkl.Concatenate(axis=-1)(feature_list)
          x = tfkl.Conv2D(nb_filter , kernel_size=(3, 3), padding="same")(x)
          feature_list.append(x)

Furthermore, if I comment out the following two lines in create_model function:

    #feature_list.append(x)
    #x = tfkl.Concatenate(axis=-1, name="Concat2")(feature_list)

then the model works without problems (so it means that generally Concatenate works correctly):

z.summary()
Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
Inputs (InputLayer)             [(None, 128, 128, 2) 0
__________________________________________________________________________________________________
Conv1 (Conv2D)                  (None, 128, 128, 16) 304         Inputs[0][0]
__________________________________________________________________________________________________
Concat1 (Concatenate)           (None, 128, 128, 18) 0           Inputs[0][0]
                                                                 Conv1[0][0]
__________________________________________________________________________________________________
Conv2 (Conv2D)                  (None, 128, 128, 16) 2608        Concat1[0][0]
==================================================================================================
Total params: 2,912
Trainable params: 2,912
Non-trainable params: 0
__________________________________________________________________________________________________

Body:
I think that's because of the names of your layers, your trying to concatenate an array with layer names that are the same : [input_x, x, x], try this :

import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as tfkl

def create_model(input_dim):

    feature_list = list()
    input_x = tfkl.Input(shape=input_dim)
    feature_list.append(input_x)
    conv1 = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same")(input_x)
    feature_list.append(conv1)

    concat1 = tfkl.Concatenate(axis=-1)(feature_list)
    conv2 = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same")(concat1)
    feature_list.append(conv2)

    concat2 = tfkl.Concatenate(axis=-1)(feature_list)

    return tf.keras.Model(inputs=input_x, outputs=concat2)

z = create_model((128,128,2))


答: Try incrementing/decrementing index at the beginning of both functions.  Also, you have 5 elements, not 4 in your array.  You should probably use shirts.length to avoid this.

Title: javascript function needs doubleclick to work

Body:
I have these two javascript functions that for some reason I have to click the button twice for them to work. any ideas?

var shirts = new Array("shirtpink.png","shirtred.png", "shirtblue.png", "shirtyellow.png","shirt.png");

var index = 0;
function changecolor(){
    if (index > 4){
        index = 0;
    }
    var shirtpick = document.getElementById("shirt");
    shirtpick.setAttribute('src',shirts[index]);
    index++;
}

other function:

function changecolorback(){
    index--;
    i++;
    if (index < 0){
        index = 4;
    }
    var shirtback = document.getElementById("shirt");
    shirtback.setAttribute('src',shirts[index]);
}


问:
How to use and build a makefile to link scip to C?
I am very new in C. I just need to use one of the functions in scip. I made a make file as below:

```<code>SCIPDIR=$/Users/amin/Documents/cProgram/scipoptsuite-6.0.2/scip

include $(SCIPDIR)/make/make.project

%.o: %.c
    $(CC) $(FLAGS) $(OFLAGS) $(BINOFLAGS) $(CFLAGS) -c $<

all: cmain

cmain: cmain.o
    $(LINKCXX) cmain.o $(LINKCXXSCIPALL) $(LDFLAGS) $(LINKCXX_o) cmain
</code>```

my cmain.c file is like this:

```<code>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                           */
/*                  This file is part of the program and library             */
/*         SCIP --- Solving Constraint Integer Programs                      */
/*                                                                           */
/*    Copyright (C) 2002-2019 Konrad-Zuse-Zentrum                            */
/*                            fuer Informationstechnik Berlin                */
/*                                                                           */
/*  SCIP is distributed under the terms of the ZIB Academic License.         */
/*                                                                           */
/*  You should have received a copy of the ZIB Academic License              */
/*  along with SCIP; see the file COPYING. If not visit scip.zib.de.         */
/*                                                                           */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/**@file   GMI/src/cmain.c
 * @brief  main file for GMI cut example
 * @author Marc Pfetsch
 */

/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/

#include <scip/scip.h>
#include <scip/scipdefplugins.h>

/** reads parameters */
static
SCIP_RETCODE readParams(
   SCIP*                 scip,               /**< SCIP data structure */
   const char*           filename            /**< parameter file name, or NULL */
   )
{
   if ( filename != NULL )
   {
      if ( SCIPfileExists(filename) )
      {
         SCIPinfoMessage(scip, NULL, "reading parameter file <%s> ...\n", filename);
         SCIP_CALL( SCIPreadParams(scip, filename) );
      }
      else
         SCIPinfoMessage(scip, NULL, "parameter file <%s> not found - using default parameters.\n", filename);
   }
   else if ( SCIPfileExists("scipgmi.set") )
   {
      SCIPinfoMessage(scip, NULL, "reading parameter file <scipgmi.set> ...\n");
      SCIP_CALL( SCIPreadParams(scip, "scipgmi.set") );
   }

   return SCIP_OKAY;
}

/** starts SCIP */
static
SCIP_RETCODE fromCommandLine(
   SCIP*                 scip,               /**< SCIP data structure */
   const char*           filename            /**< input file name */
   )
{
   /********************
    * Problem Creation *
    ********************/

   SCIPinfoMessage(scip, NULL, "read problem <%s> ...\n\n", filename);
   SCIP_CALL( SCIPreadProb(scip, filename, NULL) );

   /*******************
    * Problem Solving *
    *******************/

   /* solve problem */
   SCIPinfoMessage(scip, NULL, "solve problem ...\n\n");
   SCIP_CALL( SCIPsolve(scip) );

   SCIPinfoMessage(scip, NULL, "primal solution:\n");
   SCIP_CALL( SCIPprintBestSol(scip, NULL, FALSE) );

   /**************
    * Statistics *
    **************/

   SCIPinfoMessage(scip, NULL, "Statistics:\n");
   SCIP_CALL( SCIPprintStatistics(scip, NULL) );

   return SCIP_OKAY;
}

/** starts user interactive mode */
static
SCIP_RETCODE interactive(
   SCIP*                 scip                /**< SCIP data structure */
   )
{
   SCIP_CALL( SCIPstartInteraction(scip) );

   return SCIP_OKAY;
}

/** creates a SCIP instance with default plugins, evaluates command line parameters, runs SCIP appropriately,
 *  and frees the SCIP instance
 */
static
SCIP_RETCODE runSCIP(
   int                   argc,               /**< number of shell parameters */
   char**                argv                /**< array with shell parameters */
   )
{
   SCIP* scip = NULL;

   /*********
    * Setup *
    *********/

   /* initialize SCIP */
   SCIP_CALL( SCIPcreate(&scip) );

   /* we explicitly enable the use of a debug solution for this main SCIP instance */
   SCIPenableDebugSol(scip);

   /***********************
    * Version information *
    ***********************/

   SCIPprintVersion(scip, NULL);
   SCIPinfoMessage(scip, NULL, "\n");

   /* include default SCIP plugins */
   SCIP_CALL( SCIPincludeDefaultPlugins(scip) );

   /**************
    * Parameters *
    **************/

   if ( argc >= 3 )
   {
      SCIP_CALL( readParams(scip, argv[2]) );
   }
   else
   {
      SCIP_CALL( readParams(scip, NULL) );
   }

   /**************
    * Start SCIP *
    **************/

   if ( argc >= 2 )
   {
      SCIP_CALL( fromCommandLine(scip, argv[1]) );
   }
   else
   {
      SCIPinfoMessage(scip, NULL, "\n");

      SCIP_CALL( interactive(scip) );
   }

   /********************
    * Deinitialization *
    ********************/

   SCIP_CALL( SCIPfree(&scip) );

   BMScheckEmptyMemory();

   return SCIP_OKAY;
}

/** main method starting SCIP */
int main(
   int                   argc,               /**< number of arguments from the shell */
   char**                argv                /**< array of shell arguments */
   )
{
   SCIP_RETCODE retcode;

   retcode = runSCIP(argc, argv);
   if ( retcode != SCIP_OKAY )
   {
      SCIPprintError(retcode);
      return -1;
   }

   return 0;
}
</code>```

Now in the directory that I have these 2 file, I run Make but it doesn't work I get error: No such file or directory

```<code>make: *** No rule to make target `Users/amin/Documents/cProgram/scipoptsuite-6.0.2/scip/make/make.project'.  Stop.
</code>```

I just tried to follow a instruction that someone suggested. Please help me if you can. what I have to do?

答:
You want to separate two things

Building SCIP

Building and Linking your program.

Building SCIP

Usually one would go about and install this library using a package manager on most UNIX-like systems, or do make install to copy it into the system. Then, header files etc. will automatically be found.  If you don't want to do that but rather "bundle" SCIP with your program, you usually distribute a copy or link a copy of that version for your program (copy of the code in your sourcetree under eg. "external" or using git submodules, ...). In any case though, you don't want the path to SCIP to be absolute. As an example, use this layout:

```<code>./
-- external/SCIP
-- cmain.c
-- Makefile
</code>```

In the Makefile you can then set SCIPDIR like this for later use:

```<code>SCIPDIR := "./external/SCIP"
</code>```

First, however, you should understand how to build manually.  For that, you enter "./external/SCIP" and build the library as instructed in the Readme (often by doing something like ./configure && make && make install).  If you want to automate this, you can do this from your main file.  For that you can add a "phony" target (ie. a target that will not exactly create one output but build all dependencies) that we will call dep:

```<code>dep:
        cd $(SCIPDIR); ./configure
        $(MAKE) -C $(SCIPDIR)

.PHONY: dep
</code>```

(thanks to @UpAndAdam for pointing out that you have to change the CWD before running the configure script)

For that we recursively call make for our subproject.  We don't want to system-wide install the files, so we just build the library.

Building your program

We now add two pattern-rules that specify how to build and link C programs. GNU/Make (the one you're using) already has built-in suffix rules s.t. it already by default knows how to build C programs, but suffix rules are hard to deal with and you already use other GNU/Make features, so we can also use pattern-rules that are roughly equivalent and disable the built-in rules:

```<code>%.o: %.c
        $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

%: %.o
         $(CC) $(LDFLAGS) $(CFLAGS) -o $@ $^ $(LDLIBS)

.SUFFIXES:
</code>```

A small note here: We compile one object file from one c file by pattern matching. I used the standard variables, CPPFLAGS (C preprocessor, not C++!), CFLAGS (C compiler & Feature flags) and listed all options before the non-option argument $< which will hold the (first) dependency listed, eg. "cmain.c". Not all C compilers allow mixing options and arguments.

For linking I do the same, but I list the libraries that we want to link with last. This is important, a classic C compiler will discard any libraries listed there if there wasn't any object earlier in the list that depends on that variable.

Now that we know how to build a generic C program, we actually want to first build SCIP, then your program and link it. For that, we'll create a new PHONY dependency, called "all", that will do exactly that:

```<code>all: dep cmain

.PHONY: dep all
</code>```

However, if we now execute make all it will fail as we haven't yet specified the include path etc. For that, we set the variables that we've used before to the needed values (I guessed the specific path, as I'm on mobile):

```<code>CPPFLAGS += -I$(SCIPDIR)/include
LDFLAGS += -L$(SCIPDIR)
LDLIBS += -lscip
</code>```

Putting it all together

Now this should work, more or less. One thing though is, that it's common to have all as the default target, that is, the first target listed in the Makefile. So we write:

```<code>CPPFLAGS += -I$(SCIPDIR)/include
LDFLAGS += -L$(SCIPDIR)
LDLIBS += -lscip

all: dep cmain

%.o: %.c
    $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

%: %.o
    $(CC) $(LDFLAGS) $(CFLAGS) -o $@ $^ $(LDLIBS)

dep:
    cd $(SCIPDIR); ./configure.sh
    $(MAKE) -C $(SCIPDIR)

.PHONY: dep all
.SUFFIXES:
</code>```

Note: I'm on mobile, so I couldn't test and don't know the exact paths, but this should guide you along. Also my code here used spaces instead of tabs in the Makefile for the same reason. Be sure to replace them.

Body:
I am very new in C. I just need to use one of the functions in scip. I made a make file as below:

SCIPDIR=$/Users/amin/Documents/cProgram/scipoptsuite-6.0.2/scip

include $(SCIPDIR)/make/make.project

%.o: %.c
    $(CC) $(FLAGS) $(OFLAGS) $(BINOFLAGS) $(CFLAGS) -c $<

all: cmain

cmain: cmain.o
    $(LINKCXX) cmain.o $(LINKCXXSCIPALL) $(LDFLAGS) $(LINKCXX_o) cmain

my cmain.c file is like this:

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                           */
/*                  This file is part of the program and library             */
/*         SCIP --- Solving Constraint Integer Programs                      */
/*                                                                           */
/*    Copyright (C) 2002-2019 Konrad-Zuse-Zentrum                            */
/*                            fuer Informationstechnik Berlin                */
/*                                                                           */
/*  SCIP is distributed under the terms of the ZIB Academic License.         */
/*                                                                           */
/*  You should have received a copy of the ZIB Academic License              */
/*  along with SCIP; see the file COPYING. If not visit scip.zib.de.         */
/*                                                                           */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/**@file   GMI/src/cmain.c
 * @brief  main file for GMI cut example
 * @author Marc Pfetsch
 */

/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/

#include <scip/scip.h>
#include <scip/scipdefplugins.h>

/** reads parameters */
static
SCIP_RETCODE readParams(
   SCIP*                 scip,               /**< SCIP data structure */
   const char*           filename            /**< parameter file name, or NULL */
   )
{
   if ( filename != NULL )
   {
      if ( SCIPfileExists(filename) )
      {
         SCIPinfoMessage(scip, NULL, "reading parameter file <%s> ...\n", filename);
         SCIP_CALL( SCIPreadParams(scip, filename) );
      }
      else
         SCIPinfoMessage(scip, NULL, "parameter file <%s> not found - using default parameters.\n", filename);
   }
   else if ( SCIPfileExists("scipgmi.set") )
   {
      SCIPinfoMessage(scip, NULL, "reading parameter file <scipgmi.set> ...\n");
      SCIP_CALL( SCIPreadParams(scip, "scipgmi.set") );
   }

   return SCIP_OKAY;
}

/** starts SCIP */
static
SCIP_RETCODE fromCommandLine(
   SCIP*                 scip,               /**< SCIP data structure */
   const char*           filename            /**< input file name */
   )
{
   /********************
    * Problem Creation *
    ********************/

   SCIPinfoMessage(scip, NULL, "read problem <%s> ...\n\n", filename);
   SCIP_CALL( SCIPreadProb(scip, filename, NULL) );

   /*******************
    * Problem Solving *
    *******************/

   /* solve problem */
   SCIPinfoMessage(scip, NULL, "solve problem ...\n\n");
   SCIP_CALL( SCIPsolve(scip) );

   SCIPinfoMessage(scip, NULL, "primal solution:\n");
   SCIP_CALL( SCIPprintBestSol(scip, NULL, FALSE) );

   /**************
    * Statistics *
    **************/

   SCIPinfoMessage(scip, NULL, "Statistics:\n");
   SCIP_CALL( SCIPprintStatistics(scip, NULL) );

   return SCIP_OKAY;
}

/** starts user interactive mode */
static
SCIP_RETCODE interactive(
   SCIP*                 scip                /**< SCIP data structure */
   )
{
   SCIP_CALL( SCIPstartInteraction(scip) );

   return SCIP_OKAY;
}

/** creates a SCIP instance with default plugins, evaluates command line parameters, runs SCIP appropriately,
 *  and frees the SCIP instance
 */
static
SCIP_RETCODE runSCIP(
   int                   argc,               /**< number of shell parameters */
   char**                argv                /**< array with shell parameters */
   )
{
   SCIP* scip = NULL;

   /*********
    * Setup *
    *********/

   /* initialize SCIP */
   SCIP_CALL( SCIPcreate(&scip) );

   /* we explicitly enable the use of a debug solution for this main SCIP instance */
   SCIPenableDebugSol(scip);

   /***********************
    * Version information *
    ***********************/

   SCIPprintVersion(scip, NULL);
   SCIPinfoMessage(scip, NULL, "\n");

   /* include default SCIP plugins */
   SCIP_CALL( SCIPincludeDefaultPlugins(scip) );

   /**************
    * Parameters *
    **************/

   if ( argc >= 3 )
   {
      SCIP_CALL( readParams(scip, argv[2]) );
   }
   else
   {
      SCIP_CALL( readParams(scip, NULL) );
   }

   /**************
    * Start SCIP *
    **************/

   if ( argc >= 2 )
   {
      SCIP_CALL( fromCommandLine(scip, argv[1]) );
   }
   else
   {
      SCIPinfoMessage(scip, NULL, "\n");

      SCIP_CALL( interactive(scip) );
   }

   /********************
    * Deinitialization *
    ********************/

   SCIP_CALL( SCIPfree(&scip) );

   BMScheckEmptyMemory();

   return SCIP_OKAY;
}

/** main method starting SCIP */
int main(
   int                   argc,               /**< number of arguments from the shell */
   char**                argv                /**< array of shell arguments */
   )
{
   SCIP_RETCODE retcode;

   retcode = runSCIP(argc, argv);
   if ( retcode != SCIP_OKAY )
   {
      SCIPprintError(retcode);
      return -1;
   }

   return 0;
}

Now in the directory that I have these 2 file, I run Make but it doesn't work I get error: No such file or directory

make: *** No rule to make target `Users/amin/Documents/cProgram/scipoptsuite-6.0.2/scip/make/make.project'.  Stop.

I just tried to follow a instruction that someone suggested. Please help me if you can. what I have to do?

Body:
You want to separate two things

Building SCIP

Building and Linking your program.

Building SCIP

Usually one would go about and install this library using a package manager on most UNIX-like systems, or do make install to copy it into the system. Then, header files etc. will automatically be found.  If you don't want to do that but rather "bundle" SCIP with your program, you usually distribute a copy or link a copy of that version for your program (copy of the code in your sourcetree under eg. "external" or using git submodules, ...). In any case though, you don't want the path to SCIP to be absolute. As an example, use this layout:

./
-- external/SCIP
-- cmain.c
-- Makefile

In the Makefile you can then set SCIPDIR like this for later use:

SCIPDIR := "./external/SCIP"

First, however, you should understand how to build manually.  For that, you enter "./external/SCIP" and build the library as instructed in the Readme (often by doing something like ./configure && make && make install).  If you want to automate this, you can do this from your main file.  For that you can add a "phony" target (ie. a target that will not exactly create one output but build all dependencies) that we will call dep:

dep:
        cd $(SCIPDIR); ./configure
        $(MAKE) -C $(SCIPDIR)

.PHONY: dep

(thanks to @UpAndAdam for pointing out that you have to change the CWD before running the configure script)

For that we recursively call make for our subproject.  We don't want to system-wide install the files, so we just build the library.

Building your program

We now add two pattern-rules that specify how to build and link C programs. GNU/Make (the one you're using) already has built-in suffix rules s.t. it already by default knows how to build C programs, but suffix rules are hard to deal with and you already use other GNU/Make features, so we can also use pattern-rules that are roughly equivalent and disable the built-in rules:

%.o: %.c
        $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

%: %.o
         $(CC) $(LDFLAGS) $(CFLAGS) -o $@ $^ $(LDLIBS)

.SUFFIXES:

A small note here: We compile one object file from one c file by pattern matching. I used the standard variables, CPPFLAGS (C preprocessor, not C++!), CFLAGS (C compiler & Feature flags) and listed all options before the non-option argument $< which will hold the (first) dependency listed, eg. "cmain.c". Not all C compilers allow mixing options and arguments.

For linking I do the same, but I list the libraries that we want to link with last. This is important, a classic C compiler will discard any libraries listed there if there wasn't any object earlier in the list that depends on that variable.

Now that we know how to build a generic C program, we actually want to first build SCIP, then your program and link it. For that, we'll create a new PHONY dependency, called "all", that will do exactly that:

all: dep cmain

.PHONY: dep all

However, if we now execute make all it will fail as we haven't yet specified the include path etc. For that, we set the variables that we've used before to the needed values (I guessed the specific path, as I'm on mobile):

CPPFLAGS += -I$(SCIPDIR)/include
LDFLAGS += -L$(SCIPDIR)
LDLIBS += -lscip

Putting it all together

Now this should work, more or less. One thing though is, that it's common to have all as the default target, that is, the first target listed in the Makefile. So we write:

CPPFLAGS += -I$(SCIPDIR)/include
LDFLAGS += -L$(SCIPDIR)
LDLIBS += -lscip

all: dep cmain

%.o: %.c
    $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

%: %.o
    $(CC) $(LDFLAGS) $(CFLAGS) -o $@ $^ $(LDLIBS)

dep:
    cd $(SCIPDIR); ./configure.sh
    $(MAKE) -C $(SCIPDIR)

.PHONY: dep all
.SUFFIXES:

Note: I'm on mobile, so I couldn't test and don't know the exact paths, but this should guide you along. Also my code here used spaces instead of tabs in the Makefile for the same reason. Be sure to replace them.


答:
First of all, you cannot have two or more elements with the same id.

To detect what button is being clicked you can pass the event to the function as argument like this.

```<code>onclick="themeToggle(event)" class="switcher" id="theme-switcher-2"
</code>```

Once you have the event you can get the object that has fired it (In your case the button) like this.

```<code>    function themeToggle(event){
          var tSwitcher = event.target;
          if(tSwitcher.checked){
              localStorage.setItem('theme', 'dark-mode');
                element.classList.add('dark-mode');
            } else {
              localStorage.setItem('theme', '');
                element.classList.remove('dark-mode');
            }
    }
</code>```

EDIT

To set the default behaviour properly you have to add class="switcher" to each button and do this.

```<code>var tSwitchers = document.querySelectorAll('.switcher'));
let onpageLoad = localStorage.getItem("theme") || "";
tSwitchers.forEach((element) => {
    if(onpageLoad != null && onpageLoad  == 'dark-mode'){
       element.checked = true;
    }
});
</code>```

Title: How to use Two Toggle buttons on same page having same function with different css?

Body:
First of all, you cannot have two or more elements with the same id.

To detect what button is being clicked you can pass the event to the function as argument like this.

onclick="themeToggle(event)" class="switcher" id="theme-switcher-2"

Once you have the event you can get the object that has fired it (In your case the button) like this.

    function themeToggle(event){
          var tSwitcher = event.target;
          if(tSwitcher.checked){
              localStorage.setItem('theme', 'dark-mode');
                element.classList.add('dark-mode');
            } else {
              localStorage.setItem('theme', '');
                element.classList.remove('dark-mode');
            }
    }

EDIT

To set the default behaviour properly you have to add class="switcher" to each button and do this.

var tSwitchers = document.querySelectorAll('.switcher'));
let onpageLoad = localStorage.getItem("theme") || "";
tSwitchers.forEach((element) => {
    if(onpageLoad != null && onpageLoad  == 'dark-mode'){
       element.checked = true;
    }
});


问:
How to prevent Knex.js from running a query object when returning it from an async function?
I have a node.js backend that constructs DB queries dynamically from various inputs using Knex.js. Some of the inputs need to be processed asynchronously. My problem is, that I can't return a knex query object from an async function (or of course in a Promise resolve function) because this triggers the execution of the query. Currently I need to process all my async inputs before handing them to the query building functions but that really limits their composability. Is there a way to prevent Knex from executing a query object in an async context?</p>

答:
For my needs, the most important is to extract the where clause, because this is often the complicated part and it's shared between several queries. Happily, this is easy to do with Knex.

For example, if you have this query, and the where function is the stuff to share with other queries.

```<code>const data = await knex("mytable")
   .where(builder => {
      builder.whereNull("mytable.deleted_at")

      if (something) {
         builder.where("something", 42)
      }
   })
   .select("*")
</code>```

You can refactor as:

```<code>const makeWhereClause = ({ something }) => builder => {
   builder.whereNull("mytable.deleted_at")
   if (something) {
      builder.where("something", 42)
   }
}

const data = await knex("mytable")
   .where(makeWhereClause({something})
   .select("*")
</code>```

Body:
For my needs, the most important is to extract the where clause, because this is often the complicated part and it's shared between several queries. Happily, this is easy to do with Knex.

For example, if you have this query, and the where function is the stuff to share with other queries.

const data = await knex("mytable")
   .where(builder => {
      builder.whereNull("mytable.deleted_at")

      if (something) {
         builder.where("something", 42)
      }
   })
   .select("*")

You can refactor as:

const makeWhereClause = ({ something }) => builder => {
   builder.whereNull("mytable.deleted_at")
   if (something) {
      builder.where("something", 42)
   }
}

const data = await knex("mytable")
   .where(makeWhereClause({something})
   .select("*")