问:
Not Showing sqlite data in iphone
I have two Tabitems, In first TabItems i have One NavigationViewController. Now When i am running this application it works great but while i am using the sqllite to fetch the data and show in to the tableview cell, it will get crash.
The Crash log is here:

```<code>    2011-08-18 14:19:08.204 iBountyHunter[201:207] Unresolved error Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x4d4e1a0 {metadata=<CFBasicHash 0x4d4d590 [0x1008400]>{type = immutable dict, count = 7,
entries =>
    2 : <CFString 0x4d4dc90 [0x1008400]>{contents = "NSStoreModelVersionIdentifiers"} = <CFArray 0x4d4dd60 [0x1008400]>{type = immutable, count = 0, values = ()}
    4 : <CFString 0x4d4dce0 [0x1008400]>{contents = "NSPersistenceFrameworkVersion"} = <CFNumber 0x4d4d7e0 [0x1008400]>{value = +248, type = kCFNumberSInt64Type}
    6 : <CFString 0x4d4dd10 [0x1008400]>{contents = "NSStoreModelVersionHashes"} = <CFBasicHash 0x4d4ddf0 [0x1008400]>{type = immutable dict, count = 1,
entries =>
    1 : <CFString 0x4d4dd80 [0x1008400]>{contents = "Fugitive"} = <CFData 0x4d4dda0 [0x1008400]>{length = 32, capacity = 32, bytes = 0xe33370b6e7ca3101f91d25951e8bfe01 ... 9e50237bb313d390}
}

    7 : <CFString 0xe248b0 [0x1008400]>{contents = "NSStoreUUID"} = <CFString 0x4d4db00 [0x1008400]>{contents = "E711F65F-3C5A-4889-872B-6541E4B2863A"}
    8 : <CFString 0xe24720 [0x1008400]>{contents = "NSStoreType"} = <CFString 0xe248f0 [0x1008400]>{contents = "SQLite"}
    9 : <CFString 0x4d4d970 [0x1008400]>{contents = "NSStoreModelVersionHashesVersion"} = <CFNumber 0x4d1e420 [0x1008400]>{value = +3, type = kCFNumberSInt32Type}
    10 : <CFString 0x4d4dd40 [0x1008400]>{contents = "_NSAutoVacuumLevel"} = <CFString 0x4d4de40 [0x1008400]>{contents = "2"}
}
, reason=The model used to open the store is incompatible with the one used to create the store}, {
    metadata =     {
        NSPersistenceFrameworkVersion = 248;
        NSStoreModelVersionHashes =         {
            Fugitive = <e33370b6 e7ca3101 f91d2595 1e8bfe01 3e7fb4de 6ef2a31d 9e50237b b313d390>;
        };
        NSStoreModelVersionHashesVersion = 3;
        NSStoreModelVersionIdentifiers =         (
        );
        NSStoreType = SQLite;
        NSStoreUUID = "E711F65F-3C5A-4889-872B-6541E4B2863A";
        "_NSAutoVacuumLevel" = 2;
    };
    reason = "The model used to open the store is incompatible with the one used to create the store";
}
</code>```

Please help me regarding this.
I dont know where the problem is. . .
Thanks in advance.

答: You changed the model. Just delete the app from your device / Simulator and try again.</p>

Title: Not Showing sqlite data in iphone

Body:
I have two Tabitems, In first TabItems i have One NavigationViewController. Now When i am running this application it works great but while i am using the sqllite to fetch the data and show in to the tableview cell, it will get crash.
The Crash log is here:

    2011-08-18 14:19:08.204 iBountyHunter[201:207] Unresolved error Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x4d4e1a0 {metadata=<CFBasicHash 0x4d4d590 [0x1008400]>{type = immutable dict, count = 7,
entries =>
    2 : <CFString 0x4d4dc90 [0x1008400]>{contents = "NSStoreModelVersionIdentifiers"} = <CFArray 0x4d4dd60 [0x1008400]>{type = immutable, count = 0, values = ()}
    4 : <CFString 0x4d4dce0 [0x1008400]>{contents = "NSPersistenceFrameworkVersion"} = <CFNumber 0x4d4d7e0 [0x1008400]>{value = +248, type = kCFNumberSInt64Type}
    6 : <CFString 0x4d4dd10 [0x1008400]>{contents = "NSStoreModelVersionHashes"} = <CFBasicHash 0x4d4ddf0 [0x1008400]>{type = immutable dict, count = 1,
entries =>
    1 : <CFString 0x4d4dd80 [0x1008400]>{contents = "Fugitive"} = <CFData 0x4d4dda0 [0x1008400]>{length = 32, capacity = 32, bytes = 0xe33370b6e7ca3101f91d25951e8bfe01 ... 9e50237bb313d390}
}

    7 : <CFString 0xe248b0 [0x1008400]>{contents = "NSStoreUUID"} = <CFString 0x4d4db00 [0x1008400]>{contents = "E711F65F-3C5A-4889-872B-6541E4B2863A"}
    8 : <CFString 0xe24720 [0x1008400]>{contents = "NSStoreType"} = <CFString 0xe248f0 [0x1008400]>{contents = "SQLite"}
    9 : <CFString 0x4d4d970 [0x1008400]>{contents = "NSStoreModelVersionHashesVersion"} = <CFNumber 0x4d1e420 [0x1008400]>{value = +3, type = kCFNumberSInt32Type}
    10 : <CFString 0x4d4dd40 [0x1008400]>{contents = "_NSAutoVacuumLevel"} = <CFString 0x4d4de40 [0x1008400]>{contents = "2"}
}
, reason=The model used to open the store is incompatible with the one used to create the store}, {
    metadata =     {
        NSPersistenceFrameworkVersion = 248;
        NSStoreModelVersionHashes =         {
            Fugitive = <e33370b6 e7ca3101 f91d2595 1e8bfe01 3e7fb4de 6ef2a31d 9e50237b b313d390>;
        };
        NSStoreModelVersionHashesVersion = 3;
        NSStoreModelVersionIdentifiers =         (
        );
        NSStoreType = SQLite;
        NSStoreUUID = "E711F65F-3C5A-4889-872B-6541E4B2863A";
        "_NSAutoVacuumLevel" = 2;
    };
    reason = "The model used to open the store is incompatible with the one used to create the store";
}

Please help me regarding this.
I dont know where the problem is. . .
Thanks in advance.


来源: stackexchange

问:
How to install terraform 0.12 in an alpine container with apk?
I want to add terraform version 0.12.21 in an alpine container, but I can only add 0.11.0 using apk.  If I try to add it as the desired version I get the following error:

```<code>/ # apk upgrade terraform==0.12.21-r0
OK: 192 MiB in 66 packages
/ # apk add terraform==0.12.21-r0
ERROR: unsatisfiable constraints:
  terraform-0.11.0-r0:
    breaks: world[terraform=0.12.21-r0]
</code>```

How do I fix this apk error?

答:
I'm documenting @SantaXL's comment as an answer just to make it easier to find in the future.

apk add terraform --repository=https://dl-cdn.alpinelinux.org/alpine/edge/community
```

This doesn't specifically add version 0.12, as per the question. Instead, it installs the latest version of terraform held in the Alpine repository. Note that this isn't necessarily the latest version of terraform, but it usually is.

ContentLicense: CC BY-SA 4.0

Body:
I want to add terraform version 0.12.21 in an alpine container, but I can only add 0.11.0 using apk.  If I try to add it as the desired version I get the following error:

/ # apk upgrade terraform==0.12.21-r0
OK: 192 MiB in 66 packages
/ # apk add terraform==0.12.21-r0
ERROR: unsatisfiable constraints:
  terraform-0.11.0-r0:
    breaks: world[terraform=0.12.21-r0]

How do I fix this apk error?

Body:
I'm documenting @SantaXL's comment as an answer just to make it easier to find in the future.

apk add terraform --repository=https://dl-cdn.alpinelinux.org/alpine/edge/community

This doesn't specifically add version 0.12, as per the question. Instead, it installs the latest version of terraform held in the Alpine repository. Note that this isn't necessarily the latest version of terraform, but it usually is.


问:
Is there a way to use a map function inside another map function?
I need to "traduce" the value inside a RDD using the value in another RDD
Something like this:

```<code>rdd1=sc.parallelize(['aa,bb','cc,dd','ee,aa'])
rdd2=sc.parallelize(['aa,1' , 'bb,2' , 'cc,3' , 'dd,4' , 'ee,5'])
result: ['1,2', '3,4' , '5,1']
</code>```

I've tried to use the following map function

```<code>      def mymap (c):
          src=c[0]
          dst=c[2]
          srcnew=rdd2.lookup(src)[0]
          dstnew=rdd2.lookup(dst)[0]
          return (srcnew,dstnew)

    rdd3=rdd1.map(mymap)
</code>```

But i get the following error:

It appears that you are attempting to broadcast an RDD or reference an RDD from an action or transformation. RDD transformations and actions can only be invoked by the driver, not inside of other transformations; for example, rdd1.map(lambda x: rdd2.values.count() * x) is invalid because the values transformation and count action cannot be performed inside of the rdd1.map transformation. For more information, see SPARK-5063.

The only solution i came up to is to use the collect() command but my dataset is huge. There is a way to call the value in a RDD in another RDD?

答:
If your dataset is huge you can use the Pair RDD Join operation and leverage the distributed computation of Spark RDD

In your case, you can lookup values with two joins as follows:

    val rdd1 = sc.parallelize(Seq("aa,bb", "cc,dd", "ee,ff"))
    val rdd2 = sc.parallelize(Seq("aa,1", "bb,2", "cc,3", "dd,4", "ee,5", "ff,6"))

    // Transform rdd to Key Value (KV) RDD (a.k.a Pair RDD)
    val rdd1KV: RDD[(String, String)] = rdd1.map(x => {
      val elements = x.split(",")
      (elements.head, elements.last)
    })
    val rdd2KV: RDD[(String, String)] = rdd2.map({ x =>
      val elements = x.split(",")
      (elements.head, elements.last)
    })

    /*
    Join and format the RDD as KV
    (ee,(ff,5)) => (ff,5)
    (aa,(bb,1)) => (bb,1)
    (cc,(dd,3)) => (dd,3)
     */
    val rddTmp = rdd1KV.join(rdd2KV).map(x => x._2)

    /* Second join and format the output
    (dd,(3,4)) => 3,4
    (ff,(5,6)) => 5,6
    (bb,(1,2)) => 1,2
     */
    rddTmp.join(rdd2KV).map(x => s"${x._2._1},${x._2._2}").foreach(println)
```

Body:
I need to "traduce" the value inside a RDD using the value in another RDD
Something like this:

rdd1=sc.parallelize(['aa,bb','cc,dd','ee,aa'])
rdd2=sc.parallelize(['aa,1' , 'bb,2' , 'cc,3' , 'dd,4' , 'ee,5'])
result: ['1,2', '3,4' , '5,1']

I've tried to use the following map function

      def mymap (c):
          src=c[0]
          dst=c[2]
          srcnew=rdd2.lookup(src)[0]
          dstnew=rdd2.lookup(dst)[0]
          return (srcnew,dstnew)

    rdd3=rdd1.map(mymap)

But i get the following error:

It appears that you are attempting to broadcast an RDD or reference an RDD from an action or transformation. RDD transformations and actions can only be invoked by the driver, not inside of other transformations; for example, rdd1.map(lambda x: rdd2.values.count() * x) is invalid because the values transformation and count action cannot be performed inside of the rdd1.map transformation. For more information, see SPARK-5063.

The only solution i came up to is to use the collect() command but my dataset is huge. There is a way to call the value in a RDD in another RDD?


问:
What does :-> mean in a haskell type specification
I've seen this in a few places:

```<code>data T = T a :-> b
</code>```

Notably in quickcheck we have

```<code>data Fun a b = Fun (a :-> b, b) (a -> b)
</code>```

What is the :-> and how does it differ from ->?

答:
Answered my own question: first saw this as

```<code>data Edge = i :-> i
</code>```

:-> is of course the constructor.

ContentLicense: CC BY-SA 3.0

Body:
I've seen this in a few places:

data T = T a :-> b

Notably in quickcheck we have

data Fun a b = Fun (a :-> b, b) (a -> b)

What is the :-> and how does it differ from ->?

Body:
Answered my own question: first saw this as

data Edge = i :-> i

:-> is of course the constructor.


问:
reload react component without reloading the page
Hi i have component and function "handleAvatarUpload". After onChange i want to reload only component not whole page. Now after change function reload whole page "only for tests". How can i reload only a component in the same place where now i put page reload?

```<code>
import { useUpdateSpecialistProfileMutation } from 'api-hooks/updateSpecialistProfile/updateSpecialistProfile.generated';
import { useS3DirectUpload } from 'hooks';
import { EditIcon } from 'icons';
import { FileTypeEnum } from 'interfaces';

import { AvatarEditIcon, ImageUpload } from './AvatarEdit.styled';

interface AvatarEditProps {
  onChange: (fileId: string) => void;
  userId?: string;
  avatarPictureFileId?: string;
  userName?: ReactNode;
  isDisabled?: boolean;
  fileId?: string;
}

const AvatarEdit = ({ onChange, userId, isDisabled }: AvatarEditProps) => {
  const { upload: uploadToS3 } = useS3DirectUpload();
  const [updateSpecialistProfile] = useUpdateSpecialistProfileMutation();

  const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files === null) {
      return;
    }
    const file = event.target.files[0];
    try {
      const uploadResult = await uploadToS3(file, FileTypeEnum.AvatarImage);
      await updateSpecialistProfile({
        variables: { input: { avatarPictureFileId: uploadResult.fileId }, userId },
      });
      onChange(uploadResult.fileId);
      window.location.reload();
    } catch (error) {
      console.warn(error);
    }
  };

  return (
    <ImageUpload>
      <label htmlFor="file-input">
        <AvatarEditIcon isDisabled={isDisabled}>
          <EditIcon />
        </AvatarEditIcon>
      </label>
      {isDisabled ? null : (
        <input
          accept="image/jpeg, image/png"
          id="file-input"
          onChange={handleAvatarUpload}
          type="file"
        />
      )}
    </ImageUpload>
  );
};

export default AvatarEdit;
</code>```

i have component where image state was stored but when i edit image by component above nothing happens.

```<code>
import { useFileUrlLazyQuery } from 'api-hooks/fileUrl/fileUrl.generated';

interface ImageProps {
  alt: string;
  fileId?: string;
  fileUrl?: string;
  className?: string;
}

const Image: React.FC<ImageProps> = ({ alt, fileId, fileUrl, className }) => {
  const [resolvedFileUrl, setResolvedFileUrl] = useState<string | undefined>(fileUrl);
  const [executeFileUrlLazyQuery, { data, loading }] = useFileUrlLazyQuery();

  useEffect(() => {
    if (!loading && fileId) {
      executeFileUrlLazyQuery({
        variables: {
          fileId,
        },
      });
    }
  }, [fileId, loading, executeFileUrlLazyQuery]);

  useEffect(() => {
    if (data && data.fileUrl) {
      setResolvedFileUrl(data.fileUrl);
    }
  }, [data]);

  if (resolvedFileUrl) {
    return null;
  }

  return <img alt={alt} className={className} src={resolvedFileUrl} />;
};

export default Image;
</code>```

答:
jsut  add  this  line  in your handleAvatarUpload  function

```<code>event.preventDefault();
</code>```

Body:
Hi i have component and function "handleAvatarUpload". After onChange i want to reload only component not whole page. Now after change function reload whole page "only for tests". How can i reload only a component in the same place where now i put page reload?

import { useUpdateSpecialistProfileMutation } from 'api-hooks/updateSpecialistProfile/updateSpecialistProfile.generated';
import { useS3DirectUpload } from 'hooks';
import { EditIcon } from 'icons';
import { FileTypeEnum } from 'interfaces';

import { AvatarEditIcon, ImageUpload } from './AvatarEdit.styled';

interface AvatarEditProps {
  onChange: (fileId: string) => void;
  userId?: string;
  avatarPictureFileId?: string;
  userName?: ReactNode;
  isDisabled?: boolean;
  fileId?: string;
}

const AvatarEdit = ({ onChange, userId, isDisabled }: AvatarEditProps) => {
  const { upload: uploadToS3 } = useS3DirectUpload();
  const [updateSpecialistProfile] = useUpdateSpecialistProfileMutation();

  const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files === null) {
      return;
    }
    const file = event.target.files[0];
    try {
      const uploadResult = await uploadToS3(file, FileTypeEnum.AvatarImage);
      await updateSpecialistProfile({
        variables: { input: { avatarPictureFileId: uploadResult.fileId }, userId },
      });
      onChange(uploadResult.fileId);
      window.location.reload();
    } catch (error) {
      console.warn(error);
    }
  };

  return (
    <ImageUpload>

        <AvatarEditIcon isDisabled={isDisabled}>
          <EditIcon />
        </AvatarEditIcon>

      {isDisabled ? null : (
        <input
          accept="image/jpeg, image/png"
          id="file-input"
          onChange={handleAvatarUpload}
          type="file"
        />
      )}
    </ImageUpload>
  );
};

export default AvatarEdit;

i have component where image state was stored but when i edit image by component above nothing happens.

import { useFileUrlLazyQuery } from 'api-hooks/fileUrl/fileUrl.generated';

interface ImageProps {
  alt: string;
  fileId?: string;
  fileUrl?: string;
  className?: string;
}

const Image: React.FC<ImageProps> = ({ alt, fileId, fileUrl, className }) => {
  const [resolvedFileUrl, setResolvedFileUrl] = useState<string | undefined>(fileUrl);
  const [executeFileUrlLazyQuery, { data, loading }] = useFileUrlLazyQuery();

  useEffect(() => {
    if (!loading && fileId) {
      executeFileUrlLazyQuery({
        variables: {
          fileId,
        },
      });
    }
  }, [fileId, loading, executeFileUrlLazyQuery]);

  useEffect(() => {
    if (data && data.fileUrl) {
      setResolvedFileUrl(data.fileUrl);
    }
  }, [data]);

  if (resolvedFileUrl) {
    return null;
  }

  return ;
};

export default Image;

Body:
jsut  add  this  line  in your handleAvatarUpload  function

event.preventDefault();


问:
Update model instance by another user but keep originator name unchanged in Django
I am learning and working on particular project, where I am allowing few users in the same model (initiator, reviewer and approver) to update model by using model.forms during the different state (initiation (draft), review and approval).
I have no issue on initiation stage as the originator is the same user who does model update. problem which I am struggling appears to happen during review and approval stages which makes my model updated however originator name is replaced by another user if I call:

```<code> def update_eq(request, pk):

         ___rest of the code___

            if eq.eq_status == 'Draft':
               form = EqForm(request.POST or None, instance=eq)
                    if form.is_valid():
                            eq.initiator = request.user
                            form.save()

        ___rest of the code___
</code>```

[Solution] Based on Willem's comment my updated view...

```<code>           elif eq.eq_status == 'Review':
              form = EqForm(request.POST or None, instance=eq)
                if form.is_valid():
                    # eq.initiator = request.user
                    form.save()

        ___rest of the code___
</code>```

However, once I change the state i.e. move to Review or Approve stage and making same update i.e. calling to save form, I am getting the initiator field updated with 'None' value.

Is there any way I allow non-initiator to update the model, but keep model original initiator as current initiator still?

答:
You are editing the Eq instance, so that means the instance is already created and thus the initiator does not need to be set/updated. You thus can remove the eq.initiator = request.user line(s) in your view:

```<code>def update_eq(request, pk):
    # rest of the code …
    if eq.eq_status == 'Draft':
        form = EqForm(request.POST or None, instance=eq)
        if form.is_valid():
            # <strong>no</strong> eq.initiator = request.user
            form.save()
            return redirect('<em>name-of-some-view</em>')
    # …</code>```

Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

Body:
I am learning and working on particular project, where I am allowing few users in the same model (initiator, reviewer and approver) to update model by using model.forms during the different state (initiation (draft), review and approval).
I have no issue on initiation stage as the originator is the same user who does model update. problem which I am struggling appears to happen during review and approval stages which makes my model updated however originator name is replaced by another user if I call:

 def update_eq(request, pk):

         ___rest of the code___

            if eq.eq_status == 'Draft':
               form = EqForm(request.POST or None, instance=eq)
                    if form.is_valid():
                            eq.initiator = request.user
                            form.save()

        ___rest of the code___

[Solution] Based on Willem's comment my updated view...

           elif eq.eq_status == 'Review':
              form = EqForm(request.POST or None, instance=eq)
                if form.is_valid():
                    # eq.initiator = request.user
                    form.save()

        ___rest of the code___

However, once I change the state i.e. move to Review or Approve stage and making same update i.e. calling to save form, I am getting the initiator field updated with 'None' value.

Is there any way I allow non-initiator to update the model, but keep model original initiator as current initiator still?

Body:
You are editing the Eq instance, so that means the instance is already created and thus the initiator does not need to be set/updated. You thus can remove the eq.initiator = request.user line(s) in your view:

def update_eq(request, pk):
    # rest of the code …
    if eq.eq_status == 'Draft':
        form = EqForm(request.POST or None, instance=eq)
        if form.is_valid():
            # no eq.initiator = request.user
            form.save()
            return redirect('name-of-some-view')
    # …

Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.


问:
How to build grouped tree array from flat array in php
i am trying to re format a array as tree, main array and child arrays should be grouped by "name" property.

my flat array is like

```<code>$flat = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 2, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 4, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 5, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 6, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 7, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 8, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 9, 'parent_id' => 7, 'name' => 'ch3-1'],
    ['id' => 10, 'parent_id' => 7, 'name' => 'ch3-1']
];
</code>```

i could build tree structure by

```<code>$tree = buildTree($flat, 'parent_id', 'id');

function buildTree(array $flatList)
{
    $grouped = [];
    foreach ($flatList as $node) {
        $grouped[$node['parent_id']][] = $node;
    }

    $fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
        foreach ($siblings as $k => $sibling) {
            $id = $sibling['id'];
            if (isset($grouped[$id])) {
                $sibling['children'] = $fnBuilder($grouped[$id]);
            }
            $siblings[$k] = $sibling;
        }
        return $siblings;
    };

    return $fnBuilder($grouped[0]);
}
</code>```

this works perfectly.

But what i want is build nested array should be grouped by it's "name" property.

so the final output should be like

```<code>[
  "root1": [{
      "id": 1,
      "parent_id": 0,
      "name": "root1",
      "children": [
        "ch-1": [{
            "id": 3,
            "parent_id": 1,
            "name": "ch-1",
            "children": [
              "ch-1-1": [{
                  "id": 5,
                  "parent_id": 3,
                  "name": "ch-1-1"
                },
                {
                  "id": 6,
                  "parent_id": 3,
                  "name": "ch-1-1"
                }
              ]
            ]
          },
          {
            "id": 4,
            "parent_id": 1,
            "name": "ch-1"
          }
        ]
      ]
    },
    {
      "id": 2,
      "parent_id": 0,
      "name": "root1"
    }
  ],
  "root2": [{
      "id": 7,
      "parent_id": 0,
      "name": "root2",
      "children": [
        "ch3-1": [{
            "id": 9,
            "parent_id": 7,
            "name": "ch3-1"
          },
          {
            "id": 10,
            "parent_id": 7,
            "name": "ch3-2"
          }
        ]
      ]
    },
    {
      "id": 8,
      "parent_id": 0,
      "name": "root2"
    }
  ]
]
</code>```

I have been stuck here almost for couple of days. Please help me to solve this problem.
Thank you.

答:
```<code>function buildTree(array $flat)
    {
        $grouped = [];
        foreach ($flat as $node) {
            $grouped[$node['parent_id']][] = $node;
        }

        $fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
            foreach ($siblings as $k => $sibling) {
                $id = $sibling['id'];
                if (isset($grouped[$id])) {
                    $sibling['children'] = $fnBuilder($grouped[$id]);
                }
                $siblings[$k] = $sibling;
            }
            return $siblings;
        };
        return $fnBuilder($grouped[0]);
    }

$tree = buildTree($flat);
</code>```

pass tree structure array to groupedTree();

```<code>$groupd = groupedTree($tree);

echo json_encode($groupd, JSON_PRETTY_PRINT);

function groupedTree($tree)
    {
        $groupedByFuncTableName = array_reduce($tree, function (array $accumulator, array $element) {
            if (isset($element['children'])) {
                $element['children'] = groupedTree($element['children']);
            }
            $accumulator[$element['name']][] = $element;

            return $accumulator;
        }, []);
        return $groupedByFuncTableName;
    }

</code>```

Body:
i am trying to re format a array as tree, main array and child arrays should be grouped by "name" property.

my flat array is like

$flat = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 2, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 4, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 5, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 6, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 7, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 8, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 9, 'parent_id' => 7, 'name' => 'ch3-1'],
    ['id' => 10, 'parent_id' => 7, 'name' => 'ch3-1']
];

i could build tree structure by

$tree = buildTree($flat, 'parent_id', 'id');

function buildTree(array $flatList)
{
    $grouped = [];
    foreach ($flatList as $node) {
        $grouped[$node['parent_id']][] = $node;
    }

    $fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
        foreach ($siblings as $k => $sibling) {
            $id = $sibling['id'];
            if (isset($grouped[$id])) {
                $sibling['children'] = $fnBuilder($grouped[$id]);
            }
            $siblings[$k] = $sibling;
        }
        return $siblings;
    };

    return $fnBuilder($grouped[0]);
}

this works perfectly.

But what i want is build nested array should be grouped by it's "name" property.

so the final output should be like

[
  "root1": [{
      "id": 1,
      "parent_id": 0,
      "name": "root1",
      "children": [
        "ch-1": [{
            "id": 3,
            "parent_id": 1,
            "name": "ch-1",
            "children": [
              "ch-1-1": [{
                  "id": 5,
                  "parent_id": 3,
                  "name": "ch-1-1"
                },
                {
                  "id": 6,
                  "parent_id": 3,
                  "name": "ch-1-1"
                }
              ]
            ]
          },
          {
            "id": 4,
            "parent_id": 1,
            "name": "ch-1"
          }
        ]
      ]
    },
    {
      "id": 2,
      "parent_id": 0,
      "name": "root1"
    }
  ],
  "root2": [{
      "id": 7,
      "parent_id": 0,
      "name": "root2",
      "children": [
        "ch3-1": [{
            "id": 9,
            "parent_id": 7,
            "name": "ch3-1"
          },
          {
            "id": 10,
            "parent_id": 7,
            "name": "ch3-2"
          }
        ]
      ]
    },
    {
      "id": 8,
      "parent_id": 0,
      "name": "root2"
    }
  ]
]

I have been stuck here almost for couple of days. Please help me to solve this problem.
Thank you.

Body:
function buildTree(array $flat)
    {
        $grouped = [];
        foreach ($flat as $node) {
            $grouped[$node['parent_id']][] = $node;
        }

        $fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
            foreach ($siblings as $k => $sibling) {
                $id = $sibling['id'];
                if (isset($grouped[$id])) {
                    $sibling['children'] = $fnBuilder($grouped[$id]);
                }
                $siblings[$k] = $sibling;
            }
            return $siblings;
        };
        return $fnBuilder($grouped[0]);
    }

$tree = buildTree($flat);

pass tree structure array to groupedTree();

$groupd = groupedTree($tree);

echo json_encode($groupd, JSON_PRETTY_PRINT);

function groupedTree($tree)
    {
        $groupedByFuncTableName = array_reduce($tree, function (array $accumulator, array $element) {
            if (isset($element['children'])) {
                $element['children'] = groupedTree($element['children']);
            }
            $accumulator[$element['name']][] = $element;

            return $accumulator;
        }, []);
        return $groupedByFuncTableName;
    }


问:
Resize an Array while keeping current elements in Java?
I have searched for a way to resize an array in Java, but I could not find ways of resizing the array while keeping the current elements.

I found for example code like int[] newImage = new int[newWidth];, but this deletes the elements stored before.

My code would basically do this: whenever  a new element is added, the array largens by 1. I think this could be done with dynamic programming, but I'm, not sure how to implement it.

答: We can't do that using array datatype. Instead use a growable array which is arrayList in Java.</p>


问:
MinGW trying to use cmd.exe from CMake Makefiles
I'm trying to build cuneiform under Windows. I use CMake to generate the build and select the MinGW Makefiles option.

Internally the Makefiles have DOS C:\pathname style paths rather than unix style and SHELL is set to cmd.exe (I note that MinGW's bin dir has a cmd script but no cmd.exe) rather than bash or sh.

I start bash by double clicking on C:\MinGWzmsys\1.0\bin\bash.exe. When I then try to run make it says:

```<code>bash.exe"-3.1$ cd /c/cuneiform/build/
bash.exe"-3.1$ make
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
c:\cuneiform\build>
</code>```

I then have to type exit three times to get back into bash! Why?

I've tried to generate Makefiles that use unix style paths and call sh but can't get CMake to do that for some reason.

Ideally should I be trying this from within bash or DOS? If I try from DOS (after setting a minimal path to path=C:\MinGW\msys\1.0\bin;C:\Windows\System32) make dies in a similar fashion.

I normally write C++ under HP-UX or Java under Windows, so MinGW and CMake are all new to me, as I'm sure you can tell.

答:
Converting my comment into answer as requested.  Since different CMake generators produce different (e.g. syntax-wise) native build systems, in your case, there are basically two options:

cmake ... -G "MSYS Makefiles" ... && make (e.g. when using MSYS2)

cmake ... -G "MinGW Makefiles" ... && mingw32-make

Body:
I'm trying to build cuneiform under Windows. I use CMake to generate the build and select the MinGW Makefiles option.

Internally the Makefiles have DOS C:\pathname style paths rather than unix style and SHELL is set to cmd.exe (I note that MinGW's bin dir has a cmd script but no cmd.exe) rather than bash or sh.

I start bash by double clicking on C:\MinGWzmsys\1.0\bin\bash.exe. When I then try to run make it says:

bash.exe"-3.1$ cd /c/cuneiform/build/
bash.exe"-3.1$ make
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
c:\cuneiform\build>

I then have to type exit three times to get back into bash! Why?

I've tried to generate Makefiles that use unix style paths and call sh but can't get CMake to do that for some reason.

Ideally should I be trying this from within bash or DOS? If I try from DOS (after setting a minimal path to path=C:\MinGW\msys\1.0\bin;C:\Windows\System32) make dies in a similar fashion.

I normally write C++ under HP-UX or Java under Windows, so MinGW and CMake are all new to me, as I'm sure you can tell.


问:
ASP.NET Storing global variables - accessible from every page
I am building a large application and I ususally use a simple session to store private  global information however as the application could be rather large I belive this could be a problem due to the amount of memory sessions it could have.

Is there a better way to store such variables?

For example, when the user logs in I want to store data about that user and display it where needed without having to query the database each time.

答:
Definitely use cookies for this. The best approach is to make yourself a cookies wrapper class that will do all the heavy lifting for you - checking if cookie is null, accessing the httpcontext, etc. No need to mess up your code with all that; just abstract it all out into cookies.cs or .vb.

```<code>SetCookieValue(someValue, cookieName); //there will be some expiration concerns here as well

myValue = GetCookieValue(cookieName);
</code>```

Christian Weiss has a good strategy.

OwnerDisplayName: HenryH

LastEditorDisplayName: Rich B

ContentLicense: CC BY-SA 2.5

Body:
Definitely use cookies for this. The best approach is to make yourself a cookies wrapper class that will do all the heavy lifting for you - checking if cookie is null, accessing the httpcontext, etc. No need to mess up your code with all that; just abstract it all out into cookies.cs or .vb.

SetCookieValue(someValue, cookieName); //there will be some expiration concerns here as well

myValue = GetCookieValue(cookieName);

Christian Weiss has a good strategy.

OwnerDisplayName: Philoushka


问:
selecting second string point using js substring
i want to select a sting from the long para. it has number of dot('.')s. i want to trim the word from the second one, is it any way to do this?

example

```<code>var name = "one.two.three";
name.substring(0,name.indexOf('.'))
name.substring(0,name.lastIndexOf('.'))
</code>```

from above trimming in case if i use indexOf it gives first word (one), if i use lastIndex of it gives the word (three), but i need to select the second one, to get value as 'second'

how can i trim this using indexOf method? or to select multicombination strings like one.three or one.two, or two.three?

thanks in advance!

答:
```<code>var name="one.two.three";
var result=name.split(".").slice(0,2).join(".");
</code>```

Example:

```<code>"".split(".").slice(0,2).join(".") // return ""
"one".split(".").slice(0,2).join(".") // return "one"
"one.two".split(".").slice(0,2).join(".") // return "one.two"
"one.two.three".split(".").slice(0,2).join(".") // return "one.two"
"one.two.three.four.five".split(".").slice(0,2).join(".") // return "one.two"
</code>```

Body:
i want to select a sting from the long para. it has number of dot('.')s. i want to trim the word from the second one, is it any way to do this?

example

var name = "one.two.three";
name.substring(0,name.indexOf('.'))
name.substring(0,name.lastIndexOf('.'))

from above trimming in case if i use indexOf it gives first word (one), if i use lastIndex of it gives the word (three), but i need to select the second one, to get value as 'second'

how can i trim this using indexOf method? or to select multicombination strings like one.three or one.two, or two.three?

thanks in advance!

Body:
var name="one.two.three";
var result=name.split(".").slice(0,2).join(".");

Example:

"".split(".").slice(0,2).join(".") // return ""
"one".split(".").slice(0,2).join(".") // return "one"
"one.two".split(".").slice(0,2).join(".") // return "one.two"
"one.two.three".split(".").slice(0,2).join(".") // return "one.two"
"one.two.three.four.five".split(".").slice(0,2).join(".") // return "one.two"


问:
Excel file still open when console application running
I have a console application that takes a web service response and outputs the properties to a excel file using closedxml. Whenever I create the excel file, if the console application is still running it won't let me open the file. I'm not sure where I am going wrong as I do have a using for the method that creates the excel file. Could another part of the code be holding the file open? I have added the excel create method.</p>
```<code>static readonly XLWorkbook wbook = new XLWorkbook();

public void ExcelCreate(FixedCall[] fix, string fileName)
        {
            using (wbook)
            {
                int col = 1;
                var ws = wbook.Worksheets.Add("Sheet1");
                foreach (var propertyInfo in from propertyInfo in typeof(FixedCall).GetProperties()
                                             where !propertyInfo.Name.Contains("ExtensionData")
                                             select propertyInfo)
                {
                    int row = 1;
                    ws.Cell(row++, col).Value = propertyInfo.Name;

                    for (int i = 0; i < fix.Length; i++)
                    {
                        ws.Cell(row++, col).Value = propertyInfo.GetValue(fix[i]);
                    }

                    col++;
                }

                wbook.SaveAs(File.Create(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"{fileName}.xlsx")));
            }
        }
</code>```

答:
I recommend a pattern of:

```<code>using(var wbook = new XLWorkBook()){

  ...
  var fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"{fileName}.xlsx");
  wbook.SaveAs(fullPath);
}
</code>```

By providing just the file path, you aren't making yourself potentially responsible for closing/disposing a file stream; it's handed off to ClosedXml and I'm sure they will tidy up during the dispose if not before..

Body:
I have a console application that takes a web service response and outputs the properties to a excel file using closedxml. Whenever I create the excel file, if the console application is still running it won't let me open the file. I'm not sure where I am going wrong as I do have a using for the method that creates the excel file. Could another part of the code be holding the file open? I have added the excel create method.

static readonly XLWorkbook wbook = new XLWorkbook();

public void ExcelCreate(FixedCall[] fix, string fileName)
        {
            using (wbook)
            {
                int col = 1;
                var ws = wbook.Worksheets.Add("Sheet1");
                foreach (var propertyInfo in from propertyInfo in typeof(FixedCall).GetProperties()
                                             where !propertyInfo.Name.Contains("ExtensionData")
                                             select propertyInfo)
                {
                    int row = 1;
                    ws.Cell(row++, col).Value = propertyInfo.Name;

                    for (int i = 0; i < fix.Length; i++)
                    {
                        ws.Cell(row++, col).Value = propertyInfo.GetValue(fix[i]);
                    }

                    col++;
                }

                wbook.SaveAs(File.Create(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"{fileName}.xlsx")));
            }
        }

Body:
I recommend a pattern of:

using(var wbook = new XLWorkBook()){

  ...
  var fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"{fileName}.xlsx");
  wbook.SaveAs(fullPath);
}

By providing just the file path, you aren't making yourself potentially responsible for closing/disposing a file stream; it's handed off to ClosedXml and I'm sure they will tidy up during the dispose if not before..


问:
How to pass custom values to identityserver4 with oauth?
Our application is tenant based and we want to pass an id to the ProfileService of IdentityServer4. How is it possible to pass a custom value to profileservice coming from the first request?

https://localhost:44390/connect/authorize?redirect_uri=http://localhost:8100/auth/callback&client_id=client.id&response_type=code&state=Ou3ZXnwaKM&scope=openid email offline_access&userId=08d9e62e-c6ab-4555-8820-3ba9b3e80752&code_challenge=rF2DzrNUpzAdVi-XQV1DIq84mTaAnjZLpaWwcULt8zk&code_challenge_method=S256

The userId is not accessible in the profileservice.

答:
Authorization request has predefined structure. IdentityServer is a certified OpenId Connect protocol implementation, so you can't introduce any custom parameter you want.

According to the spec the only two "free" parameters are the state which is used by clients and should be sent back with response as it is, and acr_values which is specially aimed for sending additional parameters to the server.

So you just add &acr_values=userId:08d9e62e-c6ab-4555-8820-3ba9b3e80752 to your authorization request and the value is accessible at IdentityServer. Moreover you mentioned tenant and IdentityServer has advanced support for the tenant acr_value. Just provide &acr_values=tenant:DevPlayground and the value will be accessible as

IIdentityServerInteractionService.GetAuthorizationContextAsync(returnUrl).Tenant;
```

In general you can pass as many acr_values as you want separating them with spaces: &acr_values=userId:08d9e62e-c6ab-4555-8820-3ba9b3e80752 tenant:DevPlayground

Body:
Authorization request has predefined structure. IdentityServer is a certified OpenId Connect protocol implementation, so you can't introduce any custom parameter you want.

According to the spec the only two "free" parameters are the state which is used by clients and should be sent back with response as it is, and acr_values which is specially aimed for sending additional parameters to the server.

So you just add &acr_values=userId:08d9e62e-c6ab-4555-8820-3ba9b3e80752 to your authorization request and the value is accessible at IdentityServer. Moreover you mentioned tenant and IdentityServer has advanced support for the tenant acr_value. Just provide &acr_values=tenant:DevPlayground and the value will be accessible as

IIdentityServerInteractionService.GetAuthorizationContextAsync(returnUrl).Tenant;

In general you can pass as many acr_values as you want separating them with spaces: &acr_values=userId:08d9e62e-c6ab-4555-8820-3ba9b3e80752 tenant:DevPlayground


答:
Issue was caused by

wbook.SaveAs(File.Create(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"{fileName}.xlsx")));

Changing to:
 wbook.SaveAs(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"{fileName}.xlsx"));

Also removing the static field and adding as part of the using block  using (var wbook = new XLWorkbook()) resolved the problem.

There appeared to be a conflict between File and ClosedXml on what was handling the excel doc.

Title: Excel file still open when console application running


问:
Need to add similar customer into array after performing groupBy but with a limit per customer
I had asked a similar question yesterday and got a correct answer, but today I faced more issues.
So here is the new problem statement.
I am fetching customer contacts from salesforce which are coming as an array of objects as shown below.

Input Payload:

```<code>[
    {
        "customerID": 1,
        "customerName": "Jonhn1"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn2"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn3"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn4"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn5"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn6"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn7"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn8"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn9"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn10"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn11"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn12"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn13"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn14"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn15"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn16"
    },
    {
        "customerID": 6,
        "customerName": "Jonhn17"
    },
    {
        "customerID": 7,
        "customerName": "Jonhn17"
    }
]
</code>```

I need the output to be an array of arrays, each sub-array should have all the customer details of at most three different customers.
I got the solution till the above statement as show below

```<code>%dw 2.0
output application/json
import * from dw::core::Arrays
---
payload groupBy $.customerID pluck $ divideBy 3 map((flatten($)))
</code>```

Now the main problem,
We have to put a limit on the number of customers in an array. For example in the given input payload customer with id "1" came more than 4 (four) times, then this customer should be in a different array ( means a separate array of customer "1" e.g an array for five records) this can happen to any other customer as well.

So we have to check if a customer is repeating more than 4 times then make a separate array for that type of customer else combine it with other customers as required earlier

Expected output:

```<code>[
    [
        {
            "customerID": 1,
            "customerName": "Jonhn1"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn2"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn3"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn4"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn5"
        }
    ],
    [
        {
            "customerID": 2,
            "customerName": "Jonhn6"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn7"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn8"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn9"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn10"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn11"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn12"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn13"
        }
    ],
    [
        {
            "customerID": 5,
            "customerName": "Jonhn14"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn15"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn16"
        },
        {
            "customerID": 6,
            "customerName": "Jonhn17"
        },
        {
            "customerID": 7,
            "customerName": "Jonhn18"
        }
    ]
]
</code>```

答:
I was about to post the answer but Karthik posted, But below is the correct code that @dheerajkain is asking

If any customer came more than four times (e.g., 6 or 7 soon), then a separate array is required for that customer?

Also, as you mentioned in the comments, there is no sizing limit if one array has three customers and each customer less than four times (each customer less than or equal to 4 times)?

if it is, then try the below code:

```<code>%dw 2.0
import * from dw::core::Arrays
output application/json
var customer = payload groupBy $.customerID pluck $
---
flatten(customer map
    (if (sizeOf($)>4)
          [flatten($ divideBy 5 map(flatten($)))]
            else
    (customer filter (sizeOf ($)< 5) divideBy 3 map (flatten ($)))
    ) distinctBy $)
</code>```

Body:
I had asked a similar question yesterday and got a correct answer, but today I faced more issues.
So here is the new problem statement.
I am fetching customer contacts from salesforce which are coming as an array of objects as shown below.

Input Payload:

[
    {
        "customerID": 1,
        "customerName": "Jonhn1"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn2"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn3"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn4"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn5"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn6"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn7"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn8"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn9"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn10"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn11"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn12"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn13"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn14"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn15"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn16"
    },
    {
        "customerID": 6,
        "customerName": "Jonhn17"
    },
    {
        "customerID": 7,
        "customerName": "Jonhn17"
    }
]

I need the output to be an array of arrays, each sub-array should have all the customer details of at most three different customers.
I got the solution till the above statement as show below

%dw 2.0
output application/json
import * from dw::core::Arrays
---
payload groupBy $.customerID pluck $ divideBy 3 map((flatten($)))

Now the main problem,
We have to put a limit on the number of customers in an array. For example in the given input payload customer with id "1" came more than 4 (four) times, then this customer should be in a different array ( means a separate array of customer "1" e.g an array for five records) this can happen to any other customer as well.

So we have to check if a customer is repeating more than 4 times then make a separate array for that type of customer else combine it with other customers as required earlier

Expected output:

[
    [
        {
            "customerID": 1,
            "customerName": "Jonhn1"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn2"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn3"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn4"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn5"
        }
    ],
    [
        {
            "customerID": 2,
            "customerName": "Jonhn6"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn7"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn8"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn9"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn10"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn11"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn12"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn13"
        }
    ],
    [
        {
            "customerID": 5,
            "customerName": "Jonhn14"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn15"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn16"
        },
        {
            "customerID": 6,
            "customerName": "Jonhn17"
        },
        {
            "customerID": 7,
            "customerName": "Jonhn18"
        }
    ]
]

Body:
I was about to post the answer but Karthik posted, But below is the correct code that @dheerajkain is asking

If any customer came more than four times (e.g., 6 or 7 soon), then a separate array is required for that customer?

Also, as you mentioned in the comments, there is no sizing limit if one array has three customers and each customer less than four times (each customer less than or equal to 4 times)?

if it is, then try the below code:

%dw 2.0
import * from dw::core::Arrays
output application/json
var customer = payload groupBy $.customerID pluck $
---
flatten(customer map
    (if (sizeOf($)>4)
          [flatten($ divideBy 5 map(flatten($)))]
            else
    (customer filter (sizeOf ($)< 5) divideBy 3 map (flatten ($)))
    ) distinctBy $)


问:
JavaScript equivalent to printf/String.Format
I'm looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .NET).

My basic requirement is a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good.

I realize Microsoft's Ajax library provides a version of String.Format(), but we don't want the entire overhead of that framework.

答:
I use the template literal approach, like below:

export const messages = {
  foo: (arg1, arg2) => `Hello ${arg1} ${arg2}`,
  bar: (arg1) => `Hello ${arg1}`,
}
```
<p>From the file:</p>
<pre class="lang-js prettyprint-override"><code>console.log(messages.foo('Bar', 'World'))
console.log(messages.bar('Foo'))
</code>```

OwnerDisplayName: Chris

Body:
I use the template literal approach, like below:

export const messages = {
  foo: (arg1, arg2) => `Hello ${arg1} ${arg2}`,
  bar: (arg1) => `Hello ${arg1}`,
}

From the file:

console.log(messages.foo('Bar', 'World'))
console.log(messages.bar('Foo'))


问:
Messagebox in ttk.Spinbox bound command causes an infinite stream of pop up windows
I am working on a personal learning project that consists in a simple GUI that generates passwords. The user can either select how many characters of each type (letters, numbers and symbols) to include in the password or simply let the application choose a random combination. There is a password length constraint of 128 characters. What I am trying to do is to show a message when the user tries to increase the number of characters beyond the 128 limit.

What I've tried so far is to include a check in the function bound to the <<Increment>> event that gets called when the increment button in the spinbox is pressed. There is an if statement that checks the available characters left, if the value is zero then a messagebox.showwarnning pops up informing the user that the maximum amount of chars is 128.

The message appears but when the ok button is clicked the message closes just to pop up again and again and the only way to stop it is to kill the whole thing. I have also tried to move the messagebox to the function that is bound to the spinbox command with the same result. Any ideas on how to solve this or what am I doing terribly wrong? Thanks

This is a simplify version of the widget:

from tkinter import *
from tkinter import ttk
from tkinter import messagebox

class App(Tk):
    def __init__(self):
        super().__init__()
        self.title('Sample')
        self.geometry('300x100')
        Selector(self).pack()

class Selector(ttk.Frame):
        def __init__(self, container):
            super().__init__(container)
            self.max_length = 10
            self.input = IntVar(0);

            self.label = ttk.Label(self, text="Quantity: ").pack()
            self.spinbox = ttk.Spinbox(self, from_=0,
                                       to=self.max_length,
                                       textvariable=self.input)
            self.spinbox.pack()
            self.spinbox.bind('<<Increment>>', lambda e: self.check_length(e))

        def check_length(self, e):
            if self.input.get() == 10:
                messagebox.showwarning("Max length reached", "Too much!")

if __name__ == "__main__":
    app = App()
    app.mainloop()
```

答:
It seems that closing the messagebox retriggers the <<Increment>> event. I think I have found a workaround: the focus is removed from the spinbox after closing the messagebox and the value of the spinbox is checked only if the spinbox has the focus (which means that the user has actually clicked on it).

```<code>from tkinter import *
from tkinter import ttk
from tkinter import messagebox

class App(Tk):
    def __init__(self):
        super().__init__()
        self.title('Sample')
        self.geometry('300x100')
        Selector(self).pack()

class Selector(ttk.Frame):
        def __init__(self, container):
            super().__init__(container)
            self.max_length = 10
            self.input = IntVar(self, 0);

            self.label = ttk.Label(self, text="Quantity: ").pack()
            self.spinbox = ttk.Spinbox(self, from_=0,
                                       to=self.max_length,
                                       textvariable=self.input)
            self.spinbox.pack()
            self.spinbox.bind('<<Increment>>', lambda e: self.check_length(e))

        def check_length(self, e):
            if str(self.spinbox) != str(self.focus_get()):
                return
            if self.input.get() == 10:
                messagebox.showwarning("Max length reached", "Too much!")
                self.focus_set()

if __name__ == "__main__":
    app = App()
    app.mainloop()
</code>```

Note: This does not solve the underlying problem (the fact that <<Increment>> is endlessly triggered after closing the messagebox), it only prevents the endless reopening of the messagebox.

Body:
It seems that closing the messagebox retriggers the <<Increment>> event. I think I have found a workaround: the focus is removed from the spinbox after closing the messagebox and the value of the spinbox is checked only if the spinbox has the focus (which means that the user has actually clicked on it).

from tkinter import *
from tkinter import ttk
from tkinter import messagebox

class App(Tk):
    def __init__(self):
        super().__init__()
        self.title('Sample')
        self.geometry('300x100')
        Selector(self).pack()

class Selector(ttk.Frame):
        def __init__(self, container):
            super().__init__(container)
            self.max_length = 10
            self.input = IntVar(self, 0);

            self.label = ttk.Label(self, text="Quantity: ").pack()
            self.spinbox = ttk.Spinbox(self, from_=0,
                                       to=self.max_length,
                                       textvariable=self.input)
            self.spinbox.pack()
            self.spinbox.bind('<<Increment>>', lambda e: self.check_length(e))

        def check_length(self, e):
            if str(self.spinbox) != str(self.focus_get()):
                return
            if self.input.get() == 10:
                messagebox.showwarning("Max length reached", "Too much!")
                self.focus_set()

if __name__ == "__main__":
    app = App()
    app.mainloop()

Note: This does not solve the underlying problem (the fact that <<Increment>> is endlessly triggered after closing the messagebox), it only prevents the endless reopening of the messagebox.


问:
how to merge two arrays of objects in javascript?
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.</p>
```<code>let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]
</code>```

答:
```<code>  let arr1 = [
  {
   name: "Person1",
   age: 20
},
 {
 name: "Person2",
 age: 30
 }
]

let arr2 = [
 {
  name: "Person1",
  email: "person1@mail.com"
},
 {
   name: "Person3",
   age: 25
  }
]

var arr3 = [...arr1,...arr2]
</code>```

Body:
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]


问:
Calculate the date of Easter Sunday
Write a program to compute the date of Easter Sunday. Easter Sunday is the first Sunday after the first full moon of spring.
Use the algorithm invented by the mathematician Carl Friedrich Gauss in 1800:

Let y be the year (such as 1800 or 2001)

Divide y by 19 and call the remainder a.  Ignore the quotient.

Divide y by 100 to get a quotient b and a remainder c.

Divide b by 4 to get a quotient d and a remainder e.

Divide 8 * b + 13 by 25 to get a quotient g.  Ignore the remainder.

Divide 19 * a + b - d - g + 15 by 30 to get a remainder h.  Ignore
the quotient.

Divide c by 4 to get a quotient j and a remainder k.

Divide a + 11 * h by 319 to get a quotient m.  Ignore the remainder.

Divide 2 * e + 2 * j - k - h + m + 32 by 7 to get a remainder r. Ignore the quotient.

Divide h - m + r + 90 by 25 to get a quotient n.  Ignore the
remainder.

Divide h - m + r + n + 19 by 32 to get a remainder of p.  Ignore the
quotient.

Then Easter falls on a day p of month n.

For example, if y is 2001:

a = 6
b = 20
c = 1
d = 5
e = 0
g = 6
h = 18
j = 0
k = 1
m = 0
r = 6
n = 4
p = 15
```

<p>Therefore, in 2001, Easter Sunday fell on April 15. </p>

<p>Make sure you prompt the user for a year and have the user input the year.  Also, make sure you output the values of p and n with the appropriate messages describing the values output.</p>

<hr>

<p>I'm having a little trouble putting this into Java code. Here's what I've tried:</p>

```import java.util.Scanner;

public class Easter {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int y = 2014;
        int a = y % 19;
        int b = y / 100;
        int c = y % 100;
        int d = b / 4;
        int e = b % 4;
        int g = (8 * b + 13) / 25;
        int h = (19 * a + b - d - g + 15) % 30;
        int j = c / 4;
        int k = c % 4;
        int m = (a + 11 * h) / 319;
        int r = (2 * e + 2 * j - k - h + m + 32) % 7;
        int n = (h - m + r + 90) / 25;
        int p = (h - m + r + n + 19) % 32;

        getEasterSundayMonth = n;
        System.out.println("Month: " + Easter.getEasterSundayMonth());
    }
}
```

This is what I have. I don't know how to assign stuff, like I tried to get getEasterSundayMonth to equal the value of n, pretty sure its not right. Where do I go from here?

答:
Kotlin version:</p>
```<code>private fun getEasterSundayDate(year: Int): String {
        val a = year % 19
        val b = year /100
        val c = year % 100
        val d = b /4
        val e = b % 4
        val g = (8 * b + 13) / 25
        val h = (19 * a + b - d - g + 15) % 30
        val j = c / 4
        val k = c % 4
        val m = (a + 11 * h) / 319
        val r = (2 * e + 2 * j - k - h + m + 32) % 7
        val month = (h - m + r + 90) / 25
        val day = (h - m + r + month + 19) % 32

        return String.format("%02d", day) + "." + String.format("%02d", month)
    }
</code>```

Title: Calculate the date of Easter Sunday

Body:
Write a program to compute the date of Easter Sunday. Easter Sunday is the first Sunday after the first full moon of spring.
Use the algorithm invented by the mathematician Carl Friedrich Gauss in 1800:

Let y be the year (such as 1800 or 2001)

Divide y by 19 and call the remainder a.  Ignore the quotient.

Divide y by 100 to get a quotient b and a remainder c.

Divide b by 4 to get a quotient d and a remainder e.

Divide 8 * b + 13 by 25 to get a quotient g.  Ignore the remainder.

Divide 19 * a + b - d - g + 15 by 30 to get a remainder h.  Ignore
the quotient.

Divide c by 4 to get a quotient j and a remainder k.

Divide a + 11 * h by 319 to get a quotient m.  Ignore the remainder.

Divide 2 * e + 2 * j - k - h + m + 32 by 7 to get a remainder r. Ignore the quotient.

Divide h - m + r + 90 by 25 to get a quotient n.  Ignore the
remainder.

Divide h - m + r + n + 19 by 32 to get a remainder of p.  Ignore the
quotient.

Then Easter falls on a day p of month n.

For example, if y is 2001:

a = 6
b = 20
c = 1
d = 5
e = 0
g = 6
h = 18
j = 0
k = 1
m = 0
r = 6
n = 4
p = 15

Therefore, in 2001, Easter Sunday fell on April 15.

Make sure you prompt the user for a year and have the user input the year.  Also, make sure you output the values of p and n with the appropriate messages describing the values output.

I'm having a little trouble putting this into Java code. Here's what I've tried:

import java.util.Scanner;

public class Easter {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int y = 2014;
        int a = y % 19;
        int b = y / 100;
        int c = y % 100;
        int d = b / 4;
        int e = b % 4;
        int g = (8 * b + 13) / 25;
        int h = (19 * a + b - d - g + 15) % 30;
        int j = c / 4;
        int k = c % 4;
        int m = (a + 11 * h) / 319;
        int r = (2 * e + 2 * j - k - h + m + 32) % 7;
        int n = (h - m + r + 90) / 25;
        int p = (h - m + r + n + 19) % 32;

        getEasterSundayMonth = n;
        System.out.println("Month: " + Easter.getEasterSundayMonth());
    }
}

This is what I have. I don't know how to assign stuff, like I tried to get getEasterSundayMonth to equal the value of n, pretty sure its not right. Where do I go from here?

Body:
Kotlin version:

private fun getEasterSundayDate(year: Int): String {
        val a = year % 19
        val b = year /100
        val c = year % 100
        val d = b /4
        val e = b % 4
        val g = (8 * b + 13) / 25
        val h = (19 * a + b - d - g + 15) % 30
        val j = c / 4
        val k = c % 4
        val m = (a + 11 * h) / 319
        val r = (2 * e + 2 * j - k - h + m + 32) % 7
        val month = (h - m + r + 90) / 25
        val day = (h - m + r + month + 19) % 32

        return String.format("%02d", day) + "." + String.format("%02d", month)
    }


问:
Call a Widget based on the result of an If statement Flutter
I want to be able to call either one of two different widgets based on the result of an if statement.
I am able to get a Text Widget to show two different answers based on the result of the first dropdown box, but I am not able to call another widget the same way ...

```<code>import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = 'Option A';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),

              /*
              * This is the first dropdown that is called, This dropdown provides
              * two possible options,
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * So this is the if Statement that works based upon the first
              * drop down box's answer...
              *
              * The problem is I can not get the system to call another Drop down Butten
              * Widget based on the answer of the first DropdownBox,
              * However, i can get a Text Widget to print...
              * */
              Text((() {
                if (firstDropdownValue == 'Option A') {
                  return "Option is Option A";
                }
                return "Option is Option B";
              })()),

              /*
              * This is the second dropbox that I would like to be called if the
              * previous statement is met instead of the Text Widget above...
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 1',
                  'Option 2',
                  'Option 3',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * This is also drop box two, but this dropbox with these different
              * options should be called when the if statement is not met ..
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 4',
                  'Option 5',
                  'Option 6',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

The flow diagram is maybe easier to get the whole picture from.

答: Not the best approach for this probably, but you can use a Builder widget, inside it put your if statement and if you don't want to show your widget there, return SizedBox.shrink() instead (don't forget to setState((){}) so that the widget containing them both rebuilds them. But a better answer may be using Bloc or some other state management package. Or even ValueNotifiers and ValueListenableBuilders to update your UI only where it's needed.

Body:
I want to be able to call either one of two different widgets based on the result of an if statement.
I am able to get a Text Widget to show two different answers based on the result of the first dropdown box, but I am not able to call another widget the same way ...

import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = 'Option A';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),

              /*
              * This is the first dropdown that is called, This dropdown provides
              * two possible options,
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * So this is the if Statement that works based upon the first
              * drop down box's answer...
              *
              * The problem is I can not get the system to call another Drop down Butten
              * Widget based on the answer of the first DropdownBox,
              * However, i can get a Text Widget to print...
              * */
              Text((() {
                if (firstDropdownValue == 'Option A') {
                  return "Option is Option A";
                }
                return "Option is Option B";
              })()),

              /*
              * This is the second dropbox that I would like to be called if the
              * previous statement is met instead of the Text Widget above...
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 1',
                  'Option 2',
                  'Option 3',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * This is also drop box two, but this dropbox with these different
              * options should be called when the if statement is not met ..
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 4',
                  'Option 5',
                  'Option 6',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

The flow diagram is maybe easier to get the whole picture from.


问:
InvalidModuleDescriptorException when running my first java app
I have started learning Java and encountered a problem when trying to run my first program as given below:

```<code>public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
     System.out.println("Hello world!");
    }
}
</code>```

On Eclipse Photon I encounter this error when running it:

```<code> Error occurred during initialization of boot layer
    java.lang.module.FindException: Error reading module: C:\Users\Thomas\eclipse-workspace\HelloWorld\bin
    Caused by: java.lang.module.InvalidModuleDescriptorException: HelloWorld.class found in top-level directory (unnamed package not allowed in module)
</code>```

I looked and there is my .class file in bin directory and my .java in the src directory.

Is that normal? How do I fix that?

答:
create a package and refactor your Main class in that package in your case its HelloWorld then it will run fine.
To understand how modules work in java please watch this spectacular video MODULES IN JAVA</p>

Body:
I have started learning Java and encountered a problem when trying to run my first program as given below:

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
     System.out.println("Hello world!");
    }
}

On Eclipse Photon I encounter this error when running it:

 Error occurred during initialization of boot layer
    java.lang.module.FindException: Error reading module: C:\Users\Thomas\eclipse-workspace\HelloWorld\bin
    Caused by: java.lang.module.InvalidModuleDescriptorException: HelloWorld.class found in top-level directory (unnamed package not allowed in module)

I looked and there is my .class file in bin directory and my .java in the src directory.

Is that normal? How do I fix that?


问:
Why does Flutter's WillPopScope always block going back?
Whenever I've tried to block the ability to swipe back with Flutter on iOS I've tried using WillPopScope. However, regardless of what value I put in onWillPop: it will always block the ability to swipe back.

Why is this? It doesn't matter if onWillPop returns true or false, it always blocks.

```<code>    final isConfirmation = _isConfirmation();
    WillPopScope(
      child: Scaffold(
        appBar: _appBar(),
        body: _body(),
      ),
      onWillPop: () async => isConfirmation,
    );
</code>```

This issue happens even if I return a hard true or false

onWillPop: () async => true

onWillPop: () async => false

onWillPop: () => Future<bool>.value(true)

onWillPop: () => Future<bool>.value(false)

答:
Change your code to this.

if _isConfirmation() is a Future method, use await before it in the code below.

```<code>onWillPop: () async {
  final bool confirmation = _isConfirmation();  // use await if it is future.
  return Future<bool>.value(confirmation);
}
</code>```

Body:
Whenever I've tried to block the ability to swipe back with Flutter on iOS I've tried using WillPopScope. However, regardless of what value I put in onWillPop: it will always block the ability to swipe back.

Why is this? It doesn't matter if onWillPop returns true or false, it always blocks.

    final isConfirmation = _isConfirmation();
    WillPopScope(
      child: Scaffold(
        appBar: _appBar(),
        body: _body(),
      ),
      onWillPop: () async => isConfirmation,
    );

This issue happens even if I return a hard true or false

onWillPop: () async => true

onWillPop: () async => false

onWillPop: () => Future<bool>.value(true)

onWillPop: () => Future<bool>.value(false)

Body:
Change your code to this.

if _isConfirmation() is a Future method, use await before it in the code below.

onWillPop: () async {
  final bool confirmation = _isConfirmation();  // use await if it is future.
  return Future<bool>.value(confirmation);
}


问:
Is F# Constructed Type syntax special?
I was curious about F#'s "constructed type" syntax. It's documented here.

type-argument generic-type-name

or

generic-type-name

With the following examples:

int option

string list

int ref

option<int>

list<string>

ref<int>

Dictionary<int, string>

I was curious if there's anything special about the "backwards" syntax, with the parameter before the type, or if it's just sugar for generic types with one parameter. The following is valid:

type 'a MyOption = // MyOption<'a> also works
  | MySome of 'a
  | MyNone
```

But I could not get it to work with multiple type parameters. Why do F# developers prefer this syntax for types with one parameter? Is it possible or desirable to make it work with two?

答:
Why do F# developers prefer this syntax for types with one parameter?

Not all of us do. I love F# and am in awe of it, but find the OCaml style distracting.

It gets especially confusing when the two styles are mixed - compare the readability of Async<Result<int,string list>> list with that of List<Async<Result<int,List<string>>>>.

Here is a thread with some arguments from both sides from fslang suggestions, which I think led to the deprecation of OCaml-style for everything but list, option and a few others.

I find it regrettable that the OCaml style is specified as the preferred option (for these types) in the various style guides, and used throughout the core libraries, while there is such a strong drive to make the language more accessible to newcomers. It definitely adds to the learning curve, as documented in this question,
and here,
here,
here,
here,
here.

Is it possible or desirable to make [OCaml style naming] work with two [type parameters]?

I think a better question is: "Is it possible to only use .NET style?".

Unfortunately the tooling shows types the way they are declared, and the core libraries consistently use OCaml style. I have asked Rider about always showing declarations .NET style in code vision, who referred me to FSharp compiler services. I have not (yet) investigated that avenue further.

In our own code we have taken to overriding the OCaml signatures of functions that ship with F# and other libraries as we come across them, for example:

[<AutoOpen>]
module NoCaml =

  module List =
    /// Returns a new collection containing only the elements of the collection for which the given predicate returns "true"
    let filter = List.filter : ('a -> bool) -> List<'a> -> List<'a>

    /// val groupBy : projection:('T -> 'Key) -> list:'T list -> ('Key * 'T list) list (requires equality and equality)  'T is 'a 'Key is 'b  Applies a key-generating function to each element of a list and yields a list of unique keys. Each unique key contains a list of all elements that match to this key.
    let groupBy = List.groupBy : ('a -> 'b) -> List<'a> -> List<'b * List<'a>>

    // etc.
```

This solves the problem in almost all cases (some exceptions like list construction using [] remain, and need to be overridden at the point of declaration).

I'm not sure what influence this has on performance at runtime - hopefully the extra function calls are optimised away.

Title: Is F# Constructed Type syntax special?

Body:
I was curious about F#'s "constructed type" syntax. It's documented here.

type-argument generic-type-name

or

generic-type-name

With the following examples:

int option

string list

int ref

option<int>

list<string>

ref<int>

Dictionary<int, string>

I was curious if there's anything special about the "backwards" syntax, with the parameter before the type, or if it's just sugar for generic types with one parameter. The following is valid:

type 'a MyOption = // MyOption<'a> also works
  | MySome of 'a
  | MyNone

But I could not get it to work with multiple type parameters. Why do F# developers prefer this syntax for types with one parameter? Is it possible or desirable to make it work with two?

Body:
Why do F# developers prefer this syntax for types with one parameter?

Not all of us do. I love F# and am in awe of it, but find the OCaml style distracting.

It gets especially confusing when the two styles are mixed - compare the readability of Async<Result<int,string list>> list with that of List<Async<Result<int,List<string>>>>.

Here is a thread with some arguments from both sides from fslang suggestions, which I think led to the deprecation of OCaml-style for everything but list, option and a few others.

I find it regrettable that the OCaml style is specified as the preferred option (for these types) in the various style guides, and used throughout the core libraries, while there is such a strong drive to make the language more accessible to newcomers. It definitely adds to the learning curve, as documented in this question,
and here,
here,
here,
here,
here.

Is it possible or desirable to make [OCaml style naming] work with two [type parameters]?

I think a better question is: "Is it possible to only use .NET style?".

Unfortunately the tooling shows types the way they are declared, and the core libraries consistently use OCaml style. I have asked Rider about always showing declarations .NET style in code vision, who referred me to FSharp compiler services. I have not (yet) investigated that avenue further.

In our own code we have taken to overriding the OCaml signatures of functions that ship with F# and other libraries as we come across them, for example:

[<AutoOpen>]
module NoCaml =

  module List =
    /// Returns a new collection containing only the elements of the collection for which the given predicate returns "true"
    let filter = List.filter : ('a -> bool) -> List<'a> -> List<'a>

    /// val groupBy : projection:('T -> 'Key) -> list:'T list -> ('Key * 'T list) list (requires equality and equality)  'T is 'a 'Key is 'b  Applies a key-generating function to each element of a list and yields a list of unique keys. Each unique key contains a list of all elements that match to this key.
    let groupBy = List.groupBy : ('a -> 'b) -> List<'a> -> List<'b * List<'a>>

    // etc.

This solves the problem in almost all cases (some exceptions like list construction using [] remain, and need to be overridden at the point of declaration).

I'm not sure what influence this has on performance at runtime - hopefully the extra function calls are optimised away.


问:
Javascript Key Mapping for number
I made a shortcut in my website

```<code>alt + 1 = something()
alt + 2 = something()
shift + 1 = something()
...

window.addEventListner("keydown",(e) => {
if(e.key === 1 && e.alt) doSomething();
})

</code>```

But the problem is when i press shift+1 it become shift + ! the key become special char! And alt(option) + 1 is ¡

Should i make a Key Map for every special chars?   Or is there good other way ?

答:
You can use the code property and look for the string "Digit1". That's the purpose of code, to give you a key name unaffected by modifier keys.

Here's a demo of the difference:

window.addEventListener("keydown",(e) => {
    console.log(`key = ${e.key}, code = ${e.code}`);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Click here, then press 1, and then press !.</code>```

So for instance:

```<code>if (e.altKey && e.code === "Digit1") {
    // ...
}
</code>```

(Note that it's altKey, not alt, to see if the Alt key is down.)

Title: Javascript Key Mapping for number

Body:
I made a shortcut in my website

alt + 1 = something()
alt + 2 = something()
shift + 1 = something()
...

window.addEventListner("keydown",(e) => {
if(e.key === 1 && e.alt) doSomething();
})

But the problem is when i press shift+1 it become shift + ! the key become special char! And alt(option) + 1 is ¡

Should i make a Key Map for every special chars?   Or is there good other way ?

Body:
You can use the code property and look for the string "Digit1". That's the purpose of code, to give you a key name unaffected by modifier keys.

Here's a demo of the difference:

window.addEventListener("keydown",(e) => {
    console.log(`key = ${e.key}, code = ${e.code}`);
});

Click here, then press 1, and then press !.

So for instance:

if (e.altKey && e.code === "Digit1") {
    // ...
}

(Note that it's altKey, not alt, to see if the Alt key is down.)


问:
How to view Jetpack Compose Animation Preview?
In https://developer.android.com/jetpack/compose/animation#tooling, it is stated we can preview Animation in Android Studio.

As per this diagram (taken from the Google Developer Document link above)

However, when I load the latest Android Studio Bumblebee 2021.1.1 Patch 1

I cannot see it at all (as per the diagram below). Where is it? Did I miss anything? (I try to search help, I cannot find it as well

答:
You need to enable an Experimental option in the Android Studio settings

See documentation


问:
Why does my form submit in IE but not in Chrome?
I have a form with <input type="submit">. In Chrome submit doesn't do anything. On a Network tab in developer tools I see nothing. No errors in developer tools either. Meanwhile, if I do save a page and open a saved page, then after I press submit button, I see something appears in Network tab. This happens in Chrome and Firefox. This works as expected in IE.

Does anybody have a hindsight, what should I look at?

I don't need a direct answer, I only need to know, where should I look at. If someone posts a direction and that'll help me to solve my problem, I'll accept it as a correct answer.

Structure of a page looks like this:

```<code>html
    head
    body
        div
        div
            form
            form
            form
            form
            form
                input
                input
                table
                table
                    tbody
                        tr..td..input type=submit

</code>```

答: check your form is outside the table</p>

Body:
I have a form with <input type="submit">. In Chrome submit doesn't do anything. On a Network tab in developer tools I see nothing. No errors in developer tools either. Meanwhile, if I do save a page and open a saved page, then after I press submit button, I see something appears in Network tab. This happens in Chrome and Firefox. This works as expected in IE.

Does anybody have a hindsight, what should I look at?

I don't need a direct answer, I only need to know, where should I look at. If someone posts a direction and that'll help me to solve my problem, I'll accept it as a correct answer.

Structure of a page looks like this:

html
    head
    body
        div
        div
            form
            form
            form
            form
            form
                input
                input
                table
                table
                    tbody
                        tr..td..input type=submit

Body: check your form is outside the table


问:
When will JAVA STACK throw OutOfMemory Error instead of StackOverFlowError, in STACK?
I read that both OutOfMemoryError and StackOverFlowError can happen in stack.
But I wonder when will OOM be thrown in stack?

Is it thrown when creating new object in stack? Then I guess this new object does not belong to a stack frame, otherwise SOF will be thrown.

Thank you very much for answering. I searched on google but did not find a related answer.

I'm very sorry for previous unclear abreviations!!

答:
I strongly recommend to reduce the unnecessary use of abbreviation. While it’s clear that “OOM” refers to OutOfMemoryError, the meaning of “EOF” and “SOF” is not. “EOF” normally refers to “end of file” which does not apply here. “SOF” could refer to StackOverflow, but that’s rather unusual. I don’t think that writing the full names of the errors would take too much of your lifetime.

Regarding OutOfMemoryError, the answer is that it is implementation dependent.

The JVM specification, §2.5.2. Java Virtual Machine Stacks, says

The following exceptional conditions are associated with Java Virtual Machine stacks:

If the computation in a thread requires a larger Java Virtual Machine stack than is permitted, the Java Virtual Machine throws a StackOverflowError.

If Java Virtual Machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java Virtual Machine stack for a new thread, the Java Virtual Machine throws an OutOfMemoryError.

So in principle, an OutOfMemoryError can be thrown under certain circumstances, but the widespread HotSpot JVM doesn’t support dynamic stack expansion so this will never be a cause for an OutOfMemoryError.

The creation of a new Thread may fail with an OutOfMemoryError, but since there are several allocations involved, including the Thread instance on the heap, it hardly ever matters whether the failed allocation was supposed to provide the stack memory of the new thread or serve some other purpose.


问:
RabbitMq is not consuming the message when running the script through nohup
I have multiple rabbitmq queue which recieve the message. I recently add 2 more queue in my file but when i run that reciever script through nohup, it is not able to consume the message although in background script is running. when i run the same script by  python script.py It is working fine. My all previous rabbitmq reciever queue is working fine with nohup. My nohup command to run
the script is nohup python  script.py >> script-rabbit-reciever-app.log 2>&1 &. Is there any limitation of how many process we can run through nohup?

答: There is a limit on nohup which is a single command (in this case is just is python).  You are limited in the number of instances in nohup which is the same as any other process in linux.  You can see the process limit for a user in most common shells with ulimit -u


问:
How to format a long adding thousands separator on Arduino
I'm developing a project on Arduino that parses some JSON data from a remote web API displaying it on a 16x2 LCD.

I would like to format a long parsed with TextFinder adding the thousands separator (a comma separator would be fine).

In a nutshell, how do I code the formatLong function?

```<code>long longToBeFormatted = 32432423;

formattedLong = formatLong(longToBeFormatted); //How to implement this?

lcd.print(formattedLong) // formattedLong is a string
</code>```

答:
You could try the following:

```<code>std::string formatLong(long l) {
    int power = 0;
    while (l / (pow(1000, power)) { power += 1; }

    power -= 1;

    std::stringstream s;
    while (power) {
         s <<  l / pow(1000, power);
         s << ",";
         l % (pow(1000, power));
         power -= 1;
    }
    return s->str();
}
</code>```

The code is a shot from the hip, but the idea should work.

Body:
I'm developing a project on Arduino that parses some JSON data from a remote web API displaying it on a 16x2 LCD.

I would like to format a long parsed with TextFinder adding the thousands separator (a comma separator would be fine).

In a nutshell, how do I code the formatLong function?

long longToBeFormatted = 32432423;

formattedLong = formatLong(longToBeFormatted); //How to implement this?

lcd.print(formattedLong) // formattedLong is a string

Body:
You could try the following:

std::string formatLong(long l) {
    int power = 0;
    while (l / (pow(1000, power)) { power += 1; }

    power -= 1;

    std::stringstream s;
    while (power) {
         s <<  l / pow(1000, power);
         s << ",";
         l % (pow(1000, power));
         power -= 1;
    }
    return s->str();
}

The code is a shot from the hip, but the idea should work.