问:
Adding tabitems to tablayout based on viewpager not showing fragment
I have an app with tabpages based on a list. The tablayout is generated based on viewpager. But when I select a tab, the fragment is nog showing.

Here's my acitivty code:

```<code>List<string> categories = new List<string>
            {
                "Books",
                "Fruits",
                "Vegetables"
            };

 var view_pager = FindViewById<ViewPager>(Resource.Id.view_pager_pos);
 var tabLayout = FindViewById<TabLayout>(Resource.Id.tablayout_pos);

   _categoriesPagerAdapter = new CategoriesFragmentPagerAdapter(SupportFragmentManager,
                 FragmentPagerAdapter.BehaviorResumeOnlyCurrentFragment,
                 tabLayout.TabCount,
                 categories);

        TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        view_pager.Adapter = _categoriesPagerAdapter;
        tabLayout.SetupWithViewPager(view_pager, true);
</code>```

Here is my acitivity xml:

```<code><LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:orientation="horizontal"
     android:minWidth="25px"
     android:minHeight="25px"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:id="@+id/linearLayout_pos">

     <FrameLayout
         android:id="@+id/fragment_container_pos"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:layout_weight="0.7" />

     <com.google.android.material.tabs.TabLayout
         android:layout_weight="0.3"
         android:minWidth="25px"
         android:minHeight="25px"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         app:tabGravity="fill"
         android:id="@+id/tablayout_pos">

     </com.google.android.material.tabs.TabLayout>

     <androidx.viewpager.widget.ViewPager
         android:id="@+id/view_pager_pos"
         android:layout_width="match_parent"
         android:layout_height="0dp"
         android:layout_weight="1"
         android:background="@android:color/white" />

 </LinearLayout>
</code>```

Here is my CategoriesFragmentPagerAdapter:

```<code>internal class CategoriesFragmentPagerAdapter : FragmentPagerAdapter
     {
         private int _tabNr;
         private List<string> categories;

         public CategoriesFragmentPagerAdapter(FragmentManager fm, int behavior, int tabs, List<string> categories) : base(fm, behavior)
         {
             _tabNr = tabs;
             this.categories = categories;
         }

         public override int Count => _tabNr;

         public override Fragment GetItem(int position)
         {
             var category = categories[position];
             return new ProductsByCategoryFragment(category.Id);
         }
     }
</code>```

Here is my ProductsByCategoryFragment (tabpage fragment based on category):

```<code>internal class ProductsByCategoryFragment : AndroidX.Fragment.App.Fragment
{
    private readonly string category;

    public ProductsByCategoryFragment(string category)
    {
        this.category = category;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        return inflater.Inflate(Resource.Layout.pos_products_per_category, container, false);
    }

    public override void OnViewCreated(View view, Bundle savedInstanceState)
    {
        base.OnViewCreated(view, savedInstanceState);
    }
}
</code>```

Here is my pos_products_per_category.xml:

```<code> <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:layout_behavior="@string/appbar_scrolling_view_behavior"
     tools:showIn="@layout/app_bar_main">

     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerInParent="true"
         android:text="Category fragment" />

 </RelativeLayout>
</code>```

The tabpages I can see, but the fragment is not showing on the tabpage. Am I missing something here?

答:
I had test your code on my device. I changed some code to make it run successfully. When I changed  android:orientation="horizontal" to vertical and the android:layout_height="match_parent" to wrap content, the fragment will show.Such as:</p>
```<code><LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:orientation="vertical"
 android:minWidth="25px"
 android:minHeight="25px"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/linearLayout_pos">

 <FrameLayout
     android:id="@+id/fragment_container_pos"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_weight="0.7" />

 <com.google.android.material.tabs.TabLayout
     android:layout_weight="0.3"
     android:minWidth="25px"
     android:minHeight="25px"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     app:tabGravity="fill"
     android:id="@+id/tablayout_pos">

 </com.google.android.material.tabs.TabLayout>

 <androidx.viewpager.widget.ViewPager
     android:id="@+id/view_pager_pos"
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1"
     android:background="@android:color/white" />
</code>```

Body:
I have an app with tabpages based on a list. The tablayout is generated based on viewpager. But when I select a tab, the fragment is nog showing.

Here's my acitivty code:

List<string> categories = new List<string>
            {
                "Books",
                "Fruits",
                "Vegetables"
            };

 var view_pager = FindViewById<ViewPager>(Resource.Id.view_pager_pos);
 var tabLayout = FindViewById<TabLayout>(Resource.Id.tablayout_pos);

   _categoriesPagerAdapter = new CategoriesFragmentPagerAdapter(SupportFragmentManager,
                 FragmentPagerAdapter.BehaviorResumeOnlyCurrentFragment,
                 tabLayout.TabCount,
                 categories);

        TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        view_pager.Adapter = _categoriesPagerAdapter;
        tabLayout.SetupWithViewPager(view_pager, true);

Here is my acitivity xml:

<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:orientation="horizontal"
     android:minWidth="25px"
     android:minHeight="25px"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:id="@+id/linearLayout_pos">

     <FrameLayout
         android:id="@+id/fragment_container_pos"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:layout_weight="0.7" />

     <com.google.android.material.tabs.TabLayout
         android:layout_weight="0.3"
         android:minWidth="25px"
         android:minHeight="25px"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         app:tabGravity="fill"
         android:id="@+id/tablayout_pos">

     </com.google.android.material.tabs.TabLayout>

     <androidx.viewpager.widget.ViewPager
         android:id="@+id/view_pager_pos"
         android:layout_width="match_parent"
         android:layout_height="0dp"
         android:layout_weight="1"
         android:background="@android:color/white" />

 </LinearLayout>

Here is my CategoriesFragmentPagerAdapter:

internal class CategoriesFragmentPagerAdapter : FragmentPagerAdapter
     {
         private int _tabNr;
         private List<string> categories;

         public CategoriesFragmentPagerAdapter(FragmentManager fm, int behavior, int tabs, List<string> categories) : base(fm, behavior)
         {
             _tabNr = tabs;
             this.categories = categories;
         }

         public override int Count => _tabNr;

         public override Fragment GetItem(int position)
         {
             var category = categories[position];
             return new ProductsByCategoryFragment(category.Id);
         }
     }

Here is my ProductsByCategoryFragment (tabpage fragment based on category):

internal class ProductsByCategoryFragment : AndroidX.Fragment.App.Fragment
{
    private readonly string category;

    public ProductsByCategoryFragment(string category)
    {
        this.category = category;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        return inflater.Inflate(Resource.Layout.pos_products_per_category, container, false);
    }

    public override void OnViewCreated(View view, Bundle savedInstanceState)
    {
        base.OnViewCreated(view, savedInstanceState);
    }
}

Here is my pos_products_per_category.xml:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:layout_behavior="@string/appbar_scrolling_view_behavior"
     tools:showIn="@layout/app_bar_main">

     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerInParent="true"
         android:text="Category fragment" />

 </RelativeLayout>

The tabpages I can see, but the fragment is not showing on the tabpage. Am I missing something here?

Body:
I had test your code on my device. I changed some code to make it run successfully. When I changed  android:orientation="horizontal" to vertical and the android:layout_height="match_parent" to wrap content, the fragment will show.Such as:

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:orientation="vertical"
 android:minWidth="25px"
 android:minHeight="25px"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/linearLayout_pos">

 <FrameLayout
     android:id="@+id/fragment_container_pos"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_weight="0.7" />

 <com.google.android.material.tabs.TabLayout
     android:layout_weight="0.3"
     android:minWidth="25px"
     android:minHeight="25px"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     app:tabGravity="fill"
     android:id="@+id/tablayout_pos">

 </com.google.android.material.tabs.TabLayout>

 <androidx.viewpager.widget.ViewPager
     android:id="@+id/view_pager_pos"
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1"
     android:background="@android:color/white" />


来源: stackexchange

问:
Split ARRAY into chunks as they appear in sequence
I got an array of objects which I need to make into three chunks in the sequence as they are in the original array. For eg.

```<code>let arr = [{1},{2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}];
</code>```

This array needs to be split like this:

```<code>let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};
</code>```

答:
{1} is not a valid js structure

assuming than arr is an array of object you can :

generate a rolling char index with  String.fromCharCode(current + 97)

use an object to have char index

let arr = [{name:1},{name:2}, {name:3}, {name:4}, {name:5}, {name:6}, {name:7}, {name:8}, {name:9}, {name:10}];

function transform(theArray, chunkValue) {
  let finalObject = {};
  let current = 0;
  let currentIndex;

  theArray.forEach(element => {
    currentIndex = String.fromCharCode(current + 97);
    if (!finalObject[currentIndex]) {
      finalObject[currentIndex] = [];
    }
    finalObject[currentIndex].push(element);
    current++;
    if (current === chunkValue) {
      current = 0;
    }
  });

  console.log(finalObject);
  return finalObject;
}

transform(arr, 3);```

ContentLicense: CC BY-SA 4.0

Body:
I got an array of objects which I need to make into three chunks in the sequence as they are in the original array. For eg.

let arr = [{1},{2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}];

This array needs to be split like this:

let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};


问:
Spread Operator for array of array
How to perform spread opration on salesuser array object. need to add  ..salesuserstargetAmount:500, in that object

```<code>  {
    "station": [
        {
            "stationname":"chennai",
            "stationtargetAmount":500,
            "salesusers":[
                {
                " salesusersname":"tester",
                },
         ]
        },
    {
            "stationname":"chennai22222",
           "stationtargetAmount":500,
            "salesusers":[
                {
                " salesusersname":"tester222222",
                },
         ]
        }
    ]
 }
</code>```

Tried with

```<code>let  salesusertargetamt = "100"

 this.setState({
   salesusers: this.state.station.map((items) => {
   items.salesusers.map(el => (el.salesusersname !== "" ? { ...el, salesusertargetamt } : el))
  });
</code>```

答:
let  salesusertargetamt = "100"

 this.setState({
   salesusers: this.state.station.map((items) => {
    return items.salesusers.map(el => (el.salesusersname !== "" ? { ...el, stationtargetAmount: salesusertargetamt } : el))
  });
```

Title: Spread Operator for array of array

Body:
How to perform spread opration on salesuser array object. need to add  ..salesuserstargetAmount:500, in that object

  {
    "station": [
        {
            "stationname":"chennai",
            "stationtargetAmount":500,
            "salesusers":[
                {
                " salesusersname":"tester",
                },
         ]
        },
    {
            "stationname":"chennai22222",
           "stationtargetAmount":500,
            "salesusers":[
                {
                " salesusersname":"tester222222",
                },
         ]
        }
    ]
 }

Tried with

let  salesusertargetamt = "100"

 this.setState({
   salesusers: this.state.station.map((items) => {
   items.salesusers.map(el => (el.salesusersname !== "" ? { ...el, salesusertargetamt } : el))
  });


问:
ViewModel: Error on loading long list in IO Dispatcher
I want to load a long list inside my ViewModel class, queried from database. Data will then be shown using LazyColumn. When loading in IO Dispatcher using kotlin coroutine it throws exception but no problem when loading in Main Dispatcher.

ViewModel Class:

```<code>class TestViewModel: ViewModel() {
val itemList = mutableStateListOf<TestModel>()

init {
    viewModelScope.launch(Dispatchers.IO){
        loadList()
    }
}
</code>```

Error Message:

```<code>E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: in.rachika.composetest2, PID: 19469
java.lang.IllegalStateException: Reading a state that was created after the snapshot was taken or in a snapshot that has not yet been applied
    at androidx.compose.runtime.snapshots.SnapshotKt.readError(Snapshot.kt:1518)
    at androidx.compose.runtime.snapshots.SnapshotKt.current(Snapshot.kt:1758)
    at androidx.compose.runtime.snapshots.SnapshotStateList.add(SnapshotStateList.kt:374)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel.loadList(TestViewModel.kt:24)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel.access$loadList(TestViewModel.kt:13)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel$1.invokeSuspend(TestViewModel.kt:19)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
</code>```

答:
Snapshots are transactional and run on ui thread. You are attempting to create a snapshot on the IO thread. If you want to do your data loading on the IO thread, you need to switch back to the UI thread after you've retrieved the data. Example:

class MyViewModel: ViewModel() {
    fun getData() {
        viewModelScope.launch(Dispatchers.IO) {
            // Get Data
            val data = someAPI.getData()

            withContext(Dispatchers.Main) {
                // Display the data...
                displayData(data)
            }
        }
    }
}
```

Body:
I want to load a long list inside my ViewModel class, queried from database. Data will then be shown using LazyColumn. When loading in IO Dispatcher using kotlin coroutine it throws exception but no problem when loading in Main Dispatcher.

ViewModel Class:

class TestViewModel: ViewModel() {
val itemList = mutableStateListOf<TestModel>()

init {
    viewModelScope.launch(Dispatchers.IO){
        loadList()
    }
}

Error Message:

E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: in.rachika.composetest2, PID: 19469
java.lang.IllegalStateException: Reading a state that was created after the snapshot was taken or in a snapshot that has not yet been applied
    at androidx.compose.runtime.snapshots.SnapshotKt.readError(Snapshot.kt:1518)
    at androidx.compose.runtime.snapshots.SnapshotKt.current(Snapshot.kt:1758)
    at androidx.compose.runtime.snapshots.SnapshotStateList.add(SnapshotStateList.kt:374)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel.loadList(TestViewModel.kt:24)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel.access$loadList(TestViewModel.kt:13)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel$1.invokeSuspend(TestViewModel.kt:19)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)


问:
ssh2-sftp-client file upload incomplete when listening to streams data event
I upload files via ssh2-sftp-client by passing a readStream. That works fine, but when I add an event listener the files are not completely uploaded:

This works:

```<code>const stream = fs.createReadStream(myFile);
return this.sftpClient.put(stream, remoteFilePath)
</code>```

This only uploads 80% of the file

```<code>const stream = fs.createReadStream(myFile);
stream.on('data', (chunk) => {
  console.log('chunk passed');
});
return this.sftpClient.put(stream, remoteFilePath)
</code>```

Last message in debug mode shows no error:

```<code>chunk passed
Outbound: Sending CHANNEL_DATA (r:0, 9380)
SFTP: Outbound: Sent WRITE (id:1554)
Inbound: CHANNEL_DATA (r:0, 28)
SFTP: Inbound: Received STATUS (id:1554, 0, "Success")
Outbound: Sending CHANNEL_DATA (r:0, 17)
SFTP: Outbound: Buffered CLOSE
Inbound: CHANNEL_DATA (r:0, 28)
SFTP: Inbound: Received STATUS (id:1555, 0, "Success")
CLIENT[sftp]: put: promise resolved
CLIENT[sftp]: put: Removing temp event listeners
</code>```

Same problem when piping a stream:

```<code>const stream = fs.createReadStream(myFile);
const fileMd5Hash = crypto.createHash('md5').setEncoding('hex');
stream.pipe(fileMd5Hash);
return this.sftpClient.put(stream, remoteFilePath)
</code>```

It seems the problem lies in the fact that onData event and pipe() both switch the stream into flowing mode which might cause data loss since data is immediately "as quickly as possible" passed to the aplication.
So I wonder: how could I read the chunks to create my md5sum hash from the whole file without switching the read stream to flowing mode?

答:
So I figured out now what happens:
I skipped one line in my examples which I assumed not relevant:

```<code>const stream = fs.createReadStream(myFile);

createDirsIfNotExist(remoteFilePath);

return this.sftpClient.put(stream, remoteFilePath)
</code>```

so I had:

```<code>const stream = fs.createReadStream(myFile);

stream.on('data', (chunk) => {
  console.log('chunk passed');
});

createDirsIfNotExist(remoteFilePath);

return this.sftpClient.put(stream, remoteFilePath)
</code>```

The problem is that stream.on('data'...) triggers immediately the switch to flowing mode. If createDirsIfNotExist takes some time the first chunks will not be piped in sftpClient.

If I switch the lines:

```<code>
createDirsIfNotExist(remoteFilePath);

stream.on('data', (chunk) => {
  console.log('chunk passed');
});

return this.sftpClient.put(stream, remoteFilePath)
</code>```

It works as expected. To be shure I wrapped the data event handler in the resume event handler:

```<code>let listening = false;
stream.on('resume', () => {
  if(!listening) {
    stream.on('data', (chunk) => {
      console.log('chunk passed');
      // do whatever else is needed
    });
    listening = true;
});
</code>```

This avoids the timing problem but looks strange.

Body:
I upload files via ssh2-sftp-client by passing a readStream. That works fine, but when I add an event listener the files are not completely uploaded:

This works:

const stream = fs.createReadStream(myFile);
return this.sftpClient.put(stream, remoteFilePath)

This only uploads 80% of the file

const stream = fs.createReadStream(myFile);
stream.on('data', (chunk) => {
  console.log('chunk passed');
});
return this.sftpClient.put(stream, remoteFilePath)

Last message in debug mode shows no error:

chunk passed
Outbound: Sending CHANNEL_DATA (r:0, 9380)
SFTP: Outbound: Sent WRITE (id:1554)
Inbound: CHANNEL_DATA (r:0, 28)
SFTP: Inbound: Received STATUS (id:1554, 0, "Success")
Outbound: Sending CHANNEL_DATA (r:0, 17)
SFTP: Outbound: Buffered CLOSE
Inbound: CHANNEL_DATA (r:0, 28)
SFTP: Inbound: Received STATUS (id:1555, 0, "Success")
CLIENT[sftp]: put: promise resolved
CLIENT[sftp]: put: Removing temp event listeners

Same problem when piping a stream:

const stream = fs.createReadStream(myFile);
const fileMd5Hash = crypto.createHash('md5').setEncoding('hex');
stream.pipe(fileMd5Hash);
return this.sftpClient.put(stream, remoteFilePath)

It seems the problem lies in the fact that onData event and pipe() both switch the stream into flowing mode which might cause data loss since data is immediately "as quickly as possible" passed to the aplication.
So I wonder: how could I read the chunks to create my md5sum hash from the whole file without switching the read stream to flowing mode?

Body:
So I figured out now what happens:
I skipped one line in my examples which I assumed not relevant:

const stream = fs.createReadStream(myFile);

createDirsIfNotExist(remoteFilePath);

return this.sftpClient.put(stream, remoteFilePath)

so I had:

const stream = fs.createReadStream(myFile);

stream.on('data', (chunk) => {
  console.log('chunk passed');
});

createDirsIfNotExist(remoteFilePath);

return this.sftpClient.put(stream, remoteFilePath)

The problem is that stream.on('data'...) triggers immediately the switch to flowing mode. If createDirsIfNotExist takes some time the first chunks will not be piped in sftpClient.

If I switch the lines:

createDirsIfNotExist(remoteFilePath);

stream.on('data', (chunk) => {
  console.log('chunk passed');
});

return this.sftpClient.put(stream, remoteFilePath)

It works as expected. To be shure I wrapped the data event handler in the resume event handler:

let listening = false;
stream.on('resume', () => {
  if(!listening) {
    stream.on('data', (chunk) => {
      console.log('chunk passed');
      // do whatever else is needed
    });
    listening = true;
});

This avoids the timing problem but looks strange.


问:
How to write a converter in JOOQ to convert fields from String to Map<String, String>
How to convert a string field to map while fetching the data from DB in JOOQ</p>

答: You can implement a Converter<String, Map<String, String>> and attach that to your generated code as documented here.


问:
Converting a photo data to nsstring returns nil
I'm allowing the users of my app to either take a pic or select one from their library. When selected I need to get the images' data and convert it to a string so I can send it to a web service.

The problem I'm currently having is that [NSString initWithData:] is returning nil when I have the encoding set to UTF8. I need to set it to UTF8 for the XML message.

```<code>NSString *dataString = [[NSString alloc] initWithData:UIImageJPEGRepresentation(theImage, 1.0) encoding:NSUTF8StringEncoding];
</code>```

Thanks for any advice!

答:
You can't convert an UIImage to NSString by using initWithData:encoding: method. This method is only for converting an string's data to NSString (an Text File for example).

If you are trying to convert any kind of binary data to NSString, there are some kind of encoding available. Base64 is widely used. Also your server should have the ability to decode what you've sent.

In addition, in most cases, send an image to server just need to POST it in binary as it used to be.

ContentLicense: CC BY-SA 3.0

Body:
I'm allowing the users of my app to either take a pic or select one from their library. When selected I need to get the images' data and convert it to a string so I can send it to a web service.

The problem I'm currently having is that [NSString initWithData:] is returning nil when I have the encoding set to UTF8. I need to set it to UTF8 for the XML message.

NSString *dataString = [[NSString alloc] initWithData:UIImageJPEGRepresentation(theImage, 1.0) encoding:NSUTF8StringEncoding];

Thanks for any advice!


问:
Node.js 17.0.1 Gatsby error - "digital envelope routines::unsupported ... ERR_OSSL_EVP_UNSUPPORTED"
I am building a Gatsby site. I upgraded Node.js to v17.0.1, and when I run a build, there is an error:

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'
```

If I downgrade it to v16, it works fine, and the build will be successful. How can I fix this?

From googling, this may be a similar issue:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt #48

答:
While patching with --openssl-legacy-provider is more of a hack and a real solution would be to fix OpenSSL key size usage in Vue.js, React, etc.; a temporal workaround may be using an older version of Node.js indeed.

But I'd suggest not to downgrade Node.js; rather install NVM (main/win: nvm-windows/nodist/nvs, the last one being cross-platform) and switch between versions on demand.

Body:
I am building a Gatsby site. I upgraded Node.js to v17.0.1, and when I run a build, there is an error:

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

If I downgrade it to v16, it works fine, and the build will be successful. How can I fix this?

From googling, this may be a similar issue:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt #48


问:
OptionalProps in Mikro-orm
I am trying to work out how to define additional optional properties.

```<code>import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';

@Entity()
export abstract class BaseEntity {
  [OptionalProps]?: 'createdAt';

  @PrimaryKey()
  id: number;

  @Property()
  createdAt: Date = new Date();

}

@Entity()
export class EntityA extends BaseEntity {
  [OptionalProps]?: 'isAnotherProperty'; // This is the bit I cannot figure out

  @Property()
  isAnotherProperty: boolean = false;

}
</code>```

With the above TypeScript throws an error:

```<code>Property '[OptionalProps]' in type 'EntityA' is not assignable to the same property in base type 'BaseEntity'.
</code>```

Basically my BaseEntity has optional properties, as does EntityA. I could remove [OptionalProps]?: from BaseEntity and have [OptionalProps]?: 'createdAt' | 'isAnotherProperty'; in EntityA, but many of my entities don't require any additional optional properties beyond createdAt so I prefer not to have to duplicate [OptionalProps]?: 'createdAt'; in every entity class if I could just 'extend' it where I need to.

Is it at all possible to either append to or override [OptionalProps]?

答:
Probably the cleanest approach is via type argument on the base entity:</p>
```<code>import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';

@Entity()
export abstract class BaseEntity<Optional = never> {

  [OptionalProps]?: Optional | 'createdAt';

  @PrimaryKey()
  id: number;

  @Property()
  createdAt: Date = new Date();

}

@Entity()
export class EntityA extends BaseEntity<'isAnotherProperty'> {

  @Property()
  isAnotherProperty: boolean = false;

}
</code>```

Title: OptionalProps in Mikro-orm

Body:
I am trying to work out how to define additional optional properties.

import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';

@Entity()
export abstract class BaseEntity {
  [OptionalProps]?: 'createdAt';

  @PrimaryKey()
  id: number;

  @Property()
  createdAt: Date = new Date();

}

@Entity()
export class EntityA extends BaseEntity {
  [OptionalProps]?: 'isAnotherProperty'; // This is the bit I cannot figure out

  @Property()
  isAnotherProperty: boolean = false;

}

With the above TypeScript throws an error:

Property '[OptionalProps]' in type 'EntityA' is not assignable to the same property in base type 'BaseEntity'.

Basically my BaseEntity has optional properties, as does EntityA. I could remove [OptionalProps]?: from BaseEntity and have [OptionalProps]?: 'createdAt' | 'isAnotherProperty'; in EntityA, but many of my entities don't require any additional optional properties beyond createdAt so I prefer not to have to duplicate [OptionalProps]?: 'createdAt'; in every entity class if I could just 'extend' it where I need to.

Is it at all possible to either append to or override [OptionalProps]?

Body:
Probably the cleanest approach is via type argument on the base entity:

import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';

@Entity()
export abstract class BaseEntity<Optional = never> {

  [OptionalProps]?: Optional | 'createdAt';

  @PrimaryKey()
  id: number;

  @Property()
  createdAt: Date = new Date();

}

@Entity()
export class EntityA extends BaseEntity<'isAnotherProperty'> {

  @Property()
  isAnotherProperty: boolean = false;

}


问:
Selenium closing right after any request
Is it due to the site himself? If it is the case, how to bypass the problem?

I tried to make the web driver wait, but it didn't help...

This is my code :

```<code>from selenium import webdriver

PATH = '/Users/xxxx/chromedriver'
driver = webdriver.Chrome(PATH)
driver.get('https://haveibeenpwned.com/')
e_mail = driver.find_element_by_id('Account')
e_mail.send_keys('contact@gmail.com')
login_button = driver.find_element_by_id('searchPwnage')
login_button.click()
response = driver.find_element_by_id('pwnCount')
print(response.text)
</code>```

What can I do ?

答:
In order to make chromedriver to stay open, you have to use the detach option when starting the chromedriver.

As the following:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
```

Body:
Is it due to the site himself? If it is the case, how to bypass the problem?

I tried to make the web driver wait, but it didn't help...

This is my code :

from selenium import webdriver

PATH = '/Users/xxxx/chromedriver'
driver = webdriver.Chrome(PATH)
driver.get('https://haveibeenpwned.com/')
e_mail = driver.find_element_by_id('Account')
e_mail.send_keys('contact@gmail.com')
login_button = driver.find_element_by_id('searchPwnage')
login_button.click()
response = driver.find_element_by_id('pwnCount')
print(response.text)

What can I do ?


问:
Can anyone tell me how to save a canvas image with the background color?

window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(180, 180, 40, 40);
}

function saveWithBackground(canvas) {
var link = document.createElement("a");
link.href = canvas.toDataURL();
link.download = "download.jpg";
link.click();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
border: 1px solid black;
background-color: red;
}</code>```

<canvas id="canvas" width="400" height="400"></canvas>
<button onclick="saveWithBackground(document.getElementById('canvas'))">Save</button>```

but this does not save the image with the background.

Can someone tell me how to save it with background color?

答:
you should set the background in canvas.</p>
```<code>window.onload = function () {
    var ctx = document.getElementById("canvas").getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 400, 400);
    ctx.fillStyle = "black";
    ctx.fillRect(180, 180, 40, 40);
}
</code>```

Body:
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(180, 180, 40, 40);
}

function saveWithBackground(canvas) {
var link = document.createElement("a");
link.href = canvas.toDataURL();
link.download = "download.jpg";
link.click();
}

#canvas {
border: 1px solid black;
background-color: red;
}

<canvas id="canvas" width="400" height="400"></canvas>
<button onclick="saveWithBackground(document.getElementById('canvas'))">Save</button>

but this does not save the image with the background.

Can someone tell me how to save it with background color?

Body:
you should set the background in canvas.

window.onload = function () {
    var ctx = document.getElementById("canvas").getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 400, 400);
    ctx.fillStyle = "black";
    ctx.fillRect(180, 180, 40, 40);
}


问:
Turtle module: screen.update() seems to freeze up the program
I'm creating a game using the turtle module. I included in my code something like this to smooth out the animation:

```<code>screen.tracer(0)
</code>```

Then I update the screen with:

```<code>screen.update()
</code>```

However, when I run the code, the animation freezes. Does anyone know what's happened here?

答:
well it works correctly!

the screen should always be in freeze mode (because of .tracer(0)  method), unless it sees the .update() and then because of this method it refresh it state and then back to the freeze mode.

source: tracer documentation

so basically it should update the screen once but if you want to update the screen constantly, you should put the screen.update() (and your entire code) in a while loop. here is an example:

```<code>from turtle import Screen
screen = Screen()
screen.tracer(0)

game_is_on = True
while game_is_on:
    screen.update()

    # your code

screen.exitonclick()
</code>```

Body:
I'm creating a game using the turtle module. I included in my code something like this to smooth out the animation:

screen.tracer(0)

Then I update the screen with:

screen.update()

However, when I run the code, the animation freezes. Does anyone know what's happened here?

Body:
well it works correctly!

the screen should always be in freeze mode (because of .tracer(0)  method), unless it sees the .update() and then because of this method it refresh it state and then back to the freeze mode.

source: tracer documentation

so basically it should update the screen once but if you want to update the screen constantly, you should put the screen.update() (and your entire code) in a while loop. here is an example:

from turtle import Screen
screen = Screen()
screen.tracer(0)

game_is_on = True
while game_is_on:
    screen.update()

    # your code

screen.exitonclick()


问:
Execute Makefile using Java command?
I'm just wandering. Is there a possibility to execute makefile.in using a Java command? Something like what you can do with Java and Ant.

Thanks

答:
If I understand the question and comments correctly, then you want to use something like Runtime.exec(String).</p>

```<code>String command = "make stuff" ; the make command you wish to run
String [] envp = { } ; if you want to set some environment variables
File dir = new File ( "/home/me/" ) ; // this is the directory where the Makefile is
Process proc = Runtime.getRuntime().exec(command,envp,dir);
proc.waitFor ( ) ;
</code>```

Title: Execute Makefile using Java command?

Body:
If I understand the question and comments correctly, then you want to use something like Runtime.exec(String).

String command = "make stuff" ; the make command you wish to run
String [] envp = { } ; if you want to set some environment variables
File dir = new File ( "/home/me/" ) ; // this is the directory where the Makefile is
Process proc = Runtime.getRuntime().exec(command,envp,dir);
proc.waitFor ( ) ;


问:
Infinite loop in useEffect
I've been playing around with the new hook system in React 16.7-alpha and get stuck in an infinite loop in useEffect when the state I'm handling is an object or array.

First, I use useState and initiate it with an empty object like this:

```<code>const [obj, setObj] = useState({});
</code>```

Then, in useEffect, I use setObj to set it to an empty object again. As a second argument I'm passing [obj], hoping that it wont update if the content of the object hasn't changed. But it keeps updating. I guess because no matter the content, these are always different objects making React thinking it keep changing?

```<code>useEffect(() => {
  setIngredients({});
}, [ingredients]);
</code>```

The same is true with arrays, but as a primitive it wont get stuck in a loop, as expected.

Using these new hooks, how should I handle objects and array when checking weather the content has changed or not?

答:
I often run into an infinite re-render when having a complex object as state and updating it from useRef:

const [ingredients, setIngredients] = useState({});

useEffect(() => {
  setIngredients({
    ...ingredients,
    newIngedient: { ... }
  });
}, [ingredients]);
```
<p>In this case <code>eslint(react-hooks/exhaustive-deps)</code> forces me (correctly) to add <code>ingredients</code> to the dependency array. However, this results in an infinite re-render. Unlike what some say in this thread, this is correct, and you can't get away with putting <code>ingredients.someKey</code> or <code>ingredients.length</code> into the dependency array.</p>
<p>The solution is that setters provide the old value that you can refer to. You should use this, rather than referring to <code>ingredients</code> directly:</p>
<pre class="lang-js prettyprint-override"><code>const [ingredients, setIngredients] = useState({});

useEffect(() => {
  setIngredients(oldIngedients => {
    return {
      ...oldIngedients,
      newIngedient: { ... }
    }
  });
}, []);
</code>```

Title: Infinite loop in useEffect

Body:
I've been playing around with the new hook system in React 16.7-alpha and get stuck in an infinite loop in useEffect when the state I'm handling is an object or array.

First, I use useState and initiate it with an empty object like this:

const [obj, setObj] = useState({});

Then, in useEffect, I use setObj to set it to an empty object again. As a second argument I'm passing [obj], hoping that it wont update if the content of the object hasn't changed. But it keeps updating. I guess because no matter the content, these are always different objects making React thinking it keep changing?

useEffect(() => {
  setIngredients({});
}, [ingredients]);

The same is true with arrays, but as a primitive it wont get stuck in a loop, as expected.

Using these new hooks, how should I handle objects and array when checking weather the content has changed or not?

Body:
I often run into an infinite re-render when having a complex object as state and updating it from useRef:

const [ingredients, setIngredients] = useState({});

useEffect(() => {
  setIngredients({
    ...ingredients,
    newIngedient: { ... }
  });
}, [ingredients]);

In this case eslint(react-hooks/exhaustive-deps) forces me (correctly) to add ingredients to the dependency array. However, this results in an infinite re-render. Unlike what some say in this thread, this is correct, and you can't get away with putting ingredients.someKey or ingredients.length into the dependency array.

The solution is that setters provide the old value that you can refer to. You should use this, rather than referring to ingredients directly:

const [ingredients, setIngredients] = useState({});

useEffect(() => {
  setIngredients(oldIngedients => {
    return {
      ...oldIngedients,
      newIngedient: { ... }
    }
  });
}, []);


答:
Curly braces ({) are tricky here because they both mean block of code and JavaScript object so you need to wrap them with ():

let  salesusertargetamt = "100";

 let obj = {
    "station": [
        {
            "stationname":"chennai",
            "stationtargetAmount":500,
            "salesusers":[
                {
                " salesusersname":"tester",
                },
         ]
        },
    {
            "stationname":"chennai22222",
           "stationtargetAmount":500,
            "salesusers":[
                {
                " salesusersname":"tester222222",
                },
         ]
        }
    ]
 };

 let result = obj.station.map(items => ({
    ...items,
    salesusers: items.salesusers.map(user => (user.salesusersname !== "" ? {...user, salesusertargetamt} : user ))
 }))

 console.log(result);```

Title: Spread Operator for array of array


问:
is it possible to import data to tally in xls format?
I am new to Tally Prime. I want to import data in tally in Xls.

I have imported data in XML format.

Is it possible to import data in tally in Xls format?

Thanks in advance.

答:
No, There is no direct way to import data to Tally from Excel(xls)
You can either convert excel data to xml using VBA or use Existing tools(Paid) like

Excel To Tally -- By AccountingCompanion.com


问:
Difference between await Task and await Func<Task>()
I have a program which needs to run a number of async tasks in parallel. The main difference between two implements, Task1() and Task2():

Task1() saves the FTask of type Func<Task> and later await Task.WhenAny(FTask()),

Task2() saves the Task produced by Task.Run() and later await Task.WhenAny(Task).

I think they should be equivalent, but Task1() does not work properly, however Task2() does work.

The flow of this program is:
If there are available task contexts in the free queue, dequeue one and setup it up with an async task; when async task finished put the context back to the free queue.

The problem is Task1() which saves Func<Task> does not work, it seems the async task has more than one instances running.

The complete code is:

```<code>static async Task Task1()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task1 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.FTask = async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            };

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));
    Console.WriteLine($"-------- Task1 finished --------");
}

static async Task Task2()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task2 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = Task.Run(async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            });

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task2 finished --------");
}

public class TaskCtx
{
    public int Token;
    public int Delay1;
    public int Delay2;
    public Func<Task> FTask;
    public Task Task;

    public TaskCtx()
    {
        FTask = async () => await Task.CompletedTask;
        Task = Task.CompletedTask;
    }
}
</code>```

The output of Task1():

-------- Task1 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[0] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1   <-- [1] is running and got the ticket
[4] submit
[4] start
[1] start               <-- another [1] starts ???
[2] start
[3] start
[2] wait ticket: 1
[1] wait ticket: 1
[1] acquire ticket: 1
[4] wait ticket: 1
[3] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[2] acquire ticket: 2
[1] release ticket: 2
[3] acquire ticket: 3
[3] acquire ticket: 3
[5] submit
[6] submit
[4] start
[6] start
[2] start
[3] start
[2] wait ticket: 3
[4] wait ticket: 3
[6] wait ticket: 3
[3] wait ticket: 3
[3] acquire ticket: 3
[2] release ticket: 3
[4] acquire ticket: 4
[2] release ticket: 3
[4] acquire ticket: 4
[3] release ticket: 5
[6] acquire ticket: 6
[3] release ticket: 5
[3] release ticket: 7
[4] release ticket: 8
[4] release ticket: 8
[6] release ticket: 10
```
<p>The output of <code>Task2()</code>:</p>
<pre class="lang-none prettyprint-override"><code>-------- Task2 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] wait ticket: 0
[0] acquire ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] submit
[4] start
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] submit
[5] start
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task2 finished --------
</code>```

UPDATE:
I make another implement, by use a normal async function, not anonymous function:

```<code>static async Task Task3()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    Ticket ticket = new Ticket(0);

    Console.WriteLine($"-------- Task3 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = RunTask3Async(x, ticket, qFree);

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task3 finished --------");
}

static async Task RunTask3Async(TaskCtx x, Ticket ticket, Queue<TaskCtx> qFree)
{
    Console.WriteLine($"[{x.Token}] start");
    await Task.Delay(x.Delay1);

    Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
    while (ticket.ticket != x.Token)
    {
        await Task.Yield(); // yield and wait other task increases the ticket
    }

    Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
    await Task.Delay(x.Delay2);
    Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
    ticket.ticket++;

    qFree.Enqueue(x);
}

public class Ticket
{
    public int ticket;

    public Ticket(int t)
    {
        ticket = t;
    }

    public override string ToString()
    {
        return $"{ticket}";
    }
}
</code>```

Task3() also works, the output is:

-------- Task3 start --------
[0] start
[0] submit
[1] start
[1] submit
[2] start
[2] submit
[3] start
[3] submit
[0] wait ticket: 0
[3] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] start
[4] submit
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] start
[5] submit
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task3 finished --------
```
<p>UPDATE2:
I tried to minimal the example but the following code does not have this problem.</p>
<pre class="lang-c# prettyprint-override"><code>var FTasks = Enumerable.Range(0, 8).Select(i => async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
}).ToArray();

await Task.WhenAll(FTasks.Select(x => x()));

Console.WriteLine("----------------");

var Tasks = Enumerable.Range(0, 8).Select(i => Task.Run(async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
})).ToArray();

await Task.WhenAll(Tasks);
</code>```

答: The main difference between storing Task.Run(...) in a Task and assigning it to a Func is in the timing of excecution. Task.Run() starts the work directly whereas the function is lazy, i.e. the work starts when the function is called.

Body:
I have a program which needs to run a number of async tasks in parallel. The main difference between two implements, Task1() and Task2():

Task1() saves the FTask of type Func<Task> and later await Task.WhenAny(FTask()),

Task2() saves the Task produced by Task.Run() and later await Task.WhenAny(Task).

I think they should be equivalent, but Task1() does not work properly, however Task2() does work.

The flow of this program is:
If there are available task contexts in the free queue, dequeue one and setup it up with an async task; when async task finished put the context back to the free queue.

The problem is Task1() which saves Func<Task> does not work, it seems the async task has more than one instances running.

The complete code is:

static async Task Task1()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task1 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.FTask = async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            };

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));
    Console.WriteLine($"-------- Task1 finished --------");
}

static async Task Task2()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task2 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = Task.Run(async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            });

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task2 finished --------");
}

public class TaskCtx
{
    public int Token;
    public int Delay1;
    public int Delay2;
    public Func<Task> FTask;
    public Task Task;

    public TaskCtx()
    {
        FTask = async () => await Task.CompletedTask;
        Task = Task.CompletedTask;
    }
}

The output of Task1():

-------- Task1 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[0] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1   <-- [1] is running and got the ticket
[4] submit
[4] start
[1] start               <-- another [1] starts ???
[2] start
[3] start
[2] wait ticket: 1
[1] wait ticket: 1
[1] acquire ticket: 1
[4] wait ticket: 1
[3] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[2] acquire ticket: 2
[1] release ticket: 2
[3] acquire ticket: 3
[3] acquire ticket: 3
[5] submit
[6] submit
[4] start
[6] start
[2] start
[3] start
[2] wait ticket: 3
[4] wait ticket: 3
[6] wait ticket: 3
[3] wait ticket: 3
[3] acquire ticket: 3
[2] release ticket: 3
[4] acquire ticket: 4
[2] release ticket: 3
[4] acquire ticket: 4
[3] release ticket: 5
[6] acquire ticket: 6
[3] release ticket: 5
[3] release ticket: 7
[4] release ticket: 8
[4] release ticket: 8
[6] release ticket: 10

The output of Task2():

-------- Task2 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] wait ticket: 0
[0] acquire ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] submit
[4] start
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] submit
[5] start
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task2 finished --------

UPDATE:
I make another implement, by use a normal async function, not anonymous function:

static async Task Task3()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    Ticket ticket = new Ticket(0);

    Console.WriteLine($"-------- Task3 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = RunTask3Async(x, ticket, qFree);

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task3 finished --------");
}

static async Task RunTask3Async(TaskCtx x, Ticket ticket, Queue<TaskCtx> qFree)
{
    Console.WriteLine($"[{x.Token}] start");
    await Task.Delay(x.Delay1);

    Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
    while (ticket.ticket != x.Token)
    {
        await Task.Yield(); // yield and wait other task increases the ticket
    }

    Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
    await Task.Delay(x.Delay2);
    Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
    ticket.ticket++;

    qFree.Enqueue(x);
}

public class Ticket
{
    public int ticket;

    public Ticket(int t)
    {
        ticket = t;
    }

    public override string ToString()
    {
        return $"{ticket}";
    }
}

Task3() also works, the output is:

-------- Task3 start --------
[0] start
[0] submit
[1] start
[1] submit
[2] start
[2] submit
[3] start
[3] submit
[0] wait ticket: 0
[3] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] start
[4] submit
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] start
[5] submit
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task3 finished --------

UPDATE2:
I tried to minimal the example but the following code does not have this problem.

var FTasks = Enumerable.Range(0, 8).Select(i => async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
}).ToArray();

await Task.WhenAll(FTasks.Select(x => x()));

Console.WriteLine("----------------");

var Tasks = Enumerable.Range(0, 8).Select(i => Task.Run(async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
})).ToArray();

await Task.WhenAll(Tasks);


问:
How to install SWOOLE in a Dockerfile for Laravel8/PHP8 project?
I'll build a Laravel 8 app. The PHP language level is PHP8. How can I integrate Swoole in my Dockerfile?

Actually I try it this way:

```<code>RUN pecl channel-update https://pecl.php.net/channel.xml \
    && pecl install swoole
</code>```

But if I build the Dockerfile, it always runs into this error:

------
 > [11/19] RUN pecl channel-update https://pecl.php.net/channel.xml  && pecl install swoole:
#14 0.283 /bin/sh: 1: pecl: not found
------
failed to solve: rpc error: code = Unknown desc = executor failed running [/bin/sh -c pecl channel-update https://pecl.php.net/channel.xml  && pecl install swoole]: exit code: 127
```

Does anyone has an idea?
If you need more information about it, please let me know.

Regards,
Manny

答:
It is a sample Dockerfile that uses the official PHP 8.0 (Debian) image and installs the Swoole through the PECL:

```<code>FROM php:8.0.12-cli-bullseye

# ...

RUN pecl install swoole
RUN docker-php-ext-enable swoole
</code>```

It's also my complete Dockerfile:

```<code>FROM php:8.0.12-cli-bullseye

# Install system dependencies
RUN apt-get update && apt-get install -y \
    curl \
    libicu-dev \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    git \
    cron \
    zip \
    unzip

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN pecl install redis swoole
RUN docker-php-ext-install pdo_mysql exif pcntl bcmath gd intl soap
RUN docker-php-ext-enable redis swoole
RUN docker-php-ext-configure intl

RUN sed -i -e "s/upload_max_filesize = .*/upload_max_filesize = 1G/g" \
        -e "s/post_max_size = .*/post_max_size = 1G/g" \
        -e "s/memory_limit = .*/memory_limit = 512M/g" \
        /usr/local/etc/php/php.ini-production \
        && cp /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini

# Set working directory
WORKDIR /app

# Get latest Composer and install
COPY --from=composer:2.1.9 /usr/bin/composer /usr/bin/composer
</code>```

Body:
I'll build a Laravel 8 app. The PHP language level is PHP8. How can I integrate Swoole in my Dockerfile?

Actually I try it this way:

RUN pecl channel-update https://pecl.php.net/channel.xml \
    && pecl install swoole

But if I build the Dockerfile, it always runs into this error:

------
 > [11/19] RUN pecl channel-update https://pecl.php.net/channel.xml  && pecl install swoole:
#14 0.283 /bin/sh: 1: pecl: not found
------
failed to solve: rpc error: code = Unknown desc = executor failed running [/bin/sh -c pecl channel-update https://pecl.php.net/channel.xml  && pecl install swoole]: exit code: 127

Does anyone has an idea?
If you need more information about it, please let me know.

Regards,
Manny

Body:
It is a sample Dockerfile that uses the official PHP 8.0 (Debian) image and installs the Swoole through the PECL:

FROM php:8.0.12-cli-bullseye

# ...

RUN pecl install swoole
RUN docker-php-ext-enable swoole

It's also my complete Dockerfile:

FROM php:8.0.12-cli-bullseye

# Install system dependencies
RUN apt-get update && apt-get install -y \
    curl \
    libicu-dev \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    git \
    cron \
    zip \
    unzip

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN pecl install redis swoole
RUN docker-php-ext-install pdo_mysql exif pcntl bcmath gd intl soap
RUN docker-php-ext-enable redis swoole
RUN docker-php-ext-configure intl

RUN sed -i -e "s/upload_max_filesize = .*/upload_max_filesize = 1G/g" \
        -e "s/post_max_size = .*/post_max_size = 1G/g" \
        -e "s/memory_limit = .*/memory_limit = 512M/g" \
        /usr/local/etc/php/php.ini-production \
        && cp /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini

# Set working directory
WORKDIR /app

# Get latest Composer and install
COPY --from=composer:2.1.9 /usr/bin/composer /usr/bin/composer


问:
How to debug java source code when I implement a custom Detector for Lint?
I am a Android developer.
I have already design my own lint rules by implementing new XXXDetector and XXXIssueRegistry, here is my source code snip:

My XXXIssueRegistry file:

```<code>public class MyIssueRegistry extends IssueRegistry {
  @Override
  public List<Issue> getIssues() {

    System.out.println("!!!!!!!!!!!!! ljf MyIssueRegistry lint rules works");
    return Arrays.asList(AttrPrefixDetector.ISSUE,
            LoggerUsageDetector.ISSUE);
  }
}
</code>```

My XXXDetector file:

```<code>public class LoggerUsageDetector extends Detector
    implements Detector.ClassScanner {
public static final Issue ISSUE = Issue.create("LogUtilsNotUsed",
        "You must use our `LogUtils`",
        "Logging should be avoided in production for security and performance reasons. Therefore, we created a LogUtils that wraps all our calls to Logger and disable them for release flavor.",
        Category.MESSAGES,
        9,
        Severity.ERROR,
        new Implementation(LoggerUsageDetector.class,
                Scope.CLASS_FILE_SCOPE));

@Override
public List<String> getApplicableCallNames() {
    return Arrays.asList("v", "d", "i", "w", "e", "wtf");
}

@Override
public List<String> getApplicableMethodNames() {
    return Arrays.asList("v", "d", "i", "w", "e", "wtf");
}

@Override
public void checkCall(@NonNull ClassContext context,
                      @NonNull ClassNode classNode,
                      @NonNull MethodNode method,
                      @NonNull MethodInsnNode call) {
    String owner = call.owner;
    if (owner.startsWith("android/util/Log")) {
        context.report(ISSUE,
                method,
                call,
                context.getLocation(call),
                "You must use our `LogUtils`");
    }
}
}
</code>```

Now I can run my custom lint rules by runnig command:

```<code>$gradle lint
</code>```

And I will get output message like I expected in console.

But I want to debug my XXXDetector source file. How can I do that?
If I click "debug" or "run" or "build" , my custom lint rules will NOT run! So I have to run it in console, which don't support debug.
How can I solve this?

答:
Here's how you can debug your lint rules in AndroidStudio:

Click on Edit configurations...

Add a new run configuration "gradle":

Then, select your project and enter lintDebug for the task (it's lintLiveDebug for me because i have multiple different debug build variants and one of them is called liveDebug).

Now start this configuration with a click on the debug button like you are used to. This worked very well for me.

Also i can recommend creating a test suite for your lint code, for faster development cycles and debugging.

Body:
I am a Android developer.
I have already design my own lint rules by implementing new XXXDetector and XXXIssueRegistry, here is my source code snip:

My XXXIssueRegistry file:

public class MyIssueRegistry extends IssueRegistry {
  @Override
  public List<Issue> getIssues() {

    System.out.println("!!!!!!!!!!!!! ljf MyIssueRegistry lint rules works");
    return Arrays.asList(AttrPrefixDetector.ISSUE,
            LoggerUsageDetector.ISSUE);
  }
}

My XXXDetector file:

public class LoggerUsageDetector extends Detector
    implements Detector.ClassScanner {
public static final Issue ISSUE = Issue.create("LogUtilsNotUsed",
        "You must use our `LogUtils`",
        "Logging should be avoided in production for security and performance reasons. Therefore, we created a LogUtils that wraps all our calls to Logger and disable them for release flavor.",
        Category.MESSAGES,
        9,
        Severity.ERROR,
        new Implementation(LoggerUsageDetector.class,
                Scope.CLASS_FILE_SCOPE));

@Override
public List<String> getApplicableCallNames() {
    return Arrays.asList("v", "d", "i", "w", "e", "wtf");
}

@Override
public List<String> getApplicableMethodNames() {
    return Arrays.asList("v", "d", "i", "w", "e", "wtf");
}

@Override
public void checkCall(@NonNull ClassContext context,
                      @NonNull ClassNode classNode,
                      @NonNull MethodNode method,
                      @NonNull MethodInsnNode call) {
    String owner = call.owner;
    if (owner.startsWith("android/util/Log")) {
        context.report(ISSUE,
                method,
                call,
                context.getLocation(call),
                "You must use our `LogUtils`");
    }
}
}

Now I can run my custom lint rules by runnig command:

$gradle lint

And I will get output message like I expected in console.

But I want to debug my XXXDetector source file. How can I do that?
If I click "debug" or "run" or "build" , my custom lint rules will NOT run! So I have to run it in console, which don't support debug.
How can I solve this?


问:
The power operator in Java?
When I run the following Visual Basic code :

```<code>Dim b As Double
b = (2 ^ 16 - 1) * Math.Sqrt(Math.Sqrt((a / (2 ^ 8 - 1))))
</code>```

(Assuming a is a double whose value is 15.0)

The result I get for b is about 32,275.

But when I run the following Java code, which is supposed to do the same as above:

```<code>double b;
b = (2 ^ 16 - 1) * Math.sqrt(Math.sqrt((a / (2 ^ 8 - 1))));
</code>```

Again with a being 15, I get a much different result: about 17.

Both are solving this equation:

Why is this so? For what I'm working on, the Visual Basic yields result I'm looking for.

答: ^ is XOR operator in java. Use Math.pow(2,8) which is 2 ^ 8 in Visual Basic.

Title: The power operator in Java?

Body:
When I run the following Visual Basic code :

Dim b As Double
b = (2 ^ 16 - 1) * Math.Sqrt(Math.Sqrt((a / (2 ^ 8 - 1))))

(Assuming a is a double whose value is 15.0)

The result I get for b is about 32,275.

But when I run the following Java code, which is supposed to do the same as above:

double b;
b = (2 ^ 16 - 1) * Math.sqrt(Math.sqrt((a / (2 ^ 8 - 1))));

Again with a being 15, I get a much different result: about 17.

Both are solving this equation:

Why is this so? For what I'm working on, the Visual Basic yields result I'm looking for.


问:
Does Guice have an annotation similar to Spring's @Mandatory or @Required?
Guice does not require initialization of provides methods in the modules, allowing the service to start running without these consumers initializing, which can result in major issues after an outage.

Is there a way to require this initialization - similar to @Mandatory or @Required in Spring?

If not, how would we make initialization mandatory?

The code itself probably won't add anything, but here's a general version of what we are trying to ensure initicalizes within the module itself:

```<code>@Provides
@Singleton
public TriggeredConsumer triggeredConsumer(variousParameters) {
    TriggeredConsumer triggeredConsumer = new TriggeredConsumer(variousParameters);

    triggeredConsumer.start();
    shutdownHook.thenRun(triggeredConsumer::stop);

    return triggeredConsumer;
}
</code>```

答:
The question refers to lazy vs. eager initialisation.

```<code>@Provides
@Singleton
</code>```

Is executed only, if the provided binding is requested to be injected somewhere else due to lazy initialisation in DEVELOPMENT stage.

Caused by the bug provider methods can't bind eager singletons in Guice, eager initialisation is only  possible within the configure method of a Guice module as documented for Eager Singletons

```<code>bind(TriggeredConsumer.class).asEagerSingleton();

</code>```

or by creating the injector in PRODUCTION stage: Phase 3: Singleton Preloading:

```<code>Injector injector = Guice.createInjector(Stage.PRODUCTION, new MyGuiceModule());
</code>```

Body:
Guice does not require initialization of provides methods in the modules, allowing the service to start running without these consumers initializing, which can result in major issues after an outage.

Is there a way to require this initialization - similar to @Mandatory or @Required in Spring?

If not, how would we make initialization mandatory?

The code itself probably won't add anything, but here's a general version of what we are trying to ensure initicalizes within the module itself:

@Provides
@Singleton
public TriggeredConsumer triggeredConsumer(variousParameters) {
    TriggeredConsumer triggeredConsumer = new TriggeredConsumer(variousParameters);

    triggeredConsumer.start();
    shutdownHook.thenRun(triggeredConsumer::stop);

    return triggeredConsumer;
}

Body:
The question refers to lazy vs. eager initialisation.

@Provides
@Singleton

Is executed only, if the provided binding is requested to be injected somewhere else due to lazy initialisation in DEVELOPMENT stage.

Caused by the bug provider methods can't bind eager singletons in Guice, eager initialisation is only  possible within the configure method of a Guice module as documented for Eager Singletons

bind(TriggeredConsumer.class).asEagerSingleton();

or by creating the injector in PRODUCTION stage: Phase 3: Singleton Preloading:

Injector injector = Guice.createInjector(Stage.PRODUCTION, new MyGuiceModule());


问:
in my C# code i am getting this type of Error
System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'
Inner Exception
Win32Exception: The system cannot find the file specified</p>

答:
Possible solutions :

1- Check your connection string name and syntax.

2- Restart your SQL server.

3- Open services from your windows and restart the process of SQL because sometimes it stopes suddenly.

4- Make sure your database engine is configured to accept remote connections:

Start > All Programs > SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration
Click on Surface Area Configuration for Services and Connections
Select the instance that is having a problem > Database Engine > Remote Connections
Enable local and remote connections
Restart instance


问:
How to initialise static variables of class A in class B?
I tried using a static func in class A.

```<code>class A {
    private:
        static int a, b;
        static void init(void) {
            a = 1, b=0;
        }
};

class B {
   private:
       A::init();
}
</code>```

It is giving non-friend class cannot have a qualified name.

答:
The following works:</p>
```<code>class A {
    private:
       static int a;
    public:
       static void initialize();
       void addStatic();
       void getA();
};

class B {
    public:
        void initializeClassA();
};

int A::a = 10;

void A::addStatic() {
    ++a;
}

void A::getA() {
    return a;
}

void A::initialize() {
    a = 0;
}

void B::initializeClassA() {
    A::initialize();
}

int main() {
    A a;
    B b;

    std::cout << "Before Adding - " << a.getA() << std::endl;

    for(int i = 0; i < 3; ++i)
    {
        a.addStatiic();
    }

    std::cout << "After Adding - " << a.getA() << std::endl;
    b.initializeClassA();
    std::cout << "After Reinitializing - " << a.getA() >> std::endl;

    return 0;
}
</code>```

Body:
I tried using a static func in class A.

class A {
    private:
        static int a, b;
        static void init(void) {
            a = 1, b=0;
        }
};

class B {
   private:
       A::init();
}

It is giving non-friend class cannot have a qualified name.

Body:
The following works:

class A {
    private:
       static int a;
    public:
       static void initialize();
       void addStatic();
       void getA();
};

class B {
    public:
        void initializeClassA();
};

int A::a = 10;

void A::addStatic() {
    ++a;
}

void A::getA() {
    return a;
}

void A::initialize() {
    a = 0;
}

void B::initializeClassA() {
    A::initialize();
}

int main() {
    A a;
    B b;

    std::cout << "Before Adding - " << a.getA() << std::endl;

    for(int i = 0; i < 3; ++i)
    {
        a.addStatiic();
    }

    std::cout << "After Adding - " << a.getA() << std::endl;
    b.initializeClassA();
    std::cout << "After Reinitializing - " << a.getA() >> std::endl;

    return 0;
}


问:
Uploading images to Windows Server and making them available publicly
I am trying to upload images in my windows server VM "hosted on-premise" and make these images available publicly like www.example.com/imageFolder/cat.png.

This VM has IIS enabled (I am not sure if IIS is related here) and it is assigned a URL and available publicly.

Aside from any programming languages or frameworks, I just want to know if storing the image in the server and making it available via a link is possible? If so, how can I achieve it?

To clarify further:

I believe what I want is very simple and tedious.

Consider the following workflow:

Run an API that has end points to receive images on the server.

Store the messages in the server.

Return the link that points to the picture.

I want to know the procedure from the windows server side like

Do I need to set certain properties on the folder where I will store the images?

Do I need to add a site to show the images back to the user?

I am a developer and I am new to the Windows Server & IIS so I may not have all the fundamentals.

答:
I made a sample by using ASP.NET MVC5. You can follow this article to upload image in MVC5 application.
Upload Images on Server Folder Using ASP.NET MVC

Then, I do some changes so that it can display the url of images..

```<code>[HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            Uri requestUri = HttpContext.Request.Url;
            string baseUrl = requestUri.Scheme + Uri.SchemeDelimiter + requestUri.Host + (requestUri.IsDefaultPort ? "" : ":" + requestUri.Port);
            if (ModelState.IsValid)
            {
                try
                {
                    if (file != null)
                    {
                        string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
                        file.SaveAs(path);
                    }
                    string link = baseUrl + "/Images/" + file.FileName;
                    ViewBag.FileStatus = "File uploaded successfully.";
                    //Return the url of image
                    ViewBag.FileLink = link;
                }
                catch (Exception e)
                {
                    ViewBag.FileStatus = "Error while file uploading. Error message is "+e.Message;

                }
            }
            return View("Index");
        }
</code>```

Index.cshtml add this to show url.

```<code><div class="col-md-offset-2 col-md-10 text-success">
        @ViewBag.FileLink
</div>
</code>```

Don't forget to add a folder named Images to store images. After publishing, you also need to add it in published folder, otherwise error message will show that cannot find folder.

It works well.

Body:
I made a sample by using ASP.NET MVC5. You can follow this article to upload image in MVC5 application.
Upload Images on Server Folder Using ASP.NET MVC

Then, I do some changes so that it can display the url of images..

[HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            Uri requestUri = HttpContext.Request.Url;
            string baseUrl = requestUri.Scheme + Uri.SchemeDelimiter + requestUri.Host + (requestUri.IsDefaultPort ? "" : ":" + requestUri.Port);
            if (ModelState.IsValid)
            {
                try
                {
                    if (file != null)
                    {
                        string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
                        file.SaveAs(path);
                    }
                    string link = baseUrl + "/Images/" + file.FileName;
                    ViewBag.FileStatus = "File uploaded successfully.";
                    //Return the url of image
                    ViewBag.FileLink = link;
                }
                catch (Exception e)
                {
                    ViewBag.FileStatus = "Error while file uploading. Error message is "+e.Message;

                }
            }
            return View("Index");
        }

Index.cshtml add this to show url.

<div class="col-md-offset-2 col-md-10 text-success">
        @ViewBag.FileLink
</div>

Don't forget to add a folder named Images to store images. After publishing, you also need to add it in published folder, otherwise error message will show that cannot find folder.

It works well.


问:
Hybrid sorting using insertion sort and merge sort
I wish to implement a hybrid algorithm that switches from insertion sort to merge sort once the input array size becomes too big.

This is my main function (I fixed my input array size at 30 currently as I wish to test my merge sort function) :

```<code>    public static void main(String[] args) {
        int[] a = genrandarray(30);

        long bgn, end;
        bgn = System.currentTimeMillis();

        imsort(a, 0, a.length, 30);

        end = System.currentTimeMillis();

        for(int i = 1; i < a.length; i++){
            if(a[i-1] > a[i]){
                System.out.println("failed");
                break;
            }
        }
        System.out.println("milliseconds " + (end-bgn));
    }
</code>```

Insertion sort is called when the array size is <20, else merge sort is called:

```<code>    public static void imsort(int [] slot, int b, int e, int size) {

        //if smaller than 20, use insertion sort
        if (e-b<=20) {
            insertionSort(slot, e);  //e is the length of slot[]
            System.out.println("imsort entered!");
        }

        else {
            mergesort(b, e, slot);

            System.out.println("mergesort entered!");
        }
    }
</code>```

There is a Index 30 out of bounds error for my merge sort function currently.

```<code>    public static int merge(int n, int m, int[] slot) {
        int mid = (n+m)/2;
        int a = n, b = mid+1, i, tmp, cmp=0, comp=0;

        //sanity check
        if (m-n <= 0) return -1000;

        while (a <= mid && b <= m) {
            cmp = compare(slot[a], slot[b]);
            comp++;

            if (cmp > 0) { //slot[a] > slot[b]
                tmp = slot[b++];
                for (i = ++mid; i > a; i--)
                    slot[i] = slot[i-1];
                    slot[a++] = tmp;
            }

            else if (cmp < 0) //slot[a] < slot[b]
                    a++;

            else {
                //slot[a] == slot[b]
                if (a == mid && b == m) break;
                tmp = slot[b++];
                a++;
                for (i = ++mid; i > a; i--)
                slot[i] = slot[i-1]; slot[a++] = tmp;
            }
        } // end of while loop;

        return comp;
    } // end of merge
</code>```
```<code>    public static int mergesort(int s, int e, int[] slot) {
        //int comp =0;
        int mid = (s+e)/2;
        int right=0, left=0;

        if(e-s>0) {
            //comp++;
            left = mergesort(s,mid, slot);
            //comp++;
            right = mergesort(mid+1,e, slot);
        }
        return right + left + merge(s,e,slot);
    }
</code>```

I am unsure of the error in my merge / mergesort function. Can I get some further advice?

答:
a.length returns you 30 which is the length of your random array from the genrandarray method i believe. And your array is indexed 0 through 29. Try changing the main method like this and it will work out</p>
```<code>public static void main(String[] args) {
        int[] a = genrandarray(30);

        long bgn, end;
        bgn = System.currentTimeMillis();

        imsort(a, 0, a.length-1, 30);

        end = System.currentTimeMillis();

        for(int i = 1; i < a.length; i++){
            if(a[i-1] > a[i]){
                System.out.println("failed");
                break;
            }
        }
        System.out.println("milliseconds " + (end-bgn));
    }
</code>```

Body:
I wish to implement a hybrid algorithm that switches from insertion sort to merge sort once the input array size becomes too big.

This is my main function (I fixed my input array size at 30 currently as I wish to test my merge sort function) :

    public static void main(String[] args) {
        int[] a = genrandarray(30);

        long bgn, end;
        bgn = System.currentTimeMillis();

        imsort(a, 0, a.length, 30);

        end = System.currentTimeMillis();

        for(int i = 1; i  a[i]){
                System.out.println("failed");
                break;
            }
        }
        System.out.println("milliseconds " + (end-bgn));
    }

Insertion sort is called when the array size is <20, else merge sort is called:

    public static void imsort(int [] slot, int b, int e, int size) {

        //if smaller than 20, use insertion sort
        if (e-b<=20) {
            insertionSort(slot, e);  //e is the length of slot[]
            System.out.println("imsort entered!");
        }

        else {
            mergesort(b, e, slot);

            System.out.println("mergesort entered!");
        }
    }

There is a Index 30 out of bounds error for my merge sort function currently.

    public static int merge(int n, int m, int[] slot) {
        int mid = (n+m)/2;
        int a = n, b = mid+1, i, tmp, cmp=0, comp=0;

        //sanity check
        if (m-n <= 0) return -1000;

        while (a <= mid && b <= m) {
            cmp = compare(slot[a], slot[b]);
            comp++;

            if (cmp > 0) { //slot[a] > slot[b]
                tmp = slot[b++];
                for (i = ++mid; i > a; i--)
                    slot[i] = slot[i-1];
                    slot[a++] = tmp;
            }

            else if (cmp < 0) //slot[a] < slot[b]
                    a++;

            else {
                //slot[a] == slot[b]
                if (a == mid && b == m) break;
                tmp = slot[b++];
                a++;
                for (i = ++mid; i > a; i--)
                slot[i] = slot[i-1]; slot[a++] = tmp;
            }
        } // end of while loop;

        return comp;
    } // end of merge

    public static int mergesort(int s, int e, int[] slot) {
        //int comp =0;
        int mid = (s+e)/2;
        int right=0, left=0;

        if(e-s>0) {
            //comp++;
            left = mergesort(s,mid, slot);
            //comp++;
            right = mergesort(mid+1,e, slot);
        }
        return right + left + merge(s,e,slot);
    }

I am unsure of the error in my merge / mergesort function. Can I get some further advice?

Body:
a.length returns you 30 which is the length of your random array from the genrandarray method i believe. And your array is indexed 0 through 29. Try changing the main method like this and it will work out

public static void main(String[] args) {
        int[] a = genrandarray(30);

        long bgn, end;
        bgn = System.currentTimeMillis();

        imsort(a, 0, a.length-1, 30);

        end = System.currentTimeMillis();

        for(int i = 1; i < a.length; i++){
            if(a[i-1] > a[i]){
                System.out.println("failed");
                break;
            }
        }
        System.out.println("milliseconds " + (end-bgn));
    }


问:
Read a Bytes image from Amazon Kinesis output in python
I used imageio.get_reader(BytesIO(a),  'ffmpeg') to load a bytes image and save it as normal image.

But the below error throws when I read the image using imageio.get_reader(BytesIO(a),  'ffmpeg')

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 186, in get_reader
    return format.get_reader(request)
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/core/format.py", line 164, in get_reader
    return self.Reader(self, request)
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/core/format.py", line 214, in __init__
    self._open(**self.request.kwargs.copy())
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/plugins/ffmpeg.py", line 323, in _open
    self._initialize()
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/plugins/ffmpeg.py", line 466, in _initialize
    self._meta.update(self._read_gen.__next__())
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio_ffmpeg/_io.py", line 150, in read_frames
    raise IOError(fmt.format(err2))
OSError: Could not load meta information
=== stderr ===

ffmpeg version 4.2 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 7.3.0 (crosstool-NG 1.23.0.449-a04d0)
  configuration: --prefix=/home/tango/anaconda3 --cc=/home/conda/feedstock_root/build_artifacts/ffmpeg_1566210161358/_build_env/bin/x86_64-conda_cos6-linux-gnu-cc --disable-doc --disable-openssl --enable-avresample --enable-gnutls --enable-gpl --enable-hardcoded-tables --enable-libfreetype --enable-libopenh264 --enable-libx264 --enable-pic --enable-pthreads --enable-shared --enable-static --enable-version3 --enable-zlib --enable-libmp3lame
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
[matroska,webm @ 0x5619b9da3cc0] File ended prematurely
[matroska,webm @ 0x5619b9da3cc0] Could not find codec parameters for stream 0 (Video: h264, none, 1280x720): unspecified pixel format
Consider increasing the value for the 'analyzeduration' and 'probesize' options
Input #0, matroska,webm, from '/tmp/imageio_zm6hhpgr':
  Metadata:
    title           : Kinesis Video SDK
    encoder         : Kinesis Video SDK 1.0.0
    AWS_KINESISVIDEO_FRAGMENT_NUMBER: 91343852333183888465720004820715065721442989478
    AWS_KINESISVIDEO_SERVER_TIMESTAMP: 1580791384.096
    AWS_KINESISVIDEO_PRODUCER_TIMESTAMP: 1580791377.843
  Duration: N/A, bitrate: N/A
    Stream #0:0(eng): Video: h264, none, 1280x720, SAR 1:1 DAR 16:9, 1k tbr, 1k tbn, 2k tbc (default)
    Metadata:
      title           : kinesis_video
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> rawvideo (native))
Press [q] to stop, [?] for help
Cannot determine format of input stream 0:0 after EOF
Error marking filters as finished
Conversion failed!
</code>```

The above approach to read a MKV bytes file was done based on this thread

Or is there is any approach to parse and read the MKV bytes file.

答:
Old question, but I'll leave an answer here for future readers :)

In general, if you have a bytes string that encodes a video (or image), chances are high that you can pass it directly into ImageIO's high-level API and that it can read the bytes directly. In the case of MKV (and some other video formats) ImageIO needs a bit of help because the current ffmpeg plugin struggles with byte strings. [There is a new plugin on the way to fix this and other issues.]

ImageIO<2.15.0

import imageio as iio

req = iio.core.Request(mkv_bytes, "r")

# note: this is where imageIO needs some help, see
# https://github.com/imageio/imageio/issues/686
req._extension = ".mkv"

first_frame = iio.imread(req)

```
<p><em>ImageIO>2.15.0</em> (releases this week - W6 2022)</p>
<pre class="lang-py prettyprint-override"><code>import imageio as iio

first_frame = iio.v3.imread(mkv_bytes, format_hint=".mkv")
</code>```

Body:
I used imageio.get_reader(BytesIO(a),  'ffmpeg') to load a bytes image and save it as normal image.

But the below error throws when I read the image using imageio.get_reader(BytesIO(a),  'ffmpeg')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 186, in get_reader
    return format.get_reader(request)
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/core/format.py", line 164, in get_reader
    return self.Reader(self, request)
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/core/format.py", line 214, in __init__
    self._open(**self.request.kwargs.copy())
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/plugins/ffmpeg.py", line 323, in _open
    self._initialize()
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio/plugins/ffmpeg.py", line 466, in _initialize
    self._meta.update(self._read_gen.__next__())
  File "/home/tango/anaconda3/lib/python3.6/site-packages/imageio_ffmpeg/_io.py", line 150, in read_frames
    raise IOError(fmt.format(err2))
OSError: Could not load meta information
=== stderr ===

ffmpeg version 4.2 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 7.3.0 (crosstool-NG 1.23.0.449-a04d0)
  configuration: --prefix=/home/tango/anaconda3 --cc=/home/conda/feedstock_root/build_artifacts/ffmpeg_1566210161358/_build_env/bin/x86_64-conda_cos6-linux-gnu-cc --disable-doc --disable-openssl --enable-avresample --enable-gnutls --enable-gpl --enable-hardcoded-tables --enable-libfreetype --enable-libopenh264 --enable-libx264 --enable-pic --enable-pthreads --enable-shared --enable-static --enable-version3 --enable-zlib --enable-libmp3lame
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
[matroska,webm @ 0x5619b9da3cc0] File ended prematurely
[matroska,webm @ 0x5619b9da3cc0] Could not find codec parameters for stream 0 (Video: h264, none, 1280x720): unspecified pixel format
Consider increasing the value for the 'analyzeduration' and 'probesize' options
Input #0, matroska,webm, from '/tmp/imageio_zm6hhpgr':
  Metadata:
    title           : Kinesis Video SDK
    encoder         : Kinesis Video SDK 1.0.0
    AWS_KINESISVIDEO_FRAGMENT_NUMBER: 91343852333183888465720004820715065721442989478
    AWS_KINESISVIDEO_SERVER_TIMESTAMP: 1580791384.096
    AWS_KINESISVIDEO_PRODUCER_TIMESTAMP: 1580791377.843
  Duration: N/A, bitrate: N/A
    Stream #0:0(eng): Video: h264, none, 1280x720, SAR 1:1 DAR 16:9, 1k tbr, 1k tbn, 2k tbc (default)
    Metadata:
      title           : kinesis_video
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> rawvideo (native))
Press [q] to stop, [?] for help
Cannot determine format of input stream 0:0 after EOF
Error marking filters as finished
Conversion failed!

The above approach to read a MKV bytes file was done based on this thread

Or is there is any approach to parse and read the MKV bytes file.

Body:
Old question, but I'll leave an answer here for future readers :)

In general, if you have a bytes string that encodes a video (or image), chances are high that you can pass it directly into ImageIO's high-level API and that it can read the bytes directly. In the case of MKV (and some other video formats) ImageIO needs a bit of help because the current ffmpeg plugin struggles with byte strings. [There is a new plugin on the way to fix this and other issues.]

ImageIO<2.15.0

import imageio as iio

req = iio.core.Request(mkv_bytes, "r")

# note: this is where imageIO needs some help, see
# https://github.com/imageio/imageio/issues/686
req._extension = ".mkv"

first_frame = iio.imread(req)

ImageIO>2.15.0 (releases this week - W6 2022)

import imageio as iio

first_frame = iio.v3.imread(mkv_bytes, format_hint=".mkv")