问:
Angular: Swiper carousel is not working - Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts
I am trying to create a carousel in angular using swiper (https://swiperjs.com/angular).

I get this error:

Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not satisfy the constraint '(...args: any) => any'.
Type '((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ... 75 more ... | undefined' is not assignable to type '(...args: any) => any'.
Type 'undefined' is not assignable to type '(...args: any) => any'.

I have tried this:

-Uninstall and install again swiper with npm i swiper

-Uninstall swiper and install it again with npm i @types/swiper

Here is my code:

angular.json

```<code>    "styles": [
      "src/myTheme.scss",
      "src/styles.css",
      "node_modules/swiper/swiper-bundle.min.css"
    ],
    "scripts": ["node_modules/swiper/swiper-bundle.min.js"]
  },
</code>```

The shared module

```<code>import { SwiperModule } from 'swiper/angular';
  exports: [
    SwiperModule,
    other modules
  ]
</code>```

the component:

```<code>  config: SwiperOptions = {
    slidesPerView: 3,
    spaceBetween: 50,
    navigation: true,
    pagination: { clickable: true },
    scrollbar: { draggable: true },
  };

//in the methods
  onSwiper([swiper]) {
    console.log(swiper);
  }
  onSlideChange() {
    console.log('slide change');
  }
</code>```

the HTLM

```<code><swiper
      [config]="config"
      (swiper)="onSwiper($event)"
      (slideChange)="onSlideChange()"
    >
  <ng-template swiperSlide>Slide 1</ng-template>
  <ng-template swiperSlide>Slide 2</ng-template>
  <ng-template swiperSlide>Slide 3</ng-template>
  <ng-template swiperSlide>Slide 4</ng-template>
  <ng-template swiperSlide>Slide 5</ng-template>
  <ng-template swiperSlide>Slide 6</ng-template>
</swiper>
</code>```

does sb have an idea of what is hapenning??
Thanks

答:
I had exactly the same issue. Installing v7 solved the issue.</p>
```<code>npm i swiper@7
</code>```

Body:
I am trying to create a carousel in angular using swiper (https://swiperjs.com/angular).

I get this error:

Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not satisfy the constraint '(...args: any) => any'.
Type '((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ... 75 more ... | undefined' is not assignable to type '(...args: any) => any'.
Type 'undefined' is not assignable to type '(...args: any) => any'.

I have tried this:

-Uninstall and install again swiper with npm i swiper

-Uninstall swiper and install it again with npm i @types/swiper

Here is my code:

angular.json

    "styles": [
      "src/myTheme.scss",
      "src/styles.css",
      "node_modules/swiper/swiper-bundle.min.css"
    ],
    "scripts": ["node_modules/swiper/swiper-bundle.min.js"]
  },

The shared module

import { SwiperModule } from 'swiper/angular';
  exports: [
    SwiperModule,
    other modules
  ]

the component:

  config: SwiperOptions = {
    slidesPerView: 3,
    spaceBetween: 50,
    navigation: true,
    pagination: { clickable: true },
    scrollbar: { draggable: true },
  };

//in the methods
  onSwiper([swiper]) {
    console.log(swiper);
  }
  onSlideChange() {
    console.log('slide change');
  }

the HTLM

<swiper
      [config]="config"
      (swiper)="onSwiper($event)"
      (slideChange)="onSlideChange()"
    >
  <ng-template swiperSlide>Slide 1</ng-template>
  <ng-template swiperSlide>Slide 2</ng-template>
  <ng-template swiperSlide>Slide 3</ng-template>
  <ng-template swiperSlide>Slide 4</ng-template>
  <ng-template swiperSlide>Slide 5</ng-template>
  <ng-template swiperSlide>Slide 6</ng-template>
</swiper>

does sb have an idea of what is hapenning??
Thanks

Body:
I had exactly the same issue. Installing v7 solved the issue.

npm i swiper@7


来源: stackexchange

问:
How to set up a NIST 800-171 compliant environment for CUI
I work for a very small company (12 people maybe) that is sub on a small fed contract and is currently strapped for cash after the ending of another contract about 6 months back. Despite having no experience with this, my company has assigned me to develop the System Security Plan (SSP) and implement a system that is NIST 800-171 compliant for handling CUI. While we don't need to handle ITAR or need CMMC cert, that may be helpful to open doors in the future and I thought the solution provided here in very limited detail seemed ideal since it leaves out personal equipment: https://www.ktlsolutions.com/cloud-based-solutions-for-meeting-cmmc-requirements/ . Unfortunately, we cannot afford the consulting fee for help with this, and, additionally, if I know what I'm doing, I imagine this just takes a few clicks and config settings in Azure Government to implement. I have an Azure Government trial account. My question is two fold: for one, is there any reason to think that me with some Azure Commercial experience won't be able to set this up myself and, 2, where do I begin? Are there any guides available? I have done ten thousand Google searches of various things in the past week and it feels like the only way I can find answers is to pay a huge consulting fee. Any help would be greatly appreciated.</p>

答: You'll want to look at Azure Blueprints. Azure Blueprints provides a set of Azure Policies that will ensure that your subscription meets the NIST 800-171 guidance. See this article for more info on the NIST 800-171 blueprint: https://learn.microsoft.com/en-us/azure/governance/blueprints/samples/nist-sp-800-171-r2</p>

ContentLicense: CC BY-SA 4.0


问:
Css height:0 undocumented property?
i have main grid with 2 columns. grid take 1 fr height.
In right column i want create scrolled div with take all height.

We all know that flex dont overflow need apply min-height/min-width: 0;

But i 2 hour try apply all combination for stop height overflow. And what did i find ?
min-height dont give nothing in my example. But i miss click and write rule height:0 and overflow stopped! what is magic ? I didnt find nothing in google about it undocumented property!

```<code><div class="min-h-screen bg-teal-200 flex flex-col">
  <div class="h-20 bg-indigo-400">header</div>

    <div class="flex-grow grid grid-cols-[300px_1fr] grid-rows-1 bg-green-200">
      <div>left short content</div>
      <div class="flex flex-col">
        <div class="flex-grow bg-rose-300 overflow-y-scroll min-h-0 h-0">
              <div class="h-60 border border-black"></div>
              <div class="h-60 border border-black"></div>
              <div class="h-60 border border-black"></div>
              <div class="h-60 border border-black"></div>
              <div class="h-60 border border-black"></div>
              <div class="h-60 border border-black"></div>
        </div>
      </div>
    </div>

  <div class="h-20 bg-indigo-400">footer</div>
</div>
</code>```

sandbox:
https://play.tailwindcss.com/3fyrMQK6Me

答:
By making the element h-0 it will have a height equal to 0 thus it won't contribute to the dimension of the grid (it's like it doesn't exist). Later it will grow to fill the space with the flex-grow

If you want to work with min-height you have to do is to consider h-screen instead of min-h-screen then min-h-0 on the second child element. You have to also disable the shrinking on header and footer:

header

left short content

footer

```
</div>
</div>
</p>
<p>You can also simplify like below:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.tailwindcss.com"></script>
<div class="h-screen bg-teal-200 grid grid-cols-[300px_1fr] grid-rows-[auto_1fr_auto]">
  <div class="h-20 bg-indigo-400 col-span-2">header</div>
  <div class="bg-green-200">left short content</div>
  <div class="bg-rose-300 overflow-y-scroll">
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
  </div>
  <div class="h-20 bg-indigo-400 col-span-2">footer</div>
</div></code>```

Title: Css height:0 undocumented property?

Body:
i have main grid with 2 columns. grid take 1 fr height.
In right column i want create scrolled div with take all height.

We all know that flex dont overflow need apply min-height/min-width: 0;

But i 2 hour try apply all combination for stop height overflow. And what did i find ?
min-height dont give nothing in my example. But i miss click and write rule height:0 and overflow stopped! what is magic ? I didnt find nothing in google about it undocumented property!

header

left short content

footer

sandbox:
https://play.tailwindcss.com/3fyrMQK6Me

Body:
By making the element h-0 it will have a height equal to 0 thus it won't contribute to the dimension of the grid (it's like it doesn't exist). Later it will grow to fill the space with the flex-grow

If you want to work with min-height you have to do is to consider h-screen instead of min-h-screen then min-h-0 on the second child element. You have to also disable the shrinking on header and footer:

<script src="https://cdn.tailwindcss.com"></script>
<div class="h-screen bg-teal-200 flex flex-col">
  <div class="h-20 flex-shrink-0 bg-indigo-400">header</div>
  <div class="flex-grow grid grid-cols-[300px_1fr] grid-rows-1 bg-green-200 min-h-0">
    <div>left short content</div>
    <div class="flex flex-col">
      <div class="flex-grow bg-rose-300 overflow-y-scroll">
        <div class="h-60 border border-black"></div>
        <div class="h-60 border border-black"></div>
        <div class="h-60 border border-black"></div>
        <div class="h-60 border border-black"></div>
        <div class="h-60 border border-black"></div>
        <div class="h-60 border border-black"></div>
      </div>
    </div>
  </div>
  <div class="h-20 flex-shrink-0 bg-indigo-400">footer</div>
</div>

You can also simplify like below:

<script src="https://cdn.tailwindcss.com"></script>
<div class="h-screen bg-teal-200 grid grid-cols-[300px_1fr] grid-rows-[auto_1fr_auto]">
  <div class="h-20 bg-indigo-400 col-span-2">header</div>
  <div class="bg-green-200">left short content</div>
  <div class="bg-rose-300 overflow-y-scroll">
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
    <div class="h-60 border border-black"></div>
  </div>
  <div class="h-20 bg-indigo-400 col-span-2">footer</div>
</div>


问:
Android newbie - debugging app on physical device
I was trying to debug my code on a physical device instead of an emulator. In order to do this after a series of steps I finally plugged in my device only to see that "Samsung_Android" and "CDC serial" drivers are missing.

It seems very odd for these drivers to be missing. What am I doing wrong, any suggestions ?

Thanks in advance for your help.

答: Do you have kies installed? Go to C:\Program Files\Samsung\Kies (or whatever folder) and look for a folder named USB driver. Instal the executable inside, make sure kies is not running and connect the phone to the computer. It should work just fine</p>

ContentLicense: CC BY-SA 3.0


问:
React Material UI extremely slows VSCode autocompletion with TS
Importing the "@mui/material" will stuck the VSCode - so TS warnings will come up after 10-15s instead of less than 10ms, for example:

```<code>import { Button } from '@mui/material'
// and make a use with this button.
</code>```

Then:

```<code>new Date(). // will show the autocomplion very slow
</code>```

If you remove the import of that button, or any module from this package, everything works great again.

答:
To import components, use path imports instead of top-level imports:

// ❌ top-level imports
// import { Box, Typography } from '@mui/material'

// ✅ path imports
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'
```

This will speed up Typescript autocompletion.

Body:
Importing the "@mui/material" will stuck the VSCode - so TS warnings will come up after 10-15s instead of less than 10ms, for example:

import { Button } from '@mui/material'
// and make a use with this button.

Then:

new Date(). // will show the autocomplion very slow

If you remove the import of that button, or any module from this package, everything works great again.

Body:
To import components, use path imports instead of top-level imports:

// ❌ top-level imports
// import { Box, Typography } from '@mui/material'

// ✅ path imports
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'

This will speed up Typescript autocompletion.


问:
Is Linear Binary Search an over optimization of standard Binary Search
In understanding that Binary Search only works if the List you are searching is sorted, the assumption is that you maintain a sorted list if you are going to Search many times in an application. Searching linearly, 0(n), will always be faster than sorting and then searching, 0(nlog(n)) + log(n).

However, in my research I found that, for small datasets, a linear search, 0(n) is faster than a logarithmic search 0(log(n)). It's recommended in a book I am reading that when searching a dataset with less than 20 items a linear search performs better than a binary search due to overhead in the binary implementation. (Programming and Problem Solving with C++ 6th Edition)

A noticeable optimization to Merge Sort and Quick Sort implements a cutoff value which switches to Insertion sort when the list size becomes small enough... 15 or so items.

Could something similar be done to Binary Search... Is there a noticeable difference in performance if you were to implement a cutoff to a linear search when the size of the list becomes small enough... 20 or so items...

Binary Search Implementation:

```<code>int BinarySearch(std::vector<int>& values, const int key) {
    int iLo = 0; int iHi = values.size() - 1;
    int iMid = (iHi + iLo) / 2;

    while(iLo <= iHi) {
        if (key < values[iMid])
            iHi = iMid - 1;
        else if (key > values[iMid])
            iLo = iMid + 1;
        else
            return iMid;

        iMid = (iHi + iLo) / 2;
    }
    return -1;
}
</code>```

Binary Search with Linear Cutoff:

```<code>int LinearBinarySearch(std::vector<int>& values, const int key) {
    int iLo = 0; int iHi = values.size() - 1;
    int iMid = (iHi + iLo) / 2;

    while (iLo <= iHi) {
        if(iMid == key)
            return iMid;

        //Perform Linear Search When List Size is less than Cutoff
        if (iHi - iLo < CUTOFF) {//Linear Search Performs better on List Size < 20 or so...
        for (int i = iLo; i <= iHi; i++) {
            if (values[i] == key)
                return i;
        }
            return -1;
        }

        else if (key < values[iMid])
            iHi = iMid - 1;
        else
            iLo = iMid + 1;

        iMid = (iHi + iLo) / 2;
    }
    return -1;
}
</code>```

I populated the Sorted List to be Searched:

```<code>for (int i = 0; i < SIZE; i++) {
    values.push_back(i);
}
</code>```

Then timed the Search of 10 million items in the List with both Implementations of Binary Search and took the average runtime of each Implementation...

The result on average was .000001 seconds per search for both Implementations showing that this cutoff only complicated the Binary Search and had no performance benefits...

I would like to note that testing for equality on different data, such as strings, in the Linear Binary Search implementation may make a standard Binary Search faster, as the standard Binary Search does not test for equality. (This is an assumption that I have not tested)

I guess the question still remains... Why implement a Linear Search over a Binary Search on small sorted data sets when Binary Search is not that complicated and is extremely scalable? Can Someone give an example...

答:
The goal of Linear Binary Search is not to return the middle index where the value is stored, which is what Binary Search does. The goal is to position the hi and lo indices until they meet the cutoff range where it will finish the searching task Linearly. Understanding that in cases of small data sets, a linear search is faster than a binary search.

The question naturally becomes how small does a data set have to be for linear search to outperform binary search in a sorted list.

Given a list of 15 sorted values - We have a list of 10 million keys - we need to see if each key is in the list of values...

Compare the algorithms:

Linear Binary Search with Cutoff at 4

```<code>int LinearBinarySearch(const std::vector<int>& values, const int key) {
    int iLo = 0; int iHi = values.size() - 1;
    int iMid = (iHi + iLo) / 2;

    while (iLo <= iHi) {
        //Perform Linear Search When List Size is less than Cutoff
        if (iHi - iLo < CUTOFF) {//Linear Search Performs better on List Size < 20 or so...
            for (int i = iLo; i <= iHi; i++) {
                if (values[i] == key)
                    return i;
            }
            return -1;
        }
        else if (key < values[iMid])
            iHi = iMid;
        else
            iLo = iMid;

        iMid = (iHi + iLo) / 2;
    }
    return -1;
}
</code>```

Binary Search:

```<code>int BinarySearch(const std::vector<int>& values, const int key) {
    int iLo = 0; int iHi = values.size() - 1;
    int iMid = (iHi + iLo) / 2;

    while(iLo <= iHi) {
        if (key < values[iMid])
            iHi = iMid - 1;
        else if (key > values[iMid])
            iLo = iMid + 1;
        else
            return iMid;

        iMid = (iHi + iLo) / 2;
    }
    return -1;
}
</code>```

Linear Search:

```<code>int LinearSearch(const std::vector<int>& values, const int key) {
    for (int i = 0; i < values.size(); i++) {
        if (values[i] == key)
            return i;
    }
    return -1;
}
</code>```

Total runtime for each Algorithm to finish task:

Linear Search:   5.24367 Seconds

Binary Search:   2.43401 Seconds

Linear Binary Search Cutoff 4:   2.21329 Seconds

Note: I started the cutoff value at 20 (less than 20 was recommended in a book I am reading) - it was a second slower than binary search... So I changed the cutoff value until the optimal performance increase was found... CUTOFF = 4... (iHi - iLo) < 4 do linear search.

My first inclination as to why the cutoff mentioned in the book I am reading has such a loose upper bound is that computing power and architecture change over time... this may be incorrect, but the fact remains that we must test our cutoffs when implementing them to find the most optimal cutoff value... To be exact, the book states, "small data sets, say less than 20" - which again implies a test for the most optimal value.

Another example of testing for the most optimal cutoff is implementing a Merge or Quick Sort with a Cutoff to Insertion Sort. The cutoff value I found most optimal using Binary Insertion Sort was 15.

Since Linear Binary Search worked well with ranges of size 3 (cutoff 4) I decided to give Linear Search another go with a sorted values list of 3 elements and 10 million key values to search for.

Linear Search:   2.0799 Seconds

Binary Search:   1.95746 Seconds

Linear Binary Search with Cutoff 4:   1.87101 Seconds

It should be noted that I do not understand at this time how caching etc. works... my expectation on a list of 3 sorted values was that the linear algorithm would outperform both Binary and Linear Binary Searching algorithms due to their overhead, however it did not. I will have to take a look at the Assembly, when I get a better grasp of the language... Visual Studio Community 2019 IDE

I would argue, based on these test runs, that Linear Binary Search is a worthy Optimization to Binary Search due to its increased performance and ease of implementation. (Personally, I may forget to shift to the left or right of the middle index when positioning the Hi or Lo indices, but I wont forget how to write a linear searching algorithm... hopefully...)

One Last Test: 10 million values - 100 million keys

Binary Search:   81.5836 Seconds

Linear Binary Search with Cutoff 4:   54.1304 Seconds

Honestly, unless shown different, I will always implement Linear Binary Search over Binary Search when Searching a sorted list of any size due to increased performance and ease of implementation.

thanks @463035818_is_not_a_number for the help!! I'll leave my last comment to you for humilities sake :) I was wrong... In taking only the average runtime for each search, while excluding the total runtime for all searches, I was losing time... time adds up.

Body:
In understanding that Binary Search only works if the List you are searching is sorted, the assumption is that you maintain a sorted list if you are going to Search many times in an application. Searching linearly, 0(n), will always be faster than sorting and then searching, 0(nlog(n)) + log(n).

However, in my research I found that, for small datasets, a linear search, 0(n) is faster than a logarithmic search 0(log(n)). It's recommended in a book I am reading that when searching a dataset with less than 20 items a linear search performs better than a binary search due to overhead in the binary implementation. (Programming and Problem Solving with C++ 6th Edition)

A noticeable optimization to Merge Sort and Quick Sort implements a cutoff value which switches to Insertion sort when the list size becomes small enough... 15 or so items.

Could something similar be done to Binary Search... Is there a noticeable difference in performance if you were to implement a cutoff to a linear search when the size of the list becomes small enough... 20 or so items...

Binary Search Implementation:

int BinarySearch(std::vector<int>& values, const int key) {
    int iLo = 0; int iHi = values.size() - 1;
    int iMid = (iHi + iLo) / 2;

    while(iLo <= iHi) {
        if (key < values[iMid])
            iHi = iMid - 1;
        else if (key > values[iMid])
            iLo = iMid + 1;
        else
            return iMid;

        iMid = (iHi + iLo) / 2;
    }
    return -1;
}

Binary Search with Linear Cutoff:

int LinearBinarySearch(std::vector<int>& values, const int key) {
    int iLo = 0; int iHi = values.size() - 1;
    int iMid = (iHi + iLo) / 2;

    while (iLo <= iHi) {
        if(iMid == key)
            return iMid;

        //Perform Linear Search When List Size is less than Cutoff
        if (iHi - iLo < CUTOFF) {//Linear Search Performs better on List Size < 20 or so...
        for (int i = iLo; i <= iHi; i++) {
            if (values[i] == key)
                return i;
        }
            return -1;
        }

        else if (key < values[iMid])
            iHi = iMid - 1;
        else
            iLo = iMid + 1;

        iMid = (iHi + iLo) / 2;
    }
    return -1;
}

I populated the Sorted List to be Searched:

for (int i = 0; i < SIZE; i++) {
    values.push_back(i);
}

Then timed the Search of 10 million items in the List with both Implementations of Binary Search and took the average runtime of each Implementation...

The result on average was .000001 seconds per search for both Implementations showing that this cutoff only complicated the Binary Search and had no performance benefits...

I would like to note that testing for equality on different data, such as strings, in the Linear Binary Search implementation may make a standard Binary Search faster, as the standard Binary Search does not test for equality. (This is an assumption that I have not tested)

I guess the question still remains... Why implement a Linear Search over a Binary Search on small sorted data sets when Binary Search is not that complicated and is extremely scalable? Can Someone give an example...

Body:
The goal of Linear Binary Search is not to return the middle index where the value is stored, which is what Binary Search does. The goal is to position the hi and lo indices until they meet the cutoff range where it will finish the searching task Linearly. Understanding that in cases of small data sets, a linear search is faster than a binary search.

The question naturally becomes how small does a data set have to be for linear search to outperform binary search in a sorted list.

Given a list of 15 sorted values - We have a list of 10 million keys - we need to see if each key is in the list of values...

Compare the algorithms:

Linear Binary Search with Cutoff at 4

int LinearBinarySearch(const std::vector<int>& values, const int key) {
    int iLo = 0; int iHi = values.size() - 1;
    int iMid = (iHi + iLo) / 2;

    while (iLo <= iHi) {
        //Perform Linear Search When List Size is less than Cutoff
        if (iHi - iLo < CUTOFF) {//Linear Search Performs better on List Size < 20 or so...
            for (int i = iLo; i <= iHi; i++) {
                if (values[i] == key)
                    return i;
            }
            return -1;
        }
        else if (key < values[iMid])
            iHi = iMid;
        else
            iLo = iMid;

        iMid = (iHi + iLo) / 2;
    }
    return -1;
}

Binary Search:

int BinarySearch(const std::vector<int>& values, const int key) {
    int iLo = 0; int iHi = values.size() - 1;
    int iMid = (iHi + iLo) / 2;

    while(iLo <= iHi) {
        if (key < values[iMid])
            iHi = iMid - 1;
        else if (key > values[iMid])
            iLo = iMid + 1;
        else
            return iMid;

        iMid = (iHi + iLo) / 2;
    }
    return -1;
}

Linear Search:

int LinearSearch(const std::vector<int>& values, const int key) {
    for (int i = 0; i < values.size(); i++) {
        if (values[i] == key)
            return i;
    }
    return -1;
}

Total runtime for each Algorithm to finish task:

Linear Search:   5.24367 Seconds

Binary Search:   2.43401 Seconds

Linear Binary Search Cutoff 4:   2.21329 Seconds

Note: I started the cutoff value at 20 (less than 20 was recommended in a book I am reading) - it was a second slower than binary search... So I changed the cutoff value until the optimal performance increase was found... CUTOFF = 4... (iHi - iLo) < 4 do linear search.

My first inclination as to why the cutoff mentioned in the book I am reading has such a loose upper bound is that computing power and architecture change over time... this may be incorrect, but the fact remains that we must test our cutoffs when implementing them to find the most optimal cutoff value... To be exact, the book states, "small data sets, say less than 20" - which again implies a test for the most optimal value.

Another example of testing for the most optimal cutoff is implementing a Merge or Quick Sort with a Cutoff to Insertion Sort. The cutoff value I found most optimal using Binary Insertion Sort was 15.

Since Linear Binary Search worked well with ranges of size 3 (cutoff 4) I decided to give Linear Search another go with a sorted values list of 3 elements and 10 million key values to search for.

Linear Search:   2.0799 Seconds

Binary Search:   1.95746 Seconds

Linear Binary Search with Cutoff 4:   1.87101 Seconds

It should be noted that I do not understand at this time how caching etc. works... my expectation on a list of 3 sorted values was that the linear algorithm would outperform both Binary and Linear Binary Searching algorithms due to their overhead, however it did not. I will have to take a look at the Assembly, when I get a better grasp of the language... Visual Studio Community 2019 IDE

I would argue, based on these test runs, that Linear Binary Search is a worthy Optimization to Binary Search due to its increased performance and ease of implementation. (Personally, I may forget to shift to the left or right of the middle index when positioning the Hi or Lo indices, but I wont forget how to write a linear searching algorithm... hopefully...)

One Last Test: 10 million values - 100 million keys

Binary Search:   81.5836 Seconds

Linear Binary Search with Cutoff 4:   54.1304 Seconds

Honestly, unless shown different, I will always implement Linear Binary Search over Binary Search when Searching a sorted list of any size due to increased performance and ease of implementation.

thanks @463035818_is_not_a_number for the help!! I'll leave my last comment to you for humilities sake :) I was wrong... In taking only the average runtime for each search, while excluding the total runtime for all searches, I was losing time... time adds up.


问:
Asymptote can not create label
I am making my first steps with the vector program asymptote (https://asymptote.sourceforge.io). During my first tutorials I already encounter an error: I can't put any labels. The following code works fine:

```<code>draw((0,0) -- (2,2));
</code>```

however, if I add a label:

```<code>draw((0,0) -- (2,2));
label("x", (1,1));
</code>```

the following error message occurs:

```<code>asy -globalwrite -f pdf -o "test.pdf" "test.asy"
    pic.addBox(position,position,min(f),max(f));
              ^
C:\Program Files\MiKTeX/asymptote/plain_Label.asy: 321.15: runtime:
</code>```

As you can see I am using a Windows (10) operating system with a MiKTeX installation. The version of Asymptote included in it is:

```<code>asy --version
miktex-asy version 2.69 [(C) 2004 Andy Hammerlindl, John C. Bowman, Tom Prince]

ENABLED OPTIONS:
WebGL    3D HTML rendering
OpenGL   3D OpenGL rendering
CURL     URL support

DISABLED OPTIONS:
GSL      GNU Scientific Library (special functions)
FFTW3    Fast Fourier transforms
XDR      external data representation (portable binary file format)
Readline interactive history and editing
Editline interactive editing (if Readline is unavailable)
Sigsegv  distinguish stack overflows from segmentation faults
GC       Boehm garbage collector
</code>```

Can someone help me to fix the error? The error message is rather useless. Any help would be appreciated!

答: After some research I found out that the version of Asymptote provided by MiKTeX is not compatible with their own packages. The solution is actually quite simple: Get an official standalone from https://asymptote.sourceforge.io, then it will work.</p>

Title: Asymptote can not create label

Body:
I am making my first steps with the vector program asymptote (https://asymptote.sourceforge.io). During my first tutorials I already encounter an error: I can't put any labels. The following code works fine:

draw((0,0) -- (2,2));

however, if I add a label:

draw((0,0) -- (2,2));
label("x", (1,1));

the following error message occurs:

asy -globalwrite -f pdf -o "test.pdf" "test.asy"
    pic.addBox(position,position,min(f),max(f));
              ^
C:\Program Files\MiKTeX/asymptote/plain_Label.asy: 321.15: runtime:

As you can see I am using a Windows (10) operating system with a MiKTeX installation. The version of Asymptote included in it is:

asy --version
miktex-asy version 2.69 [(C) 2004 Andy Hammerlindl, John C. Bowman, Tom Prince]

ENABLED OPTIONS:
WebGL    3D HTML rendering
OpenGL   3D OpenGL rendering
CURL     URL support

DISABLED OPTIONS:
GSL      GNU Scientific Library (special functions)
FFTW3    Fast Fourier transforms
XDR      external data representation (portable binary file format)
Readline interactive history and editing
Editline interactive editing (if Readline is unavailable)
Sigsegv  distinguish stack overflows from segmentation faults
GC       Boehm garbage collector

Can someone help me to fix the error? The error message is rather useless. Any help would be appreciated!


问:
AppCompatImageView set background android 17
I have vector icon and use AppCompatImageView in XML

layout.xml

```<code><android.support.v7.widget.AppCompatImageView
            android:layout_width="16dp"
            android:layout_height="16dp"
            android:background="@drawable/ic_location"/>
</code>```

ic_location.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="28dp"
    android:viewportHeight="28"
    android:viewportWidth="25">
    <path
        android:fillColor="#00000000"
        android:fillType="evenOdd"
        android:pathData="M12.5107,11.0107m3.3369,0a3.3369,3.3369 0,1 0,-6.6738 0a3.3369,3.3369 0,1 0,6.6738 0"
        android:strokeColor="@color/mediumGray"
        android:strokeLineCap="square"
        android:strokeWidth="2" />
    <path
        android:fillColor="#00000000"
        android:fillType="evenOdd"
        android:pathData="M2.5,11.0107C2.5,16.5391 12.5107,26.861 12.5107,26.861C12.5107,26.861 22.5214,16.5391 22.5214,11.0107C22.5214,5.4819 18.0394,1 12.5107,1C6.9819,1 2.5,5.4819 2.5,11.0107Z"
        android:strokeColor="@color/mediumGray"
        android:strokeLineCap="square"
        android:strokeWidth="2" />
</vector>
</code>```

Log error

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    android.view.InflateException: Binary XML file line #61: Error inflating class <unknown>
        at android.view.LayoutInflater.createView(LayoutInflater.java:613)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
</code>```

it works on API 21 and above but not work on 17 API device.

when using app:srcCompat work but when use android:background app crash.

答:
You should add AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) to your activity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    setContentView(R.layout.activity_main)
}
```

After that, you can set the background programmatically. For example: image.setBackgroundResource(R.drawable.ic_circle)

Body:
I have vector icon and use AppCompatImageView in XML

layout.xml

<android.support.v7.widget.AppCompatImageView
            android:layout_width="16dp"
            android:layout_height="16dp"
            android:background="@drawable/ic_location"/>

ic_location.xml

<?xml version="1.0" encoding="UTF-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="28dp"
    android:viewportHeight="28"
    android:viewportWidth="25">
    <path
        android:fillColor="#00000000"
        android:fillType="evenOdd"
        android:pathData="M12.5107,11.0107m3.3369,0a3.3369,3.3369 0,1 0,-6.6738 0a3.3369,3.3369 0,1 0,6.6738 0"
        android:strokeColor="@color/mediumGray"
        android:strokeLineCap="square"
        android:strokeWidth="2" />
    <path
        android:fillColor="#00000000"
        android:fillType="evenOdd"
        android:pathData="M2.5,11.0107C2.5,16.5391 12.5107,26.861 12.5107,26.861C12.5107,26.861 22.5214,16.5391 22.5214,11.0107C22.5214,5.4819 18.0394,1 12.5107,1C6.9819,1 2.5,5.4819 2.5,11.0107Z"
        android:strokeColor="@color/mediumGray"
        android:strokeLineCap="square"
        android:strokeWidth="2" />
</vector>

Log error

E/AndroidRuntime: FATAL EXCEPTION: main
    android.view.InflateException: Binary XML file line #61: Error inflating class <unknown>
        at android.view.LayoutInflater.createView(LayoutInflater.java:613)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:396)

it works on API 21 and above but not work on 17 API device.

when using app:srcCompat work but when use android:background app crash.

Body:
You should add AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) to your activity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    setContentView(R.layout.activity_main)
}

After that, you can set the background programmatically. For example: image.setBackgroundResource(R.drawable.ic_circle)


问:
Google Maps - Looping through array for polyline
I want to loop through an array of coordinates that I want to use for markers and drawing a line in google maps.
Is there a solution to create the path property with a loop of const locations?

Please check my example below:

```<code>const lineSymbol = {
  path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
  strokeColor: "red",
      scale: 4
};

const locations = [
      ["Tampere", 61.50741562413278, 23.75886761967578,  1, "Termin: xx.xx"],
      ["Helsinki", 60.219957, 25.196776,  2, "test2"],
      ["Travemünde", 55.778989, 18.271974,  2, "test3"],
      ["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
      ["Ludwigsburg", 48.8893286910321,  9.197454231637288, 4, "test5"],
]

const line = new google.maps.Polyline({

    path: [
        { lat:  locations[0][1], lng: locations[0][2] },
        { lat:  60.219957, lng:  25.196776 },
        { lat:  locations[2][1], lng: locations[2][2] },
        { lat:  53.941362, lng:  10.860464 },
        { lat: 48.7733567672875, lng: 9.174572759931003 },
    ],
    strokeColor: "red",
        scale: 7,
    icons: [
        {
          icon: lineSymbol,
          offset: "100%",
        },
    ],
 map: map,
});
</code>```

By using above code it creates in Google Maps this:

The result

答:
To process your input array and create a polyline in a loop:

```<code>var path = [];
for (var i=0; i<locations.length; i++) {
  // add to polyline
  path.push({lat: locations[i][2], lng: locations[i][1]});
  // create marker
  new google.maps.Marker({
    position: path[path.length-1],
    map: map
  })
}
const line = new google.maps.Polyline({
    path: path,
    strokeColor: "red",
        scale: 7,
    icons: [
        {
          icon: lineSymbol,
          offset: "100%",
        },
    ],
 map: map,
});
</code>```

proof of concept fiddle

(note that the data in your question doesn't match your picture)

code snippet:

// This example creates a 2-pixel-wide red polyline showing the path of
// the first trans-Pacific flight between Oakland, CA, and Brisbane,
// Australia which was made by Charles Kingsford Smith.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 3,
    center: {
      lat: 0,
      lng: -180
    },
    mapTypeId: "terrain",
  });
  const lineSymbol = {
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
    strokeColor: "red",
    scale: 4
  };

  const locations = [
    ["Tampere", 61.50741562413278, 23.75886761967578, 1, "Termin: xx.xx"],
    ["Helsinki", 60.219957, 25.196776, 2, "test2"],
    ["Travemünde", 55.778989, 18.271974, 2, "test3"],
    ["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
    ["Ludwigsburg", 48.8893286910321, 9.197454231637288, 4, "test5"],
  ]
  var path = [];
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < locations.length; i++) {
    path.push({
      lat: locations[i][2],
      lng: locations[i][1]
    });
    bounds.extend(path[path.length - 1]);
    new google.maps.Marker({
      position: path[path.length - 1],
      map: map
    })

  }

  const line = new google.maps.Polyline({

    path: path,
    strokeColor: "red",
    scale: 7,
    icons: [{
      icon: lineSymbol,
      offset: "100%",
    }, ],
    map: map,
  });
  map.fitBounds(bounds);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

<!DOCTYPE html>

  <title>Simple Polylines</title>

```

Body:
I want to loop through an array of coordinates that I want to use for markers and drawing a line in google maps.
Is there a solution to create the path property with a loop of const locations?

Please check my example below:

const lineSymbol = {
  path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
  strokeColor: "red",
      scale: 4
};

const locations = [
      ["Tampere", 61.50741562413278, 23.75886761967578,  1, "Termin: xx.xx"],
      ["Helsinki", 60.219957, 25.196776,  2, "test2"],
      ["Travemünde", 55.778989, 18.271974,  2, "test3"],
      ["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
      ["Ludwigsburg", 48.8893286910321,  9.197454231637288, 4, "test5"],
]

const line = new google.maps.Polyline({

    path: [
        { lat:  locations[0][1], lng: locations[0][2] },
        { lat:  60.219957, lng:  25.196776 },
        { lat:  locations[2][1], lng: locations[2][2] },
        { lat:  53.941362, lng:  10.860464 },
        { lat: 48.7733567672875, lng: 9.174572759931003 },
    ],
    strokeColor: "red",
        scale: 7,
    icons: [
        {
          icon: lineSymbol,
          offset: "100%",
        },
    ],
 map: map,
});

By using above code it creates in Google Maps this:

The result

Body:
To process your input array and create a polyline in a loop:

var path = [];
for (var i=0; i<locations.length; i++) {
  // add to polyline
  path.push({lat: locations[i][2], lng: locations[i][1]});
  // create marker
  new google.maps.Marker({
    position: path[path.length-1],
    map: map
  })
}
const line = new google.maps.Polyline({
    path: path,
    strokeColor: "red",
        scale: 7,
    icons: [
        {
          icon: lineSymbol,
          offset: "100%",
        },
    ],
 map: map,
});

proof of concept fiddle

(note that the data in your question doesn't match your picture)

code snippet:

// This example creates a 2-pixel-wide red polyline showing the path of
// the first trans-Pacific flight between Oakland, CA, and Brisbane,
// Australia which was made by Charles Kingsford Smith.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 3,
    center: {
      lat: 0,
      lng: -180
    },
    mapTypeId: "terrain",
  });
  const lineSymbol = {
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
    strokeColor: "red",
    scale: 4
  };

  const locations = [
    ["Tampere", 61.50741562413278, 23.75886761967578, 1, "Termin: xx.xx"],
    ["Helsinki", 60.219957, 25.196776, 2, "test2"],
    ["Travemünde", 55.778989, 18.271974, 2, "test3"],
    ["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
    ["Ludwigsburg", 48.8893286910321, 9.197454231637288, 4, "test5"],
  ]
  var path = [];
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < locations.length; i++) {
    path.push({
      lat: locations[i][2],
      lng: locations[i][1]
    });
    bounds.extend(path[path.length - 1]);
    new google.maps.Marker({
      position: path[path.length - 1],
      map: map
    })

  }

  const line = new google.maps.Polyline({

    path: path,
    strokeColor: "red",
    scale: 7,
    icons: [{
      icon: lineSymbol,
      offset: "100%",
    }, ],
    map: map,
  });
  map.fitBounds(bounds);
}

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<!DOCTYPE html>
<html>

<head>
  <title>Simple Polylines</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>

  <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>

</html>


问:
Loop flow control
I have an array of objects, each object has a function that returns a Boolean value. What I need to do, is have a loop continuously running until each object returns a true value when the function is called on each object.

EDIT: Sorry I wasn't clear enough, I meant that I want the loop to break, when ALL of the objects functions return true.

Any ideas?

答:
Java style syntax:

```<code>boolean good;
while (true) {
    good = true;
    foreach (MyObject o : myArray) {
        if (!o.someFunction()) {
            good = false;
            break;
        }
    }
    if (good) break;
}
</code>```

I interpreted it as meaning that every object needed to have its function evaluated to true each time, and once they all evaluate to true break out of the loop.

Title: Loop flow control

Body:
Java style syntax:

boolean good;
while (true) {
    good = true;
    foreach (MyObject o : myArray) {
        if (!o.someFunction()) {
            good = false;
            break;
        }
    }
    if (good) break;
}

I interpreted it as meaning that every object needed to have its function evaluated to true each time, and once they all evaluate to true break out of the loop.


问:
Cannot list contents of db file in Xamarin
I want to create an easy quiz application that gets values from a .db file.

In my MainPage.xaml.cs I want to list all my questions (with just one answer option for testing,  from a database that is embedded and is implemented correctly for both platforms) in a list form just for now, but I get a white empty stuff without any error msg.

DataModels/Questions.cs

```<code>namespace quiztest.DataModels
{
    public class Questions
    {
        [PrimaryKey]
        public int ID { get; set; }
        public string Field{ get; set; }
        public string Question{ get; set; }
        public string Answer1 { get; set; }
        public string Answer2 { get; set; }
        public string Answer3 { get; set; }
        public string Answer4 { get; set; }
        public string CorrectAnswer { get; set; }
    }
}
</code>```

MainPage.xaml.cs

```<code>using quiztest.DataModels;

...

protected override void OnAppearing()
            {
                base.OnAppearing();
                using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
                {
                    var questions = conn.Table<Question>().ToList();
                    quizListView.ItemsSource = questions;

                }

            }
</code>```

MainPage.Xaml

```<code>        <StackLayout>
        <Label Text="Contents:"/>
        <Label x:Name="labelrandom"/>
        <ScrollView>
            <ListView x:Name="quizListView">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Question}" Detail="{Binding Answer1}" TextColor="Aquamarine"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </ScrollView>
    </StackLayout>
</code>```

I feel that the issue is related to getting the correct columns to show up on the textcell but I am just started learning and I am not an expert.

答:
Replace

```<code>var questions = conn.Table<Question>().ToList();
quizListView.ItemsSource = questions;
</code>```

with

```<code> var questions = (from x in conn.Table<Question>() select x).ToList();
 quizListView.ItemsSource = questions ;
</code>```

Body:
I want to create an easy quiz application that gets values from a .db file.

In my MainPage.xaml.cs I want to list all my questions (with just one answer option for testing,  from a database that is embedded and is implemented correctly for both platforms) in a list form just for now, but I get a white empty stuff without any error msg.

DataModels/Questions.cs

namespace quiztest.DataModels
{
    public class Questions
    {
        [PrimaryKey]
        public int ID { get; set; }
        public string Field{ get; set; }
        public string Question{ get; set; }
        public string Answer1 { get; set; }
        public string Answer2 { get; set; }
        public string Answer3 { get; set; }
        public string Answer4 { get; set; }
        public string CorrectAnswer { get; set; }
    }
}

MainPage.xaml.cs

using quiztest.DataModels;

...

protected override void OnAppearing()
            {
                base.OnAppearing();
                using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
                {
                    var questions = conn.Table<Question>().ToList();
                    quizListView.ItemsSource = questions;

                }

            }

MainPage.Xaml

        <StackLayout>

        <ScrollView>
            <ListView x:Name="quizListView">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Question}" Detail="{Binding Answer1}" TextColor="Aquamarine"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </ScrollView>
    </StackLayout>

I feel that the issue is related to getting the correct columns to show up on the textcell but I am just started learning and I am not an expert.

Body:
Replace

var questions = conn.Table<Question>().ToList();
quizListView.ItemsSource = questions;

with

 var questions = (from x in conn.Table<Question>() select x).ToList();
 quizListView.ItemsSource = questions ;


问:
How to echo group of arguments passed to a script, instead of each individual argument
I have this very basic script:

```<code>#!/bin/bash
for x in "$@"; do
  echo $x
done
</code>```

That when running it:

```<code>./script.sh qq ww ee rr tt yy uu ii oo pp
</code>```

The output will be an echo of each argument like this:

```<code>qq
ww
ee
rr
tt
yy
uu
ii
oo
pp
</code>```

How can I modify it to echo the arguments in a group of 4 or less (the last group), like this:

```<code>qq ww ee rr
tt yy uu ii
oo pp
</code>```

答:
You can use printf:

printf '%s %s %s %s\n' "$@"
```
```qq ww ee rr
tt yy uu ii
oo pp
```
<p><sup><strong>rematk:</strong> At the end of the last line you'll get a <code>space</code> character for each missing element</sup></p>
<hr />
<p>Or use a bash <em>substring expansion</em> to get each array slice:</p>
```#!/bin/bash

n=4
for (( i = 1; i <= $#; i += n ))
do
    echo "${@:i:n}"
done
```

Body:
I have this very basic script:

#!/bin/bash
for x in "$@"; do
  echo $x
done

That when running it:

./script.sh qq ww ee rr tt yy uu ii oo pp

The output will be an echo of each argument like this:

qq
ww
ee
rr
tt
yy
uu
ii
oo
pp

How can I modify it to echo the arguments in a group of 4 or less (the last group), like this:

qq ww ee rr
tt yy uu ii
oo pp

Body:
You can use printf:

printf '%s %s %s %s\n' "$@"

qq ww ee rr
tt yy uu ii
oo pp

rematk: At the end of the last line you'll get a space character for each missing element

Or use a bash substring expansion to get each array slice:

#!/bin/bash

n=4
for (( i = 1; i <= $#; i += n ))
do
    echo "${@:i:n}"
done


问:
Xml database in PHP
I need to use xml as database in php. Till now i used mssql,mysql as database in php. Is it possible to do so? </p>

答: Yes, actually in php5 this is very easy to implement.  http://devzone.zend.com/article/1713 for example.</p>

Title: Xml database in PHP


问:
How to use map inside map using docx npm (javascript)
I am trying to use map inside another map when creating a table for a word file using npm package docx.

The file is created, but when I try to open it in word it says that the file format is not supported. Everything works fine if I don't use the second map function so I know this is the problem.

This is what I have:

```<code>export const createTable = (items) => {
    let loopTables = items.map((item1) =>

                new Table({
                    columns: 5,
                    width: 0,
                    columnWidths: [2100, 1100, 1100, 1100, 1900],
                    layout: TableLayoutType.FIXED,
                    rows: [
                        new TableRow({
                            children: [
                                new TableCell({
                                    children: [new Paragraph({
                                        children: [
                                            new TextRun({
                                                text: `Main item ${item1[0].Group1}`,
                                            }),
                                        ]
                                    }),],
                                    columnSpan: 5,
                                }),
                            ],
                        }),
                        item1.map((item2) =>
                        new TableRow({
                            children: [
                                new TableCell({
                                    children: [new Paragraph({
                                        children: [
                                            new TextRun({
                                                text: `Nested item ${item2.Group2}`,
                                            }),
                                        ]
                                    }),],
                                    columnSpan: 5,
                                }),
                            ],
                        }),
                        )
                    ]
                }),
            )
            return loopTables
}
</code>```

loopTables is then inserted in another file like this:

```<code>{
                properties: {
                    type: SectionType.CONTINUOUS,
                },
                children: createTable(items) //Here we call the function that generates the table. It works fine without the nested map function.
            },
</code>```

Any idea whats wrong and what I should do to fix it?

答: Solved it by using two classic for loops instead. The rows was saved in two variables and then pushed togheter to an empty array. Don't know why the map didn't work though</p>

Body:
I am trying to use map inside another map when creating a table for a word file using npm package docx.

The file is created, but when I try to open it in word it says that the file format is not supported. Everything works fine if I don't use the second map function so I know this is the problem.

This is what I have:

export const createTable = (items) => {
    let loopTables = items.map((item1) =>

                new Table({
                    columns: 5,
                    width: 0,
                    columnWidths: [2100, 1100, 1100, 1100, 1900],
                    layout: TableLayoutType.FIXED,
                    rows: [
                        new TableRow({
                            children: [
                                new TableCell({
                                    children: [new Paragraph({
                                        children: [
                                            new TextRun({
                                                text: `Main item ${item1[0].Group1}`,
                                            }),
                                        ]
                                    }),],
                                    columnSpan: 5,
                                }),
                            ],
                        }),
                        item1.map((item2) =>
                        new TableRow({
                            children: [
                                new TableCell({
                                    children: [new Paragraph({
                                        children: [
                                            new TextRun({
                                                text: `Nested item ${item2.Group2}`,
                                            }),
                                        ]
                                    }),],
                                    columnSpan: 5,
                                }),
                            ],
                        }),
                        )
                    ]
                }),
            )
            return loopTables
}

loopTables is then inserted in another file like this:

{
                properties: {
                    type: SectionType.CONTINUOUS,
                },
                children: createTable(items) //Here we call the function that generates the table. It works fine without the nested map function.
            },

Any idea whats wrong and what I should do to fix it?


问:
Code undoes itself before returning value
```<code>from time import sleep
def refit(i, n, c=[]):
 sleep(1)
 print(c)
 if i[:n] != '': refit(i[n:],n,c+[i[:n]])
 sleep(1)
 print(c)
 return c
</code>```

Output when using arguments "Helloo" and 2:

```<code>[]
['He']
['He', 'll']
['He', 'll', 'oo']
['He', 'll', 'oo']
['He', 'll']
['He']
[]
[]
</code>```

The Array ['He', 'll', 'oo'] should be printed and returned, but the code is undoing itself.
What is happening? I am so confused.

答:
Within a given call to refit, you're not changing c, so c has the same value in the second print() that it does in the first print().  All the recursive calls happen in between those two print calls.

On the first call, c is []:

```<code># i = 'Helloo', n = 2, c = []
print(c)  # prints "[]"
if i[:n] != '':
    refit(i[n:],n,c+[i[:n]])  # prints a bunch of other stuff
print(c)  # prints "[]"
return c  # returns []
</code>```

On the second call to refit (indicated above by # prints a bunch of other stuff) we do:

```<code># i = 'lloo', n = 2, c = ['He']
print(c)  # prints "['He']"
if i[:n] != '':
    refit(i[n:],n,c+[i[:n]])  # prints even more stuff
print(c)  # prints "['He']"
return c  # returns ["He"]
</code>```

Our output so far looks like:

```<code>[]
['He']
(more stuff will go here)
['He']
[]
</code>```

And on and on -- each new recursive call adds another pair of print statements in the middle of the previous call.  And each call returns its original value of c, rather than the new value it got from the recursive call it just made to refit.

If you want this function to return the result from the innermost call, then it simply needs to return the result of calling refit:

```<code>def refit(i, n, c=[]):
    return refit(i[n:], n, c + [i[:n]]) if i[:n] else c

print(refit("Helloo", 2))  # ['He', 'll', 'oo']
</code>```

Body:
from time import sleep
def refit(i, n, c=[]):
 sleep(1)
 print(c)
 if i[:n] != '': refit(i[n:],n,c+[i[:n]])
 sleep(1)
 print(c)
 return c

Output when using arguments "Helloo" and 2:

[]
['He']
['He', 'll']
['He', 'll', 'oo']
['He', 'll', 'oo']
['He', 'll']
['He']
[]
[]

The Array ['He', 'll', 'oo'] should be printed and returned, but the code is undoing itself.
What is happening? I am so confused.

Body:
Within a given call to refit, you're not changing c, so c has the same value in the second print() that it does in the first print().  All the recursive calls happen in between those two print calls.

On the first call, c is []:

# i = 'Helloo', n = 2, c = []
print(c)  # prints "[]"
if i[:n] != '':
    refit(i[n:],n,c+[i[:n]])  # prints a bunch of other stuff
print(c)  # prints "[]"
return c  # returns []

On the second call to refit (indicated above by # prints a bunch of other stuff) we do:

# i = 'lloo', n = 2, c = ['He']
print(c)  # prints "['He']"
if i[:n] != '':
    refit(i[n:],n,c+[i[:n]])  # prints even more stuff
print(c)  # prints "['He']"
return c  # returns ["He"]

Our output so far looks like:

[]
['He']
(more stuff will go here)
['He']
[]

And on and on -- each new recursive call adds another pair of print statements in the middle of the previous call.  And each call returns its original value of c, rather than the new value it got from the recursive call it just made to refit.

If you want this function to return the result from the innermost call, then it simply needs to return the result of calling refit:

def refit(i, n, c=[]):
    return refit(i[n:], n, c + [i[:n]]) if i[:n] else c

print(refit("Helloo", 2))  # ['He', 'll', 'oo']


问:
Adding a new column,splitting a column value in two then insert a part of the value in the new column
I have a table with a column 'Name', like the following:

```<code>    Name
Michael Jackson
Chester Bennington
Mike Shinoda
</code>```

I want to split the 'Name' values in FirstName and LastName,blike this:

```<code>LastName          FirstName
Jackson          Michael
Bennington       Chester
Shinoda          Mike
</code>```

And also I need to create new columns and add those values, all in a single query if its possible.
So as a review, I have Name, I need to create LastName, FirstName columns, split the Name values after the first blank space,the value before the blank space will go into LastName and the values after the blank space will go into FirstName. This is what I have tried so far:

```<code>ALTER TABLE `data` ADD `FirstName` VARCHAR(30),ADD `LastName` VARCHAR(30)
INSERT INTO `data`(`LastName`,`FirstName`) VALUES ('...','...')
</code>```

Help please..

答:
INSTR shows error, so used POSITION. I am trying to split the columns at character '/':</p>
```<code>UPDATE pincode
   SET latitude = LEFT( coordinates, POSITION('/' IN coordinates) - 1 )
     , longitude = RIGHT( coordinates, LENGTH(coordinates) - POSITION('/' IN coordinates) )
 WHERE coordinates LIKE '%/%';
</code>```

Body:
I have a table with a column 'Name', like the following:

    Name
Michael Jackson
Chester Bennington
Mike Shinoda

I want to split the 'Name' values in FirstName and LastName,blike this:

LastName          FirstName
Jackson          Michael
Bennington       Chester
Shinoda          Mike

And also I need to create new columns and add those values, all in a single query if its possible.
So as a review, I have Name, I need to create LastName, FirstName columns, split the Name values after the first blank space,the value before the blank space will go into LastName and the values after the blank space will go into FirstName. This is what I have tried so far:

ALTER TABLE `data` ADD `FirstName` VARCHAR(30),ADD `LastName` VARCHAR(30)
INSERT INTO `data`(`LastName`,`FirstName`) VALUES ('...','...')

Help please..

Body:
INSTR shows error, so used POSITION. I am trying to split the columns at character '/':

UPDATE pincode
   SET latitude = LEFT( coordinates, POSITION('/' IN coordinates) - 1 )
     , longitude = RIGHT( coordinates, LENGTH(coordinates) - POSITION('/' IN coordinates) )
 WHERE coordinates LIKE '%/%';


问:
React - uncaught TypeError: Cannot read property 'setState' of undefined
I am getting the following error

Uncaught TypeError: Cannot read property 'setState' of undefined

even after binding delta in the constructor.

```<code>class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}
</code>```

答:
If anyone is looking for the same sulution when using axios, or any fetch or get, and using setState will return this error.

What you need to do, is to define the component outside, as so:

```<code>componentDidMount(){
  let currentComponent = this;
  axios.post(url, Qs.stringify(data))
     .then(function (response) {
          let data = response.data;
          currentComponent.setState({
             notifications : data.notifications
      })
   })
}
</code>```

Body:
I am getting the following error

Uncaught TypeError: Cannot read property 'setState' of undefined

even after binding delta in the constructor.

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (

{this.state.count}

                <button onClick={this.delta}>+</button>

        );
    }
}

Body:
If anyone is looking for the same sulution when using axios, or any fetch or get, and using setState will return this error.

What you need to do, is to define the component outside, as so:

componentDidMount(){
  let currentComponent = this;
  axios.post(url, Qs.stringify(data))
     .then(function (response) {
          let data = response.data;
          currentComponent.setState({
             notifications : data.notifications
      })
   })
}


问:
How to convert systemv startup scripts to systemd services?
Advice on converting SysVinit file to Systemd services will be helpful.

Currently, I am using a systemv init script which will be executed after every boot on my STM32MP1 based Avenger96 board. Now I have to switch to Systemd from SysVinit. But I am not sure how to convert the init file to relevant systemd files. I am using Yocto with Ubuntu20.04 as build system. If someone help me to get started would be really great. Below is the init script and image recipe which establishes symlink to the init script.

custom-script.sh which is installed in etc/init.d/ directory of the rootfs.

```<code>#!/bin/sh

DAEMON="swupdate"
PIDFILE="/var/run/$DAEMON.pid"

PART_STATUS=$(sgdisk -A 4:get:2 /dev/mmcblk0)
if test "${PART_STATUS}" = "4:2:1" ; then
    ROOTFS=rootfs-2
else
    ROOTFS=rootfs-1
fi

if test -f /update-ok ; then
    SURICATTA_ARGS="-c 2"
    rm -f /update-ok
fi

start() {
    printf 'Starting %s: ' "$DAEMON"
    # shellcheck disable=SC2086 # we need the word splitting
    start-stop-daemon -b -q -m -S -p "$PIDFILE" -x "/usr/bin/$DAEMON" \
        -- -f /etc/swupdate/swupdate.cfg -L -e rootfs,${ROOTFS} -u "${SURICATTA_ARGS}"
    status=$?
    if [ "$status" -eq 0 ]; then
        echo "OK"
    else
        echo "FAIL"
    fi
    return "$status"
}

stop() {
    printf 'Stopping %s: ' "$DAEMON"
    start-stop-daemon -K -q -p "$PIDFILE"
    status=$?
    if [ "$status" -eq 0 ]; then
        rm -f "$PIDFILE"
        echo "OK"
    else
        echo "FAIL"
    fi
    return "$status"
}

restart() {
    stop
    sleep 1
    start
}

case "$1" in
        start|stop|restart)
        "$1";;
    reload)
        # Restart, since there is no true "reload" feature.
        restart;;
        *)
                echo "Usage: $0 {start|stop|restart|reload}"
                exit 1
esac
</code>```

Image recipe which creates init.d dir and installs above script and also establishes symlink to rc4.d dir.

```<code>custom-image.bb
</code>```
```<code>.
.
inherit update-rc.d

SRC_URI = "file://custom-script.sh \
          "

S = "${WORKDIR}"

INITSCRIPT_PACKAGES = "${PN}"
INITSCRIPT_NAME = "custom-script.sh"
INITSCRIPT_PARAMS = "start 99 2 3 4 5 . "

do_install_append() {
    install -d ${D}${sysconfdir}/rc4.d
    install -d 644 ${D}${sysconfdir}/init.d
    install -m 0755 ${WORKDIR}/custom-script.sh ${D}${sysconfdir}/init.d
    ln -sf ../init.d/custom-script.sh ${D}${sysconfdir}/rc4.d/S99custom-script.sh
    ln -sf ../init.d/custom-script.sh ${D}${sysconfdir}/rc4.d/K99custom-script.sh
}

FILES_${PN} += "${sysconfdir}/init.d"
</code>```

Now I am trying to do the same functionality of custom-script.sh with systemd. Is it possible to make use of systemd-sysv-generator in this case?

Also, will the dir init.d completely removed once we switch to "systemd"? What will happen to other files which are present in etc/init.d?

Can anyone please help me get started?

Your help will be much appreciated.

Thanks in advance.

P.S: Please let me know if any info is missing here.

答:
/etc/init.d will not get deleted by using systemd

Have you checked /etc/systemd and /usr/lib/systemd on your Ubuntu machine for examples of systemd scripts. Along the manual pages of systemd, you should have enough examples to convert your sysv init script to systemd.

Body:
Advice on converting SysVinit file to Systemd services will be helpful.

Currently, I am using a systemv init script which will be executed after every boot on my STM32MP1 based Avenger96 board. Now I have to switch to Systemd from SysVinit. But I am not sure how to convert the init file to relevant systemd files. I am using Yocto with Ubuntu20.04 as build system. If someone help me to get started would be really great. Below is the init script and image recipe which establishes symlink to the init script.

custom-script.sh which is installed in etc/init.d/ directory of the rootfs.

#!/bin/sh

DAEMON="swupdate"
PIDFILE="/var/run/$DAEMON.pid"

PART_STATUS=$(sgdisk -A 4:get:2 /dev/mmcblk0)
if test "${PART_STATUS}" = "4:2:1" ; then
    ROOTFS=rootfs-2
else
    ROOTFS=rootfs-1
fi

if test -f /update-ok ; then
    SURICATTA_ARGS="-c 2"
    rm -f /update-ok
fi

start() {
    printf 'Starting %s: ' "$DAEMON"
    # shellcheck disable=SC2086 # we need the word splitting
    start-stop-daemon -b -q -m -S -p "$PIDFILE" -x "/usr/bin/$DAEMON" \
        -- -f /etc/swupdate/swupdate.cfg -L -e rootfs,${ROOTFS} -u "${SURICATTA_ARGS}"
    status=$?
    if [ "$status" -eq 0 ]; then
        echo "OK"
    else
        echo "FAIL"
    fi
    return "$status"
}

stop() {
    printf 'Stopping %s: ' "$DAEMON"
    start-stop-daemon -K -q -p "$PIDFILE"
    status=$?
    if [ "$status" -eq 0 ]; then
        rm -f "$PIDFILE"
        echo "OK"
    else
        echo "FAIL"
    fi
    return "$status"
}

restart() {
    stop
    sleep 1
    start
}

case "$1" in
        start|stop|restart)
        "$1";;
    reload)
        # Restart, since there is no true "reload" feature.
        restart;;
        *)
                echo "Usage: $0 {start|stop|restart|reload}"
                exit 1
esac

Image recipe which creates init.d dir and installs above script and also establishes symlink to rc4.d dir.

custom-image.bb

.
.
inherit update-rc.d

SRC_URI = "file://custom-script.sh \
          "

S = "${WORKDIR}"

INITSCRIPT_PACKAGES = "${PN}"
INITSCRIPT_NAME = "custom-script.sh"
INITSCRIPT_PARAMS = "start 99 2 3 4 5 . "

do_install_append() {
    install -d ${D}${sysconfdir}/rc4.d
    install -d 644 ${D}${sysconfdir}/init.d
    install -m 0755 ${WORKDIR}/custom-script.sh ${D}${sysconfdir}/init.d
    ln -sf ../init.d/custom-script.sh ${D}${sysconfdir}/rc4.d/S99custom-script.sh
    ln -sf ../init.d/custom-script.sh ${D}${sysconfdir}/rc4.d/K99custom-script.sh
}

FILES_${PN} += "${sysconfdir}/init.d"

Now I am trying to do the same functionality of custom-script.sh with systemd. Is it possible to make use of systemd-sysv-generator in this case?

Also, will the dir init.d completely removed once we switch to "systemd"? What will happen to other files which are present in etc/init.d?

Can anyone please help me get started?

Your help will be much appreciated.

Thanks in advance.

P.S: Please let me know if any info is missing here.


问:
R: Return a vector using %in% operator
I have a vector with delimiters and I want to generate a vector of the same length with boolean values based on whether or not one of the delimited values contains what I am after. I cannot find a way to do this neatly in vector-based logic. As an example:

```<code>x <- c('a', 'a; b', 'ab; c', 'b; c', 'c; a', 'c')
</code>```

Using some magic asking whether 'a' %in% x, I want to get the vector:

```<code>TRUE, TRUE, FALSE, FALSE, TRUE, FALSE
</code>```

I initially tried the following:

```<code>'a' %in% trimws(strsplit(x, ';'))
</code>```

But this unexpectedly collapses the entire list and returns TRUE, rather than a vector, since one of the elements in x is 'a'. Is there a way to get the vector I am looking for without rewriting the code into a for-loop?

答:
You can read each item separately with scan, trim leading and trailing WS as you attempted, and test each resulting character vector in turn with:

```<code> sapply(x, function(x){"a" %in% trimws( scan( text=x, what="",sep=";", quiet=TRUE))})
    a  a; b ab; c  b; c  c; a     c
 TRUE  TRUE FALSE FALSE  TRUE FALSE
</code>```

The top row of the result is just the names and would not affect a logical test that depended on this result. There is an unname function if needed.

Title: R: Return a vector using %in% operator

Body:
I have a vector with delimiters and I want to generate a vector of the same length with boolean values based on whether or not one of the delimited values contains what I am after. I cannot find a way to do this neatly in vector-based logic. As an example:

x <- c('a', 'a; b', 'ab; c', 'b; c', 'c; a', 'c')

Using some magic asking whether 'a' %in% x, I want to get the vector:

TRUE, TRUE, FALSE, FALSE, TRUE, FALSE

I initially tried the following:

'a' %in% trimws(strsplit(x, ';'))

But this unexpectedly collapses the entire list and returns TRUE, rather than a vector, since one of the elements in x is 'a'. Is there a way to get the vector I am looking for without rewriting the code into a for-loop?

Body:
You can read each item separately with scan, trim leading and trailing WS as you attempted, and test each resulting character vector in turn with:

 sapply(x, function(x){"a" %in% trimws( scan( text=x, what="",sep=";", quiet=TRUE))})
    a  a; b ab; c  b; c  c; a     c
 TRUE  TRUE FALSE FALSE  TRUE FALSE

The top row of the result is just the names and would not affect a logical test that depended on this result. There is an unname function if needed.


问:
How to make docker container connect everything through proxy
I know it is possible to pass http_proxy and https_proxy environment variables to a container as shown in eg. this SO answer. However, this only works for proxy-aware commands like wget and curl as they merely read and use these environment variables.

I need to connect everything through the proxy, so that all internet access is routed via the proxy. Essentially, the proxy should be transformed into a kind of VPN.

I am thinking about something similar to the --net=container option where the container gets its network from another container.

How do I configure a container to run everything through the proxy?

答:
You can use the proxy env var:

```<code>docker container run \
  -e HTTP_PROXY=http://username:password@proxy2.domain.com \
  -e HTTPS_PROXY=http://username:password@proxy2.domain.com \
 yourimage
</code>```

If you want the proxy-server to be automatically used when starting a container, you can configure default proxy-servers in the Docker CLI configuration file (~/.docker/config.json). You can find instructions for this in the networking section in the user guide

for exemple :

```<code>{
  "proxies": {
    "default": {
      "httpProxy": "http://username:password@proxy2.domain.com",
      "httpsProxy": "http://username:password@proxy2.domain.com"
    }
  }
}
</code>```

To verify if the ~/.docker/config.json configuration is working, start a container and print its env:

```<code>docker container run --rm busybox env

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=220e4df13604
HTTP_PROXY=http://username:password@proxy2.domain.com
http_proxy=http://username:password@proxy2.domain.com
HTTPS_PROXY=http://username:password@proxy2.domain.com
https_proxy=http://username:password@proxy2.domain.com
HOME=/root
</code>```

Body:
You can use the proxy env var:

docker container run \
  -e HTTP_PROXY=http://username:password@proxy2.domain.com \
  -e HTTPS_PROXY=http://username:password@proxy2.domain.com \
 yourimage

If you want the proxy-server to be automatically used when starting a container, you can configure default proxy-servers in the Docker CLI configuration file (~/.docker/config.json). You can find instructions for this in the networking section in the user guide

for exemple :

{
  "proxies": {
    "default": {
      "httpProxy": "http://username:password@proxy2.domain.com",
      "httpsProxy": "http://username:password@proxy2.domain.com"
    }
  }
}

To verify if the ~/.docker/config.json configuration is working, start a container and print its env:

docker container run --rm busybox env

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=220e4df13604
HTTP_PROXY=http://username:password@proxy2.domain.com
http_proxy=http://username:password@proxy2.domain.com
HTTPS_PROXY=http://username:password@proxy2.domain.com
https_proxy=http://username:password@proxy2.domain.com
HOME=/root


问:
How does Scalaz `F[_] : Applicative` type constraint imply use of implicit parameters?
I am struggling to understand the following function definition in Traverse trait in Scalaz:

def traverse[F[_] : Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]]

The part I don't understand is F[_] : Applicative.

Now, let's see what Applicative is:

```<code>trait Applicative[Z[_]] extends Pointed[Z] with Apply[Z] {
  override def fmap[A, B](fa: Z[A], f: A => B): Z[B] = this(pure(f), fa)
  override def apply[A, B](f: Z[A => B], a: Z[A]): Z[B] = liftA2(f, a, (_:A => B)(_: A))
  def liftA2[A, B, C](a: Z[A], b: Z[B], f: (A, B) => C): Z[C] = apply(fmap(a, f.curried), b)
}
</code>```

Here, for traverse to work for some type F, one needs to bring an implicit object of type Applicative[F] in scope.

I'd like to understand several things:

Wat exactly does F[_] : Applicative mean?

Why does F[_] has something to do with Applicative? We need Applicative[F], not F[something] extends Applicative right?

Why does this method use implicit values of type Applicative[F] without declaring implicit parameters?

答:
I think all three questions can be answered with the fact that this notation:

```<code>def traverse[F[_] : Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]]
</code>```

is equivalent to this:

```<code>def traverse[F[_], A, B](f: A => F[B], t: T[A])(implicit $ev: Applicative[F]): F[T[B]]
</code>```

The first notation is known as a context bound for F[_].

Body:
I am struggling to understand the following function definition in Traverse trait in Scalaz:

def traverse[F[_] : Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]]

The part I don't understand is F[_] : Applicative.

Now, let's see what Applicative is:

trait Applicative[Z[_]] extends Pointed[Z] with Apply[Z] {
  override def fmap[A, B](fa: Z[A], f: A => B): Z[B] = this(pure(f), fa)
  override def apply[A, B](f: Z[A => B], a: Z[A]): Z[B] = liftA2(f, a, (_:A => B)(_: A))
  def liftA2[A, B, C](a: Z[A], b: Z[B], f: (A, B) => C): Z[C] = apply(fmap(a, f.curried), b)
}

Here, for traverse to work for some type F, one needs to bring an implicit object of type Applicative[F] in scope.

I'd like to understand several things:

Wat exactly does F[_] : Applicative mean?

Why does F[_] has something to do with Applicative? We need Applicative[F], not F[something] extends Applicative right?

Why does this method use implicit values of type Applicative[F] without declaring implicit parameters?

Body:
I think all three questions can be answered with the fact that this notation:

def traverse[F[_] : Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]]

is equivalent to this:

def traverse[F[_], A, B](f: A => F[B], t: T[A])(implicit $ev: Applicative[F]): F[T[B]]

The first notation is known as a context bound for F[_].


问:
Convert JSON to array with nlohmann/json
I've not used C++ in over 20 years, so I am a bit rusty on this.

I am using the nlohmann/json json.h library and need to convert a JSON string that is an array of objects to an actual array.

As an example, I need to take this kind of response from a TRESTResponse object and turn it into a C++ array:

```<code>RESTRequest1->Execute();
String Content = RESTResponse1->Content;
</code>```

Where Content =

```<code>"[{"fullname":"Norm A","e_mail":null,"phone":"999-555-4971"},{"fullname":"Norm C","e_mail":"ht2@yahoo.com","phone":"999-555-8887"},{"fullname":"Norma Jn","e_mail":null,"phone":"999-555-5947"},{"fullname":"Norma & Frank L","e_mail":null,"phone":"999-555-1790"},{"fullname":"Norm Sh","e_mail":null,"phone":"999-555-7545"},{"fullname":"Norm S","e_mail":null,"phone":"999-555-9955"}]"
</code>```

and get it into an array of objects.  I have been unsuccessful with the library.  While I can get an array into json properly, I can't seem to get json back to an array.

I've looked at some similar posts on Stackoverflow, but I did not see one that concerns the nlohmann/json library.

答:
[EDIT] Added an example that uses your input data. [Demo]

```<code>// Outputs:
//
//   [
//     (Norm A, null, 999-555-4971),
//     (Norm C, ht2@yahoo.com, 999-555-8887),
//     (Norma Jn, null, 999-555-5947),
//     (Norma & Frank L, null, 999-555-1790),
//     (Norm Sh, null, 999-555-7545),
//     (Norm S, null, 999-555-9955)
//   ]
</code>```

The example below loads a JSON node of array type into a std::vector.

The input JSON string only contains a node writers whose content is an array of strings:

```<code>{
    "writers": [
        "Winston Groom",
        "Eric Roth"
    ]
}
</code>```

We load it into a JSON node with:

```<code>nlohmann::json j = nlohmann::json::parse(json_str);
</code>```

We parse the "value" for the writers "key", i.e. the array, with:

```<code>j.at("writers").get_to(writers);
</code>```

This will make use of the available from_json(const nlohmann::json&, YourCustomType&) in order to do the parsing.

The struct Writers parses the JSON node into a std::vector<Writer> with:

```<code>    writers.data = j.get<std::vector<Writer>>();
</code>```

And the struct Writer parses the JSON node into a std::string with:

```<code>    j.get_to(writer.name);
</code>```

[Demo]

#include <iostream>  // cout
#include <nlohmann/json.hpp>
#include <ostream>
#include <string>
#include <vector>

struct Writer
{
    std::string name{};
};
void from_json(const nlohmann::json& j, Writer& writer)
{
    j.get_to(writer.name);
}

struct Writers
{
    std::vector<Writer> data{};
};
void from_json(const nlohmann::json& j, Writers& writers)
{
    writers.data = j.get<std::vector<Writer>>();
}

int main()
{
    std::string json_str{R"({"writers": ["Winston Groom", "Eric Roth"]})"};
    Writers writers{};
    nlohmann::json j = nlohmann::json::parse(json_str.c_str());
    j.at("writers").get_to(writers);

    for (const auto& writer : writers.data)
    {
        std::cout << writer.name << ", ";
    }
}

// Outputs:
//
//   Winston Groom, Eric Roth,
```

Body:
I've not used C++ in over 20 years, so I am a bit rusty on this.

I am using the nlohmann/json json.h library and need to convert a JSON string that is an array of objects to an actual array.

As an example, I need to take this kind of response from a TRESTResponse object and turn it into a C++ array:

RESTRequest1->Execute();
String Content = RESTResponse1->Content;

Where Content =

"[{"fullname":"Norm A","e_mail":null,"phone":"999-555-4971"},{"fullname":"Norm C","e_mail":"ht2@yahoo.com","phone":"999-555-8887"},{"fullname":"Norma Jn","e_mail":null,"phone":"999-555-5947"},{"fullname":"Norma & Frank L","e_mail":null,"phone":"999-555-1790"},{"fullname":"Norm Sh","e_mail":null,"phone":"999-555-7545"},{"fullname":"Norm S","e_mail":null,"phone":"999-555-9955"}]"

and get it into an array of objects.  I have been unsuccessful with the library.  While I can get an array into json properly, I can't seem to get json back to an array.

I've looked at some similar posts on Stackoverflow, but I did not see one that concerns the nlohmann/json library.

Body:
[EDIT] Added an example that uses your input data. [Demo]

// Outputs:
//
//   [
//     (Norm A, null, 999-555-4971),
//     (Norm C, ht2@yahoo.com, 999-555-8887),
//     (Norma Jn, null, 999-555-5947),
//     (Norma & Frank L, null, 999-555-1790),
//     (Norm Sh, null, 999-555-7545),
//     (Norm S, null, 999-555-9955)
//   ]

The example below loads a JSON node of array type into a std::vector.

The input JSON string only contains a node writers whose content is an array of strings:

{
    "writers": [
        "Winston Groom",
        "Eric Roth"
    ]
}

We load it into a JSON node with:

nlohmann::json j = nlohmann::json::parse(json_str);

We parse the "value" for the writers "key", i.e. the array, with:

j.at("writers").get_to(writers);

This will make use of the available from_json(const nlohmann::json&, YourCustomType&) in order to do the parsing.

The struct Writers parses the JSON node into a std::vector<Writer> with:

    writers.data = j.get<std::vector<Writer>>();

And the struct Writer parses the JSON node into a std::string with:

    j.get_to(writer.name);

[Demo]

#include <iostream>  // cout
#include <nlohmann/json.hpp>
#include <ostream>
#include <string>
#include <vector>

struct Writer
{
    std::string name{};
};
void from_json(const nlohmann::json& j, Writer& writer)
{
    j.get_to(writer.name);
}

struct Writers
{
    std::vector<Writer> data{};
};
void from_json(const nlohmann::json& j, Writers& writers)
{
    writers.data = j.get<std::vector<Writer>>();
}

int main()
{
    std::string json_str{R"({"writers": ["Winston Groom", "Eric Roth"]})"};
    Writers writers{};
    nlohmann::json j = nlohmann::json::parse(json_str.c_str());
    j.at("writers").get_to(writers);

    for (const auto& writer : writers.data)
    {
        std::cout << writer.name << ", ";
    }
}

// Outputs:
//
//   Winston Groom, Eric Roth,


问:
Circular rotate: Issue with rotate left
In below code, where and what exactly I am doing wrong? I am getting unexpected values when rotating data back to left. What is the fix for this?</p>

```<code>public class RotateExample {
    public static byte rotateRight(byte bits, int shift) {
        return (byte)((bits >>> shift) | (bits << (8 - shift)));
    }

    public static byte rotateLeft(byte bits, int shift) {
        return (byte)((bits << shift) | (bits >>> (8 - shift)));
    }

    public static void main(String[] args)  {
        //test 1 failed
        byte a = (byte)1;
        byte b = rotateRight(a,1);
        byte c = rotateLeft(b,1);
        System.out.println(a+" "+b+" "+c);

        //test 2 passed
        a = (byte)1;
        b = rotateRight(a,2);
        c = rotateLeft(b,2);
        System.out.println(a+" "+b+" "+c);

        //test 3 failed
        a = (byte)2;
        b = rotateRight(a,2);
        c = rotateLeft(b,2);
        System.out.println(a+" "+b+" "+c);

        //test 4 passed
        a = (byte)2;
        b = rotateRight(a,3);
        c = rotateLeft(b,3);
        System.out.println(a+" "+b+" "+c);
    }
}
</code>```

答:
The current answer didn't work for me, and I realized it's because the righthand side of the operator should be shifting by the size of an Integer (32) rather than 8. This is because the byte is promoted to an Integer prior to any shifting operations taking place on it. Here is my solution:

```<code>  /**
 * Performs a circular bitwise rotation on a byte, rotating right by shift positions.
 *
 * @param bits the byte to rotate
 * @param shift the number of positions to rotate by
 * @return the rotated byte
 */
private static byte rotateRight(byte bits, int shift) {
    return (byte) (((bits & 0xff) >>> shift) | ((bits & 0xff) << (Integer.SIZE - shift)));
}

/**
 * Performs a circular bitwise rotation on a byte, rotating left by shift positions.
 *
 * @param bits the byte to rotate
 * @param shift the number of positions to rotate by
 * @return the rotated byte
 */
private static byte rotateLeft(byte bits, int shift)
{
    return (byte)(((bits & 0xff) << shift) | ((bits & 0xff) >>> (Integer.SIZE - shift)));
}
</code>```

It's an old thread, but hopefully someone can find this answer useful!

Title: Circular rotate: Issue with rotate left

Body:
In below code, where and what exactly I am doing wrong? I am getting unexpected values when rotating data back to left. What is the fix for this?

public class RotateExample {
    public static byte rotateRight(byte bits, int shift) {
        return (byte)((bits >>> shift) | (bits << (8 - shift)));
    }

    public static byte rotateLeft(byte bits, int shift) {
        return (byte)((bits << shift) | (bits >>> (8 - shift)));
    }

    public static void main(String[] args)  {
        //test 1 failed
        byte a = (byte)1;
        byte b = rotateRight(a,1);
        byte c = rotateLeft(b,1);
        System.out.println(a+" "+b+" "+c);

        //test 2 passed
        a = (byte)1;
        b = rotateRight(a,2);
        c = rotateLeft(b,2);
        System.out.println(a+" "+b+" "+c);

        //test 3 failed
        a = (byte)2;
        b = rotateRight(a,2);
        c = rotateLeft(b,2);
        System.out.println(a+" "+b+" "+c);

        //test 4 passed
        a = (byte)2;
        b = rotateRight(a,3);
        c = rotateLeft(b,3);
        System.out.println(a+" "+b+" "+c);
    }
}

Body:
The current answer didn't work for me, and I realized it's because the righthand side of the operator should be shifting by the size of an Integer (32) rather than 8. This is because the byte is promoted to an Integer prior to any shifting operations taking place on it. Here is my solution:

  /**
 * Performs a circular bitwise rotation on a byte, rotating right by shift positions.
 *
 * @param bits the byte to rotate
 * @param shift the number of positions to rotate by
 * @return the rotated byte
 */
private static byte rotateRight(byte bits, int shift) {
    return (byte) (((bits & 0xff) >>> shift) | ((bits & 0xff) << (Integer.SIZE - shift)));
}

/**
 * Performs a circular bitwise rotation on a byte, rotating left by shift positions.
 *
 * @param bits the byte to rotate
 * @param shift the number of positions to rotate by
 * @return the rotated byte
 */
private static byte rotateLeft(byte bits, int shift)
{
    return (byte)(((bits & 0xff) << shift) | ((bits & 0xff) >>> (Integer.SIZE - shift)));
}

It's an old thread, but hopefully someone can find this answer useful!


问:
Make an API call on the front end using next.js
New to next.js and trying to hook up making Prisma calls from my components.
Following the docs and examples by doing this:

```<code>try {
  await fetch('/api/postQuestion', {
    method: 'POST',
    headers: {"Content-Type": "application/json"}
  });
} catch (error) {
  console.error(error);
}
</code>```

however, it does nothing at all.

Here is postQuestion.js:

```<code>import prisma from "../../lib/prisma.js";

export default async function handler(req, res) {
    if (req.method === 'POST') {
        return await createQuestion(req, res);
    }
    else {
        return res.status(405).json({ message: 'Method not allowed', success: false });
    }
}

async function createQuestion(req, res) {
    try {
        const newQuestion = await prisma.question.create({
            data: {
                question: 'wow?',
                option1: 'blue',
                option2: 'red'
            }
        });
        return res.status(200).json(newQuestion, {success: true});
    } catch (error) {
        console.error("Request error", error);
        res.status(500).json({ error: "Error creating question", success:false });
    }
}
</code>```

答:
The proper way to fetch local API data is using getStaticProps functions and return the data

https://nextjs.org/docs/basic-features/data-fetching/get-static-props

```<code>export async function getStaticProps() {
  // Call an external API endpoint to get posts.
  // You can use any data fetching library
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}
</code>```

Body:
New to next.js and trying to hook up making Prisma calls from my components.
Following the docs and examples by doing this:

try {
  await fetch('/api/postQuestion', {
    method: 'POST',
    headers: {"Content-Type": "application/json"}
  });
} catch (error) {
  console.error(error);
}

however, it does nothing at all.

Here is postQuestion.js:

import prisma from "../../lib/prisma.js";

export default async function handler(req, res) {
    if (req.method === 'POST') {
        return await createQuestion(req, res);
    }
    else {
        return res.status(405).json({ message: 'Method not allowed', success: false });
    }
}

async function createQuestion(req, res) {
    try {
        const newQuestion = await prisma.question.create({
            data: {
                question: 'wow?',
                option1: 'blue',
                option2: 'red'
            }
        });
        return res.status(200).json(newQuestion, {success: true});
    } catch (error) {
        console.error("Request error", error);
        res.status(500).json({ error: "Error creating question", success:false });
    }
}

Body:
The proper way to fetch local API data is using getStaticProps functions and return the data

https://nextjs.org/docs/basic-features/data-fetching/get-static-props

export async function getStaticProps() {
  // Call an external API endpoint to get posts.
  // You can use any data fetching library
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}


问:
Colab Notebook: Cannot import name 'container_abcs' from 'torch._six'
I'm trying to run the deit colab notebook found here:

https://colab.research.google.com/github/facebookresearch/deit/blob/colab/notebooks/deit_inference.ipynb

but I'm running into an issue in the second cell, specifically the import timm line, which returns this:

ImportError: cannot import name 'container_abcs' from 'torch._six'

答:
In my case it worked with</p>
```<code>pip install timm==0.4.12
</code>```

Body:
In my case it worked with

pip install timm==0.4.12