问:
How to add unique identifier to each level of nested array with unknown values?
I have array that contains 4 levels of nesting:

```<code>$data =  [
    "" => [
            'sub_level_1' => [
                    'sub_level_2' => [
                            'sub_level_3' => [
                                      0 => ""
                                      1 => "val"
                                 ]
                        ]
              ]
        ],
    "top_level_2" => [
            'sub_level_1' => [
                    'sub_level_2' => [
                            'sub_level_3' => [
                                      0 => ""
                                      1 => "some_val"
                                      2 => "foo"
                                 ]
                        ]
              ]
        ]
];
</code>```

I want to add other unique identifier for each nested level, so I use a counter on each level:

```<code>$top_level_counter = 0;
$sub_level_1_counter = 0;
$sub_level_2_counter = 0;
$sub_level_3_counter = 0;

foreach ($data as &$top_level)
{
    $top_level['top_level_id'] = $top_level_counter++;

    foreach($top_level as &$sub_level_1)
    {
        $sub_level_1['sub_level_1_id'] = $sub_level_1_counter++;

            foreach($sub_level_1 as &$sub_level_2)
            {
                $sub_level_2['sub_level_2_id'] = $sub_level_2_counter++;
                // and continue with the last level..
            }
    }
}
</code>```

But as the example above, the keys can be empty ("") or even null because that's data from the database.

I end up getting errors related to invalid values, but I can't find out which.

I did figure that as I go inside each level, I have to check for:

```<code>if (is_array($sub_level_<x>)
</code>```

because on each level above I already store the unique id which is not an array. But still, even with that, I get invalid input for foreach for example.
But I can't find out what's causing that, though I suspect it might be because of a null or empty value

Is there a better way to do that?

The reason I want to do it is to have an easier to work with identifier for each element in the array because the actual data is strings in another language.

Expected result would be:

```<code>$data =  [
    "" => [
            'top_level_id' => 0,
            'sub_level_1' => [
                    'sub_level_1_id' => 0,
                    'sub_level_2' => [
                            'sub_level_2_id' => 0,
                            'sub_level_3' => [
                                      0 => ""
                                      1 => "val"
                                 ]
                        ]
              ]
        ],
    "top_level_2" => [
            'top_level_id' => 1,
            'sub_level_1' => [
                    'sub_level_1_id' => 1,
                    'sub_level_2' => [
                            'sub_level_2_id' => 1,
                            'sub_level_3' => [
                                      0 => ""
                                      1 => "some_val"
                                      2 => "foo"
                                 ]
                        ]
              ]
        ]
];
</code>```

Body:
I have array that contains 4 levels of nesting:

$data =  [
    "" => [
            'sub_level_1' => [
                    'sub_level_2' => [
                            'sub_level_3' => [
                                      0 => ""
                                      1 => "val"
                                 ]
                        ]
              ]
        ],
    "top_level_2" => [
            'sub_level_1' => [
                    'sub_level_2' => [
                            'sub_level_3' => [
                                      0 => ""
                                      1 => "some_val"
                                      2 => "foo"
                                 ]
                        ]
              ]
        ]
];

I want to add other unique identifier for each nested level, so I use a counter on each level:

$top_level_counter = 0;
$sub_level_1_counter = 0;
$sub_level_2_counter = 0;
$sub_level_3_counter = 0;

foreach ($data as &$top_level)
{
    $top_level['top_level_id'] = $top_level_counter++;

    foreach($top_level as &$sub_level_1)
    {
        $sub_level_1['sub_level_1_id'] = $sub_level_1_counter++;

            foreach($sub_level_1 as &$sub_level_2)
            {
                $sub_level_2['sub_level_2_id'] = $sub_level_2_counter++;
                // and continue with the last level..
            }
    }
}

But as the example above, the keys can be empty ("") or even null because that's data from the database.

I end up getting errors related to invalid values, but I can't find out which.

I did figure that as I go inside each level, I have to check for:

if (is_array($sub_level_<x>)

because on each level above I already store the unique id which is not an array. But still, even with that, I get invalid input for foreach for example.
But I can't find out what's causing that, though I suspect it might be because of a null or empty value

Is there a better way to do that?

The reason I want to do it is to have an easier to work with identifier for each element in the array because the actual data is strings in another language.

Expected result would be:

$data =  [
    "" => [
            'top_level_id' => 0,
            'sub_level_1' => [
                    'sub_level_1_id' => 0,
                    'sub_level_2' => [
                            'sub_level_2_id' => 0,
                            'sub_level_3' => [
                                      0 => ""
                                      1 => "val"
                                 ]
                        ]
              ]
        ],
    "top_level_2" => [
            'top_level_id' => 1,
            'sub_level_1' => [
                    'sub_level_1_id' => 1,
                    'sub_level_2' => [
                            'sub_level_2_id' => 1,
                            'sub_level_3' => [
                                      0 => ""
                                      1 => "some_val"
                                      2 => "foo"
                                 ]
                        ]
              ]
        ]
];


来源: stackexchange

问:
How to get a file using retrofit with flutter?
I have a file that I have to retrieve it from the server. The backend is developed with springboot. And I have to consume the same api with flutter.
this is how I configure the service :

```<code>@RestApi(baseUrl: "http")
abstract class ApiService {
  factory ApiService(Dio dio, {String baseUrl}) = _ApiService;

  @GET("/download/{fileName}")
  Response download(@Path("fileName") String fileName);
}

</code>```

I want to know if this can work and what are the next steps.
Thanks in advance for your help.

ContentLicense: CC BY-SA 4.0

Body:
I have a file that I have to retrieve it from the server. The backend is developed with springboot. And I have to consume the same api with flutter.
this is how I configure the service :

@RestApi(baseUrl: "http")
abstract class ApiService {
  factory ApiService(Dio dio, {String baseUrl}) = _ApiService;

  @GET("/download/{fileName}")
  Response download(@Path("fileName") String fileName);
}

I want to know if this can work and what are the next steps.
Thanks in advance for your help.


问:
Qt 6 Multimedia Static Build using Mingw on windows
I have been using Qt for long time and I want to create a simple audio player for windows that uses Qt static linked, I simply created a Qt static build and it works fine with msvc 2019 but when I try to build Qt static with same config with Mingw11.2 on windows I get this error , and what ever I do it failt to build my player statically even if it works fine with qt 5.x

```<code>C:\Users\Amr\repos\SimpleAudioPlayer\CMakeLists.txt:86: error:
Found package configuration file: C:/Users/Amr/Qt/6.4.1/mingw112_64_static/lib/cmake/Qt6/Qt6Config.cmake
but it set Qt6_FOUND to FALSE so package "Qt6" is considered to be NOT FOUND.
Reason given by package: Failed to find required Qt component "Multimedia".
Expected Config file at "C:/Users/Amr/Qt/6.4.1/mingw112_64_static/lib/cmake/Qt6Multimedia/Qt6MultimediaConfig.cmake" exists
</code>```

here is the relevant part of Qt configuration summary

```<code>Qt Multimedia:
  Spatial Audio .......................... yes
  Spatial Audio (Quick3D) ................ no
  Low level Audio Backend:
    ALSA (experimental) .................. no
    PulseAudio ........................... no
    MMRenderer ........................... no
    CoreAudio ............................ no
    Windows Media SDK .................... yes
    Open SLES (Android) .................. no
    Web Assembly ......................... no
  Plugin:
    GStreamer 1.0 ........................ no
    FFmpeg ............................... no
    MMRenderer ........................... no
    AVFoundation ......................... no
    Windows Media Foundation ............. yes
  Hardware acceleration and features:
    Video for Linux ...................... no
    VAAPI support ........................ no
    Linux DMA buffer support ............. no
    VideoToolbox ......................... no
</code>```

and this is my config

```<code>-release
-opensource
-confirm-license
-platform
win32-g++
-opengl
desktop
-no-dbus
-no-icu
-no-fontconfig
-qt-freetype
-qt-harfbuzz
-qt-doubleconversion
-nomake
examples
-nomake
tests
-static
-static-runtime
-feature-relocatable
-ssl
-no-sql-psql
-sql-sqlite
-sql-odbc
-qt-zlib
-qt-pcre
-qt-libpng
-qt-libjpeg
-no-warnings-are-errors
-make
libs
-skip
qtmqtt
-skip
qtvirtualkeyboard
-skip
qtsensors
-skip
qtcoap
-skip
qtconnectivity
-skip
qtdatavis3d
-skip
qtdoc
-skip
qtlottie
-skip
qtnetworkauth
-skip
qtopcua
-skip
qtserialport
-skip
qtpositioning
-skip
qtquicktimeline
-skip
qtquick3d
-skip
qtremoteobjects
-skip
qtscxml
-skip
qtserialbus
-skip
qtwayland
-skip
qtwebchannel
-skip
qtwebengine
-skip
qtwebview
-skip
qtquick3dphysics
-skip
qtspeech
-schannel
-no-openssl
-prefix
C:\Users\Amr\Qt\6.4.1\mingw112_64_static
</code>```

any help is appreciated
Thanks
Amr

Body:
I have been using Qt for long time and I want to create a simple audio player for windows that uses Qt static linked, I simply created a Qt static build and it works fine with msvc 2019 but when I try to build Qt static with same config with Mingw11.2 on windows I get this error , and what ever I do it failt to build my player statically even if it works fine with qt 5.x

C:\Users\Amr\repos\SimpleAudioPlayer\CMakeLists.txt:86: error:
Found package configuration file: C:/Users/Amr/Qt/6.4.1/mingw112_64_static/lib/cmake/Qt6/Qt6Config.cmake
but it set Qt6_FOUND to FALSE so package "Qt6" is considered to be NOT FOUND.
Reason given by package: Failed to find required Qt component "Multimedia".
Expected Config file at "C:/Users/Amr/Qt/6.4.1/mingw112_64_static/lib/cmake/Qt6Multimedia/Qt6MultimediaConfig.cmake" exists

here is the relevant part of Qt configuration summary

Qt Multimedia:
  Spatial Audio .......................... yes
  Spatial Audio (Quick3D) ................ no
  Low level Audio Backend:
    ALSA (experimental) .................. no
    PulseAudio ........................... no
    MMRenderer ........................... no
    CoreAudio ............................ no
    Windows Media SDK .................... yes
    Open SLES (Android) .................. no
    Web Assembly ......................... no
  Plugin:
    GStreamer 1.0 ........................ no
    FFmpeg ............................... no
    MMRenderer ........................... no
    AVFoundation ......................... no
    Windows Media Foundation ............. yes
  Hardware acceleration and features:
    Video for Linux ...................... no
    VAAPI support ........................ no
    Linux DMA buffer support ............. no
    VideoToolbox ......................... no

and this is my config

-release
-opensource
-confirm-license
-platform
win32-g++
-opengl
desktop
-no-dbus
-no-icu
-no-fontconfig
-qt-freetype
-qt-harfbuzz
-qt-doubleconversion
-nomake
examples
-nomake
tests
-static
-static-runtime
-feature-relocatable
-ssl
-no-sql-psql
-sql-sqlite
-sql-odbc
-qt-zlib
-qt-pcre
-qt-libpng
-qt-libjpeg
-no-warnings-are-errors
-make
libs
-skip
qtmqtt
-skip
qtvirtualkeyboard
-skip
qtsensors
-skip
qtcoap
-skip
qtconnectivity
-skip
qtdatavis3d
-skip
qtdoc
-skip
qtlottie
-skip
qtnetworkauth
-skip
qtopcua
-skip
qtserialport
-skip
qtpositioning
-skip
qtquicktimeline
-skip
qtquick3d
-skip
qtremoteobjects
-skip
qtscxml
-skip
qtserialbus
-skip
qtwayland
-skip
qtwebchannel
-skip
qtwebengine
-skip
qtwebview
-skip
qtquick3dphysics
-skip
qtspeech
-schannel
-no-openssl
-prefix
C:\Users\Amr\Qt\6.4.1\mingw112_64_static

any help is appreciated
Thanks
Amr


问:
CARD GAME apply the good effect (if exist) in the right game sequence
first sorry for my broken english,

I want to create a card game with python and i have some question about the game sequence.

I have created this class :

Class card with all necessary variables : name, life, initiative…, texteffects, effects

texteffects is in this class just a text description of the effect that card can have on the game sequence, effects is the name of the object defined in an other class : the class of the effect

so, each effect has his own class with the algorithmic definition of the effect

effect have an owner (the player who own (control) the card), sometimes a target (most of the time an opponement), a trigger (which time this effect would activating, testing), a duration (once per turn, once per game, permanent). Effect have a method in order to activate it or reset it

so i have a game sequence for example attack sequence with 5 steps : (this sequence is a class too, class attack and each sequence is a method of class object attack)

1 before attack

2 attack_roll

3 attack : hit

4 attack : miss

5 after attack

I want to test if one of my cards in game have a trigger on this sequence and if yes launch the method activate for example and the desactivate method at the end of the effect (with duration variable for example)

So true example :

Warrior1=cards(« Alexander »,8,4, « Kat : Your attacks deal +1 damage against warriors with more life than you. »,kat)

Object kat instance of Kat (the effects)

kat=Kat(warrior1)

Warrior2=cards(« Leo »,9,2, « Mol : Once per round, after you deal damage to an enemy warrior, gain 1 life. »,mol)

Object kat instance of Kat (the effects)

Mol=Mol(warrior2)

attack1=attack(attacker=warrior1,defender=warrior2)

attack1.before_attack() is there effect at this step => in this case no so Pass

attack1.attack_roll() is there effect at this step => in this case no so Pass

attack1.attack_hit() YES there is an effect happened : kat effect can activate here (we supose that attack hit) so i want to launch the activate method of Kat on kat who own warrior1. Activate method so answer true cause the condition is met : warrior2 have more life than warrior1)

I stop the example here but the sequence go on. My question is how can I dynamically call the method activate in the good sequence.

Probably obsviously for you but not for me If you can help me, I’ll be grateful ! and you can give me advice on the global approach of the project, maybe is not the good way to code it !

Thanks for help


问:
Inversify decorator in abstract class doesn't work with protected constructor
```<code>Decorator function return type 'abstract new (...args: never) => unknown' is not assignable to type 'void | typeof BaseController'.
  Types of construct signatures are incompatible.
    Type 'abstract new (...args: never) => unknown' is not assignable to type 'abstract new (logger: ILogger) => BaseController'.
      Type 'unknown' is not assignable to type 'BaseController'.ts(1270)
Argument of type 'typeof BaseController' is not assignable to parameter of type 'abstract new (...args: never) => unknown'.
  Cannot assign a 'protected' constructor type to a 'public' constructor type.ts(2345)
</code>```

This error rise when I make constructor protected, I'm trying to find answer in Inversify docs but where is nothing about

Example of my code

```<code>@injectable()
export abstract class BaseController {
    private readonly _router: Router

    protected constructor(@inject(TYPES.ILogger) private logger: ILogger) {
        this._router = Router();
    }
    //some code
}

</code>```

Why should it be public?

Body:
Decorator function return type 'abstract new (...args: never) => unknown' is not assignable to type 'void | typeof BaseController'.
  Types of construct signatures are incompatible.
    Type 'abstract new (...args: never) => unknown' is not assignable to type 'abstract new (logger: ILogger) => BaseController'.
      Type 'unknown' is not assignable to type 'BaseController'.ts(1270)
Argument of type 'typeof BaseController' is not assignable to parameter of type 'abstract new (...args: never) => unknown'.
  Cannot assign a 'protected' constructor type to a 'public' constructor type.ts(2345)

This error rise when I make constructor protected, I'm trying to find answer in Inversify docs but where is nothing about

Example of my code

@injectable()
export abstract class BaseController {
    private readonly _router: Router

    protected constructor(@inject(TYPES.ILogger) private logger: ILogger) {
        this._router = Router();
    }
    //some code
}

Why should it be public?


问:
Adding jquery-3.* to an existing ScriptBundle causing script exceptions in MVC4
When I add "~/Scripts/jquery-3.*" to my existing bundle, it causes a series of script exceptions within the bundle, such as "Uncaught TypeError: n(...).parents(...).andSelf is not a function", "Uncaught TypeError: $(...).ajaxSuccess is not a function", "Uncaught TypeError: Cannot read properties of undefined (reading 'mode')", and "Uncaught Error: Syntax error, unrecognized expression: #".

Below is my bundle from BundleConfig.cs.

```<code>bundles.Add(new ScriptBundle("~/bundles/myownbundlejs").Include(
                    "~/Scripts/jquery-ui.js",
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*",
                    "~/Scripts/kendo/" + kendoVersion + "/jszip.min.js",
                    "~/Scripts/kendo/" + kendoVersion + "/kendo.all.min.js",
                    "~/Scripts/kendo/" + kendoVersion + "/kendo.aspnetmvc.min.js",
                    "~/Scripts/kendo/" + kendoVersion + "/kendo.autocomplete.min.js",
                    "~/Scripts/jquery.signalR-2.4.3.min.js",
                    "~/Scripts/jquery-3.*"
                    ));
</code>```

The bundle is referenced within rezor view that is included within HEAD tags of my _Layout.cshtml.

```<code>@Scripts.Render("~/bundles/myownbundlejs")
</code>```

My files jquery-3.* file within Scripts folder are as following:

Body:
When I add "~/Scripts/jquery-3.*" to my existing bundle, it causes a series of script exceptions within the bundle, such as "Uncaught TypeError: n(...).parents(...).andSelf is not a function", "Uncaught TypeError: $(...).ajaxSuccess is not a function", "Uncaught TypeError: Cannot read properties of undefined (reading 'mode')", and "Uncaught Error: Syntax error, unrecognized expression: #".

Below is my bundle from BundleConfig.cs.

bundles.Add(new ScriptBundle("~/bundles/myownbundlejs").Include(
                    "~/Scripts/jquery-ui.js",
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*",
                    "~/Scripts/kendo/" + kendoVersion + "/jszip.min.js",
                    "~/Scripts/kendo/" + kendoVersion + "/kendo.all.min.js",
                    "~/Scripts/kendo/" + kendoVersion + "/kendo.aspnetmvc.min.js",
                    "~/Scripts/kendo/" + kendoVersion + "/kendo.autocomplete.min.js",
                    "~/Scripts/jquery.signalR-2.4.3.min.js",
                    "~/Scripts/jquery-3.*"
                    ));

The bundle is referenced within rezor view that is included within HEAD tags of my _Layout.cshtml.

@Scripts.Render("~/bundles/myownbundlejs")

My files jquery-3.* file within Scripts folder are as following:


问:
Array Parameter from Application Settings in Logic App Standard
I'm writing a workflow in Logic App Standard. I have been using parameters of type String that refer to appsetting using the syntax @{appsetting('AppSettingName')} and that works fine.

Now I have another parameter of type Array, and would like to fetch its values from app settings also.

According to my test following does work. The problem with this approach is that I have to decide on how many elements there are in the array up front and get them from separate app settings. I would prefer to have the full variable length array from just one app setting.

App settings:

```<code>  {
    "name": "MyArrayParameter:0",
    "value": "3b6138ae-2d29-ed11-9db1-00224880162d",
    "slotSetting": false
  },
  {
    "name": "MyArrayParameter:1",
    "value": "82513cc7-b638-ed11-9db1-6045bd8952ce",
    "slotSetting": false
  }
</code>```

Parameter definition Value:

```<code>[
    "@appsetting('MyArrayParameter:0')",
    "@appsetting('MyArrayParameter:1')"
]
</code>```

Body:
I'm writing a workflow in Logic App Standard. I have been using parameters of type String that refer to appsetting using the syntax @{appsetting('AppSettingName')} and that works fine.

Now I have another parameter of type Array, and would like to fetch its values from app settings also.

According to my test following does work. The problem with this approach is that I have to decide on how many elements there are in the array up front and get them from separate app settings. I would prefer to have the full variable length array from just one app setting.

App settings:

  {
    "name": "MyArrayParameter:0",
    "value": "3b6138ae-2d29-ed11-9db1-00224880162d",
    "slotSetting": false
  },
  {
    "name": "MyArrayParameter:1",
    "value": "82513cc7-b638-ed11-9db1-6045bd8952ce",
    "slotSetting": false
  }

Parameter definition Value:

[
    "@appsetting('MyArrayParameter:0')",
    "@appsetting('MyArrayParameter:1')"
]


问:
Passing Background Image Path as Props not Working in Nuxt 3
I have a banner component in which I am passing the props for the image title and
the subtitle. When I set the image prop as my background image URL, it does not work.

Here is my component

<template>
  <div class="" :style="`background-image:url(${image})`">

      {{ subTitle }}

{{ title }}

</template>

```
<p>This is my parent component</p>
<pre class="lang-html prettyprint-override"><code><shared-banner
  title="Listings"
  subTitle="LOREM IPSUM"
  image="assets/images/listingsBanner.png"
/>
</code>```

I believe the issue has something to do with the image path.

Is there a way to set dynamic image paths as props for the style object in Nuxt3?

Body:
I have a banner component in which I am passing the props for the image title and
the subtitle. When I set the image prop as my background image URL, it does not work.

Here is my component

<template>
  <div class="" :style="`background-image:url(${image})`">

      {{ subTitle }}

{{ title }}

</template>

This is my parent component

<shared-banner
  title="Listings"
  subTitle="LOREM IPSUM"
  image="assets/images/listingsBanner.png"
/>

I believe the issue has something to do with the image path.

Is there a way to set dynamic image paths as props for the style object in Nuxt3?


问:
Getting error while sending Email alert from Grafana using O365
We have been trying to use Granafa + Prometheus to monitor our servers. However, when we configure the grafana.ini file with our o365 settings, we get following error -

we checked that host is same as mx record and on port 587. We created alias also & app password for this. Even then we keep getting this error.

Checked grafana community, but did not get any useful info.

Note: Email alert was successful for gmail which had 2FA on.


问:
How to decrypt minizip's WinZip AES using Apple's CryptoKit?
A project required me to decrypt minizip's WinZip AES on iOS. At the same time, Apple's CryptoKit is an upcoming framework to fulfil these kinds of needs by making use of specially designed hardware.

How to make use of Apple's CryptoKit to accomplish this requirement? If it is not possible, what are the other iOS-friendly frameworks to achieve this goal?

Thanks in advance.


问:
I have a problem with my code. I doesn't display the list
This code is a linked list, that displays the inputted list and will delete number in the list, but when I print the list it doesn't display. My code is shown below:

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

// A linked list node

```<code>struct Node {
    int data;
    struct Node* next;
};
</code>```

/* Given a reference (pointer to pointer) to the head of a
list and an int, inserts a new node on the front of the
list. */

```<code>void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
</code>```

/* Given a reference (pointer to pointer) to the head of a
list and a key, deletes the first occurrence of key in
linked list */

```<code>
void deleteNode(struct Node** head_ref, int key)
{

    // Store head node
    struct Node *temp = *head_ref, *prev;

    // If head node itself holds the key to be deleted
    if (temp != NULL && temp->data == key) {
        *head_ref = temp->next; // Changed head
        free(temp); // free old head
        return;
    }

    // Search for the key to be deleted, keep track of the
    // previous node as we need to change 'prev->next'
    while (temp != NULL && temp->data != key) {
        prev = temp;
        temp = temp->next;
    }

    // If key was not present in linked list
    if (temp == NULL)
        return;

    // Unlink the node from linked list
    prev->next = temp->next;

    free(temp); // Free memory
}
</code>```

// This function prints contents of linked list starting
// from the given node

```<code>void printList(struct Node* node)
{

    while (node != NULL) {
        printf("%d  ", node->data);
        node = node->next;
    }
}
</code>```

// Driver code

```<code>
int main()
{
    /* Start with the empty list */
    struct Node* node;

    int key;
    printf("Enter 10 integers: \n");
    for(int i=0;i<10;i++){
    scanf("%d", &key);
    }

    printf("Entered Elements within the List\n\n");
     printList(node);

    printf("\nEnter the element to be deleted: \n");
    scanf("%d", &key);

    deleteNode(&node, &key);
    printf("\nLinked List after Deletion of %d: \n", key);
    printList(node);
    return 0;
}
</code>```

Body:
This code is a linked list, that displays the inputted list and will delete number in the list, but when I print the list it doesn't display. My code is shown below:

#include <stdio.h>
#include <stdlib.h>

// A linked list node

struct Node {
    int data;
    struct Node* next;
};

/* Given a reference (pointer to pointer) to the head of a
list and an int, inserts a new node on the front of the
list. */

void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}

/* Given a reference (pointer to pointer) to the head of a
list and a key, deletes the first occurrence of key in
linked list */

void deleteNode(struct Node** head_ref, int key)
{

    // Store head node
    struct Node *temp = *head_ref, *prev;

    // If head node itself holds the key to be deleted
    if (temp != NULL && temp->data == key) {
        *head_ref = temp->next; // Changed head
        free(temp); // free old head
        return;
    }

    // Search for the key to be deleted, keep track of the
    // previous node as we need to change 'prev->next'
    while (temp != NULL && temp->data != key) {
        prev = temp;
        temp = temp->next;
    }

    // If key was not present in linked list
    if (temp == NULL)
        return;

    // Unlink the node from linked list
    prev->next = temp->next;

    free(temp); // Free memory
}

// This function prints contents of linked list starting
// from the given node

void printList(struct Node* node)
{

    while (node != NULL) {
        printf("%d  ", node->data);
        node = node->next;
    }
}

// Driver code

int main()
{
    /* Start with the empty list */
    struct Node* node;

    int key;
    printf("Enter 10 integers: \n");
    for(int i=0;i<10;i++){
    scanf("%d", &key);
    }

    printf("Entered Elements within the List\n\n");
     printList(node);

    printf("\nEnter the element to be deleted: \n");
    scanf("%d", &key);

    deleteNode(&node, &key);
    printf("\nLinked List after Deletion of %d: \n", key);
    printList(node);
    return 0;
}


问:
build a docker img in java dosnt work on http
hello iam trying to build an heroku replacement when iam running a docker img from my application in java it works from my terminal but when iam trying to view my application on http it gives me an error page

show how it works in terminal gets the id and run the docker
showing the error message

the problem :

```<code>
  ** String command = "curl --silent -XPOST --unix-socket /run/docker.sock -d '{\"Image\":\"nginx:latest\"}' -H 'Content-Type: application/json' http://localhost/containers/create?name=nginx";**

</code>```

the code :

```<code>package com.handson.chatbot.controller;

import com.handson.chatbot.model.StudentApplication;
import com.handson.chatbot.repo.StudentApplicationsService;
import kotlin.Pair;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.PathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/app")
public class AppController {

    Map<String, Long> aliasToLastCalledTime = new HashMap<>();
    @Autowired
    StudentApplicationsService studentService;

    @Autowired
    private PathMatcher pathMatcher;

    @Autowired
    private RestTemplate restTemplate;
    OkHttpClient client = new OkHttpClient().newBuilder()
            .build();

    private String getWildcardParam(HttpServletRequest request) {
        String patternAttribute = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        String mappingAttribute = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        return this.pathMatcher.extractPathWithinPattern(patternAttribute, mappingAttribute);
    }

    // create api to register applications (student-docker, appid, = store in database with port
    // apps (docker_image, appid, port)

    @RequestMapping(method = RequestMethod.GET, value = "/{alias}/**")
    public void getItem(HttpServletRequest request, @PathVariable String alias, HttpServletResponse response) throws IOException, InterruptedException {
        String wantedApp = alias;
        System.out.println("request for app:" + wantedApp);
        // check on database for the student of app
        // random student between 9000 - 20000
        // String student = "9001"; // get this from database according to appid
        StudentApplication studentApplication = studentService.getStudentApplicationByAlias(wantedApp);
        System.out.println(studentApplication);

        ////////

        String dockerImage = studentApplication.getDocker_image();
        try {
            forwardGetRequestToApp(request, response, studentApplication.getPort());
        } catch (Exception e) {
            // start docker image
//            String command1 = "sudo service docker start";
//            Process p1 = Runtime.getRuntime().exec(new String[]{"bash", "-c", command1});
//            String command = "curl --unix-socket /var/run/docker.sock -H \"Content-Type: application/json\"  -d '{\"Image\": \"redis\"}' " +
//                    "  -X POST http://localhost/v1.41/containers/create";
            String command = "curl --silent -XPOST --unix-socket /run/docker.sock -d '{\"Image\":\"nginx:latest\"}' -H 'Content-Type: application/json' http://localhost/containers/create?name=nginx";

            String p = executeShell(command);
            System.out.println(p);
//            java.util.Scanner s = new java.util.Scanner(p.getInputStream());
//            System.out.println(s.nextLine());
            // wait for 30 seconds
            TimeUnit.SECONDS.sleep(30);
            forwardGetRequestToApp(request, response, studentApplication.getPort());
        }

        // save the last timestamp for each application
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        long timestampToMinutes = TimeUnit.MILLISECONDS.toMinutes(timestamp.getTime());
        aliasToLastCalledTime.put(wantedApp, timestampToMinutes);

        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Timestamp currentTime = new Timestamp(System.currentTimeMillis());

                for (Map.Entry<String, Long> ts : aliasToLastCalledTime.entrySet()) {
                    if ((TimeUnit.MILLISECONDS.toMinutes(currentTime.getTime()) - ts.getValue()) >= 30) {
                        // kill docker that was not used for 30 minutes

                    }
                }

            }
        }, 0, 60 * 1000);

    }

    private void forwardGetRequestToApp(HttpServletRequest request, HttpServletResponse response, Integer port) throws IOException {
        String url = "http://localhost:" + port + "/" + this.getWildcardParam(request);
        //ResponseEntity res = this.restTemplate.getForEntity(url, String.class);
        Request.Builder builder = new Request.Builder()
                .url(url)
                .get();
        String h = null;
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            h = headerNames.nextElement();
            builder.addHeader(h, request.getHeader(h));
        }
        Response response1 = client.newCall(builder.build()).execute();

        response.setContentLength((int) response1.body().contentLength());
        byte[] buffer = new byte[10240];

        try (
                OutputStream output = response.getOutputStream();
        ) {
            for (int length = 0; (length = response1.body().byteStream().read(buffer)) > 0; ) {
                output.write(buffer, 0, length);
            }
        }
        Iterator<Pair<String, String>> h2 = response1.headers().iterator();
        while (h2.hasNext()) {
            Pair<String, String> h3 = h2.next();
            response.addHeader(h3.component1(), h3.component2());
        }
    }

    private String executeShell(String cmd) throws InterruptedException, IOException {
        String res = "";
        String line;
        OutputStream stdin;
        InputStream stderr;
        InputStream stdout;

        System.out.println("executing:\n" + cmd);
        Process process = Runtime.getRuntime().exec(cmd);

        stdin = process.getOutputStream();
        stderr = process.getErrorStream();
        stdout = process.getInputStream();

        line = "\n";
        stdin.write(line.getBytes());
        stdin.flush();

        stdin.write(line.getBytes());
        stdin.flush();

        stdin.close();

        BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
        while ((line = brCleanUp.readLine()) != null) {
            res += line + "\n";
            System.out.println(line);
        }
        brCleanUp.close();

        brCleanUp = new BufferedReader(new InputStreamReader(stderr));
        while ((line = brCleanUp.readLine()) != null) {
            System.out.println("Abnormal process termination" + line);
            throw new RuntimeException("process failed and: " + line);
        }
        brCleanUp.close();

        int exitValue = process.exitValue();
        if (exitValue > 0) {

            throw new RuntimeException("exit value: " + String.valueOf(exitValue));

        }
        return res;
    }

}

</code>```

i was excepting to see the docker img in my http port but it gives me an eror page insted

Body:
hello iam trying to build an heroku replacement when iam running a docker img from my application in java it works from my terminal but when iam trying to view my application on http it gives me an error page

show how it works in terminal gets the id and run the docker
showing the error message

the problem :

  ** String command = "curl --silent -XPOST --unix-socket /run/docker.sock -d '{\"Image\":\"nginx:latest\"}' -H 'Content-Type: application/json' http://localhost/containers/create?name=nginx";**

the code :

package com.handson.chatbot.controller;

import com.handson.chatbot.model.StudentApplication;
import com.handson.chatbot.repo.StudentApplicationsService;
import kotlin.Pair;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.PathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/app")
public class AppController {

    Map<String, Long> aliasToLastCalledTime = new HashMap<>();
    @Autowired
    StudentApplicationsService studentService;

    @Autowired
    private PathMatcher pathMatcher;

    @Autowired
    private RestTemplate restTemplate;
    OkHttpClient client = new OkHttpClient().newBuilder()
            .build();

    private String getWildcardParam(HttpServletRequest request) {
        String patternAttribute = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        String mappingAttribute = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        return this.pathMatcher.extractPathWithinPattern(patternAttribute, mappingAttribute);
    }

    // create api to register applications (student-docker, appid, = store in database with port
    // apps (docker_image, appid, port)

    @RequestMapping(method = RequestMethod.GET, value = "/{alias}/**")
    public void getItem(HttpServletRequest request, @PathVariable String alias, HttpServletResponse response) throws IOException, InterruptedException {
        String wantedApp = alias;
        System.out.println("request for app:" + wantedApp);
        // check on database for the student of app
        // random student between 9000 - 20000
        // String student = "9001"; // get this from database according to appid
        StudentApplication studentApplication = studentService.getStudentApplicationByAlias(wantedApp);
        System.out.println(studentApplication);

        ////////

        String dockerImage = studentApplication.getDocker_image();
        try {
            forwardGetRequestToApp(request, response, studentApplication.getPort());
        } catch (Exception e) {
            // start docker image
//            String command1 = "sudo service docker start";
//            Process p1 = Runtime.getRuntime().exec(new String[]{"bash", "-c", command1});
//            String command = "curl --unix-socket /var/run/docker.sock -H \"Content-Type: application/json\"  -d '{\"Image\": \"redis\"}' " +
//                    "  -X POST http://localhost/v1.41/containers/create";
            String command = "curl --silent -XPOST --unix-socket /run/docker.sock -d '{\"Image\":\"nginx:latest\"}' -H 'Content-Type: application/json' http://localhost/containers/create?name=nginx";

            String p = executeShell(command);
            System.out.println(p);
//            java.util.Scanner s = new java.util.Scanner(p.getInputStream());
//            System.out.println(s.nextLine());
            // wait for 30 seconds
            TimeUnit.SECONDS.sleep(30);
            forwardGetRequestToApp(request, response, studentApplication.getPort());
        }

        // save the last timestamp for each application
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        long timestampToMinutes = TimeUnit.MILLISECONDS.toMinutes(timestamp.getTime());
        aliasToLastCalledTime.put(wantedApp, timestampToMinutes);

        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Timestamp currentTime = new Timestamp(System.currentTimeMillis());

                for (Map.Entry<String, Long> ts : aliasToLastCalledTime.entrySet()) {
                    if ((TimeUnit.MILLISECONDS.toMinutes(currentTime.getTime()) - ts.getValue()) >= 30) {
                        // kill docker that was not used for 30 minutes

                    }
                }

            }
        }, 0, 60 * 1000);

    }

    private void forwardGetRequestToApp(HttpServletRequest request, HttpServletResponse response, Integer port) throws IOException {
        String url = "http://localhost:" + port + "/" + this.getWildcardParam(request);
        //ResponseEntity res = this.restTemplate.getForEntity(url, String.class);
        Request.Builder builder = new Request.Builder()
                .url(url)
                .get();
        String h = null;
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            h = headerNames.nextElement();
            builder.addHeader(h, request.getHeader(h));
        }
        Response response1 = client.newCall(builder.build()).execute();

        response.setContentLength((int) response1.body().contentLength());
        byte[] buffer = new byte[10240];

        try (
                OutputStream output = response.getOutputStream();
        ) {
            for (int length = 0; (length = response1.body().byteStream().read(buffer)) > 0; ) {
                output.write(buffer, 0, length);
            }
        }
        Iterator<Pair<String, String>> h2 = response1.headers().iterator();
        while (h2.hasNext()) {
            Pair<String, String> h3 = h2.next();
            response.addHeader(h3.component1(), h3.component2());
        }
    }

    private String executeShell(String cmd) throws InterruptedException, IOException {
        String res = "";
        String line;
        OutputStream stdin;
        InputStream stderr;
        InputStream stdout;

        System.out.println("executing:\n" + cmd);
        Process process = Runtime.getRuntime().exec(cmd);

        stdin = process.getOutputStream();
        stderr = process.getErrorStream();
        stdout = process.getInputStream();

        line = "\n";
        stdin.write(line.getBytes());
        stdin.flush();

        stdin.write(line.getBytes());
        stdin.flush();

        stdin.close();

        BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
        while ((line = brCleanUp.readLine()) != null) {
            res += line + "\n";
            System.out.println(line);
        }
        brCleanUp.close();

        brCleanUp = new BufferedReader(new InputStreamReader(stderr));
        while ((line = brCleanUp.readLine()) != null) {
            System.out.println("Abnormal process termination" + line);
            throw new RuntimeException("process failed and: " + line);
        }
        brCleanUp.close();

        int exitValue = process.exitValue();
        if (exitValue > 0) {

            throw new RuntimeException("exit value: " + String.valueOf(exitValue));

        }
        return res;
    }

}

i was excepting to see the docker img in my http port but it gives me an eror page insted


问:
/usr/bin/ld: cannot find /usr/local/include: file format not recognized
When i want to compile a program in Ubuntu by run the make command, i get the following error:

```<code>/usr/bin/ld: cannot find /usr/local/include: file format not recognized
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [Makefile:30: bin/DataSharingClient] Error 1
</code>```

the make file is:

```<code>CPP = /usr/bin/clang++
INCPATHS = /usr/include
CFLAGS = -g -Wall -O1 $(INCPATHS) -march=native -std=c++11 -pthread -maes -mpclmul
LDLIBS = -lssl -lcrypto -lntl -lgmp -lm -ldl
LDPATH = -L/usr/local/lib

BUILD = build
PROGS = bin

SRC = crypto.cpp connect.cpp aesstream.cpp mpc.cpp param.cpp
PROGNAMES = DataSharingClient GwasClient LogiRegClient GenerateKey

OBJPATHS = $(patsubst %.cpp,$(BUILD)/%.o, $(SRC))
TESTPATHS = $(addprefix $(PROGS)/, $(PROGNAMES))

all: $(OBJPATHS) $(TESTPATHS)

obj: $(OBJPATHS)

$(BUILD):
mkdir -p $(BUILD)

$(PROGS):
mkdir -p $(PROGS)

$(BUILD)/%.o: %.cpp \*.h | $(BUILD)
$(CPP) $(CFLAGS) -o $@ -c $\<

$(PROGS)/%: %.cpp $(OBJPATHS) $(PROGS)
$(CPP) $(CFLAGS) -o $@ $\< $(LDPATH) $(OBJPATHS) $(LDLIBS)

clean:
rm -rf $(BUILD) $(PROGS) \*\~
</code>```

what is the problem? how i can fix the error?

Body:
When i want to compile a program in Ubuntu by run the make command, i get the following error:

/usr/bin/ld: cannot find /usr/local/include: file format not recognized
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [Makefile:30: bin/DataSharingClient] Error 1

the make file is:

CPP = /usr/bin/clang++
INCPATHS = /usr/include
CFLAGS = -g -Wall -O1 $(INCPATHS) -march=native -std=c++11 -pthread -maes -mpclmul
LDLIBS = -lssl -lcrypto -lntl -lgmp -lm -ldl
LDPATH = -L/usr/local/lib

BUILD = build
PROGS = bin

SRC = crypto.cpp connect.cpp aesstream.cpp mpc.cpp param.cpp
PROGNAMES = DataSharingClient GwasClient LogiRegClient GenerateKey

OBJPATHS = $(patsubst %.cpp,$(BUILD)/%.o, $(SRC))
TESTPATHS = $(addprefix $(PROGS)/, $(PROGNAMES))

all: $(OBJPATHS) $(TESTPATHS)

obj: $(OBJPATHS)

$(BUILD):
mkdir -p $(BUILD)

$(PROGS):
mkdir -p $(PROGS)

$(BUILD)/%.o: %.cpp \*.h | $(BUILD)
$(CPP) $(CFLAGS) -o $@ -c $\<

$(PROGS)/%: %.cpp $(OBJPATHS) $(PROGS)
$(CPP) $(CFLAGS) -o $@ $\< $(LDPATH) $(OBJPATHS) $(LDLIBS)

clean:
rm -rf $(BUILD) $(PROGS) \*\~

what is the problem? how i can fix the error?


问:
AttributeError: 'Post' object has no attribute 'tags'
enter image description here
enter image description here

The error comes out like that when I run it in cmder, but I don't know if I should change the 26th line to a different way

I tried to rewrite every sentence to create a tag, but I got the same error


问:
Exception: Scala module 2.14.1 requires Jackson Databind version >= 2.14.0 and < 2.15.0 - Found jackson-databind version 2.13.2-1
I am getting the exception " Scala module 2.14.1 requires Jackson Databind version >= 2.14.0 and < 2.15.0 - Found jackson-databind version 2.13.2-1" even though I have upgraded the Jackson Databind version tp 2.14.1 in the build.gardle file? How to resolve this issue?

How to resolve this issue?


问:
Which methods for adding security to GCP App Engine
I have a project on GCP where there are:

1 API written in Node.js running on App Engine

1 Frontend written in Vue/nuxt running on App Engine that calls the API

I need to add security to API adding an API Key in the header of the caller.
I also need to invoke API endpoints directly from my local PC for testing and other purposes.

I've already implemented something similar in another project using GCP API Gateway and it works fine.
My pain is that in this new project the API has a lot of endpoints and we are adding more and more periodically. As far as I know, openapi configuration of the API Gateway needs specification for each individual endpoint and the maintenance of the API Gateway could be a bit frustrating in this case.

Is there a way to use API Gateway without specifying all the endpoints, but just adding the API key security for all?
Or is there another service authentication method that could be better that API GW?


问:
Running iOS on physical device from expo-cli
I am trying to run iOS on a physical device (iPhone 12 with iOS 16) and when running react-native run-ios --device OrderDevice I get following error.

```<code>Details:  (null) deviceType from #####-000B44A90CE1001E was NULL when -platform called.
Object:   <DTDKMobileDeviceToken: ##########>
Method:   -platform
Thread:   <NSThread: 0x6######5c180>{number = 2, name = (null)}
Please file a bug at https://feedbackassistant.apple.com with this warning message and any useful information you can provide.
** BUILD FAILED **
</code>```

With xcrun xctrace list devices I can see following list.

```<code>Carlos’s MacBook Pro (DBCC450D-C508-5A34-9104-#####)
OrderDevice (16.1) (#######-000B44A90CE1001E)

== Simulators ==
iPad (9th generation) Simulator (16.0) (A1BE92DD-BA33-4727-83EB-###########)
iPad Air (5th generation) Simulator (16.0) (EE341EFA-10C9-4388-B7AC-########)
iPad Pro (11-inch) (3rd generation) Simulator (16.0) (ED21E4AB-90F1-48CB-A2D0-########)
iPad Pro (12.9-inch) (5th generation) Simulator (16.0) (C7D3BA35-E429-45C7-B969-C2B9C3CC8536)
iPad mini (6th generation) Simulator (16.0) (FEFC6BC7-BF2B-49C4-84C1-############)
iPhone 12 Simulator (16.0) (84D2B658-25B0-####-8678-4881F6CDF71C)
iPhone 14 Simulator (16.0) (C8085FDC-EFA4-####-B3A6-796FFE7B8842)
iPhone 14 Plus Simulator (16.0) (22E05920-CD4D-####-8E69-FB7F78D6049A)
iPhone 14 Pro Simulator (16.0) (A4BC978D-5F10-4BDB-#####-32768D851141)
iPhone 14 Pro Max Simulator (16.0) (1B4E9233-C61A-4775-#####-04AD4A87210C)
iPhone 8 Simulator (16.0) (328871B7-3E1A-40C4-8893-######)
iPhone SE (3rd generation) Simulator (16.0) (4175625D-####-4CCB-9FFE-72FDE96726CE)
iPhone Xʀ Simulator (16.0) (76971FDA-7485-4A8F-######-33518A1A5B7E)
</code>```

I also tried to run with the udid instead but having the same problem. I read that could be happening because the device is locked but it happens when the device is unlocked too.

When I run on XCode I have no problems. No problems either when running on a simulator, only on the physical device through expo-cli.

I read it could be related to the Signing & Capabilities. I tried changing the Podfile to what I found here on this link, but finding same problem.

https://github.com/bitrise-steplib/steps-xcode-archive/issues/299

Body:
I am trying to run iOS on a physical device (iPhone 12 with iOS 16) and when running react-native run-ios --device OrderDevice I get following error.

Details:  (null) deviceType from #####-000B44A90CE1001E was NULL when -platform called.
Object:   <DTDKMobileDeviceToken: ##########>
Method:   -platform
Thread:   <NSThread: 0x6######5c180>{number = 2, name = (null)}
Please file a bug at https://feedbackassistant.apple.com with this warning message and any useful information you can provide.
** BUILD FAILED **

With xcrun xctrace list devices I can see following list.

Carlos’s MacBook Pro (DBCC450D-C508-5A34-9104-#####)
OrderDevice (16.1) (#######-000B44A90CE1001E)

== Simulators ==
iPad (9th generation) Simulator (16.0) (A1BE92DD-BA33-4727-83EB-###########)
iPad Air (5th generation) Simulator (16.0) (EE341EFA-10C9-4388-B7AC-########)
iPad Pro (11-inch) (3rd generation) Simulator (16.0) (ED21E4AB-90F1-48CB-A2D0-########)
iPad Pro (12.9-inch) (5th generation) Simulator (16.0) (C7D3BA35-E429-45C7-B969-C2B9C3CC8536)
iPad mini (6th generation) Simulator (16.0) (FEFC6BC7-BF2B-49C4-84C1-############)
iPhone 12 Simulator (16.0) (84D2B658-25B0-####-8678-4881F6CDF71C)
iPhone 14 Simulator (16.0) (C8085FDC-EFA4-####-B3A6-796FFE7B8842)
iPhone 14 Plus Simulator (16.0) (22E05920-CD4D-####-8E69-FB7F78D6049A)
iPhone 14 Pro Simulator (16.0) (A4BC978D-5F10-4BDB-#####-32768D851141)
iPhone 14 Pro Max Simulator (16.0) (1B4E9233-C61A-4775-#####-04AD4A87210C)
iPhone 8 Simulator (16.0) (328871B7-3E1A-40C4-8893-######)
iPhone SE (3rd generation) Simulator (16.0) (4175625D-####-4CCB-9FFE-72FDE96726CE)
iPhone Xʀ Simulator (16.0) (76971FDA-7485-4A8F-######-33518A1A5B7E)

I also tried to run with the udid instead but having the same problem. I read that could be happening because the device is locked but it happens when the device is unlocked too.

When I run on XCode I have no problems. No problems either when running on a simulator, only on the physical device through expo-cli.

I read it could be related to the Signing & Capabilities. I tried changing the Podfile to what I found here on this link, but finding same problem.

https://github.com/bitrise-steplib/steps-xcode-archive/issues/299


问:
Regenerating assembly code from AST and comparing with the initial assembly code
Consider that we have a binary file with assembly code. We want to go through this process (regardless of the fact that there may be a better alternative way, but the process itself is relevant to me as such):

Generating AST from this assembly code (Named "Assembly1")

Make some changes on AST; for example converting a "while" loop to the corresponding "for" one (or any other example).

Regenerating assembly code (Named "Assembly2") from this modified AST.

My question is, if we ignore the modified part, will the rest of Assembly1 be the same as Assembly2? In other words, can we be sure that the assembly code resulting from AST will always be the same and have a single generation method? In one sentence, I want to know that if we make changes on a binary through its corresponding AST, we can rest easy after regenerating the assembly code that the rest of the parts of the assembly code remain the same as before (except for the part that we changed or parts which are related to the changed section)?
Of course, we assume that all these operations take place on a specific system with a specific architecture, and we do not have any changes in the language or compiler.


问:
Crop PDF using TallComponents(PDFKIT.NET5)
I have a floorplan PDF with bounding box. What I am trying to do is crop PDF with this bounding box to get rid of white space around floorplan.

So the idea to go through all shapes and find min/max coordinates:

```<code>internal class Program
{
    static double minX = 1000000000;
    static double minY = 1000000000;
    static double maxX = 0;
    static double maxY = 0;

    static void Main(string[] args)
    {
        using (FileStream fileIn = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            var document = new Document(fileIn);
            var shapes = document.Pages[0].CreateShapes();

            ShapeAnalysys(shapes, new Matrix());

            var minPoint = new Tuple<double, double>(maxX, minY);
            var maxPoint = new Tuple<double, double>(minX, maxY);

            var cropRectangle = new System.Drawing.RectangleF(
                    (float)minPoint.Item1,
                    (float)minPoint.Item2,
                    (float)(maxPoint.Item1 - minPoint.Item1),
                    (float)(maxPoint.Item2 - minPoint.Item2));

            var croppedDocument = new Document();

            if (document.Pages[0].Orientation == TallComponents.PDF.Orientation.Rotate270)
            {
                shapes.Transform = new MatrixTransform(shapes.Transform).Rotate(-90);
                shapes.Transform = new MatrixTransform(shapes.Transform).Translate(-(float)minPoint.Item2, (float)minPoint.Item1);
                var page = new Page(cropRectangle.Height, cropRectangle.Width);
                page.VisualOverlay.Add(shapes);
                croppedDocument.Pages.Add(page);
            }

            using (var outFile = new FileStream(fileNameOutput , FileMode.Create, FileAccess.Write))
            {
                croppedDocument.Write(outFile);

            }
            Process.Start(fileName);
        }
    }

    static void ShapeAnalysys(Shape shape, Matrix transform)
    {
        if (shape is ContentShape)
        {
            var contentShape = (ContentShape)shape;
            var tr = contentShape.Transform;
            //Matrix newTransform = tr.CreateGdiMatrix();
            var mtr = tr.AsMatrixTransform;
            Matrix newTransform = new Matrix((float)mtr.ScaleX, (float)mtr.ShearY, (float)mtr.ShearX, (float)mtr.ScaleY, (float)mtr.OffsetX, (float)mtr.OffsetY);
            newTransform.Multiply(transform, System.Drawing.Drawing2D.MatrixOrder.Append);

            if (shape is FreeHandShape)
            {
                foreach (var path in ((FreeHandShape)shape).Paths)
                    ShapeAnalysys(path, transform);
            }
            else if (shape is ShapeCollection)
            {
                foreach (Shape s in (ShapeCollection)shape)
                    ShapeAnalysys(s, newTransform);
            }
        }
    }

    static void ShapeAnalysys(FreeHandPath path, Matrix transform)
    {
        foreach (var segment in path.Segments)
        {
            if (segment is FreeHandLineSegment)
            {
                var s = (FreeHandLineSegment)segment;
                System.Drawing.PointF[] points = { new System.Drawing.PointF((float)s.X1, (float)s.Y1) };
                transform.TransformPoints(points);

                if (points[0].X > maxX)
                    maxX = points[0].X;

                if (points[0].Y > maxY)
                    maxY = points[0].Y;

                if (points[0].X < minX)
                    minX = points[0].X;

                if (points[0].Y < minY)
                    minY = points[0].Y;
            }
        }
    }
}
</code>```

For .NET I tried couple times and results are the same, but for .Core with the same code trying to crop several times I have different crop results (for first time it actually correct, but after that I have different results).

Why this could happen?

Body:
I have a floorplan PDF with bounding box. What I am trying to do is crop PDF with this bounding box to get rid of white space around floorplan.

So the idea to go through all shapes and find min/max coordinates:

internal class Program
{
    static double minX = 1000000000;
    static double minY = 1000000000;
    static double maxX = 0;
    static double maxY = 0;

    static void Main(string[] args)
    {
        using (FileStream fileIn = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            var document = new Document(fileIn);
            var shapes = document.Pages[0].CreateShapes();

            ShapeAnalysys(shapes, new Matrix());

            var minPoint = new Tuple<double, double>(maxX, minY);
            var maxPoint = new Tuple<double, double>(minX, maxY);

            var cropRectangle = new System.Drawing.RectangleF(
                    (float)minPoint.Item1,
                    (float)minPoint.Item2,
                    (float)(maxPoint.Item1 - minPoint.Item1),
                    (float)(maxPoint.Item2 - minPoint.Item2));

            var croppedDocument = new Document();

            if (document.Pages[0].Orientation == TallComponents.PDF.Orientation.Rotate270)
            {
                shapes.Transform = new MatrixTransform(shapes.Transform).Rotate(-90);
                shapes.Transform = new MatrixTransform(shapes.Transform).Translate(-(float)minPoint.Item2, (float)minPoint.Item1);
                var page = new Page(cropRectangle.Height, cropRectangle.Width);
                page.VisualOverlay.Add(shapes);
                croppedDocument.Pages.Add(page);
            }

            using (var outFile = new FileStream(fileNameOutput , FileMode.Create, FileAccess.Write))
            {
                croppedDocument.Write(outFile);

            }
            Process.Start(fileName);
        }
    }

    static void ShapeAnalysys(Shape shape, Matrix transform)
    {
        if (shape is ContentShape)
        {
            var contentShape = (ContentShape)shape;
            var tr = contentShape.Transform;
            //Matrix newTransform = tr.CreateGdiMatrix();
            var mtr = tr.AsMatrixTransform;
            Matrix newTransform = new Matrix((float)mtr.ScaleX, (float)mtr.ShearY, (float)mtr.ShearX, (float)mtr.ScaleY, (float)mtr.OffsetX, (float)mtr.OffsetY);
            newTransform.Multiply(transform, System.Drawing.Drawing2D.MatrixOrder.Append);

            if (shape is FreeHandShape)
            {
                foreach (var path in ((FreeHandShape)shape).Paths)
                    ShapeAnalysys(path, transform);
            }
            else if (shape is ShapeCollection)
            {
                foreach (Shape s in (ShapeCollection)shape)
                    ShapeAnalysys(s, newTransform);
            }
        }
    }

    static void ShapeAnalysys(FreeHandPath path, Matrix transform)
    {
        foreach (var segment in path.Segments)
        {
            if (segment is FreeHandLineSegment)
            {
                var s = (FreeHandLineSegment)segment;
                System.Drawing.PointF[] points = { new System.Drawing.PointF((float)s.X1, (float)s.Y1) };
                transform.TransformPoints(points);

                if (points[0].X > maxX)
                    maxX = points[0].X;

                if (points[0].Y > maxY)
                    maxY = points[0].Y;

                if (points[0].X < minX)
                    minX = points[0].X;

                if (points[0].Y < minY)
                    minY = points[0].Y;
            }
        }
    }
}

For .NET I tried couple times and results are the same, but for .Core with the same code trying to crop several times I have different crop results (for first time it actually correct, but after that I have different results).

Why this could happen?


问:
Removing more than one view from NavigationStack is not animated
I noticed that removing more than 1 view from a NavigationStack (using .removeLast(k) on its NavigationPath, where k > 1) is not animated at all. I was expecting to see the previous view sliding right, revealing to root view.. but what I get instead is the previous view disappearing without any animation whatsoever. (however, the animation plays as expected when removing only 1 view from the stack (k = 1))

In the example below, the animation plays when the reset button is tapped from page 2, but it does not from page 3, 4 and so on

Any help would be appreciated! Thank you

import SwiftUI

struct ContentView: View {
    @State var path = NavigationPath()
    var body: some View {
        VStack {
            NavigationStack(path: $path) {
                Subview()
                    .navigationDestination(for: Int.self) { n in
                        Subview(n:n)
                    }
            }
            // reset button
            Button(action: onTap) {
                Text("RESET")
            }
            .buttonStyle(.borderedProminent)
        }
    }

    func onTap() {
        if !path.isEmpty {
            let n = path.count
            path.removeLast(n)
        }
    }
}

struct Subview: View {
    var n: Int = 1
    var body: some View {
        NavigationLink(value: n+1) {
            Text("go to page \(n+1)")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
```


问:
I am working on Azure Functions and trying to test by mocking my MongoDB. Help me to run my test successfully
Exception I am getting

Cannot instantiate @InjectMocks field named 'csoKpiBlobTriggerFunction' of type 'class com.stellantis.cso.kpi.function.CsoKpiBlobTriggerFunction'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : Cannot invoke "String.startsWith(String)" because "connectionString" is null

```<code>@Mock
MongoCollection mockCollection;

@Mock
MongoClient mongoClient;

@Mock
MongoDatabase database;

@InjectMocks
CsoKpiBlobTriggerFunction csoKpiBlobTriggerFunction;

@InjectMocks
ExecutionContextMock executionContext;

@SuppressWarnings("unchecked")
@Test
void TestRun() throws Exception {
    File file = new File("/src/test/resources/json/10Q3EG1421896.json");
    byte[] arr = new byte[(int)file.length()];

    Mockito.when(mongoClient.getDatabase(Mockito.anyString())).thenReturn(database);

    Mockito.when(database.getCollection(Mockito.anyString())).thenReturn(mockCollection);

    csoKpiBlobTriggerFunction.run(arr,"10Q3EG1421896.json",executionContext);
    //PowerMockito.whenNew(MongoClient.class).withArguments(Mockito.anyString()).thenReturn(mongoClient);
    //PowerMockito.whenNew(MongoClientURI.class).withArguments(Mockito.anyString(),Mockito.any()).thenReturn(Mockito.any());
    //PowerMockito.whenNew(ConnectionString.class).withArguments("mongodb://").thenReturn(Mockito.any());

}
</code>```
```<code></code>```

Body:
Exception I am getting

Cannot instantiate @InjectMocks field named 'csoKpiBlobTriggerFunction' of type 'class com.stellantis.cso.kpi.function.CsoKpiBlobTriggerFunction'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : Cannot invoke "String.startsWith(String)" because "connectionString" is null

@Mock
MongoCollection mockCollection;

@Mock
MongoClient mongoClient;

@Mock
MongoDatabase database;

@InjectMocks
CsoKpiBlobTriggerFunction csoKpiBlobTriggerFunction;

@InjectMocks
ExecutionContextMock executionContext;

@SuppressWarnings("unchecked")
@Test
void TestRun() throws Exception {
    File file = new File("/src/test/resources/json/10Q3EG1421896.json");
    byte[] arr = new byte[(int)file.length()];

    Mockito.when(mongoClient.getDatabase(Mockito.anyString())).thenReturn(database);

    Mockito.when(database.getCollection(Mockito.anyString())).thenReturn(mockCollection);

    csoKpiBlobTriggerFunction.run(arr,"10Q3EG1421896.json",executionContext);
    //PowerMockito.whenNew(MongoClient.class).withArguments(Mockito.anyString()).thenReturn(mongoClient);
    //PowerMockito.whenNew(MongoClientURI.class).withArguments(Mockito.anyString(),Mockito.any()).thenReturn(Mockito.any());
    //PowerMockito.whenNew(ConnectionString.class).withArguments("mongodb://").thenReturn(Mockito.any());

}


问:
Get column name based on count and range of another column
I want to show the name of this traffic signs underneath the plot with plt.xlabel(.....). For now I can only show the label of the images since it connected to that. Traffic sign plot with numbers

For example, the first traffic sign I want: "speed limit 40km/h. I have DataFrame column with the 12 different traffic signs The column

For example, if the traffic sign number is between 1 and 40 its a traffic sign of speed limit 15km/h. and For example number 160 has traffic sign speed limit 50km/h

How can I fix this? How do I make the link?

I tried to make a def function whereby I put the number in and get it with .label but didnt work.


问:
Can I generate SPARQL queries automatically from natural language statement in apache jena API?
I have built a domain specific ontology. And I need a framework over it where user asks a query in natural language and the system turns this query to the SPARQL query automatically. If somehow I extract named entities and query word from the natural language query  statement...  What are the possibilities to have a simple SPARQL query with it. Which tools and techniques might help me?

Note: I only have simple factoid questions right now... not the complicated ones.

I have domain specific ontology. And I need a framework over it where user asks a query in natural language and the system turns this query to the SPARQL query automatically. Can Apache jena API work for it?


问:
Identify or Ignore or Stop malicious files when copying files between Azure storage accounts using AZCopy
scenario
Source storage account[X] can store any type of files[may be malicious] which user uploads.
Target storage account[Y] is personal and protected by windows defender for cloud.
We are using azcopy in PS7 to transfer files between storage accounts.

Problem
When copying files[using AZCopy] from local user folder to target storage account[Y], malicious files were blocked and exception was thrown during copying. But same is not happening with malicious files copied from source azure storage account[X] to Target azure storage account[Y].

We tried copying files to VM from Source storage account[X] and again use AZCopy to copy files from VM to Target storage account[Y], But this approach is expensive in both cost and time.

Do I need to set any specific setting in Azure Target storage account[Y] to block malicious files?
Note: Windows Defender for cloud is enabled in Target storage account[Y]

Please share your suggestions.


问:
Verify invoking a private and static method with ArgumentCaptor
I have a private and static method in a class with private constructor:

```<code>    private static void foo(Obj1 obj1, Obj2 obj2)
    {
        //some implementation
    }
</code>```

I used reflection to invoke it since it is private in my test like that:

```<code>    Method ReflectionMethod = MyClass.class.getDeclaredMethod(
                "foo", Obj1.class, Obj2.class);
    ReflectionMethod.setAccessible(true);
    ReflectionMethod.invoke(null,obj1, obj2);
</code>```

I invoke foo three times with different parameters in my test and I need to capture its arguments to be sure they are modified in foo.

When I try to capture arguments like this, the size of the list of obj1s becomes 0.

```<code>    ArgumentCaptor<Obj1> obj1Capture = ArgumentCaptor.forClass(Obj1.class);
    ArgumentCaptor<Obj2> obj2Capture = ArgumentCaptor.forClass(Obj2.class);

    verifyPrivate(MyClass.class, times(3)).invoke("foo",
    obj1Capture.capture(), obj2Capture.capture());
    List<Obj1> obj1s = obj1Capture.getAllValues();
</code>```

The list obj1s' size should have been three.

I think I am in wrong way while verifying a private static method, because I did same things for a private non-static method and it worked.

I really need help.

P.S. I mustn't change access modifiers of the foo.
Thanks.

Body:
I have a private and static method in a class with private constructor:

    private static void foo(Obj1 obj1, Obj2 obj2)
    {
        //some implementation
    }

I used reflection to invoke it since it is private in my test like that:

    Method ReflectionMethod = MyClass.class.getDeclaredMethod(
                "foo", Obj1.class, Obj2.class);
    ReflectionMethod.setAccessible(true);
    ReflectionMethod.invoke(null,obj1, obj2);

I invoke foo three times with different parameters in my test and I need to capture its arguments to be sure they are modified in foo.

When I try to capture arguments like this, the size of the list of obj1s becomes 0.

    ArgumentCaptor<Obj1> obj1Capture = ArgumentCaptor.forClass(Obj1.class);
    ArgumentCaptor<Obj2> obj2Capture = ArgumentCaptor.forClass(Obj2.class);

    verifyPrivate(MyClass.class, times(3)).invoke("foo",
    obj1Capture.capture(), obj2Capture.capture());
    List<Obj1> obj1s = obj1Capture.getAllValues();

The list obj1s' size should have been three.

I think I am in wrong way while verifying a private static method, because I did same things for a private non-static method and it worked.

I really need help.

P.S. I mustn't change access modifiers of the foo.
Thanks.


问:
Can we execute a xquery file from a docker file?
I want to run these below jobs in a docker

Install and start MarkLogic in my local.

Create range index for System axes.

Create temporal axes.

Create unitemporal collection using the temporal axes.

Job no 1 is done.
For the other remaining jobs, I want my docker file to execute xqueries .
Is it possible to execute a xquery file inside a bash file ?


问:
iOS - Identifying and activating purchases made from the App Store
IAP (Subscriptions) can be purchased from the App Store through IAP Promotions or Offer Codes. In the case where the app is not installed yet, I was wondering how to activate the purchase afterwards.

If the subscription was activated through the App Store or an Offer Code was redeemed in the App Store, is it added to the receipt automatically? I guess so, otherwise I would have to restore the purchase, which I think is wrong.

Since I can not test this use cases from a sandbox account, would be very nice to know about the behaviour in advance. Thanks!


问:
Passing argument to a ReadP Parser in Haskell
I am trying to create a parser from scratch in Haskell. I have problems passing a string as an argument to a function that is already part of a do block in which the parsing occurs. Why does the following Minimal viable example code return [] and not 4 as expected.

```<code>import Data.Char
import Text.ParserCombinators.ReadP
import Control.Applicative ((<|>))

type Parser a = ReadP a

token :: Parser a -> Parser a
token combinator = (do spaces
                       combinator)

space :: Parser Char
space = satisfy isSpace

spaces :: Parser String
spaces = many space

parseString input = readP_to_S (do
                        e <- pExpr
                        token eof
                        return e) input

pExpr = (do
            pv <- pOpHelper
            spaces
            str <- string pv
            return str
        )

pOpHelper :: Parser String
pOpHelper = (do
        e1 <- munch isDigit
        return e1
        )
</code>```

I am of course interested in returning a processed version of whatever string pv returns. However I can't understand why the current setup wouldn't return anything besides [] on parseString "4" since calling just pOpHelper wihtout pExpr seems to work.

Edit

I think I have located the 'bug' to be part of the string function. I had a closer look at it here but I can't see from the documentation why it shouldn't work in the above. But the above code is narrowed down to the parts that produce the unintended outputs as specified.

EDIT EDIT
I have now narrowed the problem down even further. It has to do with how 'consumption' works for the parser. The problem is that if I give it parseString "4" the string pv expects the "4" that is returned by pv, but it will still be parsing the next characters on which munch isDigit is no longer satisfies. This means that it will only return [("4","")] rather than [] if the input is parseString "4 4", and only if the spaces has been added to the do-clause in pExpr.

But how can I work around this and avoid 'consuming' the string that I put as input. Is there a way to use look for instance, in the above documentation.

As pointed out in the comments below I am interested in transforming whatever is the input to pOpHelper and then passing its output to functions (in a recursion) that is part of the parent parser-function called. But how can I do it without consuming the input with pOpHelper first such that the following example would return str on input of "4":

```<code>pExpr = (do
            pv <- pOpHelper
            --spaces
            str <- string pv
            if str == "(4)" then return str -- do stuff!
            else pfail

        )

pOpHelper :: Parser String
pOpHelper = (do

        e1 <- munch isDigit
        return ( "(" ++ e1 ++ ")" )
        )
</code>```

Body:
I am trying to create a parser from scratch in Haskell. I have problems passing a string as an argument to a function that is already part of a do block in which the parsing occurs. Why does the following Minimal viable example code return [] and not 4 as expected.

import Data.Char
import Text.ParserCombinators.ReadP
import Control.Applicative ((<|>))

type Parser a = ReadP a

token :: Parser a -> Parser a
token combinator = (do spaces
                       combinator)

space :: Parser Char
space = satisfy isSpace

spaces :: Parser String
spaces = many space

parseString input = readP_to_S (do
                        e <- pExpr
                        token eof
                        return e) input

pExpr = (do
            pv <- pOpHelper
            spaces
            str <- string pv
            return str
        )

pOpHelper :: Parser String
pOpHelper = (do
        e1 <- munch isDigit
        return e1
        )

I am of course interested in returning a processed version of whatever string pv returns. However I can't understand why the current setup wouldn't return anything besides [] on parseString "4" since calling just pOpHelper wihtout pExpr seems to work.

Edit

I think I have located the 'bug' to be part of the string function. I had a closer look at it here but I can't see from the documentation why it shouldn't work in the above. But the above code is narrowed down to the parts that produce the unintended outputs as specified.

EDIT EDIT
I have now narrowed the problem down even further. It has to do with how 'consumption' works for the parser. The problem is that if I give it parseString "4" the string pv expects the "4" that is returned by pv, but it will still be parsing the next characters on which munch isDigit is no longer satisfies. This means that it will only return [("4","")] rather than [] if the input is parseString "4 4", and only if the spaces has been added to the do-clause in pExpr.

But how can I work around this and avoid 'consuming' the string that I put as input. Is there a way to use look for instance, in the above documentation.

As pointed out in the comments below I am interested in transforming whatever is the input to pOpHelper and then passing its output to functions (in a recursion) that is part of the parent parser-function called. But how can I do it without consuming the input with pOpHelper first such that the following example would return str on input of "4":

pExpr = (do
            pv <- pOpHelper
            --spaces
            str <- string pv
            if str == "(4)" then return str -- do stuff!
            else pfail

        )

pOpHelper :: Parser String
pOpHelper = (do

        e1 <- munch isDigit
        return ( "(" ++ e1 ++ ")" )
        )


问:
How to deploy Zookeeper on Kubernetes - Liveness probe failed "The list of enabled four letter word commands is : [[srvr]]"
Hello I try to deploy Zookeeper in Kubernetes with this yaml file:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: zookeeper-cluster-import-deployment
  namespace: mynamespace
  labels:
    name : zookeeper-cluster-import
    app : zookeeper-cluster-import
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: zookeeper-cluster-import
  template:
    metadata:
      labels:
        app: zookeeper-cluster-import
    spec:
      restartPolicy: Always
      containers:
      - name: zookeeper
        image: dockerbase_zookeeper:v01
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 2181
          name: zookeeper
        env:
          - name: ALLOW_ANONYMOUS_LOGIN
            value: "yes"
          - name: ZOO_4LW_COMMANDS_WHITELIST
            value: "ruok"
        livenessProbe:
             exec:
                command: ['/bin/bash', '-c', 'echo "ruok" | nc -w 2 localhost 2181 | grep imok']
             initialDelaySeconds: 60
             periodSeconds: 10
             timeoutSeconds: 5
             failureThreshold: 6
             successThreshold: 1
        readinessProbe:
             exec:
                command: ['/bin/bash', '-c', 'echo "ruok" | nc -w 2 localhost 2181 | grep imok']
             initialDelaySeconds: 120
             periodSeconds: 10
             timeoutSeconds: 5
             failureThreshold: 6
             successThreshold: 1
        resources:
          requests:
            cpu: 400m
            memory: 2Gi
          limits:
            cpu: 500m
            memory: 2Gi
        securityContext:
          allowPrivilegeEscalation: false
          privileged: false
          runAsGroup: 1000
          runAsUser: 1000
      imagePullSecrets:
      - name: secret-repos
      volumes:
      - name: pv-01
        persistentVolumeClaim:
          claimName: pv-claim-01
</code>```

But when I apply this yaml I have "Liveness probe failed" and in the pod logs I see at the end of the logs : The list of enabled four letter word commands is : [[srvr]]

I don't understand because in env I did :

```<code>      - name: ZOO_4LW_COMMANDS_WHITELIST
        value: "ruok"
</code>```

It is like the command is not recognized.

Body:
Hello I try to deploy Zookeeper in Kubernetes with this yaml file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: zookeeper-cluster-import-deployment
  namespace: mynamespace
  labels:
    name : zookeeper-cluster-import
    app : zookeeper-cluster-import
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: zookeeper-cluster-import
  template:
    metadata:
      labels:
        app: zookeeper-cluster-import
    spec:
      restartPolicy: Always
      containers:
      - name: zookeeper
        image: dockerbase_zookeeper:v01
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 2181
          name: zookeeper
        env:
          - name: ALLOW_ANONYMOUS_LOGIN
            value: "yes"
          - name: ZOO_4LW_COMMANDS_WHITELIST
            value: "ruok"
        livenessProbe:
             exec:
                command: ['/bin/bash', '-c', 'echo "ruok" | nc -w 2 localhost 2181 | grep imok']
             initialDelaySeconds: 60
             periodSeconds: 10
             timeoutSeconds: 5
             failureThreshold: 6
             successThreshold: 1
        readinessProbe:
             exec:
                command: ['/bin/bash', '-c', 'echo "ruok" | nc -w 2 localhost 2181 | grep imok']
             initialDelaySeconds: 120
             periodSeconds: 10
             timeoutSeconds: 5
             failureThreshold: 6
             successThreshold: 1
        resources:
          requests:
            cpu: 400m
            memory: 2Gi
          limits:
            cpu: 500m
            memory: 2Gi
        securityContext:
          allowPrivilegeEscalation: false
          privileged: false
          runAsGroup: 1000
          runAsUser: 1000
      imagePullSecrets:
      - name: secret-repos
      volumes:
      - name: pv-01
        persistentVolumeClaim:
          claimName: pv-claim-01

But when I apply this yaml I have "Liveness probe failed" and in the pod logs I see at the end of the logs : The list of enabled four letter word commands is : [[srvr]]

I don't understand because in env I did :

      - name: ZOO_4LW_COMMANDS_WHITELIST
        value: "ruok"

It is like the command is not recognized.


问:
Pass multiple parameter to route
I have a route like below.

```<code>Route::resource( 'mosque-build', 'MosqueBuildController' );
</code>```

My blade file code is like below.

```<code><form id="delete-form-{{ $collection->id }}" action="{{ route('admin.mosque-build.destroy',$collection->id,'target') }}" method="POST" style="display: none;">
   @csrf
   @method('DELETE')
</form>
</code>```

My controller function is like below.

```<code>public function destroy($id,$type)
    {
        if($type == 'target') {
            $target_collection = Targetcollection::find($id);
            $target_collection->delete();
            return redirect()->route( 'admin.mosque-build' );
        }
    }
</code>```

I am getting error local.ERROR: Too few arguments to function.

Title: Pass multiple parameter to route

Body:
I have a route like below.

Route::resource( 'mosque-build', 'MosqueBuildController' );

My blade file code is like below.

<form id="delete-form-{{ $collection->id }}" action="{{ route('admin.mosque-build.destroy',$collection->id,'target') }}" method="POST" style="display: none;">
   @csrf
   @method('DELETE')
</form>

My controller function is like below.

public function destroy($id,$type)
    {
        if($type == 'target') {
            $target_collection = Targetcollection::find($id);
            $target_collection->delete();
            return redirect()->route( 'admin.mosque-build' );
        }
    }

I am getting error local.ERROR: Too few arguments to function.


问:
HDP 2.6.5 : java.lang.ClassNotFoundException: com.mongodb.spark.sql.DefaultSource.DefaultSource
I'm using HDP 2.6.5 and when i want to save my data (get on a json file) to a mongoDB database i have this problem.

I'm using the sandbox.

My code :

```<code>#HDFS-Mongo Used to write the json file from HDFS to Mongo DB

from pyspark.sql import SparkSession

my_spark = SparkSession \
         .builder \
         .appName("testdb") \
         .config("spark.mongodb.input.uri", "mongodb://127.0.0.1/testdb.test1") \
         .config("spark.mongodb.output.uri", "mongodb://127.0.0.1/testdb.test1") \
         .getOrCreate()

df = my_spark.read.option("multiline", "true").json("hdfs://sandbox-hdp.hortonworks.com:8020/user/root/output2.json")

df.count()

df.printSchema()

df.write.format("com.mongodb.spark.sql.DefaultSource").mode("append").option("database","testdb").option("collection", "test1").save()
</code>```

The errors :

Traceback (most recent call last):                                                                                File "hdfs_mongo.py", line 19, in <module>                                                                                df.write.format("com.mongodb.spark.sql.DefaultSource").mode("append").option("database","testdb").option("collection", "test1").save()    File "/usr/local/lib/python3.6/site-packages/pyspark/sql/readwriter.py", line 738, in save                                                    self._jwrite.save()                                                                                File "/usr/local/lib/python3.6/site-packages/py4j/java_gateway.py", line 1322, in __call__                                                    answer, self.gateway_client, self.target_id, self.name)                                                                                File "/usr/local/lib/python3.6/site-packages/pyspark/sql/utils.py", line 111, in deco                                                         return f(*a, **kw)                                                                                File "/usr/local/lib/python3.6/site-packages/py4j/protocol.py", line 328, in get_return_value                                                 format(target_id, ".", name), value)                                                                                py4j.protocol.Py4JJavaError: An error occurred while calling o44.save.                                                                      : java.lang.ClassNotFoundException:                                                                                Failed to find data source: com.mongodb.spark.sql.DefaultSource. Please find packages at                                                    http://spark.apache.org/third-party-projects.html                                                                                at org.apache.spark.sql.errors.QueryExecutionErrors$.failedToFindDataSourceError(QueryExecutionErrors.scala:443)                            at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:670)                                            at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSourceV2(DataSource.scala:720)                                          at org.apache.spark.sql.DataFrameWriter.lookupV2Provider(DataFrameWriter.scala:852)                                                         at org.apache.spark.sql.DataFrameWriter.saveInternal(DataFrameWriter.scala:256)                                                             at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:247)                                                                     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)                                                                              at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)                                                            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)                                                    at java.lang.reflect.Method.invoke(Method.java:498)                                                                                at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)                                                                             at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)                                                                       at py4j.Gateway.invoke(Gateway.java:282)                                                                                at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)                                                                     at py4j.commands.CallCommand.execute(CallCommand.java:79)                                                                                at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)                                                             at py4j.ClientServerConnection.run(ClientServerConnection.java:106)                                                                         at java.lang.Thread.run(Thread.java:748)                                                                                Caused by: java.lang.ClassNotFoundException: com.mongodb.spark.sql.DefaultSource.DefaultSource                                                      at java.net.URLClassLoader.findClass(URLClassLoader.java:381)                                                                               at java.lang.ClassLoader.loadClass(ClassLoader.java:424)                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:357)                                                                                at org.apache.spark.sql.execution.datasources.DataSource$.$anonfun$lookupDataSource$5(DataSource.scala:656)                                 at scala.util.Try$.apply(Try.scala:213)                                                                                at org.apache.spark.sql.execution.datasources.DataSource$.$anonfun$lookupDataSource$4(DataSource.scala:656)                                 at scala.util.Failure.orElse(Try.scala:224)                                                                                at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:656)                                            ... 16 more

I already try to uninstall python and install again (python3.6), i use this code and run it but it don't works :

```<code>from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("myApp") \
.config("spark.mongodb.input.uri", "mongodb://xxx.xxx.xxx.xxx:27017/sample1.zips") \
.config("spark.mongodb.output.uri", "mongodb://xxx.xxx.xxx.xxx:27017/sample1.zips") \
.config('spark.jars.packages', 'org.mongodb.spark:mongo-spark-connector_2.11:2.3.2') \
.getOrCreate()

df = spark.read.format("com.mongodb.spark.sql.DefaultSource").load()
df.printSchema()
</code>```

Body:
I'm using HDP 2.6.5 and when i want to save my data (get on a json file) to a mongoDB database i have this problem.

I'm using the sandbox.

My code :

#HDFS-Mongo Used to write the json file from HDFS to Mongo DB

from pyspark.sql import SparkSession

my_spark = SparkSession \
         .builder \
         .appName("testdb") \
         .config("spark.mongodb.input.uri", "mongodb://127.0.0.1/testdb.test1") \
         .config("spark.mongodb.output.uri", "mongodb://127.0.0.1/testdb.test1") \
         .getOrCreate()

df = my_spark.read.option("multiline", "true").json("hdfs://sandbox-hdp.hortonworks.com:8020/user/root/output2.json")

df.count()

df.printSchema()

df.write.format("com.mongodb.spark.sql.DefaultSource").mode("append").option("database","testdb").option("collection", "test1").save()

The errors :

Traceback (most recent call last):                                                                                File "hdfs_mongo.py", line 19, in <module>                                                                                df.write.format("com.mongodb.spark.sql.DefaultSource").mode("append").option("database","testdb").option("collection", "test1").save()    File "/usr/local/lib/python3.6/site-packages/pyspark/sql/readwriter.py", line 738, in save                                                    self._jwrite.save()                                                                                File "/usr/local/lib/python3.6/site-packages/py4j/java_gateway.py", line 1322, in __call__                                                    answer, self.gateway_client, self.target_id, self.name)                                                                                File "/usr/local/lib/python3.6/site-packages/pyspark/sql/utils.py", line 111, in deco                                                         return f(*a, **kw)                                                                                File "/usr/local/lib/python3.6/site-packages/py4j/protocol.py", line 328, in get_return_value                                                 format(target_id, ".", name), value)                                                                                py4j.protocol.Py4JJavaError: An error occurred while calling o44.save.                                                                      : java.lang.ClassNotFoundException:                                                                                Failed to find data source: com.mongodb.spark.sql.DefaultSource. Please find packages at                                                    http://spark.apache.org/third-party-projects.html                                                                                at org.apache.spark.sql.errors.QueryExecutionErrors$.failedToFindDataSourceError(QueryExecutionErrors.scala:443)                            at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:670)                                            at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSourceV2(DataSource.scala:720)                                          at org.apache.spark.sql.DataFrameWriter.lookupV2Provider(DataFrameWriter.scala:852)                                                         at org.apache.spark.sql.DataFrameWriter.saveInternal(DataFrameWriter.scala:256)                                                             at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:247)                                                                     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)                                                                              at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)                                                            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)                                                    at java.lang.reflect.Method.invoke(Method.java:498)                                                                                at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)                                                                             at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)                                                                       at py4j.Gateway.invoke(Gateway.java:282)                                                                                at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)                                                                     at py4j.commands.CallCommand.execute(CallCommand.java:79)                                                                                at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)                                                             at py4j.ClientServerConnection.run(ClientServerConnection.java:106)                                                                         at java.lang.Thread.run(Thread.java:748)                                                                                Caused by: java.lang.ClassNotFoundException: com.mongodb.spark.sql.DefaultSource.DefaultSource                                                      at java.net.URLClassLoader.findClass(URLClassLoader.java:381)                                                                               at java.lang.ClassLoader.loadClass(ClassLoader.java:424)                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:357)                                                                                at org.apache.spark.sql.execution.datasources.DataSource$.$anonfun$lookupDataSource$5(DataSource.scala:656)                                 at scala.util.Try$.apply(Try.scala:213)                                                                                at org.apache.spark.sql.execution.datasources.DataSource$.$anonfun$lookupDataSource$4(DataSource.scala:656)                                 at scala.util.Failure.orElse(Try.scala:224)                                                                                at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:656)                                            ... 16 more

I already try to uninstall python and install again (python3.6), i use this code and run it but it don't works :

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("myApp") \
.config("spark.mongodb.input.uri", "mongodb://xxx.xxx.xxx.xxx:27017/sample1.zips") \
.config("spark.mongodb.output.uri", "mongodb://xxx.xxx.xxx.xxx:27017/sample1.zips") \
.config('spark.jars.packages', 'org.mongodb.spark:mongo-spark-connector_2.11:2.3.2') \
.getOrCreate()

df = spark.read.format("com.mongodb.spark.sql.DefaultSource").load()
df.printSchema()