问:
How to pass data to layouts without passing data to every page controller?
I have a custom layout blade that have multi level navigation menu and 2 page blade that extends the layout. I want to create a side navigation menu that loop through data. So if I created a new side nav, I don't have to mess the layout.

But the problem is, I don't know to pass the data to the layout itself.

For now, I just pass the data on every page controller that I have. I think it would be better if I just pass the data to the layout and call any page that extends the layout without passing the data again on every page controller.

layout blade (user.blade.php)

```<code><li class="nav-item has-treeview">
   <a href="#" class="nav-link">
      <i class="nav-icon fas fa-wifi"></i>
      <p>
         Hotspot Voucher
         <i class="right fas fa-angle-left"></i>
      </p>
   </a>
   <ul class="nav nav-treeview">
      <li class="nav-item has-treeview">
         <a href="#" class="nav-link">
            <i class="far fa-circle nav-icon"></i>
            <p>
               Floors
               <i class="right fas fa-angle-left"></i>
            </p>
         </a>
         <ul class="nav nav-treeview floorlist">
            @foreach ($floors as $floor)
            <li class="nav-item">
               <a href="{{ route('home.floor.submit', $floor->floor_id) }}" class="nav-link">
                  <i class="far fa-dot-circle nav-icon"></i>
                  <p>{{ ucwords($floor->floor_name) }}</p>
               </a>
            </li>
            @endforeach
         </ul>
       </li>
    </ul>
 </li>
</code>```

Home blade (home.blade.php)

```<code>@extends('layouts.user')

@section('content')
    <!-- Content Header (Page header) -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0 text-dark">Dashboard</h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item">
                            <a href="{{ route('home') }}">Home</a>
                        </li>
                        <li class="breadcrumb-item active">Dashboard</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <div class="panel panel-default">
                        <div class="panel-body">
                            @component('components.who')
                            @endcomponent
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- /.content -->
@endsection
</code>```

Floor Blade (floor.blade.php)

```<code>@extends('layouts.user')

@section('content')
    <!-- Content Header (Page header) -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0 text-dark">{{ ucwords($get_floor_name) }}</h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item">
                            <a href="{{ route('home') }}">Home</a>
                        </li>
                        <li class="breadcrumb-item">
                            <a href="{{ route('home') }}">Dashboard</a>
                        </li>
                        <li class="breadcrumb-item active">{{ ucwords($get_floor_name) }}</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <div class="panel panel-default">
                        <div class="panel-body">
                            @foreach ($get_rooms as $get_room)
                                {{ ucwords($get_room->rooms_name) }}
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- /.content -->
@endsection
</code>```

HomeController

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Floor;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where('floors.co_id', Auth::user()->co_id)
                ->get();

        return view('home')->with('floors', $floors);
    }
}
</code>```

FloorController

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Floor;
use App\Room;

class FloorController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($fid)
    {

       $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where('floors.co_id', Auth::user()->co_id)
                ->get();

        $get_floor_details = Floor::where(['floors.co_id' => Auth::user()->co_id, 'id' => $fid])->get();

        foreach($get_floor_details as $get_floor)
        {
            $get_floor_name = $get_floor->name;
        }

        $get_rooms = Room::select(
            'rooms.id AS room_id',
            'rooms.name AS rooms_name',
            'floors.name AS get_floor_name'
            )
            ->join('floors', 'floors.id', '=', 'rooms.floor_id')
            ->where(['rooms.co_id' => Auth::user()->co_id, 'rooms.floor_id' => $fid])
            ->get();

        $data = [
                'floors' => $floors,
                'get_floor_name' => $get_floor_name,
                'get_rooms' => $get_rooms
        ];

        return view('floor')->with($data);
    }
}
</code>```

@Andy Song solution

```<code><?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use View;
use Auth;
use App\Floor;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer('layouts.user', function ($view)
        {
            $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where(['co_id' => Auth::user()->co_id])
                ->get();
            $view->with('floors', $floors);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
</code>```

答:
you can use View composers, and put in AppServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    .......
    public function boot()
    {
        View::composer('*', function ($view) {
            $view->with('foo', ['bar', 'baz']);
        });
    }
}
```

by adding the Asterisk (*) character, it means it's avialable everywhere.

Body:
I have a custom layout blade that have multi level navigation menu and 2 page blade that extends the layout. I want to create a side navigation menu that loop through data. So if I created a new side nav, I don't have to mess the layout.

But the problem is, I don't know to pass the data to the layout itself.

For now, I just pass the data on every page controller that I have. I think it would be better if I just pass the data to the layout and call any page that extends the layout without passing the data again on every page controller.

layout blade (user.blade.php)

         Hotspot Voucher

               Floors

            @foreach ($floors as $floor)

               floor_id) }}" class="nav-link">

{{ ucwords($floor->floor_name) }}

            @endforeach

Home blade (home.blade.php)

@extends('layouts.user')

@section('content')

Dashboard

                            Home

Dashboard

                            @component('components.who')
                            @endcomponent

@endsection

Floor Blade (floor.blade.php)

@extends('layouts.user')

@section('content')

{{ ucwords($get_floor_name) }}

                            Home

                            Dashboard

{{ ucwords($get_floor_name) }}

                            @foreach ($get_rooms as $get_room)
                                {{ ucwords($get_room->rooms_name) }}
                            @endforeach

@endsection

HomeController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Floor;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where('floors.co_id', Auth::user()->co_id)
                ->get();

        return view('home')->with('floors', $floors);
    }
}

FloorController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Floor;
use App\Room;

class FloorController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($fid)
    {

       $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where('floors.co_id', Auth::user()->co_id)
                ->get();

        $get_floor_details = Floor::where(['floors.co_id' => Auth::user()->co_id, 'id' => $fid])->get();

        foreach($get_floor_details as $get_floor)
        {
            $get_floor_name = $get_floor->name;
        }

        $get_rooms = Room::select(
            'rooms.id AS room_id',
            'rooms.name AS rooms_name',
            'floors.name AS get_floor_name'
            )
            ->join('floors', 'floors.id', '=', 'rooms.floor_id')
            ->where(['rooms.co_id' => Auth::user()->co_id, 'rooms.floor_id' => $fid])
            ->get();

        $data = [
                'floors' => $floors,
                'get_floor_name' => $get_floor_name,
                'get_rooms' => $get_rooms
        ];

        return view('floor')->with($data);
    }
}

@Andy Song solution

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use View;
use Auth;
use App\Floor;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer('layouts.user', function ($view)
        {
            $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where(['co_id' => Auth::user()->co_id])
                ->get();
            $view->with('floors', $floors);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Body:
you can use View composers, and put in AppServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    .......
    public function boot()
    {
        View::composer('*', function ($view) {
            $view->with('foo', ['bar', 'baz']);
        });
    }
}

by adding the Asterisk (*) character, it means it's avialable everywhere.


来源: stackexchange

问:
Function doesn't return right array's values
I've started learning functions in C.

I have a task to convert numbers from imperial to metric, which are contained in the 2d Array.

Array:

```<code>{1300, 0}  [0][0] [0][1]

{2198, 0}  [1][0] [1][1]

{4199, 1}  [2][0] [2][1]

{2103, 0}  [3][0] [3][1]

{3104, 1}  [4][0] [4][1]

{1093, 1}  [5][0] [5][1]

{3204, 0}  [6][0] [6][1]
</code>```

So I am calling function with double return SortedArray[DATA_ROWS] = find_function(MixedData);

find_function logic:

0 is an indicator of the metric system  value and 1 is an indicator of imperial system value,
i is a row indexer and j is a column indexer.

So when for cycles find out that column value is 0 or 1 they save [j-1](an actual value that we need) into SortedArray.

It also converts value if finds out that column value is 1 SortedArray[i] = MixedData[i][j-1]*CONSTANT;

Just for a check, I did printf to see if values are correct and correctly converted if needed.
I got this output:

```<code>1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00
</code>```

So, seems like correct, but in Task I have another task - use 2 functions to solve this task.
I've decided to make another function, which will sum all values in SortedArray[DATA_ROWS] and then calculate avg - average.
Then print them out.
And here comes the problem.

Calling function with no return total_AVG(SortedArray); with copied array SortedArray[DATA_ROWS]

Just to check made a printf and got this:

```<code>-1.#R
0.00
0.00
0.00
0.00
0.00
0.00
</code>```

It seems like my SortedArray[DATA_ROWS] did not copy into the second function total_AVG

Pointers are coming in the next task, so according to task's timeline I can't use them
*
(and even if I could, I have no idea how to use them still)*

Can you please tell me, what I am doing wrong.

NB:
Some comments and variables, which are not used just old ones, when I tried to correct my code.
And also I only need to understand why SortedArray[DATA_ROWS] did not copy into second function total_AVG. All further logic will be corrected after solving this problem.

Thank you! And sorry for broken English!

CODE:

```<code>#include <stdio.h>
#define DATA_ROWS 7
#define DATA_COLS 2
#define CONSTANT 0.31
#define MAX 3

double find_function(int MixedData[DATA_ROWS][DATA_COLS]);
void total_AVG(double SortedArray[DATA_ROWS]);

int main(void)
{
    int i;
    double SortedArray[DATA_ROWS];

    int MixedData[DATA_ROWS][DATA_COLS] = {
        {1300, 0},//[0][0] [0][1]
        {2198, 0},//[1][0] [1][1]
        {4199, 1},//[2][0] [2][1]
        {2103, 0},//[3][0] [3][1]
        {3104, 1},//[4][0] [4][1]
        {1093, 1},//[5][0] [5][1]
        {3204, 0}};//[6][0] [6][1]

    SortedArray[DATA_ROWS] = find_function(MixedData);
    total_AVG(SortedArray);

    return 0;
}

double find_function(int MixedData[DATA_ROWS][DATA_COLS])
{
    // imperial numbers from source array "mixedData" are 4199,3104,1093;

    int i,j; // indexers
    double SortedArray[DATA_ROWS];

    // 7 rows, each row suppose to contain only metric values
    // That means, if second for cycle with j indexer finds 0, it will contain j-1 value for example 1300 in SortedArray
    // If it finds in second for cycle with j indexer 1, it will converte the value from imperial to metric for example 4199*0.31
        /*  {1300, 0}  [0][0] [0][1]
            {2198, 0}  [1][0] [1][1]
            {4199, 1}  [2][0] [2][1]
            {2103, 0}  [3][0] [3][1]
            {3104, 1}  [4][0] [4][1]
            {1093, 1}  [5][0] [5][1]
            {3204, 0}  [6][0] [6][1] */

    // Probably problem in "double SortedArray and int MixedData"
    for(i=0;i<DATA_ROWS;i++)
    {
        for(j=0;j<DATA_COLS;j++)
        {
            if(MixedData[i][j]==0)
            {
                SortedArray[i] = MixedData[i][j-1];
            }
            else if(MixedData[i][j]==1)
            {
                SortedArray[i] = MixedData[i][j-1]*CONSTANT;

            }
        }
    }
    for(i=0;i<DATA_ROWS;i++)
    {
        //total += SortedArray[i];
        printf("%.2lf\n", SortedArray[i]);
    }

    return SortedArray[DATA_ROWS];
}

void total_AVG(double SortedArray[DATA_ROWS])
{
    double avg,total;
    int i;

    for(i=0;i<DATA_ROWS;i++)
    {
        printf("%.2lf\n", SortedArray[i]);
    }
    //avg = total/DATA_ROWS;
    //printf("Total by every worker: %.2lf\n",total);
    //printf("In average by every worker: %.2lf", avg);

    return;
}

</code>```

答:
Arrays are NOT assignable in C. C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3) ..."an expression that has type *"array of type"* is converted to an expression with type *"pointer to type"* that points to the initial element of the array object and is not an lvalue." An array is NOT an lvalue;

In order to fill an array you have to iterate over the elements and assign values to the individual elements, or copy a block of memory to your array containing the values for your elements with memcpy, etc..

Further, with double SortedArray[DATA_ROWS]; you cannot return a locally declared array from a function. When the function returns, the function stack (containing your array) is destroyed (released for re-used). You must either pass your SortedArray as a parameter to find_function and fill the values of the array passed from main() there, or you must allocate storage for the values and return a Pointer to the allocated block of memory holding your values to main(). Those are your two-options.

Rearranging Your Code

Looking at your code and what you are attempting to do, it appears you need to:

declare double total = 0; in main()

you need to change the declaration for the find function so it takes SortedArray as a parameter, e.g.

double find_function(int (*MixedData)[DATA_COLS], double *SortedArray)

you need to declare another double total; (or any other name you choose) in find_function() and that total is what you want to return from find_function() to assign to the total declared in main() thereby providing its value, e.g.

```<code>total = find_function (MixedData, SortedArray);
</code>```

You need to change the declaration for total_AVG() so it takes the SortedArray passed to find_function() and filled there to the  total_AVG() function as a parameter, along with the total returned from the find_function() e.g.

void total_AVG (double *SortedArray, double total);

With that, and uncommenting the calculations and getting rid of the unused variables in your code, you could do:

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

#define DATA_ROWS 7
#define DATA_COLS 2
#define CONSTANT 0.31
#define MAX 3

double find_function (int (*MixedData)[DATA_COLS], double *SortedArray);
void total_AVG (double *SortedArray, double total);

int main(void)
{
    double total = 0;
    double SortedArray[DATA_ROWS] = {0};    /* good idea to initialize arrays zero */

    int MixedData[DATA_ROWS][DATA_COLS] = { {1300, 0},      //[0][0] [0][1]
                                            {2198, 0},      //[1][0] [1][1]
                                            {4199, 1},      //[2][0] [2][1]
                                            {2103, 0},      //[3][0] [3][1]
                                            {3104, 1},      //[4][0] [4][1]
                                            {1093, 1},      //[5][0] [5][1]
                                            {3204, 0} };    //[6][0] [6][1]

    total = find_function (MixedData, SortedArray);
    total_AVG (SortedArray, total);
}

double find_function(int (*MixedData)[DATA_COLS], double *SortedArray)
{
    // imperial numbers from source array "mixedData" are 4199,3104,1093;

    int i,j;    // indexers
    double total = 0;

    // Probably problem in "double SortedArray and int MixedData"
    for (i=0;i<DATA_ROWS;i++)
        for (j=0;j<DATA_COLS;j++)
            if (MixedData[i][j]==0)
                SortedArray[i] = MixedData[i][j-1];
            else if (MixedData[i][j]==1)
                SortedArray[i] = MixedData[i][j-1]*CONSTANT;

    for (i=0;i<DATA_ROWS;i++) {
        total += SortedArray[i];
        printf("%.2lf\n", SortedArray[i]);
    }

    return total;
}

void total_AVG (double *SortedArray, double total)
{
    double avg;
    int i;

    for (i=0;i<DATA_ROWS;i++)
        printf("%.2lf\n", SortedArray[i]);

    avg = total/DATA_ROWS;

    printf("Total by every worker: %.2lf\n",total);
    printf("In average by every worker: %.2lf\n", avg);
}
</code>```

Example Use/Output

Running the compiled program yields the following:

```<code>$ ./bin/sorteddata
1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00
1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00
Total by every worker: 11407.76
In average by every worker: 1629.68
</code>```

(note: I have not validated this output for correctness -- that I leave to you, but at a quick glance -- it looks reasonable based on what your code does)

Let me know if you have any questions about the changes made.

ContentLicense: CC BY-SA 4.0

Body:
I've started learning functions in C.

I have a task to convert numbers from imperial to metric, which are contained in the 2d Array.

Array:

{1300, 0}  [0][0] [0][1]

{2198, 0}  [1][0] [1][1]

{4199, 1}  [2][0] [2][1]

{2103, 0}  [3][0] [3][1]

{3104, 1}  [4][0] [4][1]

{1093, 1}  [5][0] [5][1]

{3204, 0}  [6][0] [6][1]

So I am calling function with double return SortedArray[DATA_ROWS] = find_function(MixedData);

find_function logic:

0 is an indicator of the metric system  value and 1 is an indicator of imperial system value,
i is a row indexer and j is a column indexer.

So when for cycles find out that column value is 0 or 1 they save [j-1](an actual value that we need) into SortedArray.

It also converts value if finds out that column value is 1 SortedArray[i] = MixedData[i][j-1]*CONSTANT;

Just for a check, I did printf to see if values are correct and correctly converted if needed.
I got this output:

1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00

So, seems like correct, but in Task I have another task - use 2 functions to solve this task.
I've decided to make another function, which will sum all values in SortedArray[DATA_ROWS] and then calculate avg - average.
Then print them out.
And here comes the problem.

Calling function with no return total_AVG(SortedArray); with copied array SortedArray[DATA_ROWS]

Just to check made a printf and got this:

-1.#R
0.00
0.00
0.00
0.00
0.00
0.00

It seems like my SortedArray[DATA_ROWS] did not copy into the second function total_AVG

Pointers are coming in the next task, so according to task's timeline I can't use them
*
(and even if I could, I have no idea how to use them still)*

Can you please tell me, what I am doing wrong.

NB:
Some comments and variables, which are not used just old ones, when I tried to correct my code.
And also I only need to understand why SortedArray[DATA_ROWS] did not copy into second function total_AVG. All further logic will be corrected after solving this problem.

Thank you! And sorry for broken English!

CODE:

#include <stdio.h>
#define DATA_ROWS 7
#define DATA_COLS 2
#define CONSTANT 0.31
#define MAX 3

double find_function(int MixedData[DATA_ROWS][DATA_COLS]);
void total_AVG(double SortedArray[DATA_ROWS]);

int main(void)
{
    int i;
    double SortedArray[DATA_ROWS];

    int MixedData[DATA_ROWS][DATA_COLS] = {
        {1300, 0},//[0][0] [0][1]
        {2198, 0},//[1][0] [1][1]
        {4199, 1},//[2][0] [2][1]
        {2103, 0},//[3][0] [3][1]
        {3104, 1},//[4][0] [4][1]
        {1093, 1},//[5][0] [5][1]
        {3204, 0}};//[6][0] [6][1]

    SortedArray[DATA_ROWS] = find_function(MixedData);
    total_AVG(SortedArray);

    return 0;
}

double find_function(int MixedData[DATA_ROWS][DATA_COLS])
{
    // imperial numbers from source array "mixedData" are 4199,3104,1093;

    int i,j; // indexers
    double SortedArray[DATA_ROWS];

    // 7 rows, each row suppose to contain only metric values
    // That means, if second for cycle with j indexer finds 0, it will contain j-1 value for example 1300 in SortedArray
    // If it finds in second for cycle with j indexer 1, it will converte the value from imperial to metric for example 4199*0.31
        /*  {1300, 0}  [0][0] [0][1]
            {2198, 0}  [1][0] [1][1]
            {4199, 1}  [2][0] [2][1]
            {2103, 0}  [3][0] [3][1]
            {3104, 1}  [4][0] [4][1]
            {1093, 1}  [5][0] [5][1]
            {3204, 0}  [6][0] [6][1] */

    // Probably problem in "double SortedArray and int MixedData"
    for(i=0;i<DATA_ROWS;i++)
    {
        for(j=0;j<DATA_COLS;j++)
        {
            if(MixedData[i][j]==0)
            {
                SortedArray[i] = MixedData[i][j-1];
            }
            else if(MixedData[i][j]==1)
            {
                SortedArray[i] = MixedData[i][j-1]*CONSTANT;

            }
        }
    }
    for(i=0;i<DATA_ROWS;i++)
    {
        //total += SortedArray[i];
        printf("%.2lf\n", SortedArray[i]);
    }

    return SortedArray[DATA_ROWS];
}

void total_AVG(double SortedArray[DATA_ROWS])
{
    double avg,total;
    int i;

    for(i=0;i<DATA_ROWS;i++)
    {
        printf("%.2lf\n", SortedArray[i]);
    }
    //avg = total/DATA_ROWS;
    //printf("Total by every worker: %.2lf\n",total);
    //printf("In average by every worker: %.2lf", avg);

    return;
}

Body:
Arrays are NOT assignable in C. C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3) ..."an expression that has type *"array of type"* is converted to an expression with type *"pointer to type"* that points to the initial element of the array object and is not an lvalue." An array is NOT an lvalue;

In order to fill an array you have to iterate over the elements and assign values to the individual elements, or copy a block of memory to your array containing the values for your elements with memcpy, etc..

Further, with double SortedArray[DATA_ROWS]; you cannot return a locally declared array from a function. When the function returns, the function stack (containing your array) is destroyed (released for re-used). You must either pass your SortedArray as a parameter to find_function and fill the values of the array passed from main() there, or you must allocate storage for the values and return a Pointer to the allocated block of memory holding your values to main(). Those are your two-options.

Rearranging Your Code

Looking at your code and what you are attempting to do, it appears you need to:

declare double total = 0; in main()

you need to change the declaration for the find function so it takes SortedArray as a parameter, e.g.

double find_function(int (*MixedData)[DATA_COLS], double *SortedArray)

you need to declare another double total; (or any other name you choose) in find_function() and that total is what you want to return from find_function() to assign to the total declared in main() thereby providing its value, e.g.

total = find_function (MixedData, SortedArray);

You need to change the declaration for total_AVG() so it takes the SortedArray passed to find_function() and filled there to the  total_AVG() function as a parameter, along with the total returned from the find_function() e.g.

void total_AVG (double *SortedArray, double total);

With that, and uncommenting the calculations and getting rid of the unused variables in your code, you could do:

#include <stdio.h>

#define DATA_ROWS 7
#define DATA_COLS 2
#define CONSTANT 0.31
#define MAX 3

double find_function (int (*MixedData)[DATA_COLS], double *SortedArray);
void total_AVG (double *SortedArray, double total);

int main(void)
{
    double total = 0;
    double SortedArray[DATA_ROWS] = {0};    /* good idea to initialize arrays zero */

    int MixedData[DATA_ROWS][DATA_COLS] = { {1300, 0},      //[0][0] [0][1]
                                            {2198, 0},      //[1][0] [1][1]
                                            {4199, 1},      //[2][0] [2][1]
                                            {2103, 0},      //[3][0] [3][1]
                                            {3104, 1},      //[4][0] [4][1]
                                            {1093, 1},      //[5][0] [5][1]
                                            {3204, 0} };    //[6][0] [6][1]

    total = find_function (MixedData, SortedArray);
    total_AVG (SortedArray, total);
}

double find_function(int (*MixedData)[DATA_COLS], double *SortedArray)
{
    // imperial numbers from source array "mixedData" are 4199,3104,1093;

    int i,j;    // indexers
    double total = 0;

    // Probably problem in "double SortedArray and int MixedData"
    for (i=0;i<DATA_ROWS;i++)
        for (j=0;j<DATA_COLS;j++)
            if (MixedData[i][j]==0)
                SortedArray[i] = MixedData[i][j-1];
            else if (MixedData[i][j]==1)
                SortedArray[i] = MixedData[i][j-1]*CONSTANT;

    for (i=0;i<DATA_ROWS;i++) {
        total += SortedArray[i];
        printf("%.2lf\n", SortedArray[i]);
    }

    return total;
}

void total_AVG (double *SortedArray, double total)
{
    double avg;
    int i;

    for (i=0;i<DATA_ROWS;i++)
        printf("%.2lf\n", SortedArray[i]);

    avg = total/DATA_ROWS;

    printf("Total by every worker: %.2lf\n",total);
    printf("In average by every worker: %.2lf\n", avg);
}

Example Use/Output

Running the compiled program yields the following:

$ ./bin/sorteddata
1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00
1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00
Total by every worker: 11407.76
In average by every worker: 1629.68

(note: I have not validated this output for correctness -- that I leave to you, but at a quick glance -- it looks reasonable based on what your code does)

Let me know if you have any questions about the changes made.


问:
ASP.NET Core Navigation Properties For Mapping Table
I have a table called contracts which has the id of entity 1 and entity 2. I use this to create links between entities, however I can't seem to get the definition of the dbContext correct. I can get the contracts to load but only one entity. When I view the contract either Entity1 is loaded or Entity2 is loaded but never both.

The models look like this:

```<code> public class Contract
    {
        public int Entity1ID { get; set; }
        public int Entity2ID { get; set; }

        public Entity Entity1 { get; set; }

        public Entity Entity2 { get; set; }
    }
</code>```

My entity class looks like this

```<code>public class Entity
{
    public int ID { get; set; }

    public ICollection<Contract> Contracts1 { get; set; };
    public ICollection<Contract> Contracts2 { get; set; };
}
</code>```

This is my dbContext

```<code>public class EntityDbContext : DbContext
    {
        public EntityDbContext(DbContextOptions<EntityDbContext> options)
        : base(options)
        {

        }

        public DbSet<Models.Entity> Entities { get; set; }
        public DbSet<Models.Contract> Contracts { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Entity>()
                .HasKey(n => n.ID);

            modelBuilder.Entity<Contract>()
               .HasKey(n => new { n.Entity1ID, n.Entity2ID });

            modelBuilder.Entity<Contract>()
                .HasOne(n => n.Entity1)
                .WithMany(n => n.Contracts1)
                .HasForeignKey(n => n.Entity1ID);

            modelBuilder.Entity<Contract>()
                .HasOne(n => n.Entity2)
                .WithMany(n => n.Contracts2)
                .HasForeignKey(n => n.Entity2ID);

        }

    }
</code>```

答:
From your model design , there is a self-referencing many-to-many relationship in Entity model , so you should change DeleteBehavior to Restrict(the default is cascade) like below:

```<code> protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Entity>()
            .HasKey(n => n.ID);

        modelBuilder.Entity<Contract>()
           .HasKey(n => new { n.Entity1ID, n.Entity2ID });

        modelBuilder.Entity<Contract>()
            .HasOne(n => n.Entity1)
            .WithMany(n => n.Contracts1)
            .HasForeignKey(n => n.Entity1ID)
            .OnDelete(DeleteBehavior.Restrict);

        modelBuilder.Entity<Contract>()
            .HasOne(n => n.Entity2)
            .WithMany(n => n.Contracts2)
            .HasForeignKey(n => n.Entity2ID)
            .OnDelete(DeleteBehavior.Restrict);
    }
</code>```

For loading related data , you could use the Include method that Sharif suggested above to specify related data to be included in query results

```<code>var result = _context.Contracts
            .Include(c => c.Entity1)
            .Include(c => c.Entity2)
            .ToList();
</code>```

Result

Body:
I have a table called contracts which has the id of entity 1 and entity 2. I use this to create links between entities, however I can't seem to get the definition of the dbContext correct. I can get the contracts to load but only one entity. When I view the contract either Entity1 is loaded or Entity2 is loaded but never both.

The models look like this:

 public class Contract
    {
        public int Entity1ID { get; set; }
        public int Entity2ID { get; set; }

        public Entity Entity1 { get; set; }

        public Entity Entity2 { get; set; }
    }

My entity class looks like this

public class Entity
{
    public int ID { get; set; }

    public ICollection<Contract> Contracts1 { get; set; };
    public ICollection<Contract> Contracts2 { get; set; };
}

This is my dbContext

public class EntityDbContext : DbContext
    {
        public EntityDbContext(DbContextOptions<EntityDbContext> options)
        : base(options)
        {

        }

        public DbSet<Models.Entity> Entities { get; set; }
        public DbSet<Models.Contract> Contracts { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Entity>()
                .HasKey(n => n.ID);

            modelBuilder.Entity<Contract>()
               .HasKey(n => new { n.Entity1ID, n.Entity2ID });

            modelBuilder.Entity<Contract>()
                .HasOne(n => n.Entity1)
                .WithMany(n => n.Contracts1)
                .HasForeignKey(n => n.Entity1ID);

            modelBuilder.Entity<Contract>()
                .HasOne(n => n.Entity2)
                .WithMany(n => n.Contracts2)
                .HasForeignKey(n => n.Entity2ID);

        }

    }

Body:
From your model design , there is a self-referencing many-to-many relationship in Entity model , so you should change DeleteBehavior to Restrict(the default is cascade) like below:

 protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Entity>()
            .HasKey(n => n.ID);

        modelBuilder.Entity<Contract>()
           .HasKey(n => new { n.Entity1ID, n.Entity2ID });

        modelBuilder.Entity<Contract>()
            .HasOne(n => n.Entity1)
            .WithMany(n => n.Contracts1)
            .HasForeignKey(n => n.Entity1ID)
            .OnDelete(DeleteBehavior.Restrict);

        modelBuilder.Entity<Contract>()
            .HasOne(n => n.Entity2)
            .WithMany(n => n.Contracts2)
            .HasForeignKey(n => n.Entity2ID)
            .OnDelete(DeleteBehavior.Restrict);
    }

For loading related data , you could use the Include method that Sharif suggested above to specify related data to be included in query results

var result = _context.Contracts
            .Include(c => c.Entity1)
            .Include(c => c.Entity2)
            .ToList();

Result


问:
Why does file.write() add an extra string at the end?
I was updating a text file with python (3.6), with open r+

```<code>with open(f+'.play', 'r+') as f2:
  play = f2.read()
  result = manipulate(play)
  print(result)
  f2.seek(0, 0)
  f2.write(result)
</code>```

by doing this, I get an unexpected extra ending part

```<code></soap:Envelope>ap:Envelope>
</code>```

of course the extra part is after the first closing >

I fixed this by doing

```<code>with open(f+'.play', 'r+') as f2:
  play = f2.read()
  result = manipulate(play)
  print(result)
  f2.seek(0, 0)
  f2.truncate()
  f2.write(result)
</code>```

in this case the write works as I expect.

Nevertheless I do not understand why I need to truncate, is the seek(0,0) not enough?
because in my mind seek(0) + write should be overwrite the whole content in a proper way, what piece of knowledge am I missing here?

答: If your old content has bigger size than one you are writing, the extra part will stay in the file. When you call seek(0, 0) you go to the beginning and start writing from there byte by byte, but the old data is not removed. When you call truncate() you remove old data, so it works as you want.

Body:
I was updating a text file with python (3.6), with open r+

with open(f+'.play', 'r+') as f2:
  play = f2.read()
  result = manipulate(play)
  print(result)
  f2.seek(0, 0)
  f2.write(result)

by doing this, I get an unexpected extra ending part

</soap:Envelope>ap:Envelope>

of course the extra part is after the first closing >

I fixed this by doing

with open(f+'.play', 'r+') as f2:
  play = f2.read()
  result = manipulate(play)
  print(result)
  f2.seek(0, 0)
  f2.truncate()
  f2.write(result)

in this case the write works as I expect.

Nevertheless I do not understand why I need to truncate, is the seek(0,0) not enough?
because in my mind seek(0) + write should be overwrite the whole content in a proper way, what piece of knowledge am I missing here?


问:
my telegram bot keeps sending messages endlessly
I Started programming a telegram bot and I've got a problem. when I send /start command it sends me a welcome message (as i programmed it) but it doesn't sends it once! it keeps sending it endlessly like loop!
this is the source:</p>
```<code><?php
    define('API_KEY','<token>');

    function makereq($method,$datas=[])
    {
        $url = "https://api.telegram.org/bot".API_KEY."/".$method;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($datas));
        $res = curl_exec($ch);
        if(curl_error($ch)){
            var_dump(curl_error($ch));
        }else{
            return json_decode($res);
        }
    }

    $website = "https://api.telegram.org/bot".API_KEY;

    $update = json_decode(file_get_contents('php://input'));

    $chat_id = $update->message->chat->id;
    $message_id = $update->message->message_id;
    $from_id = $update->message->from->id;
    $name = $update->message->from->first_name;
    $username = $update->message->from->username;
    $textmessage = isset($update->message->text)?$update->message->text:'';
    $reply = $update->message->reply_to_message->forward_from->id;
    $stickerid = $update->message->reply_to_message->sticker->file_id;
    $messageEntity = $update->messageentity->type;

    function SendMessage($ChatId, $TextMsg)
    {
     makereq('sendMessage',[
    'chat_id'=>$ChatId,
    'text'=>$TextMsg,
    'parse_mode'=>"MarkDown"]
     );
    }
    if($textmessage == '/start')
    {
      SendMessage($chat_id,'<welcome message>');
    }

?>
</code>```

答:
When my Telegram-bot keeped sending messages, I created a table of recording posts in the database.
When I am sending a post in my Telegram-bot, written in PHP alghorythm checks if a new post already exists in the database:
* if it does, we stop the process of sending the post;
* if it doesn't, we continue sending it in Telegram.
The described method allows to stop cycle of sending the post again and again.</p>

Body:
I Started programming a telegram bot and I've got a problem. when I send /start command it sends me a welcome message (as i programmed it) but it doesn't sends it once! it keeps sending it endlessly like loop!
this is the source:

<?php
    define('API_KEY','<token>');

    function makereq($method,$datas=[])
    {
        $url = "https://api.telegram.org/bot".API_KEY."/".$method;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($datas));
        $res = curl_exec($ch);
        if(curl_error($ch)){
            var_dump(curl_error($ch));
        }else{
            return json_decode($res);
        }
    }

    $website = "https://api.telegram.org/bot".API_KEY;

    $update = json_decode(file_get_contents('php://input'));

    $chat_id = $update->message->chat->id;
    $message_id = $update->message->message_id;
    $from_id = $update->message->from->id;
    $name = $update->message->from->first_name;
    $username = $update->message->from->username;
    $textmessage = isset($update->message->text)?$update->message->text:'';
    $reply = $update->message->reply_to_message->forward_from->id;
    $stickerid = $update->message->reply_to_message->sticker->file_id;
    $messageEntity = $update->messageentity->type;

    function SendMessage($ChatId, $TextMsg)
    {
     makereq('sendMessage',[
    'chat_id'=>$ChatId,
    'text'=>$TextMsg,
    'parse_mode'=>"MarkDown"]
     );
    }
    if($textmessage == '/start')
    {
      SendMessage($chat_id,'<welcome message>');
    }

?>


问:
soft keyboard not appearing
I have a following dialog:

```<code>import android.app.AlertDialog;

public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

    private View view;
    private Context context;
    private Activity activity;

    private EditText ipEditText;

    protected IpDiscoveryDialog(Context context) {
        super(context);
        this.context = context;
    }

    public IpDiscoveryDialog(Context context, Activity activity) {
        this(context);
        this.activity = activity;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        this.view = view;
        this.setContentView(view);
    }

    @Override
    public void setContentView(@NonNull View view) {
        super.setContentView(view);
        this.buildView(view);
        this.setCancelable(false);
    }

    private void buildView(View view) {
        view.findViewById(R.id.ipConfirmButton).setOnClickListener(this);
        this.ipEditText = view.findViewById(R.id.ipEditText);
    }
}
</code>```

I open it from a different activity like this:

```<code>IpDiscoveryDialog ipDiscoveryDialog = new IpDiscoveryDialog(ScanDevicesActivity.this, ScanDevicesActivity.this);
ipDiscoveryDialog.create();
ipDiscoveryDialog.setContentView(R.layout.ip_discovery_dialog);
ipDiscoveryDialog.show();
</code>```

And the layout of the dialog is the following:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/set_ip_address"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/ipEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/ip_address"
        android:importantForAutofill="no"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/ipConfirmButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/confirm" />
</LinearLayout>
</code>```

The problem I have is that no matter what I do, I cannot open soft keyboard to edit that EditText. I tried open it manually in code, I tried different settings, nothing works.

Code like this does not work:

```<code>InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.showSoftInput(SearchEdit, InputMethodManager.SHOW_IMPLICIT);
</code>```

What else can I try? What is the issue here?

答:
try adding below code in menifext file -

```<code> <application
    .....
    android:hardwareAccelerated="true">
</code>```

Hope this will help you.

Title: soft keyboard not appearing

Body:
I have a following dialog:

import android.app.AlertDialog;

public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

    private View view;
    private Context context;
    private Activity activity;

    private EditText ipEditText;

    protected IpDiscoveryDialog(Context context) {
        super(context);
        this.context = context;
    }

    public IpDiscoveryDialog(Context context, Activity activity) {
        this(context);
        this.activity = activity;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        this.view = view;
        this.setContentView(view);
    }

    @Override
    public void setContentView(@NonNull View view) {
        super.setContentView(view);
        this.buildView(view);
        this.setCancelable(false);
    }

    private void buildView(View view) {
        view.findViewById(R.id.ipConfirmButton).setOnClickListener(this);
        this.ipEditText = view.findViewById(R.id.ipEditText);
    }
}

I open it from a different activity like this:

IpDiscoveryDialog ipDiscoveryDialog = new IpDiscoveryDialog(ScanDevicesActivity.this, ScanDevicesActivity.this);
ipDiscoveryDialog.create();
ipDiscoveryDialog.setContentView(R.layout.ip_discovery_dialog);
ipDiscoveryDialog.show();

And the layout of the dialog is the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/set_ip_address"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/ipEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/ip_address"
        android:importantForAutofill="no"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/ipConfirmButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/confirm" />
</LinearLayout>

The problem I have is that no matter what I do, I cannot open soft keyboard to edit that EditText. I tried open it manually in code, I tried different settings, nothing works.

Code like this does not work:

InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.showSoftInput(SearchEdit, InputMethodManager.SHOW_IMPLICIT);

What else can I try? What is the issue here?

Body:
try adding below code in menifext file -

 <application
    .....
    android:hardwareAccelerated="true">

Hope this will help you.


问:
Trying to convert a string/char to an integer yielded an unexpected result
I came across something strange. It is probably trivial but I can't find the answer. Can anyone explain to me why in this action I get a result of 49?</p>

```<code>using namespace std;

int main() {
    int number;
    string binary = "10101011";

    number = int(binary[0]);
    cout << number; // result is 49 , why is that?
}
</code>```

答:
You have defined string binary = "10101011";
binary[0] is character '1'. When you parse a character to int, the output is ASCII value of the character.

Body:
I came across something strange. It is probably trivial but I can't find the answer. Can anyone explain to me why in this action I get a result of 49?

using namespace std;

int main() {
    int number;
    string binary = "10101011";

    number = int(binary[0]);
    cout << number; // result is 49 , why is that?
}


问:
If I'm making a filter in an ASP.NET Core application, should I also inherit IFilterMetadata?
I've made an authorize filter (by inheriting the new IAsyncAuthorizationFilter), should I also inherit IFilterMetadata, and why/why not?

Thank you.

答:
no IAsyncAuthorizationFilter already inherits IFilterMetadata

```<code>public interface IAsyncAuthorizationFilter : Microsoft.AspNetCore.Mvc.Filters.IFilterMetadata
</code>```

as MSDN indicates IFilterMetadata is a "marker" interface to indicate filter types to MVC. For an example have a look at the source of FilterCollection.

Body:
no IAsyncAuthorizationFilter already inherits IFilterMetadata

public interface IAsyncAuthorizationFilter : Microsoft.AspNetCore.Mvc.Filters.IFilterMetadata

as MSDN indicates IFilterMetadata is a "marker" interface to indicate filter types to MVC. For an example have a look at the source of FilterCollection.


问:
Setting up multi master MySQL cluster on different AWS regions
I have a chat application that already has thousands of users. Servers are located in US(Oregon). Users are distributed across the globe. I have started facing an issue related to slow server response for users in India. I want to set up the same infra in India as well. The major problem is MySQL replication. A new MySQL master is created in India but Master-Master replication is creating problems as the database contains tables with auto-increment id as the primary key. As per my understanding, the following process is being followed

Let's assume auto-increment id is now 1000, time is XXXXXXX000 ms and latency between Oregon and Mumbai region is 200ms

At XXXXXXX000 ms, Server1(US) is adding a new row in xyz table, and now the auto-increment id is 1001.

At the same time XXXXXXX000 ms, Server2(Ind) is adding a new row in xyz table, and now the auto-increment id is 1001 on the same table.

After 200ms, Query executed on Server1(US) is replicated to Server2(Ind) which has auto-increment id as 1001 but failed to execute because the table already has that value.

Similarly, Query executed on Server2(Ind) is replicated to Server1(US) which has auto-increment id as 1001 but failed to execute because the table already has that value.

One of the solutions I found was to set auto_increment_increment and auto_increment_offset values on both the hosts as defined http://www.clusterdb.com/mysql-cluster/setting-up-mysql-asynchronous-replication-for-high-availability.
I was able to replicate that but I am not sure whether this is the right approach for a production setup on AWS EC2. Any suggestions would be appreciated.

答:
The solution you found on [http://www.clusterdb.com/mysql-cluster/setting-up-mysql-asynchronous-replication-for-high-availability][1] is the right approach to use on production server.

Server 1 :

auto_increment_increment=1

auto_increment_offset=1

Server 2:

auto_increment_increment=1

auto_increment_offset=2


问:
Can list files in an external stage but cannot access files within it?
I was updating a S3 bucket policy today to allow a lambda function in a separate account to PutObjects into that bucket.
Somehow while I was updating that policy I broke my external stage in Snowflake.

I can run the list@stage/subfolder command and see a list of all filenames in the stage.
However if I attempt to

SELECT metadata$filename FROM @stage/subfolder

I receive the Failed to access remote file: access denied.  Please check your credentials error.

I am connecting to snowflake via the third option (https://docs.snowflake.net/manuals/user-guide/data-load-s3-config.html).  I have established an IAM user and provided the access key id/secret access key when establishing the external stage.

Everything was working until I made separate changes to the bucket policy.

Does the ability to list @stage but not select from the stage ring a bell to anyone?  If not, I'll be happy to provide more specifics of the policies I've created.

答:
On AWS, listing objects and accessing objects require different privileges. Are you sure that the IAM user has access to these files? You mentioned that the lambda function in a separate account, when uploading objects, do you give "bucket-owner-full-control"?

How change S3 file ownership while cross-account uploading


问:
Making Model class from JSON
Here I am trying to make the model class of this JSON

```<code>{
  "debit": 1,
  "train": {
    "number": "14207",
    "name": "PADMAVAT EXP",
    "days": [
      {
        "code": "MON",
        "runs": "Y"
      },
      {
        "code": "TUE",
        "runs": "Y"
      },
      {
        "code": "WED",
        "runs": "Y"
      },
      {
        "code": "THU",
        "runs": "Y"
      },
      {
        "code": "FRI",
        "runs": "Y"
      },
      {
        "code": "SAT",
        "runs": "Y"
      },
      {
        "code": "SUN",
        "runs": "Y"
      }
    ],
    "classes": [
      {
        "code": "2A",
        "available": "Y",
        "name": "SECOND AC"
      },
      {
        "code": "3E",
        "available": "N",
        "name": "3rd AC ECONOMY"
      },
      {
        "code": "3A",
        "available": "Y",
        "name": "THIRD AC"
      },
      {
        "code": "2S",
        "available": "N",
        "name": "SECOND SEATING"
      },
      {
        "code": "CC",
        "available": "N",
        "name": "AC CHAIR CAR"
      },
      {
        "code": "SL",
        "available": "Y",
        "name": "SLEEPER CLASS"
      },
      {
        "code": "FC",
        "available": "N",
        "name": "FIRST CLASS"
      },
      {
        "code": "1A",
        "available": "Y",
        "name": "FIRST AC"
      }
    ]
  },
  "response_code": 200
}
</code>```

And I try this
First I create two Integer variable name response_code and debit(because inside "{" and "}" are key and value pairs)
Then I create on array List and one List named as train and classes which represents train list and classes array in json. Still Not Working

```<code>public class NewTrain {
    @SerializedName("response_code")
    private int response_code;
    @SerializedName("debit")
    private int debit;
    @SerializedName("train")
    private List<TrainClass> train= null;
   @SerializedName("classes")
    private ArrayList<classes> arrayList = null;

    public int getResponse_code() {
        return response_code;
    }

    public void setResponse_code(int response_code) {
        this.response_code = response_code;
    }

    public int getDebit() {
        return debit;
    }

    public void setDebit(int debit) {
        this.debit = debit;
    }

    public List<TrainClass> getTrain() {
        return train;
    }

    public void setTrain(List<TrainClass> train) {
        this.train = train;
    }

    public ArrayList<classes> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<classes> arrayList) {
        this.arrayList = arrayList;
    }
}

public class TrainClass
 @SerializedName("number")
    private int number;
    @SerializedName("name")
    private String name;
    @SerializedName("days")
    private List<Day> dayList = null;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Day> getDayList() {
        return dayList;
    }

    public void setDayList(List<Day> dayList) {
        this.dayList = dayList;
    }
}
public class Day {
    @SerializedName("code")
    private String code;
    @SerializedName("runs")
    private String runs;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getRuns() {
        return runs;
    }

    public void setRuns(String runs) {
        this.runs = runs;
    }

}
public class classes {
    @SerializedName("code")
    private String code;

    @SerializedName("available")
    private String available;

    @SerializedName("name")
    private String name;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getAvailable() {
        return available;
    }

    public void setAvailable(String available) {
        this.available = available;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

But instead it is giving Begin Array but was Begin Object at line 1 column 2!!!
Calling API data from server method

```<code> public void Show(View view) {

        MyWebService myWebService = MyWebService.retrofitfortrain.create(MyWebService.class);
        Call<List<NewTrain>>  call = myWebService.getTrainList();
      call.enqueue(new Callback<List<NewTrain>>() {
          @Override
          public void onResponse(Call<List<NewTrain>> call, Response<List<NewTrain>> response) {
              if(response.isSuccessful())
              {
                  for(NewTrain newTrain: response.body()) {
                      t.append(String.valueOf(newTrain.getResponse_code()));
                  }
              }
          }

          @Override
          public void onFailure(Call<List<NewTrain>> call, Throwable t) {
              Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

          }
      });

    }
</code>```

答:
As the JSON mentioned train contains a JSON object, not a list. Another of the classes list will be a member of TainClass not in the NewTrainClass.

So, instead of:

```<code>@SerializedName("train")
private List<TrainClass> train= null;
</code>```

make it

```<code>@SerializedName("train")
private TrainClass train= null;
</code>```

and also Move Classes to the TrainClass

```<code>@SerializedName("classes")
private ArrayList<classes> arrayList = null;
</code>```

Finally, the NewTrain Object will be like

```<code>public class NewTrain {
    @SerializedName("response_code")
    private int response_code;
    @SerializedName("debit")
    private int debit;
    @SerializedName("train")
    private TrainClass train;

    public int getResponse_code() {
        return response_code;
    }

    public void setResponse_code(int response_code) {
        this.response_code = response_code;
    }

    public int getDebit() {
        return debit;
    }

    public void setDebit(int debit) {
        this.debit = debit;
    }

    public TrainClass getTrain() {
        return train;
    }

    public void setTrain(TrainClass train) {
        this.train = train;
    }
}

public class TrainClass
 @SerializedName("number")
    private int number;
    @SerializedName("name")
    private String name;
    @SerializedName("days")
    private List<Day> dayList = null;
   @SerializedName("classes")
    private ArrayList<classes> arrayList = null;
    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Day> getDayList() {
        return dayList;
    }

    public void setDayList(List<Day> dayList) {
        this.dayList = dayList;
    }

    public ArrayList<classes> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<classes> arrayList) {
        this.arrayList = arrayList;
    }
}
</code>```

Look like the JSON contains only a NewTrain, not the List<NewTrain>. nd also need to update the myWebService.getTrainList();
You also need to update the method like

```<code> public void Show(View view) {

    MyWebService myWebService = MyWebService.retrofitfortrain.create(MyWebService.class);
    Call<NewTrain>  call = myWebService.getTrainList();
  call.enqueue(new Callback<NewTrain>() {
      @Override
      public void onResponse(Call<NewTrain> call, Response<NewTrain> response) {
          if(response.isSuccessful())
          {
              for(NewTrain newTrain: response.body()) {
                  t.append(String.valueOf(newTrain.getResponse_code()));
              }
          }
      }

      @Override
      public void onFailure(Call<NewTrain> call, Throwable t) {
          Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

      }
  });

}
</code>```

Hope this will work.

Title: Making Model class from JSON

Body:
Here I am trying to make the model class of this JSON

{
  "debit": 1,
  "train": {
    "number": "14207",
    "name": "PADMAVAT EXP",
    "days": [
      {
        "code": "MON",
        "runs": "Y"
      },
      {
        "code": "TUE",
        "runs": "Y"
      },
      {
        "code": "WED",
        "runs": "Y"
      },
      {
        "code": "THU",
        "runs": "Y"
      },
      {
        "code": "FRI",
        "runs": "Y"
      },
      {
        "code": "SAT",
        "runs": "Y"
      },
      {
        "code": "SUN",
        "runs": "Y"
      }
    ],
    "classes": [
      {
        "code": "2A",
        "available": "Y",
        "name": "SECOND AC"
      },
      {
        "code": "3E",
        "available": "N",
        "name": "3rd AC ECONOMY"
      },
      {
        "code": "3A",
        "available": "Y",
        "name": "THIRD AC"
      },
      {
        "code": "2S",
        "available": "N",
        "name": "SECOND SEATING"
      },
      {
        "code": "CC",
        "available": "N",
        "name": "AC CHAIR CAR"
      },
      {
        "code": "SL",
        "available": "Y",
        "name": "SLEEPER CLASS"
      },
      {
        "code": "FC",
        "available": "N",
        "name": "FIRST CLASS"
      },
      {
        "code": "1A",
        "available": "Y",
        "name": "FIRST AC"
      }
    ]
  },
  "response_code": 200
}

And I try this
First I create two Integer variable name response_code and debit(because inside "{" and "}" are key and value pairs)
Then I create on array List and one List named as train and classes which represents train list and classes array in json. Still Not Working

public class NewTrain {
    @SerializedName("response_code")
    private int response_code;
    @SerializedName("debit")
    private int debit;
    @SerializedName("train")
    private List<TrainClass> train= null;
   @SerializedName("classes")
    private ArrayList<classes> arrayList = null;

    public int getResponse_code() {
        return response_code;
    }

    public void setResponse_code(int response_code) {
        this.response_code = response_code;
    }

    public int getDebit() {
        return debit;
    }

    public void setDebit(int debit) {
        this.debit = debit;
    }

    public List<TrainClass> getTrain() {
        return train;
    }

    public void setTrain(List<TrainClass> train) {
        this.train = train;
    }

    public ArrayList<classes> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<classes> arrayList) {
        this.arrayList = arrayList;
    }
}

public class TrainClass
 @SerializedName("number")
    private int number;
    @SerializedName("name")
    private String name;
    @SerializedName("days")
    private List<Day> dayList = null;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Day> getDayList() {
        return dayList;
    }

    public void setDayList(List<Day> dayList) {
        this.dayList = dayList;
    }
}
public class Day {
    @SerializedName("code")
    private String code;
    @SerializedName("runs")
    private String runs;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getRuns() {
        return runs;
    }

    public void setRuns(String runs) {
        this.runs = runs;
    }

}
public class classes {
    @SerializedName("code")
    private String code;

    @SerializedName("available")
    private String available;

    @SerializedName("name")
    private String name;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getAvailable() {
        return available;
    }

    public void setAvailable(String available) {
        this.available = available;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

But instead it is giving Begin Array but was Begin Object at line 1 column 2!!!
Calling API data from server method

 public void Show(View view) {

        MyWebService myWebService = MyWebService.retrofitfortrain.create(MyWebService.class);
        Call<List<NewTrain>>  call = myWebService.getTrainList();
      call.enqueue(new Callback<List<NewTrain>>() {
          @Override
          public void onResponse(Call<List<NewTrain>> call, Response<List<NewTrain>> response) {
              if(response.isSuccessful())
              {
                  for(NewTrain newTrain: response.body()) {
                      t.append(String.valueOf(newTrain.getResponse_code()));
                  }
              }
          }

          @Override
          public void onFailure(Call<List<NewTrain>> call, Throwable t) {
              Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

          }
      });

    }

Body:
As the JSON mentioned train contains a JSON object, not a list. Another of the classes list will be a member of TainClass not in the NewTrainClass.

So, instead of:

@SerializedName("train")
private List<TrainClass> train= null;

make it

@SerializedName("train")
private TrainClass train= null;

and also Move Classes to the TrainClass

@SerializedName("classes")
private ArrayList<classes> arrayList = null;

Finally, the NewTrain Object will be like

public class NewTrain {
    @SerializedName("response_code")
    private int response_code;
    @SerializedName("debit")
    private int debit;
    @SerializedName("train")
    private TrainClass train;

    public int getResponse_code() {
        return response_code;
    }

    public void setResponse_code(int response_code) {
        this.response_code = response_code;
    }

    public int getDebit() {
        return debit;
    }

    public void setDebit(int debit) {
        this.debit = debit;
    }

    public TrainClass getTrain() {
        return train;
    }

    public void setTrain(TrainClass train) {
        this.train = train;
    }
}

public class TrainClass
 @SerializedName("number")
    private int number;
    @SerializedName("name")
    private String name;
    @SerializedName("days")
    private List<Day> dayList = null;
   @SerializedName("classes")
    private ArrayList<classes> arrayList = null;
    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Day> getDayList() {
        return dayList;
    }

    public void setDayList(List<Day> dayList) {
        this.dayList = dayList;
    }

    public ArrayList<classes> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<classes> arrayList) {
        this.arrayList = arrayList;
    }
}

Look like the JSON contains only a NewTrain, not the List<NewTrain>. nd also need to update the myWebService.getTrainList();
You also need to update the method like

 public void Show(View view) {

    MyWebService myWebService = MyWebService.retrofitfortrain.create(MyWebService.class);
    Call<NewTrain>  call = myWebService.getTrainList();
  call.enqueue(new Callback<NewTrain>() {
      @Override
      public void onResponse(Call<NewTrain> call, Response<NewTrain> response) {
          if(response.isSuccessful())
          {
              for(NewTrain newTrain: response.body()) {
                  t.append(String.valueOf(newTrain.getResponse_code()));
              }
          }
      }

      @Override
      public void onFailure(Call<NewTrain> call, Throwable t) {
          Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

      }
  });

}

Hope this will work.


问:
Azure function HTTP Request 404 when published to Azure through Docker and Visual Studio
I'm attempting to learn some more about Azure Functions 2.0 and Docker containers to publish to my Azure instance. I followed to tutorial below with the only difference being that I published with docker to a container registry in azure using visual studio 2019.

https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-your-first-function-visual-studio

This all worked correctly and I was able to start my container and visit the site. However, in the example you can visit /api/function1 and get a response. This works on my localhost but on the live site it returns a 404. It seems that /api/function1 is not reachable after being published.

The app itself returns this when visiting the IP itself so I know it is working. Do I need to do something else in Azure to expose my APIs?

My container log only shows this.

```<code>Hosting environment: Production
Content root path: C:\
Now listening on: http://[::]:80
Application started. Press Ctrl+C to shut down.
</code>```

I grabbed my dockerfile from here

https://github.com/Azure/azure-functions-docker/blob/master/host/2.0/nanoserver-1809/Dockerfile

```<code># escape=`

# Installer image
FROM mcr.microsoft.com/windows/servercore:1809 AS installer-env

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

# Retrieve .NET Core SDK
ENV DOTNET_SDK_VERSION 2.2.402

RUN Invoke-WebRequest -OutFile dotnet.zip https://dotnetcli.blob.core.windows.net/dotnet/Sdk/$Env:DOTNET_SDK_VERSION/dotnet-sdk-$Env:DOTNET_SDK_VERSION-win-x64.zip; `
    $dotnet_sha512 = '0fa3bf476b560c8fc70749df37a41580f5b97334b7a1f19d66e32096d055043f4d7ad2828f994306e0a24c62a3030358bcc4579d2d8d439d90f36fecfb2666f6'; `
    if ((Get-FileHash dotnet.zip -Algorithm sha512).Hash -ne $dotnet_sha512) { `
        Write-Host 'CHECKSUM VERIFICATION FAILED!'; `
        exit 1; `
    }; `
    `
    Expand-Archive dotnet.zip -DestinationPath dotnet; `
    Remove-Item -Force dotnet.zip

ENV ASPNETCORE_URLS=http://+:80 `
    DOTNET_RUNNING_IN_CONTAINER=true `
    DOTNET_USE_POLLING_FILE_WATCHER=true `
    NUGET_XMLDOC_MODE=skip `
    PublishWithAspNetCoreTargetManifest=false `
    HOST_COMMIT=69f124faed40d20d9d8e5b8d51f305d249b21512 `
    BUILD_NUMBER=12858

RUN [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    Invoke-WebRequest -OutFile host.zip https://github.com/Azure/azure-functions-host/archive/$Env:HOST_COMMIT.zip; `
    Expand-Archive host.zip .; `
    cd azure-functions-host-$Env:HOST_COMMIT; `
    /dotnet/dotnet publish /p:BuildNumber=$Env:BUILD_NUMBER /p:CommitHash=$Env:HOST_COMMIT src\WebJobs.Script.WebHost\WebJobs.Script.WebHost.csproj --output C:\runtime

# Runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2.7-nanoserver-1809

COPY --from=installer-env ["C:\\runtime", "C:\\runtime"]

ENV AzureWebJobsScriptRoot=C:\approot `
    WEBSITE_HOSTNAME=localhost:80

CMD ["dotnet", "C:\\runtime\\Microsoft.Azure.WebJobs.Script.WebHost.dll"]
</code>```

Here's my function1 code for my azure function

```<code>public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string productid = req.Query["productid"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            productid = productid ?? data?.product;

            Product newProduct = new Product()
            {
                ProductNumber = 0,
                ProductName = "Unknown",
                ProductCost = 0
            };
            if (Convert.ToInt32(productid) ==1)
            {
                newProduct = new Product()
                {
                    ProductCost = 100,
                    ProductName = "Lime Tree",
                    ProductNumber = 1
                };
            }
            else if(Convert.ToInt32(productid) == 2)
            {
                newProduct = new Product()
                {
                    ProductCost = 500,
                    ProductName = "Lemon Tree",
                    ProductNumber = 2
                };
            }
            return productid != null
                ? (ActionResult)new JsonResult(newProduct)
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
</code>```

Here's a photo of my container running with my image.

I'm new to this so any advice would be helpful for sure!

Thanks!

答:
First, I don't know if you really need to (or want to) run Functions on Windows containers. If you want to run in a container, I would probably opt for Linux. For that, this is an example Dockerfile. It does build on top of the Microsoft-provided base image. So you don't have to build that from scratch.

I'm sure there is also a base image for Windows that is already build. If you need it, just look around in the similiar repo I guess.

```<code>FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app

COPY . ./
RUN dotnet publish myfunction -c Release -o myfunction /out

FROM mcr.microsoft.com/azure-functions/dotnet:3.0 AS base
WORKDIR /app
EXPOSE 80

COPY --from=build-env /app/ao-backendfunctions/out .

ENV AzureWebJobsScriptRoot=/app
ENV AzureFunctionsJobHost__Logging__Console__IsEnabled=true
</code>```

The important part is RUN dotnet publish myfunction -c Release -o myfunction /out. Replace myfunction with the (folder) name of your actual Function.

Body:
I'm attempting to learn some more about Azure Functions 2.0 and Docker containers to publish to my Azure instance. I followed to tutorial below with the only difference being that I published with docker to a container registry in azure using visual studio 2019.

https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-your-first-function-visual-studio

This all worked correctly and I was able to start my container and visit the site. However, in the example you can visit /api/function1 and get a response. This works on my localhost but on the live site it returns a 404. It seems that /api/function1 is not reachable after being published.

The app itself returns this when visiting the IP itself so I know it is working. Do I need to do something else in Azure to expose my APIs?

My container log only shows this.

Hosting environment: Production
Content root path: C:\
Now listening on: http://[::]:80
Application started. Press Ctrl+C to shut down.

I grabbed my dockerfile from here

https://github.com/Azure/azure-functions-docker/blob/master/host/2.0/nanoserver-1809/Dockerfile

# escape=`

# Installer image
FROM mcr.microsoft.com/windows/servercore:1809 AS installer-env

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

# Retrieve .NET Core SDK
ENV DOTNET_SDK_VERSION 2.2.402

RUN Invoke-WebRequest -OutFile dotnet.zip https://dotnetcli.blob.core.windows.net/dotnet/Sdk/$Env:DOTNET_SDK_VERSION/dotnet-sdk-$Env:DOTNET_SDK_VERSION-win-x64.zip; `
    $dotnet_sha512 = '0fa3bf476b560c8fc70749df37a41580f5b97334b7a1f19d66e32096d055043f4d7ad2828f994306e0a24c62a3030358bcc4579d2d8d439d90f36fecfb2666f6'; `
    if ((Get-FileHash dotnet.zip -Algorithm sha512).Hash -ne $dotnet_sha512) { `
        Write-Host 'CHECKSUM VERIFICATION FAILED!'; `
        exit 1; `
    }; `
    `
    Expand-Archive dotnet.zip -DestinationPath dotnet; `
    Remove-Item -Force dotnet.zip

ENV ASPNETCORE_URLS=http://+:80 `
    DOTNET_RUNNING_IN_CONTAINER=true `
    DOTNET_USE_POLLING_FILE_WATCHER=true `
    NUGET_XMLDOC_MODE=skip `
    PublishWithAspNetCoreTargetManifest=false `
    HOST_COMMIT=69f124faed40d20d9d8e5b8d51f305d249b21512 `
    BUILD_NUMBER=12858

RUN [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    Invoke-WebRequest -OutFile host.zip https://github.com/Azure/azure-functions-host/archive/$Env:HOST_COMMIT.zip; `
    Expand-Archive host.zip .; `
    cd azure-functions-host-$Env:HOST_COMMIT; `
    /dotnet/dotnet publish /p:BuildNumber=$Env:BUILD_NUMBER /p:CommitHash=$Env:HOST_COMMIT src\WebJobs.Script.WebHost\WebJobs.Script.WebHost.csproj --output C:\runtime

# Runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2.7-nanoserver-1809

COPY --from=installer-env ["C:\\runtime", "C:\\runtime"]

ENV AzureWebJobsScriptRoot=C:\approot `
    WEBSITE_HOSTNAME=localhost:80

CMD ["dotnet", "C:\\runtime\\Microsoft.Azure.WebJobs.Script.WebHost.dll"]

Here's my function1 code for my azure function

public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string productid = req.Query["productid"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            productid = productid ?? data?.product;

            Product newProduct = new Product()
            {
                ProductNumber = 0,
                ProductName = "Unknown",
                ProductCost = 0
            };
            if (Convert.ToInt32(productid) ==1)
            {
                newProduct = new Product()
                {
                    ProductCost = 100,
                    ProductName = "Lime Tree",
                    ProductNumber = 1
                };
            }
            else if(Convert.ToInt32(productid) == 2)
            {
                newProduct = new Product()
                {
                    ProductCost = 500,
                    ProductName = "Lemon Tree",
                    ProductNumber = 2
                };
            }
            return productid != null
                ? (ActionResult)new JsonResult(newProduct)
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }

Here's a photo of my container running with my image.

I'm new to this so any advice would be helpful for sure!

Thanks!

Body:
First, I don't know if you really need to (or want to) run Functions on Windows containers. If you want to run in a container, I would probably opt for Linux. For that, this is an example Dockerfile. It does build on top of the Microsoft-provided base image. So you don't have to build that from scratch.

I'm sure there is also a base image for Windows that is already build. If you need it, just look around in the similiar repo I guess.

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app

COPY . ./
RUN dotnet publish myfunction -c Release -o myfunction /out

FROM mcr.microsoft.com/azure-functions/dotnet:3.0 AS base
WORKDIR /app
EXPOSE 80

COPY --from=build-env /app/ao-backendfunctions/out .

ENV AzureWebJobsScriptRoot=/app
ENV AzureFunctionsJobHost__Logging__Console__IsEnabled=true

The important part is RUN dotnet publish myfunction -c Release -o myfunction /out. Replace myfunction with the (folder) name of your actual Function.


问:
Logging Page popup in Oracle SQL Developer
The "Logging Page - Log" keeps popping up as I type in Oracle SQL Developer. I think I must have accidentally hit a shortcut and enabled some setting, but I have no idea what.</p>

答: It's not possible to suppress it, it will pop up again on any action. However you can dock it in the left bottom area and it'll stay on the "Messages" tab unless you click the other tab.</p>

ContentLicense: CC BY-SA 3.0


问:
Send mail via Python logging in with Windows Authentication
I've a conceptual doubt, I don't know if it's even possible.

Assume I log on a Windows equipment with an account (let's call it AccountA from UserA). However, this account has access to the mail account (Outlook) of the UserA and another fictional user (UserX, without any password, you logg in thanks to Windows authentication), shared by UserA, UserB and UserC.

Can I send a mail from User A using the account of User X via Python? If so, how shall I do the log in?

Thanks in advance

答:
A interesting feature with Windows Authentication is that is uses the well known Kerberos protocol under the hood. In a private environment, that means if a server trusts the Active Directory domain, you can pass the authentication of a client machine to that server provided the service is Kerberized, even if the server is a Linux or Unix box and is not a domain member.

It is mainly used for Web servers in corporate environment, but could be used for any kerberized service. Postfix for example is know to accept this kind of authentication.

If you want to access an external mail server, you will have to store the credential in plain text on the client machine, which is bad. An acceptable way would be to use a file only readable by the current user (live protection) in an encrypted folder (at rest protection).


问:
Javascript array search filter
I have the scenario, with provided example JSON data:

```<code>[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]
</code>```

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

```<code>filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});
</code>```

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.

答:
You may create additional function ageComparer for convenience

```<code>const ageComparer = (ageRange, age) => (ageRange === '23-26' ? (age >= 23 && age <= 26) : age >=27)
</code>```

And then utilize it during filtering

```<code>// ageFilter will be taken from drom down
const ageFilter = ['23-26'];

person.filter(p => p.hobby.some(v=> filterHobby.indexOf(v) !== -1) && ageFilter.some(a => ageComparer(a, +p.age)))
</code>```

Title: Javascript array search filter

Body:
I have the scenario, with provided example JSON data:

[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.

Body:
You may create additional function ageComparer for convenience

const ageComparer = (ageRange, age) => (ageRange === '23-26' ? (age >= 23 && age <= 26) : age >=27)

And then utilize it during filtering

// ageFilter will be taken from drom down
const ageFilter = ['23-26'];

person.filter(p => p.hobby.some(v=> filterHobby.indexOf(v) !== -1) && ageFilter.some(a => ageComparer(a, +p.age)))


问:
Trigger an action after selection of certain option from select2 dropdown
I'm using a Select2 dropdown. I want to trigger an event on selection of the Patient option. Right now it fires an event regardless which option is clicked.

```<code>  <div class="col-md-3">
    {!!($errors->has('name')) ? '<div class="form-group has-error">' : '<div class="form-group">'!!}
    {{Form::label('based on', 'Based on:')}}<br>
    {!! Form::select('type', ['' => 'Select type'] + ['0' => 'Image', '1' => 'Patient'], null, ['class' => 'form-control select2', 'id' => 'type',  'style' => 'width: 100%;']) !!}
  </div>
</div>
<div class="col-md-3" id="timeframe-div" style="display: none;">
  {!!($errors->has('name')) ? '<div class="form-group has-error">' : '<div class="form-group">'!!}
  {{Form::label('based on', 'Timeframe:')}}<br>
  {!! Form::select('timeframe', ['' => 'Select type'] + ['0' => 'Daily', '1' => 'Weekly', '2' => 'Monthly'], null, ['class' => 'form-control select2', 'id' => 'timeframe',  'style' => 'width: 100%;']) !!}
</div>
</code>```

$('#type').on("select2:selecting", function(e) {
  $("#timeframe-div").css("display", "block");
});
```

答:
From the Select2 documentation:

When select2:select is triggered, data from the selection can be accessed via the params.data property:

As such, use this:

```<code>$('#type').on("select2:select", function(e) {
  if (e.params.data.text === 'Patient')
    $("#id").css("display", "block");
});
</code>```

Note that this is reading the text property of the data you provide to Select2. If required you can change this to use id instead.

Body:
I'm using a Select2 dropdown. I want to trigger an event on selection of the Patient option. Right now it fires an event regardless which option is clicked.

    {!!($errors->has('name')) ? '
' : '
'!!}
    {{Form::label('based on', 'Based on:')}}

    {!! Form::select('type', ['' => 'Select type'] + ['0' => 'Image', '1' => 'Patient'], null, ['class' => 'form-control select2', 'id' => 'type',  'style' => 'width: 100%;']) !!}

  {!!($errors->has('name')) ? '
' : '
'!!}
  {{Form::label('based on', 'Timeframe:')}}

  {!! Form::select('timeframe', ['' => 'Select type'] + ['0' => 'Daily', '1' => 'Weekly', '2' => 'Monthly'], null, ['class' => 'form-control select2', 'id' => 'timeframe',  'style' => 'width: 100%;']) !!}

$('#type').on("select2:selecting", function(e) {
  $("#timeframe-div").css("display", "block");
});

Body:
From the Select2 documentation:

When select2:select is triggered, data from the selection can be accessed via the params.data property:

As such, use this:

$('#type').on("select2:select", function(e) {
  if (e.params.data.text === 'Patient')
    $("#id").css("display", "block");
});

Note that this is reading the text property of the data you provide to Select2. If required you can change this to use id instead.


问:
How to get the Facebook insights data for ad Creative
I'am trying to get the reports data for the Facebook campaign, campaign has 3 adset, 3 ad and each ad has 3 adCreatives. Please can anyone help me in getting the adCreative specific insights data. I tried with the graph API explore i did't get the data for adCreatives.

call made with params are : https://graph.facebook.com/2.9/campaingId-XXXX/insights?fields=impressions,clicks,ctr,ad_name,adset_name,cpc,cpm,cpp,campaign_name,ad_id,adset_id,account_id,account_name&level=ad&metrics=ctr&limit=10

Ex : response from Graph API explorer

```<code>{
  "data": [
    {
      "impressions": "30",
      "clicks": "1",
      "ctr": "3.333333",
      "ad_name": "I Ad",
      "adset_name": "I Ad Set",
      "cpc": "0.03",
      "cpm": "1",
      "cpp": "4.285714",
      "campaign_name": "Campaign.act_xxxxxxx",
      "ad_id": "xxxxx",
      "adset_id": "xxxxx",
      "account_id": "xxxxx",
      "account_name": "Test Account From test",
      "date_start": "2017-04-17",
      "date_stop": "2017-05-16"
    },
    {
      "impressions": "28",
      "clicks": "0",
      "ctr": "0",
      "ad_name": "H Ad",
      "adset_name": "H Ad Set",
      "cpc": "0",
      "cpm": "1.071429",
      "cpp": "3.75",
      "campaign_name": "Campaign.act_xxxxxxx",
      "ad_id": "xxxxxx",
      "adset_id": "xxxxx",
      "account_id": "xxxxxx",
      "account_name": "Test Account From test",
      "date_start": "2017-04-17",
      "date_stop": "2017-05-16"
    },
    {
      "impressions": "29",
      "clicks": "2",
      "ctr": "6.896552",
      "ad_name": "G Ad",
      "adset_name": "G Ad Set",
      "cpc": "0.025",
      "cpm": "1.724138",
      "cpp": "8.333333",
      "campaign_name": "Campaign.act_xxxxxxx",
      "ad_id": "xxxxxx",
      "adset_id": "xxxxxxxxx",
      "account_id": "xxxxxxxx",
      "account_name": "Test Account From test",
      "date_start": "2017-04-17",
      "date_stop": "2017-05-16"
    }
  ],
  "paging": {
    "cursors": {
      "before": "MAZDZD",
      "after": "MgZDZD"
    }
  }
}
</code>```

答:
Each ad can have only one creative, therefore the best way forward is to list all the ads within an account and project creative info. You can try the following graph query:

/act_{{AD_ACCOUNT_ID}}/ads?fields=adcreatives{body,effective_object_story_id,object_url,thumbnail_url,image_url,object_type},insights.date_preset(lifetime).level(ad).breakdowns(publisher_platform){spend,clicks,impressions,reach,actions,unique_actions,video_p25_watched_actions,video_p50_watched_actions,video_p75_watched_actions,video_p95_watched_actions,video_p100_watched_actions,video_10_sec_watched_actions},id,name,campaign{id,name,account_id,objective},adset{id,name},created_time&limit=250&effective_status=['ACTIVE','ARCHIVED','PAUSED','CAMPAIGN_PAUSED','ADSET_PAUSED']

Body:
I'am trying to get the reports data for the Facebook campaign, campaign has 3 adset, 3 ad and each ad has 3 adCreatives. Please can anyone help me in getting the adCreative specific insights data. I tried with the graph API explore i did't get the data for adCreatives.

call made with params are : https://graph.facebook.com/2.9/campaingId-XXXX/insights?fields=impressions,clicks,ctr,ad_name,adset_name,cpc,cpm,cpp,campaign_name,ad_id,adset_id,account_id,account_name&level=ad&metrics=ctr&limit=10

Ex : response from Graph API explorer

{
  "data": [
    {
      "impressions": "30",
      "clicks": "1",
      "ctr": "3.333333",
      "ad_name": "I Ad",
      "adset_name": "I Ad Set",
      "cpc": "0.03",
      "cpm": "1",
      "cpp": "4.285714",
      "campaign_name": "Campaign.act_xxxxxxx",
      "ad_id": "xxxxx",
      "adset_id": "xxxxx",
      "account_id": "xxxxx",
      "account_name": "Test Account From test",
      "date_start": "2017-04-17",
      "date_stop": "2017-05-16"
    },
    {
      "impressions": "28",
      "clicks": "0",
      "ctr": "0",
      "ad_name": "H Ad",
      "adset_name": "H Ad Set",
      "cpc": "0",
      "cpm": "1.071429",
      "cpp": "3.75",
      "campaign_name": "Campaign.act_xxxxxxx",
      "ad_id": "xxxxxx",
      "adset_id": "xxxxx",
      "account_id": "xxxxxx",
      "account_name": "Test Account From test",
      "date_start": "2017-04-17",
      "date_stop": "2017-05-16"
    },
    {
      "impressions": "29",
      "clicks": "2",
      "ctr": "6.896552",
      "ad_name": "G Ad",
      "adset_name": "G Ad Set",
      "cpc": "0.025",
      "cpm": "1.724138",
      "cpp": "8.333333",
      "campaign_name": "Campaign.act_xxxxxxx",
      "ad_id": "xxxxxx",
      "adset_id": "xxxxxxxxx",
      "account_id": "xxxxxxxx",
      "account_name": "Test Account From test",
      "date_start": "2017-04-17",
      "date_stop": "2017-05-16"
    }
  ],
  "paging": {
    "cursors": {
      "before": "MAZDZD",
      "after": "MgZDZD"
    }
  }
}