问:
PHP largest whole number from sum of unsorted array
Can someone tell me the best way to find the largest whole number summed from an unsorted array?

e.g.

```<code>{0.1, 0.2, 0.9, 0.5}

Largest whole number possible is 1 (0.1 + 0.9).

{0.9, 0.2, 0.5, 0.3, 0.9}

Largest possible is 2 (0.9 + 0.9 + 0.2)
</code>```

thanks

Update

I've accepted the method that i used but some of the below will be programmatically correct

答:
This is a great problem to think about.  Off the top of my head, this is the pseudocode I'd use:

A = array of elements.

A' = sorted array of elements.

S = sum of all elements.

While A' isn't empty:

V = integer portion of S.

R = remainder of S = S - floor(S)

Make a temporary copy of A', X.

Iterate from largest to smallest values of X as X[i]:

If X[i] < R, subtract X[i] from R.  Remove X[i] from X.

If R == 0, we've found the solution. V is the whole number, X contains the addends. STOP.

If X is empty, there is no solution.  STOP.

Reduce S by the largest value in A'.  S = S - Max(A').  Remove Max(A') from A'.

Go back to step #4.

Of course, I had to see if this would actually work.  Here's the (very messy, throw-away quality) code I wrote to test it:

```<code><?php
$AA = $A = array(0.1, 0.2, 0.9, 0.5);

bcscale(8);

sort($AA, SORT_NUMERIC);
echo 'A = ' . implode(', ', $A), PHP_EOL;
echo 'A\' = ' . implode(', ', $AA), PHP_EOL;

$S = array_sum($AA);
echo 'S = ' . $S, PHP_EOL;

while (count($AA)) {
    $V = floor($S);
    echo 'V = ' . $V, PHP_EOL;

    $R = bcsub($S, $V);
    echo 'R = ' . $R, PHP_EOL;

    $X = $AA;
    $XX = array();

    // Look for the largest value that is less than or equal to R.
    for ($i = count($X) - 1; $i >= 0; $i--) {
        echo 'X[i] = ' . $X[$i] . ', R = ' . $R, PHP_EOL;
        $c = bccomp($X[$i], $R);
        if ($c > 0) {
            continue;
        }
        $XX[] = $X[$i];
        $R = bcsub($R, $X[$i]);
        unset($X[$i]);

        if (bccomp($R, '0', strlen($R)) == 0) {
            echo 'Largest whole number sum: ' . $V, PHP_EOL;
            echo 'Elements: ' . implode(', ', $X), PHP_EOL;
            break 2;
        }
    }

    if (count($X) == 0) {
        echo 'No sums to a whole number are possible.', PHP_EOL;
        break;
    }

    $t = array_pop($AA);
    $S = bcsub($S, $t);
}

echo 'S = ' . $S, PHP_EOL;
?>
</code>```

It's an ugly O(N^2) algorithm, but it should be correct.  Can anyone see an initial starting array where this would fail?

For fun, I tried with an array of 50 elements, replacing the first line with these lines:

```<code>$A = array();
for ($i = 0; $i < 50; $i++) {
    $A[] = mt_rand(1, 99) / 100.0;
}
$AA = $A;
</code>```

At a glance, it looks right - I'll leave verification up to someone else ;)

Body:
Can someone tell me the best way to find the largest whole number summed from an unsorted array?

e.g.

{0.1, 0.2, 0.9, 0.5}

Largest whole number possible is 1 (0.1 + 0.9).

{0.9, 0.2, 0.5, 0.3, 0.9}

Largest possible is 2 (0.9 + 0.9 + 0.2)

thanks

Update

I've accepted the method that i used but some of the below will be programmatically correct

Body:
This is a great problem to think about.  Off the top of my head, this is the pseudocode I'd use:

A = array of elements.

A' = sorted array of elements.

S = sum of all elements.

While A' isn't empty:

V = integer portion of S.

R = remainder of S = S - floor(S)

Make a temporary copy of A', X.

Iterate from largest to smallest values of X as X[i]:

If X[i] < R, subtract X[i] from R.  Remove X[i] from X.

If R == 0, we've found the solution. V is the whole number, X contains the addends. STOP.

If X is empty, there is no solution.  STOP.

Reduce S by the largest value in A'.  S = S - Max(A').  Remove Max(A') from A'.

Go back to step #4.

Of course, I had to see if this would actually work.  Here's the (very messy, throw-away quality) code I wrote to test it:

<?php
$AA = $A = array(0.1, 0.2, 0.9, 0.5);

bcscale(8);

sort($AA, SORT_NUMERIC);
echo 'A = ' . implode(', ', $A), PHP_EOL;
echo 'A\' = ' . implode(', ', $AA), PHP_EOL;

$S = array_sum($AA);
echo 'S = ' . $S, PHP_EOL;

while (count($AA)) {
    $V = floor($S);
    echo 'V = ' . $V, PHP_EOL;

    $R = bcsub($S, $V);
    echo 'R = ' . $R, PHP_EOL;

    $X = $AA;
    $XX = array();

    // Look for the largest value that is less than or equal to R.
    for ($i = count($X) - 1; $i >= 0; $i--) {
        echo 'X[i] = ' . $X[$i] . ', R = ' . $R, PHP_EOL;
        $c = bccomp($X[$i], $R);
        if ($c > 0) {
            continue;
        }
        $XX[] = $X[$i];
        $R = bcsub($R, $X[$i]);
        unset($X[$i]);

        if (bccomp($R, '0', strlen($R)) == 0) {
            echo 'Largest whole number sum: ' . $V, PHP_EOL;
            echo 'Elements: ' . implode(', ', $X), PHP_EOL;
            break 2;
        }
    }

    if (count($X) == 0) {
        echo 'No sums to a whole number are possible.', PHP_EOL;
        break;
    }

    $t = array_pop($AA);
    $S = bcsub($S, $t);
}

echo 'S = ' . $S, PHP_EOL;
?>

It's an ugly O(N^2) algorithm, but it should be correct.  Can anyone see an initial starting array where this would fail?

For fun, I tried with an array of 50 elements, replacing the first line with these lines:

$A = array();
for ($i = 0; $i < 50; $i++) {
    $A[] = mt_rand(1, 99) / 100.0;
}
$AA = $A;

At a glance, it looks right - I'll leave verification up to someone else ;)


来源: stackexchange

问:
iOS simulator not working or taking so much time in Flutter
When I tried to run an app in an iOS Simulator it get stuck in Launching lib/main.dart on iPhone X in debug mode.... Sometimes, after a couple hours, it goes forward, so It seems that the problem here it's that it takes soo long.

In case you want to know, my computer is MBP i5 8gb

Results when execute flutter run -v on iOS Simulator:

```<code>testing flutter run -v -d BAC497EA-D54E-4B34-AE01-8ACB239AD7F5
[  +60 ms] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git rev-parse --abbrev-ref --symbolic @{u}
[  +52 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[        ] origin/stable
[        ] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git rev-parse --abbrev-ref HEAD
[  +15 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[        ] stable
[        ] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git ls-remote --get-url origin
[  +17 ms] Exit code 0 from: git ls-remote --get-url origin
[        ] https://github.com/flutter/flutter.git
[        ] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git log -n 1 --pretty=format:%H
[  +19 ms] Exit code 0 from: git log -n 1 --pretty=format:%H
[        ] 5391447fae6209bb21a89e6a5a6583cac1af9b4b
[        ] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git log -n 1 --pretty=format:%ar
[  +24 ms] Exit code 0 from: git log -n 1 --pretty=format:%ar
[        ] 5 weeks ago
[   +1 ms] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git describe --match v*.*.* --first-parent --long --tags
[  +18 ms] Exit code 0 from: git describe --match v*.*.* --first-parent --long --tags
[        ] v1.0.0-0-g5391447fa
[ +471 ms] executing: /Users/leonardodominguez/Library/Android/sdk/platform-tools/adb devices -l
[  +15 ms] Exit code 0 from: /Users/leonardodominguez/Library/Android/sdk/platform-tools/adb devices -l
[        ] List of devices attached
          emulator-5554          device product:sdk_gphone_x86 model:Android_SDK_built_for_x86 device:generic_x86 transport_id:1
[  +13 ms] executing: idevice_id -h
[  +64 ms] /usr/bin/xcrun simctl list --json devices
[+2287 ms] Launching lib/main.dart on iPhone X in debug mode...
[  +21 ms] executing: /usr/bin/defaults read /Users/leonardodominguez/Desktop/Projects/flutter/course/testing/ios/Runner/Info CFBundleIdentifier
[ +284 ms] Exit code 0 from: /usr/bin/defaults read /Users/leonardodominguez/Desktop/Projects/flutter/course/testing/ios/Runner/Info CFBundleIdentifier
[        ] $(PRODUCT_BUNDLE_IDENTIFIER)
[  +41 ms] Building Runner.app for BAC497EA-D54E-4B34-AE01-8ACB239AD7F5.
[  +36 ms] /Users/leonardodominguez/Documents/dev/flutter/bin/cache/dart-sdk/bin/dart
/Users/leonardodominguez/Documents/dev/flutter/bin/cache/artifacts/engine/darwin-x64/frontend_server.dart.snapshot --sdk-root
/Users/leonardodominguez/Documents/dev/flutter/bin/cache/artifacts/engine/common/flutter_patched_sdk/ --strong --target=flutter --no-link-platform --incremental --packages
/Users/leonardodominguez/Desktop/Projects/flutter/course/testing/.packages --output-dill build/app.dill --depfile build/snapshot_blob.bin.d package:testing/main.dart
[  +15 ms] executing: script /dev/null /usr/bin/log stream --style syslog --predicate processImagePath CONTAINS "BAC497EA-D54E-4B34-AE01-8ACB239AD7F5"
[ +160 ms] [DEVICE LOG] Filtering the log data using "processImagePath CONTAINS "BAC497EA-D54E-4B34-AE01-8ACB239AD7F5""
[+3384 ms] Building bundle
[   +2 ms] Writing asset files to build/flutter_assets
[ +350 ms] Wrote build/flutter_assets
[  +30 ms] Using legacy Xcode build system.
[  +23 ms] executing: [/Users/leonardodominguez/Desktop/Projects/flutter/course/testing/ios/] /usr/bin/xcodebuild -list
</code>```

Flutter doctor:

```<code>[✓] Flutter (Channel stable, v1.0.0, on Mac OS X 10.14 18A391, locale en-US)
    • Flutter version 1.0.0 at /Users/leonardodominguez/Documents/dev/flutter
    • Framework revision 5391447fae (5 weeks ago), 2018-11-29 19:41:26 -0800
    • Engine revision 7375a0f414
    • Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[✓] Android toolchain - develop for Android devices (Android SDK 28.0.3)
    • Android SDK at /Users/leonardodominguez/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.1, Build version 10B61
    • ios-deploy 1.9.4
    • CocoaPods version 1.5.3

[✓] Android Studio (version 3.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 31.3.1
    • Dart plugin version 181.5656
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)

[✓] VS Code (version 1.30.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 2.21.1

[✓] Connected device (2 available)
    • Android SDK built for x86 • emulator-5554                        • android-x86 • Android 9 (API 28) (emulator)
    • iPhone X                  • BAC497EA-D54E-4B34-AE01-8ACB239AD7F5 • ios         • iOS 12.1 (simulator)

• No issues found!
</code>```

答: I forgot to post the solution to this problem. If you run into it, the problem was iCloud. I moved my projects to my user's directory—iCloud does not mess there— and that fixed it.</p>

ContentLicense: CC BY-SA 4.0

Body:
When I tried to run an app in an iOS Simulator it get stuck in Launching lib/main.dart on iPhone X in debug mode.... Sometimes, after a couple hours, it goes forward, so It seems that the problem here it's that it takes soo long.

In case you want to know, my computer is MBP i5 8gb

Results when execute flutter run -v on iOS Simulator:

testing flutter run -v -d BAC497EA-D54E-4B34-AE01-8ACB239AD7F5
[  +60 ms] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git rev-parse --abbrev-ref --symbolic @{u}
[  +52 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[        ] origin/stable
[        ] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git rev-parse --abbrev-ref HEAD
[  +15 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[        ] stable
[        ] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git ls-remote --get-url origin
[  +17 ms] Exit code 0 from: git ls-remote --get-url origin
[        ] https://github.com/flutter/flutter.git
[        ] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git log -n 1 --pretty=format:%H
[  +19 ms] Exit code 0 from: git log -n 1 --pretty=format:%H
[        ] 5391447fae6209bb21a89e6a5a6583cac1af9b4b
[        ] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git log -n 1 --pretty=format:%ar
[  +24 ms] Exit code 0 from: git log -n 1 --pretty=format:%ar
[        ] 5 weeks ago
[   +1 ms] executing: [/Users/leonardodominguez/Documents/dev/flutter/] git describe --match v*.*.* --first-parent --long --tags
[  +18 ms] Exit code 0 from: git describe --match v*.*.* --first-parent --long --tags
[        ] v1.0.0-0-g5391447fa
[ +471 ms] executing: /Users/leonardodominguez/Library/Android/sdk/platform-tools/adb devices -l
[  +15 ms] Exit code 0 from: /Users/leonardodominguez/Library/Android/sdk/platform-tools/adb devices -l
[        ] List of devices attached
          emulator-5554          device product:sdk_gphone_x86 model:Android_SDK_built_for_x86 device:generic_x86 transport_id:1
[  +13 ms] executing: idevice_id -h
[  +64 ms] /usr/bin/xcrun simctl list --json devices
[+2287 ms] Launching lib/main.dart on iPhone X in debug mode...
[  +21 ms] executing: /usr/bin/defaults read /Users/leonardodominguez/Desktop/Projects/flutter/course/testing/ios/Runner/Info CFBundleIdentifier
[ +284 ms] Exit code 0 from: /usr/bin/defaults read /Users/leonardodominguez/Desktop/Projects/flutter/course/testing/ios/Runner/Info CFBundleIdentifier
[        ] $(PRODUCT_BUNDLE_IDENTIFIER)
[  +41 ms] Building Runner.app for BAC497EA-D54E-4B34-AE01-8ACB239AD7F5.
[  +36 ms] /Users/leonardodominguez/Documents/dev/flutter/bin/cache/dart-sdk/bin/dart
/Users/leonardodominguez/Documents/dev/flutter/bin/cache/artifacts/engine/darwin-x64/frontend_server.dart.snapshot --sdk-root
/Users/leonardodominguez/Documents/dev/flutter/bin/cache/artifacts/engine/common/flutter_patched_sdk/ --strong --target=flutter --no-link-platform --incremental --packages
/Users/leonardodominguez/Desktop/Projects/flutter/course/testing/.packages --output-dill build/app.dill --depfile build/snapshot_blob.bin.d package:testing/main.dart
[  +15 ms] executing: script /dev/null /usr/bin/log stream --style syslog --predicate processImagePath CONTAINS "BAC497EA-D54E-4B34-AE01-8ACB239AD7F5"
[ +160 ms] [DEVICE LOG] Filtering the log data using "processImagePath CONTAINS "BAC497EA-D54E-4B34-AE01-8ACB239AD7F5""
[+3384 ms] Building bundle
[   +2 ms] Writing asset files to build/flutter_assets
[ +350 ms] Wrote build/flutter_assets
[  +30 ms] Using legacy Xcode build system.
[  +23 ms] executing: [/Users/leonardodominguez/Desktop/Projects/flutter/course/testing/ios/] /usr/bin/xcodebuild -list

Flutter doctor:

[✓] Flutter (Channel stable, v1.0.0, on Mac OS X 10.14 18A391, locale en-US)
    • Flutter version 1.0.0 at /Users/leonardodominguez/Documents/dev/flutter
    • Framework revision 5391447fae (5 weeks ago), 2018-11-29 19:41:26 -0800
    • Engine revision 7375a0f414
    • Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[✓] Android toolchain - develop for Android devices (Android SDK 28.0.3)
    • Android SDK at /Users/leonardodominguez/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.1, Build version 10B61
    • ios-deploy 1.9.4
    • CocoaPods version 1.5.3

[✓] Android Studio (version 3.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 31.3.1
    • Dart plugin version 181.5656
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)

[✓] VS Code (version 1.30.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 2.21.1

[✓] Connected device (2 available)
    • Android SDK built for x86 • emulator-5554                        • android-x86 • Android 9 (API 28) (emulator)
    • iPhone X                  • BAC497EA-D54E-4B34-AE01-8ACB239AD7F5 • ios         • iOS 12.1 (simulator)

• No issues found!


问:
filter array and get max values of nested array of each set of objects in javascrip
I would like to filter from the nested array whose condition is count_buyer greater than 0 and then get the max purchase_amount from buyers all this while maintaining the nested array hierarchy.

I have data in an array like this

```<code>var data = [
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
      {
        'product':'ropa varon',
        'count_buyer':0,
        'buyers':[]
      }
    ];
</code>```

first I want to filter the objects that they have in their buyers array.

```<code>[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]
</code>```

then filter the maximum number of buyers whose condition is the maximum purchase_amount

```<code>[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]
</code>```

this is my code

var data = [
  {
    'product':'laptop',
    'count_buyer':3,
    'buyers':[
          { 'name': 'Vins', 'purchase_amount': 27 },
          { 'name': 'Jan', 'purchase_amount': 38 },
          { 'name': 'Alex', 'purchase_amount': 80 },
    ]
  },
  {
    'product':'televisor',
    'count_buyer':2,
    'buyers':[
          { 'name': 'Carl', 'purchase_amount': 25 },
          { 'name': 'Digi', 'purchase_amount': 40 }
    ]
  },
  {
    'product':'ropa varon',
    'count_buyer':0,
    'buyers':[]
  }
];
var filter0 = data.filter(count=> count.count_buyer > 0 )
var max = filter0.filter(buye => buye.buyers.reduce(function (prev, current) {
   return (prev.purchase_amount > current.purchase_amount) ? prev : current
}));
console.log(max)```
</div>
</div>
</p>

<p>but the result is like this</p>

```[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]
```

<p>How could I get to this result?</p>

```[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]
```

答:
After the .reduce, once you find the buyer with the maximum purchase_amount, create a new buyers array with that result as its one item.

Using .map and object spread/rest to avoid mutating the existing data, you can use:

var data = [
  {
    'product':'laptop',
    'count_buyer':3,
    'buyers':[
          { 'name': 'Vins', 'purchase_amount': 27 },
          { 'name': 'Jan', 'purchase_amount': 38 },
          { 'name': 'Alex', 'purchase_amount': 80 },
    ]
  },
  {
    'product':'televisor',
    'count_buyer':2,
    'buyers':[
          { 'name': 'Carl', 'purchase_amount': 25 },
          { 'name': 'Digi', 'purchase_amount': 40 }
    ]
  },
  {
    'product':'ropa varon',
    'count_buyer':0,
    'buyers':[]
  }
];

const output = data
  .filter(({ buyers }) => buyers.length)
  .map(({ buyers, ...rest }) => {
    const maxBuyer = buyers.reduce((a, b) => a.purchase_amount > b.purchase_amount ? a : b);
    return { ...rest, buyers: [maxBuyer] };
  });
console.log(output);```

Body:
I would like to filter from the nested array whose condition is count_buyer greater than 0 and then get the max purchase_amount from buyers all this while maintaining the nested array hierarchy.

I have data in an array like this

var data = [
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
      {
        'product':'ropa varon',
        'count_buyer':0,
        'buyers':[]
      }
    ];

first I want to filter the objects that they have in their buyers array.

[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]

then filter the maximum number of buyers whose condition is the maximum purchase_amount

[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]

this is my code

var data = [
  {
    'product':'laptop',
    'count_buyer':3,
    'buyers':[
          { 'name': 'Vins', 'purchase_amount': 27 },
          { 'name': 'Jan', 'purchase_amount': 38 },
          { 'name': 'Alex', 'purchase_amount': 80 },
    ]
  },
  {
    'product':'televisor',
    'count_buyer':2,
    'buyers':[
          { 'name': 'Carl', 'purchase_amount': 25 },
          { 'name': 'Digi', 'purchase_amount': 40 }
    ]
  },
  {
    'product':'ropa varon',
    'count_buyer':0,
    'buyers':[]
  }
];
var filter0 = data.filter(count=> count.count_buyer > 0 )
var max = filter0.filter(buye => buye.buyers.reduce(function (prev, current) {
   return (prev.purchase_amount > current.purchase_amount) ? prev : current
}));
console.log(max)

but the result is like this

[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]

How could I get to this result?

[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]


问:
2 HashMaps VS HashMap contain Pair
During the development of the service, I have a problem where I need to choose one of two solutions

use 2 hashmaps

use one hash map containing a pair of values.

Currently I have an option with 2 hashmaps, however I often need to get values from two hash tables using the same key.

```<code>class C {
Map<String, A> a = new HashMap<>();
Map<String, B> b = new HashMap<>();

A getA(String str){return a(str);}
B getB(String str){return b(str);}
}
</code>```

I am thinking of changing the code as follows

```<code>class C {
Map<String, Pair<A, B>> a_b = new HashMap<>();
Pair<A, B> getAB(String str){return a_b.get(str);}
}
</code>```

Will it be more efficient on a large hash table?

答: I think this question is not so much about efficiency or performance as it is what would make sense. And to answer what would make sense, one would have to take context into cosideration. If the values of the two hashmaps are dependant on eachother and make a logical unit which could be encapsulated into a class then use a class (or a pair if it makes more sense). If the values are not directly related and only make sense at one context as pairs but in another as separate things then consider using two maps.</p>

Title: 2 HashMaps VS HashMap contain Pair

Body:
During the development of the service, I have a problem where I need to choose one of two solutions

use 2 hashmaps

use one hash map containing a pair of values.

Currently I have an option with 2 hashmaps, however I often need to get values from two hash tables using the same key.

class C {
Map<String, A> a = new HashMap<>();
Map<String, B> b = new HashMap<>();

A getA(String str){return a(str);}
B getB(String str){return b(str);}
}

I am thinking of changing the code as follows

class C {
Map<String, Pair> a_b = new HashMap<>();
Pair getAB(String str){return a_b.get(str);}
}

Will it be more efficient on a large hash table?


问:
Font-size that expands when you resize the window
How do I make my font in HTML such that when I expand the window, the size of the text expands also. Sort of like setting a percentage for the text that will take on a percentage of the size of the box it is in.

Here is an illustration of what I would like to happen:

```<code>#box #text {
   font-size: 50%;
}
</code>```

Now lets say #box is 200px, #text should be 100px.
Obviously I can't just put a fix width for #text because in the site #box will be a dynamic width.

答: In browsers that support it, you can use CSS media queries to change your layout depending on the width of the window.</p>

ContentLicense: CC BY-SA 3.0

Body:
How do I make my font in HTML such that when I expand the window, the size of the text expands also. Sort of like setting a percentage for the text that will take on a percentage of the size of the box it is in.

Here is an illustration of what I would like to happen:

#box #text {
   font-size: 50%;
}

Now lets say #box is 200px, #text should be 100px.
Obviously I can't just put a fix width for #text because in the site #box will be a dynamic width.


问:
How to properly convert signInWithEmailAndPassword() to createCustomToken() in firebase cloud functions - Node js
I want to extend the default expiry time for the user token in my app. Currently i use signInWithEmailAndPassword function where the token lasts for an hour.

I know this can the done using the createcustomtoken function but I am a bit confused as to how to go about this.

This is my current login function:

```<code>exports.login = (req, res) => {
    const user = {
        email: req.body.email,
        password: req.body.password
    };

    firebase.auth().signInWithEmailAndPassword(user.email, user.password)
    .then((data) => {
        return data.user.getIdToken();
    })
    .then((token) => {
        return res.json({ token });
    })
    .catch((err) => {
        console.error(err);
            return res.status(403).json({ general: "Wrong credentials, please try again"})
    })
}
</code>```

答:
Unfortunately, it isn't possible to extend the expiry time more than 3600 seconds past the issue at time (iat).

In this doc you can see the exp explicitly says:

It can be a maximum of 3600 seconds later than the iat.

custom token doc

You can however use the refresh token that doesn't have an expire time to get a new token.

Refresh token

If you wanted to still create your custom token, you could do something similar to:

```<code>const someJwt = jwtDecode<{ sub: string; email: string }>(someOtherTokenFromThirdParty)

// sub is the unique id for the apple user
const customToken = await admin.auth().createCustomToken(someJwt.sub, {
    ...extraClaims
})
</code>```

Body:
I want to extend the default expiry time for the user token in my app. Currently i use signInWithEmailAndPassword function where the token lasts for an hour.

I know this can the done using the createcustomtoken function but I am a bit confused as to how to go about this.

This is my current login function:

exports.login = (req, res) => {
    const user = {
        email: req.body.email,
        password: req.body.password
    };

    firebase.auth().signInWithEmailAndPassword(user.email, user.password)
    .then((data) => {
        return data.user.getIdToken();
    })
    .then((token) => {
        return res.json({ token });
    })
    .catch((err) => {
        console.error(err);
            return res.status(403).json({ general: "Wrong credentials, please try again"})
    })
}

Body:
Unfortunately, it isn't possible to extend the expiry time more than 3600 seconds past the issue at time (iat).

In this doc you can see the exp explicitly says:

It can be a maximum of 3600 seconds later than the iat.

custom token doc

You can however use the refresh token that doesn't have an expire time to get a new token.

Refresh token

If you wanted to still create your custom token, you could do something similar to:

const someJwt = jwtDecode<{ sub: string; email: string }>(someOtherTokenFromThirdParty)

// sub is the unique id for the apple user
const customToken = await admin.auth().createCustomToken(someJwt.sub, {
    ...extraClaims
})


问:
How to limit output text in XHTML?
The function I tried.

```<code>  function handleChange(input) {
    if (input.value < 0) input.value = 0;
    if (input.value > 100) input.value = 100;
  }
</script>

</code>```

Below is the line of code I would like to limit the amount displayed.

```<code>   <rich:column>
       <h:outputText value="#{logresult.notes}" onchange="handleChange(this);" />
   </rich:column>
</code>```

Edit:

Found a solution from another Helpful user.

答:
Since some people want to report my answers and block any help I can get. I will post the answer here.</p>

```<code>Use CSS or a tag attribute: max-lines: 1;max-width: 200px;

</code>```

Title: How to limit output text in XHTML?

Body:
The function I tried.

  function handleChange(input) {
    if (input.value < 0) input.value = 0;
    if (input.value > 100) input.value = 100;
  }
</script>

Below is the line of code I would like to limit the amount displayed.

   <rich:column>
       <h:outputText value="#{logresult.notes}" onchange="handleChange(this);" />
   </rich:column>

Edit:

Found a solution from another Helpful user.

Body:
Since some people want to report my answers and block any help I can get. I will post the answer here.

Use CSS or a tag attribute: max-lines: 1;max-width: 200px;


问:
Does it make any sense to use `baseline` value with `justify-content`, `justify-items` or `justify-self` in CSS Flex/Grid?
MDN align-content, justify-content and justify-items describe baseline as one of their possible values. While baseline makes sense when is used with align-items or align-self, I don't get how it could work along with justify-content, justify-items, justify-self and align-content properties. Do you have any suggestions?

答:
The MDN is not accurate here as there is no baseline for justify-content

If you check the actual Flexbox specification you will see that there is no baseline value for justify-content

```<code>Value:  flex-start | flex-end | center | space-between | space-around
</code>```

In the near future and as defined in the CSS Box Alignment Module Level 3 we will have more generic way to align elements and even there baseline is a not a valid value of justify-content

```<code>Value:  normal | <content-distribution> | <overflow-position>? [ <content-position> | left | right ]

<content-distribution> = space-between | space-around | space-evenly | stretch

<overflow-position> = unsafe | safe

<content-position> = center | start | end | flex-start | flex-end
</code>```

By the way, there is baseline for justify-items in the new specificiation: https://drafts.csswg.org/css-align-3/#propdef-justify-items but this property doesn't exist in the actual Flexbox specification (same for justify-self)

Related: In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

align-content doesn't accept baseline with Flexbox (https://drafts.csswg.org/css-flexbox-1/#align-content-property) but it does in the New Specification

The same apply for CSS grid but you can find justify-items and justify-self there: https://www.w3.org/TR/css-grid-1/#row-align

Actually I don't have a clear example to illustrate the baseline with those properties but I am pretty sure in most of the case it will consider a fallback value as defined in the Spec:

Body:
The MDN is not accurate here as there is no baseline for justify-content

If you check the actual Flexbox specification you will see that there is no baseline value for justify-content

Value:  flex-start | flex-end | center | space-between | space-around

In the near future and as defined in the CSS Box Alignment Module Level 3 we will have more generic way to align elements and even there baseline is a not a valid value of justify-content

Value:  normal | <content-distribution> | <overflow-position>? [ <content-position> | left | right ]

<content-distribution> = space-between | space-around | space-evenly | stretch

<overflow-position> = unsafe | safe

<content-position> = center | start | end | flex-start | flex-end

By the way, there is baseline for justify-items in the new specificiation: https://drafts.csswg.org/css-align-3/#propdef-justify-items but this property doesn't exist in the actual Flexbox specification (same for justify-self)

Related: In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

align-content doesn't accept baseline with Flexbox (https://drafts.csswg.org/css-flexbox-1/#align-content-property) but it does in the New Specification

The same apply for CSS grid but you can find justify-items and justify-self there: https://www.w3.org/TR/css-grid-1/#row-align

Actually I don't have a clear example to illustrate the baseline with those properties but I am pretty sure in most of the case it will consider a fallback value as defined in the Spec:


问:
Is there a way to stop class instances from calling each other?
I have  multiple class instances that call each other's functions. I also have a system that detects if these functions call each other for too long (to avoid stack overflow). However, when it detects that, there's nothing it can do to actually stop them, so they just keep running until they reach recursion limit. Here's a simpler example:

class test:
    def activateOther(self, other):
        sleep(2)
        print('Activated Other Function', id(self))
        other.activateOther(self)

t = test()
t_ = test()
t.activateOther(t_)

del t, t_  # Even after deleting the variables/references, they continue running
```

Is there a way to actually stop these functions from running endlessly and hitting the recursion limit? If not, I suppose I'll try to add a variable to each class indicating whether they should continue running or not.

答:
Indeed, this is a typical recursion issue. There must be a condition in the code for when the recursion is stopped. The easiest is to introduce a depth parameter:

```<code>class test:
    def activateOther(self, other, depth=0):
        if depth > 88:
            return
        sleep(2)
        print('Activated Other Function', id(self))
        other.activateOther(self, depth + 1)

t = test()
t_ = test()
t.activateOther(t_)
</code>```

The actual condition, and whether the depth counter will do, depends of course on your application.

Body:
I have  multiple class instances that call each other's functions. I also have a system that detects if these functions call each other for too long (to avoid stack overflow). However, when it detects that, there's nothing it can do to actually stop them, so they just keep running until they reach recursion limit. Here's a simpler example:

class test:
    def activateOther(self, other):
        sleep(2)
        print('Activated Other Function', id(self))
        other.activateOther(self)

t = test()
t_ = test()
t.activateOther(t_)

del t, t_  # Even after deleting the variables/references, they continue running

Is there a way to actually stop these functions from running endlessly and hitting the recursion limit? If not, I suppose I'll try to add a variable to each class indicating whether they should continue running or not.

Body:
Indeed, this is a typical recursion issue. There must be a condition in the code for when the recursion is stopped. The easiest is to introduce a depth parameter:

class test:
    def activateOther(self, other, depth=0):
        if depth > 88:
            return
        sleep(2)
        print('Activated Other Function', id(self))
        other.activateOther(self, depth + 1)

t = test()
t_ = test()
t.activateOther(t_)

The actual condition, and whether the depth counter will do, depends of course on your application.


问:
Check if PHP session_id is in use
I am building a web-app that users can upload certain files and work on them through the web-app interface. I need to store these files for the length of a users session. I am creating a folder for each user using the session_id  as the folder name and storing the files in there.

The problem: There is nothing to indicate that a user walked away from my site and the session is going out of use. I need a cleanup script that takes the name of each folder and checks if that session_id is still active in order to delete unused and now unreachable folders. How can I do this?

答:
I found this helpful / I think it addresses your question:

Best place to store large amounts of session data

Title: Check if PHP session_id is in use


问:
fork() multiple times with a timer
I have this piece of code:

```<code>    int pidArr[128];
    int i=0;
    clock_t begin;
    double time_spent;
    begin = clock();
    while(1) {
        time_spent = (double)(clock() - begin) / CLOCKS_PER_SEC;
        if (time_spent>=2.0){ break; }
        pid = fork();
        if(pid == 0){
            pidArr[i] = getpid();
            i++;
        }
    }
</code>```

I want to fork() for 2 seconds to fill my pid array and break from the loop but it's not happend & my virtual machine crash badly.

I'll appreciate any help to fix it.

答:
You have accidentaly created a fork bomb, the problem is that when the timer is elapsed you should kill all the proccesses (or do whatever you want with this pidarr and after kill all the threads), like this example

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>

// maybe there is a standard macro or something like that
// but on my machine in /proc/sys/kernel/pid_max there is 4194304
#define PID_MAX 4194304

pid_t pidarr[PID_MAX];

static void
sigalrmHandler(int sig)
{
  for(int i = 1; i <= PID_MAX; i++){
    printf("Killing %ld\n",(long)pidarr[i]);
    kill(pidarr[i],SIGKILL);
  }
}

int main(void){
  struct sigaction sa;
  struct itimerval new_timer;

  pidarr[0] = getpid();

  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  sa.sa_handler = sigalrmHandler;
  if(sigaction(SIGALRM,&sa,NULL) == -1){
    perror("setting the handler");
    return 1;
  }

  new_timer.it_value.tv_sec = 2;
  new_timer.it_value.tv_usec = 0;
  new_timer.it_interval.tv_sec = 0;
  new_timer.it_interval.tv_usec = 0;

  // Create the timer
  if(setitimer(ITIMER_REAL,&new_timer,NULL) == -1){
    perror("setting the timer");
    return 1;
  }

  for(int i = 1; ;i++){
    switch(pidarr[i] = fork()){
    case -1: // ERROR
      perror("setting the timer");
      return 1;
    case 0:
      for(;;) // Waiting to die
        ;
    case 1:
      wait(NULL);
      break;
    }
  }

  return 0;
}
</code>```

I used settimer() (https://www.man7.org/linux/man-pages/man3/setitimer.3p.html) for create a two second timer and sigaction() (https://www.man7.org/linux/man-pages/man2/sigaction.2.html) for cast the signal, when the signal is arrived i will kill all the processes into the pidarr array, so my machine will not crush, if the timer was bigger we would have encountered the same problem, because the machine would crash before reaching the timer

Title: fork() multiple times with a timer

Body:
I have this piece of code:

    int pidArr[128];
    int i=0;
    clock_t begin;
    double time_spent;
    begin = clock();
    while(1) {
        time_spent = (double)(clock() - begin) / CLOCKS_PER_SEC;
        if (time_spent>=2.0){ break; }
        pid = fork();
        if(pid == 0){
            pidArr[i] = getpid();
            i++;
        }
    }

I want to fork() for 2 seconds to fill my pid array and break from the loop but it's not happend & my virtual machine crash badly.

I'll appreciate any help to fix it.

Body:
You have accidentaly created a fork bomb, the problem is that when the timer is elapsed you should kill all the proccesses (or do whatever you want with this pidarr and after kill all the threads), like this example

#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>

// maybe there is a standard macro or something like that
// but on my machine in /proc/sys/kernel/pid_max there is 4194304
#define PID_MAX 4194304

pid_t pidarr[PID_MAX];

static void
sigalrmHandler(int sig)
{
  for(int i = 1; i <= PID_MAX; i++){
    printf("Killing %ld\n",(long)pidarr[i]);
    kill(pidarr[i],SIGKILL);
  }
}

int main(void){
  struct sigaction sa;
  struct itimerval new_timer;

  pidarr[0] = getpid();

  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  sa.sa_handler = sigalrmHandler;
  if(sigaction(SIGALRM,&sa,NULL) == -1){
    perror("setting the handler");
    return 1;
  }

  new_timer.it_value.tv_sec = 2;
  new_timer.it_value.tv_usec = 0;
  new_timer.it_interval.tv_sec = 0;
  new_timer.it_interval.tv_usec = 0;

  // Create the timer
  if(setitimer(ITIMER_REAL,&new_timer,NULL) == -1){
    perror("setting the timer");
    return 1;
  }

  for(int i = 1; ;i++){
    switch(pidarr[i] = fork()){
    case -1: // ERROR
      perror("setting the timer");
      return 1;
    case 0:
      for(;;) // Waiting to die
        ;
    case 1:
      wait(NULL);
      break;
    }
  }

  return 0;
}

I used settimer() (https://www.man7.org/linux/man-pages/man3/setitimer.3p.html) for create a two second timer and sigaction() (https://www.man7.org/linux/man-pages/man2/sigaction.2.html) for cast the signal, when the signal is arrived i will kill all the processes into the pidarr array, so my machine will not crush, if the timer was bigger we would have encountered the same problem, because the machine would crash before reaching the timer


问:
Angular 9 "No provider for ControlContainer" VSCode error with a nested Form Builder Form Group
Note: I have searched for answers but all just say to "import ReactiveFormsModule and FormsModule", which I have done. All my other Reactive Forms have no issues.

Also, the code compiles and runs in the  browser with no console errors.  However, Visual Studio code persists in flagging my nested form component with the error "No provider for ControlContainer" no matter what I try and it's frustrating.

I have a formbuilder group with a nested form group, "billing address".  The inputs in this group are in a nested component in the main form, defined in the parent component TS:

```<code>  fedexFormGroup = this.fb.group({
    fedexAccountNumber: ['', Validators.required],
    fedexAccountNickname: [''],
    fedexDifferentAddress: [false],
    fedexIncludesSmartPost: [false],
    fedexAcceptTerms: [false],
    billingAddress: this.fb.group({
      addressLine1: [null, Validators.required],
      addressLine2: [null],
      company: [null],
      countryCode: [null, Validators.required],
      city: [null, Validators.required],
      email: [null, Validators.email],
      name: [null, Validators.required],
      phone: [null],
      postalCode: [null, Validators.required],
      residential: [false],
      state: [null, Validators.required]
    })
  });
</code>```

The nested component TS:

```<code>import { Component, OnInit, Input } from '@angular/core';
import { ControlContainer, FormGroupDirective, FormGroup } from '@angular/forms';

@Component({
  selector: 'spa-compact-address-block',
  templateUrl: './compact-address-block.component.html',
  styleUrls: ['./compact-address-block.component.scss'],
  viewProviders: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
    }
  ]
})
export class CompactAddressBlockComponent implements OnInit {
  @Input() formGroup: FormGroup;
  @Input() submitted = false;
  ...
}
</code>```

And then, in the parent component HTML, the code block that is flagged as an error is the spa-compact-address-block component.

```<code><form [formGroup]="formGroup">

...some top level form stuff..

   <div[formGroup]="rsFormGroup" *ngIf="isReceiving">

...second level form group fields ...

      <div[formGroup]="fedexFormGroup" *ngIf="isfedex">
        <spa-compact-address-block
          [formGroup]="billingAddressControl"
          [submitted]="submitted"
        ></spa-compact-address-block>
      </div>

   </div>

</div>

</form>
</code>```

I have also tried adding this to the parent component TS:

```<code>  get billingAddressControl() {
    return this.fedexFormGroup.controls.billingAddress as FormGroup;
  }
</code>```

No effect.  As I said, it's really not an error since it compiles and runs but I am really curious as to what I can do differently to ensure the editor does not flag this sort of thing every time I do it.

答: It seems that the error appears when the variable name formGroup is used. Change it to @Input() fGroup: FormGroup; and make necessary updates in your view file.

Body:
Note: I have searched for answers but all just say to "import ReactiveFormsModule and FormsModule", which I have done. All my other Reactive Forms have no issues.

Also, the code compiles and runs in the  browser with no console errors.  However, Visual Studio code persists in flagging my nested form component with the error "No provider for ControlContainer" no matter what I try and it's frustrating.

I have a formbuilder group with a nested form group, "billing address".  The inputs in this group are in a nested component in the main form, defined in the parent component TS:

  fedexFormGroup = this.fb.group({
    fedexAccountNumber: ['', Validators.required],
    fedexAccountNickname: [''],
    fedexDifferentAddress: [false],
    fedexIncludesSmartPost: [false],
    fedexAcceptTerms: [false],
    billingAddress: this.fb.group({
      addressLine1: [null, Validators.required],
      addressLine2: [null],
      company: [null],
      countryCode: [null, Validators.required],
      city: [null, Validators.required],
      email: [null, Validators.email],
      name: [null, Validators.required],
      phone: [null],
      postalCode: [null, Validators.required],
      residential: [false],
      state: [null, Validators.required]
    })
  });

The nested component TS:

import { Component, OnInit, Input } from '@angular/core';
import { ControlContainer, FormGroupDirective, FormGroup } from '@angular/forms';

@Component({
  selector: 'spa-compact-address-block',
  templateUrl: './compact-address-block.component.html',
  styleUrls: ['./compact-address-block.component.scss'],
  viewProviders: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
    }
  ]
})
export class CompactAddressBlockComponent implements OnInit {
  @Input() formGroup: FormGroup;
  @Input() submitted = false;
  ...
}

And then, in the parent component HTML, the code block that is flagged as an error is the spa-compact-address-block component.

<form [formGroup]="formGroup">

...some top level form stuff..

...second level form group fields ...

        <spa-compact-address-block
          [formGroup]="billingAddressControl"
          [submitted]="submitted"
        ></spa-compact-address-block>

</form>

I have also tried adding this to the parent component TS:

  get billingAddressControl() {
    return this.fedexFormGroup.controls.billingAddress as FormGroup;
  }

No effect.  As I said, it's really not an error since it compiles and runs but I am really curious as to what I can do differently to ensure the editor does not flag this sort of thing every time I do it.


问:
How to copy an image to clipboard in flutter
I searched in google for how to copy an image to clipboard in flutter but I did not find any useful information. I only found in flutter documentation this:

"ClipboardData class:

Data stored on the system clipboard.

The system clipboard can contain data of various media types. This data structure currently supports only plain text data, in the text property."

https://api.flutter.dev/flutter/services/ClipboardData-class.html

Is it impossible to copy an image to clipboard in flutter right now?

答:
I did not try and not sure if the answer is you looking for but you can give a try that first you can convert your image to  Uint8List format with BASE64 decode and encode then copy it. for conversion you can check this. link

how-to-convert-base64-string-into-image-with-flutter

also check answers of this threat

how-to-send-image-through-post-using-json-in-flutter


问:
Call Swift function from Bundle
I have declared a function in a custom bundle using Xcode and Swift.

MyBundle.bundle —> File.swift —> func …() {}

How do I call that function from another project using Foundation.Bundle?

答:
Well you can't call it directly but probably you can make some way around that might work.

You can create an instance of that class from string using NSClassFromString and then you call the method using that call

Something like below

```<code>func getClassName(_ strClassName: String) -> AnyClass! {
   let bundle = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
    let requiredClass: AnyClass = NSClassFromString("\(namespace).\(strClassName)")!;
    return requiredClass;
}
</code>```

Then you can call the method using your class instance returned by the above method like

```<code>yourClassInstance.perform(Selector("functionName"))
</code>```

Title: Call Swift function from Bundle

Body:
Well you can't call it directly but probably you can make some way around that might work.

You can create an instance of that class from string using NSClassFromString and then you call the method using that call

Something like below

func getClassName(_ strClassName: String) -> AnyClass! {
   let bundle = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
    let requiredClass: AnyClass = NSClassFromString("\(namespace).\(strClassName)")!;
    return requiredClass;
}

Then you can call the method using your class instance returned by the above method like

yourClassInstance.perform(Selector("functionName"))


问:
UI testing a tab bar controller
I have built a simple tab bar with 3 tabs.

I want to run a UI test to make sure that if the user clicks a tab bar item, the correct view controller shows.  How would I go about doing that?  Below is the code I would start with, just don't know how to write my assertion.

```<code>func testTabBarMyProfileButton() {
    let tabBarsQuery = XCUIApplication().tabBars
    tabBarsQuery.buttons["My Profile"].tap()
}

func testTabBarGraphsButton() {
    let tabBarsQuery = XCUIApplication().tabBars
    tabBarsQuery.buttons["Graphs"].tap()
}

func testTabBarAboutButton() {
    let tabBarsQuery = XCUIApplication().tabBars
    tabBarsQuery.buttons["About"].tap()
}
</code>```

答:
You can access the tabbar button by its position:</p>
```<code>app.tabBars.buttons.element(boundBy: 2).tap()
</code>```

Title: UI testing a tab bar controller

Body:
I have built a simple tab bar with 3 tabs.

I want to run a UI test to make sure that if the user clicks a tab bar item, the correct view controller shows.  How would I go about doing that?  Below is the code I would start with, just don't know how to write my assertion.

func testTabBarMyProfileButton() {
    let tabBarsQuery = XCUIApplication().tabBars
    tabBarsQuery.buttons["My Profile"].tap()
}

func testTabBarGraphsButton() {
    let tabBarsQuery = XCUIApplication().tabBars
    tabBarsQuery.buttons["Graphs"].tap()
}

func testTabBarAboutButton() {
    let tabBarsQuery = XCUIApplication().tabBars
    tabBarsQuery.buttons["About"].tap()
}

Body:
You can access the tabbar button by its position:

app.tabBars.buttons.element(boundBy: 2).tap()


问:
Open .env with file_get_contents
I have a control panel where the user can edit the API Key and Secret Key, just updating two input fields. It's ok but the thing is that I need to edit the .env file of the Laravel.

I have this code:

```<code>$path_to_file = url('.env');
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("\nH",",H",$file_contents);
file_put_contents($path_to_file,$file_contents);
</code>```

I know how works the replace but how could the path be? because if I use url() it says error, if I do not use it error again. I wonder how can I open with file_get_contents the .env in the laravel framework.

Thanks

答:
You can use base_path helper (documentation) to get absolute path to the .env file, e.g.:

```<code>>>> base_path('.env');
=> "C:\ProjectDir\.env"
</code>```

To edit the .env file more easily, I recommend you to use packages like jackiedo/dotenv-editor, which allows you to modify environment file in a few lines of code.

Title: Open .env with file_get_contents

Body:
I have a control panel where the user can edit the API Key and Secret Key, just updating two input fields. It's ok but the thing is that I need to edit the .env file of the Laravel.

I have this code:

$path_to_file = url('.env');
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("\nH",",H",$file_contents);
file_put_contents($path_to_file,$file_contents);

I know how works the replace but how could the path be? because if I use url() it says error, if I do not use it error again. I wonder how can I open with file_get_contents the .env in the laravel framework.

Thanks

Body:
You can use base_path helper (documentation) to get absolute path to the .env file, e.g.:

>>> base_path('.env');
=> "C:\ProjectDir\.env"

To edit the .env file more easily, I recommend you to use packages like jackiedo/dotenv-editor, which allows you to modify environment file in a few lines of code.


问:
Can a List.Sort using a randomized Comparison delegate run infinitely?
I'm investigating and performance testing various ways of randomizing ordered collections, and I was looking at the option of passing a Comparison delegate that just randomly returns the comparison result. For example:

```<code>int RandomComparison<T> (T x, T y)
{
    return this.random.Next (-1, 2);
}
</code>```

However, as I do not know the sorting algorithm used under the hood, I do not know if this could possibly lead to the sort logic never completing. While this method seems generally unreliable performance-wise, I'm wondering if it is actually dangerously unusable?

答:
As many already mentioned, sorting with a random comparison function does not produce a uniform distribution of permutations and should not be used. But to answer the question anyway...

From a theorectical point of view, yes you can hang infinitely depending on your sorting algorithm choice.

For example, this bubble sort keeps going until no swaps are made:

From Wikipedia:

```<code>procedure bubbleSort( A : list of sortable items )
  do
    swapped = false
    for each i in 1 to length(A) - 1 inclusive do:
      if A[i-1] > A[i] then
        swap( A[i-1], A[i] )
        swapped = true
      end if
    end for
  while swapped
end procedure
</code>```

So a malicious comparison function can make just two values be swapped in and out infinitely.

However, all decent algorithms I can think of (quicksort, mergesort, heapsort, insertionsort) only use for loops so their terminations shouldn't depend on the correctness of the sorting routine. Even bubble sort itself can be made to guarantee termination with just a couple of changes (check the wiki link for examples)

So, from a practical standpoint, no: The correctness of the comparison function should not influence the runtime behaviour of the sort*

*modulo things like quicksort being O(n^2) on the worst case...

Body:
I'm investigating and performance testing various ways of randomizing ordered collections, and I was looking at the option of passing a Comparison delegate that just randomly returns the comparison result. For example:

int RandomComparison<T> (T x, T y)
{
    return this.random.Next (-1, 2);
}

However, as I do not know the sorting algorithm used under the hood, I do not know if this could possibly lead to the sort logic never completing. While this method seems generally unreliable performance-wise, I'm wondering if it is actually dangerously unusable?

Body:
As many already mentioned, sorting with a random comparison function does not produce a uniform distribution of permutations and should not be used. But to answer the question anyway...

From a theorectical point of view, yes you can hang infinitely depending on your sorting algorithm choice.

For example, this bubble sort keeps going until no swaps are made:

From Wikipedia:

procedure bubbleSort( A : list of sortable items )
  do
    swapped = false
    for each i in 1 to length(A) - 1 inclusive do:
      if A[i-1] > A[i] then
        swap( A[i-1], A[i] )
        swapped = true
      end if
    end for
  while swapped
end procedure

So a malicious comparison function can make just two values be swapped in and out infinitely.

However, all decent algorithms I can think of (quicksort, mergesort, heapsort, insertionsort) only use for loops so their terminations shouldn't depend on the correctness of the sorting routine. Even bubble sort itself can be made to guarantee termination with just a couple of changes (check the wiki link for examples)

So, from a practical standpoint, no: The correctness of the comparison function should not influence the runtime behaviour of the sort*

*modulo things like quicksort being O(n^2) on the worst case...


问:
Android KeyGenParameterSpec.Builder ignoring setCertificateNotBefore and setCertificateNotAfter when not in Secure Hadware
I've created the following method that creates a KeyPair and logs the Certificate details:

```<code>@RequiresApi(api = Build.VERSION_CODES.N)
public void createRSAKeyPairtWithChallenge(final String alias, final String attestationChallenge) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyStoreException, CertificateException, IOException {
    Calendar start = Calendar.getInstance();
    Calendar end = new GregorianCalendar(2025,03,24);
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
    keyPairGenerator.initialize(
            new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_DECRYPT)
                    .setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4))
                    .setCertificateNotBefore(start.getTime())
                    .setCertificateNotAfter(end.getTime())
                    .setAttestationChallenge(attestationChallenge.getBytes())
                    .build());
    keyPairGenerator.generateKeyPair();

    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");

    keyStore.load(null);

    Certificate cert = keyStore.getCertificate(alias);
    Log.d(TAG,cert.toString());
}
</code>```

When I execute in a device with a Secure Hardware (TEE) it creates the cert as expected, but when I execute in a device whithout TEE or in emulator it logs the following:

```<code>Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 1 (0x1)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: CN=Android Keymaster
        Validity
            Not Before: Jan  1 00:00:00 1970 GMT
            Not After : Dec 31 23:59:59 1969 GMT
        Subject: CN=A Keymaster Key
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (1024 bit)
                Modulus:
                    00:8c:d1:bf:0e:22:ea:62:ad:e6:6d:9c:41:5c:d6:
                    f1:a1:17:6a:e4:e2:12:f7:45:21:70:ef:c0:c5:d7:
                    18:41:35:9c:42:c4:c6:11:48:0a:2d:97:a4:2a:54:
                    a0:7f:01:61:22:2e:2b:df:76:99:6c:e1:84:b9:ad:
                    f5:97:65:a7:f9:2b:bf:97:32:f8:b1:f2:06:3b:2b:
                    67:cb:ff:28:e4:1b:74:01:47:e9:91:0b:41:ec:17:
                    fe:4a:b4:3a:f5:0c:db:9b:fa:f3:c1:ef:e0:f5:bf:
                    e8:37:f9:b2:23:86:96:c4:50:5d:64:ba:b7:1b:61:
                    3f:65:54:2f:39:9b:d4:98:91
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Key Usage:
                Key Encipherment, Data Encipherment
            1.3.6.1.4.1.11129.2.1.17:
                0b...
.....
....test-cert-challenge..0..=........+L0...1.................H........w.....>......?...
            X509v3 Authority Key Identifier:
                keyid:D4:0C:10:1B:F8:CD:63:B9:F7:39:52:B5:0E:13:5C:A6:D7:99:93:86

    Signature Algorithm: sha256WithRSAEncryption
         40:79:42:eb:a2:22:e7:e5:95:8f:98:c8:de:35:80:b5:7b:fe:
         20:19:00:39:5b:59:3a:49:e0:10:06:c4:c4:a1:3e:52:69:7a:
         09:7b:39:67:28:3c:6a:94:96:9e:86:72:58:51:d9:96:0e:a8:
         1a:d9:d9:bf:24:6f:79:58:28:a5:1a:7d:14:ae:32:04:9c:e4:
         bf:1b:80:d3:4a:85:c2:e0:ab:b3:2c:b9:10:b2:ad:b2:36:00:
         68:eb:1b:52:85:b6:d0:0c:93:d5:bc:a5:35:1a:0c:02:a6:af:
         86:ee:2c:92:ef:25:5e:56:99:77:4f:72:8a:80:1a:54:33:1f:
         78:98
</code>```

As you can see the dates in Not Before and Not After are not as expected.

Does anybody know what could be the reason?

答:
Hy,
I tried you're code locally and had the same results as you already told. I also tried to manipulate the start and end dates to get:

```<code>java.lang.IllegalArgumentException: certificateNotAfter < certificateNotBefore
        at android.security.keystore.KeyGenParameterSpec.<init>(KeyGenParameterSpec.java:328)
        at android.security.keystore.KeyGenParameterSpec$Builder.build(KeyGenParameterSpec.java:1340)
        at org.chickenhook.binderfuzzy.MainActivity.createRSAKeyPairtWithChallenge(MainActivity.kt:47)
        at org.chickenhook.binderfuzzy.MainActivity.onCreate(MainActivity.kt:28)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
</code>```

This just tells us that you're params are set correctly and correctly interpreted by the Android OS also on non TEE devices.

Also I checked the Android documentation and found out that not all Keystore implementations may care about start and end date in a "secure manner" (https://developer.android.com/training/articles/keystore).

"Temporal validity interval authorizations are unlikely to be enforced by the secure hardware because it normally doesn't have an independent secure real-time clock. "

This doesn't answer you're question deterministic but tells that not all environments care about time validity because it's just not "secure". So it's better to give no time validity in order to tell there is no security for it rather than to meme validation time that doesn't really help.

Please consider that 23:59:59 1969 etc. means time_t notBefore(time_t)-1 and the 1970 means time_t notAfter=(time_t)0. So I beleve they disabled the validity but it's required that notebefore < notAfter.

However this not a deterministic answer, still searching for documentation explaining this issue in detail :(.

Body:
I've created the following method that creates a KeyPair and logs the Certificate details:

@RequiresApi(api = Build.VERSION_CODES.N)
public void createRSAKeyPairtWithChallenge(final String alias, final String attestationChallenge) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyStoreException, CertificateException, IOException {
    Calendar start = Calendar.getInstance();
    Calendar end = new GregorianCalendar(2025,03,24);
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
    keyPairGenerator.initialize(
            new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_DECRYPT)
                    .setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4))
                    .setCertificateNotBefore(start.getTime())
                    .setCertificateNotAfter(end.getTime())
                    .setAttestationChallenge(attestationChallenge.getBytes())
                    .build());
    keyPairGenerator.generateKeyPair();

    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");

    keyStore.load(null);

    Certificate cert = keyStore.getCertificate(alias);
    Log.d(TAG,cert.toString());
}

When I execute in a device with a Secure Hardware (TEE) it creates the cert as expected, but when I execute in a device whithout TEE or in emulator it logs the following:

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 1 (0x1)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: CN=Android Keymaster
        Validity
            Not Before: Jan  1 00:00:00 1970 GMT
            Not After : Dec 31 23:59:59 1969 GMT
        Subject: CN=A Keymaster Key
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (1024 bit)
                Modulus:
                    00:8c:d1:bf:0e:22:ea:62:ad:e6:6d:9c:41:5c:d6:
                    f1:a1:17:6a:e4:e2:12:f7:45:21:70:ef:c0:c5:d7:
                    18:41:35:9c:42:c4:c6:11:48:0a:2d:97:a4:2a:54:
                    a0:7f:01:61:22:2e:2b:df:76:99:6c:e1:84:b9:ad:
                    f5:97:65:a7:f9:2b:bf:97:32:f8:b1:f2:06:3b:2b:
                    67:cb:ff:28:e4:1b:74:01:47:e9:91:0b:41:ec:17:
                    fe:4a:b4:3a:f5:0c:db:9b:fa:f3:c1:ef:e0:f5:bf:
                    e8:37:f9:b2:23:86:96:c4:50:5d:64:ba:b7:1b:61:
                    3f:65:54:2f:39:9b:d4:98:91
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Key Usage:
                Key Encipherment, Data Encipherment
            1.3.6.1.4.1.11129.2.1.17:
                0b...
.....
....test-cert-challenge..0..=........+L0...1.................H........w.....>......?...
            X509v3 Authority Key Identifier:
                keyid:D4:0C:10:1B:F8:CD:63:B9:F7:39:52:B5:0E:13:5C:A6:D7:99:93:86

    Signature Algorithm: sha256WithRSAEncryption
         40:79:42:eb:a2:22:e7:e5:95:8f:98:c8:de:35:80:b5:7b:fe:
         20:19:00:39:5b:59:3a:49:e0:10:06:c4:c4:a1:3e:52:69:7a:
         09:7b:39:67:28:3c:6a:94:96:9e:86:72:58:51:d9:96:0e:a8:
         1a:d9:d9:bf:24:6f:79:58:28:a5:1a:7d:14:ae:32:04:9c:e4:
         bf:1b:80:d3:4a:85:c2:e0:ab:b3:2c:b9:10:b2:ad:b2:36:00:
         68:eb:1b:52:85:b6:d0:0c:93:d5:bc:a5:35:1a:0c:02:a6:af:
         86:ee:2c:92:ef:25:5e:56:99:77:4f:72:8a:80:1a:54:33:1f:
         78:98

As you can see the dates in Not Before and Not After are not as expected.

Does anybody know what could be the reason?

Body:
Hy,
I tried you're code locally and had the same results as you already told. I also tried to manipulate the start and end dates to get:

java.lang.IllegalArgumentException: certificateNotAfter < certificateNotBefore
        at android.security.keystore.KeyGenParameterSpec.<init>(KeyGenParameterSpec.java:328)
        at android.security.keystore.KeyGenParameterSpec$Builder.build(KeyGenParameterSpec.java:1340)
        at org.chickenhook.binderfuzzy.MainActivity.createRSAKeyPairtWithChallenge(MainActivity.kt:47)
        at org.chickenhook.binderfuzzy.MainActivity.onCreate(MainActivity.kt:28)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

This just tells us that you're params are set correctly and correctly interpreted by the Android OS also on non TEE devices.

Also I checked the Android documentation and found out that not all Keystore implementations may care about start and end date in a "secure manner" (https://developer.android.com/training/articles/keystore).

"Temporal validity interval authorizations are unlikely to be enforced by the secure hardware because it normally doesn't have an independent secure real-time clock. "

This doesn't answer you're question deterministic but tells that not all environments care about time validity because it's just not "secure". So it's better to give no time validity in order to tell there is no security for it rather than to meme validation time that doesn't really help.

Please consider that 23:59:59 1969 etc. means time_t notBefore(time_t)-1 and the 1970 means time_t notAfter=(time_t)0. So I beleve they disabled the validity but it's required that notebefore < notAfter.

However this not a deterministic answer, still searching for documentation explaining this issue in detail :(.


问:
Make modal fade in/out using ng-bootstrap modal Angular 2+
I am using Angular 4 with ng-bootstrap as shown here

I am trying to get the modal to slide and fade in/out, but there are no examples provided to do that. I have tried both solutions on this thread, such as opening my modal like so with a custom class 'slideInUp' -

this.modalService.open(content, {centered: true, backdrop: 'static', keyboard: false, windowClass:'slideInUp'}).result.then((result) => {
        this.closeResult = `Closed with: ${result}`;
      }, (reason) => {
        this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
      })```
</div>
</div>
</p>

<p>And adding the css for the 'slideInUp' -</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slideInUp {
  -webkit-animation-name: slideInUp;
  animation-name: slideInUp;
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  }
  @-webkit-keyframes slideInUp {
  0% {
  -webkit-transform: translateY(100%);
  transform: translateY(100%);
  visibility: visible;
  }
  100% {
  -webkit-transform: translateY(0);
  transform: translateY(0);
  }
  }
  @keyframes slideInUp {
  0% {
  -webkit-transform: translateY(100%);
  transform: translateY(100%);
  visibility: visible;
  }
  100% {
  -webkit-transform: translateY(0);
  transform: translateY(0);
  }
  } </code>```

The class gets applied, but the transition does not happen. Strangely, if I apply the slideInUp class to any other element, such as the body element of the modal, it works and body content slides up when the modal is opened.

Any help would be appreciated.

答:
Check to see if you have the following on your 'modal-dialog' div from Chrome DevTools.

```<code>@media (prefers-reduced-motion: reduce)
</code>```

If your operating system preferences are to limit animation, this could override your efforts to animate.

Body:
I am using Angular 4 with ng-bootstrap as shown here

I am trying to get the modal to slide and fade in/out, but there are no examples provided to do that. I have tried both solutions on this thread, such as opening my modal like so with a custom class 'slideInUp' -

this.modalService.open(content, {centered: true, backdrop: 'static', keyboard: false, windowClass:'slideInUp'}).result.then((result) => {
        this.closeResult = `Closed with: ${result}`;
      }, (reason) => {
        this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
      })

And adding the css for the 'slideInUp' -

.slideInUp {
  -webkit-animation-name: slideInUp;
  animation-name: slideInUp;
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  }
  @-webkit-keyframes slideInUp {
  0% {
  -webkit-transform: translateY(100%);
  transform: translateY(100%);
  visibility: visible;
  }
  100% {
  -webkit-transform: translateY(0);
  transform: translateY(0);
  }
  }
  @keyframes slideInUp {
  0% {
  -webkit-transform: translateY(100%);
  transform: translateY(100%);
  visibility: visible;
  }
  100% {
  -webkit-transform: translateY(0);
  transform: translateY(0);
  }
  }

The class gets applied, but the transition does not happen. Strangely, if I apply the slideInUp class to any other element, such as the body element of the modal, it works and body content slides up when the modal is opened.

Any help would be appreciated.

Body:
Check to see if you have the following on your 'modal-dialog' div from Chrome DevTools.

@media (prefers-reduced-motion: reduce)

If your operating system preferences are to limit animation, this could override your efforts to animate.


问:
php: how to use strip_tags with UTF8?
```<code>echo $src;
</code>```

gives:

```<code>4960 MALMEDY
</code>```

Then when I apply echo strip_tags($src);

gives me:

```<code>4960Â MALMEDY
</code>```

The SPACE was replaced by Â character:

What Do I do wrong ?

It looks that if I use

$src = utf8_decode($src); strip_tags works correctly.

Any rule I should know when to apply utf8_decode ?

答:
Try:

header('Content-type: text/plain; charset=utf-8');
```

Title: php: how to use strip_tags with UTF8?

Body:
echo $src;

gives:

4960 MALMEDY

Then when I apply echo strip_tags($src);

gives me:

4960Â MALMEDY

The SPACE was replaced by Â character:

What Do I do wrong ?

It looks that if I use

$src = utf8_decode($src); strip_tags works correctly.

Any rule I should know when to apply utf8_decode ?


问:
Match by group in R without replacement
I have a data set of ~20,000 cases and ~50,000 controls. Each case has been preliminarily matched with 3 controls using a join process in SQL that asked for an exact match on some covariates (e.g., a binary variable for whether the person was enrolled in the study in 2019) and allowed a match within a range for other covariates (e.g., total days enrolled within +/- 25 days). A control could thus be listed as a possible control for more than one case.

In R, I would like to select the control for each case from each case's 3 possible matches while ensuring two things: 1) controls are not repeated, and 2) for cases for which there is no exact match, that the control is matched as closely as possible on the covariates.

I think the approach I need is to group the data by the case_id and select the control_id from each group where the difference between the covariates is minimized. The wrinkle is that I need to ensure that once a control has been selected for a case in one group, it cannot be used as the control for a second case, no matter how good the covariate match is.

Here is some sample data:

```<code>case_id <- c(1,1,1,2,2,2,3,3,3,4,4,4)
control_id <- c(5,14,7,8,9,10,11,12,13,14,15,5)
case_enrolled_2019 <- c(1,1,1,0,0,0,0,0,0,1,1,1)
control_enrolled_2019 <- c(1,1,1,0,0,0,0,0,0,1,1,1)
case_enrollment_count <- c(1,1,1,3,3,3,1,1,1,1,1,1)
control_enrollment_count <- c(2,1,1,3,3,3,1,1,1,1,1,2)
case_enrolled_days <- c(300,300,300,200,200,200,600,600,600,300,300,300)
control_enrolled_days <- c(300,300,280,200,200,210,601,610,598,300,301,300)

cbind(case_id, control_id, case_enrolled_2019, control_enrolled_2019, case_enrollment_count, control_enrollment_count, case_enrolled_days, control_enrolled_days)
</code>```

I need output like:

```<code>case_id <- c(1,2,3,4)
control_id <- c(14,8,11,15)
case_enrolled_2019 <- c(1,0,0,1)
control_enrolled_2019 <- c(1,0,0,1)
case_enrollment_count <- c(1,3,1,1)
control_enrollment_count <- c(1,3,1,1)
case_enrolled_days <- c(300,200,600,300)
control_enrolled_days <- c(300,200,601,301)

cbind(case_id, control_id, case_enrolled_2019, control_enrolled_2019, case_enrollment_count, control_enrollment_count, case_enrolled_days, control_enrolled_days)

</code>```

答:
Here's a solution. It's slow because it has to loop through each case, compute the distance between it and each control unit in its block that hasn't already been matched, and then choose the nearest. Using a replicated version of this dataset with 72000 rows, it takes my computer 183 seconds. You could use parallelization to speed it up.

The first step is to create a dataset with an entry for each unique row (including control units that were initially matched with more than one treated each time) as if they were their own unit. There is probably a more elegant and generalizable way to do this, but honestly it works fine here.

 df2 <- setNames(as.data.frame(rbind(cbind(1, unique(df[,c(1,1,3,5,7)])),
                                     cbind(0, df[,c(1,2,4,6,8)]))),
                 c("cc", "block", "id", "enrolled_2019", "enrollment_count", "enrolled_days"))

head(df2)
#>   cc block id enrolled_2019 enrollment_count enrolled_days
#> 1  1     1  1             1                1           300
#> 2  1     2  2             0                3           200
#> 3  1     3  3             0                1           600
#> 4  1     4  4             1                1           300
#> 5  0     1  5             1                2           300
#> 6  0     1 14             1                1           300
```

<p>This leaves us with a dataset with 6 columns: the first <code>cc</code> is whether the unit is a case (1) or control (0). The second <code>block</code> is which initial matched block each unit is a part of. The third <code>id</code> is the unit's ID. The others are the variable values.</p>

<p>Next, we initialize the IDs of the cases and controls to match, and add a column to <code>df2</code> containing whether each unit was matched or not. This is important for ensuring two rows that correspond to the same control ID are not both matched.</p>

<pre class="lang-r prettyprint-override"><code>cases <- unique(df2$id[df2$cc == 1])
controls <- rep(NA, length(cases))
df2$matched <- FALSE
</code>```

Next we loop through each case and find its match. In the loop, we first ensure there are any available control units for the case. If not, we skip the case and it remains unmatched. If so, we compute the distance between it and the remaining control units in the block using match_on from the optmatch package. This just creates a distance matrix with one row for each case and a column for each control. In this case, we have one case and at most three controls. We take the value with the minimum distance and find the control ID it corresponds to and store it in the controls vector. We also make sure to mark as "matched" any rows in df2 with the same ID so the control unit isn't reused.

for (i in seq_along(cases)) {
    if (any(df2$block==cases[i] & !df2$matched)) {
        dist <- optmatch::match_on(cc ~ enrolled_2019 + enrollment_count + enrolled_days,
                                   data = df2[df2$block==cases[i] & !df2$matched,])
        controls[i] <- df2$id[as.numeric(colnames(dist)[which.min(dist)])]
        df2$matched[df2$id == controls[i]] <- TRUE
    }
}
```

<p>Finally we extract the pairs from the matched controls. We use <code>na.omit</code> in case there are unmatched cases, which are discarded.</p>

<pre class="lang-r prettyprint-override"><code>(pairs <- na.omit(data.frame(cases, controls)))
#>   cases controls
#> 1     1       14
#> 2     2        8
#> 3     3       11
#> 4     4       15

matched_df <- df[interaction(df[,1], df[,2]) %in% interaction(pairs[,1], pairs[,2]),]
</code>```

Created on 2020-05-28 by the reprex package (v0.3.0)

Title: Match by group in R without replacement

Body:
I have a data set of ~20,000 cases and ~50,000 controls. Each case has been preliminarily matched with 3 controls using a join process in SQL that asked for an exact match on some covariates (e.g., a binary variable for whether the person was enrolled in the study in 2019) and allowed a match within a range for other covariates (e.g., total days enrolled within +/- 25 days). A control could thus be listed as a possible control for more than one case.

In R, I would like to select the control for each case from each case's 3 possible matches while ensuring two things: 1) controls are not repeated, and 2) for cases for which there is no exact match, that the control is matched as closely as possible on the covariates.

I think the approach I need is to group the data by the case_id and select the control_id from each group where the difference between the covariates is minimized. The wrinkle is that I need to ensure that once a control has been selected for a case in one group, it cannot be used as the control for a second case, no matter how good the covariate match is.

Here is some sample data:

case_id <- c(1,1,1,2,2,2,3,3,3,4,4,4)
control_id <- c(5,14,7,8,9,10,11,12,13,14,15,5)
case_enrolled_2019 <- c(1,1,1,0,0,0,0,0,0,1,1,1)
control_enrolled_2019 <- c(1,1,1,0,0,0,0,0,0,1,1,1)
case_enrollment_count <- c(1,1,1,3,3,3,1,1,1,1,1,1)
control_enrollment_count <- c(2,1,1,3,3,3,1,1,1,1,1,2)
case_enrolled_days <- c(300,300,300,200,200,200,600,600,600,300,300,300)
control_enrolled_days <- c(300,300,280,200,200,210,601,610,598,300,301,300)

cbind(case_id, control_id, case_enrolled_2019, control_enrolled_2019, case_enrollment_count, control_enrollment_count, case_enrolled_days, control_enrolled_days)

I need output like:

case_id <- c(1,2,3,4)
control_id <- c(14,8,11,15)
case_enrolled_2019 <- c(1,0,0,1)
control_enrolled_2019 <- c(1,0,0,1)
case_enrollment_count <- c(1,3,1,1)
control_enrollment_count <- c(1,3,1,1)
case_enrolled_days <- c(300,200,600,300)
control_enrolled_days <- c(300,200,601,301)

cbind(case_id, control_id, case_enrolled_2019, control_enrolled_2019, case_enrollment_count, control_enrollment_count, case_enrolled_days, control_enrolled_days)

Body:
Here's a solution. It's slow because it has to loop through each case, compute the distance between it and each control unit in its block that hasn't already been matched, and then choose the nearest. Using a replicated version of this dataset with 72000 rows, it takes my computer 183 seconds. You could use parallelization to speed it up.

The first step is to create a dataset with an entry for each unique row (including control units that were initially matched with more than one treated each time) as if they were their own unit. There is probably a more elegant and generalizable way to do this, but honestly it works fine here.

 df2 <- setNames(as.data.frame(rbind(cbind(1, unique(df[,c(1,1,3,5,7)])),
                                     cbind(0, df[,c(1,2,4,6,8)]))),
                 c("cc", "block", "id", "enrolled_2019", "enrollment_count", "enrolled_days"))

head(df2)
#>   cc block id enrolled_2019 enrollment_count enrolled_days
#> 1  1     1  1             1                1           300
#> 2  1     2  2             0                3           200
#> 3  1     3  3             0                1           600
#> 4  1     4  4             1                1           300
#> 5  0     1  5             1                2           300
#> 6  0     1 14             1                1           300

This leaves us with a dataset with 6 columns: the first cc is whether the unit is a case (1) or control (0). The second block is which initial matched block each unit is a part of. The third id is the unit's ID. The others are the variable values.

Next, we initialize the IDs of the cases and controls to match, and add a column to df2 containing whether each unit was matched or not. This is important for ensuring two rows that correspond to the same control ID are not both matched.

cases <- unique(df2$id[df2$cc == 1])
controls <- rep(NA, length(cases))
df2$matched <- FALSE

Next we loop through each case and find its match. In the loop, we first ensure there are any available control units for the case. If not, we skip the case and it remains unmatched. If so, we compute the distance between it and the remaining control units in the block using match_on from the optmatch package. This just creates a distance matrix with one row for each case and a column for each control. In this case, we have one case and at most three controls. We take the value with the minimum distance and find the control ID it corresponds to and store it in the controls vector. We also make sure to mark as "matched" any rows in df2 with the same ID so the control unit isn't reused.

for (i in seq_along(cases)) {
    if (any(df2$block==cases[i] & !df2$matched)) {
        dist <- optmatch::match_on(cc ~ enrolled_2019 + enrollment_count + enrolled_days,
                                   data = df2[df2$block==cases[i] & !df2$matched,])
        controls[i] <- df2$id[as.numeric(colnames(dist)[which.min(dist)])]
        df2$matched[df2$id == controls[i]] <- TRUE
    }
}

Finally we extract the pairs from the matched controls. We use na.omit in case there are unmatched cases, which are discarded.

(pairs <- na.omit(data.frame(cases, controls)))
#>   cases controls
#> 1     1       14
#> 2     2        8
#> 3     3       11
#> 4     4       15

matched_df <- df[interaction(df[,1], df[,2]) %in% interaction(pairs[,1], pairs[,2]),]

Created on 2020-05-28 by the reprex package (v0.3.0)


问:
How to print the even-indexed and odd-indexed characters of strings?
Task at hand:

Given a string, S, of length N that is indexed from 0 to N-1, print
  its even-indexed and odd-indexed characters as 2 space-separated
  strings on a single line.

The test cases are written such that The first line contains an
  integer, N (the number of test cases). Each line i of the N subsequent
  lines contain a String.

Here is my code:

```<code>N = int(raw_input())

for i in range(0,N):
    string = raw_input()

evenlist = []
oddlist = []

for item, char in enumerate(strg):
    if item % 2 == 0:
        evenlist.append(char)
    else:
        oddlist.append(char)

print ''.join(evenlist), ''.join(oddlist)
</code>```

Sample run:

The first input is:
2
Hacker
Rank

Expected output is:
Hce akr
Rn ak
```

<p>But I get:</p>

<pre class="lang-none prettyprint-override"><code>HceRn akrak
</code>```

Here is a link to the assignment that might explain the question better.

答:
```<code>t = int(input())
for i in range(t):
    s = input()
    idx = 0
    newstr = ''
    newstr2 = ''
    for letter in s:
        if idx % 2 == 0:
            newstr = newstr + s[idx]
        else:
            newstr2 = newstr2 + s[idx]
        idx += 1
    print(newstr, newstr2)
</code>```

Body:
Task at hand:

Given a string, S, of length N that is indexed from 0 to N-1, print
  its even-indexed and odd-indexed characters as 2 space-separated
  strings on a single line.

The test cases are written such that The first line contains an
  integer, N (the number of test cases). Each line i of the N subsequent
  lines contain a String.

Here is my code:

N = int(raw_input())

for i in range(0,N):
    string = raw_input()

evenlist = []
oddlist = []

for item, char in enumerate(strg):
    if item % 2 == 0:
        evenlist.append(char)
    else:
        oddlist.append(char)

print ''.join(evenlist), ''.join(oddlist)

Sample run:

The first input is:
2
Hacker
Rank

Expected output is:
Hce akr
Rn ak

But I get:

HceRn akrak

Here is a link to the assignment that might explain the question better.


问:
How to change toolbar back button icon in android material components
I would like to change the default navigate up icon (back button icon) to my custom icon. I not using a drawer, just a simple toolbar and material components

Is this possible?

答:
If you are using a Toolbar to change the icon just use:

```<code>Toolbar toolbar = findViewById(R.id.xxx);
toolbar.setNavigationIcon(R.drawable.xxxx4);
setSupportActionBar(toolbar);
</code>```

If you are using the ActionBar you can use:

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxx);
</code>```

You can also change it overriding in your app theme the homeAsUpIndicator attribute:

```<code>  <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
    <item name="homeAsUpIndicator">@drawable/...</item>
  </style>
</code>```

If you are using the Navigation Components, currently there isn't a way to customize the HomeAsUpIndicator icon, and it is an expected behavior with the Up button displayed when you are on a non-root destination.

There is a workaround adding an addOnDestinationChangedListener after your setup method and checking the destination.

Something like:

```<code>navController.addOnDestinationChangedListener(
        new NavController.OnDestinationChangedListener() {
            @Override
            public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
                if (destination.getId() == R.id.nav_xxx) {
                    //With ActionBar
                    //getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxxx);

                    //With a Toolbar
                    toolbar.setNavigationIcon(R.drawable.xxxx);
                }
            }
        });
</code>```

Body:
If you are using a Toolbar to change the icon just use:

Toolbar toolbar = findViewById(R.id.xxx);
toolbar.setNavigationIcon(R.drawable.xxxx4);
setSupportActionBar(toolbar);

If you are using the ActionBar you can use:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxx);

You can also change it overriding in your app theme the homeAsUpIndicator attribute:

  <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
    <item name="homeAsUpIndicator">@drawable/...</item>
  </style>

If you are using the Navigation Components, currently there isn't a way to customize the HomeAsUpIndicator icon, and it is an expected behavior with the Up button displayed when you are on a non-root destination.

There is a workaround adding an addOnDestinationChangedListener after your setup method and checking the destination.

Something like:

navController.addOnDestinationChangedListener(
        new NavController.OnDestinationChangedListener() {
            @Override
            public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
                if (destination.getId() == R.id.nav_xxx) {
                    //With ActionBar
                    //getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxxx);

                    //With a Toolbar
                    toolbar.setNavigationIcon(R.drawable.xxxx);
                }
            }
        });